Skip to main content

sim_lib_auto_order/
invoice.rs

1//! Balanced invoice export data for modeled work orders.
2
3use sim_citizen::{CitizenField, field_error};
4use sim_kernel::{Error, Expr, NumberLiteral, Result, Symbol};
5use sim_lib_auto_core::text_read_construct_expr;
6use sim_lib_auto_parts::{OrderStatus, PartLine};
7
8/// Reference-only invoice evidence compatible with ledger draft attachments.
9#[derive(Clone, Debug, PartialEq, Eq, sim_citizen_derive::Citizen)]
10#[citizen(symbol = "auto/LedgerInvoiceEvidence", version = 0)]
11pub struct LedgerInvoiceEvidence {
12    /// Source namespace for the evidence.
13    pub backend: String,
14    /// Source-local evidence id.
15    pub external_id: String,
16    /// Optional immutable version or digest marker.
17    pub version: Option<String>,
18    /// Optional operator-facing URL.
19    pub web_url: Option<String>,
20    /// Optional voucher or capture digest.
21    pub immutable_hint: Option<String>,
22}
23
24impl Default for LedgerInvoiceEvidence {
25    fn default() -> Self {
26        Self::new(
27            "auto/work-order",
28            "SIM-WO-1",
29            Some("modeled-v0"),
30            None::<String>,
31            None::<String>,
32        )
33    }
34}
35
36impl LedgerInvoiceEvidence {
37    /// Builds an invoice evidence reference.
38    pub fn new(
39        backend: impl Into<String>,
40        external_id: impl Into<String>,
41        version: Option<impl Into<String>>,
42        web_url: Option<impl Into<String>>,
43        immutable_hint: Option<impl Into<String>>,
44    ) -> Self {
45        Self {
46            backend: backend.into(),
47            external_id: external_id.into(),
48            version: version.map(Into::into),
49            web_url: web_url.map(Into::into),
50            immutable_hint: immutable_hint.map(Into::into),
51        }
52    }
53
54    /// Encodes this evidence reference as explicit read-construct data.
55    pub fn to_expr(&self) -> Expr {
56        text_read_construct_expr(
57            "auto/LedgerInvoiceEvidence",
58            vec![
59                Expr::Symbol(Symbol::new("v0")),
60                Expr::String(self.backend.clone()),
61                Expr::String(self.external_id.clone()),
62                option_string_expr(&self.version),
63                option_string_expr(&self.web_url),
64                option_string_expr(&self.immutable_hint),
65            ],
66        )
67    }
68}
69
70impl CitizenField for LedgerInvoiceEvidence {
71    fn encode_field(&self) -> Expr {
72        self.to_expr()
73    }
74
75    fn decode_field_expr(expr: &Expr, field: &'static str) -> Result<Self> {
76        let args = read_construct_args(expr, "auto/LedgerInvoiceEvidence", field, 5)?;
77        Ok(Self {
78            backend: string_arg(&args[0], field)?,
79            external_id: string_arg(&args[1], field)?,
80            version: option_string_arg(&args[2], field)?,
81            web_url: option_string_arg(&args[3], field)?,
82            immutable_hint: option_string_arg(&args[4], field)?,
83        })
84    }
85}
86
87/// One exact minor-unit invoice posting.
88#[derive(Clone, Debug, PartialEq, Eq, sim_citizen_derive::Citizen)]
89#[citizen(symbol = "auto/LedgerInvoicePosting", version = 0)]
90pub struct LedgerInvoicePosting {
91    /// Ledger account text.
92    pub account: String,
93    /// Signed amount in currency minor units.
94    pub amount_minor: i64,
95    /// Operator-facing posting text.
96    pub text: String,
97}
98
99impl Default for LedgerInvoicePosting {
100    fn default() -> Self {
101        Self::new("1510", 1_000, "modeled customer receivable")
102    }
103}
104
105impl LedgerInvoicePosting {
106    /// Builds an invoice posting.
107    pub fn new(account: impl Into<String>, amount_minor: i64, text: impl Into<String>) -> Self {
108        Self {
109            account: account.into(),
110            amount_minor,
111            text: text.into(),
112        }
113    }
114
115    /// Encodes this posting as explicit read-construct data.
116    pub fn to_expr(&self) -> Expr {
117        text_read_construct_expr(
118            "auto/LedgerInvoicePosting",
119            vec![
120                Expr::Symbol(Symbol::new("v0")),
121                Expr::String(self.account.clone()),
122                number_expr(self.amount_minor),
123                Expr::String(self.text.clone()),
124            ],
125        )
126    }
127}
128
129impl CitizenField for LedgerInvoicePosting {
130    fn encode_field(&self) -> Expr {
131        self.to_expr()
132    }
133
134    fn decode_field_expr(expr: &Expr, field: &'static str) -> Result<Self> {
135        let args = read_construct_args(expr, "auto/LedgerInvoicePosting", field, 3)?;
136        Ok(Self {
137            account: string_arg(&args[0], field)?,
138            amount_minor: i64_arg(&args[1], field)?,
139            text: string_arg(&args[2], field)?,
140        })
141    }
142}
143
144/// Balanced invoice draft export for ledger tooling.
145#[derive(Clone, Debug, PartialEq, Eq, sim_citizen_derive::Citizen)]
146#[citizen(symbol = "auto/LedgerInvoiceExport", version = 0)]
147pub struct LedgerInvoiceExport {
148    /// ISO-like voucher date text.
149    pub voucher_date: String,
150    /// Operator-facing voucher text.
151    pub voucher_text: String,
152    /// Currency code.
153    pub currency: String,
154    /// Exact posting lines.
155    pub postings: Vec<LedgerInvoicePosting>,
156    /// Reference-only evidence attachments.
157    pub evidence: Vec<LedgerInvoiceEvidence>,
158}
159
160impl Default for LedgerInvoiceExport {
161    fn default() -> Self {
162        Self::for_work_order(
163            "SIM-WO-1",
164            &OrderStatus::default(),
165            &[PartLine::default()],
166            90,
167        )
168    }
169}
170
171impl LedgerInvoiceExport {
172    /// Builds the modeled invoice export for one work order.
173    pub fn for_work_order(
174        work_order_id: &str,
175        order: &OrderStatus,
176        parts: &[PartLine],
177        labor_minutes: u32,
178    ) -> Self {
179        let parts_minor = parts_minor(parts);
180        let labor_minor = i64::from(labor_minutes) * 1_250;
181        let total_minor = parts_minor + labor_minor;
182        Self {
183            voucher_date: "2026-01-15".to_owned(),
184            voucher_text: format!("modeled work order {work_order_id} {}", order.id),
185            currency: "SEK".to_owned(),
186            postings: vec![
187                LedgerInvoicePosting::new("1510", total_minor, "customer receivable"),
188                LedgerInvoicePosting::new("3041", -parts_minor, "modeled parts revenue"),
189                LedgerInvoicePosting::new("3051", -labor_minor, "modeled labor revenue"),
190            ],
191            evidence: vec![LedgerInvoiceEvidence::new(
192                "auto/work-order",
193                work_order_id,
194                Some("modeled-v0"),
195                None::<String>,
196                Some(order.ledger_ref.clone()),
197            )],
198        }
199    }
200
201    /// Returns whether the posting lines sum to zero.
202    pub fn is_balanced(&self) -> bool {
203        self.postings
204            .iter()
205            .map(|posting| posting.amount_minor)
206            .sum::<i64>()
207            == 0
208    }
209
210    /// Returns the signed posting sum.
211    pub fn minor_sum(&self) -> i64 {
212        self.postings
213            .iter()
214            .map(|posting| posting.amount_minor)
215            .sum()
216    }
217
218    /// Encodes this export as explicit read-construct data.
219    pub fn to_expr(&self) -> Expr {
220        text_read_construct_expr(
221            "auto/LedgerInvoiceExport",
222            vec![
223                Expr::Symbol(Symbol::new("v0")),
224                Expr::String(self.voucher_date.clone()),
225                Expr::String(self.voucher_text.clone()),
226                Expr::String(self.currency.clone()),
227                Expr::List(
228                    self.postings
229                        .iter()
230                        .map(LedgerInvoicePosting::to_expr)
231                        .collect(),
232                ),
233                Expr::List(
234                    self.evidence
235                        .iter()
236                        .map(LedgerInvoiceEvidence::to_expr)
237                        .collect(),
238                ),
239            ],
240        )
241    }
242}
243
244impl CitizenField for LedgerInvoiceExport {
245    fn encode_field(&self) -> Expr {
246        self.to_expr()
247    }
248
249    fn decode_field_expr(expr: &Expr, field: &'static str) -> Result<Self> {
250        let args = read_construct_args(expr, "auto/LedgerInvoiceExport", field, 5)?;
251        Ok(Self {
252            voucher_date: string_arg(&args[0], field)?,
253            voucher_text: string_arg(&args[1], field)?,
254            currency: string_arg(&args[2], field)?,
255            postings: Vec::<LedgerInvoicePosting>::decode_field_expr(&args[3], field)?,
256            evidence: Vec::<LedgerInvoiceEvidence>::decode_field_expr(&args[4], field)?,
257        })
258    }
259}
260
261fn parts_minor(parts: &[PartLine]) -> i64 {
262    parts
263        .iter()
264        .map(|part| i64::from(part.qty) * modeled_unit_minor(&part.sku))
265        .sum()
266}
267
268fn modeled_unit_minor(sku: &str) -> i64 {
269    if sku.contains("COIL") { 54_900 } else { 19_900 }
270}
271
272fn option_string_expr(value: &Option<String>) -> Expr {
273    value
274        .as_ref()
275        .map(|text| Expr::String(text.clone()))
276        .unwrap_or(Expr::Nil)
277}
278
279pub(crate) fn number_expr(value: i64) -> Expr {
280    Expr::Number(NumberLiteral {
281        domain: Symbol::qualified("core", "Number"),
282        canonical: value.to_string(),
283    })
284}
285
286pub(crate) fn read_construct_args<'a>(
287    expr: &'a Expr,
288    class: &'static str,
289    field: &'static str,
290    arity: usize,
291) -> Result<&'a [Expr]> {
292    let Expr::Extension { tag, payload } = expr else {
293        return Err(field_error(field, "expected citizen read-construct"));
294    };
295    if tag != &Symbol::qualified("citizen", "read-construct") {
296        return Err(field_error(
297            field,
298            format!("expected citizen read-construct, found {tag}"),
299        ));
300    }
301    let Expr::Vector(items) = payload.as_ref() else {
302        return Err(field_error(
303            field,
304            "read-construct payload must be a vector",
305        ));
306    };
307    if items.len() != arity + 2 {
308        return Err(field_error(
309            field,
310            format!(
311                "expected {arity} constructor field(s), found {}",
312                items.len().saturating_sub(2)
313            ),
314        ));
315    }
316    match &items[0] {
317        Expr::Symbol(symbol) if symbol == &symbol_text(class) => {}
318        Expr::Symbol(symbol) => {
319            return Err(field_error(
320                field,
321                format!("expected class {class}, found {symbol}"),
322            ));
323        }
324        other => {
325            return Err(field_error(
326                field,
327                format!("expected class symbol, found {other:?}"),
328            ));
329        }
330    }
331    match &items[1] {
332        Expr::Symbol(version) if version == &Symbol::new("v0") => Ok(&items[2..]),
333        other => Err(field_error(field, format!("expected v0, found {other:?}"))),
334    }
335}
336
337pub(crate) fn string_arg(expr: &Expr, field: &'static str) -> Result<String> {
338    match expr {
339        Expr::String(value) => Ok(value.clone()),
340        Expr::Symbol(symbol) => Ok(symbol.as_qualified_str()),
341        other => Err(field_error(
342            field,
343            format!("expected string or symbol, found {other:?}"),
344        )),
345    }
346}
347
348pub(crate) fn bool_arg(expr: &Expr, field: &'static str) -> Result<bool> {
349    match expr {
350        Expr::Bool(value) => Ok(*value),
351        other => Err(field_error(
352            field,
353            format!("expected bool, found {other:?}"),
354        )),
355    }
356}
357
358pub(crate) fn i64_arg(expr: &Expr, field: &'static str) -> Result<i64> {
359    let Expr::Number(number) = expr else {
360        return Err(field_error(
361            field,
362            format!("expected number, found {expr:?}"),
363        ));
364    };
365    number
366        .canonical
367        .parse::<i64>()
368        .map_err(|err| Error::Eval(format!("citizen field {field}: invalid integer: {err}")))
369}
370
371pub(crate) fn u32_arg(expr: &Expr, field: &'static str) -> Result<u32> {
372    let value = i64_arg(expr, field)?;
373    u32::try_from(value)
374        .map_err(|_| field_error(field, format!("integer {value} is out of range for u32")))
375}
376
377pub(crate) fn option_string_arg(expr: &Expr, field: &'static str) -> Result<Option<String>> {
378    match expr {
379        Expr::Nil => Ok(None),
380        other => string_arg(other, field).map(Some),
381    }
382}
383
384pub(crate) fn string_list_arg(expr: &Expr, field: &'static str) -> Result<Vec<String>> {
385    match expr {
386        Expr::List(items) => items.iter().map(|item| string_arg(item, field)).collect(),
387        other => Err(field_error(
388            field,
389            format!("expected list, found {other:?}"),
390        )),
391    }
392}
393
394pub(crate) fn symbol_text(text: &str) -> Symbol {
395    if let Some((namespace, name)) = text.split_once('/') {
396        Symbol::qualified(namespace, name)
397    } else {
398        Symbol::new(text)
399    }
400}