1use std::fs;
5use std::path::{Path, PathBuf};
6
7use jiff::Timestamp;
8use jiff::tz::TimeZone;
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11use vpf::{Plan, Step};
12
13use crate::journal::Entry;
14use crate::person::Ask;
15
16#[derive(Clone, Debug, PartialEq, Eq)]
18pub enum Outcome {
19 Done,
21 Stopped(String),
23 Waiting(Vec<Waiting>),
25}
26
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Waiting {
30 pub step: String,
32 pub key: String,
34 pub wait: Wait,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum Wait {
42 Answer(Ask),
44 Approval(Ask),
46 Decision(String),
48 Choice {
50 question: String,
52 options: Vec<String>,
54 },
55 Time(Timestamp),
57}
58
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum Reply {
63 Text(String),
65 Yes,
67 No {
69 points: String,
71 back: Vec<String>,
73 },
74 Option(usize),
76}
77
78#[derive(Clone, Debug, PartialEq)]
80pub struct Version {
81 pub plan: Plan,
83 pub approved_by: Option<String>,
85 pub from: Option<String>,
87 pub at: Timestamp,
89}
90
91#[derive(Clone, Debug, Deserialize)]
93pub struct ProofRecord {
94 pub by: String,
96 pub asked: String,
98 #[serde(default)]
100 pub passed: bool,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub points: Option<String>,
104 #[serde(default)]
106 pub skipped: bool,
107 #[serde(default)]
109 pub reason: Option<String>,
110}
111
112impl Serialize for ProofRecord {
113 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
114 use serde::ser::SerializeMap;
115 let mut map = serializer.serialize_map(None)?;
116 map.serialize_entry("by", &self.by)?;
117 map.serialize_entry("asked", &self.asked)?;
118 if self.skipped {
119 map.serialize_entry("skipped", &true)?;
120 } else {
121 map.serialize_entry("passed", &self.passed)?;
122 }
123 if let Some(points) = &self.points {
124 map.serialize_entry("points", points)?;
125 }
126 if let Some(reason) = &self.reason {
127 map.serialize_entry("reason", reason)?;
128 }
129 map.end()
130 }
131}
132
133#[derive(Clone, Debug, Serialize, Deserialize)]
135pub struct Attempt {
136 pub by: String,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub answer: Option<String>,
141 pub proofs: Vec<ProofRecord>,
143 #[serde(default, skip_serializing_if = "Vec::is_empty")]
145 pub steps: Vec<StepRecord>,
146 #[serde(default, skip_serializing_if = "Vec::is_empty")]
148 pub back: Vec<String>,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub failed: Option<String>,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub conversation: Option<String>,
156 #[serde(default, skip_serializing_if = "Vec::is_empty")]
159 pub changed: Vec<String>,
160}
161
162impl Attempt {
163 pub fn by(by: &str) -> Self {
165 Self {
166 by: by.to_owned(),
167 answer: None,
168 proofs: Vec::new(),
169 steps: Vec::new(),
170 back: Vec::new(),
171 failed: None,
172 conversation: None,
173 changed: Vec::new(),
174 }
175 }
176}
177
178#[derive(Clone, Debug, Serialize, Deserialize)]
180pub struct ItemRecord {
181 pub item: String,
183 pub answer: Option<String>,
185 pub attempts: Vec<Attempt>,
187}
188
189#[derive(Clone, Debug, Serialize, Deserialize)]
191pub struct StepRecord {
192 pub id: String,
194 pub answer: Option<String>,
196 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
198 pub skipped: bool,
199 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
201 pub ended: bool,
202 pub attempts: Vec<Attempt>,
204 #[serde(default, skip_serializing_if = "Vec::is_empty")]
206 pub items: Vec<ItemRecord>,
207}
208
209impl StepRecord {
210 pub fn new(id: &str) -> Self {
212 Self {
213 id: id.to_owned(),
214 answer: None,
215 skipped: false,
216 ended: false,
217 attempts: Vec::new(),
218 items: Vec::new(),
219 }
220 }
221
222 pub fn started(&self) -> bool {
224 !self.attempts.is_empty() || !self.items.is_empty()
225 }
226}
227
228#[derive(Clone, Debug, Serialize, Deserialize)]
230pub struct Decision {
231 pub step: String,
233 pub asked: String,
235 pub answer: String,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub by: Option<String>,
240}
241
242#[derive(Clone, Debug)]
244pub struct Record {
245 pub id: String,
247 pub plan: Option<String>,
249 pub wish: String,
251 pub asked: String,
253 pub started: Timestamp,
255 pub ended: Timestamp,
257 pub outcome: Outcome,
259 pub cost: f64,
261 pub cost_unmeasured: bool,
263 pub steps: Vec<StepRecord>,
265 pub decisions: Vec<Decision>,
267 pub versions: Vec<Version>,
269 pub journal: Vec<Entry>,
272}
273
274#[derive(Deserialize)]
276struct Kept {
277 #[serde(default)]
278 id: String,
279 plan: Option<String>,
280 wish: String,
281 asked: String,
282 started: Timestamp,
283 ended: Timestamp,
284 outcome: String,
285 #[serde(default)]
286 reason: Option<String>,
287 #[serde(default)]
288 waiting: Option<Vec<Waiting>>,
289 cost: f64,
290 cost_unmeasured: bool,
291 steps: Vec<StepRecord>,
292 decisions: Vec<Decision>,
293 #[serde(default)]
294 versions: Vec<KeptVersion>,
295 #[serde(default)]
296 journal: Vec<Entry>,
297}
298
299#[derive(Deserialize)]
300struct KeptVersion {
301 plan: Value,
302 approved_by: Option<String>,
303 from: Option<String>,
304 at: Timestamp,
305}
306
307impl Record {
308 pub fn to_json(&self) -> Value {
310 let (outcome, reason, waiting) = match &self.outcome {
311 Outcome::Done => ("done", None, None),
312 Outcome::Stopped(reason) => ("stopped", Some(reason), None),
313 Outcome::Waiting(waiting) => ("waiting", None, Some(waiting)),
314 };
315 let versions: Vec<Value> = self
316 .versions
317 .iter()
318 .map(|version| {
319 json!({
320 "plan": version.plan,
321 "approved_by": version.approved_by,
322 "from": version.from,
323 "at": version.at,
324 })
325 })
326 .collect();
327 json!({
328 "id": self.id,
329 "plan": self.plan,
330 "wish": self.wish,
331 "asked": self.asked,
332 "started": self.started.to_string(),
333 "ended": self.ended.to_string(),
334 "outcome": outcome,
335 "reason": reason,
336 "waiting": waiting,
337 "cost": self.cost,
338 "cost_unmeasured": self.cost_unmeasured,
339 "steps": self.steps,
340 "decisions": self.decisions,
341 "versions": versions,
342 "journal": self.journal,
343 })
344 }
345
346 pub fn load(file: &Path) -> Result<Self, String> {
352 let text = fs::read_to_string(file)
353 .map_err(|error| format!("cannot read {}: {error}", file.display()))?;
354 let kept: Kept = serde_json::from_str(&text)
355 .map_err(|error| format!("{} does not hold a run: {error}", file.display()))?;
356 let outcome = match kept.outcome.as_str() {
357 "done" => Outcome::Done,
358 "waiting" => Outcome::Waiting(kept.waiting.unwrap_or_default()),
359 _ => Outcome::Stopped(kept.reason.unwrap_or_default()),
360 };
361 let mut versions = Vec::new();
362 for version in kept.versions {
363 let report = vpf::check(&version.plan.to_string());
364 let plan = report
365 .plan
366 .filter(|_| report.problems.is_empty())
367 .ok_or_else(|| format!("{} holds a plan with problems", file.display()))?;
368 versions.push(Version {
369 plan,
370 approved_by: version.approved_by,
371 from: version.from,
372 at: version.at,
373 });
374 }
375 let id = if kept.id.is_empty() {
376 file.file_stem()
377 .and_then(|stem| stem.to_str())
378 .unwrap_or_default()
379 .to_owned()
380 } else {
381 kept.id
382 };
383 Ok(Self {
384 id,
385 plan: kept.plan,
386 wish: kept.wish,
387 asked: kept.asked,
388 started: kept.started,
389 ended: kept.ended,
390 outcome,
391 cost: kept.cost,
392 cost_unmeasured: kept.cost_unmeasured,
393 steps: kept.steps,
394 decisions: kept.decisions,
395 versions,
396 journal: kept.journal,
397 })
398 }
399
400 pub fn file(&self, folder: &Path) -> PathBuf {
402 runs(folder).join(format!("{}.json", self.id))
403 }
404
405 pub fn keep(&self, folder: &Path) -> std::io::Result<PathBuf> {
411 fs::create_dir_all(runs(folder))?;
412 let file = self.file(folder);
413 let text = serde_json::to_string_pretty(&self.to_json()).unwrap_or_default();
414 fs::write(&file, text + "\n")?;
415 Ok(file)
416 }
417
418 pub fn add_entries(&mut self, entries: impl IntoIterator<Item = Entry>) {
422 let mut places: std::collections::HashMap<String, usize> = self
423 .journal
424 .iter()
425 .enumerate()
426 .map(|(place, entry)| (entry.key.clone(), place))
427 .collect();
428 for entry in entries {
429 if let Some(&place) = places.get(&entry.key) {
430 self.journal[place] = entry;
431 } else {
432 places.insert(entry.key.clone(), self.journal.len());
433 self.journal.push(entry);
434 }
435 }
436 }
437
438 pub fn reply(&mut self, key: &str, reply: Reply, by: Option<&str>) -> Result<(), String> {
446 let Outcome::Waiting(waiting) = &mut self.outcome else {
447 return Err(format!("the run {} waits for nothing", self.id));
448 };
449 let place = waiting
450 .iter()
451 .position(|waiting| waiting.key == key)
452 .ok_or_else(|| format!("the run {} does not wait for {key}", self.id))?;
453 fits(&waiting[place].wait, &reply, by)?;
454 waiting.remove(place);
455 self.journal.push(Entry {
456 key: key.to_owned(),
457 at: Timestamp::now(),
458 by: by.map(str::to_owned),
459 value: serde_json::to_value(reply).unwrap_or_default(),
460 });
461 Ok(())
462 }
463
464 pub fn change(&mut self, plan: &Plan, approved_by: &str, at: Timestamp) -> Result<(), String> {
472 if !matches!(self.outcome, Outcome::Waiting(_)) {
473 return Err(format!(
474 "the run {} does not wait, so its plan cannot change",
475 self.id
476 ));
477 }
478 let approved_by = approved_by.trim();
479 if approved_by.is_empty() {
480 return Err("a new version of the plan needs the person's approval".to_owned());
481 }
482 let report = vpf::check(&serde_json::to_string(plan).unwrap_or_default());
483 if !report.problems.is_empty() {
484 let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
485 return Err(format!(
486 "the new version has problems: {}",
487 problems.join("; ")
488 ));
489 }
490 let old = self
491 .versions
492 .last()
493 .ok_or_else(|| format!("the run {} keeps no plan", self.id))?;
494 for (step, record) in old.plan.steps.iter().zip(&self.steps) {
495 let new = plan.steps.iter().find(|new| new.id == step.id);
496 if record.ended && new != Some(step) {
497 return Err(format!(
498 "the step {} has ended, so it must stay as it was",
499 step.id
500 ));
501 }
502 if record.started()
503 && !new.is_some_and(|new| new.by == step.by && new.what == step.what)
504 {
505 return Err(format!(
506 "the step {} has started, so it must keep its id, by and do",
507 step.id
508 ));
509 }
510 if record.started() && step.irreversible() && !new.is_some_and(Step::irreversible) {
511 return Err(format!(
512 "the step {} has started and cannot be undone, so it stays so",
513 step.id
514 ));
515 }
516 }
517 let ended: Vec<&str> = self
518 .steps
519 .iter()
520 .filter(|record| record.ended)
521 .map(|record| record.id.as_str())
522 .collect();
523 let from = plan
524 .steps
525 .iter()
526 .find(|step| !ended.contains(&step.id.as_str()))
527 .map(|step| step.id.clone());
528 self.wish = crate::fill::fill(
529 &plan.wish,
530 &std::collections::HashMap::from([("asked".to_owned(), self.asked.clone())]),
531 );
532 self.versions.push(Version {
533 plan: plan.clone(),
534 approved_by: Some(approved_by.to_owned()),
535 from,
536 at,
537 });
538 Ok(())
539 }
540}
541
542fn fits(wait: &Wait, reply: &Reply, by: Option<&str>) -> Result<(), String> {
544 let ask = match wait {
545 Wait::Answer(ask) | Wait::Approval(ask) => Some(ask),
546 _ => None,
547 };
548 if let Some(ask) = ask.filter(|ask| !ask.people.is_empty()) {
549 if !by.is_some_and(|by| ask.people.iter().any(|person| person == by)) {
550 return Err(format!(
551 "only {} may answer this; say who answers",
552 ask.people.join(" or ")
553 ));
554 }
555 }
556 match (wait, reply) {
557 (Wait::Answer(ask), Reply::Text(text)) => {
558 if ask.choices.is_empty() || ask.choices.iter().any(|choice| choice == text.trim()) {
559 Ok(())
560 } else {
561 Err(format!(
562 "the answer must be one of: {}",
563 ask.choices.join(", ")
564 ))
565 }
566 }
567 (Wait::Approval(ask), Reply::No { back, .. }) => {
568 match back.iter().find(|id| !ask.back_to.contains(id)) {
569 Some(id) => Err(format!(
570 "the work may not go back to {id}; it may go back to: {}",
571 ask.back_to.join(", ")
572 )),
573 None => Ok(()),
574 }
575 }
576 (Wait::Approval(_) | Wait::Decision(_), Reply::Yes)
577 | (Wait::Decision(_), Reply::No { .. }) => Ok(()),
578 (Wait::Choice { options, .. }, Reply::Option(chosen)) if *chosen < options.len() => Ok(()),
579 (Wait::Time(at), _) => Err(format!("this waits for a time, {at}, not for an answer")),
580 _ => Err("the reply does not fit what is asked".to_owned()),
581 }
582}
583
584pub fn runs(folder: &Path) -> PathBuf {
586 folder.join(".vpf").join("runs")
587}
588
589pub fn spent_this_month(folder: &Path, plan: &str, now: Timestamp) -> f64 {
591 let zone = TimeZone::system();
592 let month = |at: Timestamp| {
593 let date = at.to_zoned(zone.clone()).date();
594 (date.year(), date.month())
595 };
596 let this = month(now);
597 let Ok(read) = fs::read_dir(runs(folder)) else {
598 return 0.0;
599 };
600 read.filter_map(Result::ok)
601 .filter_map(|entry| fs::read_to_string(entry.path()).ok())
602 .filter_map(|text| serde_json::from_str::<Value>(&text).ok())
603 .filter(|record| record["plan"] == plan)
604 .filter(|record| {
605 record["started"]
606 .as_str()
607 .and_then(|started| started.parse::<Timestamp>().ok())
608 .is_some_and(|started| month(started) == this)
609 })
610 .filter_map(|record| record["cost"].as_f64())
611 .sum()
612}