actor_sample/order_actor/
entity.rs

1//! Entity trait implementation for the Order resource type.
2//!
3//! This module contains the [`ActorEntity`] trait implementation
4//! that enables [`Order`] to be managed by the generic [`actor_framework::ResourceActor`].
5//!
6//! See the trait implementation on [`Order`] for method documentation.
7
8use crate::clients::{ProductClient, UserClient};
9use crate::model::{Order, OrderCreate, OrderId};
10use crate::order_actor::OrderError;
11use actor_framework::{ActorClient, ActorEntity};
12use async_trait::async_trait;
13
14/// Marker constant to ensure module documentation is rendered.
15#[doc(hidden)]
16/// Marker constant to verify ActorEntity trait implementation exists at compile time.
17#[allow(dead_code)]
18pub const ENTITY_IMPL_PRESENT: bool = true;
19
20#[async_trait]
21impl ActorEntity for Order {
22    type Id = OrderId;
23    type Create = OrderCreate;
24    type Update = (); // No updates for now
25    type Action = (); // No custom actions for now
26    type ActionResult = ();
27    type Context = (UserClient, ProductClient);
28    type Error = OrderError;
29
30    // fn id(&self) -> &String { &self.id }
31
32    /// Creates a new Order from creation parameters.
33    fn from_create_params(id: Self::Id, params: Self::Create) -> Result<Self, Self::Error> {
34        Ok(Self::new(
35            id,
36            params.user_id,
37            params.product_id,
38            params.quantity,
39            params.total,
40        ))
41    }
42
43    /// Validates the order by checking User existence and reserving Product stock.
44    async fn on_create(
45        &mut self,
46        (user_client, product_client): &Self::Context,
47    ) -> Result<(), Self::Error> {
48        // 1. Validate User
49        let user = user_client.get(self.user_id.clone()).await?;
50
51        if user.is_none() {
52            return Err(OrderError::InvalidUser(self.user_id.to_string()));
53        }
54
55        // 2. Reserve Stock - errors automatically convert via #[from]
56        product_client
57            .reserve_stock(self.product_id.clone(), self.quantity)
58            .await?;
59
60        Ok(())
61    }
62
63    async fn handle_action(
64        &mut self,
65        _action: Self::Action,
66        _ctx: &Self::Context,
67    ) -> Result<Self::ActionResult, Self::Error> {
68        Ok(())
69    }
70
71    async fn on_update(
72        &mut self,
73        _update: Self::Update,
74        _ctx: &Self::Context,
75    ) -> Result<(), Self::Error> {
76        Ok(())
77    }
78
79    async fn on_delete(&self, _ctx: &Self::Context) -> Result<(), Self::Error> {
80        Ok(())
81    }
82}