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_app_payments_package.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, 19 minutes ago History
test_app_payments_package.py · 8.6 KB · 209 lines
1"""app-payments (plan/payments-spec.md): the first ERP-tail module and the
2deliberate stress test of the whole primitive stack — append-only money
3movements, hook-enforced invariants (overpayment gate, refund <= refundable,
4invoice_id stamped from the payment), and rollup/formula-derived paid and
5balance amounts on invoices.
6
7Placement per docs/business-logic-patterns.md: gates in hooks, derived
8positions in rollups/formulas, policy in app_settings, corrections as
9compensating records.
10"""
11
12import json
13import pathlib
14
15import object_records
16import object_server
17from conftest import schema_header, stage_collection
18from test_object_server import (
19 TEST_ADMIN_TOKEN,
20 enable_admin_token,
21 request,
22)
23
24AUTH = [("authorization", f"Token {TEST_ADMIN_TOKEN}")]
25REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
26PACKAGES = REPO_ROOT / "packages"
27
28
29def setup_env(tmp_path, monkeypatch, *, overpayment_policy=None):
30 data_dir = tmp_path / "data"
31
32 # inv1 is seeded straight into the TSV (not via create_collection_record)
33 # so it starts life already "sent" with no payments -- pin the row to
34 # the real schema's field order so a later schema edit can't silently
35 # shift these values into the wrong columns.
36 invoice_fields = schema_header("app-invoices", "invoices").strip("\n").split("\t")
37 invoice_values = {"id": "inv1", "number": "INV-1", "customer_name": "Acme",
38 "status": "sent", "total_cents": "10000", "owner_id": "admin"}
39 invoice_row = "\t".join(invoice_values.get(f, "") for f in invoice_fields) + "\n"
40 stage_collection(data_dir, "app-invoices", "invoices", rows=invoice_row)
41
42 stage_collection(data_dir, "app-payments", "payments")
43 stage_collection(data_dir, "app-payments", "refunds")
44 # Credit notes applied to an invoice: balance_due_cents subtracts them
45 # (app-invoices 0.17.0), so its rollup source must exist.
46 stage_collection(data_dir, "app-invoices", "invoice_credits")
47
48 settings_rows = ""
49 if overpayment_policy:
50 settings_rows = f"s1\tpayments.overpayment_policy\t{overpayment_policy}\t\n"
51 stage_collection(data_dir, "app-settings", "app_settings", rows=settings_rows)
52
53 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
54 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(PACKAGES / "app-payments" / "objects"))
55 enable_admin_token(monkeypatch)
56 return data_dir
57
58
59def pay(record):
60 # admin-token writes don't session-stamp owner_id; set it so the
61 # owner-guarded received->bounced transition works in tests.
62 body = {"method": "transfer", "received_on": "2026-07-24", "owner_id": "admin", **record}
63 return request(
64 "/collections/payments/records",
65 method="POST",
66 body=json.dumps(body).encode("utf-8"),
67 headers=AUTH,
68 )
69
70
71def refund(record):
72 body = {"refunded_on": "2026-07-24", **record}
73 return request(
74 "/collections/refunds/records",
75 method="POST",
76 body=json.dumps(body).encode("utf-8"),
77 headers=AUTH,
78 )
79
80
81def invoice(data_dir):
82 return object_records.get_collection_record("invoices", "inv1", base_dir=data_dir)
83
84
85def test_payment_rolls_up_paid_and_balance_on_the_invoice(tmp_path, monkeypatch):
86 data_dir = setup_env(tmp_path, monkeypatch)
87 status, _, payload = pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "4000"})
88 assert status in (200, 201), payload
89 row = invoice(data_dir)
90 assert row["payments_received_cents"] == "4000"
91 assert row["amount_paid_cents"] == "4000"
92 assert row["balance_due_cents"] == "6000"
93
94
95def test_bounced_payment_leaves_the_rollup(tmp_path, monkeypatch):
96 data_dir = setup_env(tmp_path, monkeypatch)
97 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "4000"})
98 status, _, _ = request(
99 "/collections/payments/records/p1",
100 method="PUT",
101 body=json.dumps({"status": "bounced"}).encode("utf-8"),
102 headers=AUTH,
103 )
104 assert status == 200
105 row = invoice(data_dir)
106 assert row["payments_received_cents"] == "0"
107 assert row["balance_due_cents"] == "10000"
108
109
110def test_overpayment_rejected_by_default_allowed_by_setting(tmp_path, monkeypatch):
111 data_dir = setup_env(tmp_path, monkeypatch)
112 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "9000"})
113 status, _, payload = pay({"id": "p2", "invoice_id": "inv1", "amount_cents": "2000"})
114 assert status == 409
115 assert payload["code"] == "check_refused"
116 assert "remaining balance of 1000" in payload["error"]
117 assert invoice(data_dir)["payments_received_cents"] == "9000"
118
119 # Exactly the remaining balance is fine.
120 status, _, _ = pay({"id": "p3", "invoice_id": "inv1", "amount_cents": "1000"})
121 assert status in (200, 201)
122 assert invoice(data_dir)["balance_due_cents"] == "0"
123
124
125def test_overpayment_allowed_when_policy_says_allow(tmp_path, monkeypatch):
126 data_dir = setup_env(tmp_path, monkeypatch, overpayment_policy="allow")
127 status, _, _ = pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "15000"})
128 assert status in (200, 201)
129 assert invoice(data_dir)["balance_due_cents"] == "-5000"
130
131
132def test_nonpositive_amounts_rejected(tmp_path, monkeypatch):
133 setup_env(tmp_path, monkeypatch)
134 # validation.min on amount_cents, for every writer (the hooks no longer
135 # carry a copy of it)
136 status, _, payload = pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "0"})
137 assert status == 400 and "below min" in payload["error"]
138 pay({"id": "p2", "invoice_id": "inv1", "amount_cents": "1000"})
139 status, _, payload = refund({"id": "r1", "payment_id": "p2", "amount_cents": "-5"})
140 assert status == 400 and "below min" in payload["error"]
141
142
143def test_refund_invariant_and_stamp(tmp_path, monkeypatch):
144 data_dir = setup_env(tmp_path, monkeypatch)
145 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "5000"})
146
147 # Client-supplied invoice_id is overridden by the stamp from the payment.
148 status, _, payload = refund(
149 {"id": "r1", "payment_id": "p1", "amount_cents": "2000", "invoice_id": "WRONG"}
150 )
151 assert status in (200, 201), payload
152 stored = object_records.get_collection_record("refunds", "r1", base_dir=data_dir)
153 assert stored["invoice_id"] == "inv1"
154
155 # Rollups: payment.refunded_cents and invoice paid/balance reflect it.
156 payment = object_records.get_collection_record("payments", "p1", base_dir=data_dir)
157 assert payment["refunded_cents"] == "2000"
158 row = invoice(data_dir)
159 assert row["refunded_cents"] == "2000"
160 assert row["amount_paid_cents"] == "3000"
161 assert row["balance_due_cents"] == "7000"
162
163 # Over-refunding what remains is rejected with the refundable amount.
164 status, _, payload = refund({"id": "r2", "payment_id": "p1", "amount_cents": "3500"})
165 assert status == 409
166 assert "refundable 3000" in payload["error"]
167
168 # Exactly the remainder is fine; the chain zeroes out.
169 status, _, _ = refund({"id": "r3", "payment_id": "p1", "amount_cents": "3000"})
170 assert status in (200, 201)
171 assert invoice(data_dir)["amount_paid_cents"] == "0"
172
173
174def test_cannot_refund_a_bounced_payment(tmp_path, monkeypatch):
175 setup_env(tmp_path, monkeypatch)
176 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "1000"})
177 request(
178 "/collections/payments/records/p1",
179 method="PUT",
180 body=json.dumps({"status": "bounced"}).encode("utf-8"),
181 headers=AUTH,
182 )
183 status, _, payload = refund({"id": "r1", "payment_id": "p1", "amount_cents": "500"})
184 assert status == 409
185 assert "bounced" in payload["error"]
186
187
188def test_package_manifest_shape():
189 import object_packages
190
191 package = object_packages.get_package("app-payments", root=PACKAGES)
192 assert package["id"] == "app-payments"
193 assert {s["collection"] for s in package["schemas"]} >= {"payments", "refunds"}
194 assert {o["id"] for o in package["objects"]} >= {
195 # site_payments was deleted in 0.6.0: /payments is a seeded view
196 # (tests/test_pages_converted_to_views.py).
197 "hook_payments", "hook_refunds",
198 "system_books", # journal composer (books spine)
199 "system_invoice_status", # event-driven paid/partial flips (slice 2)
200 # 0.2.0: Stripe as a payment METHOD -- the webhook writes an ordinary
201 # payments row and the existing reaction chain does the rest.
202 "webhook_stripe", "action_stripe_checkout",
203 }
204 assert "app-invoices" in {d["id"] for d in package["dependencies"]}
205 for schema_name in ("payments", "refunds"):
206 schema = json.loads(
207 (PACKAGES / "app-payments" / "schemas" / f"{schema_name}.json").read_text()
208 )
209 assert schema["storage"] == "append" # money moves, never mutates