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.
mileage_expenses.py · 6.9 KB · 161 lines
| 1 | """system_mileage_expenses -- HANDLES mileage_logs writes; owes the driver. |
| 2 | |
| 3 | An approved trip in a PERSONAL vehicle becomes one expense: |
| 4 | |
| 5 | amount the reimbursement stamped on the log at approval |
| 6 | paid_by personal (the business owes the driver; system_expense_books |
| 7 | credits the reimbursable liability when it books it) |
| 8 | category the mileage category (setting expenses.mileage_category_id, |
| 9 | default the seeded expcat_mileage), stamped as the hook would |
| 10 | status approved, approved_by/at copied from the log: the log WAS |
| 11 | the approval, by somebody other than the driver, and a |
| 12 | second approval of the same miles would be a ritual |
| 13 | generated_from mileage_logs/{id}, unique on expenses -- so a replayed |
| 14 | event, or the HTTP dispatch and the change-log replay both |
| 15 | delivering it, books nothing twice (docs/logic-decisions.md #7) |
| 16 | |
| 17 | A trip in a BUSINESS vehicle reimburses nothing (the business already pays |
| 18 | its costs) and creates nothing. Rejecting an approved log rejects the |
| 19 | expense it created, so the books reverse; an expense already billed is left |
| 20 | and the answer says so (mileage is created unbillable, so that is a hand |
| 21 | edit somebody made). |
| 22 | |
| 23 | Why a reaction and not part of the approval (#6): the approval is a gate |
| 24 | on the log; creating the expense is a consequence of the gate passing. A |
| 25 | category that is not configured must not stop a manager approving a trip |
| 26 | -- it skips with the reason, and the log stands. |
| 27 | |
| 28 | The expense this writes is a storage-level write, so the HTTP dispatcher |
| 29 | never sees it; its journal is posted by system_expense_books when the |
| 30 | change-log replay (DBBASIC_ENABLE_CHANGE_DISPATCH) delivers the expense's |
| 31 | own `created` event -- the dispatch docs/logic-decisions.md #9 says the |
| 32 | third storage-level writer must use instead of composing the journal |
| 33 | itself. Both are idempotent by their markers. |
| 34 | """ |
| 35 | |
| 36 | import os |
| 37 | |
| 38 | import object_collections |
| 39 | import object_expense_rules as rules |
| 40 | import object_ids |
| 41 | import object_records |
| 42 | |
| 43 | HANDLES = [ |
| 44 | "mileage_logs.record.created", |
| 45 | "mileage_logs.record.updated", |
| 46 | ] |
| 47 | |
| 48 | ACTOR = "system_mileage_expenses" |
| 49 | DEFAULT_CATEGORY = "expcat_mileage" |
| 50 | |
| 51 | |
| 52 | def _base_dir(): |
| 53 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 54 | |
| 55 | |
| 56 | def _setting(base, key, default=""): |
| 57 | try: |
| 58 | rows = object_records.read_collection_records_where("app_settings", "key", key, base_dir=base) |
| 59 | except object_collections.CollectionNotFoundError: |
| 60 | return default |
| 61 | for row in rows: |
| 62 | if rules.text(row.get("value")): |
| 63 | return rules.text(row.get("value")) |
| 64 | return default |
| 65 | |
| 66 | |
| 67 | def _log_for(request, base): |
| 68 | record_id = rules.text(request.get("record_id") or request.get("id") |
| 69 | or (request.get("record") or {}).get("id")) |
| 70 | if not record_id: |
| 71 | return None |
| 72 | try: |
| 73 | return object_records.get_collection_record("mileage_logs", record_id, base_dir=base) |
| 74 | except object_records.RecordNotFoundError: |
| 75 | return None |
| 76 | |
| 77 | |
| 78 | def _generated(base, marker): |
| 79 | rows = object_records.read_collection_records_where("expenses", "generated_from", marker, base_dir=base) |
| 80 | return rows[0] if rows else None |
| 81 | |
| 82 | |
| 83 | def _reject(base, marker): |
| 84 | expense = _generated(base, marker) |
| 85 | if expense is None: |
| 86 | return {"ok": True, "skipped": "no expense was created for this trip"} |
| 87 | status = rules.text(expense.get("status")) |
| 88 | if status == "rejected": |
| 89 | return {"ok": True, "skipped": "its expense is already rejected", "expense_id": expense["id"]} |
| 90 | if status != "approved": |
| 91 | return {"ok": False, "error": (f"The trip was rejected but its expense {expense['id']} is " |
| 92 | f"{status}; correct it by hand.")} |
| 93 | object_records.update_collection_record( |
| 94 | "expenses", expense["id"], {"status": "rejected", |
| 95 | "notes": (rules.text(expense.get("notes")) + |
| 96 | " Rejected with its mileage log.").strip()}, |
| 97 | base_dir=base, actor=ACTOR) |
| 98 | return {"ok": True, "rejected": expense["id"]} |
| 99 | |
| 100 | |
| 101 | def EVENT(request): |
| 102 | base = _base_dir() |
| 103 | log = _log_for(request, base) |
| 104 | if not log: |
| 105 | return {"ok": True, "skipped": "no mileage log in the event"} |
| 106 | marker = f"mileage_logs/{log['id']}" |
| 107 | status = rules.text(log.get("status")) |
| 108 | if status == "rejected": |
| 109 | return _reject(base, marker) |
| 110 | if status != "approved": |
| 111 | return {"ok": True, "skipped": "not approved"} |
| 112 | |
| 113 | owed = rules.whole(log.get("reimbursement_cents"), field="reimbursement_cents") |
| 114 | if owed <= 0: |
| 115 | return {"ok": True, "skipped": "nothing to reimburse (a business vehicle, or zero miles)"} |
| 116 | already = _generated(base, marker) |
| 117 | if already is not None: |
| 118 | return {"ok": True, "skipped": "already created", "expense_id": already["id"]} |
| 119 | |
| 120 | category_id = _setting(base, "expenses.mileage_category_id", DEFAULT_CATEGORY) |
| 121 | try: |
| 122 | category = object_records.get_collection_record("expense_categories", category_id, base_dir=base) |
| 123 | except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError): |
| 124 | return {"ok": True, "skipped": f"mileage category {category_id} not found", |
| 125 | "needs": ["expenses.mileage_category_id"]} |
| 126 | |
| 127 | rate = rules.text(log.get("rate_hundredths_cent")) |
| 128 | cents_per_mile = f"{int(rate) // 100}.{int(rate) % 100:02d}" if rate.isdigit() else rate |
| 129 | expense = { |
| 130 | "id": object_ids.new_uuid4(), |
| 131 | "description": (f"Mileage {rules.text(log.get('trip_date'))}: {rules.text(log.get('from_place'))} " |
| 132 | f"to {rules.text(log.get('to_place'))}, {rules.text(log.get('miles'))} mi " |
| 133 | f"at {cents_per_mile} cents/mi")[:300], |
| 134 | "incurred_on": rules.text(log.get("trip_date")), |
| 135 | "amount_cents": str(owed), |
| 136 | "currency": "USD", |
| 137 | "paid_by": "personal", |
| 138 | "billable": "false", |
| 139 | "markup_bps": "0", |
| 140 | "billable_amount_cents": "0", |
| 141 | "status": "approved", |
| 142 | "approved_by": rules.text(log.get("approved_by")), |
| 143 | "approved_at": rules.text(log.get("approved_at")), |
| 144 | "category_id": category_id, |
| 145 | "business_purpose": rules.text(log.get("business_purpose")), |
| 146 | "location": f"{rules.text(log.get('from_place'))} to {rules.text(log.get('to_place'))}"[:200], |
| 147 | "notes": f"Created from mileage log {log['id']} when it was approved.", |
| 148 | "owner_id": rules.text(log.get("owner_id")), |
| 149 | "generated_from": marker, |
| 150 | **rules.category_stamps(category, str(owed)), |
| 151 | } |
| 152 | try: |
| 153 | object_records.create_collection_record( |
| 154 | "expenses", expense, base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 155 | except object_records.UniqueConstraintError as exc: |
| 156 | return {"ok": True, "skipped": "already created", "expense_id": exc.existing_id} |
| 157 | return {"ok": True, "expense_id": expense["id"], "amount_cents": owed} |
| 158 | |
| 159 | |
| 160 | # The change dispatcher calls EVENT; POST lets an operator poke it by hand. |
| 161 | POST = EVENT |