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 still_working(&self, folder: &Path) -> Vec<u32> {
403 self.kept_work(folder)
404 .into_iter()
405 .filter_map(|(pid, running)| running.then_some(pid))
406 .collect()
407 }
408
409 pub fn stopped_working(&self, folder: &Path) -> Vec<u32> {
412 self.kept_work(folder)
413 .into_iter()
414 .filter_map(|(pid, running)| (!running).then_some(pid))
415 .collect()
416 }
417
418 fn kept_work(&self, folder: &Path) -> Vec<(u32, bool)> {
420 let Ok(read) = fs::read_dir(runs(folder).join(format!("{}.out", self.id))) else {
421 return Vec::new();
422 };
423 let mut work: Vec<(u32, bool)> = read
424 .filter_map(Result::ok)
425 .map(|entry| entry.path())
426 .filter(|dir| crate::command::kept(dir).is_none())
427 .filter_map(|dir| {
428 let pid = fs::read_to_string(dir.join("pid"))
429 .ok()?
430 .trim()
431 .parse()
432 .ok()?;
433 Some((pid, crate::command::alive(pid)))
434 })
435 .collect();
436 work.sort_unstable();
437 work
438 }
439
440 pub fn file(&self, folder: &Path) -> PathBuf {
442 runs(folder).join(format!("{}.json", self.id))
443 }
444
445 pub fn keep(&self, folder: &Path) -> std::io::Result<PathBuf> {
451 fs::create_dir_all(runs(folder))?;
452 let file = self.file(folder);
453 let text = serde_json::to_string_pretty(&self.to_json()).unwrap_or_default();
454 fs::write(&file, text + "\n")?;
455 Ok(file)
456 }
457
458 pub fn add_entries(&mut self, entries: impl IntoIterator<Item = Entry>) {
462 let mut places: std::collections::HashMap<String, usize> = self
463 .journal
464 .iter()
465 .enumerate()
466 .map(|(place, entry)| (entry.key.clone(), place))
467 .collect();
468 for entry in entries {
469 if let Some(&place) = places.get(&entry.key) {
470 self.journal[place] = entry;
471 } else {
472 places.insert(entry.key.clone(), self.journal.len());
473 self.journal.push(entry);
474 }
475 }
476 }
477
478 pub fn reply(&mut self, key: &str, reply: Reply, by: Option<&str>) -> Result<(), String> {
486 let Outcome::Waiting(waiting) = &mut self.outcome else {
487 return Err(format!("the run {} waits for nothing", self.id));
488 };
489 let place = waiting
490 .iter()
491 .position(|waiting| waiting.key == key)
492 .ok_or_else(|| format!("the run {} does not wait for {key}", self.id))?;
493 fits(&waiting[place].wait, &reply, by)?;
494 waiting.remove(place);
495 self.journal.push(Entry {
496 key: key.to_owned(),
497 at: Timestamp::now(),
498 by: by.map(str::to_owned),
499 value: serde_json::to_value(reply).unwrap_or_default(),
500 });
501 Ok(())
502 }
503
504 pub fn change(&mut self, plan: &Plan, approved_by: &str, at: Timestamp) -> Result<(), String> {
512 if !matches!(self.outcome, Outcome::Waiting(_)) {
513 return Err(format!(
514 "the run {} does not wait, so its plan cannot change",
515 self.id
516 ));
517 }
518 let approved_by = approved_by.trim();
519 if approved_by.is_empty() {
520 return Err("a new version of the plan needs the person's approval".to_owned());
521 }
522 let report = vpf::check(&serde_json::to_string(plan).unwrap_or_default());
523 if !report.problems.is_empty() {
524 let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
525 return Err(format!(
526 "the new version has problems: {}",
527 problems.join("; ")
528 ));
529 }
530 let old = self
531 .versions
532 .last()
533 .ok_or_else(|| format!("the run {} keeps no plan", self.id))?;
534 for (step, record) in old.plan.steps.iter().zip(&self.steps) {
535 let new = plan.steps.iter().find(|new| new.id == step.id);
536 if record.ended && new != Some(step) {
537 return Err(format!(
538 "the step {} has ended, so it must stay as it was",
539 step.id
540 ));
541 }
542 if record.started()
543 && !new.is_some_and(|new| new.by == step.by && new.what == step.what)
544 {
545 return Err(format!(
546 "the step {} has started, so it must keep its id, by and do",
547 step.id
548 ));
549 }
550 if record.started() && step.irreversible() && !new.is_some_and(Step::irreversible) {
551 return Err(format!(
552 "the step {} has started and cannot be undone, so it stays so",
553 step.id
554 ));
555 }
556 }
557 let ended: Vec<&str> = self
558 .steps
559 .iter()
560 .filter(|record| record.ended)
561 .map(|record| record.id.as_str())
562 .collect();
563 let from = plan
564 .steps
565 .iter()
566 .find(|step| !ended.contains(&step.id.as_str()))
567 .map(|step| step.id.clone());
568 self.wish = crate::fill::fill(
569 &plan.wish,
570 &std::collections::HashMap::from([("asked".to_owned(), self.asked.clone())]),
571 );
572 self.versions.push(Version {
573 plan: plan.clone(),
574 approved_by: Some(approved_by.to_owned()),
575 from,
576 at,
577 });
578 Ok(())
579 }
580}
581
582fn fits(wait: &Wait, reply: &Reply, by: Option<&str>) -> Result<(), String> {
584 let ask = match wait {
585 Wait::Answer(ask) | Wait::Approval(ask) => Some(ask),
586 _ => None,
587 };
588 if let Some(ask) = ask.filter(|ask| !ask.people.is_empty()) {
589 if !by.is_some_and(|by| ask.people.iter().any(|person| person == by)) {
590 return Err(format!(
591 "only {} may answer this; say who answers",
592 ask.people.join(" or ")
593 ));
594 }
595 }
596 match (wait, reply) {
597 (Wait::Answer(ask), Reply::Text(text)) => {
598 if ask.choices.is_empty() || ask.choices.iter().any(|choice| choice == text.trim()) {
599 Ok(())
600 } else {
601 Err(format!(
602 "the answer must be one of: {}",
603 ask.choices.join(", ")
604 ))
605 }
606 }
607 (Wait::Approval(ask), Reply::No { back, .. }) => {
608 match back.iter().find(|id| !ask.back_to.contains(id)) {
609 Some(id) => Err(format!(
610 "the work may not go back to {id}; it may go back to: {}",
611 ask.back_to.join(", ")
612 )),
613 None => Ok(()),
614 }
615 }
616 (Wait::Approval(_) | Wait::Decision(_), Reply::Yes)
617 | (Wait::Decision(_), Reply::No { .. }) => Ok(()),
618 (Wait::Choice { options, .. }, Reply::Option(chosen)) if *chosen < options.len() => Ok(()),
619 (Wait::Time(at), _) => Err(format!("this waits for a time, {at}, not for an answer")),
620 _ => Err("the reply does not fit what is asked".to_owned()),
621 }
622}
623
624pub fn runs(folder: &Path) -> PathBuf {
626 folder.join(".vpf").join("runs")
627}
628
629pub fn spent_this_month(folder: &Path, plan: &str, now: Timestamp) -> f64 {
631 let zone = TimeZone::system();
632 let month = |at: Timestamp| {
633 let date = at.to_zoned(zone.clone()).date();
634 (date.year(), date.month())
635 };
636 let this = month(now);
637 let Ok(read) = fs::read_dir(runs(folder)) else {
638 return 0.0;
639 };
640 read.filter_map(Result::ok)
641 .filter_map(|entry| fs::read_to_string(entry.path()).ok())
642 .filter_map(|text| serde_json::from_str::<Value>(&text).ok())
643 .filter(|record| record["plan"] == plan)
644 .filter(|record| {
645 record["started"]
646 .as_str()
647 .and_then(|started| started.parse::<Timestamp>().ok())
648 .is_some_and(|started| month(started) == this)
649 })
650 .filter_map(|record| record["cost"].as_f64())
651 .sum()
652}