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

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
expenses.py · 5.0 KB · 123 lines
1"""Pre-write hook for expenses: the gate between spending and the books.
2
3The same shape as hook_time_logs, because it is the same problem --
4somebody other than the person who incurred the cost has to say yes
5before it becomes a journal entry or a line on a client's bill.
6
7One difference from time, and it matters: approval here does NOT require
8the expense to be billable. Unbillable time is simply not billed;
9unbillable spending still left the bank account, still belongs in the
10ledger, and still has to be approved by somebody. Refusing to approve it
11would leave real money unrecorded, which is a worse failure than an
12unbilled hour.
13
14Approval stamps the markup and the billable amount (docs/logic-decisions.md
15#1), so re-running a bill can never apply this quarter's markup policy to
16last quarter's approved costs. After that the expense is frozen -- a
17mistake is corrected by a compensating entry or a credit, never by
18editing the record of what was spent (#5, #8). The journal itself is a
19REACTION and lives in system_expense_books (#6), not here: a books
20mapping that is not configured yet must never block somebody from
21recording that they bought a plane ticket.
22"""
23
24import os
25from datetime import datetime, timezone
26
27import object_rates
28import object_records
29
30_ALLOWED_AFTER_APPROVAL = {"status", "invoice_id", "notes", "receipt_ref"}
31
32
33def _base_dir():
34 return os.environ.get("DBBASIC_DATA_DIR", "data")
35
36
37def _truthy(value):
38 return str(value or "").strip().lower() in ("true", "1", "yes", "on")
39
40
41def _int(value):
42 try:
43 return int(str(value or "0").strip() or 0)
44 except (TypeError, ValueError):
45 return 0
46
47
48def _setting(base, key, default=""):
49 try:
50 for row in object_records.read_collection_records("app_settings", base_dir=base):
51 if row.get("key") == key and str(row.get("value") or "").strip():
52 return row["value"].strip()
53 except Exception:
54 pass
55 return default
56
57
58def BEFORE_WRITE(request):
59 action = request.get("action")
60 record = dict(request.get("record") or {})
61 existing = request.get("existing") or {}
62 changes = request.get("changes") or {}
63 subject = request.get("subject") or {}
64 actor = str(subject.get("user_id") or "")
65
66 was = str(existing.get("status") or "") if action == "update" else ""
67 now = str(record.get("status") or existing.get("status") or "draft")
68 merged = {**existing, **record}
69
70 if action == "create" and _int(merged.get("amount_cents")) <= 0:
71 return {"error": ("An expense needs an amount. A refund or a credit "
72 "note is its own positive record on the other side, "
73 "never a negative spend."), "status": 400}
74
75 # --- frozen once approved -------------------------------------------
76 if action == "update" and was in ("approved", "billed"):
77 touched = [field for field in changes
78 if field not in _ALLOWED_AFTER_APPROVAL]
79 if touched:
80 return {"error": (
81 f"This expense is {was}; what was spent is settled and its "
82 f"journal is already posted. Correct it with a compensating "
83 f"entry or a credit, not by editing "
84 f"{', '.join(sorted(touched))}."), "status": 409}
85 if was == "billed" and now != "billed":
86 return {"error": ("A billed expense cannot be reopened. A dispute "
87 "is a credit on the invoice, not a rewind."),
88 "status": 409}
89
90 # --- submitting ------------------------------------------------------
91 if now == "submitted" and was != "submitted":
92 if _int(merged.get("amount_cents")) <= 0:
93 return {"error": "An expense with no amount has nothing to approve.",
94 "status": 400}
95 if not str(merged.get("incurred_on") or "").strip():
96 return {"error": ("An expense needs the date it was incurred: that "
97 "is the period its journal belongs to."),
98 "status": 400}
99
100 # --- approving -------------------------------------------------------
101 if now == "approved" and was != "approved":
102 owner = str(merged.get("owner_id") or "")
103 if actor and owner and actor == owner:
104 return {"error": ("Expenses are approved by somebody other than the "
105 "person who incurred them. Approving your own "
106 "spending is not an approval."), "status": 403}
107
108 base = _base_dir()
109 markup = merged.get("markup_bps")
110 if markup in (None, ""):
111 markup = _setting(base, "billing.expense_markup_bps", "0")
112 markup_bps = _int(markup)
113 amount = _int(merged.get("amount_cents"))
114
115 record["markup_bps"] = str(markup_bps)
116 record["billable_amount_cents"] = str(
117 object_rates.with_markup(amount, markup_bps)
118 if _truthy(merged.get("billable")) else 0)
119 record["approved_by"] = actor
120 record["approved_at"] = datetime.now(timezone.utc).isoformat()
121 return {"record": record}
122
123 return None