datasynth-core 2.4.0

Core domain models, traits, and distributions for synthetic enterprise data generation
Documentation
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
//! AR Credit Memo model.

use chrono::{DateTime, NaiveDate, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

use crate::models::subledger::{CurrencyAmount, GLReference, SubledgerDocumentStatus, TaxInfo};

/// AR Credit Memo (reduces customer balance).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ARCreditMemo {
    /// Unique credit memo number.
    pub credit_memo_number: String,
    /// Company code.
    pub company_code: String,
    /// Customer ID.
    pub customer_id: String,
    /// Customer name.
    pub customer_name: String,
    /// Credit memo date.
    pub memo_date: NaiveDate,
    /// Posting date.
    pub posting_date: NaiveDate,
    /// Credit memo type.
    pub memo_type: ARCreditMemoType,
    /// Credit memo status.
    pub status: SubledgerDocumentStatus,
    /// Reason code.
    pub reason_code: CreditMemoReason,
    /// Reason description.
    pub reason_description: String,
    /// Credit memo lines.
    pub lines: Vec<ARCreditMemoLine>,
    /// Net amount (before tax).
    pub net_amount: CurrencyAmount,
    /// Tax amount.
    pub tax_amount: CurrencyAmount,
    /// Gross amount (total credit).
    pub gross_amount: CurrencyAmount,
    /// Amount applied to invoices.
    pub amount_applied: Decimal,
    /// Amount remaining.
    pub amount_remaining: Decimal,
    /// Tax details.
    pub tax_details: Vec<TaxInfo>,
    /// Reference invoice (if applicable).
    pub reference_invoice: Option<String>,
    /// Reference return order.
    pub reference_return: Option<String>,
    /// Applied to invoices.
    pub applied_invoices: Vec<CreditMemoApplication>,
    /// GL reference.
    pub gl_reference: Option<GLReference>,
    /// Approval status.
    pub approval_status: ApprovalStatus,
    /// Approved by.
    pub approved_by: Option<String>,
    /// Approval date.
    pub approved_date: Option<NaiveDate>,
    /// Created timestamp.
    #[serde(with = "crate::serde_timestamp::utc")]
    pub created_at: DateTime<Utc>,
    /// Created by user.
    pub created_by: Option<String>,
    /// Notes.
    pub notes: Option<String>,
}

