stateset-core 0.8.1

Core domain models and business logic for StateSet iCommerce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Purchase Order domain models
//!
//! Handles supplier ordering for inventory replenishment.

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use stateset_primitives::{CurrencyCode, ProductId, PurchaseOrderId};
use strum::{Display, EnumString};
use uuid::Uuid;

/// Purchase order status
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, Serialize, Deserialize, Default)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PurchaseOrderStatus {
    /// Draft - not yet submitted
    #[default]
    Draft,
    /// Pending approval
    PendingApproval,
    /// Approved, ready to send
    Approved,
    /// Sent to supplier
    Sent,
    /// Acknowledged by supplier
    Acknowledged,
    /// Partially received
    PartiallyReceived,
    /// Fully received
    Received,
    /// Completed/closed
    Completed,
    /// Cancelled
    Cancelled,
    /// On hold
    OnHold,
}

impl std::str::FromStr for PurchaseOrderStatus {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "draft" => Ok(Self::Draft),
            "pending_approval" => Ok(Self::PendingApproval),
            "approved" => Ok(Self::Approved),
            "sent" => Ok(Self::Sent),
            "acknowledged" => Ok(Self::Acknowledged),
            "partially_received" => Ok(Self::PartiallyReceived),
            "received" => Ok(Self::Received),
            "completed" => Ok(Self::Completed),
            "cancelled" | "canceled" => Ok(Self::Cancelled),
            "on_hold" => Ok(Self::OnHold),
            _ => Err(format!("Unknown purchase order status: {}", s)),
        }
    }
}

/// Payment terms for purchase orders
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Display, EnumString, Serialize, Deserialize, Default,
)]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PaymentTerms {
    /// Payment due on receipt
    #[default]
    DueOnReceipt,
    /// Net 15 days
    #[strum(serialize = "net_15", serialize = "net15")]
    Net15,
    /// Net 30 days
    #[strum(serialize = "net_30", serialize = "net30")]
    Net30,
    /// Net 45 days
    #[strum(serialize = "net_45", serialize = "net45")]
    Net45,
    /// Net 60 days
    #[strum(serialize = "net_60", serialize = "net60")]
    Net60,
    /// Net 90 days
    #[strum(serialize = "net_90", serialize = "net90")]
    Net90,
    /// 2% discount if paid in 10 days, net 30
    #[strum(serialize = "2_10_net_30", serialize = "2/10_net_30")]
    TwoTenNet30,
    /// Prepaid
    Prepaid,
    /// Cash on delivery
    #[strum(serialize = "cash_on_delivery", serialize = "cod")]
    CashOnDelivery,
    /// Letter of credit
    #[strum(serialize = "letter_of_credit", serialize = "lc")]
    LetterOfCredit,
}

/// A supplier/vendor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Supplier {
    /// Unique supplier ID
    pub id: Uuid,
    /// Supplier code/number
    pub supplier_code: String,
    /// Company name
    pub name: String,
    /// Contact person name
    pub contact_name: Option<String>,
    /// Contact email
    pub email: Option<String>,
    /// Contact phone
    pub phone: Option<String>,
    /// Website
    pub website: Option<String>,
    /// Address
    pub address: Option<String>,
    /// City
    pub city: Option<String>,
    /// State/Province
    pub state: Option<String>,
    /// Postal code
    pub postal_code: Option<String>,
    /// Country
    pub country: Option<String>,
    /// Tax ID / VAT number
    pub tax_id: Option<String>,
    /// Default payment terms
    pub payment_terms: PaymentTerms,
    /// Default currency
    pub currency: CurrencyCode,
    /// Lead time in days
    pub lead_time_days: Option<i32>,
    /// Minimum order amount
    pub minimum_order: Option<Decimal>,
    /// Whether supplier is active
    pub is_active: bool,
    /// Notes
    pub notes: Option<String>,
    /// When created
    pub created_at: DateTime<Utc>,
    /// When last updated
    pub updated_at: DateTime<Utc>,
}

/// Input for creating a supplier
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CreateSupplier {
    /// Company name
    pub name: String,
    /// Supplier code (auto-generated if not provided)
    pub supplier_code: Option<String>,
    /// Contact person
    pub contact_name: Option<String>,
    /// Email
    pub email: Option<String>,
    /// Phone
    pub phone: Option<String>,
    /// Website
    pub website: Option<String>,
    /// Address
    pub address: Option<String>,
    /// City
    pub city: Option<String>,
    /// State
    pub state: Option<String>,
    /// Postal code
    pub postal_code: Option<String>,
    /// Country
    pub country: Option<String>,
    /// Tax ID
    pub tax_id: Option<String>,
    /// Payment terms
    pub payment_terms: Option<PaymentTerms>,
    /// Currency (defaults to USD)
    pub currency: Option<CurrencyCode>,
    /// Lead time in days
    pub lead_time_days: Option<i32>,
    /// Minimum order amount
    pub minimum_order: Option<Decimal>,
    /// Notes
    pub notes: Option<String>,
}

