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

9 downloads

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, 49 minutes ago History
counter_pay.py · 5.1 KB · 107 lines
1"""action_counter_pay -- a cashier takes payment for a sale at the counter.
2
3POST {"invoice_id": "..." | "order_id": "...", "amount_cents": "650", "method": "cash"}
4
5Payments are recorded by role:manager over the records API (app-payments
60.8.0 took the grant away from customers, who owned the invoices they could
7mark paid). A cashier is the person who actually takes the money at a
8counter, and Corner Cup's cashiers had no way to record it except the
9owner's login. Granting cashiers create on payments would not do: a
10payment's invoice_id declares relation.requires update, so they would also
11need update on invoices -- the power to reprice and void bills.
12
13So this action records it, in process, for a bill the caller may read and
14that is issued (not a draft, a void, a quote or a credit note) with money
15still open on it; anything else gets the answer a missing id gets, before
16anything is written. The amount defaults to the open balance and may not
17exceed it, and the ledger's locked check (hook_payments.LOCKED_CHECK, every
18writer) still refuses anything over it. Only the roles app-counter's rules
19give execute on this action run it (object_corrections.staff_refusal),
20whatever the server's enforcement setting.
21The payment is filed under the bill's owner, as checkout and the Stripe
22webhook file theirs, and attributed to the cashier in the change log
23(actor "action_counter_pay:<user>").
24"""
25
26from __future__ import annotations
27
28import os
29from datetime import date
30
31import object_access
32import object_corrections
33import object_ids
34import object_record_changes
35import object_records
36
37ACTOR = "action_counter_pay"
38METHODS = ("cash", "card", "check", "transfer", "other")
39
40
41def _base_dir():
42 return os.environ.get("DBBASIC_DATA_DIR", "data")
43
44
45def _post(request):
46 text = object_corrections.text
47 base = _base_dir()
48 access = object_access.Access(request.get("_identity"), base_dir=base)
49 if not access.signed_in:
50 return {"status": 401, "error": "Sign in to take a payment."}
51 staff = object_corrections.staff_refusal(access, "action_counter_pay", doing="take a payment here")
52 if staff:
53 return staff
54 invoice = None
55 if text(request.get("invoice_id")):
56 invoice = access.get("invoices", text(request.get("invoice_id")))
57 elif text(request.get("order_id")):
58 order = access.get("orders", text(request.get("order_id")))
59 if order is not None:
60 # access: filtered to the order read through access.get above, and each bill asked about with access.can
61 bills = object_corrections.bills_for_order(
62 order, object_records.read_collection_records("invoices", base_dir=base))
63 bills = [b for b in bills if object_corrections.issued(b)
64 and access.can("read", "invoices", b)]
65 # The one still owing first; a settled one answers "nothing is owed".
66 bills.sort(key=lambda b: object_corrections.cents(b.get("balance_due_cents")) <= 0)
67 invoice = bills[0] if bills else None
68 # Only an issued bill takes a payment here: not a draft, a void, a quote
69 # or a credit note, whichever way it was named. All of those get the
70 # answer a missing or unreadable id gets, before anything is written.
71 if not object_corrections.issued(invoice):
72 return {"status": 404, "error": "No bill to take payment for."}
73 method = text(request.get("method") or "cash")
74 if method not in METHODS:
75 return {"status": 400, "error": f"method is one of {', '.join(METHODS)}."}
76 balance = object_corrections.cents(invoice.get("balance_due_cents"))
77 if balance <= 0:
78 return {"status": 409, "error": "Nothing is owed on this bill."}
79 amount = object_corrections.cents(request.get("amount_cents") or balance)
80 if amount <= 0:
81 return {"status": 400, "error": "amount_cents is a whole number of cents above zero."}
82 if amount > balance:
83 return {"status": 409, "error": f"This bill has {balance} open; nothing was recorded."}
84 row = {"id": object_ids.new_uuid4(), "invoice_id": text(invoice.get("id")),
85 "amount_cents": str(amount), "method": method,
86 "received_on": date.today().isoformat(), "status": "received",
87 "reference": text(request.get("reference"))[:120],
88 "owner_id": text(invoice.get("owner_id"))}
89 try:
90 # access: system write after access check above (access.get on the bill)
91 stored = object_records.create_collection_record(
92 "payments", row, base_dir=base, actor=f"{ACTOR}:{access.user_id}")
93 except object_records.CheckRefusedError as exc:
94 return {"status": exc.status, "error": str(exc)}
95 return {"status": 200, "ok": True, "payment_id": stored["id"],
96 "invoice_id": row["invoice_id"], "amount_cents": amount}
97
98
99def _t(value):
100 return str(value if value is not None else "").strip()
101
102
103def POST(request):
104 """Every record change this action writes carries why, as the history
105 entry's message (object_record_changes.change_reason)."""
106 with object_record_changes.change_reason(f"payment taken at the counter ({_t(request.get('method')) or 'cash'})"):
107 return _post(request)