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

9 downloads

dbbasic-object-server/tests/test_payments_slice2.py
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, 18 minutes ago History
test_payments_slice2.py · 8.5 KB · 208 lines
1"""Payments slice 2 (plan/payments-spec.md): aging + dunning.
2
3Doctrinal split under test: paid/partial flips are EVENT-driven
4(system_invoice_status reacts the moment money moves); overdue + dunning
5escalation are TIME-driven (system_invoice_aging, a daemon-scheduled pass —
6docs/logic-decisions.md #2). Dunning emails go straight to the generic
7outbox (customer_email is a raw address, not a user id); the owner's in_app
8ping is a seeded notify_rule (pure data).
9"""
10
11import json
12import pathlib
13
14import object_execution
15import object_records
16import python_object_runtime
17from conftest import stage_collection
18
19REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
20PACKAGES = REPO_ROOT / "packages"
21RUNTIME = python_object_runtime.PythonObjectRuntime()
22
23
24def setup_env(tmp_path, monkeypatch, *, settings=()):
25 data_dir = tmp_path / "data"
26 for pkg, name in (("app-invoices", "invoices"), ("app-payments", "payments"),
27 ("app-payments", "refunds"), ("app-email", "email_outbox"),
28 ("app-invoices", "invoice_credits")):
29 stage_collection(data_dir, pkg, name)
30
31 rows = ""
32 for i, (k, v) in enumerate(settings):
33 rows += f"s{i}\t{k}\t{v}\t\n"
34 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
35 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
36 return data_dir
37
38
39def make_invoice(data_dir, iid="inv1", status="sent", total="10000",
40 due="2026-07-10", email="grace@acme.test", **extra):
41 rec = {"id": iid, "number": f"N-{iid}", "customer_name": "Acme",
42 "customer_email": email, "status": status, "due_date": due,
43 "total_cents": total, "owner_id": "dan"}
44 rec.update(extra)
45 return object_records.create_collection_record("invoices", rec, base_dir=data_dir)
46
47
48def pay(data_dir, pid, invoice_id, cents, status="received"):
49 return object_records.create_collection_record(
50 "payments",
51 {"id": pid, "invoice_id": invoice_id, "amount_cents": cents,
52 "method": "card", "received_on": "2026-07-09", "status": status,
53 "owner_id": "dan"},
54 base_dir=data_dir)
55
56
57def fire_status(collection, record_id, action_raw):
58 return object_execution.execute_object(
59 RUNTIME,
60 object_execution.ObjectExecutionRequest(
61 "system_invoice_status", method="EVENT",
62 payload={"event": f"{collection}.record.{action_raw}d",
63 "collection": collection, "record_id": record_id,
64 "action": action_raw}),
65 roots=[PACKAGES / "app-payments" / "objects"])
66
67
68def run_aging(today):
69 return object_execution.execute_object(
70 RUNTIME,
71 object_execution.ObjectExecutionRequest(
72 "system_invoice_aging", method="POST", payload={"today": today}),
73 roots=[PACKAGES / "app-invoices" / "objects"])
74
75
76def invoice(data_dir, iid="inv1"):
77 return object_records.get_collection_record("invoices", iid, base_dir=data_dir)
78
79
80def outbox(data_dir):
81 return object_records.read_collection_records("email_outbox", base_dir=data_dir)
82
83
84def test_status_flips_partial_then_paid_then_back_on_refund(tmp_path, monkeypatch):
85 data_dir = setup_env(tmp_path, monkeypatch)
86 make_invoice(data_dir)
87 pay(data_dir, "p1", "inv1", "4000")
88 fire_status("payments", "p1", "create")
89 assert invoice(data_dir)["status"] == "partial"
90
91 pay(data_dir, "p2", "inv1", "6000")
92 fire_status("payments", "p2", "create")
93 assert invoice(data_dir)["status"] == "paid"
94
95 object_records.create_collection_record(
96 "refunds", {"id": "r1", "payment_id": "p2", "invoice_id": "inv1",
97 "amount_cents": "2000", "refunded_on": "2026-07-11",
98 "owner_id": "dan"}, base_dir=data_dir)
99 fire_status("refunds", "r1", "create")
100 assert invoice(data_dir)["status"] == "partial"
101
102
103def test_status_never_touches_draft_or_void(tmp_path, monkeypatch):
104 data_dir = setup_env(tmp_path, monkeypatch)
105 make_invoice(data_dir, iid="invd", status="draft")
106 pay(data_dir, "p1", "invd", "10000")
107 fire_status("payments", "p1", "create")
108 assert invoice(data_dir, "invd")["status"] == "draft"
109
110
111def test_aging_flips_overdue_dunns_and_respects_grace(tmp_path, monkeypatch):
112 data_dir = setup_env(tmp_path, monkeypatch,
113 settings=(("payments.grace_days", "3"),))
114 make_invoice(data_dir) # due 2026-07-10, unpaid
115
116 # Inside grace: due+3 = 07-13; today 07-12 -> untouched.
117 run_aging("2026-07-12")
118 assert invoice(data_dir)["status"] == "sent"
119 assert outbox(data_dir) == []
120
121 # Past grace -> overdue, level 1, dunning email queued to the customer.
122 result = run_aging("2026-07-14")
123 assert result.result["flipped_overdue"] == 1
124 row = invoice(data_dir)
125 assert row["status"] == "overdue"
126 assert row["dunning_level"] == "1"
127 assert row["last_dunned_on"] == "2026-07-14"
128 mails = outbox(data_dir)
129 assert len(mails) == 1
130 assert mails[0]["to"] == "grace@acme.test"
131 assert "overdue" in mails[0]["subject"]
132 assert mails[0]["status"] == "queued"
133
134
135def test_dunning_escalates_on_schedule_and_stops_at_max(tmp_path, monkeypatch):
136 data_dir = setup_env(tmp_path, monkeypatch,
137 settings=(("payments.dunning_repeat_days", "7"),
138 ("payments.dunning_max_level", "3")))
139 make_invoice(data_dir)
140 run_aging("2026-07-11") # -> overdue, level 1
141 run_aging("2026-07-12") # too soon: no escalation
142 assert invoice(data_dir)["dunning_level"] == "1"
143 run_aging("2026-07-18") # +7d -> level 2
144 assert invoice(data_dir)["dunning_level"] == "2"
145 run_aging("2026-07-25") # +7d -> level 3 (max)
146 assert invoice(data_dir)["dunning_level"] == "3"
147 run_aging("2026-08-10") # capped: stays 3
148 assert invoice(data_dir)["dunning_level"] == "3"
149 assert len(outbox(data_dir)) == 3 # one email per level
150
151
152def test_aging_clears_overdue_when_balance_paid_out_of_band(tmp_path, monkeypatch):
153 data_dir = setup_env(tmp_path, monkeypatch)
154 make_invoice(data_dir)
155 run_aging("2026-07-11")
156 assert invoice(data_dir)["status"] == "overdue"
157 pay(data_dir, "p1", "inv1", "10000") # storage-level: no event fired
158 result = run_aging("2026-07-12")
159 assert invoice(data_dir)["status"] == "paid"
160 assert result.result["flipped_overdue"] == 0
161
162
163def test_aging_skips_paid_void_and_no_due_date(tmp_path, monkeypatch):
164 data_dir = setup_env(tmp_path, monkeypatch)
165 make_invoice(data_dir, iid="a", status="paid")
166 make_invoice(data_dir, iid="b", status="void")
167 make_invoice(data_dir, iid="c", status="sent", due="")
168 run_aging("2026-08-01")
169 assert invoice(data_dir, "a")["status"] == "paid"
170 assert invoice(data_dir, "b")["status"] == "void"
171 assert invoice(data_dir, "c")["status"] == "sent"
172 assert outbox(data_dir) == []
173
174
175def test_dunning_without_customer_email_still_escalates(tmp_path, monkeypatch):
176 data_dir = setup_env(tmp_path, monkeypatch)
177 make_invoice(data_dir, email="")
178 result = run_aging("2026-07-11")
179 assert invoice(data_dir)["status"] == "overdue"
180 assert outbox(data_dir) == []
181 assert result.result["results"][0]["emailed"] is False
182
183
184def test_owner_notify_rule_seed_matches_the_overdue_change(tmp_path, monkeypatch):
185 """The dunning notify seed is pure data — prove it fires with the real
186 notify engine against the change our aging pass produces."""
187 import object_notify
188 data_dir = setup_env(tmp_path, monkeypatch)
189 make_invoice(data_dir)
190 run_aging("2026-07-11")
191 row = invoice(data_dir)
192
193 seed = (PACKAGES / "app-invoices" / "seed" / "notify_rules.tsv").read_text().splitlines()
194 header = seed[0].split("\t")
195 import csv, io
196 parsed = next(csv.DictReader(io.StringIO("\n".join(seed)), delimiter="\t"))
197 rule = dict(parsed)
198 # Mirror a REAL record-change entry: changed_fields present (the notify
199 # engine's transition semantics — a match condition must be on a field the
200 # write actually changed, so the rule fires once per transition, not on
201 # every later edit of an overdue invoice).
202 change = {"collection": "invoices", "record_id": "inv1",
203 "action": "update", "after": row, "actor": "system_invoice_aging",
204 "changed_fields": ["status", "dunning_level", "last_dunned_on"]}
205 notes = object_notify.notifications_for_change(rule, change, base_dir=data_dir)
206 assert len(notes) == 1
207 assert notes[0]["user_id"] == "dan"
208 assert "overdue" in notes[0]["body"]