/// Input for updating a supplier
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateSupplier {
    /// Update name
    pub name: Option<String>,
    /// Update contact name
    pub contact_name: Option<String>,
    /// Update email
    pub email: Option<String>,
    /// Update phone
    pub phone: Option<String>,
    /// Update website
    pub website: Option<String>,
    /// Update address
    pub address: Option<String>,
    /// Update city
    pub city: Option<String>,
    /// Update state
    pub state: Option<String>,
    /// Update postal code
    pub postal_code: Option<String>,
    /// Update country
    pub country: Option<String>,
    /// Update tax ID
    pub tax_id: Option<String>,
    /// Update payment terms
    pub payment_terms: Option<PaymentTerms>,
    /// Update currency
    pub currency: Option<CurrencyCode>,
    /// Update lead time
    pub lead_time_days: Option<i32>,
    /// Update minimum order
    pub minimum_order: Option<Decimal>,
    /// Update active status
    pub is_active: Option<bool>,
    /// Update notes
    pub notes: Option<String>,
}

/// Filter for listing suppliers
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SupplierFilter {
    /// Search by name
    pub name: Option<String>,
    /// Filter by country
    pub country: Option<String>,
    /// Filter by active only
    pub active_only: Option<bool>,
    /// Limit results
    pub limit: Option<u32>,
    /// Offset for pagination
    pub offset: Option<u32>,
}

/// A purchase order
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PurchaseOrder {
    /// Unique ID
    pub id: PurchaseOrderId,
    /// Human-readable PO number
    pub po_number: String,
    /// Supplier ID
    pub supplier_id: Uuid,
    /// PO status
    pub status: PurchaseOrderStatus,
    /// Order date
    pub order_date: DateTime<Utc>,
    /// Expected delivery date
    pub expected_date: Option<DateTime<Utc>>,
    /// Actual delivery date
    pub delivered_date: Option<DateTime<Utc>>,
    /// Ship to address
    pub ship_to_address: Option<String>,
    /// Ship to city
    pub ship_to_city: Option<String>,
    /// Ship to state
    pub ship_to_state: Option<String>,
    /// Ship to postal code
    pub ship_to_postal_code: Option<String>,
    /// Ship to country
    pub ship_to_country: Option<String>,
    /// Payment terms
    pub payment_terms: PaymentTerms,
    /// Currency
    pub currency: CurrencyCode,
    /// Subtotal (sum of line items)
    pub subtotal: Decimal,
    /// Tax amount
    pub tax_amount: Decimal,
    /// Shipping cost
    pub shipping_cost: Decimal,
    /// Discount amount
    pub discount_amount: Decimal,
    /// Total amount
    pub total: Decimal,
    /// Amount paid
    pub amount_paid: Decimal,
    /// Supplier reference number
    pub supplier_reference: Option<String>,
    /// Internal notes
    pub notes: Option<String>,
    /// Supplier notes (visible to supplier)
    pub supplier_notes: Option<String>,
    /// Who approved the PO
    pub approved_by: Option<String>,
    /// When approved
    pub approved_at: Option<DateTime<Utc>>,
    /// Line items
    pub items: Vec<PurchaseOrderItem>,
    /// When sent to supplier
    pub sent_at: Option<DateTime<Utc>>,
    /// When created
    pub created_at: DateTime<Utc>,
    /// When last updated
    pub updated_at: DateTime<Utc>,
}

/// A line item on a purchase order
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PurchaseOrderItem {
    /// Unique ID
    pub id: Uuid,
    /// Parent PO ID
    pub purchase_order_id: PurchaseOrderId,
    /// Product ID (if linked)
    pub product_id: Option<ProductId>,
    /// SKU
    pub sku: String,
    /// Item name/description
    pub name: String,
    /// Supplier's part number
    pub supplier_sku: Option<String>,
    /// Quantity ordered
    pub quantity_ordered: Decimal,
    /// Quantity received
    pub quantity_received: Decimal,
    /// Unit of measure
    pub unit_of_measure: Option<String>,
    /// Unit cost
    pub unit_cost: Decimal,
    /// Line total
    pub line_total: Decimal,
    /// Tax amount for this line
    pub tax_amount: Decimal,
    /// Discount amount for this line
    pub discount_amount: Decimal,
    /// Expected date for this item
    pub expected_date: Option<DateTime<Utc>>,
    /// Notes for this line
    pub notes: Option<String>,
    /// When created
    pub created_at: DateTime<Utc>,
    /// When last updated
    pub updated_at: DateTime<Utc>,
}

