[insight] Projects: spent by line and unplanned, income without VAT and never twice, profit and margin, progress, the forecast, late, time by task and week, billed and unbilled; Project on budget and Finished on time medals

This commit is contained in:
2026-11-11 21:07:42 +01:00
parent 3245341ebc
commit 65899bc170
6 changed files with 579 additions and 4 deletions
+2 -1
View File
@@ -1,12 +1,13 @@
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
//! how to cancel, whether the month will stay under its limit, where the money went and how it compares with
//! your plan, how your savings goals fill, and the medals and challenges you earn. Pure: "today" and seeds are parameters.
//! your plan, how your savings goals fill, your projects against their budgets and tasks, and the medals and challenges you earn. Pure: "today" and seeds are parameters.
pub mod cancel;
pub mod forecast;
pub mod goals;
pub mod household;
pub mod plan;
pub mod projects;
pub mod rewards;
pub mod spending;
pub mod stats;
+278
View File
@@ -0,0 +1,278 @@
//! Projects: what each one has cost against its budget lines, what it earned (a business), how far its tasks are,
//! what it will cost in the end, whether it is late, and its time. A payment counts in a project by hand
//! (`payment.projected`) or by a project rule of its merchant; it still counts in its budget and its month too.
use crate::spending::is_spending;
use fiscus_ledger::goal::Colour;
use fiscus_ledger::project::{week_of, EntryId, Kind, Phase, ProjectRecord, Status, TaskRecord, TaskStatus};
use fiscus_ledger::{Date, Haler, State};
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct LineStatus {
pub id: String,
pub name: String,
pub planned: Haler,
pub spent: Haler,
/// Planned less spent; negative when over.
pub left: Haler,
pub over: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub struct TaskCounts {
pub todo: usize,
pub doing: usize,
pub done: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ProjectSummary {
pub id: String,
pub name: String,
pub kind: Kind,
pub status: Status,
pub colour: Colour,
pub starts: Option<Date>,
pub ends: Option<Date>,
/// All the budget lines together.
pub planned: Haler,
/// Money out of the payments in the project (positive).
pub spent: Haler,
/// A business: paid invoices of the project (without VAT) and money in put into it.
pub income: Haler,
pub profit: Haler,
/// Profit of income in thousandths; `None` without income.
pub margin_permille: Option<i64>,
/// What the open tasks are estimated to cost.
pub open_estimates: Haler,
/// Spent plus the open estimates: what it will have cost.
pub forecast: Haler,
/// Tasks done, in thousandths: by their estimates when every task has one, else by count.
pub progress_permille: u32,
pub tasks: TaskCounts,
pub late_tasks: usize,
/// Spent, or the forecast, above the plan.
pub over_budget: bool,
/// An open task past its due date, or the project past its end with tasks open.
pub late: bool,
pub minutes: u64,
pub unbilled_minutes: u64,
pub unbilled: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ProjectPayment {
pub id: String,
pub date: Date,
pub merchant: String,
pub amount: Haler,
pub line: Option<String>,
/// Counted by a project rule, not put in by hand.
pub by_rule: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct TaskStatusRow {
pub task: TaskRecord,
pub late: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct TaskTime {
pub task: Option<String>,
pub minutes: u64,
pub amount: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ProjectDetail {
pub summary: ProjectSummary,
pub lines: Vec<LineStatus>,
/// Spent outside any line.
pub unplanned: Haler,
/// The latest first.
pub payments: Vec<ProjectPayment>,
/// Open tasks by due date (none last), then the done ones, the latest done first.
pub tasks: Vec<TaskStatusRow>,
/// By start.
pub phases: Vec<Phase>,
pub time_by_task: Vec<TaskTime>,
/// Monday of each week with time → minutes, oldest first.
pub time_by_week: Vec<(Date, u64)>,
/// What all the time is worth, and the entries not invoiced yet (by date).
pub billable: Haler,
pub unbilled_entries: Vec<EntryId>,
pub invoices: Vec<String>,
}
fn sum(it: impl Iterator<Item = Haler>) -> Haler {
Haler(it.fold(0i64, |s, h| s.saturating_add(h.0)))
}
fn permille(part: i64, whole: i64) -> u32 {
if whole <= 0 {
return 0;
}
(i128::from(part.clamp(0, whole)) * 1000 / i128::from(whole)) as u32
}
fn summary_and_rows(state: &State, p: &ProjectRecord, today: Date) -> (ProjectSummary, Vec<LineStatus>, Haler, Vec<ProjectPayment>, Vec<TaskStatusRow>) {
// The payments in the project.
let mut payments = Vec::new();
let mut by_line: BTreeMap<Option<String>, i64> = BTreeMap::new();
let mut inflow = 0i64;
let invoice_payments: Vec<&String> = state.invoice_payments.iter().filter(|(_, inv)| p.invoices.contains(*inv)).map(|(pay, _)| pay).collect();
for e in state.effective_payments() {
let Some((project, line)) = state.project_of(&e) else { continue };
if project != p.id {
continue;
}
let line = line.filter(|l| p.line(l).is_some());
if is_spending(&e) {
let slot = by_line.entry(line.clone()).or_insert(0);
*slot = slot.saturating_add(e.amount.0.saturating_neg());
} else if e.amount.0 > 0 && e.category.as_deref() != Some(fiscus_ledger::categories::TRANSFERS) && !invoice_payments.contains(&&e.id) {
inflow = inflow.saturating_add(e.amount.0);
}
payments.push(ProjectPayment { by_rule: !state.projects.payments.contains_key(&e.id), id: e.id, date: e.date, merchant: e.merchant, amount: e.amount, line });
}
payments.sort_by(|a, b| b.date.cmp(&a.date).then(a.id.cmp(&b.id)));
let spent = Haler(by_line.values().fold(0i64, |s, v| s.saturating_add(*v)));
let unplanned = Haler(by_line.get(&None).copied().unwrap_or(0));
let lines: Vec<LineStatus> = p
.lines
.iter()
.map(|l| {
let s = Haler(by_line.get(&Some(l.id.clone())).copied().unwrap_or(0));
let left = Haler(l.planned.0.saturating_sub(s.0));
LineStatus { id: l.id.clone(), name: l.name.clone(), planned: l.planned, spent: s, left, over: left.0 < 0 }
})
.collect();
let planned = sum(p.lines.iter().map(|l| l.planned));
// Income: the project's paid invoices without VAT, and money in put into it (not the lines that paid them).
let invoiced = sum(p.invoices.iter().filter_map(|i| state.invoices.get(i)).filter(|r| r.paid.is_some() && !r.cancelled).map(|r| r.totals.net));
let income = Haler(invoiced.0.saturating_add(inflow));
let profit = Haler(income.0.saturating_sub(spent.0));
let margin_permille = (income.0 > 0).then(|| (i128::from(profit.0) * 1000 / i128::from(income.0)) as i64);
// Tasks.
let mut tasks: Vec<TaskStatusRow> = state
.projects
.tasks
.values()
.filter(|t| t.project == p.id)
.map(|t| TaskStatusRow { late: t.status != TaskStatus::Done && t.fields.due.is_some_and(|d| d < today), task: t.clone() })
.collect();
tasks.sort_by(|a, b| {
let done = |t: &TaskStatusRow| t.task.status == TaskStatus::Done;
done(a).cmp(&done(b)).then_with(|| {
if done(a) {
b.task.done_on.cmp(&a.task.done_on)
} else {
(a.task.fields.due.is_none(), a.task.fields.due).cmp(&(b.task.fields.due.is_none(), b.task.fields.due))
}
})
.then(a.task.seq.cmp(&b.task.seq))
});
let mut counts = TaskCounts::default();
for t in &tasks {
match t.task.status {
TaskStatus::Todo => counts.todo += 1,
TaskStatus::Doing => counts.doing += 1,
TaskStatus::Done => counts.done += 1,
}
}
let open_estimates = sum(tasks.iter().filter(|t| t.task.status != TaskStatus::Done).filter_map(|t| t.task.fields.estimate));
let all_estimated = !tasks.is_empty() && tasks.iter().all(|t| t.task.fields.estimate.is_some_and(|e| e.0 > 0));
let progress_permille = if all_estimated {
let total = sum(tasks.iter().filter_map(|t| t.task.fields.estimate));
let done = sum(tasks.iter().filter(|t| t.task.status == TaskStatus::Done).filter_map(|t| t.task.fields.estimate));
permille(done.0, total.0)
} else {
permille(counts.done as i64, tasks.len() as i64)
};
let forecast = Haler(spent.0.saturating_add(open_estimates.0));
let late_tasks = tasks.iter().filter(|t| t.late).count();
let open = p.is_open();
let late = open && (late_tasks > 0 || (p.ends.is_some_and(|e| e < today) && counts.todo + counts.doing > 0));
let over_budget = planned.0 > 0 && (spent > planned || forecast > planned);
// Time.
let entries: Vec<_> = state.projects.time.values().filter(|t| t.project == p.id).collect();
let minutes: u64 = entries.iter().map(|t| u64::from(t.minutes)).sum();
let unbilled_minutes: u64 = entries.iter().filter(|t| t.invoice.is_none()).map(|t| u64::from(t.minutes)).sum();
let unbilled = sum(entries.iter().filter(|t| t.invoice.is_none()).map(|t| t.amount()));
let summary = ProjectSummary {
id: p.id.clone(),
name: p.name.clone(),
kind: p.kind,
status: p.status,
colour: p.colour,
starts: p.starts,
ends: p.ends,
planned,
spent,
income,
profit,
margin_permille,
open_estimates,
forecast,
progress_permille,
tasks: counts,
late_tasks,
over_budget,
late,
minutes,
unbilled_minutes,
unbilled,
};
(summary, lines, unplanned, payments, tasks)
}
/// Every project: the open ones in the order made, then the done ones, the latest done first.
pub fn projects(state: &State, today: Date) -> Vec<ProjectSummary> {
let mut open: Vec<&ProjectRecord> = state.projects.projects.values().filter(|p| p.is_open()).collect();
open.sort_by_key(|p| p.seq);
let mut done: Vec<&ProjectRecord> = state.projects.projects.values().filter(|p| !p.is_open()).collect();
done.sort_by_key(|p| std::cmp::Reverse((p.status_on, p.seq)));
open.into_iter().chain(done).map(|p| summary_and_rows(state, p, today).0).collect()
}
/// One project in full.
pub fn project(state: &State, id: &str, today: Date) -> Option<ProjectDetail> {
let p = state.projects.projects.get(id)?;
let (summary, lines, unplanned, payments, tasks) = summary_and_rows(state, p, today);
let mut phases = p.phases.clone();
phases.sort_by(|a, b| a.starts.cmp(&b.starts).then(a.id.cmp(&b.id)));
let mut entries: Vec<_> = state.projects.time.values().filter(|t| t.project == p.id).collect();
entries.sort_by(|a, b| a.on.cmp(&b.on).then(a.seq.cmp(&b.seq)));
let mut by_task: BTreeMap<Option<String>, (u64, i64)> = BTreeMap::new();
let mut by_week: BTreeMap<Date, u64> = BTreeMap::new();
for t in &entries {
let slot = by_task.entry(t.task.clone()).or_insert((0, 0));
slot.0 += u64::from(t.minutes);
slot.1 = slot.1.saturating_add(t.amount().0);
*by_week.entry(week_of(t.on)).or_insert(0) += u64::from(t.minutes);
}
let mut time_by_task: Vec<TaskTime> = by_task.into_iter().map(|(task, (minutes, amount))| TaskTime { task, minutes, amount: Haler(amount) }).collect();
time_by_task.sort_by(|a, b| b.minutes.cmp(&a.minutes).then(a.task.cmp(&b.task)));
Some(ProjectDetail {
lines,
unplanned,
payments,
tasks,
phases,
time_by_task,
time_by_week: by_week.into_iter().collect(),
billable: sum(entries.iter().map(|t| t.amount())),
unbilled_entries: entries.iter().filter(|t| t.invoice.is_none()).map(|t| t.id.clone()).collect(),
invoices: p.invoices.iter().cloned().collect(),
summary,
})
}
+18
View File
@@ -32,6 +32,10 @@ pub enum Medal {
GoalMilestone { goal: String, name: String, permille: u32 },
/// Money put aside in this many complete months running (3 or more), up to `until`'s month.
SavingStreak { months: u32, until: Date },
/// A project done within its budget (it had one).
ProjectOnBudget { project: String, name: String },
/// A project done by its end date (it had one).
FinishedOnTime { project: String, name: String },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
@@ -332,6 +336,20 @@ pub fn rewards(state: &State, insight: &Insight, shared: &BTreeSet<BudgetId>, to
medals.push(Earned { medal: Medal::SavingStreak { months: n, until: last }, on: last.month_end() });
}
// Projects done: within their budget, by their end date.
let summaries = crate::projects::projects(state, today);
for p in state.projects.projects.values().filter(|p| !p.is_open()) {
let Some(on) = p.status_on else { continue };
if let Some(s) = summaries.iter().find(|s| s.id == p.id) {
if s.planned.0 > 0 && s.spent <= s.planned {
medals.push(Earned { medal: Medal::ProjectOnBudget { project: p.id.clone(), name: p.name.clone() }, on });
}
}
if p.ends.is_some_and(|e| on <= e) {
medals.push(Earned { medal: Medal::FinishedOnTime { project: p.id.clone(), name: p.name.clone() }, on });
}
}
medals.sort_by_key(|m| std::cmp::Reverse(m.on));
let month = today.month_start();
Rewards {