Skip to main content

sim_lib_auto_order/
model.rs

1//! Work-order and conformance report model values.
2
3use std::collections::BTreeSet;
4
5use sim_citizen::CitizenField;
6use sim_kernel::{CapabilityName, Expr, Symbol};
7use sim_lib_auto_core::{
8    AUTO_DIAGNOSTICS_READ, AUTO_ORDER, BrandCaps, VehicleId, text_read_construct_expr,
9    vehicle_read_construct,
10};
11use sim_lib_auto_parts::{OrderStatus, PartLine};
12
13use crate::LedgerInvoiceExport;
14use crate::invoice::{
15    bool_arg, number_expr, read_construct_args, string_arg, string_list_arg, u32_arg,
16};
17
18mod fields;
19
20/// One work-order ledger event.
21#[derive(Clone, Debug, PartialEq, Eq, sim_citizen_derive::Citizen)]
22#[citizen(symbol = "auto/WorkOrderEvent", version = 0)]
23pub struct WorkOrderEvent {
24    /// Manifest site label.
25    pub site: String,
26    /// Operation symbol text.
27    pub operation: String,
28    /// Manifest lane selected by policy.
29    pub lane: String,
30    /// Required operation capability.
31    pub capability: String,
32    /// Effect class applied by the vendor gate.
33    pub effect: String,
34    /// Stable outcome label.
35    pub outcome: String,
36    /// Operator-facing note.
37    pub note: String,
38    /// Capabilities delegated to the child site request.
39    pub delegated_capabilities: Vec<String>,
40}
41
42impl Default for WorkOrderEvent {
43    fn default() -> Self {
44        Self::from_input(WorkOrderEventInput {
45            site: "xentry".to_owned(),
46            operation: "read/dtc".to_owned(),
47            lane: "read".to_owned(),
48            capability: CapabilityName::new(AUTO_DIAGNOSTICS_READ),
49            effect: "pure".to_owned(),
50            outcome: "accepted".to_owned(),
51            note: "modeled diagnostic read".to_owned(),
52            delegated_capabilities: vec![CapabilityName::new(AUTO_DIAGNOSTICS_READ)],
53        })
54    }
55}
56
57impl WorkOrderEvent {
58    pub(crate) fn from_input(input: WorkOrderEventInput) -> Self {
59        Self {
60            site: input.site,
61            operation: input.operation,
62            lane: input.lane,
63            capability: input.capability.as_str().to_owned(),
64            effect: input.effect,
65            outcome: input.outcome,
66            note: input.note,
67            delegated_capabilities: input
68                .delegated_capabilities
69                .into_iter()
70                .map(|capability| capability.as_str().to_owned())
71                .collect(),
72        }
73    }
74
75    /// Returns whether this event was accepted.
76    pub fn accepted(&self) -> bool {
77        self.outcome == "accepted"
78    }
79
80    /// Returns whether this event was denied by capability policy.
81    pub fn denied(&self) -> bool {
82        self.outcome == "denied"
83    }
84
85    /// Encodes this event as explicit read-construct data.
86    pub fn to_expr(&self) -> Expr {
87        text_read_construct_expr(
88            "auto/WorkOrderEvent",
89            vec![
90                Expr::Symbol(Symbol::new("v0")),
91                Expr::String(self.site.clone()),
92                Expr::String(self.operation.clone()),
93                Expr::String(self.lane.clone()),
94                Expr::String(self.capability.clone()),
95                Expr::String(self.effect.clone()),
96                Expr::String(self.outcome.clone()),
97                Expr::String(self.note.clone()),
98                Expr::List(
99                    self.delegated_capabilities
100                        .iter()
101                        .map(|capability| Expr::String(capability.clone()))
102                        .collect(),
103                ),
104            ],
105        )
106    }
107}
108
109pub(crate) struct WorkOrderEventInput {
110    pub(crate) site: String,
111    pub(crate) operation: String,
112    pub(crate) lane: String,
113    pub(crate) capability: CapabilityName,
114    pub(crate) effect: String,
115    pub(crate) outcome: String,
116    pub(crate) note: String,
117    pub(crate) delegated_capabilities: Vec<CapabilityName>,
118}
119
120impl CitizenField for WorkOrderEvent {
121    fn encode_field(&self) -> Expr {
122        self.to_expr()
123    }
124
125    fn decode_field_expr(expr: &Expr, field: &'static str) -> sim_kernel::Result<Self> {
126        let args = read_construct_args(expr, "auto/WorkOrderEvent", field, 8)?;
127        Ok(Self {
128            site: string_arg(&args[0], field)?,
129            operation: string_arg(&args[1], field)?,
130            lane: string_arg(&args[2], field)?,
131            capability: string_arg(&args[3], field)?,
132            effect: string_arg(&args[4], field)?,
133            outcome: string_arg(&args[5], field)?,
134            note: string_arg(&args[6], field)?,
135            delegated_capabilities: string_list_arg(&args[7], field)?,
136        })
137    }
138}
139
140/// Append-only modeled work-order ledger.
141#[derive(Clone, Debug, Default, PartialEq, Eq, sim_citizen_derive::Citizen)]
142#[citizen(symbol = "auto/WorkOrderLedger", version = 0)]
143pub struct WorkOrderLedger {
144    /// Recorded work-order events.
145    pub events: Vec<WorkOrderEvent>,
146}
147
148impl WorkOrderLedger {
149    /// Builds an empty work-order ledger.
150    pub fn new() -> Self {
151        Self::default()
152    }
153
154    /// Appends an event.
155    pub fn push(&mut self, event: WorkOrderEvent) {
156        self.events.push(event);
157    }
158
159    /// Number of accepted events.
160    pub fn accepted_count(&self) -> usize {
161        self.events.iter().filter(|event| event.accepted()).count()
162    }
163
164    /// Number of denied events.
165    pub fn denied_count(&self) -> usize {
166        self.events.iter().filter(|event| event.denied()).count()
167    }
168
169    /// Returns the unique site labels in the ledger.
170    pub fn sites(&self) -> BTreeSet<String> {
171        self.events.iter().map(|event| event.site.clone()).collect()
172    }
173
174    /// Encodes this ledger as explicit read-construct data.
175    pub fn to_expr(&self) -> Expr {
176        text_read_construct_expr(
177            "auto/WorkOrderLedger",
178            vec![
179                Expr::Symbol(Symbol::new("v0")),
180                Expr::List(self.events.iter().map(WorkOrderEvent::to_expr).collect()),
181            ],
182        )
183    }
184}
185
186impl CitizenField for WorkOrderLedger {
187    fn encode_field(&self) -> Expr {
188        self.to_expr()
189    }
190
191    fn decode_field_expr(expr: &Expr, field: &'static str) -> sim_kernel::Result<Self> {
192        let args = read_construct_args(expr, "auto/WorkOrderLedger", field, 1)?;
193        Ok(Self {
194            events: Vec::<WorkOrderEvent>::decode_field_expr(&args[0], field)?,
195        })
196    }
197}
198
199/// One modeled automotive work-order session.
200#[derive(Clone, Debug, PartialEq, Eq, sim_citizen_derive::Citizen)]
201#[citizen(symbol = "auto/WorkOrder", version = 0)]
202pub struct WorkOrder {
203    /// Stable modeled work-order id.
204    pub id: String,
205    /// Vehicle bound to the work order.
206    #[citizen(with = "fields::vehicle_field")]
207    pub vehicle: VehicleId,
208    /// Parent shop capability profile.
209    #[citizen(with = "fields::brand_caps_field")]
210    pub site: BrandCaps,
211    /// Work-order ledger.
212    pub ledger: WorkOrderLedger,
213    /// Parts cart used by the order step.
214    #[citizen(with = "fields::part_lines_field")]
215    pub parts: Vec<PartLine>,
216    /// Modeled supplier order status.
217    #[citizen(with = "fields::order_status_option_field")]
218    pub order_status: Option<OrderStatus>,
219    /// Optional balanced invoice export.
220    pub invoice: Option<LedgerInvoiceExport>,
221}
222
223impl Default for WorkOrder {
224    fn default() -> Self {
225        Self {
226            id: "SIM-WO-1".to_owned(),
227            vehicle: VehicleId::new("modeled-se", "vehicle-alpha"),
228            site: BrandCaps::new(
229                "modeled-shop",
230                vec![
231                    CapabilityName::new(AUTO_DIAGNOSTICS_READ),
232                    CapabilityName::new(AUTO_ORDER),
233                ],
234            ),
235            ledger: WorkOrderLedger::default(),
236            parts: vec![PartLine::default()],
237            order_status: Some(OrderStatus::default()),
238            invoice: Some(LedgerInvoiceExport::default()),
239        }
240    }
241}
242
243impl WorkOrder {
244    /// Builds a modeled work order.
245    pub fn new(
246        id: impl Into<String>,
247        vehicle: VehicleId,
248        parent_grants: Vec<CapabilityName>,
249    ) -> Self {
250        Self {
251            id: id.into(),
252            vehicle,
253            site: BrandCaps::new("modeled-shop", parent_grants),
254            ledger: WorkOrderLedger::new(),
255            parts: vec![PartLine::default()],
256            order_status: None,
257            invoice: None,
258        }
259    }
260
261    /// Encodes this work order as explicit read-construct data.
262    pub fn to_expr(&self) -> Expr {
263        text_read_construct_expr(
264            "auto/WorkOrder",
265            vec![
266                Expr::Symbol(Symbol::new("v0")),
267                Expr::String(self.id.clone()),
268                vehicle_read_construct(&self.vehicle),
269                brand_caps_expr(&self.site),
270                self.ledger.to_expr(),
271                Expr::List(self.parts.iter().map(PartLine::to_expr).collect()),
272                self.order_status
273                    .as_ref()
274                    .map(OrderStatus::to_expr)
275                    .unwrap_or(Expr::Nil),
276                self.invoice
277                    .as_ref()
278                    .map(LedgerInvoiceExport::to_expr)
279                    .unwrap_or(Expr::Nil),
280            ],
281        )
282    }
283}
284
285impl CitizenField for WorkOrder {
286    fn encode_field(&self) -> Expr {
287        self.to_expr()
288    }
289
290    fn decode_field_expr(expr: &Expr, field: &'static str) -> sim_kernel::Result<Self> {
291        let args = read_construct_args(expr, "auto/WorkOrder", field, 7)?;
292        Ok(Self {
293            id: string_arg(&args[0], field)?,
294            vehicle: fields::vehicle_field::decode(&args[1])?,
295            site: fields::brand_caps_field::decode(&args[2])?,
296            ledger: WorkOrderLedger::decode_field_expr(&args[3], field)?,
297            parts: fields::part_lines_field::decode(&args[4])?,
298            order_status: fields::order_status_option_field::decode(&args[5])?,
299            invoice: Option::<LedgerInvoiceExport>::decode_field_expr(&args[6], field)?,
300        })
301    }
302}
303
304/// Modeled work-order conformance result.
305#[derive(Clone, Debug, Default, PartialEq, Eq, sim_citizen_derive::Citizen)]
306#[citizen(symbol = "auto/ConformanceReport", version = 0)]
307pub struct ConformanceReport {
308    /// Whether the modeled conformance story passed.
309    pub passed: bool,
310    /// Work order produced by the story.
311    pub work_order: WorkOrder,
312    /// Number of distinct sites reached.
313    pub site_count: u32,
314    /// Number of expected sites.
315    pub expected_site_count: u32,
316    /// Number of accepted operation events.
317    pub accepted_count: u32,
318    /// Number of denied operation events.
319    pub denied_count: u32,
320    /// Delegation violations found while diminishing grants.
321    pub delegation_violations: Vec<String>,
322    /// Other conformance issues.
323    pub issues: Vec<String>,
324}
325
326impl ConformanceReport {
327    /// Builds a report.
328    pub fn new(
329        work_order: WorkOrder,
330        expected_site_count: usize,
331        delegation_violations: Vec<String>,
332        issues: Vec<String>,
333    ) -> Self {
334        let site_count = work_order.ledger.sites().len();
335        let accepted_count = work_order.ledger.accepted_count();
336        let denied_count = work_order.ledger.denied_count();
337        let passed = site_count == expected_site_count
338            && delegation_violations.is_empty()
339            && issues.is_empty()
340            && work_order
341                .invoice
342                .as_ref()
343                .is_some_and(LedgerInvoiceExport::is_balanced);
344        Self {
345            passed,
346            work_order,
347            site_count: site_count as u32,
348            expected_site_count: expected_site_count as u32,
349            accepted_count: accepted_count as u32,
350            denied_count: denied_count as u32,
351            delegation_violations,
352            issues,
353        }
354    }
355
356    /// Encodes this report as explicit read-construct data.
357    pub fn to_expr(&self) -> Expr {
358        text_read_construct_expr(
359            "auto/ConformanceReport",
360            vec![
361                Expr::Symbol(Symbol::new("v0")),
362                Expr::Bool(self.passed),
363                self.work_order.to_expr(),
364                number_expr(i64::from(self.site_count)),
365                number_expr(i64::from(self.expected_site_count)),
366                number_expr(i64::from(self.accepted_count)),
367                number_expr(i64::from(self.denied_count)),
368                string_list_expr(&self.delegation_violations),
369                string_list_expr(&self.issues),
370            ],
371        )
372    }
373}
374
375impl CitizenField for ConformanceReport {
376    fn encode_field(&self) -> Expr {
377        self.to_expr()
378    }
379
380    fn decode_field_expr(expr: &Expr, field: &'static str) -> sim_kernel::Result<Self> {
381        let args = read_construct_args(expr, "auto/ConformanceReport", field, 8)?;
382        Ok(Self {
383            passed: bool_arg(&args[0], field)?,
384            work_order: WorkOrder::decode_field_expr(&args[1], field)?,
385            site_count: u32_arg(&args[2], field)?,
386            expected_site_count: u32_arg(&args[3], field)?,
387            accepted_count: u32_arg(&args[4], field)?,
388            denied_count: u32_arg(&args[5], field)?,
389            delegation_violations: string_list_arg(&args[6], field)?,
390            issues: string_list_arg(&args[7], field)?,
391        })
392    }
393}
394
395fn brand_caps_expr(site: &BrandCaps) -> Expr {
396    text_read_construct_expr(
397        "auto/BrandCaps",
398        vec![
399            Expr::Symbol(Symbol::new("v0")),
400            Expr::String(site.brand.clone()),
401            Expr::List(
402                site.capabilities
403                    .iter()
404                    .map(|capability| Expr::String(capability.as_str().to_owned()))
405                    .collect(),
406            ),
407        ],
408    )
409}
410
411fn string_list_expr(items: &[String]) -> Expr {
412    Expr::List(
413        items
414            .iter()
415            .map(|item| Expr::String(item.clone()))
416            .collect(),
417    )
418}