Skip to main content

backbone_payroll/domain/entity/
compensation_change.rs

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