[insight] Projects: budget lines, payments in projects, tasks, phases, time and invoices; v0.7.0 #9
@@ -6,10 +6,10 @@ subscription / price-change / trial detection and a seeded month-end forecast. N
|
||||
|
||||
| Crate | |
|
||||
|:--|:--|
|
||||
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans, savings goals and challenges |
|
||||
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans, savings goals and challenges, projects (lines, tasks, phases, time) |
|
||||
| `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples |
|
||||
| `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers, goals and their ways to save, medals |
|
||||
| `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers, goals and their ways to save, medals, projects against their budgets |
|
||||
|
||||
Design: [docs/01_core.md](docs/01_core.md), [02](docs/02_capture_sharing.md), [03 invoices](docs/03_invoices.md), [04 plans and statistics](docs/04_plans_stats.md), [05 goals and rewards](docs/05_goals_rewards.md). Tests: `cargo test --workspace`.
|
||||
Design: [docs/01_core.md](docs/01_core.md), [02](docs/02_capture_sharing.md), [03 invoices](docs/03_invoices.md), [04 plans and statistics](docs/04_plans_stats.md), [05 goals and rewards](docs/05_goals_rewards.md), [06 projects](docs/06_projects.md). Tests: `cargo test --workspace`.
|
||||
|
||||
Licence: MPL-2.0.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//! A project's numbers: spent by line and unplanned, payments by hand and by rule within the project's dates,
|
||||
//! income without VAT and never twice, profit and margin, progress by estimates or by count, the forecast, late,
|
||||
//! time by task and week, billed and unbilled, and the two project medals.
|
||||
|
||||
use fiscus_insight::projects::{project, projects};
|
||||
use fiscus_insight::rewards::{rewards, Medal};
|
||||
use fiscus_insight::subscriptions::analyse;
|
||||
use fiscus_ledger::goal::Colour;
|
||||
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
|
||||
use fiscus_ledger::project::{Kind, Status, TaskFields, TaskStatus};
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn ledger(bodies: Vec<EventBody>) -> State {
|
||||
let log: Vec<Event> = bodies.into_iter().enumerate().map(|(i, b)| Event::new(format!("e{i}"), Timestamp(0), b)).collect();
|
||||
let s = State::replay(&log);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
s
|
||||
}
|
||||
|
||||
fn made(id: &str, kind: Kind, starts: &str, ends: &str) -> EventBody {
|
||||
EventBody::ProjectCreated { project: id.into(), name: format!("Project {id}"), kind, template: None, starts: Some(d(starts)), ends: Some(d(ends)), colour: Colour::Blue, rate: Some(Haler(80_000)) }
|
||||
}
|
||||
|
||||
fn line(project: &str, id: &str, planned: i64) -> EventBody {
|
||||
EventBody::ProjectLineSet { project: project.into(), line: id.into(), name: id.to_uppercase(), planned: Haler(planned) }
|
||||
}
|
||||
|
||||
fn paid(id: &str, amount: i64, date: &str, merchant: &str, category: Option<&str>) -> EventBody {
|
||||
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: category.map(str::to_string), note: None }
|
||||
}
|
||||
|
||||
fn into(payment: &str, project: &str, line: Option<&str>) -> EventBody {
|
||||
EventBody::PaymentProjected { payment: payment.into(), project: project.into(), line: line.map(str::to_string) }
|
||||
}
|
||||
|
||||
fn task(id: &str, project: &str, due: Option<&str>, estimate: Option<i64>) -> EventBody {
|
||||
EventBody::TaskCreated {
|
||||
task: id.into(),
|
||||
project: project.into(),
|
||||
fields: TaskFields { title: format!("Task {id}"), phase: None, due: due.map(d), estimate: estimate.map(Haler), line: None, assignee: None, milestone: false },
|
||||
}
|
||||
}
|
||||
|
||||
fn done(task: &str, on: &str) -> EventBody {
|
||||
EventBody::TaskStatusSet { task: task.into(), status: TaskStatus::Done, on: d(on) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renovation_spent_by_line_by_hand_and_by_rule_within_its_dates() {
|
||||
let today = d("2026-11-20");
|
||||
let s = ledger(vec![
|
||||
made("flat", Kind::Simple, "2026-11-01", "2027-02-28"),
|
||||
line("flat", "kitchen", 12_000_000),
|
||||
line("flat", "tiles", 4_500_000),
|
||||
paid("p1", -9_000_000, "2026-11-04", "IKEA Zlicin", None),
|
||||
into("p1", "flat", Some("kitchen")),
|
||||
paid("p2", -5_000_000, "2026-11-06", "Siko koupelny", None),
|
||||
into("p2", "flat", Some("tiles")),
|
||||
paid("p3", -120_000, "2026-11-08", "Hornbach Cerny Most", None),
|
||||
paid("p4", -80_000, "2026-10-20", "Hornbach Cerny Most", None),
|
||||
paid("p5", -50_000, "2026-11-09", "Albert", Some("groceries")),
|
||||
EventBody::ProjectRuleSet { merchant_key: fiscus_ledger::merchant::merchant_key("Hornbach Cerny Most"), project: Some("flat".into()) },
|
||||
task("t1", "flat", Some("2026-11-10"), None),
|
||||
task("t2", "flat", Some("2026-12-10"), None),
|
||||
task("t3", "flat", None, None),
|
||||
done("t3", "2026-11-07"),
|
||||
]);
|
||||
let p = project(&s, "flat", today).unwrap();
|
||||
let lines: Vec<(&str, Haler, Haler, bool)> = p.lines.iter().map(|l| (l.id.as_str(), l.spent, l.left, l.over)).collect();
|
||||
assert_eq!(lines, [("kitchen", Haler(9_000_000), Haler(3_000_000), false), ("tiles", Haler(5_000_000), Haler(-500_000), true)]);
|
||||
// Hornbach in November by the rule (before the project started: not), Albert never.
|
||||
assert_eq!(p.unplanned, Haler(120_000));
|
||||
assert_eq!(p.summary.spent, Haler(14_120_000));
|
||||
assert_eq!(p.payments.iter().map(|x| (x.id.as_str(), x.by_rule)).collect::<Vec<_>>(), [("p3", true), ("p2", false), ("p1", false)]);
|
||||
assert_eq!((p.summary.planned, p.summary.over_budget), (Haler(16_500_000), false), "a line over is not the project over");
|
||||
// One task of three done (no estimates: by count); t1 is past its due date.
|
||||
assert_eq!((p.summary.progress_permille, p.summary.late_tasks, p.summary.late), (333, 1, true));
|
||||
assert_eq!((p.summary.tasks.todo, p.summary.tasks.done), (2, 1));
|
||||
assert_eq!(p.tasks.iter().map(|t| (t.task.id.as_str(), t.late)).collect::<Vec<_>>(), [("t1", true), ("t2", false), ("t3", false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_forecast_and_progress_by_estimates() {
|
||||
let today = d("2026-11-20");
|
||||
let s = ledger(vec![
|
||||
made("flat", Kind::Simple, "2026-11-01", "2027-02-28"),
|
||||
line("flat", "all", 10_000_000),
|
||||
paid("p1", -6_000_000, "2026-11-04", "Firma Novak", None),
|
||||
into("p1", "flat", Some("all")),
|
||||
task("t1", "flat", None, Some(6_000_000)),
|
||||
task("t2", "flat", None, Some(5_000_000)),
|
||||
done("t1", "2026-11-05"),
|
||||
]);
|
||||
let p = &projects(&s, today)[0];
|
||||
// 6 of 11 (by estimates) done; 6 spent + 5 to come = 11 > 10 planned.
|
||||
assert_eq!((p.progress_permille, p.open_estimates, p.forecast, p.over_budget), (545, Haler(5_000_000), Haler(11_000_000), true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_business_earns_from_paid_invoices_without_vat_and_never_twice() {
|
||||
let today = d("2026-11-20");
|
||||
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
|
||||
let invoice = |id: &str, number: &str| Invoice {
|
||||
id: id.into(),
|
||||
number: number.into(),
|
||||
issued: d("2026-11-05"),
|
||||
due: d("2026-11-19"),
|
||||
taxable: None,
|
||||
customer: party("Pekárna Novák", "45244782"),
|
||||
lines: vec![InvoiceLine { text: "Web".into(), quantity: 10_000, unit: "h".into(), unit_price: Haler(80_000), vat: None }],
|
||||
budget: None,
|
||||
language: Language::Cs,
|
||||
};
|
||||
let s = ledger(vec![
|
||||
made("web", Kind::Business, "2026-11-01", "2026-12-31"),
|
||||
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001") },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i2", "20260002") },
|
||||
EventBody::TimeLogged { entry: "l1".into(), project: "web".into(), task: None, minutes: 600, on: d("2026-11-03"), rate: Haler(80_000), note: String::new() },
|
||||
EventBody::TimeLogged { entry: "l2".into(), project: "web".into(), task: None, minutes: 90, on: d("2026-11-10"), rate: Haler(80_000), note: String::new() },
|
||||
EventBody::InvoiceProjected { invoice: "i1".into(), project: "web".into(), entries: vec!["l1".into()] },
|
||||
EventBody::InvoiceProjected { invoice: "i2".into(), project: "web".into(), entries: vec![] },
|
||||
// i1 marked paid by hand (its money in is not put into the project: the invoice is the income).
|
||||
EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-11-18") },
|
||||
// A tip from the client straight into the project; a tool bought for it.
|
||||
paid("in2", 50_000, "2026-11-19", "Pekarna Novak", Some("income")),
|
||||
into("in2", "web", None),
|
||||
paid("out1", -100_000, "2026-11-12", "Adobe", None),
|
||||
into("out1", "web", None),
|
||||
]);
|
||||
let p = project(&s, "web", today).unwrap();
|
||||
// i1 paid (8 000 Kč without VAT) and the tip (500 Kč); i2 is not paid yet.
|
||||
assert_eq!(p.summary.income, Haler(800_000 + 50_000));
|
||||
let s2 = ledger(vec![
|
||||
made("web", Kind::Business, "2026-11-01", "2026-12-31"),
|
||||
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001") },
|
||||
EventBody::InvoiceProjected { invoice: "i1".into(), project: "web".into(), entries: vec![] },
|
||||
EventBody::PaymentImported {
|
||||
payment: "line1".into(),
|
||||
line: fiscus_ledger::import::StatementLine {
|
||||
bank: "test".into(),
|
||||
account: "1/0000".into(),
|
||||
booked: d("2026-11-18"),
|
||||
amount: Haler(800_000),
|
||||
merchant: "Pekarna Novak".into(),
|
||||
counterparty: None,
|
||||
variable_symbol: Some("20260001".into()),
|
||||
message: None,
|
||||
bank_ref: None,
|
||||
},
|
||||
line_key: "k1".into(),
|
||||
},
|
||||
EventBody::InvoicePaid { invoice: "i1".into(), payment: Some("line1".into()), on: d("2026-11-18") },
|
||||
into("line1", "web", None),
|
||||
]);
|
||||
// A statement line that paid the project's invoice, put into the project too, is the invoice: counted once.
|
||||
assert_eq!(project(&s2, "web", today).unwrap().summary.income, Haler(800_000));
|
||||
|
||||
assert_eq!((p.summary.spent, p.summary.profit), (Haler(100_000), Haler(750_000)));
|
||||
assert_eq!(p.summary.margin_permille, Some(882));
|
||||
// 11 h 30 min logged; 10 h billed by i1, 1 h 30 min (1 200 Kč) not yet.
|
||||
assert_eq!((p.summary.minutes, p.summary.unbilled_minutes, p.summary.unbilled, p.billable), (690, 90, Haler(120_000), Haler(920_000)));
|
||||
assert_eq!(p.unbilled_entries, ["l2"]);
|
||||
assert_eq!(p.time_by_week, [(d("2026-11-02"), 600), (d("2026-11-09"), 90)]);
|
||||
assert_eq!((p.time_by_task[0].task.clone(), p.time_by_task[0].minutes), (None, 690));
|
||||
assert_eq!(p.invoices, ["i1", "i2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_late_past_its_end_and_the_medals_when_done() {
|
||||
let s = ledger(vec![
|
||||
made("trip", Kind::Simple, "2026-08-01", "2026-09-30"),
|
||||
line("trip", "all", 3_000_000),
|
||||
paid("p1", -2_500_000, "2026-08-15", "Booking.com", None),
|
||||
into("p1", "trip", None),
|
||||
task("t1", "trip", None, None),
|
||||
]);
|
||||
let today = d("2026-10-05");
|
||||
assert!(projects(&s, today)[0].late, "past its end with a task open");
|
||||
|
||||
let mut log = vec![
|
||||
made("trip", Kind::Simple, "2026-08-01", "2026-09-30"),
|
||||
line("trip", "all", 3_000_000),
|
||||
paid("p1", -2_500_000, "2026-08-15", "Booking.com", None),
|
||||
into("p1", "trip", None),
|
||||
task("t1", "trip", None, None),
|
||||
done("t1", "2026-09-20"),
|
||||
EventBody::ProjectStatusSet { project: "trip".into(), status: Status::Done, on: d("2026-09-25") },
|
||||
made("late", Kind::Simple, "2026-08-01", "2026-09-01"),
|
||||
line("late", "all", 100_000),
|
||||
paid("p2", -500_000, "2026-08-15", "Bauhaus", None),
|
||||
into("p2", "late", None),
|
||||
EventBody::ProjectStatusSet { project: "late".into(), status: Status::Done, on: d("2026-09-10") },
|
||||
];
|
||||
let s = ledger(std::mem::take(&mut log));
|
||||
assert!(!projects(&s, today).iter().any(|p| p.late), "a done project is never late");
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
||||
let got: Vec<(&str, Date)> = r
|
||||
.medals
|
||||
.iter()
|
||||
.filter_map(|e| match &e.medal {
|
||||
Medal::ProjectOnBudget { project, .. } => Some(("on budget", if project == "trip" { e.on } else { d("1970-01-01") })),
|
||||
Medal::FinishedOnTime { project, .. } => Some(("on time", if project == "trip" { e.on } else { d("1970-01-01") })),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(got, [("on budget", d("2026-09-25")), ("on time", d("2026-09-25"))], "the trip earns both; the late, over one neither");
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# 06: Projects (v0.7.0)
|
||||
|
||||
Projects plan and track a piece of work: a renovation or a trip (**simple**), or a side business or client work
|
||||
(**business**). A project is a **second label on payments**: a payment in a project still counts in its budget and
|
||||
its month, so nothing is counted twice. Projects live in the personal log, and the sharing boundary (`share.rs`)
|
||||
still builds only `payment.shared`.
|
||||
|
||||
## Events (`fiscus-ledger::project`)
|
||||
| Event | What |
|
||||
|:--|:--|
|
||||
| `project.created { project, name, kind, template?, starts?, ends?, colour, rate? }` | simple or business; a template id the app knows; an hourly rate for a business |
|
||||
| `project.changed { … }` | the latest counts. Once a project has phases or time it stays business |
|
||||
| `project.status_set { project, status, on }` | planning, active, on hold, done (`on` is the day) |
|
||||
| `project.line_set { project, line, name, planned }` | a budget line; a planned amount of 0 removes it |
|
||||
| `project.phase_set` / `project.phase_removed` | a business project's phase with dates; one still holding tasks is not removed |
|
||||
| `payment.projected { payment, project, line? }` / `payment.unprojected` | one project per payment, into an open project |
|
||||
| `project.rule_set { merchant_key, project? }` | "always this merchant → this project": payments within the project's dates, while it is open |
|
||||
| `task.created { task, project, fields }` / `task.changed` / `task.status_set` | title, phase, due, estimate, line, assignee, milestone; to do, doing, done (with the day) |
|
||||
| `time.logged { entry, project, task?, minutes, on, rate, note }` / `time.removed` | business only; invoiced time is not removed |
|
||||
| `invoice.projected { invoice, project, entries }` | an invoice for a business project, and the time entries it bills (each once) |
|
||||
|
||||
**What each event accepts:**
|
||||
- names: 1–60 characters, task titles 1–120, assignees 1–40;
|
||||
- amounts: 0–100 000 000 Kč;
|
||||
- hourly rates: 0–100 000 Kč;
|
||||
- dates: a project or phase cannot end before it starts;
|
||||
- at most 50 projects open, 100 budget lines, 50 phases and 200 open tasks per project;
|
||||
- time: at most 24 hours a day across all projects.
|
||||
|
||||
Every refusal changes nothing.
|
||||
|
||||
**Time** is minutes × the rate per hour, rounded half up to the haléř once per entry. Weeks start on Monday
|
||||
(`project::week_of`).
|
||||
|
||||
## A project's numbers (`fiscus-insight::projects`)
|
||||
`projects(state, today)` returns a summary per project: the open projects in the order they were made, then the
|
||||
done ones, the latest first. `project(state, id, today)` adds the details.
|
||||
|
||||
**What a summary holds:**
|
||||
- **planned**: all budget lines together.
|
||||
- **spent**: money out of the payments in the project, positive; transfers do not count.
|
||||
- **unplanned**: spent outside any line.
|
||||
- **lines**: planned, spent, left and over for each.
|
||||
- **income** (business):
|
||||
- paid invoices of the project, without VAT;
|
||||
- money in put into the project, except a statement line that paid one of the project's invoices: that line
|
||||
*is* the invoice, so it counts once.
|
||||
|
||||
If an invoice is marked paid by hand, its money in stays out of the project.
|
||||
- **profit**: income − spent. **margin**: profit of income, in thousandths.
|
||||
- **progress**: tasks done, by their estimates when every task has one, else by count.
|
||||
- **forecast**: spent + the open tasks' estimates.
|
||||
- **over budget**: spent or the forecast above the plan. One line over is not the project over.
|
||||
- **late**: an open task past its due date, or the project past its end with tasks open. A done project is never
|
||||
late.
|
||||
- **time**:
|
||||
- minutes, billable and unbilled;
|
||||
- time by task, and by week.
|
||||
|
||||
**Medals** (`rewards`), for a project that is done:
|
||||
- *Project on budget*: it had a plan, and it spent no more;
|
||||
- *Finished on time*: it had an end date, and it was done by it.
|
||||
|
||||
Both are earned on the day it was done.
|
||||
Reference in New Issue
Block a user