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_counter_exchange.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_counter_exchange.py · 12.7 KB · 234 lines
1"""The counter's corrections and the box-to-box exchange, on one set of books.
2
3Two lines of work met here: the café (Corner Cup) corrects a sale by new
4records that cite the line -- a void before payment, a line refund or credit
5note after -- and the exchange (BeanCo and Brewly) sends invoices and credit
6notes to a trading partner's box so both companies' books agree. A sale can
7be both: a counter that also invoices a business customer over the exchange.
8Each test checks that a correction made at the counter keeps the two boxes
9agreeing, through the HTTP API with permission enforcement on.
10"""
11
12from __future__ import annotations
13
14import pytest
15
16import object_records
17from exchange_harness import connect, two_companies
18
19PACKAGES = ["app-orders", "app-invoices", "app-payments", "app-bills", "app-receiving",
20 "app-catalog", "app-settings", "app-counter"]
21
22
23def create(box, collection, record, user="owner", expect=201):
24 status, body = box.call(user, "POST", f"/collections/{collection}/records", record)
25 assert status == expect, (collection, status, body)
26 return body.get("record", body)
27
28
29def get(box, collection, record_id):
30 status, body = box.call("admin", "GET", f"/collections/{collection}/records/{record_id}")
31 assert status == 200, body
32 return body.get("record", body)
33
34
35def stamp(box, collection, record):
36 """An in-process writer's row (checkout's, here): it may set the
37 read_only link an invoice line carries to the order line it bills."""
38 with box.active():
39 return object_records.create_collection_record(collection, record,
40 base_dir=box.data_dir,
41 preserve_read_only=True)
42
43
44@pytest.fixture
45def trade():
46 with two_companies(PACKAGES, buyer="brewly.example", seller="beanco.example") as (
47 network, buyer, seller):
48 connect(buyer, seller)
49 yield network, buyer, seller
50
51
52def sale(seller, buyer, number, lines):
53 """A sale order and its issued invoice, each invoice line linked to the
54 order line it bills (as app-shop's checkout links them)."""
55 order = create(seller, "orders", {"number": f"SO-{number}", "customer_name": "Brewly",
56 "currency": "EUR", "order_date": "2026-12-01"})
57 invoice = create(seller, "invoices", {"number": number, "customer_name": "Brewly",
58 "currency": "EUR", "issue_date": "2026-12-03",
59 "due_date": "2027-01-02", "status": "sent",
60 "source_order_id": order["id"]})
61 out = []
62 for description, quantity, unit, price in lines:
63 line = create(seller, "order_lines", {"order_id": order["id"],
64 "description": description,
65 "quantity": quantity, "unit_code": unit,
66 "unit_price_cents": price})
67 billing = stamp(seller, "invoice_lines", {
68 "invoice_id": invoice["id"], "order_line_id": line["id"],
69 "description": description, "quantity": quantity, "unit_code": unit,
70 "unit_price_cents": str(price), "owner_id": "owner"})
71 out.append((line, billing))
72 # The totals the handlers would stamp (they are off on these boxes).
73 total = sum(int(float(q) * p) for _, q, _, p in lines)
74 with seller.active():
75 for collection, row in (("orders", order), ("invoices", invoice)):
76 object_records.update_collection_record(
77 collection, row["id"], {"subtotal_cents": str(total), "total_cents": str(total)},
78 base_dir=seller.data_dir)
79 return order, invoice, out
80
81
82def test_a_line_of_an_invoice_sent_to_a_partner_is_not_voided_at_the_counter(trade):
83 """Voiding restates our invoice by the line. Once the invoice is in the
84 partner's books as signed, doing that on one box alone is exactly the
85 disagreement the exchange exists to prevent: the void refuses and names
86 the credit note instead, and nothing changes."""
87 network, buyer, seller = trade
88 order, invoice, [(beans, _), (bags, _)] = sale(
89 seller, buyer, "INV-300", [("Beans", "10", "KGM", 2000), ("Bags", "10", "XBG", 30)])
90 status, body = seller.send("invoices", invoice["id"], partner=buyer.domain)
91 assert status == 200, body
92 status, body = seller.call("owner", "POST", "/objects/action_counter_void",
93 {"order_line_id": bags["id"], "reason_code": "customer_error"})
94 assert status == 409 and body["sent_to"] == [buyer.domain], body
95 assert "credit note" in body["error"]
96 assert get(seller, "order_lines", bags["id"])["quantity"] == "10"
97 assert get(seller, "invoices", invoice["id"])["total_cents"] == "20300"
98
99
100def only(rows, **where):
101 found = [r for r in rows if all(r.get(k) == v for k, v in where.items())]
102 assert len(found) == 1, (where, rows)
103 return found[0]
104
105
106def sent_and_delivered(sender, collection, record_id, **extra):
107 status, body = sender.send(collection, record_id, **extra)
108 assert status == 200, body
109 assert sender.deliver()["delivered"] == 1, sender.records("exchange_outbox")
110 return body["document_id"]
111
112
113def bill_for(buyer, document_id):
114 row = only(buyer.records("exchange_inbox"), document_id=document_id)
115 assert row["mapping_status"] == "mapped", row["mapping_reason"]
116 return get(buyer, "supplier_bills", row["mapped_record_id"])
117
118
119def pay_sixty_percent(buyer, seller, bill, invoice):
120 """Brewly pays 224.40 of the 374.00 and BeanCo confirms it in the bank."""
121 status, body = buyer.call("owner", "PUT", f"/collections/supplier_bills/records/{bill['id']}",
122 {"status": "approved"})
123 assert status == 200, body
124 payment = create(buyer, "supplier_payments", {"supplier_name": "BeanCo",
125 "supplier_domain": seller.domain,
126 "currency": "EUR", "paid_on": "2026-12-20",
127 "payment_reference": "RF18"})
128 create(buyer, "supplier_payment_lines", {"payment_id": payment["id"], "bill_id": bill["id"],
129 "amount_cents": 22440})
130 doc = sent_and_delivered(buyer, "supplier_payments", payment["id"])
131 row = only(seller.records("exchange_inbox"), document_id=doc)
132 status, body = seller.call("owner", "POST", "/objects/action_exchange_confirm_remittance",
133 {"inbox_id": row["id"], "received_on": "2026-12-21"})
134 assert status == 200, body
135 assert get(seller, "invoices", invoice["id"])["balance_due_cents"] == "14960"
136
137
138def test_a_credit_note_issued_at_the_counter_nets_like_one_sent_through_the_exchange(trade):
139 """The phase 1 numbers, with the credit issued the counter's way: BeanCo
140 invoices 374.00 (beans, and the bag they came in), Brewly pays 60%, and
141 the bag arrives damaged. A person at BeanCo gives the bag back with
142 action_counter_correct -- citing the line, with a reason code, approved
143 -- and then sends that credit note to Brewly.
144
145 There is one credit-note model: the counter's credit note is applied in
146 the act that issues it (an invoice_credits row, source counter), so
147 BeanCo's invoice owes 131.10 before anything is sent; sending it applies
148 nothing twice and carries the line with ref_line_id naming the credited
149 invoice line; and Brewly's box ends at 131.10 too."""
150 network, buyer, seller = trade
151 order, invoice, [(beans, beans_billed), (bag, bag_billed)] = sale(
152 seller, buyer, "INV-400", [("Yirgacheffe beans", "10", "KGM", 3555),
153 ("Bag", "1", "XBG", 1850)])
154 inv_doc = sent_and_delivered(seller, "invoices", invoice["id"], partner=buyer.domain)
155 assert get(seller, "invoices", invoice["id"])["total_cents"] == "37400"
156 bill = bill_for(buyer, inv_doc)
157 pay_sixty_percent(buyer, seller, bill, invoice)
158
159 # The bag, cited, with a reason; the owner approves their own correction.
160 status, body = seller.call("owner", "POST", "/objects/action_counter_correct",
161 {"order_line_id": bag["id"], "quantity": "1",
162 "reason_code": "quality", "settle": "credit_note"})
163 assert status == 200, body
164 assert body["amount_cents"] == 1850 and body["approved_by"] == "owner"
165 note = get(seller, "invoices", body["credit_note_id"])
166 assert (note["doc_type"], note["credits_invoice_id"], note["reason_code"]) == (
167 "credit_note", invoice["id"], "quality")
168 [credit_line] = [l for l in seller.records("invoice_lines") if l["invoice_id"] == note["id"]]
169 assert (credit_line["order_line_id"], credit_line["credits_line_id"]) == (
170 bag["id"], bag_billed["id"])
171
172 # Applied as it was issued, exactly as the exchange applies one it sends.
173 [applied] = seller.records("invoice_credits")
174 assert (applied["credit_note_id"], applied["invoice_id"], applied["amount_cents"],
175 applied["source"]) == (note["id"], invoice["id"], "1850", "counter")
176 assert get(seller, "invoices", invoice["id"])["balance_due_cents"] == "13110"
177 assert get(seller, "invoices", note["id"])["balance_due_cents"] == "0"
178 assert get(seller, "invoices", invoice["id"])["amount_paid_cents"] == "22440", \
179 "a credit is not a payment"
180
181 # Sent: the line says which invoice line it gives back; nothing applies twice.
182 cn_doc = sent_and_delivered(seller, "invoices", note["id"])
183 import json
184 [sent] = [r for r in seller.records("exchange_outbox") if r["document_id"] == cn_doc]
185 envelope = json.loads(sent["envelope"])["envelope"]
186 assert envelope["type"] == "credit_note"
187 assert {"id": inv_doc, "type": "invoice"} in envelope["refs"]
188 [line] = envelope["body"]["lines"]
189 assert (line["ref_line_id"], line["quantity"], line["unit_code"],
190 line["line_extension_minor"]) == (bag_billed["id"], "1", "XBG", 1850)
191 assert len(seller.records("invoice_credits")) == 1
192
193 # Both books agree, to the cent.
194 credit_bill = bill_for(buyer, cn_doc)
195 assert (credit_bill["doc_type"], credit_bill["outstanding_cents"]) == ("credit_note", "0")
196 bill = get(buyer, "supplier_bills", bill["id"])
197 seller_invoice = get(seller, "invoices", invoice["id"])
198 assert seller_invoice["balance_due_cents"] == bill["outstanding_cents"] == "13110"
199 receivable = sum(int(i["balance_due_cents"]) for i in seller.records("invoices"))
200 payable = sum(int(b["outstanding_cents"]) for b in buyer.records("supplier_bills"))
201 assert receivable == payable == 13110
202
203 # And the bag cannot be given back again, by credit note or refund.
204 for settle in ("credit_note", "refund"):
205 status, body = seller.call("owner", "POST", "/objects/action_counter_correct",
206 {"order_line_id": bag["id"], "quantity": "1",
207 "reason_code": "quality", "settle": settle})
208 assert status == 409, (settle, body)
209
210
211def test_a_hand_made_credit_note_citing_the_line_meets_the_same_ceiling(trade):
212 """A credit note made by hand cites the order line the same way the
213 counter's does, so the never-more-than-sold rule counts it: the counter
214 cannot then give the same unit back again."""
215 network, buyer, seller = trade
216 order, invoice, [(beans, beans_billed)] = sale(
217 seller, buyer, "INV-401", [("Beans", "2", "KGM", 2000)])
218 status, body = seller.call("owner", "POST", "/collections/payments/records",
219 {"invoice_id": invoice["id"], "amount_cents": "4000",
220 "method": "cash", "received_on": "2026-12-04"})
221 assert status == 201, body
222 note = create(seller, "invoices", {"doc_type": "credit_note", "number": "CN-401",
223 "customer_name": "Brewly", "currency": "EUR",
224 "issue_date": "2026-12-05", "status": "sent",
225 "credits_invoice_id": invoice["id"]})
226 stamp(seller, "invoice_lines", {"invoice_id": note["id"], "order_line_id": beans["id"],
227 "credits_line_id": beans_billed["id"],
228 "description": "Credit: Beans", "quantity": "2",
229 "unit_code": "KGM", "unit_price_cents": "2000",
230 "owner_id": "owner"})
231 status, body = seller.call("owner", "POST", "/objects/action_counter_correct",
232 {"order_line_id": beans["id"], "quantity": "1",
233 "reason_code": "quality", "settle": "credit_note"})
234 assert status == 409 and "already corrected" in body["error"], body