askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
expenses.py · 9.7 KB · 215 lines
| 1 | """Pre-write hook for expenses: the gate between spending and the books. |
| 2 | |
| 3 | The same shape as hook_time_logs, because it is the same problem -- |
| 4 | somebody other than the person who incurred the cost has to say yes |
| 5 | before it becomes a journal entry or a line on a client's bill. |
| 6 | |
| 7 | One difference from time, and it matters: approval here does NOT require |
| 8 | the expense to be billable. Unbillable time is simply not billed; |
| 9 | unbillable spending still left the bank account, still belongs in the |
| 10 | ledger, and still has to be approved by somebody. Refusing to approve it |
| 11 | would leave real money unrecorded, which is a worse failure than an |
| 12 | unbilled hour. |
| 13 | |
| 14 | Approval 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 |
| 16 | last quarter's approved costs. After that the expense is frozen -- a |
| 17 | mistake is corrected by a compensating entry or a credit, never by |
| 18 | editing the record of what was spent (#5, #8). The freeze is the schema's |
| 19 | `locked_when` (approved and billed; status, invoice_id, notes and |
| 20 | receipt_ref may still move), checked inside the write lock for every |
| 21 | writer and on delete; `transitions` leaves billed terminal; `amount_cents` |
| 22 | declares `validation.min` 1 and `incurred_on` is `required`, so the hook no |
| 23 | longer carries a copy of those either. The journal itself is a |
| 24 | REACTION and lives in system_expense_books (#6), not here: a books |
| 25 | mapping that is not configured yet must never block somebody from |
| 26 | recording that they bought a plane ticket. |
| 27 | |
| 28 | Substantiation (app-finance 0.19.0). An expense names a category, and the |
| 29 | category says what an auditor will ask for: a business purpose, the people |
| 30 | who were there, a receipt over some amount, and how much of it is |
| 31 | deductible. Three placements were weighed: |
| 32 | |
| 33 | - `required_when` alone cannot read another collection, so it cannot say |
| 34 | "required when the CATEGORY says so". |
| 35 | - A hook alone is advisory (it runs before the write lock) and is skipped by |
| 36 | every storage-level writer: confirm_scan, the mileage handler, imports. |
| 37 | - A locked check alone can refuse but not fill anything in, so every client |
| 38 | would have to compute the deductible share itself. |
| 39 | |
| 40 | So the three are layered, each doing the part only it can. This hook |
| 41 | STAMPS what the category says onto the expense (receipt_required, |
| 42 | purpose_required, attendees_required, deductible_bps, deductible_cents) on |
| 43 | any write that changes the category or the amount and on the moves into |
| 44 | submitted and approved. `required_when` on the schema turns the stamped |
| 45 | flags into refusals while the expense is submitted, approved or billed -- |
| 46 | declared, for every writer. And LOCKED_CHECK below, inside the write lock |
| 47 | and for every writer, refuses stamps that disagree with the category at |
| 48 | that moment, so nobody can submit a client dinner stamped "no attendees |
| 49 | required" by writing below this hook. Both call |
| 50 | object_expense_rules.category_stamps, so the early answer and the locked |
| 51 | one are one function. The stamps are point-in-time (#1): once approved |
| 52 | they are frozen with the rest of the record, and a category edited next |
| 53 | year restates nothing. |
| 54 | """ |
| 55 | |
| 56 | import os |
| 57 | from datetime import datetime, timezone |
| 58 | |
| 59 | import object_collections |
| 60 | import object_expense_rules as rules |
| 61 | import object_rates |
| 62 | import object_records |
| 63 | |
| 64 | |
| 65 | def _base_dir(): |
| 66 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 67 | |
| 68 | |
| 69 | def _truthy(value): |
| 70 | return str(value or "").strip().lower() in ("true", "1", "yes", "on") |
| 71 | |
| 72 | |
| 73 | def _int(value): |
| 74 | try: |
| 75 | return int(str(value or "0").strip() or 0) |
| 76 | except (TypeError, ValueError): |
| 77 | return 0 |
| 78 | |
| 79 | |
| 80 | def _setting(base, key, default=""): |
| 81 | try: |
| 82 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 83 | if row.get("key") == key and str(row.get("value") or "").strip(): |
| 84 | return row["value"].strip() |
| 85 | except Exception: |
| 86 | pass |
| 87 | return default |
| 88 | |
| 89 | |
| 90 | def _category(base, category_id): |
| 91 | """The category row, None when there is no such row (or no categories |
| 92 | collection at all, which is a fact, not an unknown). Raises when the |
| 93 | collection cannot be read: an unread category is not "no requirements".""" |
| 94 | try: |
| 95 | return object_records.get_collection_record( |
| 96 | "expense_categories", category_id, base_dir=base) |
| 97 | except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError): |
| 98 | return None |
| 99 | |
| 100 | |
| 101 | def _inactive_choice(category, existing, category_id): |
| 102 | changed = existing is None or rules.text(existing.get("category_id")) != category_id |
| 103 | return changed and not rules.truthy(rules.text(category.get("active")) or "true") |
| 104 | |
| 105 | |
| 106 | def _stamp(record, existing, base): |
| 107 | """(record with the category's stamps, None) or (None, refusal).""" |
| 108 | if not rules.stamps_are_judged(record, existing): |
| 109 | return record, None |
| 110 | category_id = rules.text(record.get("category_id")) |
| 111 | if not category_id: |
| 112 | return {**record, **rules.blank_stamps()}, None |
| 113 | try: |
| 114 | category = _category(base, category_id) |
| 115 | except Exception: |
| 116 | return None, {"error": "Expense categories are unreadable; refusing to judge " |
| 117 | "this expense against unknown requirements.", "status": 503} |
| 118 | if category is None: |
| 119 | return record, None # the relation check answers "missing record" |
| 120 | if _inactive_choice(category, existing, category_id): |
| 121 | return None, {"error": f"The category {category.get('name') or category_id} is no " |
| 122 | "longer in use. Choose another.", "status": 409} |
| 123 | try: |
| 124 | stamps = rules.category_stamps(category, record.get("amount_cents")) |
| 125 | except ValueError: |
| 126 | return record, None # validation names a bad amount; the check a bad category |
| 127 | return {**record, **stamps}, None |
| 128 | |
| 129 | |
| 130 | def LOCKED_CHECK(request): |
| 131 | """category_stamps: inside the write lock, for every writer. The |
| 132 | expense's stamps must be what its category says now, whenever they are |
| 133 | judged (a create; a change of category, amount or stamp; a move into |
| 134 | submitted or approved). No category: every stamp blank. A category |
| 135 | collection that cannot be read raises (503, nothing written).""" |
| 136 | record = request.get("record") or {} |
| 137 | existing = request.get("existing") if request.get("action") == "update" else None |
| 138 | if not rules.stamps_are_judged(record, existing): |
| 139 | return None |
| 140 | base = request.get("base_dir") or _base_dir() |
| 141 | category_id = rules.text(record.get("category_id")) |
| 142 | category = None |
| 143 | if category_id: |
| 144 | category = _category(base, category_id) |
| 145 | if category is None: |
| 146 | return {"error": f"No expense category {category_id}.", "status": 409} |
| 147 | if _inactive_choice(category, existing, category_id): |
| 148 | return {"error": f"The category {category.get('name') or category_id} is no " |
| 149 | "longer in use.", "status": 409} |
| 150 | try: |
| 151 | mismatch = rules.stamp_mismatch(record, category) |
| 152 | except ValueError as exc: |
| 153 | return {"error": f"This expense cannot be judged against its category: {exc}.", |
| 154 | "status": 409} |
| 155 | if mismatch: |
| 156 | return {"error": ("This expense's substantiation stamps do not match its category: " |
| 157 | f"{mismatch}. They are stamped from the category when the expense " |
| 158 | "is written through the record API; a writer below it stamps them " |
| 159 | "with object_expense_rules.category_stamps."), "status": 409} |
| 160 | return None |
| 161 | |
| 162 | |
| 163 | def BEFORE_WRITE(request): |
| 164 | action = request.get("action") |
| 165 | if action not in ("create", "update"): |
| 166 | # Same guard, same reason, as hook_time_logs: asked about a delete, |
| 167 | # the rules below mistook an approved expense for one being |
| 168 | # approved and answered with the self-approval refusal or a markup |
| 169 | # stamp. This hook takes no position on a delete; whether an |
| 170 | # approved or billed expense may be deleted is the schema's |
| 171 | # `locked_when` (it may not). |
| 172 | return None |
| 173 | record = dict(request.get("record") or {}) |
| 174 | existing = request.get("existing") or {} |
| 175 | subject = request.get("subject") or {} |
| 176 | actor = str(subject.get("user_id") or "") |
| 177 | |
| 178 | was = str(existing.get("status") or "") if action == "update" else "" |
| 179 | now = str(record.get("status") or existing.get("status") or "draft") |
| 180 | merged = {**existing, **record} |
| 181 | |
| 182 | stamped, refusal = _stamp(merged, existing if action == "update" else None, _base_dir()) |
| 183 | if refusal: |
| 184 | return refusal |
| 185 | stamped_fields = {name: stamped[name] for name in rules.STAMP_FIELDS |
| 186 | if rules.text(stamped.get(name)) != rules.text(merged.get(name))} |
| 187 | record.update(stamped_fields) |
| 188 | merged.update(stamped_fields) |
| 189 | |
| 190 | # --- approving ------------------------------------------------------- |
| 191 | if now == "approved" and was != "approved": |
| 192 | owner = str(merged.get("owner_id") or "") |
| 193 | if actor and owner and actor == owner: |
| 194 | return {"error": ("Expenses are approved by somebody other than the " |
| 195 | "person who incurred them. Approving your own " |
| 196 | "spending is not an approval."), "status": 403} |
| 197 | |
| 198 | base = _base_dir() |
| 199 | markup = merged.get("markup_bps") |
| 200 | if markup in (None, ""): |
| 201 | markup = _setting(base, "billing.expense_markup_bps", "0") |
| 202 | markup_bps = _int(markup) |
| 203 | amount = _int(merged.get("amount_cents")) |
| 204 | |
| 205 | record["markup_bps"] = str(markup_bps) |
| 206 | record["billable_amount_cents"] = str( |
| 207 | object_rates.with_markup(amount, markup_bps) |
| 208 | if _truthy(merged.get("billable")) else 0) |
| 209 | record["approved_by"] = actor |
| 210 | record["approved_at"] = datetime.now(timezone.utc).isoformat() |
| 211 | return {"record": record} |
| 212 | |
| 213 | if stamped_fields: |
| 214 | return {"record": record} |
| 215 | return None |