1use crate::fields::StepField;
9use crate::model::{Add, Arrow, Callout, Instructions, Signoff, Step, Torque, ToolUse};
10use crate::wizard::{Component, Level};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::collections::HashSet;
14
15pub fn merge(block: &mut Instructions, step_ids: &[&str]) -> Result<String, String> {
20 if step_ids.len() < 2 {
21 return Err("pick two or more steps to merge".into());
22 }
23 let mut located = Vec::new();
24 for id in step_ids {
25 let parent = block.parent_id(id).ok_or_else(|| format!("no step '{id}'"))?.map(str::to_string);
26 let (_, index) = block.siblings(id).ok_or_else(|| format!("no step '{id}'"))?;
27 if located.contains(&(parent.clone(), index)) {
28 return Err(format!("step '{id}' is named twice"));
29 }
30 located.push((parent, index));
31 }
32 if located.iter().any(|(parent, _)| *parent != located[0].0) {
33 return Err("only sibling steps can be merged (steps under the same parent): these are not siblings".into());
34 }
35 let mut indices: Vec<usize> = located.iter().map(|(_, i)| *i).collect();
36 indices.sort_unstable();
37 let (steps, _) = block.siblings_mut(step_ids[0]).ok_or_else(|| format!("no step '{}'", step_ids[0]))?;
38 let mut absorbed: Vec<Step> = Vec::new();
39 for &i in indices[1..].iter().rev() {
40 absorbed.push(steps.remove(i));
41 }
42 absorbed.reverse();
43 let keeper = &mut steps[indices[0]];
44 for step in absorbed {
45 keeper.adds.extend(step.adds);
46 for tool in step.tools {
47 if !keeper.tools.contains(&tool) {
48 keeper.tools.push(tool);
49 }
50 }
51 keeper.callouts.extend(step.callouts);
52 keeper.arrows.extend(step.arrows);
53 if !step.notes.is_empty() {
54 if !keeper.notes.is_empty() {
55 keeper.notes.push('\n');
56 }
57 keeper.notes.push_str(&step.notes);
58 }
59 if keeper.torque.is_none() {
60 keeper.torque = step.torque;
61 }
62 if keeper.view.is_none() {
63 keeper.view = step.view;
64 }
65 if keeper.motion.is_none() {
66 keeper.motion = step.motion;
67 }
68 keeper.signoff.required |= step.signoff.required;
69 keeper.fields.extend(step.fields);
70 keeper.steps.extend(step.steps);
71 }
72 keeper.coalesce_adds();
73 Ok(keeper.id.clone())
74}
75
76pub fn split(block: &mut Instructions, step_id: &str, add_indices: &[usize]) -> Result<String, String> {
80 let count = block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?.adds.len();
81 let picked: HashSet<usize> = add_indices.iter().copied().collect();
82 if picked.is_empty() {
83 return Err("pick the parts to split into a new step".into());
84 }
85 if let Some(bad) = picked.iter().find(|&&i| i >= count) {
86 return Err(format!("step '{step_id}' has no part {bad}"));
87 }
88 if picked.len() == count {
89 return Err("a split must leave at least one part in the step".into());
90 }
91 let id = block.next_id("MS");
92 let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
93 let step = &mut steps[s];
94 let (moved, kept): (Vec<_>, Vec<_>) =
95 std::mem::take(&mut step.adds).into_iter().enumerate().partition(|(i, _)| picked.contains(i));
96 step.adds = kept.into_iter().map(|(_, a)| a).collect();
97 let moved: Vec<_> = moved.into_iter().map(|(_, a)| a).collect();
98 let moved_occurrences: HashSet<&str> = moved.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)).collect();
99 let (arrows, kept_arrows): (Vec<Arrow>, Vec<Arrow>) =
100 std::mem::take(&mut step.arrows).into_iter().partition(|a| moved_occurrences.contains(a.occurrence.as_str()));
101 step.arrows = kept_arrows;
102 let (callouts, kept_callouts): (Vec<Callout>, Vec<Callout>) = std::mem::take(&mut step.callouts)
103 .into_iter()
104 .partition(|k| k.occurrence.as_deref().is_some_and(|o| moved_occurrences.contains(o)));
105 step.callouts = kept_callouts;
106 let torque = if moved.iter().any(|a| a.fastener) { step.torque.clone() } else { None };
107 if torque.is_some() && !step.adds.iter().any(|a| a.fastener) {
108 step.torque = None;
109 }
110 let title = match moved.as_slice() {
111 [one] if one.quantity() == 1 => format!("Install {}", one.part),
112 [one] => format!("Install {} × {}", one.quantity(), one.part),
113 _ => format!("{} (continued)", step.title),
114 };
115 let tools = step.tools.clone();
116 let new = Step { id: id.clone(), title, adds: moved, tools, torque, callouts, arrows, ..Step::default() };
117 steps.insert(s + 1, new);
118 Ok(id)
119}
120
121pub fn move_step(block: &mut Instructions, step_id: &str, index: usize) -> Result<(), String> {
123 let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
124 let step = steps.remove(s);
125 let index = index.min(steps.len());
126 steps.insert(index, step);
127 Ok(())
128}
129
130pub fn nest_step(block: &mut Instructions, step_id: &str, parent: Option<&str>, index: usize) -> Result<(), String> {
134 let step = block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
135 if let Some(parent) = parent {
136 if step.contains(parent) {
137 return Err(format!("step '{step_id}' cannot be nested inside itself"));
138 }
139 block.step(parent).ok_or_else(|| format!("no step '{parent}'"))?;
140 }
141 let (siblings, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
142 let step = siblings.remove(s);
143 let list = match parent {
144 None => &mut block.steps,
145 Some(parent) => &mut block.step_mut(parent).ok_or_else(|| format!("no step '{parent}'"))?.steps,
146 };
147 let index = index.min(list.len());
148 list.insert(index, step);
149 Ok(())
150}
151
152pub fn move_add(block: &mut Instructions, from: &str, add_index: usize, to: &str) -> Result<(), String> {
155 let from_parent = block.parent_id(from).ok_or_else(|| format!("no step '{from}'"))?.map(str::to_string);
156 let to_parent = block.parent_id(to).ok_or_else(|| format!("no step '{to}'"))?.map(str::to_string);
157 if from_parent != to_parent {
158 return Err("a part can only move to a sibling step (one under the same parent)".into());
159 }
160 if from == to {
161 return Ok(());
162 }
163 let source = block.step_mut(from).ok_or_else(|| format!("no step '{from}'"))?;
164 if add_index >= source.adds.len() {
165 return Err(format!("step '{from}' has no part {add_index}"));
166 }
167 let add = source.adds.remove(add_index);
168 let occurrences: HashSet<String> = add.occurrences.iter().cloned().collect();
169 let (arrows, kept): (Vec<Arrow>, Vec<Arrow>) =
170 std::mem::take(&mut source.arrows).into_iter().partition(|a| occurrences.contains(&a.occurrence));
171 source.arrows = kept;
172 let target = block.step_mut(to).ok_or_else(|| format!("no step '{to}'"))?;
173 target.adds.push(add);
174 target.coalesce_adds();
175 target.arrows.extend(arrows);
176 Ok(())
177}
178
179pub fn insert_step(block: &mut Instructions, after: Option<&str>) -> Result<String, String> {
182 if let Some(step_id) = after {
183 block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
184 }
185 let id = block.next_id("MS");
186 let step = Step::new(id.clone(), "New step".into());
187 match after {
188 Some(step_id) => {
189 let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
190 steps.insert(s + 1, step);
191 }
192 None => block.steps.push(step),
193 }
194 Ok(id)
195}
196
197#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct AddReport {
203 pub added: usize,
204 #[serde(default)]
205 pub left: Vec<LeftOccurrence>,
206}
207
208#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct LeftOccurrence {
212 pub occurrence: String,
213 pub step: String,
216}
217
218fn holder<'a>(block: &'a Instructions, occurrence: &str) -> Option<(&'a Step, bool)> {
221 let mut best: Option<(&Step, usize)> = None;
222 for (_, step) in block.steps() {
223 for added in step.adds.iter().flat_map(|a| a.occurrences.iter()) {
224 if added == occurrence {
225 return Some((step, true));
226 }
227 if occurrence.starts_with(added.as_str()) && occurrence[added.len()..].starts_with(':') && best.is_none_or(|(_, len)| added.len() > len) {
228 best = Some((step, added.len()));
229 }
230 }
231 }
232 best.map(|(step, _)| (step, false))
233}
234
235pub fn add_parts(block: &mut Instructions, step_id: &str, components: &[&Component]) -> Result<AddReport, String> {
244 block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
245 let mut report = AddReport::default();
246 let mut adds: Vec<Add> = Vec::new();
247 let mut torque = None;
248 for component in components {
249 match holder(block, &component.path) {
250 Some((step, true)) => report.left.push(LeftOccurrence { occurrence: component.path.clone(), step: step.id.clone() }),
251 Some((step, false)) if step.id == step_id || !step.contains(step_id) => {
252 report.left.push(LeftOccurrence { occurrence: component.path.clone(), step: step.id.clone() })
253 }
254 _ => {
255 if adds.iter().any(|a| a.occurrences.contains(&component.path)) {
256 continue;
257 }
258 adds.push(Add {
259 find_number: component.find_number.clone(),
260 subassembly: component.children.is_some(),
261 fastener: component.fastener,
262 serial_tracked: component.serial_tracked,
263 ..Add::named(vec![component.path.clone()], component.part_key(), &component.part)
264 });
265 if component.fastener && torque.is_none() {
266 torque = component.torque.as_deref().and_then(Torque::from_attribute);
267 }
268 report.added += 1;
269 }
270 }
271 }
272 let step = block.step_mut(step_id).expect("checked above");
273 step.adds.extend(adds);
274 if step.torque.is_none() {
275 step.torque = torque;
276 }
277 step.coalesce_adds();
278 Ok(report)
279}
280
281pub fn remove_add(block: &mut Instructions, step_id: &str, add_index: usize) -> Result<Add, String> {
285 let step = block.step_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
286 if add_index >= step.adds.len() {
287 return Err(format!("step '{step_id}' has no part {add_index}"));
288 }
289 let add = step.adds.remove(add_index);
290 let gone: HashSet<&str> = add.occurrences.iter().map(String::as_str).collect();
291 step.arrows.retain(|a| !gone.contains(a.occurrence.as_str()));
292 step.callouts.retain(|c| !c.occurrence.as_deref().is_some_and(|o| gone.contains(o)));
293 if !step.adds.iter().any(|a| a.fastener) && step.torque.as_ref().is_some_and(|t| t.source == crate::model::TorqueSource::Part) {
294 step.torque = None;
295 }
296 Ok(add)
297}
298
299pub fn unplanned<'a>(block: &Instructions, level: &'a Level) -> Vec<&'a Component> {
306 fn walk<'a>(block: &Instructions, level: &'a Level, out: &mut Vec<&'a Component>) {
307 for component in &level.components {
308 match holder(block, &component.path) {
309 None => out.push(component),
310 Some((placing, false)) => {
311 if !placing.steps.is_empty() {
312 out.push(component);
313 }
314 }
315 Some((_, true)) => {
316 if let Some(children) = &component.children {
317 walk(block, children, out);
318 }
319 }
320 }
321 }
322 }
323 let mut out = Vec::new();
324 walk(block, level, &mut out);
325 out
326}
327
328pub fn empty_steps(block: &Instructions) -> Vec<String> {
332 block.steps().filter(|(_, s)| s.adds.is_empty() && s.steps.is_empty() && s.fields.is_empty()).map(|(_, s)| s.id.clone()).collect()
333}
334
335pub fn delete_step(block: &mut Instructions, step_id: &str) -> Result<(), String> {
338 let step = block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
339 if !step.adds.is_empty() {
340 return Err("move this step's parts to another step before deleting it".into());
341 }
342 if !step.steps.is_empty() {
343 return Err("move or delete the steps under this step before deleting it".into());
344 }
345 let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
346 steps.remove(s);
347 Ok(())
348}
349
350pub fn update_step(block: &mut Instructions, step_id: &str, patch: &Value) -> Result<(), String> {
356 let object = patch.as_object().ok_or("a step update is a JSON object")?;
357 let mut ids_needed = 0;
358 if let Some(Value::Array(callouts)) = object.get("callouts") {
359 ids_needed = callouts.iter().filter(|c| c.get("id").and_then(Value::as_str).is_none_or(str::is_empty)).count();
360 }
361 let mut fresh: Vec<String> = (0..ids_needed).map(|_| block.next_id("MK")).collect();
362 let fields_needed = match object.get("fields") {
363 Some(Value::Array(fields)) => fields.iter().filter(|f| f.get("id").and_then(Value::as_str).is_none_or(str::is_empty)).count(),
364 _ => 0,
365 };
366 let mut fresh_fields: Vec<String> = (0..fields_needed).map(|_| block.next_id("MF")).collect();
367 let step = block.step_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
368 let mut next = step.clone();
369 for (key, value) in object {
370 let parse = |what: &str| format!("step {key}: not a valid {what}");
371 match key.as_str() {
372 "title" => next.title = value.as_str().ok_or_else(|| parse("text"))?.to_string(),
373 "notes" => next.notes = value.as_str().ok_or_else(|| parse("text"))?.to_string(),
374 "view" => next.view = value.as_str().filter(|v| !v.is_empty()).map(str::to_string),
375 "tools" => next.tools = serde_json::from_value::<Vec<ToolUse>>(value.clone()).map_err(|_| parse("tools list"))?,
376 "torque" => {
377 next.torque = if value.is_null() {
378 None
379 } else {
380 let mut torque: Torque = serde_json::from_value(with_source(value)).map_err(|_| parse("torque"))?;
381 torque.source = crate::model::TorqueSource::Override;
382 Some(torque)
383 }
384 }
385 "callouts" => {
386 let mut list = Vec::new();
387 for item in value.as_array().ok_or_else(|| parse("callouts list"))? {
388 let mut item = item.clone();
389 if item.get("id").and_then(Value::as_str).is_none_or(str::is_empty) {
390 item["id"] = Value::String(fresh.remove(0));
391 }
392 list.push(serde_json::from_value::<Callout>(item).map_err(|_| parse("callout"))?);
393 }
394 next.callouts = list;
395 }
396 "arrows" => next.arrows = serde_json::from_value::<Vec<Arrow>>(value.clone()).map_err(|_| parse("arrows list"))?,
397 "signoff" => next.signoff = serde_json::from_value::<Signoff>(value.clone()).map_err(|_| parse("signoff"))?,
398 "motion" => next.motion = (!value.is_null()).then(|| value.clone()),
399 "fields" => {
400 let mut list = Vec::new();
401 for item in value.as_array().ok_or_else(|| parse("fields list"))? {
402 let mut field = StepField::from_json(item).map_err(|e| format!("step {key}: {e}"))?;
403 if field.id.is_empty() {
404 field.id = fresh_fields.remove(0);
405 }
406 list.push(field);
407 }
408 next.fields = list;
409 }
410 other => return Err(format!("a step has no field '{other}'")),
411 }
412 }
413 *step = next;
414 Ok(())
415}
416
417pub fn add_field(block: &mut Instructions, step_id: &str, field: &Value, index: Option<usize>) -> Result<String, String> {
422 block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
423 let mut field = StepField::from_json(field)?;
424 let id = block.next_id("MF");
425 field.id = id.clone();
426 let step = block.step_mut(step_id).expect("checked above");
427 let index = index.unwrap_or(usize::MAX).min(step.fields.len());
428 step.fields.insert(index, field);
429 Ok(id)
430}
431
432fn field_index(step: &Step, field_id: &str) -> Result<usize, String> {
433 step.fields.iter().position(|f| f.id == field_id).ok_or_else(|| format!("step '{}' has no field '{field_id}'", step.id))
434}
435
436pub fn update_field(block: &mut Instructions, step_id: &str, field_id: &str, patch: &Value) -> Result<(), String> {
438 let step = block.step_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
439 let index = field_index(step, field_id)?;
440 step.fields[index] = step.fields[index].patched(patch)?;
441 Ok(())
442}
443
444pub fn remove_field(block: &mut Instructions, step_id: &str, field_id: &str) -> Result<StepField, String> {
446 let step = block.step_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
447 let index = field_index(step, field_id)?;
448 Ok(step.fields.remove(index))
449}
450
451pub fn move_field(block: &mut Instructions, step_id: &str, field_id: &str, index: usize) -> Result<(), String> {
453 let step = block.step_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
454 let at = field_index(step, field_id)?;
455 let field = step.fields.remove(at);
456 let index = index.min(step.fields.len());
457 step.fields.insert(index, field);
458 Ok(())
459}
460
461fn with_source(value: &Value) -> Value {
462 let mut value = value.clone();
463 if let Some(object) = value.as_object_mut() {
464 object.entry("source").or_insert(Value::String("override".into()));
465 }
466 value
467}
468
469#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
472#[serde(rename_all = "camelCase")]
473pub struct Presentation {
474 pub placed: Vec<String>,
475 pub adding: Vec<String>,
476 pub hidden: Vec<String>,
477}
478
479pub fn presentation(block: &Instructions, step_id: &str, occurrences: &[String]) -> Result<Presentation, String> {
486 let (siblings, s) = block.siblings(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
487 let mut earlier_list = Vec::new();
488 for sibling in &siblings[..s] {
489 sibling.occurrences_with_descendants(&mut earlier_list);
490 }
491 let earlier: HashSet<&str> = earlier_list.into_iter().collect();
492 let mut now_list = Vec::new();
493 siblings[s].occurrences_with_descendants(&mut now_list);
494 let now: HashSet<&str> = now_list.into_iter().collect();
495 let mut out = Presentation::default();
496 for path in occurrences {
497 let covered = |set: &HashSet<&str>| {
498 set.contains(path.as_str()) || set.iter().any(|p| path.starts_with(p) && path[p.len()..].starts_with(':'))
499 };
500 if covered(&now) {
501 out.adding.push(path.clone());
502 } else if covered(&earlier) {
503 out.placed.push(path.clone());
504 } else {
505 out.hidden.push(path.clone());
506 }
507 }
508 Ok(out)
509}
510