impl ARCreditMemo {
    /// Creates a new credit memo.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        credit_memo_number: String,
        company_code: String,
        customer_id: String,
        customer_name: String,
        memo_date: NaiveDate,
        reason_code: CreditMemoReason,
        reason_description: String,
        currency: String,
    ) -> Self {
        Self {
            credit_memo_number,
            company_code,
            customer_id,
            customer_name,
            memo_date,
            posting_date: memo_date,
            memo_type: ARCreditMemoType::Standard,
            status: SubledgerDocumentStatus::Open,
            reason_code,
            reason_description,
            lines: Vec::new(),
            net_amount: CurrencyAmount::single_currency(Decimal::ZERO, currency.clone()),
            tax_amount: CurrencyAmount::single_currency(Decimal::ZERO, currency.clone()),
            gross_amount: CurrencyAmount::single_currency(Decimal::ZERO, currency),
            amount_applied: Decimal::ZERO,
            amount_remaining: Decimal::ZERO,
            tax_details: Vec::new(),
            reference_invoice: None,
            reference_return: None,
            applied_invoices: Vec::new(),
            gl_reference: None,
            approval_status: ApprovalStatus::Pending,
            approved_by: None,
            approved_date: None,
            created_at: Utc::now(),
            created_by: None,
            notes: None,
        }
    }

    /// Creates credit memo for a specific invoice.
    #[allow(clippy::too_many_arguments)]
    pub fn for_invoice(
        credit_memo_number: String,
        company_code: String,
        customer_id: String,
        customer_name: String,
        memo_date: NaiveDate,
        invoice_number: String,
        reason_code: CreditMemoReason,
        reason_description: String,
        currency: String,
    ) -> Self {
        let mut memo = Self::new(
            credit_memo_number,
            company_code,
            customer_id,
            customer_name,
            memo_date,
            reason_code,
            reason_description,
            currency,
        );
        memo.reference_invoice = Some(invoice_number);
        memo
    }

    /// Adds a credit memo line.
    pub fn add_line(&mut self, line: ARCreditMemoLine) {
        self.lines.push(line);
        self.recalculate_totals();
    }

    /// Recalculates totals from lines.
    pub fn recalculate_totals(&mut self) {
        let net_total: Decimal = self.lines.iter().map(|l| l.net_amount).sum();
        let tax_total: Decimal = self.lines.iter().map(|l| l.tax_amount).sum();
        let gross_total = net_total + tax_total;

        self.net_amount.document_amount = net_total;
        self.net_amount.local_amount = net_total * self.net_amount.exchange_rate;
        self.tax_amount.document_amount = tax_total;
        self.tax_amount.local_amount = tax_total * self.tax_amount.exchange_rate;
        self.gross_amount.document_amount = gross_total;
        self.gross_amount.local_amount = gross_total * self.gross_amount.exchange_rate;
        self.amount_remaining = gross_total - self.amount_applied;
    }

    /// Applies credit memo to an invoice.
    pub fn apply_to_invoice(&mut self, invoice_number: String, amount: Decimal) {
        let application = CreditMemoApplication {
            invoice_number,
            amount_applied: amount,
            application_date: chrono::Local::now().date_naive(),
        };

        self.applied_invoices.push(application);
        self.amount_applied += amount;
        self.amount_remaining = self.gross_amount.document_amount - self.amount_applied;

        if self.amount_remaining <= Decimal::ZERO {
            self.status = SubledgerDocumentStatus::Cleared;
        } else {
            self.status = SubledgerDocumentStatus::PartiallyCleared;
        }
    }

    /// Approves the credit memo.
    pub fn approve(&mut self, approver: String, approval_date: NaiveDate) {
        self.approval_status = ApprovalStatus::Approved;
        self.approved_by = Some(approver);
        self.approved_date = Some(approval_date);
    }

    /// Rejects the credit memo.
    pub fn reject(&mut self, reason: String) {
        self.approval_status = ApprovalStatus::Rejected;
        self.notes = Some(format!(
            "{}Rejected: {}",
            self.notes
                .as_ref()
                .map(|n| format!("{n}. "))
                .unwrap_or_default(),
            reason
        ));
    }

    /// Sets the GL reference.
    pub fn set_gl_reference(&mut self, reference: GLReference) {
        self.gl_reference = Some(reference);
    }

    /// Sets reference return order.
    pub fn with_return_order(mut self, return_order: String) -> Self {
        self.reference_return = Some(return_order);
        self.memo_type = ARCreditMemoType::Return;
        self
    }

    /// Requires approval above threshold.
    pub fn requires_approval(&self, threshold: Decimal) -> bool {
        self.gross_amount.document_amount > threshold
    }
}

/// Type of credit memo.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ARCreditMemoType {
    /// Standard credit memo.
    #[default]
    Standard,
    /// Return credit memo.
    Return,
    /// Price adjustment.
    PriceAdjustment,
    /// Quantity adjustment.
    QuantityAdjustment,
    /// Rebate/volume discount.
    Rebate,
    /// Promotional credit.
    Promotional,
    /// Cancellation credit.
    Cancellation,
}

/// Reason code for credit memo.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum CreditMemoReason {
    /// Goods returned.
    Return,
    /// Damaged goods.
    Damaged,
    /// Wrong item shipped.
    WrongItem,
    /// Price error.
    PriceError,
    /// Quantity error.
    QuantityError,
    /// Quality issue.
    QualityIssue,
    /// Late delivery.
    LateDelivery,
    /// Promotional discount.
    Promotional,
    /// Volume rebate.
    VolumeRebate,
    /// Customer goodwill.
    Goodwill,
    /// Billing error.
    BillingError,
    /// Contract adjustment.
    ContractAdjustment,
    /// Other.
    #[default]
    Other,
}

/// Credit memo line item.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ARCreditMemoLine {
    /// Line number.
    pub line_number: u32,
    /// Material/product ID.
    pub material_id: Option<String>,
    /// Description.
    pub description: String,
    /// Quantity credited.
    pub quantity: Decimal,
    /// Unit of measure.
    pub unit: String,
    /// Unit price.
    pub unit_price: Decimal,
    /// Net amount.
    pub net_amount: Decimal,
    /// Tax code.
    pub tax_code: Option<String>,
    /// Tax rate.
    pub tax_rate: Decimal,
    /// Tax amount.
    pub tax_amount: Decimal,
    /// Gross amount.
    pub gross_amount: Decimal,
    /// Revenue account (credit).
    pub revenue_account: String,
    /// Reference invoice line.
    pub reference_invoice_line: Option<u32>,
    /// Cost center.
    pub cost_center: Option<String>,
    /// Profit center.
    pub profit_center: Option<String>,
}

