[insight] Projects: budget lines, payments in projects, tasks, phases, time and invoices; v0.7.0 #9
Generated
+4
-4
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-capture"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"proptest",
|
||||
@@ -150,7 +150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-insight"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"serde",
|
||||
@@ -159,7 +159,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-ledger"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -169,7 +169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-statement"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"fiscus-ledger",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
edition = "2021"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::date::{Date, Timestamp};
|
||||
use crate::goal::{ChallengeGoal, ChallengeId, Colour, GoalId, Way, WayKind};
|
||||
use crate::project::{EntryId, Kind, LineId, PhaseId, ProjectId, Status, TaskFields, TaskId, TaskStatus};
|
||||
use crate::import::StatementLine;
|
||||
use crate::invoice::{Invoice, InvoiceId, Supplier};
|
||||
use crate::money::Haler;
|
||||
@@ -187,4 +188,42 @@ pub enum EventBody {
|
||||
/// Given up; a challenge is given up once.
|
||||
#[serde(rename = "challenge.abandoned")]
|
||||
ChallengeAbandoned { challenge: ChallengeId, on: Date },
|
||||
/// A project (see [`crate::project`]): simple or business, from a template or empty.
|
||||
#[serde(rename = "project.created")]
|
||||
ProjectCreated { project: ProjectId, name: String, kind: Kind, template: Option<String>, starts: Option<Date>, ends: Option<Date>, colour: Colour, rate: Option<Haler> },
|
||||
/// Its name, kind, dates, colour or rate changed; the latest counts.
|
||||
#[serde(rename = "project.changed")]
|
||||
ProjectChanged { project: ProjectId, name: String, kind: Kind, starts: Option<Date>, ends: Option<Date>, colour: Colour, rate: Option<Haler> },
|
||||
#[serde(rename = "project.status_set")]
|
||||
ProjectStatusSet { project: ProjectId, status: Status, on: Date },
|
||||
/// A budget line: its name and planned amount. Zero planned removes it.
|
||||
#[serde(rename = "project.line_set")]
|
||||
ProjectLineSet { project: ProjectId, line: LineId, name: String, planned: Haler },
|
||||
/// A phase of a project, from `starts` to `ends`.
|
||||
#[serde(rename = "project.phase_set")]
|
||||
ProjectPhaseSet { project: ProjectId, phase: PhaseId, name: String, starts: Date, ends: Date },
|
||||
#[serde(rename = "project.phase_removed")]
|
||||
ProjectPhaseRemoved { project: ProjectId, phase: PhaseId },
|
||||
/// A payment put into a project (and one of its lines). One project per payment; it stays in its budget.
|
||||
#[serde(rename = "payment.projected")]
|
||||
PaymentProjected { payment: PaymentId, project: ProjectId, line: Option<LineId> },
|
||||
#[serde(rename = "payment.unprojected")]
|
||||
PaymentUnprojected { payment: PaymentId },
|
||||
/// "Always <merchant key> → <project>"; `None` removes the rule. It stops when the project is done.
|
||||
#[serde(rename = "project.rule_set")]
|
||||
ProjectRuleSet { merchant_key: String, project: Option<ProjectId> },
|
||||
#[serde(rename = "task.created")]
|
||||
TaskCreated { task: TaskId, project: ProjectId, fields: TaskFields },
|
||||
#[serde(rename = "task.changed")]
|
||||
TaskChanged { task: TaskId, fields: TaskFields },
|
||||
#[serde(rename = "task.status_set")]
|
||||
TaskStatusSet { task: TaskId, status: TaskStatus, on: Date },
|
||||
/// Time worked on a business project (a task of it, or the project as a whole), at an hourly rate.
|
||||
#[serde(rename = "time.logged")]
|
||||
TimeLogged { entry: EntryId, project: ProjectId, task: Option<TaskId>, minutes: u32, on: Date, rate: Haler, note: String },
|
||||
#[serde(rename = "time.removed")]
|
||||
TimeRemoved { entry: EntryId },
|
||||
/// An invoice issued for a business project, and the time entries it bills (none: not from time).
|
||||
#[serde(rename = "invoice.projected")]
|
||||
InvoiceProjected { invoice: InvoiceId, project: ProjectId, entries: Vec<EntryId> },
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod matching;
|
||||
pub mod merchant;
|
||||
pub mod money;
|
||||
pub mod pay;
|
||||
pub mod project;
|
||||
pub mod share;
|
||||
pub mod split;
|
||||
pub mod state;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! Projects: planning and tracking a piece of work with its own budget, tasks and (for a business) phases, time
|
||||
//! and income. A project is a second label on payments: a payment in a project still counts in its budget and in
|
||||
//! the month, so nothing is counted twice. Personal log only, like plans and goals.
|
||||
|
||||
use crate::date::Date;
|
||||
use crate::event::PaymentId;
|
||||
use crate::goal::Colour;
|
||||
use crate::invoice::InvoiceId;
|
||||
use crate::money::Haler;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub type ProjectId = String;
|
||||
pub type TaskId = String;
|
||||
pub type LineId = String;
|
||||
pub type PhaseId = String;
|
||||
pub type EntryId = String;
|
||||
|
||||
/// At most this many projects not done at once.
|
||||
pub const MAX_OPEN_PROJECTS: usize = 50;
|
||||
/// Per project: budget lines, phases, and tasks not done.
|
||||
pub const MAX_LINES: usize = 100;
|
||||
pub const MAX_PHASES: usize = 50;
|
||||
pub const MAX_OPEN_TASKS: usize = 200;
|
||||
/// A planned amount, an estimate: 0 to 100 000 000 Kč.
|
||||
pub const MAX_AMOUNT: Haler = Haler(10_000_000_000);
|
||||
/// An hourly rate: 0 to 100 000 Kč.
|
||||
pub const MAX_RATE: Haler = Haler(10_000_000);
|
||||
/// Time logged on one day across all projects: at most 24 hours.
|
||||
pub const MAX_MINUTES_A_DAY: u32 = 24 * 60;
|
||||
|
||||
/// Simple (a renovation, a trip): a budget and a checklist. Business (a side business, client work): also
|
||||
/// income, phases, a timeline and time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Kind {
|
||||
Simple,
|
||||
Business,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Status {
|
||||
Planning,
|
||||
Active,
|
||||
OnHold,
|
||||
Done,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TaskStatus {
|
||||
Todo,
|
||||
Doing,
|
||||
Done,
|
||||
}
|
||||
|
||||
/// A task's fields as `task.created` and `task.changed` carry them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TaskFields {
|
||||
pub title: String,
|
||||
pub phase: Option<PhaseId>,
|
||||
pub due: Option<Date>,
|
||||
pub estimate: Option<Haler>,
|
||||
pub line: Option<LineId>,
|
||||
pub assignee: Option<String>,
|
||||
pub milestone: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Line {
|
||||
pub id: LineId,
|
||||
pub name: String,
|
||||
pub planned: Haler,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Phase {
|
||||
pub id: PhaseId,
|
||||
pub name: String,
|
||||
pub starts: Date,
|
||||
pub ends: Date,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProjectRecord {
|
||||
pub id: ProjectId,
|
||||
pub name: String,
|
||||
pub kind: Kind,
|
||||
pub template: Option<String>,
|
||||
pub starts: Option<Date>,
|
||||
pub ends: Option<Date>,
|
||||
pub colour: Colour,
|
||||
/// The hourly rate time is logged at unless an entry says otherwise (business).
|
||||
pub rate: Option<Haler>,
|
||||
pub status: Status,
|
||||
/// When the status was last set (the day a project was done).
|
||||
pub status_on: Option<Date>,
|
||||
/// In the order made.
|
||||
pub lines: Vec<Line>,
|
||||
pub phases: Vec<Phase>,
|
||||
/// Invoices issued for this project.
|
||||
pub invoices: BTreeSet<InvoiceId>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
impl ProjectRecord {
|
||||
pub fn is_open(&self) -> bool {
|
||||
self.status != Status::Done
|
||||
}
|
||||
|
||||
pub fn line(&self, id: &str) -> Option<&Line> {
|
||||
self.lines.iter().find(|l| l.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TaskRecord {
|
||||
pub id: TaskId,
|
||||
pub project: ProjectId,
|
||||
pub fields: TaskFields,
|
||||
pub status: TaskStatus,
|
||||
/// The day it was done.
|
||||
pub done_on: Option<Date>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TimeEntry {
|
||||
pub id: EntryId,
|
||||
pub project: ProjectId,
|
||||
pub task: Option<TaskId>,
|
||||
pub minutes: u32,
|
||||
pub on: Date,
|
||||
/// Per hour.
|
||||
pub rate: Haler,
|
||||
pub note: String,
|
||||
/// The invoice that billed it.
|
||||
pub invoice: Option<InvoiceId>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
impl TimeEntry {
|
||||
/// What the entry is worth: minutes × the hourly rate, rounded to the haléř (half up).
|
||||
pub fn amount(&self) -> Haler {
|
||||
let v = (i128::from(self.minutes) * i128::from(self.rate.0) + 30) / 60;
|
||||
Haler(i64::try_from(v).unwrap_or(i64::MAX))
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything about projects in a ledger.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Projects {
|
||||
pub projects: BTreeMap<ProjectId, ProjectRecord>,
|
||||
pub tasks: BTreeMap<TaskId, TaskRecord>,
|
||||
pub time: BTreeMap<EntryId, TimeEntry>,
|
||||
/// A payment put into a project (and a line) by hand.
|
||||
pub payments: BTreeMap<PaymentId, (ProjectId, Option<LineId>)>,
|
||||
/// "Always this merchant → this project", by merchant key.
|
||||
pub rules: BTreeMap<String, ProjectId>,
|
||||
}
|
||||
|
||||
/// The Monday of `d`'s week.
|
||||
pub fn week_of(d: Date) -> Date {
|
||||
// 1970-01-01 was a Thursday.
|
||||
d.add_days(-(d.days() + 3).rem_euclid(7))
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use crate::date::Date;
|
||||
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
|
||||
use crate::goal::{self, ChallengeGoal, ChallengeId, ChallengeRecord, GoalId, GoalRecord, Saving, Way, WayKind};
|
||||
use crate::import::StatementLine;
|
||||
use crate::project::{self, Line, Phase, ProjectRecord, Projects, TaskRecord, TaskStatus, TimeEntry};
|
||||
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
|
||||
use crate::merchant::merchant_key;
|
||||
use crate::money::Haler;
|
||||
@@ -234,6 +235,8 @@ pub struct State {
|
||||
pub saving_ids: BTreeSet<String>,
|
||||
/// Challenges by id (`challenge.*`).
|
||||
pub challenges: BTreeMap<ChallengeId, ChallengeRecord>,
|
||||
/// Projects, their tasks, time, and the payments put into them (`project.*`, `task.*`, `time.*`).
|
||||
pub projects: Projects,
|
||||
pub rejected: Vec<Rejection>,
|
||||
}
|
||||
|
||||
@@ -287,6 +290,42 @@ fn name_ok(s: &str, max: usize) -> bool {
|
||||
!s.trim().is_empty() && s.chars().count() <= max && text_ok(s)
|
||||
}
|
||||
|
||||
/// A project's name, dates and rate, for `project.created` and `project.changed`.
|
||||
fn project_fields(name: &str, starts: Option<Date>, ends: Option<Date>, rate: Option<Haler>) -> Result<(), &'static str> {
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
return Err("a project name must be 1-60 characters");
|
||||
}
|
||||
if let (Some(s), Some(e)) = (starts, ends) {
|
||||
if e < s {
|
||||
return Err("a project ends before it starts");
|
||||
}
|
||||
}
|
||||
if rate.is_some_and(|r| r.0 < 0 || r > project::MAX_RATE) {
|
||||
return Err("an hourly rate is 0-100 000 CZK");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A task's fields, checked against its project.
|
||||
fn task_fields(p: &ProjectRecord, f: &project::TaskFields) -> Result<(), &'static str> {
|
||||
if !name_ok(&f.title, 120) || f.title.trim() != f.title {
|
||||
return Err("a task title must be 1-120 characters");
|
||||
}
|
||||
if f.phase.as_ref().is_some_and(|ph| !p.phases.iter().any(|x| &x.id == ph)) {
|
||||
return Err("no such phase in the project");
|
||||
}
|
||||
if f.line.as_ref().is_some_and(|l| p.line(l).is_none()) {
|
||||
return Err("no such budget line in the project");
|
||||
}
|
||||
if f.estimate.is_some_and(|e| e.0 < 0 || e > project::MAX_AMOUNT) {
|
||||
return Err("an estimate is 0-100 000 000 CZK");
|
||||
}
|
||||
if f.assignee.as_ref().is_some_and(|a| !name_ok(a, 40) || a.trim() != a) {
|
||||
return Err("an assignee name must be 1-40 characters");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A goal's name and target, for `goal.created` and `goal.changed`.
|
||||
fn goal_fields(name: &str, target: Haler) -> Result<(), &'static str> {
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
@@ -911,10 +950,238 @@ impl State {
|
||||
}
|
||||
c.abandoned = Some(*on);
|
||||
}
|
||||
EventBody::ProjectCreated { project, name, kind, template, starts, ends, colour, rate } => {
|
||||
if !id_ok(project) || self.projects.projects.contains_key(project) {
|
||||
return Err("a project with this id exists");
|
||||
}
|
||||
project_fields(name, *starts, *ends, *rate)?;
|
||||
if template.as_ref().is_some_and(|t| !id_ok(t)) {
|
||||
return Err("not a template id");
|
||||
}
|
||||
if self.projects.projects.values().filter(|p| p.is_open()).count() >= project::MAX_OPEN_PROJECTS {
|
||||
return Err("at most 50 projects are open at once");
|
||||
}
|
||||
self.projects.projects.insert(
|
||||
project.clone(),
|
||||
ProjectRecord {
|
||||
id: project.clone(),
|
||||
name: name.clone(),
|
||||
kind: *kind,
|
||||
template: template.clone(),
|
||||
starts: *starts,
|
||||
ends: *ends,
|
||||
colour: *colour,
|
||||
rate: *rate,
|
||||
status: project::Status::Active,
|
||||
status_on: None,
|
||||
lines: Vec::new(),
|
||||
phases: Vec::new(),
|
||||
invoices: BTreeSet::new(),
|
||||
seq,
|
||||
},
|
||||
);
|
||||
}
|
||||
EventBody::ProjectChanged { project, name, kind, starts, ends, colour, rate } => {
|
||||
project_fields(name, *starts, *ends, *rate)?;
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if *kind == project::Kind::Simple && (!p.phases.is_empty() || self.projects.time.values().any(|t| &t.project == project)) {
|
||||
return Err("a project with phases or time stays a business project");
|
||||
}
|
||||
(p.name, p.kind, p.starts, p.ends, p.colour, p.rate) = (name.clone(), *kind, *starts, *ends, *colour, *rate);
|
||||
}
|
||||
EventBody::ProjectStatusSet { project, status, on } => {
|
||||
let reopening = *status != project::Status::Done;
|
||||
let open = self.projects.projects.values().filter(|p| p.is_open()).count();
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if reopening && !p.is_open() && open >= project::MAX_OPEN_PROJECTS {
|
||||
return Err("at most 50 projects are open at once");
|
||||
}
|
||||
p.status = *status;
|
||||
p.status_on = Some(*on);
|
||||
}
|
||||
EventBody::ProjectLineSet { project, line, name, planned } => {
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if !id_ok(line) {
|
||||
return Err("not a line id");
|
||||
}
|
||||
if planned.0 < 0 || *planned > project::MAX_AMOUNT {
|
||||
return Err("a planned amount is 0-100 000 000 CZK");
|
||||
}
|
||||
if planned.0 == 0 {
|
||||
p.lines.retain(|l| &l.id != line);
|
||||
} else {
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
return Err("a budget line name must be 1-60 characters");
|
||||
}
|
||||
match p.lines.iter().position(|l| &l.id == line) {
|
||||
Some(i) => (p.lines[i].name, p.lines[i].planned) = (name.clone(), *planned),
|
||||
None if p.lines.len() >= project::MAX_LINES => return Err("at most 100 budget lines a project"),
|
||||
None => p.lines.push(Line { id: line.clone(), name: name.clone(), planned: *planned, seq }),
|
||||
}
|
||||
}
|
||||
}
|
||||
EventBody::ProjectPhaseSet { project, phase, name, starts, ends } => {
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if p.kind != project::Kind::Business {
|
||||
return Err("only a business project has phases");
|
||||
}
|
||||
if !id_ok(phase) {
|
||||
return Err("not a phase id");
|
||||
}
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
return Err("a phase name must be 1-60 characters");
|
||||
}
|
||||
if ends < starts {
|
||||
return Err("a phase ends before it starts");
|
||||
}
|
||||
match p.phases.iter().position(|x| &x.id == phase) {
|
||||
Some(i) => (p.phases[i].name, p.phases[i].starts, p.phases[i].ends) = (name.clone(), *starts, *ends),
|
||||
None if p.phases.len() >= project::MAX_PHASES => return Err("at most 50 phases a project"),
|
||||
None => p.phases.push(Phase { id: phase.clone(), name: name.clone(), starts: *starts, ends: *ends }),
|
||||
}
|
||||
}
|
||||
EventBody::ProjectPhaseRemoved { project, phase } => {
|
||||
if self.projects.tasks.values().any(|t| &t.project == project && t.fields.phase.as_ref() == Some(phase)) {
|
||||
return Err("tasks are still in this phase");
|
||||
}
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
let before = p.phases.len();
|
||||
p.phases.retain(|x| &x.id != phase);
|
||||
if p.phases.len() == before {
|
||||
return Err("no such phase in the project");
|
||||
}
|
||||
}
|
||||
EventBody::PaymentProjected { payment, project, line } => {
|
||||
if self.effective_payment(payment).is_none() {
|
||||
return Err("no such payment");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
if !p.is_open() {
|
||||
return Err("the project is done");
|
||||
}
|
||||
if line.as_ref().is_some_and(|l| p.line(l).is_none()) {
|
||||
return Err("no such budget line in the project");
|
||||
}
|
||||
self.projects.payments.insert(payment.clone(), (project.clone(), line.clone()));
|
||||
}
|
||||
EventBody::PaymentUnprojected { payment } => {
|
||||
if self.projects.payments.remove(payment).is_none() {
|
||||
return Err("this payment is in no project");
|
||||
}
|
||||
}
|
||||
EventBody::ProjectRuleSet { merchant_key: key, project } => {
|
||||
if key.is_empty() || merchant_key(key) != *key {
|
||||
return Err("not a merchant key");
|
||||
}
|
||||
match project {
|
||||
Some(id) => {
|
||||
if !self.projects.projects.get(id).is_some_and(ProjectRecord::is_open) {
|
||||
return Err("no such open project");
|
||||
}
|
||||
self.projects.rules.insert(key.clone(), id.clone());
|
||||
}
|
||||
None => {
|
||||
self.projects.rules.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
EventBody::TaskCreated { task, project, fields } => {
|
||||
if !id_ok(task) || self.projects.tasks.contains_key(task) {
|
||||
return Err("a task with this id exists");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
task_fields(p, fields)?;
|
||||
if self.projects.tasks.values().filter(|t| &t.project == project && t.status != TaskStatus::Done).count() >= project::MAX_OPEN_TASKS {
|
||||
return Err("at most 200 open tasks a project");
|
||||
}
|
||||
self.projects.tasks.insert(task.clone(), TaskRecord { id: task.clone(), project: project.clone(), fields: fields.clone(), status: TaskStatus::Todo, done_on: None, seq });
|
||||
}
|
||||
EventBody::TaskChanged { task, fields } => {
|
||||
let t = self.projects.tasks.get(task).ok_or("no such task")?;
|
||||
let p = self.projects.projects.get(&t.project).ok_or("no such project")?;
|
||||
task_fields(p, fields)?;
|
||||
self.projects.tasks.get_mut(task).expect("checked").fields = fields.clone();
|
||||
}
|
||||
EventBody::TaskStatusSet { task, status, on } => {
|
||||
let t = self.projects.tasks.get_mut(task).ok_or("no such task")?;
|
||||
t.status = *status;
|
||||
t.done_on = (*status == TaskStatus::Done).then_some(*on);
|
||||
}
|
||||
EventBody::TimeLogged { entry, project, task, minutes, on, rate, note } => {
|
||||
if !id_ok(entry) || self.projects.time.contains_key(entry) {
|
||||
return Err("a time entry with this id exists");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
if p.kind != project::Kind::Business {
|
||||
return Err("only a business project logs time");
|
||||
}
|
||||
if task.as_ref().is_some_and(|t| !self.projects.tasks.get(t).is_some_and(|x| &x.project == project)) {
|
||||
return Err("no such task in the project");
|
||||
}
|
||||
let day: u32 = self.projects.time.values().filter(|t| t.on == *on).map(|t| t.minutes).sum();
|
||||
if *minutes == 0 || day + minutes > project::MAX_MINUTES_A_DAY {
|
||||
return Err("time logged is 1 minute to 24 hours a day");
|
||||
}
|
||||
if rate.0 < 0 || *rate > project::MAX_RATE {
|
||||
return Err("an hourly rate is 0-100 000 CZK");
|
||||
}
|
||||
if note.chars().count() > 200 || !text_ok(note) {
|
||||
return Err("a note is at most 200 characters");
|
||||
}
|
||||
self.projects.time.insert(
|
||||
entry.clone(),
|
||||
TimeEntry { id: entry.clone(), project: project.clone(), task: task.clone(), minutes: *minutes, on: *on, rate: *rate, note: note.clone(), invoice: None, seq },
|
||||
);
|
||||
}
|
||||
EventBody::TimeRemoved { entry } => {
|
||||
let t = self.projects.time.get(entry).ok_or("no such time entry")?;
|
||||
if t.invoice.is_some() {
|
||||
return Err("this time is invoiced");
|
||||
}
|
||||
self.projects.time.remove(entry);
|
||||
}
|
||||
EventBody::InvoiceProjected { invoice, project, entries } => {
|
||||
if !self.invoices.contains_key(invoice) {
|
||||
return Err("no such invoice");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
if p.kind != project::Kind::Business {
|
||||
return Err("only a business project has invoices");
|
||||
}
|
||||
if self.projects.projects.values().any(|x| x.invoices.contains(invoice)) {
|
||||
return Err("this invoice is in a project already");
|
||||
}
|
||||
if entries.iter().collect::<BTreeSet<_>>().len() != entries.len() {
|
||||
return Err("a time entry appears twice");
|
||||
}
|
||||
for e in entries {
|
||||
match self.projects.time.get(e) {
|
||||
Some(t) if &t.project == project && t.invoice.is_none() => {}
|
||||
Some(t) if t.invoice.is_some() => return Err("this time is invoiced"),
|
||||
_ => return Err("no such time entry in the project"),
|
||||
}
|
||||
}
|
||||
for e in entries {
|
||||
self.projects.time.get_mut(e).expect("checked").invoice = Some(invoice.clone());
|
||||
}
|
||||
self.projects.projects.get_mut(project).expect("checked").invoices.insert(invoice.clone());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The project a payment is in, and its line: put there by hand, else by a project rule of its merchant while
|
||||
/// the project is open and the payment falls in the project's dates.
|
||||
pub fn project_of(&self, p: &EffectivePayment) -> Option<(String, Option<String>)> {
|
||||
if let Some((project, line)) = self.projects.payments.get(&p.id) {
|
||||
return Some((project.clone(), line.clone()));
|
||||
}
|
||||
let id = self.projects.rules.get(&p.merchant_key)?;
|
||||
let rec = self.projects.projects.get(id)?;
|
||||
let in_dates = rec.starts.is_none_or(|s| p.date >= s) && rec.ends.is_none_or(|e| p.date <= e);
|
||||
(rec.is_open() && in_dates).then(|| (id.clone(), None))
|
||||
}
|
||||
|
||||
/// A default category or one of your own.
|
||||
pub fn category_known(&self, id: &str) -> bool {
|
||||
categories::DEFAULT.iter().any(|(d, _)| *d == id) || self.custom_categories.contains_key(id)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Projects in the ledger: what is accepted, and every refusal changing nothing. A done project takes no more
|
||||
//! payments, a simple project has no phases or time, time never passes 24 hours a day, and an entry is
|
||||
//! invoiced once.
|
||||
|
||||
use fiscus_ledger::goal::Colour;
|
||||
use fiscus_ledger::project::{week_of, Kind, Status, TaskFields, TaskStatus};
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn ev(id: &str, body: EventBody) -> Event {
|
||||
Event::new(id, Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn project(id: &str, kind: Kind) -> EventBody {
|
||||
EventBody::ProjectCreated { project: id.into(), name: "Flat".into(), kind, template: Some("renovation".into()), starts: Some(d("2026-11-01")), ends: Some(d("2027-02-28")), colour: Colour::Teal, rate: Some(Haler(80_000)) }
|
||||
}
|
||||
|
||||
fn task(id: &str, project: &str, title: &str) -> EventBody {
|
||||
EventBody::TaskCreated { task: id.into(), project: project.into(), fields: fields(title) }
|
||||
}
|
||||
|
||||
fn fields(title: &str) -> TaskFields {
|
||||
TaskFields { title: title.into(), phase: None, due: None, estimate: None, line: None, assignee: None, milestone: false }
|
||||
}
|
||||
|
||||
fn payment(id: &str, amount: i64, date: &str, merchant: &str) -> EventBody {
|
||||
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: None, note: None }
|
||||
}
|
||||
|
||||
fn log(entry: &str, project: &str, minutes: u32, on: &str) -> EventBody {
|
||||
EventBody::TimeLogged { entry: entry.into(), project: project.into(), task: None, minutes, on: d(on), rate: Haler(80_000), note: String::new() }
|
||||
}
|
||||
|
||||
/// The base ledger, then `body`: the reason it was refused, or `None` when it was accepted.
|
||||
fn refusal(base: &[EventBody], body: EventBody) -> Option<String> {
|
||||
let mut log: Vec<Event> = base.iter().enumerate().map(|(i, b)| ev(&format!("b{i}"), b.clone())).collect();
|
||||
let before = State::replay(&log);
|
||||
assert!(before.rejected.is_empty(), "{:?}", before.rejected);
|
||||
log.push(ev("x", body));
|
||||
let after = State::replay(&log);
|
||||
match after.rejected.last() {
|
||||
Some(r) => {
|
||||
assert_eq!(after.projects, before.projects, "a refusal changes no project");
|
||||
Some(r.reason.clone())
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_its_lines_tasks_and_payments() {
|
||||
let s = State::replay(&[
|
||||
ev("e1", project("p1", Kind::Simple)),
|
||||
ev("e2", EventBody::ProjectLineSet { project: "p1".into(), line: "kitchen".into(), name: "Kitchen".into(), planned: Haler(12_000_000) }),
|
||||
ev("e3", EventBody::ProjectLineSet { project: "p1".into(), line: "tiles".into(), name: "Tiles".into(), planned: Haler(4_500_000) }),
|
||||
ev("e4", EventBody::ProjectLineSet { project: "p1".into(), line: "tiles".into(), name: "Tiles and grout".into(), planned: Haler(5_000_000) }),
|
||||
ev("e5", task("t1", "p1", "Order the kitchen")),
|
||||
ev("e6", EventBody::TaskStatusSet { task: "t1".into(), status: TaskStatus::Done, on: d("2026-11-05") }),
|
||||
ev("e7", payment("pay1", -1_250_000, "2026-11-04", "IKEA Zlicin")),
|
||||
ev("e8", EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: Some("kitchen".into()) }),
|
||||
ev("e9", EventBody::ProjectLineSet { project: "p1".into(), line: "kitchen".into(), name: "Kitchen".into(), planned: Haler(0) }),
|
||||
]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
let p = &s.projects.projects["p1"];
|
||||
assert_eq!(p.lines.iter().map(|l| (l.name.as_str(), l.planned)).collect::<Vec<_>>(), [("Tiles and grout", Haler(5_000_000))], "zero removes a line");
|
||||
assert_eq!((p.status, p.kind), (Status::Active, Kind::Simple));
|
||||
let t = &s.projects.tasks["t1"];
|
||||
assert_eq!((t.status, t.done_on), (TaskStatus::Done, Some(d("2026-11-05"))));
|
||||
assert_eq!(s.projects.payments["pay1"], ("p1".to_string(), Some("kitchen".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_is_checked_when_made_and_changed() {
|
||||
let made = |name: &str, starts: &str, ends: &str, rate: i64| EventBody::ProjectCreated {
|
||||
project: "p1".into(),
|
||||
name: name.into(),
|
||||
kind: Kind::Business,
|
||||
template: None,
|
||||
starts: Some(d(starts)),
|
||||
ends: Some(d(ends)),
|
||||
colour: Colour::Amber,
|
||||
rate: Some(Haler(rate)),
|
||||
};
|
||||
assert_eq!(refusal(&[], made("", "2026-11-01", "2026-12-01", 0)).as_deref(), Some("a project name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], made(" Web", "2026-11-01", "2026-12-01", 0)).as_deref(), Some("a project name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], made("Web", "2026-12-01", "2026-11-01", 0)).as_deref(), Some("a project ends before it starts"));
|
||||
assert_eq!(refusal(&[], made("Web", "2026-11-01", "2026-12-01", -1)).as_deref(), Some("an hourly rate is 0-100 000 CZK"));
|
||||
assert_eq!(refusal(&[], made("Web", "2026-11-01", "2026-12-01", 10_000_001)).as_deref(), Some("an hourly rate is 0-100 000 CZK"));
|
||||
assert_eq!(refusal(&[project("p1", Kind::Simple)], project("p1", Kind::Simple)).as_deref(), Some("a project with this id exists"));
|
||||
let fifty: Vec<EventBody> = (0..50).map(|i| project(&format!("p{i}"), Kind::Simple)).collect();
|
||||
assert_eq!(refusal(&fifty, project("p50", Kind::Simple)).as_deref(), Some("at most 50 projects are open at once"));
|
||||
let mut one_done = fifty.clone();
|
||||
one_done.push(EventBody::ProjectStatusSet { project: "p3".into(), status: Status::Done, on: d("2026-11-20") });
|
||||
assert_eq!(refusal(&one_done, project("p50", Kind::Simple)), None, "a done project frees its place");
|
||||
let mut full_again = one_done.clone();
|
||||
full_again.push(project("p50", Kind::Simple));
|
||||
assert_eq!(refusal(&full_again, EventBody::ProjectStatusSet { project: "p3".into(), status: Status::Active, on: d("2026-11-21") }).as_deref(), Some("at most 50 projects are open at once"), "nor can it reopen into a full list");
|
||||
|
||||
let base = [project("p1", Kind::Business), log("l1", "p1", 60, "2026-11-02")];
|
||||
let to_simple = EventBody::ProjectChanged { project: "p1".into(), name: "Flat".into(), kind: Kind::Simple, starts: None, ends: None, colour: Colour::Coral, rate: None };
|
||||
assert_eq!(refusal(&base, to_simple).as_deref(), Some("a project with phases or time stays a business project"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_phases_and_tasks_are_checked() {
|
||||
let base = [project("p1", Kind::Simple), project("b1", Kind::Business)];
|
||||
let line = |planned: i64, name: &str| EventBody::ProjectLineSet { project: "p1".into(), line: "l".into(), name: name.into(), planned: Haler(planned) };
|
||||
assert_eq!(refusal(&base, line(-1, "Tiles")).as_deref(), Some("a planned amount is 0-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, line(10_000_000_001, "Tiles")).as_deref(), Some("a planned amount is 0-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, line(100, "")).as_deref(), Some("a budget line name must be 1-60 characters"));
|
||||
let phase = |project: &str, starts: &str, ends: &str| EventBody::ProjectPhaseSet { project: project.into(), phase: "ph1".into(), name: "Design".into(), starts: d(starts), ends: d(ends) };
|
||||
assert_eq!(refusal(&base, phase("p1", "2026-11-01", "2026-11-30")).as_deref(), Some("only a business project has phases"));
|
||||
assert_eq!(refusal(&base, phase("b1", "2026-11-30", "2026-11-01")).as_deref(), Some("a phase ends before it starts"));
|
||||
assert_eq!(refusal(&base, phase("b1", "2026-11-01", "2026-11-30")), None);
|
||||
|
||||
let mut f = fields("Tile the bathroom");
|
||||
f.line = Some("nope".into());
|
||||
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "p1".into(), fields: f }).as_deref(), Some("no such budget line in the project"));
|
||||
let mut f = fields("Tile the bathroom");
|
||||
f.phase = Some("nope".into());
|
||||
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "b1".into(), fields: f }).as_deref(), Some("no such phase in the project"));
|
||||
let mut f = fields("Tile the bathroom");
|
||||
f.estimate = Some(Haler(-1));
|
||||
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "p1".into(), fields: f }).as_deref(), Some("an estimate is 0-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, task("t", "p1", "")).as_deref(), Some("a task title must be 1-120 characters"));
|
||||
assert_eq!(refusal(&base, task("t", "nope", "Tile")).as_deref(), Some("no such project"));
|
||||
let two_hundred: Vec<EventBody> = std::iter::once(project("p1", Kind::Simple)).chain((0..200).map(|i| task(&format!("t{i}"), "p1", "Job"))).collect();
|
||||
assert_eq!(refusal(&two_hundred, task("t200", "p1", "One more")).as_deref(), Some("at most 200 open tasks a project"));
|
||||
|
||||
let with_task = [project("b1", Kind::Business), phase("b1", "2026-11-01", "2026-11-30"), EventBody::TaskCreated { task: "t".into(), project: "b1".into(), fields: TaskFields { phase: Some("ph1".into()), ..fields("Wireframes") } }];
|
||||
assert_eq!(refusal(&with_task, EventBody::ProjectPhaseRemoved { project: "b1".into(), phase: "ph1".into() }).as_deref(), Some("tasks are still in this phase"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payments_go_into_an_open_project_once() {
|
||||
let base = [project("p1", Kind::Simple), payment("pay1", -50_000, "2026-11-03", "Hornbach")];
|
||||
assert_eq!(refusal(&base, EventBody::PaymentProjected { payment: "nope".into(), project: "p1".into(), line: None }).as_deref(), Some("no such payment"));
|
||||
assert_eq!(refusal(&base, EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: Some("nope".into()) }).as_deref(), Some("no such budget line in the project"));
|
||||
assert_eq!(refusal(&base, EventBody::PaymentUnprojected { payment: "pay1".into() }).as_deref(), Some("this payment is in no project"));
|
||||
let mut done = base.to_vec();
|
||||
done.push(EventBody::ProjectStatusSet { project: "p1".into(), status: Status::Done, on: d("2026-11-10") });
|
||||
assert_eq!(refusal(&done, EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: None }).as_deref(), Some("the project is done"));
|
||||
assert_eq!(refusal(&done, EventBody::ProjectRuleSet { merchant_key: "hornbach".into(), project: Some("p1".into()) }).as_deref(), Some("no such open project"));
|
||||
assert_eq!(refusal(&base, EventBody::ProjectRuleSet { merchant_key: "Hornbach Praha".into(), project: Some("p1".into()) }).as_deref(), Some("not a merchant key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_is_business_only_never_over_a_day_and_invoiced_once() {
|
||||
let base = [project("p1", Kind::Simple), project("b1", Kind::Business), log("l1", "b1", 600, "2026-11-02")];
|
||||
assert_eq!(refusal(&base, log("l2", "p1", 60, "2026-11-02")).as_deref(), Some("only a business project logs time"));
|
||||
assert_eq!(refusal(&base, log("l2", "b1", 0, "2026-11-02")).as_deref(), Some("time logged is 1 minute to 24 hours a day"));
|
||||
assert_eq!(refusal(&base, log("l2", "b1", 841, "2026-11-02")).as_deref(), Some("time logged is 1 minute to 24 hours a day"));
|
||||
assert_eq!(refusal(&base, log("l2", "b1", 840, "2026-11-02")), None, "exactly 24 hours");
|
||||
assert_eq!(refusal(&base, log("l1", "b1", 60, "2026-11-03")).as_deref(), Some("a time entry with this id exists"));
|
||||
assert_eq!(
|
||||
refusal(&base, EventBody::TimeLogged { entry: "l2".into(), project: "b1".into(), task: Some("nope".into()), minutes: 60, on: d("2026-11-03"), rate: Haler(0), note: String::new() }).as_deref(),
|
||||
Some("no such task in the project")
|
||||
);
|
||||
// An invoice for the project bills the entry once; billed time stays.
|
||||
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
|
||||
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 = Invoice {
|
||||
id: "i1".into(),
|
||||
number: "20260001".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 mut billed = base.to_vec();
|
||||
billed.push(EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } });
|
||||
billed.push(EventBody::InvoiceIssued { invoice });
|
||||
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "p1".into(), entries: vec![] }).as_deref(), Some("only a business project has invoices"));
|
||||
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec!["l1".into(), "l1".into()] }).as_deref(), Some("a time entry appears twice"));
|
||||
billed.push(EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec!["l1".into()] });
|
||||
assert_eq!(refusal(&billed, EventBody::TimeRemoved { entry: "l1".into() }).as_deref(), Some("this time is invoiced"));
|
||||
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec![] }).as_deref(), Some("this invoice is in a project already"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weeks_start_on_monday_and_time_rounds_once() {
|
||||
assert_eq!(week_of(d("2026-11-11")), d("2026-11-09"));
|
||||
assert_eq!(week_of(d("2026-11-09")), d("2026-11-09"));
|
||||
assert_eq!(week_of(d("2026-11-15")), d("2026-11-09"));
|
||||
assert_eq!(week_of(d("1970-01-01")), d("1969-12-29"));
|
||||
let s = State::replay(&[
|
||||
ev("a", project("b1", Kind::Business)),
|
||||
ev("b", EventBody::TimeLogged { entry: "l".into(), project: "b1".into(), task: None, minutes: 25, on: d("2026-11-02"), rate: Haler(65_050), note: String::new() }),
|
||||
]);
|
||||
// 25 min at 650,50 Kč/h = 271,0416… Kč → 271,04 Kč.
|
||||
assert_eq!(s.projects.time["l"].amount(), Haler(27_104));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_projects_do_not_parse() {
|
||||
for bad in [
|
||||
r#"{"id":"x","at":0,"type":"project.created","project":"p","name":"A","kind":"empire","template":null,"starts":null,"ends":null,"colour":"teal","rate":null}"#,
|
||||
r#"{"id":"x","at":0,"type":"project.created","project":"p","name":"A","kind":"simple","template":null,"starts":null,"ends":null,"colour":"teal","rate":10.5}"#,
|
||||
r#"{"id":"x","at":0,"type":"task.created","task":"t","project":"p","fields":{"title":"A","phase":null,"due":null,"estimate":null,"line":null,"assignee":null,"milestone":false,"secret":1}}"#,
|
||||
r#"{"id":"x","at":0,"type":"time.logged","entry":"e","project":"p","task":null,"minutes":-5,"on":"2026-11-02","rate":0,"note":""}"#,
|
||||
r#"{"id":"x","at":0,"type":"task.status_set","task":"t","status":"abandoned","on":"2026-11-02"}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<Event>(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user