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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use super::*;
use serde_json::Value;
// ===========================================================================
// BOM export (assemblies build-spec §9) — the parts list straight off the
// MAIN-SIDE parts library + live component projection, both already warm via
// the assembly sync (`sync_assembly` re-executes main-side after each applied
// run). One row per parts-library entry: `{partName, sourceKey, quantity}`
// with quantity = live ACOMP instance count. A sub-assembly is ONE row at
// this level — its internal parts are its own document's business (the
// rigid-nesting model). Exported as CSV and JSON through the file dialog's
// Export modal; deliberately small: no per-configuration quantities, no
// extra columns, no localization.
// ===========================================================================
/// One BOM row: a parts-library entry + its live instance count. Field order
/// IS the exported JSON key order (serde serializes structs in declaration
/// order), so the record shape stays `{partName, sourceKey, quantity}`.
#[derive(serde::Serialize)]
struct BomRow {
#[serde(rename = "partName")]
part_name: String,
#[serde(rename = "sourceKey")]
source_key: String,
quantity: usize,
}
/// Quote a CSV field only when it needs it (comma / quote / CR / LF),
/// doubling embedded quotes — minimal RFC-4180 so a part name or store path
/// with a comma can never shear a row.
fn csv_field(text: &str) -> String {
if text.contains([',', '"', '\n', '\r']) {
format!("\"{}\"", text.replace('"', "\"\""))
} else {
text.to_string()
}
}
impl EngineState {
/// The BOM rows in parts-library order (BTreeMap ⇒ alphabetical part
/// name — deterministic). Quantity counts component RECORDS (instances),
/// not member solids, so a multi-body part is still one per placement.
/// Errs (`"no components in the assembly"`) on a componentless document.
fn bom_rows(&mut self) -> Result<Vec<BomRow>, String> {
self.ensure_assembly_synced();
if self.assembly_components.is_empty() {
return Err("no components in the assembly".into());
}
let library: std::collections::BTreeMap<String, Value> =
serde_json::from_str(&brep_kernel::parts_library_json())
.map_err(|error| format!("parts library unreadable: {error}"))?;
Ok(library
.into_iter()
.map(|(part_name, entry)| {
let quantity = self
.assembly_components
.iter()
.filter(|record| record.part_name == part_name)
.count();
BomRow {
source_key: entry
.get("sourceKey")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
part_name,
quantity,
}
})
// The kernel GCs zero-instance entries at the end of every run;
// the filter keeps the export honest mid-mutation regardless.
.filter(|row| row.quantity > 0)
.collect())
}
/// Export the assembly BOM as CSV: the exact `partName,sourceKey,quantity`
/// header, one line per parts-library entry, LF endings.
pub fn export_bom_csv(&mut self) -> Result<String, String> {
let mut out = String::from("partName,sourceKey,quantity\n");
for row in self.bom_rows()? {
out.push_str(&format!(
"{},{},{}\n",
csv_field(&row.part_name),
csv_field(&row.source_key),
row.quantity
));
}
Ok(out)
}
/// Export the assembly BOM as a JSON array of the same records — the CSV
/// sibling of [`Self::export_bom_csv`].
pub fn export_bom_json(&mut self) -> Result<String, String> {
serde_json::to_string(&self.bom_rows()?)
.map_err(|error| format!("BOM serialize: {error}"))
}
// ======================================================================
// BOM ATTRIBUTES — the editable columns behind the BOM panel
//
// Two stores, because the data has two lifetimes:
//
// * PART attributes (Part Number, Material, Mass…) describe the PART, so
// they live on the part's OWN document, under the top-level
// [`PART_ATTRIBUTES`] key: `partsLibrary[part].document.partAttributes`.
// Being on the part document means they travel WITH the part — the
// write-through lane saves that same document back to its `sourceKey`,
// so opening the part standalone shows the same Part Number. `History`
// keeps unknown top-level document keys verbatim (`from_request_json`
// parses into a `Value` and only lifts out the keys it owns), so the key
// round-trips through save/open with no format work.
//
// * OCCURRENCE attributes (Item Number, Reference Designator, Find
// Number…) describe ONE PLACEMENT, so they live on the placing ACOMP
// feature, under [`OCCURRENCE_ATTRIBUTES`] —
// `feature.inputParams.bom`. NESTED rather than flat so a user-added
// custom column can never collide with a schema param (`isFixed`,
// `partName`, `transform`); the ACOMP builder reads its four keys by
// name and ignores the rest, and the solver write-back fold
// (`assembly_apply_document_json`) INSERTS `transform`/`isFixed` into the
// existing params object rather than rebuilding it, so a solve never
// strips this.
//
// Quantity is deliberately absent from both: it is DERIVED (how many
// occurrences a packed row rolls up), never stored, so it can never
// disagree with the model.
// ======================================================================
/// Read a part's attribute record (`{}` when the part has none / is
/// unknown). Never errs — a BOM row for a part mid-import simply shows
/// blanks.
pub fn part_attributes(&self, part_name: &str) -> Value {
self.history
.parts_library()
.get(part_name)
.and_then(|entry| entry.get("document"))
.and_then(|document| document.get(PART_ATTRIBUTES))
.filter(|value| value.is_object())
.cloned()
.unwrap_or_else(|| Value::Object(serde_json::Map::new()))
}
/// A part's `(sourceKey, sourceSignature)` — what the app's write-through
/// lane needs to decide whether the file on disk is still the one this
/// entry was built from. `None` for an unknown part; the key is returned
/// even when EMPTY (embedded-only), because "" is exactly what the
/// write-through lane checks for.
pub fn part_source(&self, part_name: &str) -> Option<(String, String)> {
let entry = self.history.parts_library().get(part_name)?;
Some((
entry
.get("sourceKey")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
entry
.get("sourceSignature")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
))
}
/// A part's embedded document as text — the payload the app writes through
/// to the part's `sourceKey` after an attribute edit.
pub fn part_document_json(&self, part_name: &str) -> Option<String> {
self.history
.parts_library()
.get(part_name)
.and_then(|entry| entry.get("document"))
.map(|document| document.to_string())
}
/// Write ONE part attribute. `Value::Null` (or an empty string) REMOVES the
/// key, so clearing a cell leaves no `""` litter in the saved document.
///
/// # Why this is not just a document edit
///
/// The document's `partsLibrary` block is a MIRROR of the kernel's
/// main-side store, not the truth: `sync_assembly` re-serializes the store
/// over the block after every run, and the per-run request does not carry
/// the block at all ([`History::prefix_request`] omits it). So a change
/// written only into the block is erased by the next sync. This therefore
/// writes BOTH: the kernel store (via `refresh_library_entry`, which is the
/// same door edit-in-place and update-components use) and the document
/// block + undo checkpoint. [`Self::undo`] re-installs the rewound block
/// into the store, which is what makes the pair rewind together.
///
/// The `snapshot` is deliberately KEPT: an attribute is not geometry, so
/// there is nothing to re-evaluate. `refresh_library_entry` still marks the
/// entry dirty (its contract), so the ACOMP self-heal re-derives it on the
/// next run — correct, just not free. That is the price of the attributes
/// living on the part document, and it is why the panel commits a text cell
/// on focus-loss rather than per keystroke.
pub fn set_part_attribute(
&mut self,
part_name: &str,
key: &str,
value: Value,
) -> Result<(), String> {
if key.is_empty() {
return Err("part attribute: empty key".to_string());
}
let mut block = self.history.parts_library().clone();
let entry = block
.get_mut(part_name)
.ok_or_else(|| format!("no parts-library entry '{part_name}'"))?;
let document = entry
.get_mut("document")
.filter(|value| value.is_object())
.ok_or_else(|| format!("part '{part_name}': malformed document"))?;
write_attribute(document, PART_ATTRIBUTES, key, value)?;
let document_text = document.to_string();
let signature = super::document_signature(&document_text);
entry["sourceSignature"] = Value::String(signature.clone());
// The kernel store is the block's authority — write it there too, or
// the next `sync_assembly` mirrors the OLD entry back over this edit.
brep_kernel::refresh_library_entry(part_name, &signature, &document_text)
.map_err(|error| format!("part '{part_name}': {error:?}"))?;
self.history
.set_parts_library_edited(block, Some(&format!("partattr:{part_name}:{key}")));
self.rerun_history();
Ok(())
}
/// Read ONE occurrence's attribute record (`{}` when it has none).
pub fn occurrence_attributes(&self, component_id: &str) -> Value {
self.history
.index_of(component_id)
.and_then(|index| self.history.feature_params(index))
.and_then(|params| params.get(OCCURRENCE_ATTRIBUTES).cloned())
.filter(Value::is_object)
.unwrap_or_else(|| Value::Object(serde_json::Map::new()))
}
/// Write ONE occurrence attribute across `component_ids` — ONE undo step
/// however many ids there are.
///
/// The fan-out lane: a PACKED BOM row rolls up every occurrence of a part
/// whose occurrence data matches, and editing that row's cell must apply to
/// all of them. One id (the unpacked case) is the same call with a
/// one-element slice, so there is no second code path to keep in step.
/// `Value::Null` / `""` removes the key.
pub fn set_occurrence_attribute(
&mut self,
component_ids: &[String],
key: &str,
value: Value,
) -> Result<(), String> {
if key.is_empty() {
return Err("occurrence attribute: empty key".to_string());
}
let mut edits: Vec<(String, Value)> = Vec::with_capacity(component_ids.len());
for id in component_ids {
let index = self
.history
.index_of(id)
.ok_or_else(|| format!("no component feature '{id}'"))?;
let mut params = self
.history
.feature_params(index)
.unwrap_or_else(|| Value::Object(serde_json::Map::new()));
if !params.is_object() {
return Err(format!("component '{id}': malformed inputParams"));
}
write_attribute(&mut params, OCCURRENCE_ATTRIBUTES, key, value.clone())?;
edits.push((id.clone(), params));
}
self.update_many_feature_params(&edits)?;
Ok(())
}
}
/// The part document's attribute-record key (see the module's BOM-attributes
/// block). A top-level document key, so it rides save/open untouched.
pub const PART_ATTRIBUTES: &str = "partAttributes";
/// The ACOMP `inputParams` attribute-record key.
pub const OCCURRENCE_ATTRIBUTES: &str = "bom";
/// Set (or, for a null/empty value, REMOVE) `record[key]` inside `owner`'s
/// attribute record, creating the record on first write and dropping it again
/// when the last attribute goes — so a document that was never annotated
/// serializes exactly as it did before (the `metadata` field's convention).
fn write_attribute(
owner: &mut Value,
record_key: &str,
key: &str,
value: Value,
) -> Result<(), String> {
let object = owner
.as_object_mut()
.ok_or_else(|| "attribute owner is not an object".to_string())?;
let clearing = matches!(&value, Value::Null)
|| matches!(&value, Value::String(text) if text.is_empty());
if clearing {
let mut empty = false;
if let Some(record) = object.get_mut(record_key).and_then(Value::as_object_mut) {
record.remove(key);
empty = record.is_empty();
}
if empty {
object.remove(record_key);
}
return Ok(());
}
let record = object
.entry(record_key.to_string())
.or_insert_with(|| Value::Object(serde_json::Map::new()));
if !record.is_object() {
*record = Value::Object(serde_json::Map::new());
}
record
.as_object_mut()
.expect("just normalized to an object")
.insert(key.to_string(), value);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn fresh_state() -> EngineState {
brep_kernel::clear_history_cache();
EngineState::new()
}
/// A one-cube part document with a distinguishing `size` (distinct content
/// per part so nothing dedups across entries).
fn part_document(size: f64) -> String {
component_fixtures::cube_part_document(size).to_string()
}
/// RIGID NESTING: an inserted ASSEMBLY (the embedded document is itself a
/// two-instance assembly over its own partsLibrary) is ONE row at this
/// level — its internal parts never leak into the parent's BOM.
#[test]
fn a_sub_assembly_is_one_row_at_this_level() {
let mut state = fresh_state();
let sub_assembly = component_fixtures::two_instance_assembly_json();
state
.insert_component(ComponentInsert::New {
name: "sub-asm",
source_key: "sub-asm",
source_signature: "sig-sub",
document_json: &sub_assembly,
})
.expect("sub-assembly inserts");
// The nested instance is fully resident (both internal cubes came
// along as members of the ONE parent record)…
let components = state.assembly_components();
assert_eq!(components.len(), 1, "one parent-level instance");
assert_eq!(components[0].solids.len(), 2, "…carrying two member solids");
// …yet the BOM stays one row.
assert_eq!(
state.export_bom_csv().unwrap(),
"partName,sourceKey,quantity\nsub-asm,sub-asm,1\n"
);
}
/// The lane's core fixture: two instances of one part + one of another →
/// rows (partA,2), (partB,1) — asserted as the EXACT CSV text (incl. the
/// header) and the EXACT JSON array.
#[test]
fn two_of_one_part_one_of_another_exact_csv_and_json() {
let mut state = fresh_state();
state
.insert_component(ComponentInsert::New {
name: "partA",
source_key: "partA-src",
source_signature: "sig-a",
document_json: &part_document(2.0),
})
.unwrap();
state
.insert_component(ComponentInsert::Existing { part_name: "partA" })
.unwrap();
state
.insert_component(ComponentInsert::New {
name: "partB",
source_key: "partB-src",
source_signature: "sig-b",
document_json: &part_document(3.0),
})
.unwrap();
assert_eq!(
state.export_bom_csv().unwrap(),
"partName,sourceKey,quantity\npartA,partA-src,2\npartB,partB-src,1\n"
);
assert_eq!(
state.export_bom_json().unwrap(),
r#"[{"partName":"partA","sourceKey":"partA-src","quantity":2},{"partName":"partB","sourceKey":"partB-src","quantity":1}]"#
);
}
/// A componentless document refuses both formats with the exact guard the
/// file dialog surfaces as status + toast.
#[test]
fn componentless_document_refuses_bom_export() {
let mut state = fresh_state();
assert_eq!(
state.export_bom_csv().unwrap_err(),
"no components in the assembly"
);
assert_eq!(
state.export_bom_json().unwrap_err(),
"no components in the assembly"
);
}
/// The minimal RFC-4180 quoting: plain fields pass through untouched;
/// commas/quotes trigger quoting with doubled quotes.
#[test]
fn csv_fields_quote_only_when_needed() {
assert_eq!(csv_field("plain-name"), "plain-name");
assert_eq!(csv_field("a,b"), "\"a,b\"");
assert_eq!(csv_field("say \"hi\""), "\"say \"\"hi\"\"\"");
}
// --- BOM attributes ---------------------------------------------------
/// Two instances of one part + one of another — the fixture every
/// attribute test edits (ACOMP1/ACOMP2 are `partA`, ACOMP3 is `partB`).
fn two_part_assembly() -> EngineState {
let mut state = fresh_state();
state
.insert_component(ComponentInsert::New {
name: "partA",
source_key: "partA-src",
source_signature: "sig-a",
document_json: &part_document(2.0),
})
.unwrap();
state
.insert_component(ComponentInsert::Existing { part_name: "partA" })
.unwrap();
state
.insert_component(ComponentInsert::New {
name: "partB",
source_key: "partB-src",
source_signature: "sig-b",
document_json: &part_document(3.0),
})
.unwrap();
state
}
/// A PART attribute lands on the part's own document (so it travels with
/// the part, not the assembly), is read back through the accessor, rides
/// the saved document, and rewinds in ONE undo — which only works because
/// undo re-installs the rewound library block into the kernel store.
#[test]
fn part_attribute_writes_the_part_document_and_undoes_in_one_step() {
let mut state = two_part_assembly();
assert_eq!(
state.part_attributes("partA"),
serde_json::json!({}),
"no attributes until one is written"
);
state
.set_part_attribute("partA", "Part_Number", Value::String("PN-1000".into()))
.expect("attribute writes");
assert_eq!(state.part_attributes("partA")["Part_Number"], "PN-1000");
// It is on the PART's document — the place that travels with the part
// through write-through — not on the assembly or the library entry.
let saved: Value = serde_json::from_str(&state.history_request_json()).unwrap();
assert_eq!(
saved["partsLibrary"]["partA"]["document"][PART_ATTRIBUTES]["Part_Number"],
"PN-1000"
);
assert!(
saved.get(PART_ATTRIBUTES).is_none(),
"the ASSEMBLY document must not carry the part's attributes"
);
// The sibling part is untouched.
assert_eq!(state.part_attributes("partB"), serde_json::json!({}));
// ONE undo takes it back — and it STAYS back after the re-run's
// `sync_assembly` re-mirrors the library block from the kernel store.
state.undo();
state.ensure_assembly_synced();
assert_eq!(
state.part_attributes("partA"),
serde_json::json!({}),
"one undo, and the re-mirror does not resurrect the edit"
);
state.redo();
state.ensure_assembly_synced();
assert_eq!(state.part_attributes("partA")["Part_Number"], "PN-1000");
}
/// The PACKED fan-out: one edit across the two occurrences of `partA` is
/// ONE undo step, not two — the whole reason
/// [`EngineState::update_many_feature_params`] exists.
#[test]
fn packed_occurrence_edit_fans_out_and_undoes_in_one_step() {
let mut state = two_part_assembly();
let packed = vec!["ACOMP1".to_string(), "ACOMP2".to_string()];
state
.set_occurrence_attribute(&packed, "Find_Number", Value::String("7".into()))
.expect("fan-out writes");
assert_eq!(state.occurrence_attributes("ACOMP1")["Find_Number"], "7");
assert_eq!(state.occurrence_attributes("ACOMP2")["Find_Number"], "7");
assert_eq!(
state.occurrence_attributes("ACOMP3"),
serde_json::json!({}),
"the other part's occurrence is untouched"
);
// ONE undo, both gone. (A `update_feature_params` loop would need two:
// its coalesce key is per feature INDEX, so the two edits never merge.)
state.undo();
assert_eq!(state.occurrence_attributes("ACOMP1"), serde_json::json!({}));
assert_eq!(state.occurrence_attributes("ACOMP2"), serde_json::json!({}));
}
/// Occurrence attributes ride the ACOMP's `inputParams` under a NESTED
/// key, so they survive the post-run solver write-back fold (which inserts
/// `transform`/`isFixed` into the existing params object) and cannot
/// collide with a schema param. Quantity is never stored.
#[test]
fn occurrence_attributes_are_nested_and_survive_the_solve_fold() {
let mut state = two_part_assembly();
state
.set_occurrence_attribute(
&["ACOMP3".to_string()],
"Reference_Designator",
Value::String("R7".into()),
)
.unwrap();
// Nested under the record key, alongside — never replacing — the
// schema params.
let index = state.history.index_of("ACOMP3").unwrap();
let params = state.history.feature_params(index).unwrap();
assert_eq!(params[OCCURRENCE_ATTRIBUTES]["Reference_Designator"], "R7");
assert_eq!(params["partName"], "partB", "schema params intact");
assert!(params.get("isFixed").is_some(), "schema params intact");
assert!(
params.get("quantity").is_none() && params[OCCURRENCE_ATTRIBUTES].get("Quantity").is_none(),
"quantity is DERIVED from the occurrence count, never stored"
);
// A re-run + assembly sync folds solved poses back onto the feature;
// the fold inserts keys rather than rebuilding the params object, so
// the record is still there.
state.ensure_assembly_synced();
assert_eq!(
state.occurrence_attributes("ACOMP3")["Reference_Designator"],
"R7"
);
}
/// Clearing a cell REMOVES the key (and the record with the last key), so
/// a document that was never annotated — or was annotated and cleared —
/// serializes without the record rather than carrying `""` litter.
#[test]
fn clearing_an_attribute_removes_the_key_and_the_empty_record() {
let mut state = two_part_assembly();
let one = vec!["ACOMP1".to_string()];
state
.set_occurrence_attribute(&one, "Notes", Value::String("check fit".into()))
.unwrap();
state
.set_occurrence_attribute(&one, "Find_Number", Value::String("3".into()))
.unwrap();
state
.set_occurrence_attribute(&one, "Notes", Value::String(String::new()))
.unwrap();
let attributes = state.occurrence_attributes("ACOMP1");
assert!(attributes.get("Notes").is_none(), "cleared key is gone");
assert_eq!(attributes["Find_Number"], "3", "siblings survive");
state
.set_occurrence_attribute(&one, "Find_Number", Value::Null)
.unwrap();
let index = state.history.index_of("ACOMP1").unwrap();
let params = state.history.feature_params(index).unwrap();
assert!(
params.get(OCCURRENCE_ATTRIBUTES).is_none(),
"the last attribute takes the empty record with it"
);
}
/// Non-string values keep their JSON type — a numeric column stores a
/// number, so sorting and export never have to re-parse text.
#[test]
fn numeric_attributes_keep_their_json_type() {
let mut state = two_part_assembly();
state
.set_part_attribute("partA", "Mass", serde_json::json!(12.5))
.unwrap();
assert_eq!(state.part_attributes("partA")["Mass"], 12.5);
assert!(state.part_attributes("partA")["Mass"].is_number());
}
/// The write-through inputs: a part's `(sourceKey, sourceSignature)` and
/// its document text, with the signature re-stamped over the EDITED
/// document so the app writes and hashes the same bytes.
#[test]
fn part_source_and_document_track_the_attribute_edit() {
let mut state = two_part_assembly();
state
.set_part_attribute("partA", "Material", Value::String("6061-T6".into()))
.unwrap();
let (key, signature) = state.part_source("partA").expect("partA has a source");
assert_eq!(key, "partA-src");
let document = state.part_document_json("partA").expect("document text");
assert!(document.contains("6061-T6"), "the edit is in the text");
assert_eq!(
signature,
super::super::document_signature(&document),
"the stamped signature hashes the very text the app writes through"
);
assert!(state.part_source("nope").is_none());
}
/// Unknown ids are refused BEFORE anything is written — a fan-out can
/// never half-apply.
#[test]
fn a_fan_out_over_an_unknown_id_writes_nothing() {
let mut state = two_part_assembly();
let ids = vec!["ACOMP1".to_string(), "NOPE".to_string()];
assert_eq!(
state
.set_occurrence_attribute(&ids, "Notes", Value::String("x".into()))
.unwrap_err(),
"no component feature 'NOPE'"
);
assert_eq!(
state.occurrence_attributes("ACOMP1"),
serde_json::json!({}),
"the good id was not written either"
);
assert!(!state.can_undo() || {
// Nothing was checkpointed for the refused batch: undoing here
// rewinds the INSERT, not a phantom attribute edit.
state.undo();
state.assembly_components().len() < 3
});
}
}