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_exchange_documents.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_exchange_documents.py · 22.4 KB · 379 lines
1"""Box-to-box exchange, the documents: what each one becomes on the other box.
2
3The two-company simulation that motivated the exchange closed a purchase cycle
4with every cross-company step retyped. This replays that cycle between two
5boxes in one process (tests/exchange_harness.py) with nothing retyped: the
6shop's purchase order becomes the supplier's draft sale order, the supplier's
7confirmation is checked against the shop's order, its invoice becomes the
8shop's supplier bill (never paid by anything but a person), the shop's
9remittance waits at the supplier until somebody confirms the money against
10the bank, a credit note points at the bill it credits, and the shop's goods
11receipt lands against the supplier's order. Then what goes wrong: totals that
12do not add up, a package that is not installed, and the limits of the
13partner principal.
14"""
15
16from __future__ import annotations
17
18import json
19
20import pytest
21
22import object_access
23import object_packages
24from exchange_harness import connect, two_companies
25
26PACKAGES = ["app-orders", "app-invoices", "app-payments", "app-bills", "app-receiving"]
27
28
29def create(box, collection, record, user="owner"):
30 status, body = box.call(user, "POST", f"/collections/{collection}/records", record)
31 assert status == 201, (collection, status, body)
32 return body["record"]
33
34
35def put(box, collection, record_id, changes, user="owner", expect=200):
36 status, body = box.call(user, "PUT", f"/collections/{collection}/records/{record_id}", changes)
37 assert status == expect, (collection, status, body)
38 return body
39
40
41def get(box, collection, record_id):
42 status, body = box.call("admin", "GET", f"/collections/{collection}/records/{record_id}")
43 assert status == 200, body
44 return body.get("record", body)
45
46
47def only(rows, **where):
48 found = [r for r in rows if all(r.get(k) == v for k, v in where.items())]
49 assert len(found) == 1, (where, rows)
50 return found[0]
51
52
53def sent_and_delivered(sender, collection, record_id, **extra):
54 status, body = sender.send(collection, record_id, **extra)
55 assert status == 200, body
56 result = sender.deliver()
57 assert result["delivered"] == 1, (result, sender.records("exchange_outbox"))
58 return body["document_id"]
59
60
61def paid_and_remitted(buyer, seller, bill, reference=""):
62 """A payment of the whole bill, recorded and sent as a remittance."""
63 payment = create(buyer, "supplier_payments", {
64 "supplier_name": bill["supplier_name"], "supplier_domain": seller.domain,
65 "currency": bill["currency"], "paid_on": "2026-12-20", "payment_reference": reference})
66 create(buyer, "supplier_payment_lines", {"payment_id": payment["id"], "bill_id": bill["id"],
67 "amount_cents": bill["total_cents"]})
68 return sent_and_delivered(buyer, "supplier_payments", payment["id"])
69
70
71def purchase_order(buyer, seller):
72 order = create(buyer, "orders", {"doc_type": "purchase", "number": "PO-1042",
73 "customer_name": "Supplier Ltd", "currency": "EUR",
74 "order_date": "2026-12-01"})
75 lines = [create(buyer, "order_lines", {"order_id": order["id"], "description": "Widget",
76 "quantity": 12, "unit_price_cents": 1850}),
77 create(buyer, "order_lines", {"order_id": order["id"], "description": "Gasket",
78 "quantity": "2.5", "unit_price_cents": 400})]
79 put(buyer, "orders", order["id"], {"subtotal_cents": 23200, "total_cents": 23200})
80 doc = sent_and_delivered(buyer, "orders", order["id"], partner=seller.domain)
81 return order, lines, doc
82
83
84@pytest.fixture
85def trade():
86 with two_companies(PACKAGES) as (network, buyer, seller):
87 connect(buyer, seller)
88 yield network, buyer, seller
89
90
91def test_the_purchase_cycle_crosses_with_nothing_retyped(trade):
92 network, buyer, seller = trade
93
94 # 1. The shop's purchase order becomes the supplier's draft sale order.
95 po, po_lines, po_doc = purchase_order(buyer, seller)
96 received = only(seller.records("exchange_inbox"), document_id=po_doc)
97 assert received["mapping_status"] == "mapped", received["mapping_reason"]
98 sale = get(seller, "orders", received["mapped_record_id"])
99 assert (sale["doc_type"], sale["status"], sale["number"], sale["currency"]) == \
100 ("sale", "draft", "PO-1042", "EUR")
101 assert sale["customer_name"] == "Buyer Ltd" and sale["owner_id"] == "owner"
102 assert sale["total_cents"] == "23200", "the writer stamped the totals itself"
103 sale_lines = [l for l in seller.records("order_lines") if l["order_id"] == sale["id"]]
104 assert sorted((l["description"], l["quantity"], l["unit_price_cents"]) for l in sale_lines) == \
105 [("Gasket", "2.5", "400"), ("Widget", "12", "1850")]
106
107 # 2. The supplier confirms; the shop checks it against its own order.
108 conf_doc = sent_and_delivered(seller, "orders", sale["id"], response="accepted")
109 confirmation = only(buyer.records("exchange_inbox"), document_id=conf_doc)
110 assert confirmation["mapping_status"] == "mapped", confirmation["mapping_reason"]
111 assert confirmation["mapped_record_id"] == po["id"]
112 assert "as ordered" in confirmation["mapping_reason"]
113
114 # 3. The supplier invoices; the shop gets a supplier bill, waiting for a person.
115 invoice = create(seller, "invoices", {"number": "INV-77", "customer_name": "Buyer Ltd",
116 "currency": "EUR", "issue_date": "2026-12-03",
117 "due_date": "2027-01-02", "source_order_id": sale["id"]})
118 for line in sale_lines:
119 create(seller, "invoice_lines", {"invoice_id": invoice["id"], "description": line["description"],
120 "quantity": line["quantity"],
121 "unit_price_cents": line["unit_price_cents"]})
122 put(seller, "invoices", invoice["id"], {"subtotal_cents": 23200, "total_cents": 23200,
123 "status": "sent"})
124 inv_doc = sent_and_delivered(seller, "invoices", invoice["id"])
125 arrived = only(buyer.records("exchange_inbox"), document_id=inv_doc)
126 assert arrived["mapping_status"] == "mapped", arrived["mapping_reason"]
127 bill = get(buyer, "supplier_bills", arrived["mapped_record_id"])
128 assert (bill["status"], bill["total_cents"], bill["currency"], bill["number"]) == \
129 ("received", "23200", "EUR", "INV-77")
130 assert bill["purchase_order_id"] == po["id"] and bill["supplier_domain"] == seller.domain
131 assert bill["source"] == "exchange" and bill["due_date"] == "2027-01-02"
132 assert len([l for l in buyer.records("supplier_bill_lines") if l["bill_id"] == bill["id"]]) == 2
133 # Never paid automatically: no payment anywhere, and the bill waits.
134 assert buyer.records("payments") == []
135 # The supplier's document is not edited, even by its owner.
136 put(buyer, "supplier_bills", bill["id"], {"total_cents": 1}, expect=409)
137
138 # 4. A person approves and pays; the shop tells the supplier.
139 put(buyer, "supplier_bills", bill["id"], {"status": "approved"})
140 rem_doc = paid_and_remitted(buyer, seller, bill, reference="RF18539007547034")
141 put(buyer, "supplier_bills", bill["id"], {"status": "paid", "paid_on": "2026-12-20",
142 "payment_reference": "RF18539007547034"})
143
144 # 5. At the supplier the remittance is pending until the bank shows it.
145 remittance = only(seller.records("exchange_inbox"), document_id=rem_doc)
146 assert remittance["mapping_status"] == "awaiting_confirmation", remittance["mapping_reason"]
147 assert "RF18539007547034" in remittance["mapping_reason"]
148 assert seller.records("payments") == [], "a remittance is a claim, not money"
149 assert get(seller, "invoices", invoice["id"])["balance_due_cents"] == "23200"
150 status, body = seller.call("clerk", "POST", "/objects/action_exchange_confirm_remittance",
151 {"inbox_id": remittance["id"]})
152 assert status == 403, "recording a payment is staff's"
153 status, body = seller.call("owner", "POST", "/objects/action_exchange_confirm_remittance",
154 {"inbox_id": remittance["id"], "received_on": "2026-12-21"})
155 assert status == 200, body
156 [payment] = seller.records("payments")
157 assert (payment["invoice_id"], payment["amount_cents"], payment["status"],
158 payment["received_on"]) == (invoice["id"], "23200", "received", "2026-12-21")
159 assert get(seller, "invoices", invoice["id"])["balance_due_cents"] == "0"
160 status, body = seller.call("owner", "POST", "/objects/action_exchange_confirm_remittance",
161 {"inbox_id": remittance["id"]})
162 assert status == 409 and len(seller.records("payments")) == 1
163
164 # 6. A credit note points at the bill it credits.
165 credit = create(seller, "invoices", {"doc_type": "credit_note", "number": "CN-5",
166 "customer_name": "Buyer Ltd", "currency": "EUR",
167 "issue_date": "2026-12-22"})
168 create(seller, "invoice_lines", {"invoice_id": credit["id"], "description": "Damaged gasket",
169 "quantity": 1, "unit_price_cents": 400})
170 put(seller, "invoices", credit["id"], {"subtotal_cents": 400, "total_cents": 400})
171 cn_doc = sent_and_delivered(seller, "invoices", credit["id"],
172 credits_invoice_id=invoice["id"])
173 arrived = only(buyer.records("exchange_inbox"), document_id=cn_doc)
174 assert arrived["mapping_status"] == "mapped", arrived["mapping_reason"]
175 credit_bill = get(buyer, "supplier_bills", arrived["mapped_record_id"])
176 assert (credit_bill["doc_type"], credit_bill["credited_bill_id"], credit_bill["total_cents"]) == \
177 ("credit_note", bill["id"], "400")
178
179 # 7. The shop's goods receipt lands against the supplier's order.
180 receipt = create(buyer, "receipts", {"order_id": po["id"], "received_on": "2026-12-10"})
181 for line in po_lines:
182 create(buyer, "receipt_lines", {"receipt_id": receipt["id"], "order_line_id": line["id"],
183 "description": line["description"],
184 "quantity_expected": line["quantity"],
185 "quantity_received": line["quantity"]})
186 put(buyer, "receipts", receipt["id"], {"status": "received"})
187 rcpt_doc = sent_and_delivered(buyer, "receipts", receipt["id"])
188 landed = only(seller.records("exchange_inbox"), document_id=rcpt_doc)
189 assert landed["mapping_status"] == "mapped", landed["mapping_reason"]
190 assert landed["mapped_record_id"] == sale["id"] and "Widget: 12 received" in landed["mapping_reason"]
191
192 # Every document both sides hold has the same id and a verified receipt.
193 for box in (buyer, seller):
194 assert all(r["status"] == "delivered" and r["receipt_verified"] == "true"
195 for r in box.records("exchange_outbox"))
196
197
198def test_a_mapped_purchase_order_is_a_back_office_draft_that_holds_no_stock(trade):
199 """Online checkout's orders reserve stock (orders.reserves_stock,
200 object_reservations); a partner's purchase order is a draft a person
201 has not confirmed, so it must hold nothing on the shelf."""
202 import object_reservations
203 network, buyer, seller = trade
204 _, _, po_doc = purchase_order(buyer, seller)
205 sale = get(seller, "orders", only(seller.records("exchange_inbox"),
206 document_id=po_doc)["mapped_record_id"])
207 assert sale["reserves_stock"] == "false"
208 assert not object_reservations.reserves(sale)
209
210
211def test_the_customer_who_owns_an_invoice_cannot_confirm_a_remittance_for_it(trade):
212 """Checkout and the biller raise invoices OWNED BY the customer, who may
213 still update them (field-limited). Confirming a remittance records a
214 payment, which is staff's: the customer is refused and nothing is
215 written, as app-payments refuses them a payment directly."""
216 network, buyer, seller = trade
217 _, _, po_doc = purchase_order(buyer, seller)
218 sale_id = only(seller.records("exchange_inbox"), document_id=po_doc)["mapped_record_id"]
219 invoice = create(seller, "invoices", {"number": "INV-C", "customer_name": "Buyer Ltd",
220 "currency": "EUR", "issue_date": "2026-12-03",
221 "source_order_id": sale_id, "owner_id": "clerk"},
222 user="admin")
223 create(seller, "invoice_lines", {"invoice_id": invoice["id"], "description": "Widget",
224 "quantity": 1, "unit_price_cents": 500, "owner_id": "clerk"},
225 user="admin")
226 put(seller, "invoices", invoice["id"], {"subtotal_cents": 500, "total_cents": 500})
227 status, body = seller.send("invoices", invoice["id"], user="clerk")
228 assert status == 403, "a customer does not send documents in the business's name"
229 inv_doc = sent_and_delivered(seller, "invoices", invoice["id"])
230 bill_id = only(buyer.records("exchange_inbox"), document_id=inv_doc)["mapped_record_id"]
231 put(buyer, "supplier_bills", bill_id, {"status": "approved"})
232 rem_doc = paid_and_remitted(buyer, seller, get(buyer, "supplier_bills", bill_id))
233 remittance = only(seller.records("exchange_inbox"), document_id=rem_doc)
234 status, body = seller.call("clerk", "POST", "/objects/action_exchange_confirm_remittance",
235 {"inbox_id": remittance["id"]})
236 assert status == 403, body
237 # The object asks the policy too, so a grant of the action to the wrong
238 # people (or a call from inside the box) still records nothing.
239 import object_exchange_box as xbox
240 with seller.active():
241 with pytest.raises(xbox.Refusal) as refused:
242 xbox.confirm_remittance(str(seller.data_dir), remittance["id"],
243 {"user_id": "clerk", "roles": []})
244 assert refused.value.status == 403
245 assert seller.records("payments") == []
246 assert only(seller.records("exchange_inbox"),
247 document_id=rem_doc)["mapping_status"] == "awaiting_confirmation"
248 status, body = seller.call("owner", "POST", "/objects/action_exchange_confirm_remittance",
249 {"inbox_id": remittance["id"]})
250 assert status == 200 and len(seller.records("payments")) == 1, body
251
252
253def test_a_confirmation_that_differs_from_the_order_is_shown_not_applied(trade):
254 network, buyer, seller = trade
255 po, _, po_doc = purchase_order(buyer, seller)
256 sale_id = only(seller.records("exchange_inbox"), document_id=po_doc)["mapped_record_id"]
257 widget = [l for l in seller.records("order_lines")
258 if l["order_id"] == sale_id and l["description"] == "Widget"][0]
259 put(seller, "order_lines", widget["id"], {"quantity": 10})
260 # The totals handler is a reaction (off here); stamp what it would.
261 put(seller, "orders", sale_id, {"subtotal_cents": 19500, "total_cents": 19500})
262 conf_doc = sent_and_delivered(seller, "orders", sale_id, response="amended")
263 row = only(buyer.records("exchange_inbox"), document_id=conf_doc)
264 assert row["mapping_status"] == "needs_attention"
265 assert "amended" in row["mapping_reason"] and "19500" in row["mapping_reason"]
266 assert get(buyer, "orders", po["id"])["total_cents"] == "23200", "our order is not rewritten"
267
268
269def test_an_order_whose_stored_total_disagrees_with_its_lines_is_not_sent(trade):
270 """The totals handlers are reactions, off on a stock box: a line edited
271 after the total leaves the total stale. Sending either number would put
272 one in the partner's books that ours cannot reproduce, so the send is
273 refused naming both, and nothing is queued."""
274 network, buyer, seller = trade
275 order = create(buyer, "orders", {"doc_type": "purchase", "number": "PO-ODD",
276 "customer_name": "S", "currency": "EUR",
277 "order_date": "2026-12-01"})
278 create(buyer, "order_lines", {"order_id": order["id"], "description": "Widget",
279 "quantity": 1, "unit_price_cents": 100, "tax_rate_bps": 2000})
280 put(buyer, "orders", order["id"], {"subtotal_cents": 100, "tax_cents": 0, "total_cents": 100})
281 status, body = buyer.send("orders", order["id"], partner=seller.domain)
282 assert status == 409 and body["code"] == "totals_disagree", body
283 assert "is 100" in body["error"] and "come to 120" in body["error"]
284 assert buyer.records("exchange_outbox") == []
285 put(buyer, "orders", order["id"], {"tax_cents": 20, "total_cents": 120})
286 doc = sent_and_delivered(buyer, "orders", order["id"], partner=seller.domain)
287 row = only(seller.records("exchange_inbox"), document_id=doc)
288 assert row["mapping_status"] == "mapped", row["mapping_reason"]
289
290
291def test_an_order_with_no_totals_stamped_is_totalled_on_send(trade):
292 """A box with the totals handlers off never stamps a total. Phase 0
293 would have sent such an order for 0; the sender now stamps what the
294 handler would have, so its own order and the partner's agree."""
295 network, buyer, seller = trade
296 order = create(buyer, "orders", {"doc_type": "purchase", "number": "PO-RAW",
297 "customer_name": "S", "currency": "EUR",
298 "order_date": "2026-12-01"})
299 create(buyer, "order_lines", {"order_id": order["id"], "description": "Widget",
300 "quantity": "2.5", "unit_price_cents": 400, "tax_rate_bps": 2000})
301 doc = sent_and_delivered(buyer, "orders", order["id"], partner=seller.domain)
302 assert get(buyer, "orders", order["id"])["total_cents"] == "1200"
303 row = only(seller.records("exchange_inbox"), document_id=doc)
304 assert row["mapping_status"] == "mapped", row["mapping_reason"]
305 assert get(seller, "orders", row["mapped_record_id"])["total_cents"] == "1200"
306
307
308def test_a_received_order_whose_lines_do_not_add_up_is_flagged(trade):
309 """Our sender refuses to send such a thing; another engine might not.
310 The receiver checks on its own and still makes the draft, flagged."""
311 from test_exchange_protocol import envelope_from, post, wire_from
312 network, buyer, seller = trade
313 envelope = envelope_from(buyer, seller.domain, body={
314 "number": "PO-ODD", "issue_date": "2026-12-01", "currency": "EUR",
315 "lines": [{"line_id": "1", "description": "Widget", "quantity": "1",
316 "unit_price_minor": 100, "line_extension_minor": 100, "tax_rate_bps": 2000}],
317 "totals": {"line_extension_minor": 100, "tax_minor": 0, "payable_minor": 100}})
318 status, answer = post(network, seller, wire_from(buyer, envelope))
319 assert status == 200, answer
320 row = only(seller.records("exchange_inbox"), document_id=envelope["id"])
321 assert row["mapping_status"] == "needs_attention" and "come to 120" in row["mapping_reason"]
322 assert row["mapped_record_id"], "the draft order is still made, for a person to look at"
323
324
325def test_a_document_nothing_can_map_waits_and_maps_once_the_package_arrives():
326 with two_companies(["app-orders"], PACKAGES) as (network, buyer, seller):
327 connect(buyer, seller)
328 invoice = create(seller, "invoices", {"number": "INV-1", "customer_name": "Buyer Ltd",
329 "currency": "EUR", "issue_date": "2026-12-03"})
330 create(seller, "invoice_lines", {"invoice_id": invoice["id"], "description": "Widget",
331 "quantity": 1, "unit_price_cents": 500})
332 put(seller, "invoices", invoice["id"], {"subtotal_cents": 500, "total_cents": 500})
333 doc = sent_and_delivered(seller, "invoices", invoice["id"], partner=buyer.domain)
334 row = only(buyer.records("exchange_inbox"), document_id=doc)
335 assert row["mapping_status"] == "needs_attention"
336 assert "supplier_bills" in row["mapping_reason"], row["mapping_reason"]
337 status, counts = buyer.call("owner", "GET", "/collections/exchange_inbox/records"
338 "?mapping_status=needs_attention")
339 assert status == 200 and len(counts["records"]) == 1
340 with buyer.active():
341 object_packages.install_package("app-bills", root=buyer.sandbox.packages_dir,
342 base_dir=buyer.data_dir,
343 object_roots=[buyer.sandbox.objects_dir])
344 status, body = buyer.admin("remap", inbox_id=row["id"])
345 assert status == 200 and body["mapping_status"] == "mapped", body
346 status, body = buyer.admin("remap", inbox_id=row["id"])
347 assert status == 409, "a mapped document is never mapped twice"
348 assert len(buyer.records("supplier_bills")) == 1
349
350
351def test_the_partner_principal_can_create_what_documents_become_and_nothing_else(trade):
352 """What a partner can cause on our box is declared in app-exchange's
353 rules: create orders and their lines, supplier bills and their lines,
354 and the application of a credit note it sent (supplier_bill_credits).
355 Not read anything, not touch invoices or payments, not update."""
356 network, buyer, seller = trade
357 with seller.active():
358 access = object_access.Access({"user_id": "exchange-partner:shop.example",
359 "roles": ["exchange_partner"]}, base_dir=seller.data_dir)
360 row = {"id": "x", "owner_id": "owner"}
361 for collection in ("orders", "order_lines", "supplier_bills", "supplier_bill_lines",
362 "supplier_bill_credits"):
363 assert access.can("create", collection, row), collection
364 assert not access.can("read", collection, row), collection
365 assert not access.can("update", collection, row), collection
366 assert not access.can("delete", collection, row), collection
367 for collection in ("invoices", "payments", "trading_partners", "exchange_inbox",
368 "fin_journals", "contacts", "supplier_payments",
369 "supplier_payment_lines", "invoice_credits"):
370 assert not access.can("create", collection, row), collection
371
372
373def test_rules_declare_exactly_the_partner_principal_grants():
374 rules = json.loads(open("packages/app-exchange/permissions/rules.json").read())["rules"]
375 partner = sorted((r["collection"], tuple(r["actions"])) for r in rules
376 if r["principal"] == "role:exchange_partner")
377 assert partner == [("order_lines", ("create",)), ("orders", ("create",)),
378 ("supplier_bill_credits", ("create",)),
379 ("supplier_bill_lines", ("create",)), ("supplier_bills", ("create",))]