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/object_exchange_box.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, 8 minutes ago History
object_exchange_box.py · 122.1 KB · 2299 lines
1"""object_exchange_box -- one box's side of the exchange: who it is, who its
2partners are, what arrived and what it sends.
3
4object_exchange holds the primitives (canonical bytes, keys, signatures,
5the transport). This module reads and writes the app-exchange collections
6and is what the package's objects call: the profile at
7`/.well-known/dbbasic`, the inbound endpoint (`POST /webhooks/exchange`,
8the core raw-body route, so the bytes we keep are the bytes that arrived),
9the operator's actions and the daemon's delivery pass. It lives at the
10root rather than inside the package because four objects share it and
11package objects cannot import one another; it imports no optional
12dependency itself (everything signed goes through object_exchange).
13
14## Who is trusted, and for what
15
16- **A partner is explicit and mutual** (trading_partners). Box A asks
17 (`connect`): it fetches B's profile from B's own domain, pins the keys it
18 lists, and sends B a signed `connection_request` carrying A's profile.
19 B stores the request as `pending` and does nothing else: it makes no
20 outbound request on behalf of a stranger (an unknown sender must not be
21 able to make our box fetch URLs). B's operator `accept`s: only then does
22 B fetch A's profile from A's domain, check that the key the request was
23 signed with is the one A's domain publishes, pin A's keys and answer with
24 a signed `connection_accept`, which A verifies against the keys it pinned
25 when it asked. Either side `disconnect`s; the next delivery is refused,
26 because every inbound check re-reads the partner row.
27- **Pinned keys, not the profile, decide.** A document verifies only against
28 keys pinned for that partner. A partner who rotates sends, with each
29 delivery, the vouches its keys carry (the old key signing the new one); a
30 new key is pinned only when a key we already pinned vouched for it. A key
31 nobody vouched for is refused, and the partner must reconnect.
32- **The partner principal.** Turning a document into records (`_map_*`)
33 runs as a synthetic subject, `exchange-partner:<domain>` with the single
34 role `exchange_partner`, asked through object_access like any other
35 writer. app-exchange's rules grant that role create on exactly the
36 collections a document becomes (orders and order_lines, supplier_bills
37 and supplier_bill_lines) and nothing else, so what a partner can cause on
38 our box is declared in a rules file a reviewer can read, not decided here.
39
40## The inbound checks, in order
41
42Size, shape, the sender is a connected partner (one answer for unknown and
43disconnected, so the endpoint does not tell a prober who our partners
44are), both signatures are by keys pinned for it (the document's and the
45delivery's), the delivery names this envelope and its stamp is inside the
46clock window, the recipient is us, the document is well formed, its type
47is one this partner may send us, and its (sender, id) is new. Only then is
48it written -- verbatim, frozen by `locked_when`, with `unique` on (sender,
49id) deciding a race inside the write lock -- and a receipt signed. A
50duplicate (sender, id) with the same envelope stores nothing and gets back
51the receipt the first one got; the same id with a different envelope is a
52409, because answering it with the first document's receipt would tell the
53sender we stored something we did not.
54
55## Reactions after the write
56
57Mapping into business records happens after the inbox row exists, in the
58same request: this is a storage-level writer, so it performs its own
59reaction (docs/logic-decisions.md #9) rather than relying on a change
60dispatcher that is off on a stock install. It never changes the receipt:
61the receipt means "stored and verified", not "accepted by the business".
62A document that cannot be mapped stays in the inbox with the reason and
63`mapping_status = needs_attention`, which the package declares as an
64attention queue. An invoice becomes a supplier bill in `received`; nothing
65here, or anywhere in the exchange, pays one.
66
67## Delivery
68
69Sending writes a signed envelope into exchange_outbox and returns; the
70daemon's pass (`deliver_due`, scheduled by app-exchange) posts each due row
71with a freshly signed delivery stamp, verifies the receipt that comes back
72against the partner's pinned keys, and retries with exponential backoff on
73no answer or a 5xx. Retrying is safe because delivery is idempotent at the
74receiver (unique (sender, id)), and costs nothing: this is not a paid call.
75Two passes overlapping can deliver the same row twice; the receiver stores
76it once and returns one receipt, so no claim is taken.
77"""
78
79from __future__ import annotations
80
81import json
82import os
83from datetime import datetime, timedelta, timezone
84from decimal import Decimal, InvalidOperation
85from typing import Any, Mapping
86
87import object_access
88import object_collections
89import object_exchange as ex
90import object_ids
91import object_lines
92import object_records
93import object_schemas
94
95ACTOR = "exchange"
96PARTNER_ROLE = "exchange_partner"
97# Besides the policy's admin roles (admin, superuser by default), the role
98# that may manage partners and keys: the business's owner.
99MANAGER_ROLE = "owner"
100IDENTITY_ID = "self"
101
102# A box holds at most this many unanswered connection requests. Strangers
103# can make them (that is what a request is), so they are bounded.
104MAX_PENDING_REQUESTS = 100
105
106RETRY_BASE_SECONDS = 60
107RETRY_MAX_SECONDS = 6 * 3600
108MAX_ATTEMPTS = 12
109
110MAPPED = "mapped"
111NEEDS_ATTENTION = "needs_attention"
112AWAITING_CONFIRMATION = "awaiting_confirmation"
113
114
115class Refusal(Exception):
116 """An answer that is not a success: an HTTP status, a stable code and a
117 sentence for a person."""
118
119 def __init__(self, status: int, code: str, message: str, **extra: Any):
120 super().__init__(message)
121 self.status = status
122 self.code = code
123 self.message = message
124 self.extra = extra
125
126 def answer(self) -> dict[str, Any]:
127 return {"status": self.status, "ok": False, "code": self.code,
128 "error": self.message, **self.extra}
129
130
131def base_dir() -> str:
132 return os.environ.get("DBBASIC_DATA_DIR", "data")
133
134
135def _text(value: Any) -> str:
136 return str(value if value is not None else "").strip()
137
138
139def _now() -> datetime:
140 return datetime.now(timezone.utc)
141
142
143def _rows(collection: str, base: str) -> list[dict[str, Any]]:
144 """Every row; [] when the collection is not installed (a fact: nothing
145 is there). Any other failure propagates: unreadable is not empty."""
146 try:
147 return object_records.read_collection_records(collection, base_dir=base)
148 except object_collections.CollectionNotFoundError:
149 return []
150
151
152def _installed(collection: str, base: str) -> bool:
153 """A package declared it. Not "the name is known": a permission rule
154 naming a collection makes the name known (app-exchange's own rules name
155 supplier_bills), and writing to a collection nobody declared would make
156 rows no schema validates."""
157 try:
158 schema = object_schemas.get_schema(collection, base_dir=base)
159 except (object_schemas.SchemaNotFoundError, object_collections.CollectionNotFoundError):
160 return False
161 return schema.get("source") != "derived" and bool(schema.get("fields"))
162
163
164def _get(collection: str, record_id: str, base: str) -> dict[str, Any] | None:
165 try:
166 return object_records.get_collection_record(collection, record_id, base_dir=base)
167 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError,
168 object_collections.CollectionNotFoundError):
169 return None
170
171
172def _json(text: Any, default: Any) -> Any:
173 try:
174 return json.loads(text) if _text(text) else default
175 except ValueError:
176 return default
177
178
179def _types(text: Any) -> list[str]:
180 return [t for t in (part.strip() for part in _text(text).split(",")) if t]
181
182
183def is_manager(access: object_access.Access) -> bool:
184 return access.is_admin or MANAGER_ROLE in access.subject.roles
185
186
187STAFF_ROLE = "manager"
188
189
190def is_staff(access: object_access.Access) -> bool:
191 """Admins, the owner role, and role:manager, the platform's staff role
192 (the one app-invoices and app-payments give invoice money, order status
193 and payments to). A plain registered user is a customer: checkout and the
194 subscription biller raise orders and invoices OWNED BY the customer, so
195 "may update this record" alone would let a customer send their own
196 invoice to a partner box in the business's name."""
197 return is_manager(access) or STAFF_ROLE in access.subject.roles
198
199
200def require_manager(identity: Mapping[str, Any] | None, base: str) -> object_access.Access:
201 access = object_access.Access(identity, base_dir=base)
202 if not is_manager(access):
203 raise Refusal(403, "not_allowed",
204 "Only an admin or the owner manages trading partners and keys.")
205 return access
206
207
208# --- identity and keys -------------------------------------------------------------
209
210def identity(base: str) -> dict[str, Any] | None:
211 return _get("exchange_identity", IDENTITY_ID, base)
212
213
214def require_identity(base: str) -> dict[str, Any]:
215 row = identity(base)
216 if not row or not _text(row.get("domain")):
217 raise Refusal(409, "not_configured",
218 "This box has no exchange identity yet: an admin sets its domain "
219 "and company name (action_exchange_admin, op=setup).")
220 return row
221
222
223def keys(base: str) -> list[dict[str, Any]]:
224 rows = _rows("exchange_keys", base)
225 return sorted(rows, key=lambda r: _text(r.get("created_at")))
226
227
228def active_key(base: str) -> dict[str, Any]:
229 active = [r for r in keys(base) if _text(r.get("status")) == "active"]
230 if not active:
231 raise Refusal(409, "no_key", "This box has no active exchange key; run setup.")
232 row = active[-1]
233 if not ex.has_private_key(base, _text(row.get("key_id"))):
234 raise Refusal(409, "private_key_missing",
235 f"The private key for {row.get('key_id')} is not on this box (a restore "
236 f"does not bring it back: backups never hold it). Put the key file back "
237 f"under the data directory's exchange/private/, or rotate the key and "
238 f"have partners reconnect.")
239 return row
240
241
242def _sign(base: str, message: bytes) -> dict[str, str]:
243 return ex.sign(base, _text(active_key(base).get("key_id")), message)
244
245
246def _vouches(base: str) -> list[dict[str, Any]]:
247 """Every vouch our keys carry, so a partner can follow a chain of
248 rotations from a key it pinned to the one signing now."""
249 out = []
250 for row in keys(base):
251 signature = _json(row.get("vouch_signature"), None)
252 if signature:
253 out.append({"key_id": row["key_id"], "public_key": row["public_key"],
254 "vouched_by": row.get("vouched_by"), "signature": signature})
255 return out
256
257
258def _new_key_row(base: str, *, vouched_by: str = "") -> dict[str, Any]:
259 key_id, public = ex.generate_key(base)
260 row = {"id": key_id[8:], "key_id": key_id, "public_key": public, "status": "active",
261 "created_at": ex.utc_stamp(), "retired_at": "", "vouched_by": "",
262 "vouch_signature": ""}
263 if vouched_by:
264 row["vouched_by"] = vouched_by
265 row["vouch_signature"] = json.dumps(
266 ex.sign(base, vouched_by, ex.vouch_message(key_id, public)))
267 object_records.create_collection_record("exchange_keys", row, base_dir=base, actor=ACTOR,
268 preserve_read_only=True)
269 return row
270
271
272def setup(base: str, *, domain: str, company_name: str,
273 document_types: list[str] | None = None) -> dict[str, Any]:
274 """Name this box (its domain and company) and make its first key."""
275 ex._ed25519() # refuse before writing anything when the extra is missing
276 domain = _text(domain).lower()
277 if not ex.valid_domain(domain):
278 raise Refusal(400, "bad_domain", "The domain must be a DNS name like supplier.example.")
279 if not _text(company_name):
280 raise Refusal(400, "bad_name", "The company name is required.")
281 types = document_types or list(ex.DOCUMENT_TYPES)
282 unknown = [t for t in types if t not in ex.DOCUMENT_TYPES]
283 if unknown:
284 raise Refusal(400, "bad_types", f"Unknown document types: {', '.join(unknown)}")
285 current = identity(base)
286 fields = {"domain": domain, "company_name": _text(company_name),
287 "document_types": ",".join(types), "updated_at": ex.utc_stamp()}
288 if current:
289 if _text(current.get("domain")) and _text(current["domain"]) != domain:
290 raise Refusal(409, "domain_fixed",
291 "This box's exchange domain is already set; partners pinned it. "
292 "A new domain is a new identity, not an edit.")
293 fields["profile_version"] = str(int(_text(current.get("profile_version")) or "1") + 1)
294 object_records.update_collection_record("exchange_identity", IDENTITY_ID, fields,
295 base_dir=base, actor=ACTOR)
296 else:
297 object_records.create_collection_record(
298 "exchange_identity", {"id": IDENTITY_ID, "profile_version": "1", **fields},
299 base_dir=base, actor=ACTOR)
300 if not [r for r in keys(base) if _text(r.get("status")) == "active"]:
301 _new_key_row(base)
302 return profile(base)
303
304
305def rotate_key(base: str) -> dict[str, Any]:
306 """A new active key, vouched for by the old one; the old key is listed as
307 retired (so what it signed still verifies) and its private half removed."""
308 require_identity(base)
309 old = active_key(base)
310 new = _new_key_row(base, vouched_by=_text(old["key_id"]))
311 object_records.update_collection_record(
312 "exchange_keys", old["id"], {"status": "retired", "retired_at": ex.utc_stamp()},
313 base_dir=base, actor=ACTOR)
314 ex.destroy_private_key(base, _text(old["key_id"]))
315 row = identity(base) or {}
316 object_records.update_collection_record(
317 "exchange_identity", IDENTITY_ID,
318 {"profile_version": str(int(_text(row.get("profile_version")) or "1") + 1),
319 "updated_at": ex.utc_stamp()}, base_dir=base, actor=ACTOR)
320 return {"ok": True, "retired": old["key_id"], "active": new["key_id"]}
321
322
323def profile(base: str) -> dict[str, Any]:
324 """The public profile, signed by the active key."""
325 row = require_identity(base)
326 domain = _text(row["domain"])
327 body = {
328 "dbbasic_profile": ex.PROFILE_VERSION,
329 "profile_version": int(_text(row.get("profile_version")) or "1"),
330 "domain": domain,
331 "company_name": _text(row.get("company_name")),
332 "exchange_endpoint": ex.endpoint_for(domain),
333 "dron_document": ex.DRON_DOCUMENT_VERSION,
334 "document_types": _types(row.get("document_types")),
335 "keys": [{"key_id": k["key_id"], "alg": ex.ALG, "public_key": k["public_key"],
336 "status": k["status"], "created_at": k.get("created_at") or "",
337 "retired_at": k.get("retired_at") or ""}
338 for k in keys(base)],
339 "key_vouches": _vouches(base),
340 }
341 body["signature"] = _sign(base, ex.profile_message(body))
342 return body
343
344
345def check_profile(fetched: Any, domain: str) -> dict[str, Any]:
346 """A partner's profile as fetched from its own domain: it names that
347 domain, its endpoint is on it, and it is signed by an active key it
348 lists. Returns it, or raises Refusal."""
349 if not isinstance(fetched, Mapping) or fetched.get("dbbasic_profile") != ex.PROFILE_VERSION:
350 raise Refusal(502, "bad_profile", f"{domain} did not answer with a dbbasic profile.")
351 if fetched.get("domain") != domain:
352 raise Refusal(502, "bad_profile", f"The profile at {domain} names another domain.")
353 if not ex.endpoint_on_domain(fetched.get("exchange_endpoint"), domain):
354 raise Refusal(502, "bad_profile",
355 f"The profile at {domain} sends documents off its own domain.")
356 listed = {k.get("key_id"): k for k in fetched.get("keys") or [] if isinstance(k, Mapping)}
357 signature = fetched.get("signature") or {}
358 signer = listed.get(signature.get("key_id") if isinstance(signature, Mapping) else None)
359 if not signer or signer.get("status") != "active" or not ex.verify(
360 signer.get("public_key"), ex.profile_message(fetched), signature):
361 raise Refusal(502, "bad_profile", f"The profile at {domain} is not signed by its own key.")
362 return dict(fetched)
363
364
365def _profile_keys(fetched: Mapping[str, Any]) -> list[dict[str, str]]:
366 return [{"key_id": k["key_id"], "public_key": k["public_key"]}
367 for k in fetched.get("keys") or []
368 if isinstance(k, Mapping) and k.get("key_id") == ex.key_id_for(
369 ex.unb64u(k.get("public_key") or ""))]
370
371
372def fetch_profile(domain: str) -> dict[str, Any]:
373 try:
374 status, payload = ex.request_json("GET", ex.profile_url(domain))
375 except ex.TransportError as exc:
376 raise Refusal(502, "unreachable", f"{domain} could not be reached: {exc}") from exc
377 if status != 200:
378 raise Refusal(502, "bad_profile", f"{domain} answered {status} for its profile.")
379 return check_profile(payload, domain)
380
381
382def record_key_backup(base: str, where: str) -> dict[str, Any]:
383 """The operator says where the active private key is backed up. The box
384 cannot see a backup (the key is deliberately in none of its own), so
385 this is a person's statement, recorded with when they made it, and
386 what the readiness check reports; it is asked again after a rotation,
387 because the new key is a new file."""
388 where = _text(where)[:300]
389 if not where:
390 raise Refusal(400, "no_location",
391 "Say where the key is kept (\"1Password, vault Ops\", \"sealed USB in the safe\").")
392 key = active_key(base)
393 object_records.update_collection_record(
394 "exchange_keys", key["id"], {"backup_note": where, "backed_up_at": ex.utc_stamp()},
395 base_dir=base, actor=ACTOR)
396 return {"ok": True, "key_id": key["key_id"], "backup_note": where}
397
398
399def _check(checks: list[dict[str, Any]], check_id: str, severity: str, finding: str,
400 fix: str = "") -> None:
401 checks.append({"id": check_id, "ok": severity == "ok", "severity": severity,
402 "finding": finding, "fix": fix})
403
404
405def readiness(base: str) -> dict[str, Any]:
406 """Everything a box needs to trade, checked and said in plain words, each
407 with the fix. The two-company simulation needed someone who knew the
408 internals: totals stamped by hand on a stock box, the manager role to
409 issue invoices, the private key backed up by hand, the daemon running
410 for anything to be delivered. Read-only: it changes nothing."""
411 import object_daemon_status
412 import object_identity
413
414 checks: list[dict[str, Any]] = []
415 if ex.available():
416 _check(checks, "crypto", "ok", "The signing library (the exchange extra) is installed.")
417 else:
418 _check(checks, "crypto", "error", "The signing library is not installed, so nothing can be "
419 "signed, sent or received.", ex.EXTRA_HINT)
420
421 me = identity(base)
422 domain = _text((me or {}).get("domain"))
423 if domain:
424 _check(checks, "domain", "ok", f"This box trades as {domain} "
425 f"({_text(me.get('company_name'))}). Partners reach it at "
426 f"{ex.endpoint_for(domain)}; that address must serve this box over HTTPS.")
427 else:
428 _check(checks, "domain", "error", "This box has no trading name yet.",
429 "As an admin or owner: action_exchange_admin {\"op\": \"setup\", \"domain\": "
430 "\"yourcompany.example\", \"company_name\": \"Your Company Ltd\"}. The domain is "
431 "permanent: it is who you are to every partner.")
432
433 active = [k for k in keys(base) if _text(k.get("status")) == "active"]
434 if domain and not active:
435 _check(checks, "key", "error", "There is no signing key.", "Run setup again to make one.")
436 elif active:
437 key = active[-1]
438 path = ex.private_dir(base) / f"{_text(key['key_id'])[8:]}.key"
439 if not ex.has_private_key(base, _text(key["key_id"])):
440 _check(checks, "key", "error",
441 f"The private key {key['key_id']} is missing from {path}, so nothing can be "
442 f"signed (a restore does not bring it back: no backup holds it).",
443 "Put the key file back from where you keep it, or rotate the key "
444 "(op=rotate_key) and ask partners to reconnect.")
445 elif _text(key.get("backup_note")):
446 _check(checks, "key", "ok", f"The signing key is at {path}; you said it is backed up "
447 f"in: {key['backup_note']} ({key.get('backed_up_at')}).")
448 else:
449 _check(checks, "key", "warning",
450 f"The signing key is at {path} and nobody has said it is backed up. No backup "
451 f"this box makes contains it: lose the disk and you lose the identity every "
452 f"partner trusts.",
453 f"Copy {path} somewhere safe with your other secrets, then record where: "
454 f"action_exchange_admin {{\"op\": \"record_key_backup\", \"where\": \"...\"}}.")
455
456 status = object_daemon_status.reactions_status(base_dir=base)
457 queued = sum(1 for r in _rows("exchange_outbox", base) if _text(r.get("status")) == "queued")
458 if status["daemon"]["running"]:
459 _check(checks, "daemon", "ok", "The daemon is running: queued documents are delivered "
460 "every three minutes.")
461 else:
462 _check(checks, "daemon", "error",
463 "The daemon is not running, so nothing you send is delivered"
464 + (f" ({queued} document(s) waiting)" if queued else "") + ".",
465 "Run `python object_daemon.py` as a service beside the server (with the scheduler "
466 "extra installed: pip install 'dbbasic-object-server[scheduler]'). To deliver "
467 "once by hand, an admin can POST /objects/system_exchange_deliver.")
468 if not status["schedules"]["croniter_available"]:
469 _check(checks, "scheduler", "error", "The scheduler extra (croniter) is missing, so the "
470 "delivery pass never comes due even with the daemon running.",
471 "pip install 'dbbasic-object-server[scheduler]' in the server's environment.")
472
473 handlers = status["handlers"]
474 if handlers["event_handlers_enabled"] or handlers["change_dispatch_enabled"]:
475 _check(checks, "totals", "ok", "The totals reactions run: an order's or invoice's total "
476 "follows its lines.")
477 else:
478 _check(checks, "totals", "warning",
479 "The totals reactions are off (the default), so editing a line does not update its "
480 "order's or invoice's total. The exchange copes: a received order is totalled as it "
481 "arrives, a record never totalled is totalled when you send it, and a record whose "
482 "total disagrees with its lines is refused with both numbers -- but you would then "
483 "have to correct it by hand.",
484 "Set DBBASIC_ENABLE_CHANGE_DISPATCH=true and run the daemon (or "
485 "DBBASIC_ENABLE_EVENT_HANDLERS=true for edits made through the API), so totals "
486 "follow line edits.")
487
488 try:
489 users = object_identity.list_users(base_dir=base)
490 except Exception: # a status read never fails
491 users = []
492
493 def holders(role: str) -> list[str]:
494 return sorted(_text(u.get("user_id")) for u in users
495 if role in (u.get("roles") or []) and _text(u.get("status") or "active") == "active")
496
497 owners, managers = holders(MANAGER_ROLE), holders(STAFF_ROLE)
498 who = (f"Owner role (manages partners and keys, sends, decides): {', '.join(owners) or 'nobody'}. "
499 f"Manager role (sends documents, confirms remittances against the bank, decides on "
500 f"confirmations): {', '.join(managers) or 'nobody'}. Admins can do all of it.")
501 if managers:
502 _check(checks, "roles", "ok", who)
503 else:
504 _check(checks, "roles", "warning", who + " Without a manager, recording a partner's "
505 "payment (and issuing invoices at all) is left to admins.",
506 "Give the people who run the books role:manager (an admin: PUT "
507 "/identity/users/<user>/roles), and the business's owner role:owner.")
508
509 partners_ = partners(base)
510 by_status: dict[str, int] = {}
511 for row in partners_:
512 by_status[_text(row.get("status"))] = by_status.get(_text(row.get("status")), 0) + 1
513 if by_status.get("pending"):
514 _check(checks, "partners", "warning",
515 f"{by_status['pending']} compan(y/ies) asked to connect and wait for you.",
516 "Look at trading_partners rows with status pending and accept the ones you know "
517 "(op=accept); ignore the rest.")
518 else:
519 _check(checks, "partners", "ok" if by_status.get("connected") else "warning",
520 f"Connected partners: {by_status.get('connected', 0)}.",
521 "" if by_status.get("connected") else
522 "Connect to a partner: action_exchange_admin {\"op\": \"connect\", \"domain\": "
523 "\"partner.example\"}; their owner accepts.")
524
525 targets = {"orders": "purchase orders and confirmations (app-orders)",
526 "invoices": "invoicing customers (app-invoices)",
527 "payments": "recording customers' remittances (app-payments)",
528 "supplier_bills": "receiving invoices and credit notes (app-bills)",
529 "supplier_payments": "paying suppliers part or whole (app-bills 0.3.0)",
530 "receipts": "goods receipts (app-receiving)"}
531 missing = [f"{text}" for name, text in targets.items() if not _installed(name, base)]
532 if missing:
533 _check(checks, "packages", "warning", "Not installed, so those documents wait in the "
534 "inbox: " + "; ".join(missing) + ".",
535 "Install the packages for the documents you trade; waiting documents are mapped "
536 "with op=remap.")
537 else:
538 _check(checks, "packages", "ok", "Every package a document can become is installed.")
539
540 errors = [c for c in checks if c["severity"] == "error"]
541 warnings = [c for c in checks if c["severity"] == "warning"]
542 summary = ("Ready to trade." if not errors and not warnings else
543 "Can trade, with things to fix." if not errors else "Not ready to trade.")
544 return {"ok": True, "ready": not errors, "summary": summary,
545 "errors": len(errors), "warnings": len(warnings), "checks": checks}
546
547
548# --- partners ------------------------------------------------------------------------
549
550def partners(base: str) -> list[dict[str, Any]]:
551 return _rows("trading_partners", base)
552
553
554def partner_by_domain(base: str, domain: str) -> dict[str, Any] | None:
555 for row in partners(base):
556 if _text(row.get("domain")) == domain:
557 return row
558 return None
559
560
561def _pinned(partner: Mapping[str, Any]) -> dict[str, str]:
562 return {k["key_id"]: k["public_key"] for k in _json(partner.get("pinned_keys"), [])
563 if isinstance(k, Mapping) and k.get("key_id") and k.get("public_key")}
564
565
566def _absorb_vouches(pinned: dict[str, str], vouches: Any) -> dict[str, str]:
567 """Pinned keys plus every key a pinned key vouched for (followed until
568 nothing changes, so a chain of rotations is followed)."""
569 pinned = dict(pinned)
570 vouches = [v for v in vouches or [] if isinstance(v, Mapping)] if isinstance(vouches, list) else []
571 changed = True
572 while changed:
573 changed = False
574 for vouch in vouches:
575 key_id, public = vouch.get("key_id"), vouch.get("public_key")
576 by = vouch.get("vouched_by")
577 if not key_id or key_id in pinned or by not in pinned:
578 continue
579 try:
580 derived = ex.key_id_for(ex.unb64u(public or ""))
581 except ValueError:
582 continue
583 if derived == key_id and ex.verify(pinned[by], ex.vouch_message(key_id, public),
584 vouch.get("signature")):
585 pinned[key_id] = public
586 changed = True
587 return pinned
588
589
590def _pin(base: str, partner: Mapping[str, Any], pinned: dict[str, str]) -> None:
591 if pinned == _pinned(partner):
592 return
593 object_records.update_collection_record(
594 "trading_partners", partner["id"],
595 {"pinned_keys": json.dumps([{"key_id": k, "public_key": v}
596 for k, v in sorted(pinned.items())])},
597 base_dir=base, actor=ACTOR)
598
599
600def _wire(base: str, envelope: Mapping[str, Any], signature: Mapping[str, Any]) -> dict[str, Any]:
601 """What goes on the wire: the envelope and its signature, verbatim as
602 stored, plus a delivery stamp signed now."""
603 delivery = {"sender": envelope["sender"], "recipient": envelope["recipient"],
604 "envelope_sha256": ex.sha256_hex(ex.canonical(envelope)),
605 "sent_at": ex.utc_stamp()}
606 return {"dron_delivery": ex.DRON_DOCUMENT_VERSION, "envelope": dict(envelope),
607 "signature": dict(signature), "delivery": delivery,
608 "delivery_signature": _sign(base, ex.delivery_message(delivery)),
609 "key_vouches": _vouches(base)}
610
611
612def _signed_envelope(base: str, **kwargs: Any) -> tuple[dict[str, Any], dict[str, str]]:
613 envelope = ex.new_envelope(**kwargs)
614 return envelope, _sign(base, ex.canonical(envelope))
615
616
617def _post(endpoint: str, wire: Mapping[str, Any]) -> tuple[int, Any]:
618 try:
619 return ex.request_json("POST", endpoint, wire)
620 except ex.TransportError as exc:
621 raise Refusal(502, "unreachable", f"The partner could not be reached: {exc}") from exc
622
623
624def connect(base: str, domain: str, *, local_owner: str) -> dict[str, Any]:
625 me = require_identity(base)
626 domain = _text(domain).lower()
627 if not ex.valid_domain(domain):
628 raise Refusal(400, "bad_domain", "The partner's domain must be a DNS name.")
629 if domain == _text(me["domain"]):
630 raise Refusal(400, "self", "A box cannot be its own trading partner.")
631 existing = partner_by_domain(base, domain)
632 if existing and _text(existing.get("status")) == "connected":
633 raise Refusal(409, "already_connected", f"{domain} is already a connected partner.")
634 if existing and _text(existing.get("status")) == "pending":
635 raise Refusal(409, "they_asked_first",
636 f"{domain} has already asked to connect; accept their request instead.")
637 fetched = fetch_profile(domain)
638 fields = {
639 "domain": domain, "company_name": _text(fetched.get("company_name")),
640 "status": "requested", "initiated_by": "us",
641 "exchange_endpoint": fetched["exchange_endpoint"],
642 "pinned_keys": json.dumps(_profile_keys(fetched)),
643 "profile": json.dumps(fetched, sort_keys=True),
644 "receive_types": ",".join(ex.DOCUMENT_TYPES), "send_types": ",".join(ex.DOCUMENT_TYPES),
645 "local_owner_id": local_owner, "requested_at": ex.utc_stamp(), "last_error": "",
646 }
647 if existing:
648 row = object_records.update_collection_record("trading_partners", existing["id"], fields,
649 base_dir=base, actor=ACTOR)
650 else:
651 row = object_records.create_collection_record(
652 "trading_partners", {"id": object_ids.new_uuid4(), **fields},
653 base_dir=base, actor=ACTOR)
654 envelope, signature = _signed_envelope(
655 base, doc_id=f"conn-{object_ids.new_uuid4()}", doc_type="connection_request",
656 sender=_text(me["domain"]), recipient=domain, body={"profile": profile(base)})
657 status, answer = _post(row["exchange_endpoint"], _wire(base, envelope, signature))
658 if status not in (200, 202):
659 reason = answer.get("error") if isinstance(answer, Mapping) else ""
660 object_records.update_collection_record(
661 "trading_partners", row["id"], {"last_error": f"{status} {reason}"[:300]},
662 base_dir=base, actor=ACTOR)
663 raise Refusal(502, "request_refused", f"{domain} refused the request ({status}): {reason}")
664 return {"ok": True, "partner_id": row["id"], "status": "requested",
665 "message": f"Asked {domain} to connect; their operator must accept."}
666
667
668def accept(base: str, partner_id: str, *, local_owner: str) -> dict[str, Any]:
669 me = require_identity(base)
670 row = _get("trading_partners", partner_id, base)
671 if not row:
672 raise Refusal(404, "no_partner", "No such partner.")
673 if _text(row.get("status")) not in ("pending", "connected"):
674 raise Refusal(409, "not_pending",
675 f"{row.get('domain')} has not asked to connect (status {row.get('status')}).")
676 domain = _text(row["domain"])
677 fetched = fetch_profile(domain)
678 claimed = _json(row.get("profile"), {})
679 request_key = _text(row.get("request_key_id"))
680 published = {k["key_id"]: k["public_key"] for k in _profile_keys(fetched)}
681 claimed_keys = {k["key_id"]: k["public_key"] for k in _profile_keys(claimed)}
682 if not request_key or published.get(request_key) != claimed_keys.get(request_key):
683 raise Refusal(409, "key_mismatch",
684 f"The request was signed with a key {domain} does not publish; "
685 f"it did not come from {domain}. Refuse it.")
686 row = object_records.update_collection_record(
687 "trading_partners", partner_id,
688 {"status": "connected", "connected_at": ex.utc_stamp(),
689 "company_name": _text(fetched.get("company_name")),
690 "exchange_endpoint": fetched["exchange_endpoint"],
691 "pinned_keys": json.dumps(_profile_keys(fetched)),
692 "profile": json.dumps(fetched, sort_keys=True),
693 "local_owner_id": _text(row.get("local_owner_id")) or local_owner,
694 "disconnected_at": "", "last_error": ""},
695 base_dir=base, actor=ACTOR)
696 envelope, signature = _signed_envelope(
697 base, doc_id=f"conn-{object_ids.new_uuid4()}", doc_type="connection_accept",
698 sender=_text(me["domain"]), recipient=domain, body={"profile": profile(base)})
699 status, answer = _post(row["exchange_endpoint"], _wire(base, envelope, signature))
700 if status not in (200, 202):
701 reason = answer.get("error") if isinstance(answer, Mapping) else ""
702 raise Refusal(502, "accept_not_delivered",
703 f"Connected here, but {domain} did not take the acceptance ({status}: "
704 f"{reason}). Accept again to resend it.")
705 return {"ok": True, "partner_id": partner_id, "status": "connected"}
706
707
708def disconnect(base: str, partner_id: str, *, reason: str = "") -> dict[str, Any]:
709 """End a relationship: refuse everything from this partner from now on,
710 and tell them, with a signed connection_end, so their box shows us
711 disconnected too (the simulation found the other side still showing
712 "connected" and still sending). Ours is decided first and does not
713 depend on theirs: if the notice cannot be delivered, we are still
714 disconnected here and the answer says they were not told."""
715 me = require_identity(base)
716 row = _get("trading_partners", partner_id, base)
717 if not row:
718 raise Refusal(404, "no_partner", "No such partner.")
719 was = _text(row.get("status"))
720 reason = _text(reason)[:300]
721 object_records.update_collection_record(
722 "trading_partners", partner_id,
723 {"status": "disconnected", "disconnected_at": ex.utc_stamp(), "disconnected_by": "us",
724 "disconnect_reason": reason}, base_dir=base, actor=ACTOR)
725 answer = {"ok": True, "partner_id": partner_id, "status": "disconnected", "notified": False,
726 "message": "Documents from this partner are refused from now on."}
727 if was not in ("connected", "requested") or not _text(row.get("exchange_endpoint")):
728 return answer
729 envelope, signature = _signed_envelope(
730 base, doc_id=f"end-{object_ids.new_uuid4()}", doc_type="connection_end",
731 sender=_text(me["domain"]), recipient=_text(row["domain"]),
732 body={"reason": reason} if reason else {})
733 try:
734 status, reply = _post(_text(row["exchange_endpoint"]), _wire(base, envelope, signature))
735 except Refusal as refusal:
736 status, reply = 0, {"error": refusal.message}
737 if 200 <= status < 300:
738 answer.update(notified=True, message=answer["message"] + f" {row['domain']} was told.")
739 else:
740 why = reply.get("error") if isinstance(reply, Mapping) else ""
741 answer["message"] += (f" {row['domain']} could not be told ({status or 'no answer'}: "
742 f"{why}); they will be refused all the same.")
743 return answer
744
745
746def set_types(base: str, partner_id: str, *, receive_types: Any = None,
747 send_types: Any = None) -> dict[str, Any]:
748 row = _get("trading_partners", partner_id, base)
749 if not row:
750 raise Refusal(404, "no_partner", "No such partner.")
751 changes = {}
752 for key, value in (("receive_types", receive_types), ("send_types", send_types)):
753 if value is None:
754 continue
755 values = value if isinstance(value, list) else _types(value)
756 unknown = [t for t in values if t not in ex.DOCUMENT_TYPES]
757 if unknown:
758 raise Refusal(400, "bad_types", f"Unknown document types: {', '.join(unknown)}")
759 changes[key] = ",".join(values)
760 if changes:
761 object_records.update_collection_record("trading_partners", partner_id, changes,
762 base_dir=base, actor=ACTOR)
763 return {"ok": True, "partner_id": partner_id, **changes}
764
765
766# --- inbound -----------------------------------------------------------------------------
767
768def _refuse_not_partner() -> Refusal:
769 return Refusal(403, "not_a_partner", "The sender is not a connected trading partner of this box.")
770
771
772def _verify_wire(pinned: dict[str, str], wire: Mapping[str, Any],
773 envelope: Mapping[str, Any]) -> None:
774 """Both signatures by pinned keys, and the delivery names this envelope."""
775 signature = wire.get("signature")
776 delivery = wire.get("delivery")
777 delivery_signature = wire.get("delivery_signature")
778 if not isinstance(signature, Mapping) or not isinstance(delivery_signature, Mapping) \
779 or not isinstance(delivery, Mapping):
780 raise Refusal(400, "malformed", "The delivery is missing its signatures.")
781 for sig in (signature, delivery_signature):
782 if sig.get("key_id") not in pinned:
783 raise Refusal(403, "key_not_pinned",
784 "The document is signed with a key not pinned for this partner.")
785 try:
786 envelope_bytes = ex.canonical(envelope)
787 delivery_bytes = ex.delivery_message(delivery)
788 except ex.CanonicalError as exc:
789 raise Refusal(400, "malformed", f"Not canonicalisable: {exc}") from exc
790 if not ex.verify(pinned[signature["key_id"]], envelope_bytes, signature):
791 raise Refusal(401, "bad_signature", "The document's signature does not verify.")
792 if not ex.verify(pinned[delivery_signature["key_id"]], delivery_bytes, delivery_signature):
793 raise Refusal(401, "bad_signature", "The delivery's signature does not verify.")
794 if (delivery.get("envelope_sha256") != ex.sha256_hex(envelope_bytes)
795 or delivery.get("sender") != envelope.get("sender")
796 or delivery.get("recipient") != envelope.get("recipient")):
797 raise Refusal(400, "delivery_mismatch", "The delivery does not name this document.")
798 if not ex.within_window(delivery.get("sent_at")):
799 raise Refusal(400, "stale_delivery",
800 "The delivery is stamped outside this box's clock window "
801 "(a replay, or a clock that is wrong).")
802
803
804def inbound(base: str, raw: Any) -> dict[str, Any]:
805 """Handle one POST to the exchange endpoint. Returns the answer, with
806 its HTTP status in `status`."""
807 try:
808 return _inbound(base, raw)
809 except Refusal as refusal:
810 return refusal.answer()
811 except ex.ExchangeUnavailable as exc:
812 return {"status": 409, "ok": False, "code": "exchange_unavailable", "error": str(exc)}
813
814
815def _inbound(base: str, raw: Any) -> dict[str, Any]:
816 if not isinstance(raw, str) or not raw:
817 raise Refusal(400, "malformed", "Empty body.")
818 if len(raw.encode("utf-8")) > ex.MAX_DOCUMENT_BYTES:
819 raise Refusal(413, "too_large", "The document is larger than this box accepts.")
820 me = require_identity(base)
821 ex._ed25519()
822 try:
823 wire = json.loads(raw)
824 except ValueError as exc:
825 raise Refusal(400, "malformed", "The body is not JSON.") from exc
826 if not isinstance(wire, Mapping) or wire.get("dron_delivery") != ex.DRON_DOCUMENT_VERSION:
827 raise Refusal(400, "malformed", "Not a dron delivery.")
828 envelope = wire.get("envelope")
829 if not isinstance(envelope, Mapping):
830 raise Refusal(400, "malformed", "The delivery carries no envelope.")
831 sender = _text(envelope.get("sender"))
832 doc_type = envelope.get("type")
833
834 if doc_type == "connection_request":
835 return _inbound_connection_request(base, me, wire, envelope)
836
837 partner = partner_by_domain(base, sender) if ex.valid_domain(sender) else None
838 if doc_type in ("connection_accept", "connection_end"):
839 if not partner or _text(partner.get("status")) not in ("requested", "connected"):
840 # One answer for unknown and disconnected, as for every other
841 # document: a notice from a partner we already let go changes
842 # nothing, and saying so would tell a prober who they were.
843 raise _refuse_not_partner()
844 elif not partner or _text(partner.get("status")) != "connected":
845 raise _refuse_not_partner()
846
847 pinned = _pinned(partner)
848 widened = _absorb_vouches(pinned, wire.get("key_vouches"))
849 _verify_wire(widened, wire, envelope)
850 # From here the sender is proven: a refusal is answered with a SIGNED
851 # refusal receipt naming the document, which the sender's box verifies
852 # and records against what it sent (phase 0 answered a bare error the
853 # sender could not tell from a proxy's, and showed the document open).
854 try:
855 return _inbound_verified(base, me, partner, raw, wire, envelope, widened)
856 except Refusal as refusal:
857 if doc_type in ex.DOCUMENT_TYPES and ex.valid_id(envelope.get("id")):
858 refusal.extra["refusal"] = _signed_refusal(base, me, envelope, refusal)
859 raise
860
861
862def _signed_refusal(base: str, me: Mapping[str, Any], envelope: Mapping[str, Any],
863 refusal: Refusal) -> dict[str, Any]:
864 receipt = {"dron_receipt": ex.DRON_DOCUMENT_VERSION, "document_id": _text(envelope.get("id")),
865 "document_type": _text(envelope.get("type")), "sender": _text(envelope.get("sender")),
866 "recipient": _text(me["domain"]),
867 "envelope_sha256": ex.sha256_hex(ex.canonical(envelope)),
868 "received_at": ex.utc_stamp(), "status": "refused", "code": refusal.code,
869 "reason": refusal.message[:500]}
870 return {"receipt": receipt, "signature": _sign(base, ex.receipt_message(receipt)),
871 "key_vouches": _vouches(base)}
872
873
874def _inbound_verified(base: str, me: Mapping[str, Any], partner: Mapping[str, Any], raw: str,
875 wire: Mapping[str, Any], envelope: Mapping[str, Any],
876 widened: dict[str, str]) -> dict[str, Any]:
877 sender = _text(envelope.get("sender"))
878 doc_type = envelope.get("type")
879 if envelope.get("recipient") != _text(me["domain"]):
880 raise Refusal(400, "wrong_recipient", "The document is addressed to another box.")
881 try:
882 ex.validate_envelope(envelope)
883 except ex.EnvelopeError as exc:
884 raise Refusal(422, "invalid_document", "The document is not well formed.",
885 problems=exc.problems) from exc
886 _pin(base, partner, widened)
887
888 if doc_type == "connection_accept":
889 if _text(partner.get("status")) == "requested":
890 object_records.update_collection_record(
891 "trading_partners", partner["id"],
892 {"status": "connected", "connected_at": ex.utc_stamp(), "last_error": "",
893 "disconnected_by": "", "disconnect_reason": ""},
894 base_dir=base, actor=ACTOR)
895 return {"status": 200, "ok": True, "connected": True}
896 if doc_type == "connection_end":
897 return _inbound_connection_end(base, partner, envelope)
898 if doc_type == "document_refusal":
899 return _inbound_document_refusal(base, partner, wire, envelope)
900
901 if doc_type not in _types(partner.get("receive_types")):
902 raise Refusal(403, "type_not_allowed",
903 f"This box does not accept {doc_type} documents from {sender}.")
904 if doc_type not in _types(me.get("document_types")):
905 raise Refusal(403, "type_not_allowed", f"This box does not accept {doc_type} documents.")
906 return _store(base, me, partner, raw, wire, envelope)
907
908
909def _inbound_connection_end(base: str, partner: Mapping[str, Any],
910 envelope: Mapping[str, Any]) -> dict[str, Any]:
911 """The partner ended the relationship. Recorded as disconnected BY THEM,
912 with their reason, so this box refuses their documents, stops sending
913 them ours (delivery and send both re-read the row) and shows why. A
914 notice older than the connection it would end is refused: a captured
915 notice from an earlier relationship cannot end a new one."""
916 made = ex.parse_stamp(envelope.get("created_at"))
917 since = ex.parse_stamp(partner.get("connected_at")) or ex.parse_stamp(partner.get("requested_at"))
918 if made and since and made < since:
919 raise Refusal(409, "stale_notice", "This notice predates the connection it would end.")
920 reason = _text((envelope.get("body") or {}).get("reason"))[:300]
921 object_records.update_collection_record(
922 "trading_partners", partner["id"],
923 {"status": "disconnected", "disconnected_at": ex.utc_stamp(), "disconnected_by": "them",
924 "disconnect_reason": reason,
925 "last_error": f"{partner['domain']} ended the connection"
926 + (f": {reason}" if reason else ".")}, base_dir=base, actor=ACTOR)
927 return {"status": 200, "ok": True, "disconnected": True}
928
929
930def _related_record_note(base: str, collection: str, record_id: str, note: str) -> None:
931 """Show what the partner said on the record a document was made from (an
932 invoice reads "refused by partner: ..."), where its schema has the place
933 for it. Best effort: the outbox row is the record of the refusal."""
934 try:
935 schema = object_schemas.get_schema(collection, base_dir=base)
936 except (object_schemas.SchemaNotFoundError, object_collections.CollectionNotFoundError):
937 return
938 if not any(f.get("name") == "exchange_status" for f in schema.get("fields") or []):
939 return
940 try:
941 object_records.update_collection_record(collection, record_id,
942 {"exchange_status": note[:500]}, base_dir=base,
943 actor=ACTOR, preserve_read_only=True)
944 except (object_records.RecordNotFoundError, object_records.RecordLockedError,
945 object_records.InvalidRecordPayloadError, object_records.CheckRefusedError):
946 pass
947
948
949def _record_refusal(base: str, row: Mapping[str, Any], partner_domain: str, code: str,
950 reason: str, evidence: Mapping[str, Any]) -> dict[str, Any]:
951 note = f"Refused by {partner_domain}: {reason}" + (f" ({code})" if code else "")
952 updated = object_records.update_collection_record(
953 "exchange_outbox", row["id"],
954 {"status": "refused", "refused_at": ex.utc_stamp(), "refusal_reason": note[:500],
955 "refusal": json.dumps(evidence, sort_keys=True, ensure_ascii=False),
956 "last_error": note[:500], "updated_at": ex.utc_stamp()}, base_dir=base, actor=ACTOR)
957 _related_record_note(base, _text(row.get("source_collection")),
958 _text(row.get("source_record_id")), note)
959 return updated
960
961
962def _inbound_document_refusal(base: str, partner: Mapping[str, Any], wire: Mapping[str, Any],
963 envelope: Mapping[str, Any]) -> dict[str, Any]:
964 """The partner refused a document we delivered (a person there decided:
965 "this invoice is not ours", "wrong prices"). Recorded against our outbox
966 row -- status refused, the reason, and the signed notice as evidence --
967 and on the record it was made from, and shown as attention here."""
968 body = envelope.get("body") or {}
969 row = _outbox_source(base, _text(body.get("document_id")), _text(partner["domain"]))
970 if not row or _text(row.get("envelope_sha256")) != _text(body.get("envelope_sha256")):
971 raise Refusal(404, "unknown_document", "This box sent no such document to you.")
972 if _text(row.get("status")) == "refused":
973 return {"status": 200, "ok": True, "duplicate": True}
974 _record_refusal(base, row, _text(partner["domain"]), _text(body.get("code")),
975 _text(body.get("reason")),
976 {"envelope": dict(envelope), "signature": dict(wire["signature"])})
977 return {"status": 200, "ok": True, "recorded": True}
978
979
980def _inbound_connection_request(base: str, me: Mapping[str, Any], wire: Mapping[str, Any],
981 envelope: Mapping[str, Any]) -> dict[str, Any]:
982 """A stranger asking to connect. Verified against the keys in the profile
983 it carries (which proves it holds them, not that it is that domain: the
984 operator's accept checks the domain). Nothing is fetched now."""
985 sender = _text(envelope.get("sender"))
986 try:
987 ex.validate_envelope(envelope)
988 except ex.EnvelopeError as exc:
989 raise Refusal(422, "invalid_document", "Not a well-formed request.",
990 problems=exc.problems) from exc
991 if envelope.get("recipient") != _text(me["domain"]):
992 raise Refusal(400, "wrong_recipient", "The request is addressed to another box.")
993 claimed = (envelope.get("body") or {}).get("profile")
994 if not isinstance(claimed, Mapping) or claimed.get("domain") != sender \
995 or not ex.endpoint_on_domain(claimed.get("exchange_endpoint"), sender):
996 raise Refusal(400, "bad_profile", "The request carries no profile for its sender.")
997 pinned = {k["key_id"]: k["public_key"] for k in _profile_keys(claimed)}
998 _verify_wire(pinned, wire, envelope)
999 existing = partner_by_domain(base, sender)
1000 if existing and _text(existing.get("status")) == "connected":
1001 return {"status": 200, "ok": True, "message": "Already connected."}
1002 if not existing and sum(1 for r in partners(base)
1003 if _text(r.get("status")) == "pending") >= MAX_PENDING_REQUESTS:
1004 raise Refusal(429, "too_many_requests", "This box has too many unanswered requests.")
1005 fields = {
1006 "domain": sender, "company_name": _text(claimed.get("company_name"))[:200],
1007 "status": "pending", "initiated_by": "them",
1008 "exchange_endpoint": claimed["exchange_endpoint"],
1009 "pinned_keys": json.dumps([]),
1010 "request_key_id": _text(wire["signature"].get("key_id")),
1011 "profile": json.dumps(claimed, sort_keys=True),
1012 "receive_types": ",".join(ex.DOCUMENT_TYPES), "send_types": ",".join(ex.DOCUMENT_TYPES),
1013 "requested_at": ex.utc_stamp(), "last_error": "",
1014 }
1015 if existing:
1016 object_records.update_collection_record("trading_partners", existing["id"], fields,
1017 base_dir=base, actor=ACTOR)
1018 else:
1019 object_records.create_collection_record(
1020 "trading_partners", {"id": object_ids.new_uuid4(), **fields},
1021 base_dir=base, actor=ACTOR)
1022 return {"status": 202, "ok": True,
1023 "message": "Request received; it waits for this box's operator to accept."}
1024
1025
1026def _inbox_row(base: str, sender: str, document_id: str) -> dict[str, Any] | None:
1027 for row in _rows("exchange_inbox", base):
1028 if _text(row.get("sender")) == sender and _text(row.get("document_id")) == document_id:
1029 return row
1030 return None
1031
1032
1033def _duplicate(row: Mapping[str, Any], envelope_sha: str) -> dict[str, Any]:
1034 if _text(row.get("envelope_sha256")) != envelope_sha:
1035 raise Refusal(409, "id_reused",
1036 "A different document was already received under this id.")
1037 stored = _json(row.get("receipt"), {})
1038 return {"status": 200, "ok": True, "duplicate": True, **stored}
1039
1040
1041def _store(base: str, me: Mapping[str, Any], partner: Mapping[str, Any], raw: str,
1042 wire: Mapping[str, Any], envelope: Mapping[str, Any]) -> dict[str, Any]:
1043 sender = _text(envelope["sender"])
1044 document_id = _text(envelope["id"])
1045 envelope_sha = ex.sha256_hex(ex.canonical(envelope))
1046 existing = _inbox_row(base, sender, document_id)
1047 if existing:
1048 return _duplicate(existing, envelope_sha)
1049 received_at = ex.utc_stamp()
1050 receipt = {"dron_receipt": ex.DRON_DOCUMENT_VERSION, "document_id": document_id,
1051 "document_type": envelope["type"], "sender": sender,
1052 "recipient": _text(me["domain"]), "envelope_sha256": envelope_sha,
1053 "received_at": received_at, "status": "stored"}
1054 signed = {"receipt": receipt, "signature": _sign(base, ex.receipt_message(receipt)),
1055 "key_vouches": _vouches(base)}
1056 row = {
1057 "id": object_ids.new_uuid4(), "sender": sender, "recipient": _text(me["domain"]),
1058 "partner_id": partner["id"], "document_id": document_id,
1059 "document_type": envelope["type"], "envelope_sha256": envelope_sha,
1060 "key_id": _text(wire["signature"].get("key_id")), "raw_body": raw,
1061 "received_at": received_at, "receipt": json.dumps(signed, sort_keys=True),
1062 "integrity": "verified", "mapping_status": "pending", "mapping_reason": "",
1063 "mapped_collection": "", "mapped_record_id": "",
1064 "owner_id": _text(partner.get("local_owner_id")),
1065 }
1066 try:
1067 stored = object_records.create_collection_record("exchange_inbox", row, base_dir=base,
1068 actor=ACTOR)
1069 except object_records.UniqueConstraintError:
1070 # Another delivery of the same document won the race inside the lock.
1071 existing = _inbox_row(base, sender, document_id)
1072 if existing:
1073 return _duplicate(existing, envelope_sha)
1074 raise
1075 map_document(base, stored, envelope, partner)
1076 return {"status": 200, "ok": True, "duplicate": False, **signed}
1077
1078
1079# --- mapping (reactions after the write) ------------------------------------------------
1080
1081def _partner_access(base: str, partner: Mapping[str, Any]) -> object_access.Access:
1082 return object_access.Access(
1083 {"user_id": f"exchange-partner:{partner['domain']}", "roles": [PARTNER_ROLE]},
1084 base_dir=base)
1085
1086
1087def _decimal_text(value: Any) -> str:
1088 try:
1089 number = Decimal(_text(value) or "0")
1090 except InvalidOperation:
1091 number = Decimal(0)
1092 text = format(number.normalize(), "f")
1093 return "0" if text in ("-0", "") else text
1094
1095
1096def _set_mapping(base: str, inbox_id: str, status: str, reason: str = "",
1097 collection: str = "", record_id: str = "") -> dict[str, Any]:
1098 return object_records.update_collection_record(
1099 "exchange_inbox", inbox_id,
1100 {"mapping_status": status, "mapping_reason": reason[:2000],
1101 "mapped_collection": collection, "mapped_record_id": record_id,
1102 "updated_at": ex.utc_stamp()}, base_dir=base, actor=ACTOR)
1103
1104
1105class _Unmappable(Exception):
1106 pass
1107
1108
1109def map_document(base: str, inbox_row: Mapping[str, Any], envelope: Mapping[str, Any] | None = None,
1110 partner: Mapping[str, Any] | None = None) -> dict[str, Any]:
1111 """Turn a stored document into business records. Never raises: what
1112 could not be done is written on the inbox row for a person."""
1113 if envelope is None:
1114 envelope = _json(inbox_row.get("raw_body"), {}).get("envelope") or {}
1115 partner = partner or _get("trading_partners", _text(inbox_row.get("partner_id")), base) or {}
1116 mapper = _MAPPERS.get(_text(inbox_row.get("document_type")))
1117 try:
1118 if mapper is None:
1119 raise _Unmappable(f"Nothing maps {inbox_row.get('document_type')} documents yet.")
1120 status, reason, collection, record_id = mapper(base, inbox_row, envelope, partner)
1121 except _Unmappable as exc:
1122 return _set_mapping(base, inbox_row["id"], NEEDS_ATTENTION, str(exc))
1123 except (object_records.InvalidRecordPayloadError, object_records.CheckRefusedError,
1124 object_records.UniqueConstraintError, object_records.RecordLockedError,
1125 ValueError) as exc:
1126 return _set_mapping(base, inbox_row["id"], NEEDS_ATTENTION,
1127 f"Could not be turned into records: {str(exc)[:500]}")
1128 return _set_mapping(base, inbox_row["id"], status, reason, collection, record_id)
1129
1130
1131def _require_installed(base: str, *collections: str) -> None:
1132 missing = [c for c in collections if not _installed(c, base)]
1133 if missing:
1134 raise _Unmappable(f"Not installed on this box: {', '.join(missing)}.")
1135
1136
1137def _create_as_partner(base: str, access: object_access.Access, collection: str,
1138 record: dict[str, Any], *, server_stamps: bool = False) -> dict[str, Any]:
1139 if not access.can("create", collection, record):
1140 raise _Unmappable(f"The partner principal may not create {collection} "
1141 f"(app-exchange's rules decide what a document may become).")
1142 return object_records.create_collection_record(collection, record, base_dir=base,
1143 actor=f"exchange:{access.user_id}",
1144 preserve_read_only=server_stamps)
1145
1146
1147def _ref(envelope: Mapping[str, Any], doc_type: str) -> str:
1148 for ref in envelope.get("refs") or []:
1149 if isinstance(ref, Mapping) and ref.get("type") == doc_type:
1150 return _text(ref.get("id"))
1151 return ""
1152
1153
1154def _outbox_source(base: str, document_id: str, partner_domain: str) -> dict[str, Any] | None:
1155 """The outbox row of a document WE sent this partner, by document id."""
1156 for row in _rows("exchange_outbox", base):
1157 if _text(row.get("document_id")) == document_id \
1158 and _text(row.get("partner_domain")) == partner_domain:
1159 return row
1160 return None
1161
1162
1163def _lines_total(lines: list[Mapping[str, Any]]) -> int:
1164 return sum(int(line.get("line_extension_minor") or 0) for line in lines)
1165
1166
1167def _document_lines(body: Mapping[str, Any], owner: str) -> list[dict[str, Any]]:
1168 out = []
1169 for line in body.get("lines") or []:
1170 row = {"partner_line_id": _text(line.get("line_id"))[:128],
1171 "description": _text(line.get("description"))[:300],
1172 "quantity": _decimal_text(line.get("quantity")),
1173 "unit_code": _text(line.get("unit_code")) or ex.DEFAULT_UNIT_CODE,
1174 "unit_price_cents": str(int(line.get("unit_price_minor") or 0)),
1175 "tax_rate_bps": str(int(line.get("tax_rate_bps") or 0)),
1176 "owner_id": owner}
1177 amounts = object_lines.line_amounts(row)
1178 row["line_total_cents"] = str(amounts["line_total_cents"])
1179 row["line_tax_cents"] = str(amounts["line_tax_cents"])
1180 out.append(row)
1181 return out
1182
1183
1184def _map_purchase_order(base, inbox_row, envelope, partner):
1185 _require_installed(base, "orders", "order_lines")
1186 body = envelope["body"]
1187 access = _partner_access(base, partner)
1188 owner = _text(partner.get("local_owner_id"))
1189 order = {"id": object_ids.new_uuid4(), "doc_type": "sale",
1190 "number": _text(body["number"])[:100],
1191 "customer_name": (_text(partner.get("company_name")) or _text(partner["domain"]))[:200],
1192 "currency": body["currency"], "status": "draft",
1193 "order_date": body["issue_date"],
1194 "notes": (f"Received from {partner['domain']} as purchase order {body['number']} "
1195 f"(exchange document {envelope['id']})."),
1196 "owner_id": owner,
1197 # A partner's purchase order is a back-office draft nobody has
1198 # confirmed: it must hold nothing on the shelf. Only checkout's
1199 # online orders reserve (object_reservations); stamped false
1200 # here explicitly rather than left to a default, so the stock
1201 # hold check and the storefront's "only N left" never count it.
1202 "reserves_stock": "false"}
1203 lines = _document_lines(body, owner)
1204 if not access.can("create", "order_lines", {**lines[0], "order_id": order["id"]}):
1205 raise _Unmappable("The partner principal may not create order_lines.")
1206 _create_as_partner(base, access, "orders", order, server_stamps=True)
1207 for line in lines:
1208 _create_as_partner(base, access, "order_lines", {"id": object_ids.new_uuid4(),
1209 "order_id": order["id"], **line})
1210 # This writer stamps the totals itself (logic-decisions #9): the
1211 # change dispatcher that would run order_totals is off on a stock box.
1212 totals = object_lines.totals(lines)
1213 object_records.update_collection_record(
1214 "orders", order["id"],
1215 {"subtotal_cents": str(totals["subtotal_cents"]), "tax_cents": str(totals["tax_cents"]),
1216 "total_cents": str(totals["total_cents"])}, base_dir=base, actor=ACTOR)
1217 stated = body["totals"]
1218 if totals["total_cents"] != stated["payable_minor"]:
1219 return (NEEDS_ATTENTION,
1220 f"Draft order created, but its lines come to {totals['total_cents']} and the "
1221 f"purchase order says {stated['payable_minor']} ({body['currency']} minor units).",
1222 "orders", order["id"])
1223 return MAPPED, f"Draft sale order for {partner['domain']}'s {body['number']}.", "orders", order["id"]
1224
1225
1226def _map_order_confirmation(base, inbox_row, envelope, partner):
1227 body = envelope["body"]
1228 po_doc = _ref(envelope, "purchase_order")
1229 sent = _outbox_source(base, po_doc, _text(partner["domain"])) if po_doc else None
1230 if not sent:
1231 raise _Unmappable("This confirmation refers to no purchase order this box sent.")
1232 order = _get("orders", _text(sent.get("source_record_id")), base)
1233 if not order:
1234 raise _Unmappable("The purchase order it confirms is no longer on this box.")
1235 differences = []
1236 if body.get("response") != "accepted":
1237 differences.append(f"the seller's answer is {body.get('response')}")
1238 line_diffs = confirmation_differences(base, order, body)
1239 differences += [text for kind, text in line_diffs if kind["kind"] != "none"]
1240 caveat = "".join(f" Note: {text}." for kind, text in line_diffs if kind["kind"] == "none")
1241 if int(_text(order.get("total_cents")) or 0) != body["totals"]["payable_minor"]:
1242 differences.append(f"the confirmed total is {body['totals']['payable_minor']}, "
1243 f"our order says {order.get('total_cents')}")
1244 if body.get("currency") != _text(order.get("currency")):
1245 differences.append(f"currency {body.get('currency')} vs ours {order.get('currency')}")
1246 if differences:
1247 return (NEEDS_ATTENTION, "Confirmed with differences: " + "; ".join(differences) + "."
1248 + caveat, "orders", order["id"])
1249 return (MAPPED, f"{partner['domain']} confirmed purchase order {order.get('number')} "
1250 f"as ordered (their number {body['number']}).{caveat}", "orders", order["id"])
1251
1252
1253def _our_line_as_sent(base: str, line: Mapping[str, Any]) -> dict[str, Any]:
1254 """One of our order lines in the terms a document states it."""
1255 try:
1256 unit = _line_unit(base, line)
1257 except Refusal:
1258 unit = _text(line.get("unit_code")) or ex.DEFAULT_UNIT_CODE
1259 return {"quantity": _decimal_text(line.get("quantity") or "1"), "unit_code": unit,
1260 "unit_price_minor": _int_text(line.get("unit_price_cents"))
1261 + _int_text(line.get("modifier_cents"))}
1262
1263
1264def confirmation_differences(base: str, order: Mapping[str, Any],
1265 body: Mapping[str, Any]) -> list[tuple[dict[str, Any], str]]:
1266 """Every line-level difference between our purchase order as it stands
1267 and a seller's confirmation of it, as (what to do, words): changed lines
1268 (quantity, unit, price), lines rejected or missing, and lines the
1269 seller added. Our own computation, not the seller's line_status: the
1270 seller saying "accepted" proves nothing about the numbers. A
1271 confirmation from an engine that does not refer to our lines
1272 (no ref_line_id anywhere) is compared on its total only, and says so."""
1273 ours = {_text(l["id"]): l for l in _record_lines(base, "order_lines", "order_id",
1274 _text(order["id"]))}
1275 theirs = [l for l in body.get("lines") or [] if isinstance(l, Mapping)]
1276 if not any(_text(l.get("ref_line_id")) for l in theirs):
1277 return [({"kind": "none"}, "the confirmation does not refer to our lines, so it was "
1278 "compared on its total only")]
1279 by_ref = {_text(l.get("ref_line_id")): l for l in theirs if _text(l.get("ref_line_id"))}
1280 out = []
1281 for line_id, line in sorted(ours.items(), key=lambda kv: _text(kv[1].get("description"))):
1282 name = _text(line.get("description"))
1283 answer = by_ref.get(line_id)
1284 if _same_quantity(line.get("quantity"), "0") and (
1285 answer is None or _text(answer.get("line_status")) == "rejected"):
1286 continue # a line we already took off (an earlier accepted amendment)
1287 if answer is None or _text(answer.get("line_status")) == "rejected":
1288 out.append(({"kind": "rejected", "line_id": line_id},
1289 f"line {name!r} rejected"))
1290 continue
1291 changes = _line_changes(_our_line_as_sent(base, line), answer)
1292 if changes:
1293 out.append(({"kind": "changed", "line_id": line_id, "answer": dict(answer)},
1294 f"line {name!r}: " + ", ".join(changes)))
1295 for line in theirs:
1296 ref = _text(line.get("ref_line_id"))
1297 if not ref and _text(line.get("line_status")) != "rejected":
1298 out.append(({"kind": "added", "answer": dict(line)},
1299 f"line {_text(line.get('description'))!r} added: "
1300 f"{_decimal_text(line.get('quantity'))} "
1301 f"{_text(line.get('unit_code')) or ex.DEFAULT_UNIT_CODE} at "
1302 f"{line.get('unit_price_minor')}"))
1303 elif ref and ref not in ours:
1304 out.append(({"kind": "unknown", "answer": dict(line)},
1305 f"line {_text(line.get('description'))!r} answers a line we never ordered"))
1306 return out
1307
1308
1309def _map_bill(base, inbox_row, envelope, partner, doc_type):
1310 _require_installed(base, "supplier_bills", "supplier_bill_lines")
1311 if doc_type == "credit_note":
1312 # A credit note is applied with the row it arrives with (below);
1313 # without the collection that holds that row it would read as one
1314 # more bill to pay, so it waits until app-bills has it.
1315 _require_installed(base, "supplier_bill_credits")
1316 body = envelope["body"]
1317 access = _partner_access(base, partner)
1318 owner = _text(partner.get("local_owner_id"))
1319 po_id = ""
1320 po_doc = _ref(envelope, "purchase_order")
1321 if po_doc:
1322 sent = _outbox_source(base, po_doc, _text(partner["domain"]))
1323 po_id = _text(sent.get("source_record_id")) if sent else ""
1324 credited = ""
1325 problems = []
1326 invoice_doc = _ref(envelope, "invoice") if doc_type == "credit_note" else ""
1327 if invoice_doc:
1328 earlier = _inbox_row(base, _text(partner["domain"]), invoice_doc)
1329 if earlier and _text(earlier.get("mapped_collection")) == "supplier_bills":
1330 credited = _text(earlier.get("mapped_record_id"))
1331 credited_bill = _get("supplier_bills", credited, base) if credited else None
1332 if not credited_bill or _text(credited_bill.get("doc_type")) != "invoice":
1333 credited = ""
1334 problems.append("it credits an invoice this box holds no bill for, so the credit "
1335 "stands on account until a person applies it")
1336 elif _text(credited_bill.get("currency")) != body["currency"]:
1337 credited = ""
1338 problems.append(f"it is in {body['currency']} and the bill it credits is in "
1339 f"{credited_bill.get('currency')}, so the credit stands on account")
1340 totals = body["totals"]
1341 bill = {"id": object_ids.new_uuid4(), "doc_type": doc_type,
1342 "number": _text(body["number"])[:100],
1343 "supplier_name": (_text(partner.get("company_name")) or partner["domain"])[:200],
1344 "supplier_domain": partner["domain"], "currency": body["currency"],
1345 "issue_date": body["issue_date"], "due_date": _text(body.get("due_date")),
1346 "subtotal_cents": str(totals["line_extension_minor"]),
1347 "charge_cents": str(int(totals.get("charge_minor") or 0)),
1348 "tax_cents": str(totals["tax_minor"]), "total_cents": str(totals["payable_minor"]),
1349 "status": "received", "source": "exchange",
1350 "exchange_document_id": envelope["id"], "purchase_order_id": po_id,
1351 "credited_bill_id": credited, "owner_id": owner,
1352 "notes": f"Received from {partner['domain']} (exchange document {envelope['id']})."}
1353 _create_as_partner(base, access, "supplier_bills", bill)
1354 for line in body["lines"]:
1355 _create_as_partner(base, access, "supplier_bill_lines", {
1356 "id": object_ids.new_uuid4(), "bill_id": bill["id"],
1357 "description": _text(line["description"])[:300],
1358 "quantity": _decimal_text(line["quantity"]),
1359 "unit_code": _text(line.get("unit_code")) or ex.DEFAULT_UNIT_CODE,
1360 "unit_price_cents": str(line["unit_price_minor"]),
1361 "line_total_cents": str(line["line_extension_minor"]),
1362 "tax_rate_bps": str(int(line.get("tax_rate_bps") or 0)),
1363 "source": "exchange", "owner_id": owner})
1364 applied = ""
1365 if doc_type == "credit_note":
1366 # The credit is applied as the document says, in the same act that
1367 # records it: the bill it credits owes that much less, and the
1368 # credit note itself never reads as money we owe (its
1369 # credit_applied_cents equals its total). On account when it names
1370 # no bill we hold.
1371 _create_as_partner(base, access, "supplier_bill_credits", {
1372 "id": object_ids.new_uuid4(), "credit_bill_id": bill["id"], "bill_id": credited,
1373 "amount_cents": str(totals["payable_minor"]),
1374 "on_account": "false" if credited else "true",
1375 "source": "exchange", "owner_id": owner})
1376 if credited:
1377 after = _get("supplier_bills", credited, base) or {}
1378 applied = (f" Applied to bill {after.get('number')}, which now has "
1379 f"{after.get('outstanding_cents')} outstanding.")
1380 else:
1381 applied = " The credit stands on account until it is applied to a bill."
1382 if _lines_total(body["lines"]) != totals["line_extension_minor"]:
1383 problems.append(f"its lines add up to {_lines_total(body['lines'])}, its total says "
1384 f"{totals['line_extension_minor']}")
1385 expected = totals["line_extension_minor"] + int(totals.get("charge_minor") or 0) \
1386 + totals["tax_minor"]
1387 if expected != totals["payable_minor"]:
1388 problems.append(f"lines, charges and tax come to {expected}, payable says "
1389 f"{totals['payable_minor']}")
1390 if po_doc and not po_id:
1391 problems.append("it names a purchase order this box never sent")
1392 word = "credit note" if doc_type == "credit_note" else "bill"
1393 if problems:
1394 return (NEEDS_ATTENTION, f"Supplier {word} recorded as received, but " + "; ".join(problems)
1395 + ". It was not changed: it is the supplier's document." + applied,
1396 "supplier_bills", bill["id"])
1397 if doc_type == "credit_note":
1398 return (MAPPED, f"Supplier credit note {body['number']} from {partner['domain']}."
1399 + applied, "supplier_bills", bill["id"])
1400 return (MAPPED, f"Supplier {word} {body['number']} from {partner['domain']}, waiting for a "
1401 f"person to approve it. Nothing pays it automatically.", "supplier_bills",
1402 bill["id"])
1403
1404
1405def _map_invoice(base, inbox_row, envelope, partner):
1406 return _map_bill(base, inbox_row, envelope, partner, "invoice")
1407
1408
1409def _map_credit_note(base, inbox_row, envelope, partner):
1410 return _map_bill(base, inbox_row, envelope, partner, "credit_note")
1411
1412
1413def _settled_invoices(base: str, envelope: Mapping[str, Any],
1414 partner: Mapping[str, Any]) -> list[tuple[dict[str, Any], int]]:
1415 out = []
1416 for item in envelope["body"]["settles"]:
1417 sent = _outbox_source(base, _text(item["document_id"]), _text(partner["domain"]))
1418 if not sent or _text(sent.get("source_collection")) != "invoices":
1419 raise _Unmappable(f"The remittance settles {item['document_id']}, which is not an "
1420 f"invoice this box sent {partner['domain']}.")
1421 invoice = _get("invoices", _text(sent.get("source_record_id")), base)
1422 if not invoice:
1423 raise _Unmappable(f"The invoice sent as {item['document_id']} is no longer here.")
1424 if _text(invoice.get("currency")) != envelope["body"]["currency"]:
1425 raise _Unmappable(f"The remittance is in {envelope['body']['currency']}; invoice "
1426 f"{invoice.get('number')} is in {invoice.get('currency')}.")
1427 out.append((invoice, int(item["amount_minor"])))
1428 return out
1429
1430
1431def _map_remittance(base, inbox_row, envelope, partner):
1432 """A remittance is the payer SAYING it paid; the bank statement is the
1433 proof (docs/box-to-box-exchange.md "Payments"). So it records nothing as
1434 received: it waits, as attention, for a person to confirm it against the
1435 bank, and confirm_remittance then records the payment under the
1436 payments collection's own rules (its overpayment check included)."""
1437 _require_installed(base, "invoices", "payments")
1438 settled = _settled_invoices(base, envelope, partner)
1439 body = envelope["body"]
1440 numbers = ", ".join(
1441 f"{inv.get('number')} ({amount}"
1442 + (f", a part payment: {inv.get('balance_due_cents')} outstanding, "
1443 f"{_int_text(inv.get('balance_due_cents')) - amount} left after it"
1444 if amount < _int_text(inv.get("balance_due_cents")) else "") + ")"
1445 for inv, amount in settled)
1446 return (AWAITING_CONFIRMATION,
1447 f"{partner['domain']} says it paid {body['paid_minor']} {body['currency']} on "
1448 f"{body['paid_on']} (reference {body.get('payment_reference') or 'none'}) for "
1449 f"{numbers}. Pending: confirm it against the bank statement to record the payment.",
1450 "invoices", settled[0][0]["id"])
1451
1452
1453def _map_receipt(base, inbox_row, envelope, partner):
1454 _require_installed(base, "orders")
1455 order = None
1456 for doc_type in ("order_confirmation", "purchase_order"):
1457 ref = _ref(envelope, doc_type)
1458 if not ref:
1459 continue
1460 if doc_type == "order_confirmation":
1461 sent = _outbox_source(base, ref, _text(partner["domain"]))
1462 order = _get("orders", _text(sent.get("source_record_id")), base) if sent else None
1463 else:
1464 earlier = _inbox_row(base, _text(partner["domain"]), ref)
1465 if earlier and _text(earlier.get("mapped_collection")) == "orders":
1466 order = _get("orders", _text(earlier.get("mapped_record_id")), base)
1467 if order:
1468 break
1469 if not order:
1470 raise _Unmappable("This goods receipt refers to no order of ours.")
1471 lines = envelope["body"]["lines"]
1472 summary = "; ".join(f"{l['description']}: {l['quantity_received']} received"
1473 + (f", {l['quantity_rejected']} rejected" if l.get("quantity_rejected")
1474 not in (None, "", "0") else "") for l in lines)
1475 return (MAPPED, f"{partner['domain']} received the goods on "
1476 f"{envelope['body']['received_on']}: {summary}.", "orders", order["id"])
1477
1478
1479_MAPPERS = {
1480 "purchase_order": _map_purchase_order,
1481 "order_confirmation": _map_order_confirmation,
1482 "invoice": _map_invoice,
1483 "credit_note": _map_credit_note,
1484 "remittance": _map_remittance,
1485 "receipt": _map_receipt,
1486}
1487
1488
1489def remap(base: str, inbox_id: str) -> dict[str, Any]:
1490 """Try the mapping again (a package installed since, a rule changed).
1491 Only a row that needs attention and created nothing is retried, so a
1492 second attempt can never make a second order or bill."""
1493 row = _get("exchange_inbox", inbox_id, base)
1494 if not row:
1495 raise Refusal(404, "no_document", "No such inbox document.")
1496 if _text(row.get("mapping_status")) != NEEDS_ATTENTION or _text(row.get("mapped_record_id")):
1497 raise Refusal(409, "not_retryable",
1498 "Only a document that needs attention and made no record is retried.")
1499 return {"ok": True, **map_document(base, row)}
1500
1501
1502def resolve_confirmation(base: str, inbox_id: str, identity_: Mapping[str, Any] | None, *,
1503 decision: str, note: str = "") -> dict[str, Any]:
1504 """A person decides on a confirmation that differs from our order.
1505
1506 accept: our purchase order becomes what the seller confirmed, through
1507 recorded changes -- each line write is made under this person's name
1508 (actor exchange-accept:<user>, in the change log beside every other
1509 write), changed lines take the confirmed quantity, unit and price,
1510 rejected lines go to quantity 0 (kept, so what we asked for stays
1511 visible), added lines are added, and the order's totals are stamped from
1512 its lines. The inbox row records who decided what, and when, and the
1513 differences that were applied. Nothing is applied that a person did not
1514 see: the differences are recomputed from the stored document against
1515 the order as it stands now.
1516
1517 reject: nothing in our order changes; the decision is recorded the same
1518 way. (Telling the seller is a new document, not built yet.)
1519
1520 Staff only, and only someone who may update the order."""
1521 if decision not in ("accept", "reject"):
1522 raise Refusal(400, "bad_decision", "decision is accept or reject.")
1523 row = _get("exchange_inbox", inbox_id, base)
1524 if not row or _text(row.get("document_type")) != "order_confirmation":
1525 raise Refusal(404, "no_document", "No such order confirmation.")
1526 if _text(row.get("mapping_status")) != NEEDS_ATTENTION or _text(row.get("resolution")) \
1527 or _text(row.get("mapped_collection")) != "orders":
1528 raise Refusal(409, "not_pending",
1529 "Only a confirmation that differs from our order, and that nobody has "
1530 "decided on yet, is accepted or rejected.")
1531 access = object_access.Access(identity_, base_dir=base)
1532 if not is_staff(access):
1533 raise Refusal(403, "not_allowed", "Deciding on a supplier's confirmation is for staff.")
1534 order = access.get("orders", _text(row.get("mapped_record_id")), action="update")
1535 if order is None:
1536 raise Refusal(404, "no_order", "No such order.")
1537 envelope = _json(row.get("raw_body"), {}).get("envelope") or {}
1538 body = envelope.get("body") or {}
1539 if body.get("currency") != _text(order.get("currency")):
1540 raise Refusal(409, "currency_mismatch",
1541 "The confirmation is in another currency; it cannot be applied to this "
1542 "order. Reject it and ask the seller.")
1543 differences = confirmation_differences(base, order, body)
1544 actor = f"exchange-accept:{access.user_id}"
1545 applied = []
1546 if decision == "accept":
1547 if any(d["kind"] in ("none", "unknown") for d, _ in differences):
1548 raise Refusal(409, "not_line_by_line",
1549 "This confirmation cannot be applied line by line ("
1550 + "; ".join(t for d, t in differences if d["kind"] in ("none", "unknown"))
1551 + "). Change the order by hand, or reject it.")
1552 for change, text in differences:
1553 line = ({} if change["kind"] == "added" else
1554 _get("order_lines", change["line_id"], base) or {})
1555 if change["kind"] != "added" and not access.can("update", "order_lines", line):
1556 raise Refusal(403, "not_allowed", f"You may not change {text}.")
1557 for change, text in differences:
1558 answer = change.get("answer") or {}
1559 if change["kind"] == "changed":
1560 line = _get("order_lines", change["line_id"], base) or {}
1561 object_records.update_collection_record(
1562 "order_lines", change["line_id"],
1563 {"quantity": _decimal_text(answer.get("quantity")),
1564 "unit_code": _text(answer.get("unit_code")) or ex.DEFAULT_UNIT_CODE,
1565 "unit_price_cents": str(int(answer.get("unit_price_minor") or 0)
1566 - _int_text(line.get("modifier_cents")))},
1567 base_dir=base, actor=actor)
1568 elif change["kind"] == "rejected":
1569 object_records.update_collection_record(
1570 "order_lines", change["line_id"], {"quantity": "0"}, base_dir=base, actor=actor)
1571 elif change["kind"] == "added":
1572 object_records.create_collection_record("order_lines", {
1573 "id": object_ids.new_uuid4(), "order_id": order["id"],
1574 "partner_line_id": _text(answer.get("line_id"))[:128],
1575 "description": _text(answer.get("description"))[:300] or "item",
1576 "quantity": _decimal_text(answer.get("quantity")),
1577 "unit_code": _text(answer.get("unit_code")) or ex.DEFAULT_UNIT_CODE,
1578 "unit_price_cents": str(int(answer.get("unit_price_minor") or 0)),
1579 "tax_rate_bps": str(int(answer.get("tax_rate_bps") or 0)),
1580 "owner_id": _text(order.get("owner_id"))}, base_dir=base, actor=actor)
1581 applied.append(text)
1582 lines = _record_lines(base, "order_lines", "order_id", _text(order["id"]))
1583 totals = line_derived_totals(order, lines)
1584 object_records.update_collection_record(
1585 "orders", order["id"], {k: str(v) for k, v in totals.items()}, base_dir=base,
1586 actor=actor)
1587 reason = (f"Amended confirmation {body.get('number')} accepted by {access.user_id}; our "
1588 f"order now says what the seller confirmed ("
1589 + ("; ".join(applied) or "no line changes") + f"), total {totals['total_cents']}.")
1590 if totals["total_cents"] != int((body.get("totals") or {}).get("payable_minor") or 0):
1591 reason += (f" Its total still differs from the confirmed "
1592 f"{(body.get('totals') or {}).get('payable_minor')}: check document-level "
1593 f"tax or charges.")
1594 else:
1595 reason = (f"Confirmation {body.get('number')} rejected by {access.user_id}"
1596 + (f": {_text(note)[:300]}" if _text(note) else "")
1597 + ". Our order was not changed. Differences: "
1598 + ("; ".join(t for _, t in differences) or "none") + ".")
1599 object_records.update_collection_record(
1600 "exchange_inbox", inbox_id,
1601 {"mapping_status": MAPPED, "mapping_reason": reason[:2000],
1602 "resolution": "accepted" if decision == "accept" else "rejected",
1603 "resolved_by": access.user_id, "resolved_at": ex.utc_stamp(),
1604 "updated_at": ex.utc_stamp()}, base_dir=base, actor=ACTOR)
1605 return {"ok": True, "inbox_id": inbox_id, "resolution": decision + "ed",
1606 "order_id": order["id"], "applied": applied, "message": reason}
1607
1608
1609def confirm_remittance(base: str, inbox_id: str, identity_: Mapping[str, Any] | None, *,
1610 received_on: str = "") -> dict[str, Any]:
1611 row = _get("exchange_inbox", inbox_id, base)
1612 if not row or _text(row.get("document_type")) != "remittance":
1613 raise Refusal(404, "no_document", "No such remittance.")
1614 if _text(row.get("mapping_status")) != AWAITING_CONFIRMATION:
1615 raise Refusal(409, "not_pending", "This remittance is not waiting for confirmation.")
1616 access = object_access.Access(identity_, base_dir=base)
1617 partner = _get("trading_partners", _text(row.get("partner_id")), base) or {}
1618 envelope = _json(row.get("raw_body"), {}).get("envelope") or {}
1619 try:
1620 settled = _settled_invoices(base, envelope, partner)
1621 except _Unmappable as exc:
1622 raise Refusal(409, "unmappable", str(exc)) from exc
1623 for invoice, amount in settled:
1624 if access.get("invoices", invoice["id"], action="update") is None:
1625 raise Refusal(404, "no_invoice", "No such invoice.")
1626 # What the invoice still owes after payments AND credits applied to
1627 # it (balance_due_cents): the payments hook's own ceiling knows
1628 # payments and refunds but not credit notes, so a remittance for the
1629 # full invoice after a credit would pass it and leave the customer
1630 # in credit by the amount we already credited.
1631 if amount > _int_text(invoice.get("balance_due_cents")):
1632 raise Refusal(409, "more_than_owed",
1633 f"The remittance pays {amount} on invoice {invoice.get('number')}, which "
1634 f"has {invoice.get('balance_due_cents')} outstanding after payments and "
1635 f"credits. Ask the customer; nothing was recorded.")
1636 reference = f"exchange {envelope['id']}"[:120]
1637 existing = {(_text(p.get("invoice_id")), _text(p.get("reference")))
1638 for p in _rows("payments", base)}
1639 payments = []
1640 for invoice, amount in settled:
1641 if (invoice["id"], reference) in existing:
1642 continue
1643 payments.append({
1644 "id": object_ids.new_uuid4(), "invoice_id": invoice["id"],
1645 "amount_cents": str(amount), "method": "transfer",
1646 "received_on": _text(received_on) or envelope["body"]["paid_on"],
1647 "reference": reference, "status": "received",
1648 "notes": f"Remittance from {row.get('sender')}, confirmed by {access.user_id}.",
1649 "owner_id": _text(invoice.get("owner_id"))})
1650 # Recording a payment is staff's (app-payments 0.8.0: registered users
1651 # only read their own; role:manager creates). The customer who owns an
1652 # invoice may still update it, so the invoice check above would let them
1653 # record "money received" on their own bill -- the hole that release
1654 # closed. Asked of the policy for every payment, before anything is
1655 # written: a refusal writes nothing.
1656 for payment in payments:
1657 if not access.can("create", "payments", payment):
1658 raise Refusal(403, "not_allowed",
1659 "Recording a payment is for staff; this account may not.")
1660 created = []
1661 for payment in payments:
1662 try:
1663 object_records.create_collection_record("payments", payment, base_dir=base,
1664 actor=f"exchange:{access.user_id}")
1665 except (object_records.CheckRefusedError, object_records.InvalidRecordPayloadError) as exc:
1666 raise Refusal(409, "payment_refused", f"The payment was refused: {exc}") from exc
1667 created.append(payment["id"])
1668 _set_mapping(base, inbox_id, MAPPED,
1669 f"Confirmed against the bank by {access.user_id}; payments recorded.",
1670 "invoices", settled[0][0]["id"])
1671 return {"ok": True, "payments": created}
1672
1673
1674# --- outbound ----------------------------------------------------------------------------
1675
1676def _record_lines(base: str, collection: str, fk: str, parent_id: str) -> list[dict[str, Any]]:
1677 return [row for row in _rows(collection, base) if _text(row.get(fk)) == parent_id]
1678
1679
1680def _line_unit(base: str, line: Mapping[str, Any]) -> str:
1681 """The Rec 20 code a line is sent with: the line's own unit_code; else
1682 its product's unit, as a code; else C62 ("one", a count), which is what
1683 a free-text line with no unit has always meant. A product whose unit
1684 names nothing this box can code is refused rather than sent as C62:
1685 that silent "one" is how ten kilograms became ten of something."""
1686 own = _text(line.get("unit_code"))
1687 if own:
1688 code = ex.unit_code_for(own) or (own if ex.valid_unit_code(own) else None)
1689 if not code:
1690 raise Refusal(409, "unknown_unit",
1691 f"The line {_text(line.get('description'))!r} has unit {own!r}, which "
1692 f"is not a UN/ECE Rec 20 code this box knows (KGM, C62, LTR, XBG ...).")
1693 return code
1694 product_id = _text(line.get("product_id"))
1695 product = _get("products", product_id, base) if product_id else None
1696 unit = _text((product or {}).get("unit"))
1697 if not unit:
1698 return ex.DEFAULT_UNIT_CODE
1699 code = ex.unit_code_for(unit)
1700 if not code:
1701 raise Refusal(409, "unknown_unit",
1702 f"The line {_text(line.get('description'))!r} is for a product sold by "
1703 f"{unit!r}, which has no UN/ECE Rec 20 code here. Set the line's unit_code "
1704 f"(KGM kilogram, C62 one, LTR litre, XBG bag, ...) or the product's unit "
1705 f"to a known one, then send again.")
1706 return code
1707
1708
1709def _int_text(value: Any) -> int:
1710 try:
1711 return int(_text(value) or 0)
1712 except ValueError:
1713 return 0
1714
1715
1716def line_derived_totals(record: Mapping[str, Any],
1717 lines: list[Mapping[str, Any]]) -> dict[str, int]:
1718 """What the totals handlers (order_totals, invoice_totals) would stamp on
1719 this record, by their rule exactly: subtotal is the lines; tax is the
1720 lines' tax when any line states a rate, else the document's own stored
1721 tax (tax computed once over the whole sale lives only there, and a fold
1722 that cannot see it must not replace it -- AGENTS.md); total is the two."""
1723 folded = object_lines.totals(lines)
1724 states_rate = any(_int_text(line.get("tax_rate_bps")) for line in lines)
1725 tax = folded["tax_cents"] if states_rate else _int_text(record.get("tax_cents"))
1726 return {"subtotal_cents": folded["subtotal_cents"], "tax_cents": tax,
1727 "total_cents": folded["subtotal_cents"] + tax}
1728
1729
1730def _settle_totals(base: str, collection: str, record: dict[str, Any],
1731 lines: list[Mapping[str, Any]]) -> dict[str, Any]:
1732 """Make the totals a document is sent with correct, whether or not the
1733 totals handlers run on this box (they are reactions, off on a stock
1734 install). The two-company simulation stamped every total by hand; a box
1735 that did not would have sent an invoice for 0.
1736
1737 - The stored total agrees with the lines (the handlers ran, or somebody
1738 kept it right): sent as it is.
1739 - Nothing was ever stamped (total blank or 0): this writer stamps what
1740 the handler would have (logic-decisions #9: a storage-level writer
1741 performs its own reactions), then sends it. Nothing is lost: there
1742 was no number to replace.
1743 - A total that DISAGREES with the lines is refused, naming both: one of
1744 them is wrong and only a person knows which (a line edited after the
1745 total, or a total typed by hand). Sending either would put a number
1746 in the other company's books that ours cannot reproduce.
1747 """
1748 if not lines:
1749 raise Refusal(409, "no_lines", "This record has no lines, so there is nothing to send.")
1750 derived = line_derived_totals(record, lines)
1751 stored = _int_text(record.get("total_cents"))
1752 if stored == derived["total_cents"]:
1753 return record
1754 if stored == 0 and _int_text(record.get("subtotal_cents")) == 0:
1755 changes = {k: str(v) for k, v in derived.items()}
1756 try:
1757 updated = object_records.update_collection_record(collection, record["id"], changes,
1758 base_dir=base, actor=ACTOR)
1759 except (object_records.RecordLockedError, object_records.InvalidRecordPayloadError,
1760 object_records.CheckRefusedError) as exc:
1761 raise Refusal(409, "totals_not_stamped",
1762 f"The totals could not be stamped before sending: {exc}") from exc
1763 return {**record, **updated}
1764 raise Refusal(409, "totals_disagree",
1765 f"This record's total is {stored} but its lines come to "
1766 f"{derived['total_cents']} ({_text(record.get('currency'))} minor units: lines "
1767 f"{derived['subtotal_cents']}, tax {derived['tax_cents']}). The totals handlers "
1768 f"are probably off (DBBASIC_ENABLE_EVENT_HANDLERS / "
1769 f"DBBASIC_ENABLE_CHANGE_DISPATCH), so the total was not recomputed when a line "
1770 f"changed. Correct the lines or set the total to {derived['total_cents']}, then "
1771 f"send again.", lines_total=derived["total_cents"], stored_total=stored)
1772
1773
1774def _priced_body(base: str, record: Mapping[str, Any], lines: list[Mapping[str, Any]], *,
1775 date_field: str) -> dict[str, Any]:
1776 out_lines = []
1777 for line in lines:
1778 amounts = object_lines.line_amounts(line)
1779 # The net unit price (UBL PriceAmount): a per-unit modifier ("oat
1780 # milk +60c") is part of what one unit costs, so quantity x price
1781 # reproduces the line at the other end.
1782 unit_price = _int_text(line.get("unit_price_cents")) + _int_text(line.get("modifier_cents"))
1783 entry = {"line_id": _text(line["id"]), "description": _text(line.get("description")),
1784 "quantity": _decimal_text(line.get("quantity") or "1"),
1785 "unit_code": _line_unit(base, line),
1786 "unit_price_minor": unit_price,
1787 "line_extension_minor": amounts["line_total_cents"]}
1788 if _text(line.get("tax_rate_bps")):
1789 entry["tax_rate_bps"] = _int_text(line["tax_rate_bps"])
1790 out_lines.append(entry)
1791 derived = line_derived_totals(record, lines)
1792 totals = {"line_extension_minor": derived["subtotal_cents"], "tax_minor": derived["tax_cents"],
1793 "payable_minor": derived["total_cents"]}
1794 body = {"number": _text(record.get("number")),
1795 "issue_date": _text(record.get(date_field)) or _now().date().isoformat(),
1796 "currency": _text(record.get("currency")) or "USD",
1797 "lines": out_lines, "totals": totals}
1798 if _text(record.get("due_date")):
1799 body["due_date"] = _text(record["due_date"])
1800 return body
1801
1802
1803def _same_quantity(a: Any, b: Any) -> bool:
1804 try:
1805 return Decimal(_text(a) or "0") == Decimal(_text(b) or "0")
1806 except InvalidOperation:
1807 return _text(a) == _text(b)
1808
1809
1810def _line_changes(asked: Mapping[str, Any], answered: Mapping[str, Any]) -> list[str]:
1811 """What differs between a line as asked for and as answered, in words:
1812 quantity, unit and unit price, the three things a confirmation commits."""
1813 out = []
1814 unit_a = _text(asked.get("unit_code")) or ex.DEFAULT_UNIT_CODE
1815 unit_b = _text(answered.get("unit_code")) or ex.DEFAULT_UNIT_CODE
1816 if not _same_quantity(asked.get("quantity"), answered.get("quantity")):
1817 out.append(f"quantity {_decimal_text(asked.get('quantity'))} -> "
1818 f"{_decimal_text(answered.get('quantity'))}")
1819 if unit_a != unit_b:
1820 out.append(f"unit {unit_a} -> {unit_b}")
1821 if int(asked.get("unit_price_minor") or 0) != int(answered.get("unit_price_minor") or 0):
1822 out.append(f"unit price {asked.get('unit_price_minor')} -> {answered.get('unit_price_minor')}")
1823 return out
1824
1825
1826def _confirm_lines(body: dict[str, Any], origin: Mapping[str, Any] | None,
1827 lines: list[Mapping[str, Any]], requested: str) -> None:
1828 """Answer the buyer's purchase order line by line (UBL OrderResponse
1829 LineResponse): each of our lines names the buyer's line it answers
1830 (ref_line_id) and says accepted, changed or added; each of the buyer's
1831 lines we no longer have is answered rejected with quantity 0. The
1832 document's response is derived from the lines -- a seller who says
1833 "accepted" while a line changed is refused, because the buyer's box
1834 compares the lines and would flag it anyway, and the two answers would
1835 disagree in a signed document."""
1836 asked = {}
1837 if origin:
1838 envelope = _json(origin.get("raw_body"), {}).get("envelope") or {}
1839 asked = {_text(l.get("line_id")): l for l in (envelope.get("body") or {}).get("lines") or []
1840 if isinstance(l, Mapping)}
1841 answered = set()
1842 for entry, line in zip(body["lines"], lines):
1843 ref = _text(line.get("partner_line_id"))
1844 if ref and ref in asked:
1845 answered.add(ref)
1846 entry["ref_line_id"] = ref
1847 entry["line_status"] = "changed" if _line_changes(asked[ref], entry) else "accepted"
1848 else:
1849 entry["line_status"] = "added"
1850 for ref, line in asked.items():
1851 if ref in answered or not ex.valid_id(ref):
1852 continue
1853 body["lines"].append({
1854 "line_id": f"rejected-{ref}"[:128], "ref_line_id": ref,
1855 "description": _text(line.get("description")) or "item", "quantity": "0",
1856 "unit_code": _text(line.get("unit_code")) or ex.DEFAULT_UNIT_CODE,
1857 "unit_price_minor": int(line.get("unit_price_minor") or 0),
1858 "line_extension_minor": 0, "line_status": "rejected"})
1859 statuses = {l["line_status"] for l in body["lines"]}
1860 derived = ("rejected" if statuses == {"rejected"} else
1861 "accepted" if statuses == {"accepted"} else "amended")
1862 if requested and requested != derived:
1863 raise Refusal(409, "response_disagrees",
1864 f"The lines say this order is {derived} (line by line: "
1865 + ", ".join(sorted(statuses)) + f"), not {requested}. Send it as {derived}, "
1866 f"or change the lines first.", derived=derived)
1867 body["response"] = derived
1868
1869
1870def _inbox_for_record(base: str, collection: str, record_id: str) -> dict[str, Any] | None:
1871 for row in _rows("exchange_inbox", base):
1872 if _text(row.get("mapped_collection")) == collection \
1873 and _text(row.get("mapped_record_id")) == record_id:
1874 return row
1875 return None
1876
1877
1878def _sent_for_record(base: str, collection: str, record_id: str,
1879 doc_type: str) -> dict[str, Any] | None:
1880 for row in _rows("exchange_outbox", base):
1881 if (_text(row.get("source_collection")) == collection
1882 and _text(row.get("source_record_id")) == record_id
1883 and _text(row.get("document_type")) == doc_type):
1884 return row
1885 return None
1886
1887
1888def _compose(base: str, collection: str, record: Mapping[str, Any],
1889 requested: Mapping[str, Any]) -> tuple[str, str, dict[str, Any], list[dict[str, str]]]:
1890 """(document type, partner domain or "", body, refs) for one record."""
1891 rid = _text(record["id"])
1892 refs: list[dict[str, str]] = []
1893 partner = ""
1894 if collection == "orders":
1895 lines = _record_lines(base, "order_lines", "order_id", rid)
1896 if _text(record.get("doc_type")) != "purchase" and _text(requested.get("response")) == "rejected":
1897 # Rejecting the whole order: every line the buyer asked for is
1898 # answered "rejected" and nothing is payable.
1899 lines = []
1900 else:
1901 record = _settle_totals(base, "orders", dict(record), lines)
1902 body = _priced_body(base, record, lines, date_field="order_date")
1903 if _text(record.get("doc_type")) == "purchase":
1904 return "purchase_order", partner, body, refs
1905 origin = _inbox_for_record(base, "orders", rid)
1906 if origin and _text(origin.get("document_type")) == "purchase_order":
1907 partner = _text(origin["sender"])
1908 refs.append({"id": _text(origin["document_id"]), "type": "purchase_order"})
1909 _confirm_lines(body, origin, lines, _text(requested.get("response")))
1910 return "order_confirmation", partner, body, refs
1911 if collection == "invoices":
1912 if _text(record.get("doc_type")) == "quote":
1913 raise Refusal(409, "not_sendable", "A quote is not a document this exchange sends.")
1914 lines = _record_lines(base, "invoice_lines", "invoice_id", rid)
1915 record = _settle_totals(base, "invoices", dict(record), lines)
1916 body = _priced_body(base, record, lines, date_field="issue_date")
1917 doc_type = "credit_note" if _text(record.get("doc_type")) == "credit_note" else "invoice"
1918 order_id = _text(record.get("source_order_id"))
1919 origin = _inbox_for_record(base, "orders", order_id) if order_id else None
1920 if origin and _text(origin.get("document_type")) == "purchase_order":
1921 partner = _text(origin["sender"])
1922 refs.append({"id": _text(origin["document_id"]), "type": "purchase_order"})
1923 credits = _text(requested.get("credits_invoice_id")) or _text(record.get("credits_invoice_id"))
1924 if doc_type == "credit_note" and credits:
1925 sent = _sent_for_record(base, "invoices", credits, "invoice")
1926 if not sent:
1927 raise Refusal(409, "not_sent", "The invoice this credits was never sent.")
1928 credited = _get("invoices", credits, base) or {}
1929 if _text(credited.get("currency")) != body["currency"]:
1930 raise Refusal(409, "currency_mismatch",
1931 f"The credit note is in {body['currency']}; the invoice it credits "
1932 f"is in {credited.get('currency')}.")
1933 partner = partner or _text(sent["partner_domain"])
1934 refs.append({"id": _text(sent["document_id"]), "type": "invoice"})
1935 _cite_credited_lines(base, body, lines, credits)
1936 return doc_type, partner, body, refs
1937 if collection == "supplier_bills":
1938 raise Refusal(409, "send_the_payment",
1939 "A remittance says how much was paid on each bill, so it is sent from the "
1940 "payment, not the bill: record what you paid in supplier_payments (one line "
1941 "per bill in supplier_payment_lines, any amount up to what the bill still "
1942 "owes) and send that (collection: supplier_payments).")
1943 if collection == "supplier_payments":
1944 return _compose_remittance(base, record)
1945 if collection == "receipts":
1946 if _text(record.get("status")) != "received":
1947 raise Refusal(409, "not_received", "A goods receipt is sent once it is received.")
1948 lines = _record_lines(base, "receipt_lines", "receipt_id", rid)
1949 if not lines:
1950 raise Refusal(409, "no_lines", "This receipt has no lines.")
1951 body = {"received_on": _text(record.get("received_on")) or _now().date().isoformat(),
1952 "lines": [{"line_id": _text(l["id"]), "description": _text(l.get("description")) or "item",
1953 "quantity_received": _decimal_text(l.get("quantity_received")),
1954 "quantity_rejected": _decimal_text(l.get("quantity_rejected"))}
1955 for l in lines]}
1956 sent = _sent_for_record(base, "orders", _text(record.get("order_id")), "purchase_order")
1957 if sent:
1958 partner = _text(sent["partner_domain"])
1959 refs.append({"id": _text(sent["document_id"]), "type": "purchase_order"})
1960 return "receipt", partner, body, refs
1961 raise Refusal(400, "not_sendable", f"Nothing is sent from {collection} records.")
1962
1963
1964def _cite_credited_lines(base: str, body: dict[str, Any], lines: list[Mapping[str, Any]],
1965 credited_invoice_id: str) -> None:
1966 """A credit-note line that says which line of the credited invoice it
1967 gives back (invoice_lines.credits_line_id: app-counter stamps it, staff
1968 may set it on a hand-made one) is sent with ref_line_id naming that line
1969 -- its line_id in the invoice document the customer's box already holds.
1970 A line naming no line, or a line of some other invoice, is sent without
1971 one rather than pointing at something the other box never received."""
1972 credited = {_text(l["id"]) for l in _record_lines(base, "invoice_lines", "invoice_id",
1973 credited_invoice_id)}
1974 for entry, line in zip(body["lines"], lines):
1975 ref = _text(line.get("credits_line_id"))
1976 if ref and ref in credited and ex.valid_id(ref):
1977 entry["ref_line_id"] = ref
1978
1979
1980def _compose_remittance(base: str, payment: Mapping[str, Any]
1981 ) -> tuple[str, str, dict[str, Any], list[dict[str, str]]]:
1982 """A remittance from one supplier payment: exactly what was paid on each
1983 bill, which may be less than the bill (60% of it) and may span several
1984 bills of one supplier. Refused, naming the fix, when a line could not
1985 honestly be told to the supplier: a bill that did not come through the
1986 exchange (the supplier's box would not know it), bills of two suppliers
1987 or currencies in one payment, a bill nobody approved, or a payment that
1988 takes a bill past what it owes after credits."""
1989 lines = _record_lines(base, "supplier_payment_lines", "payment_id", _text(payment["id"]))
1990 if not lines:
1991 raise Refusal(409, "no_lines", "This payment has no lines: add one per bill it pays.")
1992 currency = _text(payment.get("currency"))
1993 per_bill: dict[str, int] = {}
1994 bills: dict[str, dict[str, Any]] = {}
1995 for line in lines:
1996 bill = _get("supplier_bills", _text(line.get("bill_id")), base)
1997 if not bill:
1998 raise Refusal(409, "no_bill", f"Payment line {line['id']} names no bill on this box.")
1999 if _text(bill.get("source")) != "exchange" or not _text(bill.get("exchange_document_id")):
2000 raise Refusal(409, "not_exchanged",
2001 f"Bill {bill.get('number')} did not arrive through the exchange, so the "
2002 f"supplier's box would not know what it pays.")
2003 if _text(bill.get("doc_type")) != "invoice":
2004 raise Refusal(409, "not_an_invoice",
2005 f"{bill.get('number')} is a credit note; it is applied, not paid.")
2006 if _text(bill.get("status")) not in ("approved", "paid"):
2007 raise Refusal(409, "not_approved",
2008 f"Bill {bill.get('number')} is {bill.get('status')}: a bill is paid once "
2009 f"a person approved it.")
2010 if _text(bill.get("currency")) != currency:
2011 raise Refusal(409, "currency_mismatch",
2012 f"The payment is in {currency}; bill {bill.get('number')} is in "
2013 f"{bill.get('currency')}.")
2014 bills[bill["id"]] = bill
2015 per_bill[bill["id"]] = per_bill.get(bill["id"], 0) + _int_text(line.get("amount_cents"))
2016 domains = {_text(b.get("supplier_domain")) for b in bills.values()}
2017 if len(domains) != 1:
2018 raise Refusal(409, "several_suppliers",
2019 "One remittance goes to one supplier; this payment pays bills of "
2020 + ", ".join(sorted(domains)) + ".")
2021 for bill_id, bill in bills.items():
2022 if _int_text(bill.get("outstanding_cents")) < 0:
2023 raise Refusal(409, "overpaid",
2024 f"Bill {bill.get('number')} would be paid past what it owes: "
2025 f"{bill.get('total_cents')} billed, {bill.get('credited_cents') or 0} "
2026 f"credited, {bill.get('paid_cents')} paid. Correct the payment line.")
2027 settles = [{"document_id": _text(bills[b]["exchange_document_id"]),
2028 "number": _text(bills[b].get("number")), "amount_minor": amount}
2029 for b, amount in sorted(per_bill.items(), key=lambda kv: _text(bills[kv[0]].get("number")))]
2030 body = {"currency": currency, "paid_minor": sum(per_bill.values()),
2031 "paid_on": _text(payment.get("paid_on")) or _now().date().isoformat(),
2032 "payment_reference": _text(payment.get("payment_reference")),
2033 "settles": settles}
2034 refs = [{"id": item["document_id"], "type": "invoice"} for item in settles]
2035 return "remittance", domains.pop(), body, refs
2036
2037
2038def _after_send(base: str, collection: str, record: Mapping[str, Any], doc_type: str,
2039 document_id: str, body: Mapping[str, Any], refs: list[Mapping[str, str]],
2040 credited_invoice_id: str) -> None:
2041 """What sending a document makes true in our own books, written by this
2042 writer in the same act (logic-decisions #9), after the signed document
2043 exists and never before:
2044
2045 - a remittance freezes the payment it was made from, and its lines: the
2046 supplier has been told, so it is a fact both companies hold;
2047 - a credit note is applied as it says -- to the invoice it credits, or on
2048 the customer's account -- so the customer's box and ours reduce the
2049 same invoice by the same amount, and the credit note itself never
2050 reads as a balance due."""
2051 if collection == "supplier_payments":
2052 object_records.update_collection_record(
2053 "supplier_payments", record["id"],
2054 {"remitted": "true", "remittance_document_id": document_id},
2055 base_dir=base, actor=ACTOR, preserve_read_only=True)
2056 for line in _record_lines(base, "supplier_payment_lines", "payment_id", _text(record["id"])):
2057 object_records.update_collection_record(
2058 "supplier_payment_lines", line["id"], {"remitted": "true"},
2059 base_dir=base, actor=ACTOR, preserve_read_only=True)
2060 elif doc_type == "credit_note" and _installed("invoice_credits", base):
2061 if any(_text(r.get("credit_note_id")) == _text(record["id"])
2062 for r in _rows("invoice_credits", base)):
2063 return
2064 object_records.create_collection_record("invoice_credits", {
2065 "id": object_ids.new_uuid4(), "credit_note_id": _text(record["id"]),
2066 "invoice_id": credited_invoice_id,
2067 "amount_cents": str(body["totals"]["payable_minor"]),
2068 "applied_on": _text(body.get("issue_date")) or _now().date().isoformat(),
2069 "source": "exchange", "owner_id": _text(record.get("owner_id"))},
2070 base_dir=base, actor=ACTOR)
2071
2072
2073def send(base: str, identity_: Mapping[str, Any] | None, *, collection: str, record_id: str,
2074 partner_domain: str = "", requested: Mapping[str, Any] | None = None) -> dict[str, Any]:
2075 """Make the signed document for one business record and queue it.
2076 Staff only (is_staff), and only a record they may update."""
2077 me = require_identity(base)
2078 ex._ed25519()
2079 access = object_access.Access(identity_, base_dir=base)
2080 if not is_staff(access):
2081 raise Refusal(403, "not_allowed",
2082 "Sending a document to a trading partner is for staff.")
2083 collection, record_id = _text(collection), _text(record_id)
2084 try:
2085 record = access.get(collection, record_id, action="update")
2086 except object_collections.CollectionNotFoundError:
2087 record = None
2088 if record is None:
2089 raise Refusal(404, "no_record", "No such record.")
2090 doc_type, derived, body, refs = _compose(base, collection, record, requested or {})
2091 domain = _text(partner_domain).lower() or derived
2092 if not domain:
2093 raise Refusal(400, "no_partner", "Name the partner to send this to (partner).")
2094 partner = partner_by_domain(base, domain)
2095 if not partner or _text(partner.get("status")) != "connected":
2096 raise Refusal(409, "not_connected", f"{domain} is not a connected trading partner.")
2097 if doc_type not in _types(partner.get("send_types")):
2098 raise Refusal(403, "type_not_allowed", f"Sending {doc_type} to {domain} is switched off.")
2099 already = _sent_for_record(base, collection, record_id, doc_type)
2100 if already:
2101 raise Refusal(409, "already_sent",
2102 f"This record was already sent as {already['document_id']}; corrections "
2103 f"are new documents (a credit note), not a second copy.",
2104 document_id=already["document_id"], outbox_id=already["id"])
2105 document_id = f"doc-{object_ids.new_uuid4()}"
2106 try:
2107 envelope, signature = _signed_envelope(base, doc_id=document_id, doc_type=doc_type,
2108 sender=_text(me["domain"]), recipient=domain,
2109 body=body, refs=refs)
2110 except ex.EnvelopeError as exc:
2111 # Our own record does not make a well-formed document (no lines, a
2112 # date or currency missing): say what, rather than fail the request.
2113 raise Refusal(409, "not_sendable", "This record does not make a well-formed document: "
2114 + "; ".join(exc.problems) + ".", problems=exc.problems) from exc
2115 row = {"id": object_ids.new_uuid4(), "document_id": document_id, "document_type": doc_type,
2116 "partner_domain": domain, "source_collection": collection, "source_record_id": record_id,
2117 "envelope": json.dumps({"envelope": envelope, "signature": signature}, sort_keys=True,
2118 ensure_ascii=False),
2119 "envelope_sha256": ex.sha256_hex(ex.canonical(envelope)), "status": "queued",
2120 "attempts": "0", "next_attempt_at": "", "last_error": "", "receipt": "",
2121 "receipt_verified": "false", "owner_id": access.user_id}
2122 try:
2123 object_records.create_collection_record("exchange_outbox", row, base_dir=base, actor=ACTOR)
2124 except object_records.UniqueConstraintError as exc:
2125 raise Refusal(409, "already_sent", "This record was already sent.") from exc
2126 credited = ""
2127 if doc_type == "credit_note" and any(ref.get("type") == "invoice" for ref in refs):
2128 # _compose found it sent (it is the invoice the document refers to).
2129 credited = (_text((requested or {}).get("credits_invoice_id"))
2130 or _text(record.get("credits_invoice_id")))
2131 _after_send(base, collection, record, doc_type, document_id, body, refs, credited)
2132 return {"ok": True, "document_id": document_id, "document_type": doc_type,
2133 "outbox_id": row["id"], "partner": domain, "status": "queued"}
2134
2135
2136def refuse_document(base: str, inbox_id: str, identity_: Mapping[str, Any] | None, *,
2137 reason: str) -> dict[str, Any]:
2138 """A person refuses a document a partner delivered ("not our order",
2139 "these prices were never agreed"): the sender is told with a signed
2140 document_refusal naming the document by id and hash, which its box
2141 records against what it sent; here the inbox row records the decision
2142 and a bill made from a refused invoice is disputed. Nothing is recorded
2143 unless the sender was told, so the two boxes never disagree about
2144 whether a document was refused. Staff only."""
2145 me = require_identity(base)
2146 reason = _text(reason)[:500]
2147 if not reason:
2148 raise Refusal(400, "no_reason", "Say why the document is refused; the sender is told.")
2149 row = _get("exchange_inbox", inbox_id, base)
2150 if not row:
2151 raise Refusal(404, "no_document", "No such inbox document.")
2152 if _text(row.get("resolution")):
2153 raise Refusal(409, "already_decided", f"This document was already {row['resolution']}.")
2154 if _text(row.get("document_type")) == "remittance" \
2155 and _text(row.get("mapping_status")) != AWAITING_CONFIRMATION:
2156 raise Refusal(409, "already_recorded", "A confirmed remittance is a recorded payment.")
2157 access = object_access.Access(identity_, base_dir=base)
2158 if not is_staff(access):
2159 raise Refusal(403, "not_allowed", "Refusing a partner's document is for staff.")
2160 partner = _get("trading_partners", _text(row.get("partner_id")), base) or {}
2161 if _text(partner.get("status")) != "connected":
2162 raise Refusal(409, "not_connected", "That partner is no longer connected.")
2163 envelope, signature = _signed_envelope(
2164 base, doc_id=f"refusal-{object_ids.new_uuid4()}", doc_type="document_refusal",
2165 sender=_text(me["domain"]), recipient=_text(partner["domain"]),
2166 refs=[{"id": _text(row["document_id"]), "type": _text(row["document_type"])}],
2167 body={"document_id": _text(row["document_id"]),
2168 "envelope_sha256": _text(row["envelope_sha256"]),
2169 "code": "refused_by_person", "reason": reason})
2170 status, reply = _post(_text(partner["exchange_endpoint"]), _wire(base, envelope, signature))
2171 if not 200 <= status < 300:
2172 why = reply.get("error") if isinstance(reply, Mapping) else ""
2173 raise Refusal(502, "not_delivered",
2174 f"{partner['domain']} could not be told ({status}: {why}); nothing was "
2175 f"recorded. Try again.")
2176 object_records.update_collection_record(
2177 "exchange_inbox", inbox_id,
2178 {"mapping_status": MAPPED, "resolution": "refused", "resolved_by": access.user_id,
2179 "resolved_at": ex.utc_stamp(),
2180 "mapping_reason": f"Refused by {access.user_id}: {reason}. {partner['domain']} was told."[:2000],
2181 "updated_at": ex.utc_stamp()}, base_dir=base, actor=ACTOR)
2182 if _text(row.get("mapped_collection")) == "supplier_bills" and _text(row.get("mapped_record_id")):
2183 bill = _get("supplier_bills", _text(row["mapped_record_id"]), base) or {}
2184 if _text(bill.get("status")) == "received":
2185 object_records.update_collection_record(
2186 "supplier_bills", bill["id"], {"status": "disputed"}, base_dir=base,
2187 actor=f"exchange-refuse:{access.user_id}")
2188 return {"ok": True, "inbox_id": inbox_id, "resolution": "refused", "told": partner["domain"]}
2189
2190
2191def _due(row: Mapping[str, Any], now: datetime) -> bool:
2192 if _text(row.get("status")) != "queued":
2193 return False
2194 when = ex.parse_stamp(row.get("next_attempt_at"))
2195 return when is None or when <= now
2196
2197
2198def backoff_seconds(attempts: int) -> int:
2199 return int(min(RETRY_BASE_SECONDS * (2 ** max(0, attempts - 1)), RETRY_MAX_SECONDS))
2200
2201
2202def _check_receipt(base: str, partner: Mapping[str, Any], row: Mapping[str, Any],
2203 answer: Any, me: Mapping[str, Any], *, status: str = "stored") -> str:
2204 """'' when the answer is a receipt for exactly this document, signed by a
2205 key pinned for this partner; otherwise what is wrong with it."""
2206 if not isinstance(answer, Mapping):
2207 return "the answer was not JSON"
2208 receipt, signature = answer.get("receipt"), answer.get("signature")
2209 if not isinstance(receipt, Mapping) or not isinstance(signature, Mapping):
2210 return "the answer carried no signed receipt"
2211 expected = {"dron_receipt": ex.DRON_DOCUMENT_VERSION, "document_id": row["document_id"],
2212 "sender": _text(me["domain"]), "recipient": row["partner_domain"],
2213 "envelope_sha256": row["envelope_sha256"], "status": status}
2214 for key, value in expected.items():
2215 if receipt.get(key) != value:
2216 return f"the receipt's {key} does not match"
2217 pinned = _absorb_vouches(_pinned(partner), answer.get("key_vouches"))
2218 if signature.get("key_id") not in pinned:
2219 return "the receipt is signed with a key not pinned for this partner"
2220 if not ex.verify(pinned[signature["key_id"]], ex.receipt_message(receipt), signature):
2221 return "the receipt's signature does not verify"
2222 _pin(base, partner, pinned)
2223 return ""
2224
2225
2226def deliver_one(base: str, row: Mapping[str, Any], now: datetime | None = None) -> dict[str, Any]:
2227 now = now or _now()
2228 me = require_identity(base)
2229 attempts = int(_text(row.get("attempts")) or 0) + 1
2230 update: dict[str, Any] = {"attempts": str(attempts), "updated_at": ex.utc_stamp(now)}
2231 partner = partner_by_domain(base, _text(row.get("partner_domain")))
2232 if not partner or _text(partner.get("status")) != "connected":
2233 update.update(status="dead", last_error="The partner is not connected.")
2234 return object_records.update_collection_record("exchange_outbox", row["id"], update,
2235 base_dir=base, actor=ACTOR)
2236 stored = _json(row.get("envelope"), {})
2237 wire = _wire(base, stored["envelope"], stored["signature"])
2238 try:
2239 status, answer = ex.request_json("POST", _text(partner["exchange_endpoint"]), wire)
2240 except ex.TransportError as exc:
2241 status, answer = 0, {"error": str(exc)}
2242 update["last_status_code"] = str(status)
2243 if 200 <= status < 300:
2244 problem = _check_receipt(base, partner, row, answer, me)
2245 if problem:
2246 update.update(status="dead", last_error=f"Delivered, but {problem}.")
2247 else:
2248 update.update(status="delivered", delivered_at=ex.utc_stamp(now), last_error="",
2249 receipt=json.dumps(answer, sort_keys=True), receipt_verified="true")
2250 elif status and 400 <= status < 500 and status not in (408, 425, 429):
2251 reason = answer.get("error") if isinstance(answer, Mapping) else ""
2252 signed = answer.get("refusal") if isinstance(answer, Mapping) else None
2253 if isinstance(signed, Mapping) and not _check_receipt(base, partner, row, signed, me,
2254 status="refused"):
2255 object_records.update_collection_record("exchange_outbox", row["id"], update,
2256 base_dir=base, actor=ACTOR)
2257 receipt = signed["receipt"]
2258 return _record_refusal(base, row, _text(partner["domain"]),
2259 _text(receipt.get("code")), _text(receipt.get("reason")),
2260 dict(signed))
2261 update.update(status="dead", last_error=f"Refused by the partner ({status}): {reason}"[:500])
2262 else:
2263 reason = answer.get("error") if isinstance(answer, Mapping) else ""
2264 update["last_error"] = f"No delivery ({status or 'no answer'}): {reason}"[:500]
2265 if attempts >= MAX_ATTEMPTS:
2266 update["status"] = "dead"
2267 else:
2268 update["next_attempt_at"] = ex.utc_stamp(now + timedelta(seconds=backoff_seconds(attempts)))
2269 return object_records.update_collection_record("exchange_outbox", row["id"], update,
2270 base_dir=base, actor=ACTOR)
2271
2272
2273def deliver_due(base: str, *, now: datetime | None = None, limit: int = 50) -> dict[str, Any]:
2274 """The daemon's pass: every due outbox row, oldest first."""
2275 now = now or _now()
2276 if identity(base) is None:
2277 return {"ok": True, "attempted": 0, "note": "exchange not configured"}
2278 due = sorted((r for r in _rows("exchange_outbox", base) if _due(r, now)),
2279 key=lambda r: _text(r.get("created_at")))[:limit]
2280 results = {"delivered": 0, "retrying": 0, "dead": 0}
2281 for row in due:
2282 after = deliver_one(base, row, now)
2283 status = _text(after.get("status"))
2284 results["delivered" if status == "delivered" else "dead" if status == "dead"
2285 else "retrying"] += 1
2286 return {"ok": True, "attempted": len(due), **results}
2287
2288
2289def requeue(base: str, outbox_id: str) -> dict[str, Any]:
2290 row = _get("exchange_outbox", outbox_id, base)
2291 if not row:
2292 raise Refusal(404, "no_document", "No such outbox document.")
2293 if _text(row.get("status")) != "dead":
2294 raise Refusal(409, "not_dead", "Only a document whose delivery stopped is queued again.")
2295 object_records.update_collection_record(
2296 "exchange_outbox", outbox_id,
2297 {"status": "queued", "attempts": "0", "next_attempt_at": "", "updated_at": ex.utc_stamp()},
2298 base_dir=base, actor=ACTOR)
2299 return {"ok": True, "outbox_id": outbox_id, "status": "queued"}