impl ARCreditMemoLine {
    /// Creates a new credit memo line.
    pub fn new(
        line_number: u32,
        description: String,
        quantity: Decimal,
        unit: String,
        unit_price: Decimal,
        revenue_account: String,
    ) -> Self {
        let net_amount = (quantity * unit_price).round_dp(2);
        Self {
            line_number,
            material_id: None,
            description,
            quantity,
            unit,
            unit_price,
            net_amount,
            tax_code: None,
            tax_rate: Decimal::ZERO,
            tax_amount: Decimal::ZERO,
            gross_amount: net_amount,
            revenue_account,
            reference_invoice_line: None,
            cost_center: None,
            profit_center: None,
        }
    }

    /// Sets tax information.
    pub fn with_tax(mut self, tax_code: String, tax_rate: Decimal) -> Self {
        self.tax_code = Some(tax_code);
        self.tax_rate = tax_rate;
        self.tax_amount = (self.net_amount * tax_rate / rust_decimal_macros::dec!(100)).round_dp(2);
        self.gross_amount = self.net_amount + self.tax_amount;
        self
    }

    /// Sets reference to original invoice line.
    pub fn with_invoice_reference(mut self, line_number: u32) -> Self {
        self.reference_invoice_line = Some(line_number);
        self
    }
}

/// Application of credit memo to invoice.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreditMemoApplication {
    /// Invoice number.
    pub invoice_number: String,
    /// Amount applied.
    pub amount_applied: Decimal,
    /// Application date.
    pub application_date: NaiveDate,
}

/// Approval status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ApprovalStatus {
    /// Pending approval.
    #[default]
    Pending,
    /// Approved.
    Approved,
    /// Rejected.
    Rejected,
    /// Not required (under threshold).
    NotRequired,
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    #[test]
    fn test_credit_memo_creation() {
        let memo = ARCreditMemo::new(
            "CM001".to_string(),
            "1000".to_string(),
            "CUST001".to_string(),
            "Test Customer".to_string(),
            NaiveDate::from_ymd_opt(2024, 2, 15).unwrap(),
            CreditMemoReason::Return,
            "Goods returned".to_string(),
            "USD".to_string(),
        );

        assert_eq!(memo.status, SubledgerDocumentStatus::Open);
        assert_eq!(memo.approval_status, ApprovalStatus::Pending);
    }

    #[test]
    fn test_credit_memo_totals() {
        let mut memo = ARCreditMemo::new(
            "CM001".to_string(),
            "1000".to_string(),
            "CUST001".to_string(),
            "Test Customer".to_string(),
            NaiveDate::from_ymd_opt(2024, 2, 15).unwrap(),
            CreditMemoReason::PriceError,
            "Price correction".to_string(),
            "USD".to_string(),
        );

        let line = ARCreditMemoLine::new(
            1,
            "Product A".to_string(),
            dec!(5),
            "EA".to_string(),
            dec!(100),
            "4000".to_string(),
        )
        .with_tax("VAT".to_string(), dec!(20));

        memo.add_line(line);

        assert_eq!(memo.net_amount.document_amount, dec!(500));
        assert_eq!(memo.tax_amount.document_amount, dec!(100));
        assert_eq!(memo.gross_amount.document_amount, dec!(600));
    }

    #[test]
    fn test_apply_to_invoice() {
        let mut memo = ARCreditMemo::new(
            "CM001".to_string(),
            "1000".to_string(),
            "CUST001".to_string(),
            "Test Customer".to_string(),
            NaiveDate::from_ymd_opt(2024, 2, 15).unwrap(),
            CreditMemoReason::Return,
            "Goods returned".to_string(),
            "USD".to_string(),
        );

        let line = ARCreditMemoLine::new(
            1,
            "Product A".to_string(),
            dec!(10),
            "EA".to_string(),
            dec!(50),
            "4000".to_string(),
        );
        memo.add_line(line);

        memo.apply_to_invoice("INV001".to_string(), dec!(300));

        assert_eq!(memo.amount_applied, dec!(300));
        assert_eq!(memo.amount_remaining, dec!(200));
        assert_eq!(memo.status, SubledgerDocumentStatus::PartiallyCleared);
    }

    #[test]
    fn test_approval_workflow() {
        let mut memo = ARCreditMemo::new(
            "CM001".to_string(),
            "1000".to_string(),
            "CUST001".to_string(),
            "Test Customer".to_string(),
            NaiveDate::from_ymd_opt(2024, 2, 15).unwrap(),
            CreditMemoReason::Return,
            "Goods returned".to_string(),
            "USD".to_string(),
        );

        memo.approve(
            "MANAGER1".to_string(),
            NaiveDate::from_ymd_opt(2024, 2, 16).unwrap(),
        );

        assert_eq!(memo.approval_status, ApprovalStatus::Approved);
        assert_eq!(memo.approved_by, Some("MANAGER1".to_string()));
    }
}