Skip to main content

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