/// Input for creating a purchase order
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CreatePurchaseOrder {
    /// Supplier ID
    pub supplier_id: Uuid,
    /// Order date (defaults to now)
    pub order_date: Option<DateTime<Utc>>,
    /// Expected delivery date
    pub expected_date: Option<DateTime<Utc>>,
    /// Ship to address
    pub ship_to_address: Option<String>,
    /// Ship to city
    pub ship_to_city: Option<String>,
    /// Ship to state
    pub ship_to_state: Option<String>,
    /// Ship to postal code
    pub ship_to_postal_code: Option<String>,
    /// Ship to country
    pub ship_to_country: Option<String>,
    /// Payment terms (defaults to supplier's terms)
    pub payment_terms: Option<PaymentTerms>,
    /// Currency (defaults to supplier's currency)
    pub currency: Option<CurrencyCode>,
    /// Tax amount
    pub tax_amount: Option<Decimal>,
    /// Shipping cost
    pub shipping_cost: Option<Decimal>,
    /// Discount amount
    pub discount_amount: Option<Decimal>,
    /// Notes
    pub notes: Option<String>,
    /// Supplier notes
    pub supplier_notes: Option<String>,
    /// Line items
    pub items: Vec<CreatePurchaseOrderItem>,
}

/// Input for creating a PO line item
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CreatePurchaseOrderItem {
    /// Product ID
    pub product_id: Option<ProductId>,
    /// SKU
    pub sku: String,
    /// Item name
    pub name: String,
    /// Supplier's part number
    pub supplier_sku: Option<String>,
    /// Quantity to order
    pub quantity: Decimal,
    /// Unit of measure
    pub unit_of_measure: Option<String>,
    /// Unit cost
    pub unit_cost: Decimal,
    /// Tax amount
    pub tax_amount: Option<Decimal>,
    /// Discount amount
    pub discount_amount: Option<Decimal>,
    /// Expected date
    pub expected_date: Option<DateTime<Utc>>,
    /// Notes
    pub notes: Option<String>,
}

/// Input for updating a purchase order
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdatePurchaseOrder {
    /// Update expected date
    pub expected_date: Option<DateTime<Utc>>,
    /// Update ship to address
    pub ship_to_address: Option<String>,
    /// Update ship to city
    pub ship_to_city: Option<String>,
    /// Update ship to state
    pub ship_to_state: Option<String>,
    /// Update ship to postal code
    pub ship_to_postal_code: Option<String>,
    /// Update ship to country
    pub ship_to_country: Option<String>,
    /// Update payment terms
    pub payment_terms: Option<PaymentTerms>,
    /// Update tax amount
    pub tax_amount: Option<Decimal>,
    /// Update shipping cost
    pub shipping_cost: Option<Decimal>,
    /// Update discount amount
    pub discount_amount: Option<Decimal>,
    /// Update notes
    pub notes: Option<String>,
    /// Update supplier notes
    pub supplier_notes: Option<String>,
    /// Update supplier reference
    pub supplier_reference: Option<String>,
}

/// Input for receiving items on a purchase order
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ReceivePurchaseOrderItems {
    /// Items being received
    pub items: Vec<ReceivePurchaseOrderItem>,
    /// Notes about the receipt
    pub notes: Option<String>,
}

/// Input for receiving a single PO line item
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ReceivePurchaseOrderItem {
    /// PO item ID
    pub item_id: Uuid,
    /// Quantity being received
    pub quantity_received: Decimal,
    /// Notes
    pub notes: Option<String>,
}

/// Filter for listing purchase orders
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PurchaseOrderFilter {
    /// Filter by supplier ID
    pub supplier_id: Option<Uuid>,
    /// Filter by status
    pub status: Option<PurchaseOrderStatus>,
    /// Filter by date range start
    pub from_date: Option<DateTime<Utc>>,
    /// Filter by date range end
    pub to_date: Option<DateTime<Utc>>,
    /// Filter by minimum total
    pub min_total: Option<Decimal>,
    /// Filter by maximum total
    pub max_total: Option<Decimal>,
    /// Limit results
    pub limit: Option<u32>,
    /// Offset for pagination
    pub offset: Option<u32>,
}

/// Generate a unique supplier code
pub fn generate_supplier_code() -> String {
    let now = chrono::Utc::now();
    let short_id = &uuid::Uuid::new_v4().simple().to_string()[..8];
    format!("SUP-{}-{short_id}", now.format("%Y%m%d%H%M%S"))
}

/// Generate a unique purchase order number
pub fn generate_po_number() -> String {
    let now = chrono::Utc::now();
    let short_id = &uuid::Uuid::new_v4().to_string()[..8];
    format!("PO-{}-{}", now.format("%Y%m%d%H%M%S"), short_id)
}

#[cfg(test)]
mod tests {
    use super::generate_supplier_code;

    #[test]
    fn generated_supplier_codes_include_entropy_suffix() {
        let first = generate_supplier_code();
        let second = generate_supplier_code();

        assert!(first.starts_with("SUP-"));
        assert!(first.len() > "SUP-20260101120000".len());
        assert_ne!(first, second);
    }
}