Skip to main content

backbone_pos/domain/entity/
pos_payment.rs

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