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.
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 | |
| 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 journal itself is a |
| 19 | REACTION and lives in system_expense_books (#6), not here: a books |
| 20 | mapping that is not configured yet must never block somebody from |
| 21 | recording that they bought a plane ticket. |
| 22 | """ |
| 23 | |
| 24 | import os |
| 25 | from datetime import datetime, timezone |
| 26 | |
| 27 | import object_rates |
| 28 | import object_records |
| 29 | |
| 30 | _ALLOWED_AFTER_APPROVAL = {"status", "invoice_id", "notes", "receipt_ref"} |
| 31 | |
| 32 | |
| 33 | def _base_dir(): |
| 34 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 35 | |
| 36 | |
| 37 | def _truthy(value): |
| 38 | return str(value or "").strip().lower() in ("true", "1", "yes", "on") |
| 39 | |
| 40 | |
| 41 | def _int(value): |
| 42 | try: |
| 43 | return int(str(value or "0").strip() or 0) |
| 44 | except (TypeError, ValueError): |
| 45 | return 0 |
| 46 | |
| 47 | |
| 48 | def _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 | |
| 58 | def 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 |