Skip to main content

backbone_inventory/domain/entity/
route_rule.rs

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