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

0 downloads

dbbasic-object-server/tests/test_app_payments_package.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
test_app_payments_package.py · 8.2 KB · 202 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
45 settings_rows = ""
46 if overpayment_policy:
47 settings_rows = f"s1\tpayments.overpayment_policy\t{overpayment_policy}\t\n"
48 stage_collection(data_dir, "app-settings", "app_settings", rows=settings_rows)
49
50 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
51 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(PACKAGES / "app-payments" / "objects"))
52 enable_admin_token(monkeypatch)
53 return data_dir
54
55
56def pay(record):
57 # admin-token writes don't session-stamp owner_id; set it so the
58 # owner-guarded received->bounced transition works in tests.
59 body = {"method": "transfer", "received_on": "2026-07-24", "owner_id": "admin", **record}
60 return request(
61 "/collections/payments/records",
62 method="POST",
63 body=json.dumps(body).encode("utf-8"),
64 headers=AUTH,
65 )
66
67
68def refund(record):
69 body = {"refunded_on": "2026-07-24", **record}
70 return request(
71 "/collections/refunds/records",
72 method="POST",
73 body=json.dumps(body).encode("utf-8"),
74 headers=AUTH,
75 )
76
77
78def invoice(data_dir):
79 return object_records.get_collection_record("invoices", "inv1", base_dir=data_dir)
80
81
82def test_payment_rolls_up_paid_and_balance_on_the_invoice(tmp_path, monkeypatch):
83 data_dir = setup_env(tmp_path, monkeypatch)
84 status, _, payload = pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "4000"})
85 assert status in (200, 201), payload
86 row = invoice(data_dir)
87 assert row["payments_received_cents"] == "4000"
88 assert row["amount_paid_cents"] == "4000"
89 assert row["balance_due_cents"] == "6000"
90
91
92def test_bounced_payment_leaves_the_rollup(tmp_path, monkeypatch):
93 data_dir = setup_env(tmp_path, monkeypatch)
94 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "4000"})
95 status, _, _ = request(
96 "/collections/payments/records/p1",
97 method="PUT",
98 body=json.dumps({"status": "bounced"}).encode("utf-8"),
99 headers=AUTH,
100 )
101 assert status == 200
102 row = invoice(data_dir)
103 assert row["payments_received_cents"] == "0"
104 assert row["balance_due_cents"] == "10000"
105
106
107def test_overpayment_rejected_by_default_allowed_by_setting(tmp_path, monkeypatch):
108 data_dir = setup_env(tmp_path, monkeypatch)
109 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "9000"})
110 status, _, payload = pay({"id": "p2", "invoice_id": "inv1", "amount_cents": "2000"})
111 assert status == 409
112 assert payload["code"] == "hook_rejected"
113 assert "remaining balance of 1000" in payload["error"]
114 assert invoice(data_dir)["payments_received_cents"] == "9000"
115
116 # Exactly the remaining balance is fine.
117 status, _, _ = pay({"id": "p3", "invoice_id": "inv1", "amount_cents": "1000"})
118 assert status in (200, 201)
119 assert invoice(data_dir)["balance_due_cents"] == "0"
120
121
122def test_overpayment_allowed_when_policy_says_allow(tmp_path, monkeypatch):
123 data_dir = setup_env(tmp_path, monkeypatch, overpayment_policy="allow")
124 status, _, _ = pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "15000"})
125 assert status in (200, 201)
126 assert invoice(data_dir)["balance_due_cents"] == "-5000"
127
128
129def test_nonpositive_amounts_rejected(tmp_path, monkeypatch):
130 setup_env(tmp_path, monkeypatch)
131 status, _, payload = pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "0"})
132 assert status == 400 and payload["code"] == "hook_rejected"
133 pay({"id": "p2", "invoice_id": "inv1", "amount_cents": "1000"})
134 status, _, payload = refund({"id": "r1", "payment_id": "p2", "amount_cents": "-5"})
135 assert status == 400 and payload["code"] == "hook_rejected"
136
137
138def test_refund_invariant_and_stamp(tmp_path, monkeypatch):
139 data_dir = setup_env(tmp_path, monkeypatch)
140 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "5000"})
141
142 # Client-supplied invoice_id is overridden by the stamp from the payment.
143 status, _, payload = refund(
144 {"id": "r1", "payment_id": "p1", "amount_cents": "2000", "invoice_id": "WRONG"}
145 )
146 assert status in (200, 201), payload
147 stored = object_records.get_collection_record("refunds", "r1", base_dir=data_dir)
148 assert stored["invoice_id"] == "inv1"
149
150 # Rollups: payment.refunded_cents and invoice paid/balance reflect it.
151 payment = object_records.get_collection_record("payments", "p1", base_dir=data_dir)
152 assert payment["refunded_cents"] == "2000"
153 row = invoice(data_dir)
154 assert row["refunded_cents"] == "2000"
155 assert row["amount_paid_cents"] == "3000"
156 assert row["balance_due_cents"] == "7000"
157
158 # Over-refunding what remains is rejected with the refundable amount.
159 status, _, payload = refund({"id": "r2", "payment_id": "p1", "amount_cents": "3500"})
160 assert status == 409
161 assert "refundable 3000" in payload["error"]
162
163 # Exactly the remainder is fine; the chain zeroes out.
164 status, _, _ = refund({"id": "r3", "payment_id": "p1", "amount_cents": "3000"})
165 assert status in (200, 201)
166 assert invoice(data_dir)["amount_paid_cents"] == "0"
167
168
169def test_cannot_refund_a_bounced_payment(tmp_path, monkeypatch):
170 setup_env(tmp_path, monkeypatch)
171 pay({"id": "p1", "invoice_id": "inv1", "amount_cents": "1000"})
172 request(
173 "/collections/payments/records/p1",
174 method="PUT",
175 body=json.dumps({"status": "bounced"}).encode("utf-8"),
176 headers=AUTH,
177 )
178 status, _, payload = refund({"id": "r1", "payment_id": "p1", "amount_cents": "500"})
179 assert status == 409
180 assert "bounced" in payload["error"]
181
182
183def test_package_manifest_shape():
184 import object_packages
185
186 package = object_packages.get_package("app-payments", root=PACKAGES)
187 assert package["id"] == "app-payments"
188 assert {s["collection"] for s in package["schemas"]} == {"payments", "refunds"}
189 assert {o["id"] for o in package["objects"]} == {
190 "site_payments", "hook_payments", "hook_refunds",
191 "system_books", # journal composer (books spine)
192 "system_invoice_status", # event-driven paid/partial flips (slice 2)
193 # 0.2.0: Stripe as a payment METHOD -- the webhook writes an ordinary
194 # payments row and the existing reaction chain does the rest.
195 "webhook_stripe", "action_stripe_checkout",
196 }
197 assert "app-invoices" in {d["id"] for d in package["dependencies"]}
198 for schema_name in ("payments", "refunds"):
199 schema = json.loads(
200 (PACKAGES / "app-payments" / "schemas" / f"{schema_name}.json").read_text()
201 )
202 assert schema["storage"] == "append" # money moves, never mutates