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_phase1.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_exchange_phase1.py · 35.3 KB · 637 lines
1"""Box-to-box exchange, phase 1: what the two-company simulation found missing.
2
3A Haiku simulation ran phase 0 as two real businesses -- BeanCo Roasters
4(supplier) and Brewly (a café buying from it) -- and found six gaps. Each
5test here replays one of them between two boxes in one process
6(tests/exchange_harness.py) and checks the result on BOTH boxes, because the
7point of the exchange is that the two sets of books agree without anybody
8retyping or reconciling them by hand.
9"""
10
11from __future__ import annotations
12
13import pytest
14
15import object_exchange as ex
16from exchange_harness import connect, two_companies
17
18PACKAGES = ["app-orders", "app-invoices", "app-payments", "app-bills", "app-receiving",
19 "app-catalog"]
20
21
22def create(box, collection, record, user="owner", expect=201):
23 status, body = box.call(user, "POST", f"/collections/{collection}/records", record)
24 assert status == expect, (collection, status, body)
25 return body.get("record", body)
26
27
28def put(box, collection, record_id, changes, user="owner", expect=200):
29 status, body = box.call(user, "PUT", f"/collections/{collection}/records/{record_id}", changes)
30 assert status == expect, (collection, status, body)
31 return body
32
33
34def get(box, collection, record_id):
35 status, body = box.call("admin", "GET", f"/collections/{collection}/records/{record_id}")
36 assert status == 200, body
37 return body.get("record", body)
38
39
40def only(rows, **where):
41 found = [r for r in rows if all(r.get(k) == v for k, v in where.items())]
42 assert len(found) == 1, (where, rows)
43 return found[0]
44
45
46def lines_of(box, collection, fk, parent_id):
47 return [r for r in box.records(collection) if r.get(fk) == parent_id]
48
49
50def sent_and_delivered(sender, collection, record_id, **extra):
51 status, body = sender.send(collection, record_id, **extra)
52 assert status == 200, body
53 result = sender.deliver()
54 assert result["delivered"] == 1, (result, sender.records("exchange_outbox"))
55 return body["document_id"]
56
57
58@pytest.fixture
59def trade():
60 with two_companies(PACKAGES, buyer="brewly.example", seller="beanco.example") as (
61 network, buyer, seller):
62 connect(buyer, seller)
63 yield network, buyer, seller
64
65
66# --- 3. units --------------------------------------------------------------------------
67
68def test_ten_kilograms_and_ten_bags_arrive_distinguishable(trade):
69 """Phase 0 sent every line as C62 ("one"): Brewly ordered 10 kg of
70 beans and 10 paper bags and BeanCo's box received two lines of "10".
71 Now a line carries its unit as a UN/ECE Rec 20 code -- the line's own,
72 or its product's free-text unit coded -- quantities may be decimal, and
73 both survive to the seller's order and back on the buyer's bill."""
74 network, buyer, seller = trade
75 beans = create(buyer, "products", {"name": "Yirgacheffe beans", "unit": "kg"})
76 bags = create(buyer, "products", {"name": "Paper bags", "unit": "Bags"})
77 order = create(buyer, "orders", {"doc_type": "purchase", "number": "PO-77",
78 "customer_name": "BeanCo", "currency": "EUR",
79 "order_date": "2026-12-01"})
80 for product, quantity, price in ((beans, "10.5", 2400), (bags, "10", 35)):
81 create(buyer, "order_lines", {"order_id": order["id"], "product_id": product["id"],
82 "description": product["name"], "quantity": quantity,
83 "unit_price_cents": price})
84 create(buyer, "order_lines", {"order_id": order["id"], "description": "Oat milk",
85 "quantity": "6", "unit_code": "LTR", "unit_price_cents": 210})
86 doc = sent_and_delivered(buyer, "orders", order["id"], partner=seller.domain)
87
88 # The signed document says what each quantity counts.
89 [sent] = buyer.records("exchange_outbox")
90 import json
91 lines = json.loads(sent["envelope"])["envelope"]["body"]["lines"]
92 assert sorted((l["description"], l["quantity"], l["unit_code"]) for l in lines) == [
93 ("Oat milk", "6", "LTR"), ("Paper bags", "10", "XBG"), ("Yirgacheffe beans", "10.5", "KGM")]
94
95 # The seller's draft order has the same quantities in the same units.
96 inbox = only(seller.records("exchange_inbox"), document_id=doc)
97 assert inbox["mapping_status"] == "mapped", inbox["mapping_reason"]
98 sale_lines = lines_of(seller, "order_lines", "order_id", inbox["mapped_record_id"])
99 assert sorted((l["description"], l["quantity"], l["unit_code"]) for l in sale_lines) == [
100 ("Oat milk", "6", "LTR"), ("Paper bags", "10", "XBG"), ("Yirgacheffe beans", "10.5", "KGM")]
101 assert get(seller, "orders", inbox["mapped_record_id"])["total_cents"] == str(
102 25200 + 350 + 1260)
103
104 # And they come back on the invoice as the buyer's bill lines.
105 invoice = create(seller, "invoices", {"number": "INV-9", "customer_name": "Brewly",
106 "currency": "EUR", "issue_date": "2026-12-03",
107 "source_order_id": inbox["mapped_record_id"]})
108 for line in sale_lines:
109 create(seller, "invoice_lines", {"invoice_id": invoice["id"],
110 "description": line["description"],
111 "quantity": line["quantity"],
112 "unit_code": line["unit_code"],
113 "unit_price_cents": line["unit_price_cents"]})
114 inv_doc = sent_and_delivered(seller, "invoices", invoice["id"])
115 bill_id = only(buyer.records("exchange_inbox"), document_id=inv_doc)["mapped_record_id"]
116 bill_lines = lines_of(buyer, "supplier_bill_lines", "bill_id", bill_id)
117 assert sorted((l["description"], l["quantity"], l["unit_code"]) for l in bill_lines) == [
118 ("Oat milk", "6", "LTR"), ("Paper bags", "10", "XBG"), ("Yirgacheffe beans", "10.5", "KGM")]
119
120
121def test_a_unit_nobody_can_code_is_refused_not_sent_as_one(trade):
122 """A product sold by "bunch" has no Rec 20 code this box knows. Sending
123 it as C62 is exactly the silent mistake units exist to prevent, so the
124 send is refused naming the line and the fix, and nothing is queued."""
125 network, buyer, seller = trade
126 herbs = create(buyer, "products", {"name": "Mint", "unit": "bunch"})
127 order = create(buyer, "orders", {"doc_type": "purchase", "number": "PO-78",
128 "customer_name": "BeanCo", "currency": "EUR",
129 "order_date": "2026-12-01"})
130 create(buyer, "order_lines", {"order_id": order["id"], "product_id": herbs["id"],
131 "description": "Mint", "quantity": "3",
132 "unit_price_cents": 150})
133 status, body = buyer.send("orders", order["id"], partner=seller.domain)
134 assert status == 409 and body["code"] == "unknown_unit", body
135 assert "bunch" in body["error"] and "unit_code" in body["error"]
136 assert buyer.records("exchange_outbox") == []
137 put(buyer, "order_lines", lines_of(buyer, "order_lines", "order_id", order["id"])[0]["id"],
138 {"unit_code": "H87"})
139 status, body = buyer.send("orders", order["id"], partner=seller.domain)
140 assert status == 200, body
141
142
143def test_unit_words_map_to_rec20_codes():
144 assert [ex.unit_code_for(w) for w in ("kg", "Kilograms", "KGM", "bags", "each", "l",
145 "hours", "pcs", "box", "")] == \
146 ["KGM", "KGM", "KGM", "XBG", "EA", "LTR", "HUR", "H87", "XBX", None]
147 assert ex.unit_code_for("bunch") is None
148 assert all(ex.valid_unit_code(code) for code in ex.UNIT_NAMES)
149
150
151# --- 1 and 2. part payments and credit notes that net -----------------------------------
152
153def invoice_for(seller, buyer, number, lines, *, doc_type="invoice", **extra):
154 """An invoice (or credit note) the seller raises, its totals never
155 stamped by hand: the totals handlers are off on these boxes, and sending
156 stamps what they would have."""
157 invoice = create(seller, "invoices", {"doc_type": doc_type, "number": number,
158 "customer_name": "Brewly", "currency": "EUR",
159 "issue_date": "2026-12-03", "due_date": "2027-01-02",
160 **extra})
161 for description, quantity, unit, price in lines:
162 create(seller, "invoice_lines", {"invoice_id": invoice["id"], "description": description,
163 "quantity": quantity, "unit_code": unit,
164 "unit_price_cents": price})
165 return invoice
166
167
168def bill_for(buyer, document_id):
169 row = only(buyer.records("exchange_inbox"), document_id=document_id)
170 assert row["mapping_status"] == "mapped", row["mapping_reason"]
171 return get(buyer, "supplier_bills", row["mapped_record_id"])
172
173
174def pay(buyer, seller, paid_on, reference, amounts):
175 """The buyer records one payment over several bills and tells the seller."""
176 payment = create(buyer, "supplier_payments", {"supplier_name": "BeanCo",
177 "supplier_domain": seller.domain,
178 "currency": "EUR", "paid_on": paid_on,
179 "payment_reference": reference})
180 for bill_id, amount in amounts:
181 create(buyer, "supplier_payment_lines", {"payment_id": payment["id"], "bill_id": bill_id,
182 "amount_cents": amount})
183 doc = sent_and_delivered(buyer, "supplier_payments", payment["id"])
184 return payment, doc
185
186
187def awaiting(seller, document_id):
188 row = only(seller.records("exchange_inbox"), document_id=document_id)
189 assert row["mapping_status"] == "awaiting_confirmation", row["mapping_reason"]
190 return row
191
192
193def confirm(seller, document_id, user="owner"):
194 row = awaiting(seller, document_id)
195 return row, seller.call(user, "POST", "/objects/action_exchange_confirm_remittance",
196 {"inbox_id": row["id"], "received_on": "2026-12-21"})
197
198
199def test_a_sixty_percent_payment_and_a_credit_note_leave_both_books_owing_the_same(trade):
200 """The simulation's numbers: BeanCo invoices 374.00, Brewly pays 60%
201 (224.40), BeanCo credits 18.50 for a damaged bag. Phase 0 could express
202 neither the part payment (a remittance always paid the whole bill) nor
203 the credit (it reduced nobody's balance, and BeanCo showed it as 18.50
204 DUE). Both boxes must now say 131.10 is outstanding, exactly."""
205 network, buyer, seller = trade
206 invoice = invoice_for(seller, buyer, "INV-100", [("Yirgacheffe beans", "10", "KGM", 3740)])
207 inv_doc = sent_and_delivered(seller, "invoices", invoice["id"], partner=buyer.domain)
208 assert get(seller, "invoices", invoice["id"])["total_cents"] == "37400", "stamped on send"
209 bill = bill_for(buyer, inv_doc)
210 assert (bill["total_cents"], bill["outstanding_cents"]) == ("37400", "37400")
211 put(buyer, "supplier_bills", bill["id"], {"status": "approved"})
212
213 # 60% is paid and the remittance says exactly that.
214 payment, rem_doc = pay(buyer, seller, "2026-12-20", "RF18539007547034", [(bill["id"], 22440)])
215 bill = get(buyer, "supplier_bills", bill["id"])
216 assert (bill["paid_cents"], bill["outstanding_cents"]) == ("22440", "14960")
217 import json
218 [sent] = [r for r in buyer.records("exchange_outbox") if r["document_id"] == rem_doc]
219 body = json.loads(sent["envelope"])["envelope"]["body"]
220 assert body["paid_minor"] == 22440 and body["settles"] == [
221 {"document_id": inv_doc, "number": "INV-100", "amount_minor": 22440}]
222
223 # The supplier was told: the payment is now a fact, frozen, and cannot grow.
224 assert get(buyer, "supplier_payments", payment["id"])["remitted"] == "true"
225 put(buyer, "supplier_payments", payment["id"], {"paid_on": "2026-12-19"}, expect=403)
226 put(buyer, "supplier_payments", payment["id"], {"paid_on": "2026-12-19"}, user="admin",
227 expect=409)
228 create(buyer, "supplier_payment_lines", {"payment_id": payment["id"], "bill_id": bill["id"],
229 "amount_cents": 1}, expect=403)
230
231 # At the seller it is a part payment, recorded at exactly that amount
232 # once a person has seen it in the bank.
233 row = awaiting(seller, rem_doc)
234 assert "part payment" in row["mapping_reason"] and "14960 left" in row["mapping_reason"]
235 assert seller.records("payments") == [], "a remittance is a claim until the bank shows it"
236 row, (status, answer) = confirm(seller, rem_doc)
237 assert status == 200, answer
238 [payment_row] = seller.records("payments")
239 assert payment_row["amount_cents"] == "22440"
240 assert get(seller, "invoices", invoice["id"])["balance_due_cents"] == "14960"
241
242 # A damaged bag: the seller credits 18.50 against that invoice.
243 credit = invoice_for(seller, buyer, "CN-7", [("Damaged bag", "1", "XBG", 1850)],
244 doc_type="credit_note", credits_invoice_id=invoice["id"])
245 cn_doc = sent_and_delivered(seller, "invoices", credit["id"])
246 seller_invoice = get(seller, "invoices", invoice["id"])
247 seller_credit = get(seller, "invoices", credit["id"])
248 assert seller_invoice["credited_cents"] == "1850"
249 assert seller_credit["balance_due_cents"] == "0", "a credit note is not money the customer owes"
250 assert seller_invoice["amount_paid_cents"] == "22440", "a credit is not a payment"
251 [applied] = seller.records("invoice_credits")
252 assert (applied["credit_note_id"], applied["invoice_id"], applied["amount_cents"],
253 applied["source"]) == (credit["id"], invoice["id"], "1850", "exchange")
254
255 credit_bill = bill_for(buyer, cn_doc)
256 assert (credit_bill["doc_type"], credit_bill["outstanding_cents"]) == ("credit_note", "0")
257 bill = get(buyer, "supplier_bills", bill["id"])
258 assert bill["credited_cents"] == "1850"
259
260 # Both books agree, to the cent.
261 assert seller_invoice["balance_due_cents"] == bill["outstanding_cents"] == "13110"
262 receivable = sum(int(i["balance_due_cents"]) for i in seller.records("invoices"))
263 payable = sum(int(b["outstanding_cents"]) for b in buyer.records("supplier_bills"))
264 assert receivable == payable == 13110
265
266
267def test_one_payment_settles_several_bills_and_nothing_pays_more_than_is_owed(trade):
268 network, buyer, seller = trade
269 first = invoice_for(seller, buyer, "INV-1", [("Beans", "10", "KGM", 2000)])
270 second = invoice_for(seller, buyer, "INV-2", [("Bags", "100", "XBG", 30)])
271 bills = []
272 for invoice in (first, second):
273 doc = sent_and_delivered(seller, "invoices", invoice["id"], partner=buyer.domain)
274 bill = bill_for(buyer, doc)
275 put(buyer, "supplier_bills", bill["id"], {"status": "approved"})
276 bills.append(bill)
277
278 # Paying more than a bill owes is refused before anything is sent.
279 over = create(buyer, "supplier_payments", {"supplier_name": "BeanCo",
280 "supplier_domain": seller.domain,
281 "currency": "EUR", "paid_on": "2026-12-20"})
282 create(buyer, "supplier_payment_lines", {"payment_id": over["id"], "bill_id": bills[1]["id"],
283 "amount_cents": 3001})
284 status, body = buyer.send("supplier_payments", over["id"])
285 assert status == 409 and body["code"] == "overpaid", body
286 status, body = buyer.call("owner", "DELETE", "/collections/supplier_payments/records/"
287 + over["id"])
288 for line in lines_of(buyer, "supplier_payment_lines", "payment_id", over["id"]):
289 buyer.call("owner", "DELETE", f"/collections/supplier_payment_lines/records/{line['id']}")
290
291 # A bill is still paid from the payment, not marked paid and sent.
292 status, body = buyer.send("supplier_bills", bills[0]["id"])
293 assert status == 409 and body["code"] == "send_the_payment", body
294
295 _, doc = pay(buyer, seller, "2026-12-20", "RF71", [(bills[0]["id"], 20000),
296 (bills[1]["id"], 1000)])
297 row, (status, answer) = confirm(seller, doc)
298 assert status == 200, answer
299 paid = sorted((p["invoice_id"], p["amount_cents"]) for p in seller.records("payments"))
300 assert paid == sorted([(first["id"], "20000"), (second["id"], "1000")])
301 assert get(seller, "invoices", first["id"])["balance_due_cents"] == "0"
302 assert get(seller, "invoices", second["id"])["balance_due_cents"] == "2000"
303 assert get(buyer, "supplier_bills", bills[1]["id"])["outstanding_cents"] == "2000"
304
305
306def test_a_remittance_for_more_than_an_invoice_owes_after_credits_is_not_recorded(trade):
307 """The payments hook's ceiling knows payments and refunds, not credit
308 notes. A remittance (from another engine, or a buyer whose box missed the
309 credit) for the full invoice after a credit would pass it; confirming
310 refuses it, naming what is owed, and records nothing."""
311 from test_exchange_protocol import post, wire_from
312 network, buyer, seller = trade
313 invoice = invoice_for(seller, buyer, "INV-5", [("Beans", "1", "KGM", 10000)])
314 inv_doc = sent_and_delivered(seller, "invoices", invoice["id"], partner=buyer.domain)
315 credit = invoice_for(seller, buyer, "CN-5", [("Short weight", "1", "C62", 500)],
316 doc_type="credit_note", credits_invoice_id=invoice["id"])
317 sent_and_delivered(seller, "invoices", credit["id"])
318 assert get(seller, "invoices", invoice["id"])["balance_due_cents"] == "9500"
319 envelope = ex.new_envelope(doc_id="doc-rem-full", doc_type="remittance", sender=buyer.domain,
320 recipient=seller.domain, refs=[{"id": inv_doc, "type": "invoice"}],
321 body={"currency": "EUR", "paid_minor": 10000,
322 "paid_on": "2026-12-20",
323 "settles": [{"document_id": inv_doc, "amount_minor": 10000}]})
324 status, answer = post(network, seller, wire_from(buyer, envelope))
325 assert status == 200, answer
326 row, (status, answer) = confirm(seller, "doc-rem-full")
327 assert status == 409 and answer["code"] == "more_than_owed", answer
328 assert "9500" in answer["error"] and seller.records("payments") == []
329
330
331def test_a_credit_note_for_an_invoice_we_hold_no_bill_for_stands_on_account(trade):
332 network, buyer, seller = trade
333 credit = invoice_for(seller, buyer, "CN-9", [("Goodwill", "1", "C62", 700)],
334 doc_type="credit_note")
335 doc = sent_and_delivered(seller, "invoices", credit["id"], partner=buyer.domain)
336 credit_bill = bill_for(buyer, doc)
337 assert (credit_bill["outstanding_cents"], credit_bill["credit_unapplied_cents"]) == ("0", "700")
338 assert "on account" in only(buyer.records("exchange_inbox"),
339 document_id=doc)["mapping_reason"]
340 assert get(seller, "invoices", credit["id"])["balance_due_cents"] == "0"
341 [applied] = seller.records("invoice_credits")
342 assert applied["invoice_id"] == "" and applied["amount_cents"] == "700"
343
344
345# --- 4. line-by-line confirmations ------------------------------------------------------
346
347def brewly_order(buyer, seller, number="PO-200"):
348 """Brewly's purchase order: 10 kg of beans, 10 bags, 6 litres of oat milk."""
349 order = create(buyer, "orders", {"doc_type": "purchase", "number": number,
350 "customer_name": "BeanCo", "currency": "EUR",
351 "order_date": "2026-12-01"})
352 lines = {}
353 for description, quantity, unit, price in (("Yirgacheffe beans", "10", "KGM", 2400),
354 ("Paper bags", "10", "XBG", 35),
355 ("Oat milk", "6", "LTR", 210)):
356 lines[description] = create(buyer, "order_lines", {
357 "order_id": order["id"], "description": description, "quantity": quantity,
358 "unit_code": unit, "unit_price_cents": price})
359 doc = sent_and_delivered(buyer, "orders", order["id"], partner=seller.domain)
360 inbox = only(seller.records("exchange_inbox"), document_id=doc)
361 return order, lines, inbox["mapped_record_id"]
362
363
364def amend(seller, sale_id):
365 """BeanCo can ship 8 kg, not 10; bags went up to 40c; no oat milk; and it
366 adds a free-ish sample. Then it stamps the totals itself, as a box with
367 the totals handlers off must."""
368 sale_lines = {l["description"]: l for l in lines_of(seller, "order_lines", "order_id", sale_id)}
369 put(seller, "order_lines", sale_lines["Yirgacheffe beans"]["id"], {"quantity": "8"})
370 put(seller, "order_lines", sale_lines["Paper bags"]["id"], {"unit_price_cents": 40})
371 status, body = seller.call("owner", "DELETE",
372 f"/collections/order_lines/records/{sale_lines['Oat milk']['id']}")
373 assert status in (200, 204), body
374 create(seller, "order_lines", {"order_id": sale_id, "description": "Decaf sample",
375 "quantity": "1", "unit_code": "XBG", "unit_price_cents": 500})
376 total = 8 * 2400 + 10 * 40 + 500
377 put(seller, "orders", sale_id, {"subtotal_cents": total, "total_cents": total})
378 return total
379
380
381def test_a_confirmation_is_compared_line_by_line_and_accepting_it_is_a_recorded_change(trade):
382 """Phase 0 compared a confirmation on its answer and total only, and a
383 flagged difference had no way to be resolved. Now each line is
384 answered and compared -- quantity, unit, price, rejected, added -- every
385 difference is listed, and a person accepts (our order becomes what was
386 confirmed, each write under their name) or rejects it."""
387 import json
388 import object_record_changes
389 network, buyer, seller = trade
390 order, lines, sale_id = brewly_order(buyer, seller)
391 total = amend(seller, sale_id)
392
393 # The seller cannot call a changed order "accepted": the lines say amended.
394 status, body = seller.send("orders", sale_id, response="accepted")
395 assert status == 409 and body["code"] == "response_disagrees" and body["derived"] == "amended"
396 conf_doc = sent_and_delivered(seller, "orders", sale_id)
397 [sent] = [r for r in seller.records("exchange_outbox") if r["document_id"] == conf_doc]
398 sent_body = json.loads(sent["envelope"])["envelope"]["body"]
399 assert sent_body["response"] == "amended"
400 assert sorted((l["description"], l["line_status"]) for l in sent_body["lines"]) == [
401 ("Decaf sample", "added"), ("Oat milk", "rejected"), ("Paper bags", "changed"),
402 ("Yirgacheffe beans", "changed")]
403
404 # The buyer sees every difference, and its order is untouched.
405 row = only(buyer.records("exchange_inbox"), document_id=conf_doc)
406 assert row["mapping_status"] == "needs_attention"
407 reason = row["mapping_reason"]
408 for words in ("line 'Yirgacheffe beans': quantity 10 -> 8",
409 "line 'Paper bags': unit price 35 -> 40", "line 'Oat milk' rejected",
410 "line 'Decaf sample' added: 1 XBG at 500"):
411 assert words in reason, (words, reason)
412 assert get(buyer, "orders", order["id"])["total_cents"] == str(24000 + 350 + 1260)
413
414 # A customer account cannot decide; staff can.
415 status, body = buyer.call("clerk", "POST", "/objects/action_exchange_resolve",
416 {"inbox_id": row["id"], "decision": "accept"})
417 assert status == 403, body
418 status, body = buyer.call("owner", "POST", "/objects/action_exchange_resolve",
419 {"inbox_id": row["id"], "decision": "accept"})
420 assert status == 200, body
421
422 ours = {l["description"]: l for l in lines_of(buyer, "order_lines", "order_id", order["id"])}
423 assert (ours["Yirgacheffe beans"]["quantity"], ours["Paper bags"]["unit_price_cents"],
424 ours["Oat milk"]["quantity"]) == ("8", "40", "0")
425 assert (ours["Decaf sample"]["quantity"], ours["Decaf sample"]["unit_code"]) == ("1", "XBG")
426 assert get(buyer, "orders", order["id"])["total_cents"] == str(total), \
427 "both companies' orders now say the same"
428 with buyer.active():
429 change = object_record_changes.latest_record_change(
430 "order_lines", lines["Yirgacheffe beans"]["id"], base_dir=str(buyer.data_dir))
431 assert "exchange-accept:owner" in json.dumps(change), change
432 row = only(buyer.records("exchange_inbox"), document_id=conf_doc)
433 assert (row["mapping_status"], row["resolution"], row["resolved_by"]) == \
434 ("mapped", "accepted", "owner")
435 status, body = buyer.call("owner", "POST", "/objects/action_exchange_resolve",
436 {"inbox_id": row["id"], "decision": "accept"})
437 assert status == 409, "decided once"
438
439
440def test_rejecting_an_amended_confirmation_leaves_our_order_alone(trade):
441 network, buyer, seller = trade
442 order, lines, sale_id = brewly_order(buyer, seller, "PO-201")
443 amend(seller, sale_id)
444 conf_doc = sent_and_delivered(seller, "orders", sale_id)
445 row = only(buyer.records("exchange_inbox"), document_id=conf_doc)
446 before = sorted((l["description"], l["quantity"], l["unit_price_cents"])
447 for l in lines_of(buyer, "order_lines", "order_id", order["id"]))
448 status, body = buyer.call("owner", "POST", "/objects/action_exchange_resolve",
449 {"inbox_id": row["id"], "decision": "reject",
450 "note": "we need the full 10 kg"})
451 assert status == 200, body
452 after = sorted((l["description"], l["quantity"], l["unit_price_cents"])
453 for l in lines_of(buyer, "order_lines", "order_id", order["id"]))
454 assert after == before
455 row = only(buyer.records("exchange_inbox"), document_id=conf_doc)
456 assert row["resolution"] == "rejected" and "we need the full 10 kg" in row["mapping_reason"]
457
458
459def test_a_confirmation_as_ordered_maps_cleanly_line_by_line(trade):
460 network, buyer, seller = trade
461 order, lines, sale_id = brewly_order(buyer, seller, "PO-202")
462 conf_doc = sent_and_delivered(seller, "orders", sale_id)
463 row = only(buyer.records("exchange_inbox"), document_id=conf_doc)
464 assert row["mapping_status"] == "mapped" and "as ordered" in row["mapping_reason"]
465 status, body = buyer.call("owner", "POST", "/objects/action_exchange_resolve",
466 {"inbox_id": row["id"], "decision": "accept"})
467 assert status == 409, "nothing to decide"
468
469
470# --- 5. disconnect notices and refusals ------------------------------------------------
471
472def partner_row(box, domain):
473 return only(box.records("trading_partners"), domain=domain)
474
475
476def test_disconnecting_tells_the_other_side_which_stops_sending(trade):
477 """Phase 0: BeanCo disconnected Brewly and Brewly's box still showed it
478 connected and kept sending. Now the other box gets a signed notice and
479 records the partner as disconnected by them, with the reason."""
480 network, buyer, seller = trade
481 status, body = seller.admin("disconnect", partner_id=partner_row(seller, buyer.domain)["id"],
482 reason="account closed")
483 assert status == 200 and body["notified"] is True, body
484 theirs = partner_row(buyer, seller.domain)
485 assert (theirs["status"], theirs["disconnected_by"], theirs["disconnect_reason"]) == \
486 ("disconnected", "them", "account closed")
487 assert "ended the connection: account closed" in theirs["last_error"]
488 assert partner_row(seller, buyer.domain)["disconnected_by"] == "us"
489 order = create(buyer, "orders", {"doc_type": "purchase", "number": "PO-9",
490 "customer_name": "BeanCo", "currency": "EUR",
491 "order_date": "2026-12-01"})
492 create(buyer, "order_lines", {"order_id": order["id"], "description": "Beans",
493 "quantity": "1", "unit_code": "KGM", "unit_price_cents": 100})
494 status, body = buyer.send("orders", order["id"], partner=seller.domain)
495 assert status == 409 and body["code"] == "not_connected", body
496
497
498def test_a_notice_that_cannot_be_delivered_still_disconnects_us(trade):
499 network, buyer, seller = trade
500 network.down.add(buyer.domain)
501 status, body = seller.admin("disconnect", partner_id=partner_row(seller, buyer.domain)["id"])
502 network.down.discard(buyer.domain)
503 assert status == 200 and body["notified"] is False and "could not be told" in body["message"]
504 assert partner_row(seller, buyer.domain)["status"] == "disconnected"
505 assert partner_row(buyer, seller.domain)["status"] == "connected"
506
507
508def test_a_notice_from_a_stranger_or_an_old_relationship_ends_nothing(trade):
509 from test_exchange_protocol import post, wire_from
510 network, buyer, seller = trade
511 stale = ex.new_envelope(doc_id="end-old", doc_type="connection_end", sender=seller.domain,
512 recipient=buyer.domain, body={}, created_at="2020-01-01T00:00:00Z")
513 status, answer = post(network, buyer, wire_from(seller, stale))
514 assert status == 409 and answer["code"] == "stale_notice", answer
515 assert partner_row(buyer, seller.domain)["status"] == "connected"
516
517
518def test_a_document_the_partner_refuses_is_recorded_as_refused_with_its_signed_reason(trade):
519 """A type the partner does not take is refused AFTER its box verified
520 who sent it, so the answer is a signed refusal receipt. The sender
521 keeps it, marks the outbox row refused (attention), and the order says
522 so -- phase 0 left a dead row and the order looked sent."""
523 network, buyer, seller = trade
524 status, body = seller.admin("set_types", partner_id=partner_row(seller, buyer.domain)["id"],
525 receive_types=["remittance", "receipt"])
526 assert status == 200, body
527 order = create(buyer, "orders", {"doc_type": "purchase", "number": "PO-10",
528 "customer_name": "BeanCo", "currency": "EUR",
529 "order_date": "2026-12-01"})
530 create(buyer, "order_lines", {"order_id": order["id"], "description": "Beans",
531 "quantity": "1", "unit_code": "KGM", "unit_price_cents": 100})
532 status, body = buyer.send("orders", order["id"], partner=seller.domain)
533 assert status == 200, body
534 result = buyer.deliver()
535 assert result["delivered"] == 0
536 [row] = buyer.records("exchange_outbox")
537 assert row["status"] == "refused", row
538 assert "does not accept purchase_order" in row["refusal_reason"]
539 import json
540 refusal = json.loads(row["refusal"])
541 assert refusal["receipt"]["status"] == "refused" and refusal["receipt"]["code"] == "type_not_allowed"
542 assert get(buyer, "orders", order["id"])["exchange_status"].startswith(
543 f"Refused by {seller.domain}: ")
544 status, counts = buyer.call("owner", "GET",
545 "/collections/exchange_outbox/records?status=refused")
546 assert status == 200 and len(counts["records"]) == 1
547
548
549def test_a_person_refusing_an_invoice_tells_the_seller_whose_invoice_then_says_so(trade):
550 network, buyer, seller = trade
551 invoice = invoice_for(seller, buyer, "INV-X", [("Beans", "5", "KGM", 2000)])
552 doc = sent_and_delivered(seller, "invoices", invoice["id"], partner=buyer.domain)
553 inbox = only(buyer.records("exchange_inbox"), document_id=doc)
554 status, body = buyer.call("clerk", "POST", "/objects/action_exchange_resolve",
555 {"inbox_id": inbox["id"], "decision": "refuse",
556 "note": "not our order"})
557 assert status == 403, body
558 status, body = buyer.call("owner", "POST", "/objects/action_exchange_resolve",
559 {"inbox_id": inbox["id"], "decision": "refuse"})
560 assert status == 400, "a refusal says why"
561 status, body = buyer.call("owner", "POST", "/objects/action_exchange_resolve",
562 {"inbox_id": inbox["id"], "decision": "refuse",
563 "note": "not our order"})
564 assert status == 200, body
565
566 # The buyer: decided, and the bill is disputed rather than waiting to be paid.
567 inbox = only(buyer.records("exchange_inbox"), document_id=doc)
568 assert (inbox["resolution"], inbox["resolved_by"]) == ("refused", "owner")
569 assert get(buyer, "supplier_bills", inbox["mapped_record_id"])["status"] == "disputed"
570
571 # The seller: the outbox row and the invoice both say so, with attention.
572 [row] = [r for r in seller.records("exchange_outbox") if r["document_id"] == doc]
573 assert row["status"] == "refused" and "not our order" in row["refusal_reason"]
574 assert get(seller, "invoices", invoice["id"])["exchange_status"] == \
575 f"Refused by {buyer.domain}: not our order (refused_by_person)"
576 status, body = buyer.call("owner", "POST", "/objects/action_exchange_resolve",
577 {"inbox_id": inbox["id"], "decision": "refuse", "note": "again"})
578 assert status == 409
579
580
581def test_a_refusal_must_name_a_document_we_sent_that_partner(trade):
582 from test_exchange_protocol import post, wire_from
583 network, buyer, seller = trade
584 forged = ex.new_envelope(doc_id="refusal-x", doc_type="document_refusal",
585 sender=buyer.domain, recipient=seller.domain,
586 body={"document_id": "doc-never-sent", "envelope_sha256": "0" * 64,
587 "reason": "no"})
588 status, answer = post(network, seller, wire_from(buyer, forged))
589 assert status == 404 and answer["code"] == "unknown_document", answer
590
591
592# --- 6. what a box needs to trade, said in plain words ---------------------------------
593
594def checks_of(box, user="owner"):
595 status, body = box.admin("check", user=user)
596 assert status == 200, body
597 return body, {c["id"]: c for c in body["checks"]}
598
599
600def test_the_setup_check_says_what_a_box_needs_and_how_to_fix_it(monkeypatch):
601 """The simulation's setup needed someone who knew the internals. The
602 check names each thing -- the trading name, the key and where its backup
603 is, the daemon, the totals reactions, who holds which role, partners,
604 packages -- with the fix, and it changes nothing."""
605 import importlib.util
606 import pathlib
607 with two_companies(PACKAGES, buyer="brewly.example", seller="beanco.example") as (
608 network, buyer, seller):
609 body, checks = checks_of(buyer)
610 assert body["ready"] is False and checks["daemon"]["severity"] == "error"
611 assert "object_daemon.py" in checks["daemon"]["fix"]
612 assert checks["domain"]["ok"] and "brewly.example" in checks["domain"]["finding"]
613 key = checks["key"]
614 assert key["severity"] == "warning" and "exchange/private/" in key["finding"]
615 assert "record_key_backup" in key["fix"]
616 assert checks["totals"]["severity"] == "warning"
617 assert "DBBASIC_ENABLE_CHANGE_DISPATCH" in checks["totals"]["fix"]
618 assert checks["roles"]["ok"] and "owner" in checks["roles"]["finding"]
619 assert checks["partners"]["severity"] == "warning" and "connect" in checks["partners"]["fix"]
620 assert checks["packages"]["ok"], checks["packages"]
621
622 status, answer = buyer.admin("check", user="clerk")
623 assert status == 403, "the check is for whoever runs the box"
624
625 # Each fix, made, turns its check green.
626 status, answer = buyer.admin("record_key_backup", where="1Password, vault Ops")
627 assert status == 200, answer
628 (pathlib.Path(buyer.data_dir) / ".daemon_heartbeat").write_text("{}\n")
629 monkeypatch.setenv("DBBASIC_ENABLE_EVENT_HANDLERS", "true")
630 connect(buyer, seller)
631 body, checks = checks_of(buyer)
632 assert checks["key"]["ok"] and "1Password, vault Ops" in checks["key"]["finding"]
633 assert checks["daemon"]["ok"] and checks["totals"]["ok"] and checks["partners"]["ok"]
634 if importlib.util.find_spec("croniter") is None:
635 assert checks["scheduler"]["severity"] == "error"
636 else:
637 assert body["ready"] is True, body