Skip to main content

backbone_pos/domain/entity/
pos_invoice_item.rs

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