Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
invoice_status.py · 4.9 KB · 122 lines
1"""system_invoice_status -- HANDLES payment, refund and credit writes; the
2invoice's status follows the money the moment it moves.
3
4The event-driven half of invoice aging (plan/payments-spec.md slice 2):
5a customer who just paid must not stay "overdue" until tomorrow's daemon
6pass; the time-driven half (sent -> overdue, dunning escalation) lives in
7system_invoice_aging, per docs/logic-decisions.md #2.
8
9**Status follows the money (the owner's decision, 2026-11-30).** An issued
10invoice's total never changes. Its status is read off what was received,
11refunded and credited, by object_corrections.money_status, every time one
12of those moves: paid, partial, sent, credit_owed (the shop owes the
13customer), refunded (credited away and the money given back) or credited
14(credited away, nothing paid). overdue is kept while anything is still
15owed; turning sent into overdue is the aging pass's. draft and void are a
16person's and are never moved here.
17
18What this used to get wrong (findings M3, M4): it computed paid -> sent for
19a fully refunded invoice, a bounced cheque or a deleted payment, the
20invoices ladder refused the move (paid allowed only partial) and the
21refusal was swallowed, so the invoice stayed `paid` with the whole balance
22owing and nobody dunned it. invoices v13 lets any money state follow any
23other, because money can move back.
24
25The money is read from the invoice's DERIVED fields (payments_received_cents,
26refunded_cents, credited_cents: rollups the storage layer recomputed before
27dispatch), never re-summed here.
28
29A DELETED payment, refund or credit is followed too: the row is gone by
30dispatch time, so its invoice_id comes from the change log's before-image.
31"""
32
33import os
34
35import object_corrections
36import object_record_changes
37import object_records
38
39HANDLES = [
40 "payments.record.created",
41 "payments.record.updated",
42 "payments.record.deleted",
43 "refunds.record.created",
44 "refunds.record.deleted",
45 "invoice_credits.record.created",
46 "invoice_credits.record.updated",
47 "invoice_credits.record.deleted",
48]
49
50ACTOR = "system_invoice_status"
51_SOURCES = ("payments", "refunds", "invoice_credits")
52
53
54def _base_dir():
55 return os.environ.get("DBBASIC_DATA_DIR", "data")
56
57
58def _deleted_invoice_id(collection, record_id, base):
59 """The invoice a just-deleted row belonged to, from the newest
60 change-log entry's before-image, or "" when it cannot be told."""
61 try:
62 change = object_record_changes.latest_record_change(
63 collection, record_id, base_dir=base)
64 except Exception:
65 return ""
66 before = (change or {}).get("before") or {}
67 return str(before.get("invoice_id") or "")
68
69
70def follow(invoice_id, base, actor=ACTOR):
71 """Move one invoice's status to what its money says. Returns the
72 handler's answer. Shared with the aging pass's fall-back."""
73 try:
74 invoice = object_records.get_collection_record("invoices", invoice_id, base_dir=base)
75 except Exception as exc:
76 return {"ok": False, "error": str(exc)[:200]}
77 if not object_corrections.is_bill(invoice):
78 return {"ok": True, "skipped": "not an invoice (a quote or credit note)"}
79 status = str(invoice.get("status") or "")
80 if status not in object_corrections.MONEY_STATES:
81 return {"ok": True, "skipped": f"status {status!r} not auto-flipped"}
82 new_status = object_corrections.money_status(
83 status, total=invoice.get("total_cents"),
84 received=invoice.get("payments_received_cents"),
85 refunded=invoice.get("refunded_cents"),
86 credited=invoice.get("credited_cents"))
87 if new_status == status:
88 return {"ok": True, "skipped": "status already correct"}
89 try:
90 object_records.update_collection_record(
91 "invoices", invoice_id, {"status": new_status}, base_dir=base, actor=actor)
92 except Exception as exc:
93 return {"ok": False, "error": str(exc)[:200]}
94 return {"ok": True, "invoice": invoice_id, "status": new_status}
95
96
97def EVENT(request):
98 collection = str(request.get("collection") or "")
99 record_id = str(request.get("record_id") or "")
100 if not record_id:
101 return {"ok": True, "skipped": "no record id"}
102 if collection not in _SOURCES:
103 return {"ok": True, "skipped": "not a money event"}
104 base = _base_dir()
105 action = str(request.get("action") or "")
106
107 try:
108 row = object_records.get_collection_record(collection, record_id, base_dir=base)
109 invoice_id = row.get("invoice_id", "")
110 except Exception:
111 if action not in ("delete", "deleted"):
112 return {"ok": True, "skipped": "source row gone"}
113 invoice_id = _deleted_invoice_id(collection, record_id, base)
114 if not invoice_id:
115 return {"ok": True, "skipped": "source row gone; its invoice "
116 "is not in the change log"}
117 if not invoice_id:
118 return {"ok": True, "skipped": "no invoice"}
119 return follow(invoice_id, base)
120
121
122POST = EVENT