Skip to main content

backbone_pos/domain/entity/
pos_profile.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use sqlx::FromRow;
4use uuid::Uuid;
5use rust_decimal::Decimal;
6
7use super::PosCashRoundingStrategy;
8use super::PosProfileStatus;
9use super::AuditMetadata;
10
11/// Strongly-typed ID for PosProfile
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(transparent)]
14pub struct PosProfileId(pub Uuid);
15
16impl PosProfileId {
17    pub fn new(id: Uuid) -> Self { Self(id) }
18    pub fn generate() -> Self { Self(Uuid::new_v4()) }
19    pub fn into_inner(self) -> Uuid { self.0 }
20}
21
22impl std::fmt::Display for PosProfileId {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "{}", self.0)
25    }
26}
27
28impl std::str::FromStr for PosProfileId {
29    type Err = uuid::Error;
30    fn from_str(s: &str) -> Result<Self, Self::Err> {
31        Ok(Self(Uuid::parse_str(s)?))
32    }
33}
34
35impl From<Uuid> for PosProfileId {
36    fn from(id: Uuid) -> Self { Self(id) }
37}
38
39impl From<PosProfileId> for Uuid {
40    fn from(id: PosProfileId) -> Self { id.0 }
41}
42
43impl AsRef<Uuid> for PosProfileId {
44    fn as_ref(&self) -> &Uuid { &self.0 }
45}
46
47impl std::ops::Deref for PosProfileId {
48    type Target = Uuid;
49    fn deref(&self) -> &Self::Target { &self.0 }
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
53pub struct PosProfile {
54    pub id: Uuid,
55    pub branch_id: Option<Uuid>,
56    pub name: String,
57    pub default_customer_id: Option<Uuid>,
58    pub currency: String,
59    pub income_account_id: Option<Uuid>,
60    pub receivable_account_id: Option<Uuid>,
61    pub cash_account_id: Option<Uuid>,
62    pub write_off_account_id: Option<Uuid>,
63    pub tax_account_id: Option<Uuid>,
64    pub tax_rate: Decimal,
65    pub tax_template_ids: Option<serde_json::Value>,
66    pub warehouse_id: Option<Uuid>,
67    pub cogs_account_id: Option<Uuid>,
68    pub inventory_account_id: Option<Uuid>,
69    pub allow_discount: bool,
70    pub cash_rounding_strategy: PosCashRoundingStrategy,
71    pub cash_rounding_unit: Decimal,
72    pub status: PosProfileStatus,
73    #[serde(default)]
74    #[sqlx(json)]
75    pub metadata: AuditMetadata,
76}
77
78impl PosProfile {
79    /// Create a builder for PosProfile
80    pub fn builder() -> PosProfileBuilder {
81        <PosProfileBuilder as Default>::default()
82    }
83
84    /// Create a new PosProfile with required fields
85    pub fn new(name: String, currency: String, tax_rate: Decimal, allow_discount: bool, cash_rounding_strategy: PosCashRoundingStrategy, cash_rounding_unit: Decimal, status: PosProfileStatus) -> Self {
86        Self {
87            id: Uuid::new_v4(),
88            branch_id: None,
89            name,
90            default_customer_id: None,
91            currency,
92            income_account_id: None,
93            receivable_account_id: None,
94            cash_account_id: None,
95            write_off_account_id: None,
96            tax_account_id: None,
97            tax_rate,
98            tax_template_ids: None,
99            warehouse_id: None,
100            cogs_account_id: None,
101            inventory_account_id: None,
102            allow_discount,
103            cash_rounding_strategy,
104            cash_rounding_unit,
105            status,
106            metadata: AuditMetadata::default(),
107        }
108    }
109
110    /// Get the entity's unique identifier
111    pub fn id(&self) -> &Uuid {
112        &self.id
113    }
114
115    /// Get a strongly-typed ID for this entity
116    pub fn typed_id(&self) -> PosProfileId {
117        PosProfileId(self.id)
118    }
119
120    /// Get when this entity was created
121    pub fn created_at(&self) -> Option<&DateTime<Utc>> {
122        self.metadata.created_at.as_ref()
123    }
124
125    /// Get when this entity was last updated
126    pub fn updated_at(&self) -> Option<&DateTime<Utc>> {
127        self.metadata.updated_at.as_ref()
128    }
129
130    /// Check if this entity is soft deleted
131    pub fn is_deleted(&self) -> bool {
132        self.metadata.deleted_at.is_some()
133    }
134
135    /// Check if this entity is active (not deleted)
136    pub fn is_active(&self) -> bool {
137        self.metadata.deleted_at.is_none()
138    }
139
140    /// Get when this entity was deleted
141    pub fn deleted_at(&self) -> Option<&DateTime<Utc>> {
142        self.metadata.deleted_at.as_ref()
143    }
144
145    /// Get who created this entity
146    pub fn created_by(&self) -> Option<&Uuid> {
147        self.metadata.created_by.as_ref()
148    }
149
150    /// Get who last updated this entity
151    pub fn updated_by(&self) -> Option<&Uuid> {
152        self.metadata.updated_by.as_ref()
153    }
154
155    /// Get who deleted this entity
156    pub fn deleted_by(&self) -> Option<&Uuid> {
157        self.metadata.deleted_by.as_ref()
158    }
159
160    /// Get the current status
161    pub fn status(&self) -> &PosProfileStatus {
162        &self.status
163    }
164
165
166    // ==========================================================
167    // Fluent Setters (with_* for optional fields)
168    // ==========================================================
169
170    /// Set the branch_id field (chainable)
171    pub fn with_branch_id(mut self, value: Uuid) -> Self {
172        self.branch_id = Some(value);
173        self
174    }
175
176    /// Set the default_customer_id field (chainable)
177    pub fn with_default_customer_id(mut self, value: Uuid) -> Self {
178        self.default_customer_id = Some(value);
179        self
180    }
181
182    /// Set the income_account_id field (chainable)
183    pub fn with_income_account_id(mut self, value: Uuid) -> Self {
184        self.income_account_id = Some(value);
185        self
186    }
187
188    /// Set the receivable_account_id field (chainable)
189    pub fn with_receivable_account_id(mut self, value: Uuid) -> Self {
190        self.receivable_account_id = Some(value);
191        self
192    }
193
194    /// Set the cash_account_id field (chainable)
195    pub fn with_cash_account_id(mut self, value: Uuid) -> Self {
196        self.cash_account_id = Some(value);
197        self
198    }
199
200    /// Set the write_off_account_id field (chainable)
201    pub fn with_write_off_account_id(mut self, value: Uuid) -> Self {
202        self.write_off_account_id = Some(value);
203        self
204    }
205
206    /// Set the tax_account_id field (chainable)
207    pub fn with_tax_account_id(mut self, value: Uuid) -> Self {
208        self.tax_account_id = Some(value);
209        self
210    }
211
212    /// Set the tax_template_ids field (chainable)
213    pub fn with_tax_template_ids(mut self, value: serde_json::Value) -> Self {
214        self.tax_template_ids = Some(value);
215        self
216    }
217
218    /// Set the warehouse_id field (chainable)
219    pub fn with_warehouse_id(mut self, value: Uuid) -> Self {
220        self.warehouse_id = Some(value);
221        self
222    }
223
224    /// Set the cogs_account_id field (chainable)
225    pub fn with_cogs_account_id(mut self, value: Uuid) -> Self {
226        self.cogs_account_id = Some(value);
227        self
228    }
229
230    /// Set the inventory_account_id field (chainable)
231    pub fn with_inventory_account_id(mut self, value: Uuid) -> Self {
232        self.inventory_account_id = Some(value);
233        self
234    }
235
236    // ==========================================================
237    // Partial Update
238    // ==========================================================
239
240    /// Apply partial updates from a map of field name to JSON value
241    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
242        for (key, value) in fields {
243            match key.as_str() {
244                "branch_id" => {
245                    if let Ok(v) = serde_json::from_value(value) { self.branch_id = v; }
246                }
247                "name" => {
248                    if let Ok(v) = serde_json::from_value(value) { self.name = v; }
249                }
250                "default_customer_id" => {
251                    if let Ok(v) = serde_json::from_value(value) { self.default_customer_id = v; }
252                }
253                "currency" => {
254                    if let Ok(v) = serde_json::from_value(value) { self.currency = v; }
255                }
256                "income_account_id" => {
257                    if let Ok(v) = serde_json::from_value(value) { self.income_account_id = v; }
258                }
259                "receivable_account_id" => {
260                    if let Ok(v) = serde_json::from_value(value) { self.receivable_account_id = v; }
261                }
262                "cash_account_id" => {
263                    if let Ok(v) = serde_json::from_value(value) { self.cash_account_id = v; }
264                }
265                "write_off_account_id" => {
266                    if let Ok(v) = serde_json::from_value(value) { self.write_off_account_id = v; }
267                }
268                "tax_account_id" => {
269                    if let Ok(v) = serde_json::from_value(value) { self.tax_account_id = v; }
270                }
271                "tax_rate" => {
272                    if let Ok(v) = serde_json::from_value(value) { self.tax_rate = v; }
273                }
274                "tax_template_ids" => {
275                    if let Ok(v) = serde_json::from_value(value) { self.tax_template_ids = v; }
276                }
277                "warehouse_id" => {
278                    if let Ok(v) = serde_json::from_value(value) { self.warehouse_id = v; }
279                }
280                "cogs_account_id" => {
281                    if let Ok(v) = serde_json::from_value(value) { self.cogs_account_id = v; }
282                }
283                "inventory_account_id" => {
284                    if let Ok(v) = serde_json::from_value(value) { self.inventory_account_id = v; }
285                }
286                "allow_discount" => {
287                    if let Ok(v) = serde_json::from_value(value) { self.allow_discount = v; }
288                }
289                "cash_rounding_strategy" => {
290                    if let Ok(v) = serde_json::from_value(value) { self.cash_rounding_strategy = v; }
291                }
292                "cash_rounding_unit" => {
293                    if let Ok(v) = serde_json::from_value(value) { self.cash_rounding_unit = v; }
294                }
295                "status" => {
296                    if let Ok(v) = serde_json::from_value(value) { self.status = v; }
297                }
298                _ => {} // ignore unknown fields
299            }
300        }
301    }
302
303}
304
305impl super::Entity for PosProfile {
306    type Id = Uuid;
307
308    fn entity_id(&self) -> &Self::Id {
309        &self.id
310    }
311
312    fn entity_type() -> &'static str {
313        "PosProfile"
314    }
315}
316
317impl backbone_core::PersistentEntity for PosProfile {
318    fn entity_id(&self) -> String {
319        self.id.to_string()
320    }
321    fn set_entity_id(&mut self, id: String) {
322        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
323            self.id = uuid;
324        }
325    }
326    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
327        self.metadata.created_at
328    }
329    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
330        self.metadata.created_at = Some(ts);
331    }
332    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
333        self.metadata.updated_at
334    }
335    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
336        self.metadata.updated_at = Some(ts);
337    }
338    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
339        self.metadata.deleted_at
340    }
341    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
342        self.metadata.deleted_at = ts;
343    }
344}
345
346impl backbone_orm::EntityRepoMeta for PosProfile {
347    fn column_types() -> std::collections::HashMap<String, String> {
348        let mut m = std::collections::HashMap::new();
349        m.insert("id".to_string(), "uuid".to_string());
350        m.insert("branch_id".to_string(), "uuid".to_string());
351        m.insert("default_customer_id".to_string(), "uuid".to_string());
352        m.insert("income_account_id".to_string(), "uuid".to_string());
353        m.insert("receivable_account_id".to_string(), "uuid".to_string());
354        m.insert("cash_account_id".to_string(), "uuid".to_string());
355        m.insert("write_off_account_id".to_string(), "uuid".to_string());
356        m.insert("tax_account_id".to_string(), "uuid".to_string());
357        m.insert("warehouse_id".to_string(), "uuid".to_string());
358        m.insert("cogs_account_id".to_string(), "uuid".to_string());
359        m.insert("inventory_account_id".to_string(), "uuid".to_string());
360        m.insert("cash_rounding_strategy".to_string(), "pos_cash_rounding_strategy".to_string());
361        m.insert("status".to_string(), "pos_profile_status".to_string());
362        m
363    }
364    fn search_fields() -> &'static [&'static str] {
365        &["name", "currency"]
366    }
367}
368
369/// Builder for PosProfile entity
370///
371/// Provides a fluent API for constructing PosProfile instances.
372/// System fields (id, metadata, timestamps) are auto-initialized.
373#[derive(Debug, Clone, Default)]
374pub struct PosProfileBuilder {
375    branch_id: Option<Uuid>,
376    name: Option<String>,
377    default_customer_id: Option<Uuid>,
378    currency: Option<String>,
379    income_account_id: Option<Uuid>,
380    receivable_account_id: Option<Uuid>,
381    cash_account_id: Option<Uuid>,
382    write_off_account_id: Option<Uuid>,
383    tax_account_id: Option<Uuid>,
384    tax_rate: Option<Decimal>,
385    tax_template_ids: Option<serde_json::Value>,
386    warehouse_id: Option<Uuid>,
387    cogs_account_id: Option<Uuid>,
388    inventory_account_id: Option<Uuid>,
389    allow_discount: Option<bool>,
390    cash_rounding_strategy: Option<PosCashRoundingStrategy>,
391    cash_rounding_unit: Option<Decimal>,
392    status: Option<PosProfileStatus>,
393}
394
395impl PosProfileBuilder {
396    /// Set the branch_id field (optional)
397    pub fn branch_id(mut self, value: Uuid) -> Self {
398        self.branch_id = Some(value);
399        self
400    }
401
402    /// Set the name field (required)
403    pub fn name(mut self, value: String) -> Self {
404        self.name = Some(value);
405        self
406    }
407
408    /// Set the default_customer_id field (optional)
409    pub fn default_customer_id(mut self, value: Uuid) -> Self {
410        self.default_customer_id = Some(value);
411        self
412    }
413
414    /// Set the currency field (default: `"IDR".to_string()`)
415    pub fn currency(mut self, value: String) -> Self {
416        self.currency = Some(value);
417        self
418    }
419
420    /// Set the income_account_id field (optional)
421    pub fn income_account_id(mut self, value: Uuid) -> Self {
422        self.income_account_id = Some(value);
423        self
424    }
425
426    /// Set the receivable_account_id field (optional)
427    pub fn receivable_account_id(mut self, value: Uuid) -> Self {
428        self.receivable_account_id = Some(value);
429        self
430    }
431
432    /// Set the cash_account_id field (optional)
433    pub fn cash_account_id(mut self, value: Uuid) -> Self {
434        self.cash_account_id = Some(value);
435        self
436    }
437
438    /// Set the write_off_account_id field (optional)
439    pub fn write_off_account_id(mut self, value: Uuid) -> Self {
440        self.write_off_account_id = Some(value);
441        self
442    }
443
444    /// Set the tax_account_id field (optional)
445    pub fn tax_account_id(mut self, value: Uuid) -> Self {
446        self.tax_account_id = Some(value);
447        self
448    }
449
450    /// Set the tax_rate field (default: `Decimal::from(0)`)
451    pub fn tax_rate(mut self, value: Decimal) -> Self {
452        self.tax_rate = Some(value);
453        self
454    }
455
456    /// Set the tax_template_ids field (optional)
457    pub fn tax_template_ids(mut self, value: serde_json::Value) -> Self {
458        self.tax_template_ids = Some(value);
459        self
460    }
461
462    /// Set the warehouse_id field (optional)
463    pub fn warehouse_id(mut self, value: Uuid) -> Self {
464        self.warehouse_id = Some(value);
465        self
466    }
467
468    /// Set the cogs_account_id field (optional)
469    pub fn cogs_account_id(mut self, value: Uuid) -> Self {
470        self.cogs_account_id = Some(value);
471        self
472    }
473
474    /// Set the inventory_account_id field (optional)
475    pub fn inventory_account_id(mut self, value: Uuid) -> Self {
476        self.inventory_account_id = Some(value);
477        self
478    }
479
480    /// Set the allow_discount field (default: `true`)
481    pub fn allow_discount(mut self, value: bool) -> Self {
482        self.allow_discount = Some(value);
483        self
484    }
485
486    /// Set the cash_rounding_strategy field (default: `PosCashRoundingStrategy::default()`)
487    pub fn cash_rounding_strategy(mut self, value: PosCashRoundingStrategy) -> Self {
488        self.cash_rounding_strategy = Some(value);
489        self
490    }
491
492    /// Set the cash_rounding_unit field (default: `Decimal::from(0)`)
493    pub fn cash_rounding_unit(mut self, value: Decimal) -> Self {
494        self.cash_rounding_unit = Some(value);
495        self
496    }
497
498    /// Set the status field (default: `PosProfileStatus::default()`)
499    pub fn status(mut self, value: PosProfileStatus) -> Self {
500        self.status = Some(value);
501        self
502    }
503
504    /// Build the PosProfile entity
505    ///
506    /// Returns Err if any required field without a default is missing.
507    pub fn build(self) -> Result<PosProfile, String> {
508        let name = self.name.ok_or_else(|| "name is required".to_string())?;
509
510        Ok(PosProfile {
511            id: Uuid::new_v4(),
512            branch_id: self.branch_id,
513            name,
514            default_customer_id: self.default_customer_id,
515            currency: self.currency.unwrap_or("IDR".to_string()),
516            income_account_id: self.income_account_id,
517            receivable_account_id: self.receivable_account_id,
518            cash_account_id: self.cash_account_id,
519            write_off_account_id: self.write_off_account_id,
520            tax_account_id: self.tax_account_id,
521            tax_rate: self.tax_rate.unwrap_or(Decimal::from(0)),
522            tax_template_ids: self.tax_template_ids,
523            warehouse_id: self.warehouse_id,
524            cogs_account_id: self.cogs_account_id,
525            inventory_account_id: self.inventory_account_id,
526            allow_discount: self.allow_discount.unwrap_or(true),
527            cash_rounding_strategy: self.cash_rounding_strategy.unwrap_or_default(),
528            cash_rounding_unit: self.cash_rounding_unit.unwrap_or(Decimal::from(0)),
529            status: self.status.unwrap_or_default(),
530            metadata: AuditMetadata::default(),
531        })
532    }
533}