[ledger] Invoices: supplier, invoice numbers as variable symbols, VAT per rate, paid by a matching statement line, the tax reserve; v0.4.0
This commit is contained in:
@@ -5,6 +5,7 @@ use crate::categories;
|
||||
use crate::date::Date;
|
||||
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
|
||||
use crate::import::StatementLine;
|
||||
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
|
||||
use crate::merchant::merchant_key;
|
||||
use crate::money::Haler;
|
||||
use crate::pay::{spayd, Iban};
|
||||
@@ -142,6 +143,37 @@ pub struct ShareView {
|
||||
pub spayd: Option<String>,
|
||||
}
|
||||
|
||||
/// An issued invoice, its totals, and what became of it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct InvoiceRecord {
|
||||
pub invoice: Invoice,
|
||||
/// The supplier as it was when the invoice was issued.
|
||||
pub supplier: Supplier,
|
||||
pub totals: Totals,
|
||||
pub paid: Option<Paid>,
|
||||
pub cancelled: bool,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Paid {
|
||||
/// The statement line that paid it; `None` when marked paid by hand.
|
||||
pub payment: Option<PaymentId>,
|
||||
pub on: Date,
|
||||
/// Set aside for tax: the VAT, and the reserve share of the rest.
|
||||
pub reserve: Haler,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Withdrawal {
|
||||
pub id: String,
|
||||
pub amount: Haler,
|
||||
pub on: Date,
|
||||
pub note: String,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rejection {
|
||||
pub event: EventId,
|
||||
@@ -175,6 +207,13 @@ pub struct State {
|
||||
pub profile_name: Option<String>,
|
||||
/// The shared budgets I share my subscription names with (`household.sharing_set`).
|
||||
pub household_sharing: BTreeSet<BudgetId>,
|
||||
pub supplier: Option<Supplier>,
|
||||
pub invoices: BTreeMap<InvoiceId, InvoiceRecord>,
|
||||
/// Invoice number → invoice.
|
||||
pub invoice_numbers: BTreeMap<String, InvoiceId>,
|
||||
/// A statement line → the invoice it paid.
|
||||
pub invoice_payments: BTreeMap<PaymentId, InvoiceId>,
|
||||
pub withdrawals: Vec<Withdrawal>,
|
||||
pub rejected: Vec<Rejection>,
|
||||
}
|
||||
|
||||
@@ -618,6 +657,68 @@ impl State {
|
||||
return Err("a name must be 1-40 characters");
|
||||
}
|
||||
}
|
||||
EventBody::SupplierSet { supplier } => {
|
||||
supplier.check().map_err(|_| "not a valid supplier")?;
|
||||
self.supplier = Some(supplier.clone());
|
||||
}
|
||||
EventBody::InvoiceIssued { invoice } => {
|
||||
let supplier = self.supplier.clone().ok_or("set the supplier before issuing an invoice")?;
|
||||
if !id_ok(&invoice.id) || self.invoices.contains_key(&invoice.id) {
|
||||
return Err("an invoice with this id exists");
|
||||
}
|
||||
if self.invoice_numbers.contains_key(&invoice.number) {
|
||||
return Err("an invoice with this number exists");
|
||||
}
|
||||
if invoice.budget.as_ref().is_some_and(|b| !self.budgets.contains_key(b)) {
|
||||
return Err("no such budget");
|
||||
}
|
||||
let totals = invoice.check(&supplier).map_err(|_| "not a valid invoice")?;
|
||||
self.invoice_numbers.insert(invoice.number.clone(), invoice.id.clone());
|
||||
self.invoices.insert(invoice.id.clone(), InvoiceRecord { invoice: invoice.clone(), supplier, totals, paid: None, cancelled: false, seq });
|
||||
}
|
||||
EventBody::InvoicePaid { invoice, payment, on } => {
|
||||
let rec = self.invoices.get(invoice).ok_or("no such invoice")?;
|
||||
if rec.cancelled || rec.paid.is_some() {
|
||||
return Err("the invoice is cancelled or paid already");
|
||||
}
|
||||
if *on < rec.invoice.issued {
|
||||
return Err("paid before it was issued");
|
||||
}
|
||||
if let Some(p) = payment {
|
||||
if self.invoice_payments.contains_key(p) {
|
||||
return Err("this payment paid another invoice");
|
||||
}
|
||||
let e = self.effective_payment(p).ok_or("no such payment")?;
|
||||
if e.line.is_none() || e.amount != rec.totals.total {
|
||||
return Err("the payment is not a statement line of the invoice's amount");
|
||||
}
|
||||
}
|
||||
let reserve = rec.supplier.reserve_for(&rec.totals);
|
||||
if let Some(p) = payment {
|
||||
self.invoice_payments.insert(p.clone(), invoice.clone());
|
||||
}
|
||||
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
|
||||
rec.paid = Some(Paid { payment: payment.clone(), on: *on, reserve, seq });
|
||||
}
|
||||
EventBody::InvoiceCancelled { invoice } => {
|
||||
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
|
||||
if rec.paid.is_some() || rec.cancelled {
|
||||
return Err("only an unpaid invoice can be cancelled");
|
||||
}
|
||||
rec.cancelled = true;
|
||||
}
|
||||
EventBody::ReserveWithdrawn { withdrawal, amount, on, note } => {
|
||||
if !id_ok(withdrawal) || self.withdrawals.iter().any(|w| &w.id == withdrawal) {
|
||||
return Err("a withdrawal with this id exists");
|
||||
}
|
||||
if amount.0 <= 0 || *amount > self.reserve_balance() {
|
||||
return Err("more than the reserve holds");
|
||||
}
|
||||
if note.chars().count() > 200 || !text_ok(note) {
|
||||
return Err("a note is at most 200 characters");
|
||||
}
|
||||
self.withdrawals.push(Withdrawal { id: withdrawal.clone(), amount: *amount, on: *on, note: note.clone(), seq });
|
||||
}
|
||||
EventBody::SubscriptionsShared { budget, names } => {
|
||||
if !self.budgets.contains_key(budget) {
|
||||
return Err("no such budget");
|
||||
@@ -636,6 +737,31 @@ impl State {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What the tax reserve holds: everything set aside for paid invoices, less what was taken out.
|
||||
pub fn reserve_balance(&self) -> Haler {
|
||||
let set: i64 = self.invoices.values().filter_map(|r| r.paid.as_ref()).map(|p| p.reserve.0).fold(0, i64::saturating_add);
|
||||
let out: i64 = self.withdrawals.iter().map(|w| w.amount.0).fold(0, i64::saturating_add);
|
||||
Haler(set.saturating_sub(out))
|
||||
}
|
||||
|
||||
/// The number the next invoice issued in `year` gets.
|
||||
pub fn next_invoice_number(&self, year: i32) -> Option<String> {
|
||||
let prefix = year.to_string();
|
||||
let last = self.invoice_numbers.keys().filter(|n| n.starts_with(&prefix)).filter_map(|n| n[4..].parse::<u32>().ok()).max().unwrap_or(0);
|
||||
crate::invoice::invoice_number(year, last + 1).ok()
|
||||
}
|
||||
|
||||
/// QR Platba for an unpaid invoice: its total, its number as the variable symbol, to the account set.
|
||||
pub fn invoice_spayd(&self, invoice: &str) -> Option<String> {
|
||||
let r = self.invoices.get(invoice)?;
|
||||
if r.paid.is_some() || r.cancelled {
|
||||
return None;
|
||||
}
|
||||
let a = self.account.as_ref()?;
|
||||
let iban = Iban::parse(&a.iban).ok()?;
|
||||
spayd(&iban, r.totals.total, Some(&a.name), &format!("Faktura {}", r.invoice.number), Some(&r.invoice.number)).ok()
|
||||
}
|
||||
|
||||
/// Whether a phone's capture token (its SHA-256 in hex) may post captures.
|
||||
pub fn capture_token_active(&self, token: &str) -> bool {
|
||||
self.capture_tokens.get(token).is_some_and(|t| !t.revoked)
|
||||
|
||||
Reference in New Issue
Block a user