Skip to main content

backbone_pos/domain/entity/
pos_cash_movement.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use sqlx::FromRow;
4use uuid::Uuid;
5use rust_decimal::Decimal;
6
7use super::PosCashMovementType;
8use super::AuditMetadata;
9
10/// Strongly-typed ID for PosCashMovement
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct PosCashMovementId(pub Uuid);
14
15impl PosCashMovementId {
16    pub fn new(id: Uuid) -> Self { Self(id) }
17    pub fn generate() -> Self { Self(Uuid::new_v4()) }
18    pub fn into_inner(self) -> Uuid { self.0 }
19}
20
21impl std::fmt::Display for PosCashMovementId {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        write!(f, "{}", self.0)
24    }
25}
26
27impl std::str::FromStr for PosCashMovementId {
28    type Err = uuid::Error;
29    fn from_str(s: &str) -> Result<Self, Self::Err> {
30        Ok(Self(Uuid::parse_str(s)?))
31    }
32}
33
34impl From<Uuid> for PosCashMovementId {
35    fn from(id: Uuid) -> Self { Self(id) }
36}
37
38impl From<PosCashMovementId> for Uuid {
39    fn from(id: PosCashMovementId) -> Self { id.0 }
40}
41
42impl AsRef<Uuid> for PosCashMovementId {
43    fn as_ref(&self) -> &Uuid { &self.0 }
44}
45
46impl std::ops::Deref for PosCashMovementId {
47    type Target = Uuid;
48    fn deref(&self) -> &Self::Target { &self.0 }
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
52pub struct PosCashMovement {
53    pub id: Uuid,
54    pub pos_profile_id: Uuid,
55    pub opening_entry_id: Uuid,
56    pub cashier_party_id: Uuid,
57    pub movement_type: PosCashMovementType,
58    pub amount: Decimal,
59    pub reason: Option<String>,
60    pub moved_at: DateTime<Utc>,
61    #[serde(default)]
62    #[sqlx(json)]
63    pub metadata: AuditMetadata,
64}
65
66impl PosCashMovement {
67    /// Create a builder for PosCashMovement
68    pub fn builder() -> PosCashMovementBuilder {
69        <PosCashMovementBuilder as Default>::default()
70    }
71
72    /// Create a new PosCashMovement with required fields
73    pub fn new(pos_profile_id: Uuid, opening_entry_id: Uuid, cashier_party_id: Uuid, movement_type: PosCashMovementType, amount: Decimal, moved_at: DateTime<Utc>) -> Self {
74        Self {
75            id: Uuid::new_v4(),
76            pos_profile_id,
77            opening_entry_id,
78            cashier_party_id,
79            movement_type,
80            amount,
81            reason: None,
82            moved_at,
83            metadata: AuditMetadata::default(),
84        }
85    }
86
87    /// Get the entity's unique identifier
88    pub fn id(&self) -> &Uuid {
89        &self.id
90    }
91
92    /// Get a strongly-typed ID for this entity
93    pub fn typed_id(&self) -> PosCashMovementId {
94        PosCashMovementId(self.id)
95    }
96
97    /// Get when this entity was created
98    pub fn created_at(&self) -> Option<&DateTime<Utc>> {
99        self.metadata.created_at.as_ref()
100    }
101
102    /// Get when this entity was last updated
103    pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
104        self.metadata.updated_at.as_ref()
105    }
106
107    /// Check if this entity is soft deleted
108    pub fn is_deleted(&self) -> bool {
109        self.metadata.deleted_at.is_some()
110    }
111
112    /// Check if this entity is active (not deleted)
113    pub fn is_active(&self) -> bool {
114        self.metadata.deleted_at.is_none()
115    }
116
117    /// Get when this entity was deleted
118    pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
119        self.metadata.deleted_at.as_ref()
120    }
121
122    /// Get who created this entity
123    pub fn created_by(&self) -> Option<&Uuid> {
124        self.metadata.created_by.as_ref()
125    }
126
127    /// Get who last updated this entity
128    pub fn updated_by(&self) -> Option<&Uuid> {
129        self.metadata.updated_by.as_ref()
130    }
131
132    /// Get who deleted this entity
133    pub fn deleted_by(&self) -> Option<&Uuid> {
134        self.metadata.deleted_by.as_ref()
135    }
136
137
138    // ==========================================================
139    // Fluent Setters (with_* for optional fields)
140    // ==========================================================
141
142    /// Set the reason field (chainable)
143    pub fn with_reason(mut self, value: String) -> Self {
144        self.reason = Some(value);
145        self
146    }
147
148    // ==========================================================
149    // Partial Update
150    // ==========================================================
151
152    /// Apply partial updates from a map of field name to JSON value
153    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
154        for (key, value) in fields {
155            match key.as_str() {
156                "pos_profile_id" => {
157                    if let Ok(v) = serde_json::from_value(value) { self.pos_profile_id = v; }
158                }
159                "opening_entry_id" => {
160                    if let Ok(v) = serde_json::from_value(value) { self.opening_entry_id = v; }
161                }
162                "cashier_party_id" => {
163                    if let Ok(v) = serde_json::from_value(value) { self.cashier_party_id = v; }
164                }
165                "movement_type" => {
166                    if let Ok(v) = serde_json::from_value(value) { self.movement_type = v; }
167                }
168                "amount" => {
169                    if let Ok(v) = serde_json::from_value(value) { self.amount = v; }
170                }
171                "reason" => {
172                    if let Ok(v) = serde_json::from_value(value) { self.reason = v; }
173                }
174                "moved_at" => {
175                    if let Ok(v) = serde_json::from_value(value) { self.moved_at = v; }
176                }
177                _ => {} // ignore unknown fields
178            }
179        }
180    }
181
182}
183
184impl super::Entity for PosCashMovement {
185    type Id = Uuid;
186
187    fn entity_id(&self) -> &Self::Id {
188        &self.id
189    }
190
191    fn entity_type() -> &'static str {
192        "PosCashMovement"
193    }
194}
195
196impl backbone_core::PersistentEntity for PosCashMovement {
197    fn entity_id(&self) -> String {
198        self.id.to_string()
199    }
200    fn set_entity_id(&mut self, id: String) {
201        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
202            self.id = uuid;
203        }
204    }
205    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
206        self.metadata.created_at
207    }
208    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
209        self.metadata.created_at = Some(ts);
210    }
211    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
212        self.metadata.updated_at
213    }
214    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
215        self.metadata.updated_at = Some(ts);
216    }
217    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
218        self.metadata.deleted_at
219    }
220    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
221        self.metadata.deleted_at = ts;
222    }
223}
224
225impl backbone_orm::EntityRepoMeta for PosCashMovement {
226    fn column_types() -> std::collections::HashMap<String, String> {
227        let mut m = std::collections::HashMap::new();
228        m.insert("id".to_string(), "uuid".to_string());
229        m.insert("pos_profile_id".to_string(), "uuid".to_string());
230        m.insert("opening_entry_id".to_string(), "uuid".to_string());
231        m.insert("cashier_party_id".to_string(), "uuid".to_string());
232        m.insert("movement_type".to_string(), "pos_cash_movement_type".to_string());
233        m.insert("moved_at".to_string(), "timestamptz".to_string());
234        m
235    }
236    fn search_fields() -> &'static [&'static str] {
237        &[]
238    }
239}
240
241/// Builder for PosCashMovement entity
242///
243/// Provides a fluent API for constructing PosCashMovement instances.
244/// System fields (id, metadata, timestamps) are auto-initialized.
245#[derive(Debug, Clone, Default)]
246pub struct PosCashMovementBuilder {
247    pos_profile_id: Option<Uuid>,
248    opening_entry_id: Option<Uuid>,
249    cashier_party_id: Option<Uuid>,
250    movement_type: Option<PosCashMovementType>,
251    amount: Option<Decimal>,
252    reason: Option<String>,
253    moved_at: Option<DateTime<Utc>>,
254}
255
256impl PosCashMovementBuilder {
257    /// Set the pos_profile_id field (required)
258    pub fn pos_profile_id(mut self, value: Uuid) -> Self {
259        self.pos_profile_id = Some(value);
260        self
261    }
262
263    /// Set the opening_entry_id field (required)
264    pub fn opening_entry_id(mut self, value: Uuid) -> Self {
265        self.opening_entry_id = Some(value);
266        self
267    }
268
269    /// Set the cashier_party_id field (required)
270    pub fn cashier_party_id(mut self, value: Uuid) -> Self {
271        self.cashier_party_id = Some(value);
272        self
273    }
274
275    /// Set the movement_type field (required)
276    pub fn movement_type(mut self, value: PosCashMovementType) -> Self {
277        self.movement_type = Some(value);
278        self
279    }
280
281    /// Set the amount field (default: `Decimal::from(0)`)
282    pub fn amount(mut self, value: Decimal) -> Self {
283        self.amount = Some(value);
284        self
285    }
286
287    /// Set the reason field (optional)
288    pub fn reason(mut self, value: String) -> Self {
289        self.reason = Some(value);
290        self
291    }
292
293    /// Set the moved_at field (required)
294    pub fn moved_at(mut self, value: DateTime<Utc>) -> Self {
295        self.moved_at = Some(value);
296        self
297    }
298
299    /// Build the PosCashMovement entity
300    ///
301    /// Returns Err if any required field without a default is missing.
302    pub fn build(self) -> Result<PosCashMovement, String> {
303        let pos_profile_id = self.pos_profile_id.ok_or_else(|| "pos_profile_id is required".to_string())?;
304        let opening_entry_id = self.opening_entry_id.ok_or_else(|| "opening_entry_id is required".to_string())?;
305        let cashier_party_id = self.cashier_party_id.ok_or_else(|| "cashier_party_id is required".to_string())?;
306        let movement_type = self.movement_type.ok_or_else(|| "movement_type is required".to_string())?;
307        let moved_at = self.moved_at.ok_or_else(|| "moved_at is required".to_string())?;
308
309        Ok(PosCashMovement {
310            id: Uuid::new_v4(),
311            pos_profile_id,
312            opening_entry_id,
313            cashier_party_id,
314            movement_type,
315            amount: self.amount.unwrap_or(Decimal::from(0)),
316            reason: self.reason,
317            moved_at,
318            metadata: AuditMetadata::default(),
319        })
320    }
321}