Skip to main content

backbone_payroll/domain/entity/
salary_component.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use sqlx::FromRow;
4use uuid::Uuid;
5use rust_decimal::Decimal;
6
7use super::ComponentType;
8use super::AuditMetadata;
9
10/// Strongly-typed ID for SalaryComponent
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct SalaryComponentId(pub Uuid);
14
15impl SalaryComponentId {
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 SalaryComponentId {
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 SalaryComponentId {
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 SalaryComponentId {
35    fn from(id: Uuid) -> Self { Self(id) }
36}
37
38impl From<SalaryComponentId> for Uuid {
39    fn from(id: SalaryComponentId) -> Self { id.0 }
40}
41
42impl AsRef<Uuid> for SalaryComponentId {
43    fn as_ref(&self) -> &Uuid { &self.0 }
44}
45
46impl std::ops::Deref for SalaryComponentId {
47    type Target = Uuid;
48    fn deref(&self) -> &Self::Target { &self.0 }
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
52pub struct SalaryComponent {
53    pub id: Uuid,
54    pub structure_id: Uuid,
55    pub name: String,
56    pub component_type: ComponentType,
57    pub amount: Decimal,
58    pub gl_account_id: Uuid,
59    pub is_statutory: bool,
60    #[serde(default)]
61    #[sqlx(json)]
62    pub metadata: AuditMetadata,
63}
64
65impl SalaryComponent {
66    /// Create a builder for SalaryComponent
67    pub fn builder() -> SalaryComponentBuilder {
68        <SalaryComponentBuilder as Default>::default()
69    }
70
71    /// Create a new SalaryComponent with required fields
72    pub fn new(structure_id: Uuid, name: String, component_type: ComponentType, amount: Decimal, gl_account_id: Uuid, is_statutory: bool) -> Self {
73        Self {
74            id: Uuid::new_v4(),
75            structure_id,
76            name,
77            component_type,
78            amount,
79            gl_account_id,
80            is_statutory,
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) -> SalaryComponentId {
92        SalaryComponentId(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    // Partial Update
138    // ==========================================================
139
140    /// Apply partial updates from a map of field name to JSON value
141    pub fn apply_patch(&mut self, fields: std::collections::HashMap<String, serde_json::Value>) {
142        for (key, value) in fields {
143            match key.as_str() {
144                "structure_id" => {
145                    if let Ok(v) = serde_json::from_value(value) { self.structure_id = v; }
146                }
147                "name" => {
148                    if let Ok(v) = serde_json::from_value(value) { self.name = v; }
149                }
150                "component_type" => {
151                    if let Ok(v) = serde_json::from_value(value) { self.component_type = v; }
152                }
153                "amount" => {
154                    if let Ok(v) = serde_json::from_value(value) { self.amount = v; }
155                }
156                "gl_account_id" => {
157                    if let Ok(v) = serde_json::from_value(value) { self.gl_account_id = v; }
158                }
159                "is_statutory" => {
160                    if let Ok(v) = serde_json::from_value(value) { self.is_statutory = v; }
161                }
162                _ => {} // ignore unknown fields
163            }
164        }
165    }
166
167    // <<< CUSTOM METHODS START >>>
168    // <<< CUSTOM METHODS END >>>
169}
170
171impl super::Entity for SalaryComponent {
172    type Id = Uuid;
173
174    fn entity_id(&self) -> &Self::Id {
175        &self.id
176    }
177
178    fn entity_type() -> &'static str {
179        "SalaryComponent"
180    }
181}
182
183impl backbone_core::PersistentEntity for SalaryComponent {
184    fn entity_id(&self) -> String {
185        self.id.to_string()
186    }
187    fn set_entity_id(&mut self, id: String) {
188        if let Ok(uuid) = uuid::Uuid::parse_str(&id) {
189            self.id = uuid;
190        }
191    }
192    fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
193        self.metadata.created_at
194    }
195    fn set_created_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
196        self.metadata.created_at = Some(ts);
197    }
198    fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
199        self.metadata.updated_at
200    }
201    fn set_updated_at(&mut self, ts: chrono::DateTime<chrono::Utc>) {
202        self.metadata.updated_at = Some(ts);
203    }
204    fn deleted_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
205        self.metadata.deleted_at
206    }
207    fn set_deleted_at(&mut self, ts: Option<chrono::DateTime<chrono::Utc>>) {
208        self.metadata.deleted_at = ts;
209    }
210}
211
212impl backbone_orm::EntityRepoMeta for SalaryComponent {
213    fn column_types() -> std::collections::HashMap<String, String> {
214        let mut m = std::collections::HashMap::new();
215        m.insert("id".to_string(), "uuid".to_string());
216        m.insert("structure_id".to_string(), "uuid".to_string());
217        m.insert("gl_account_id".to_string(), "uuid".to_string());
218        m.insert("component_type".to_string(), "component_type".to_string());
219        m
220    }
221    fn search_fields() -> &'static [&'static str] {
222        &["name"]
223    }
224}
225
226/// Builder for SalaryComponent entity
227///
228/// Provides a fluent API for constructing SalaryComponent instances.
229/// System fields (id, metadata, timestamps) are auto-initialized.
230#[derive(Debug, Clone, Default)]
231pub struct SalaryComponentBuilder {
232    structure_id: Option<Uuid>,
233    name: Option<String>,
234    component_type: Option<ComponentType>,
235    amount: Option<Decimal>,
236    gl_account_id: Option<Uuid>,
237    is_statutory: Option<bool>,
238}
239
240impl SalaryComponentBuilder {
241    /// Set the structure_id field (required)
242    pub fn structure_id(mut self, value: Uuid) -> Self {
243        self.structure_id = Some(value);
244        self
245    }
246
247    /// Set the name field (required)
248    pub fn name(mut self, value: String) -> Self {
249        self.name = Some(value);
250        self
251    }
252
253    /// Set the component_type field (default: `ComponentType::default()`)
254    pub fn component_type(mut self, value: ComponentType) -> Self {
255        self.component_type = Some(value);
256        self
257    }
258
259    /// Set the amount field (default: `Decimal::from(0)`)
260    pub fn amount(mut self, value: Decimal) -> Self {
261        self.amount = Some(value);
262        self
263    }
264
265    /// Set the gl_account_id field (required)
266    pub fn gl_account_id(mut self, value: Uuid) -> Self {
267        self.gl_account_id = Some(value);
268        self
269    }
270
271    /// Set the is_statutory field (default: `false`)
272    pub fn is_statutory(mut self, value: bool) -> Self {
273        self.is_statutory = Some(value);
274        self
275    }
276
277    /// Build the SalaryComponent entity
278    ///
279    /// Returns Err if any required field without a default is missing.
280    pub fn build(self) -> Result<SalaryComponent, String> {
281        let structure_id = self.structure_id.ok_or_else(|| "structure_id is required".to_string())?;
282        let name = self.name.ok_or_else(|| "name is required".to_string())?;
283        let gl_account_id = self.gl_account_id.ok_or_else(|| "gl_account_id is required".to_string())?;
284
285        Ok(SalaryComponent {
286            id: Uuid::new_v4(),
287            structure_id,
288            name,
289            component_type: self.component_type.unwrap_or_default(),
290            amount: self.amount.unwrap_or(Decimal::from(0)),
291            gl_account_id,
292            is_statutory: self.is_statutory.unwrap_or(false),
293            metadata: AuditMetadata::default(),
294        })
295    }
296}