use std::collections::BTreeMap;
use printobserver_printer_api::FileFacts;
use printobserver_types::{EventRecord, Timestamp};
use crate::accounting::{Feed, Figures, NOTHING_MM, lengths_of};
use crate::error::CoreError;
use crate::kinds::{
FileTallyRebaselinedPayload, RebaselineDisposition, UnaccountedPrintPayload, system_source,
};
use crate::records::{ChargeKey, ChargeMethod, PrintOutcome, SpoolRecord, UnverifiedReason};
use crate::store::{Charge, EventDraft, FileTally, SpoolMutation};
use crate::supervisor::Supervisor;
#[derive(Debug, Clone, Copy)]
struct Unseen {
print_number: i64,
outcome: PrintOutcome,
}
#[derive(Debug, Clone, Copy, Default)]
struct Settled {
successes: i64,
failures: i64,
}
impl Settled {
const fn total(self) -> i64 {
self.successes + self.failures
}
}
fn unseen_between(from: (i64, i64), to: (i64, i64), settled: Settled) -> Vec<Unseen> {
let grown = |now: i64, before: i64, seen: i64| {
now.checked_sub(before)
.and_then(|growth| growth.checked_sub(seen))
.map(|unseen| unseen.max(0))
};
let (Some(successes), Some(failures), Some(total)) = (
grown(to.0, from.0, settled.successes),
grown(to.1, from.1, settled.failures),
to.0.checked_add(to.1),
) else {
return Vec::new();
};
let Some(first) = successes
.checked_add(failures)
.and_then(|unseen| total.checked_sub(unseen))
.and_then(|before| before.checked_add(1))
else {
return Vec::new();
};
(0..successes.saturating_add(failures))
.map(|offset| Unseen {
print_number: first.saturating_add(offset),
outcome: if offset < successes {
PrintOutcome::Completed
} else {
PrintOutcome::Failed
},
})
.collect()
}
fn settled_since(
settlements: &[(String, Timestamp, PrintOutcome)],
file_name: &str,
since: Option<Timestamp>,
) -> Settled {
let mut settled = Settled::default();
for (_, _, outcome) in settlements
.iter()
.filter(|(file, at, _)| file == file_name && since.is_none_or(|since| *at >= since))
{
if *outcome == PrintOutcome::Completed {
settled.successes += 1;
} else {
settled.failures += 1;
}
}
settled
}
#[derive(Debug, Default)]
struct Accounting {
tallies: Vec<FileTally>,
charges: Vec<Charge>,
marks: Vec<SpoolMutation>,
events: Vec<EventDraft>,
figures: Figures,
}
impl Supervisor {
pub async fn account_unobserved_prints(&self) -> Result<Vec<EventRecord>, CoreError> {
let files = self
.read_printed_files()
.await
.map_err(CoreError::Printer)?;
let _writing = self.spool_writes().await;
let held = self.stores().filament.file_tallies().await?;
let now = self.clock().now();
if held.is_empty() {
let baseline = files
.iter()
.filter(|file| readable(file))
.map(|file| FileTally {
file_name: file.file_name.clone(),
origin: file.origin.clone(),
generation: 0,
successes: file.successes,
failures: file.failures,
observed_at: now,
})
.collect();
return Ok(self
.stores()
.filament
.account_tallies(baseline, Vec::new(), Vec::new(), Vec::new())
.await?);
}
let loaded = self.stores().filament.loaded_spools().await?;
let settlements = self.settlements_of(&files).await?;
let mut accounting = Accounting::default();
for file in files.iter().filter(|file| readable(file)) {
let previous = held
.iter()
.find(|tally| tally.file_name == file.file_name && tally.origin == file.origin);
self.account_file(file, previous, &settlements, &loaded, now, &mut accounting)?;
}
Ok(self
.stores()
.filament
.account_tallies(
accounting.tallies,
accounting.charges,
accounting.marks,
accounting.events,
)
.await?)
}
async fn settlements_of(
&self,
files: &[FileFacts],
) -> Result<Vec<(String, Timestamp, PrintOutcome)>, CoreError> {
let mut settlements = Vec::new();
for print in self.stores().prints.prints().await? {
let Some(file_name) = print
.file_name
.filter(|name| files.iter().any(|file| &file.file_name == name))
else {
continue;
};
if let Some((at, outcome)) = self.stores().filament.print_settlement(print.id).await? {
settlements.push((file_name, at, outcome));
}
}
Ok(settlements)
}
fn account_file(
&self,
file: &FileFacts,
previous: Option<&FileTally>,
settlements: &[(String, Timestamp, PrintOutcome)],
loaded: &[SpoolRecord],
now: Timestamp,
accounting: &mut Accounting,
) -> Result<(), CoreError> {
let since = previous.map(|tally| tally.observed_at);
let settled = settled_since(settlements, &file.file_name, since);
let (generation, unseen) = match previous {
Some(held) if file.successes < held.successes || file.failures < held.failures => {
let generation = held.generation + 1;
let accounted = settled.total() == 0;
accounting.events.push(self.draft_of(
None,
system_source(),
&FileTallyRebaselinedPayload {
file_name: file.file_name.clone(),
origin: file.origin.clone(),
old_generation: held.generation,
new_generation: generation,
old_successes: held.successes,
old_failures: held.failures,
new_successes: file.successes,
new_failures: file.failures,
disposition: if accounted {
RebaselineDisposition::Accounted
} else {
RebaselineDisposition::Unverified
},
},
)?);
if accounted {
let unseen =
unseen_between((0, 0), (file.successes, file.failures), Settled::default());
(generation, unseen)
} else {
for spool in spools_for(file, loaded) {
accounting.marks.push(self.mark_of(
spool.id,
UnverifiedReason::TallyReset {
file_name: file.file_name.clone(),
origin: file.origin.clone(),
},
None,
)?);
}
(generation, Vec::new())
}
}
Some(held) => (
held.generation,
unseen_between(
(held.successes, held.failures),
(file.successes, file.failures),
settled,
),
),
None => (
0,
unseen_between((0, 0), (file.successes, file.failures), settled),
),
};
for print in unseen {
self.account_unseen(file, generation, print, loaded, accounting)?;
}
accounting.tallies.push(FileTally {
file_name: file.file_name.clone(),
origin: file.origin.clone(),
generation,
successes: file.successes,
failures: file.failures,
observed_at: now,
});
Ok(())
}
fn account_unseen(
&self,
file: &FileFacts,
generation: u32,
print: Unseen,
loaded: &[SpoolRecord],
accounting: &mut Accounting,
) -> Result<(), CoreError> {
let printed_at = file.last_print.as_ref().map(|last| last.at);
let analysed: Option<BTreeMap<i64, f64>> = file.filament.as_deref().map(lengths_of);
let mut charged = false;
match (&analysed, print.outcome) {
(Some(lengths), PrintOutcome::Completed) => {
for (tool, length) in lengths {
if *length <= NOTHING_MM {
continue;
}
let spool = loaded
.iter()
.find(|spool| spool.loaded_tool() == Some(*tool));
charged |= spool.is_some();
accounting.charges.push(self.charge_of(
Feed {
key: ChargeKey::Unobserved {
origin: file.origin.clone(),
file_name: file.file_name.clone(),
generation,
print_number: print.print_number,
tool: *tool,
},
method: ChargeMethod::UnobservedEstimate,
length_mm: *length,
analysed_length_mm: Some(*length),
position: None,
note: None,
},
spool,
&mut accounting.figures,
system_source(),
)?);
}
}
_ => {
for spool in spools_for(file, loaded) {
accounting.marks.push(self.mark_of(
spool.id,
UnverifiedReason::UnaccountedPrint {
file_name: file.file_name.clone(),
printed_at: printed_at.unwrap_or_else(|| self.clock().now()),
},
None,
)?);
}
}
}
accounting.events.push(self.draft_of(
None,
system_source(),
&UnaccountedPrintPayload {
file_name: file.file_name.clone(),
printed_at,
success: print.outcome == PrintOutcome::Completed,
charged,
},
)?);
Ok(())
}
}
fn readable(file: &FileFacts) -> bool {
file.successes >= 0 && file.failures >= 0 && file.successes.checked_add(file.failures).is_some()
}
fn spools_for<'a>(file: &FileFacts, loaded: &'a [SpoolRecord]) -> Vec<&'a SpoolRecord> {
match file.filament.as_deref().map(lengths_of) {
Some(lengths) => loaded
.iter()
.filter(|spool| {
spool
.loaded_tool()
.is_some_and(|tool| lengths.get(&tool).is_some_and(|l| *l > NOTHING_MM))
})
.collect(),
None => loaded.iter().collect(),
}
}