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.
object_expense_rules.py · 16.3 KB · 373 lines
| 1 | """Expense substantiation, mileage and fringe-benefit arithmetic -- pure. |
| 2 | |
| 3 | No I/O, no clock, no data directory (AGENTS.md "pure logic at the root"): |
| 4 | the package objects in app-finance read the rows and call these, so the |
| 5 | early answer a hook gives and the locked answer a check gives are the same |
| 6 | function and cannot drift (docs/validation-and-logic.md, "Locked checks"). |
| 7 | |
| 8 | What this encodes, and what it deliberately does not: |
| 9 | |
| 10 | - **Rates and thresholds are data.** Nothing here knows that a client meal |
| 11 | is 50% deductible, that receipts start at $75, or what the IRS mileage |
| 12 | rate was in any year. Those live in `expense_categories` and |
| 13 | `mileage_rates`, rows an operator maintains with the source beside the |
| 14 | number. A constant here would be wrong the year it changes and silent |
| 15 | about being wrong. |
| 16 | - **Stamped, never re-derived.** The requirements and deductible share an |
| 17 | expense was judged by are copied onto it (docs/logic-decisions.md #1), so |
| 18 | editing a category next year restates nothing that was approved this |
| 19 | year. `category_stamps` is the one function that computes them, and the |
| 20 | check refuses a stamp that disagrees with it at the moment it matters. |
| 21 | - **Integer money, rounded half-up once** (#10). A deductible share is |
| 22 | `amount * bps / 10000`; a mileage reimbursement is `miles * rate / 100` |
| 23 | with the rate in hundredths of a cent. No float touches either. |
| 24 | - **Not tax advice.** The report says what the operator's categories said; |
| 25 | whether that is what the law says is a question for an accountant. |
| 26 | """ |
| 27 | |
| 28 | from __future__ import annotations |
| 29 | |
| 30 | import csv |
| 31 | import io |
| 32 | from typing import Any, Iterable, Mapping |
| 33 | |
| 34 | BPS_WHOLE = 10_000 |
| 35 | STAMP_FIELDS = ("receipt_required", "purpose_required", "attendees_required", |
| 36 | "deductible_bps", "deductible_cents") |
| 37 | ON_THE_BOOKS = ("approved", "billed") |
| 38 | PERIODS = ("month", "quarter", "year") |
| 39 | |
| 40 | |
| 41 | def text(value: Any) -> str: |
| 42 | return str(value if value is not None else "").strip() |
| 43 | |
| 44 | |
| 45 | def truthy(value: Any) -> bool: |
| 46 | return text(value).lower() in ("true", "1", "yes", "on") |
| 47 | |
| 48 | |
| 49 | def whole(value: Any, *, field: str = "value") -> int: |
| 50 | """A stored integer cell as an int. Raises ValueError on anything else: |
| 51 | a rule that cannot read its input must not guess it (fail closed).""" |
| 52 | cell = text(value) |
| 53 | if not cell or not cell.lstrip("-").isdigit(): |
| 54 | raise ValueError(f"{field} is not a whole number: {cell!r}") |
| 55 | return int(cell) |
| 56 | |
| 57 | |
| 58 | def optional_whole(value: Any, *, field: str = "value") -> int | None: |
| 59 | return None if text(value) == "" else whole(value, field=field) |
| 60 | |
| 61 | |
| 62 | def half_up(numerator: int, denominator: int) -> int: |
| 63 | """numerator / denominator rounded half-up, for non-negative numerators.""" |
| 64 | if denominator <= 0: |
| 65 | raise ValueError("denominator must be positive") |
| 66 | if numerator < 0: |
| 67 | raise ValueError("a share of a negative amount is not defined here") |
| 68 | return (numerator + denominator // 2) // denominator |
| 69 | |
| 70 | |
| 71 | def bps_share(amount_cents: int, bps: int) -> int: |
| 72 | """The `bps` basis-point share of an amount, half-up, once. 5000 is half.""" |
| 73 | if not 0 <= bps <= BPS_WHOLE: |
| 74 | raise ValueError(f"basis points must be 0..{BPS_WHOLE}, got {bps}") |
| 75 | return half_up(amount_cents * bps, BPS_WHOLE) |
| 76 | |
| 77 | |
| 78 | # --- expenses ----------------------------------------------------------------- |
| 79 | |
| 80 | def blank_stamps() -> dict[str, str]: |
| 81 | """What an expense with no category carries: nothing claimed.""" |
| 82 | return {name: "" for name in STAMP_FIELDS} |
| 83 | |
| 84 | |
| 85 | def receipt_required(category: Mapping[str, Any], amount_cents: int) -> bool: |
| 86 | """`receipt_required_over_cents` blank: never; otherwise strictly over it. |
| 87 | |
| 88 | "Over" is literal: a threshold of 7499 requires a receipt from $75.00. |
| 89 | 0 requires one for every positive amount.""" |
| 90 | threshold = optional_whole(category.get("receipt_required_over_cents"), |
| 91 | field="receipt_required_over_cents") |
| 92 | return threshold is not None and amount_cents > threshold |
| 93 | |
| 94 | |
| 95 | def category_stamps(category: Mapping[str, Any], amount_cents: Any) -> dict[str, str]: |
| 96 | """The stamps an expense of this amount in this category carries, as the |
| 97 | strings the record layer stores. Raises ValueError when the category's |
| 98 | own numbers cannot be read -- a check then refuses rather than stamps.""" |
| 99 | amount = whole(amount_cents, field="amount_cents") |
| 100 | bps = whole(category.get("deductible_bps"), field="deductible_bps") |
| 101 | deductible = bps_share(amount, bps) |
| 102 | return { |
| 103 | "receipt_required": "true" if receipt_required(category, amount) else "false", |
| 104 | "purpose_required": "true" if truthy(category.get("requires_business_purpose")) else "false", |
| 105 | "attendees_required": "true" if truthy(category.get("requires_attendees")) else "false", |
| 106 | "deductible_bps": str(bps), |
| 107 | "deductible_cents": str(deductible), |
| 108 | } |
| 109 | |
| 110 | |
| 111 | def stamps_of(record: Mapping[str, Any]) -> dict[str, str]: |
| 112 | return {name: text(record.get(name)) for name in STAMP_FIELDS} |
| 113 | |
| 114 | |
| 115 | def judged_fields() -> tuple[str, ...]: |
| 116 | """The fields whose change makes the stamps a question again.""" |
| 117 | return ("category_id", "amount_cents") + STAMP_FIELDS |
| 118 | |
| 119 | |
| 120 | def stamps_are_judged(record: Mapping[str, Any], existing: Mapping[str, Any] | None) -> bool: |
| 121 | """Whether this write must carry stamps that agree with the category now. |
| 122 | |
| 123 | On a create: always. On an update: when the category, the amount or a |
| 124 | stamp changes, or when the expense moves INTO submitted or approved -- |
| 125 | the two moments the requirements are about. Not when an approved |
| 126 | expense moves on to billed or back to rejected: it was judged when it |
| 127 | was approved, and a category edited since must not block its billing or |
| 128 | its rejection (both would be a later policy restating an earlier act). |
| 129 | """ |
| 130 | if existing is None: |
| 131 | return True |
| 132 | for name in judged_fields(): |
| 133 | if text(record.get(name)) != text(existing.get(name)): |
| 134 | return True |
| 135 | now = text(record.get("status")) or "draft" |
| 136 | was = text(existing.get("status")) or "draft" |
| 137 | return now != was and now in ("submitted", "approved") |
| 138 | |
| 139 | |
| 140 | def stamp_mismatch(record: Mapping[str, Any], category: Mapping[str, Any] | None) -> str: |
| 141 | """"" when the record's stamps are what its category says now, else a |
| 142 | sentence naming the first field that disagrees. `category` None means |
| 143 | the record names none, and then every stamp must be blank.""" |
| 144 | if category is None: |
| 145 | wanted = blank_stamps() |
| 146 | else: |
| 147 | wanted = category_stamps(category, record.get("amount_cents")) |
| 148 | have = stamps_of(record) |
| 149 | for name in STAMP_FIELDS: |
| 150 | if have[name] != wanted[name]: |
| 151 | return (f"{name} is {have[name] or 'blank'!r} but the category says " |
| 152 | f"{wanted[name] or 'blank'!r}") |
| 153 | return "" |
| 154 | |
| 155 | |
| 156 | def substantiation_gaps(expense: Mapping[str, Any]) -> list[str]: |
| 157 | """What an expense on the books lacks to stand up on its own: the |
| 158 | receipt, purpose and attendees its stamps required, an approver, and a |
| 159 | category to say how much of it is deductible. A machine-made expense |
| 160 | (mileage) carries its evidence in the record it was generated from.""" |
| 161 | gaps: list[str] = [] |
| 162 | generated = text(expense.get("generated_from")) |
| 163 | has_receipt = bool(text(expense.get("receipt_scan_id"))) or generated.startswith("mileage_logs/") |
| 164 | if not text(expense.get("category_id")): |
| 165 | gaps.append("category") |
| 166 | if truthy(expense.get("receipt_required")) and not has_receipt: |
| 167 | gaps.append("receipt") |
| 168 | if truthy(expense.get("purpose_required")) and not text(expense.get("business_purpose")): |
| 169 | gaps.append("business_purpose") |
| 170 | if truthy(expense.get("attendees_required")) and not text(expense.get("attendees")): |
| 171 | gaps.append("attendees") |
| 172 | if not text(expense.get("approved_by")): |
| 173 | gaps.append("approval") |
| 174 | return gaps |
| 175 | |
| 176 | |
| 177 | def period_of(day: str, period: str) -> str: |
| 178 | """'2025-05-17' as '2025-05', '2025-Q2' or '2025'.""" |
| 179 | if period not in PERIODS: |
| 180 | raise ValueError(f"period must be one of {', '.join(PERIODS)}") |
| 181 | day = text(day) |
| 182 | if len(day) < 10 or day[4] != "-" or day[7] != "-": |
| 183 | raise ValueError(f"not a date: {day!r}") |
| 184 | if period == "year": |
| 185 | return day[:4] |
| 186 | if period == "month": |
| 187 | return day[:7] |
| 188 | return f"{day[:4]}-Q{(int(day[5:7]) - 1) // 3 + 1}" |
| 189 | |
| 190 | |
| 191 | def _bucket() -> dict[str, int]: |
| 192 | return {"count": 0, "amount_cents": 0, "deductible_cents": 0, |
| 193 | "nondeductible_cents": 0, "unclassified_cents": 0} |
| 194 | |
| 195 | |
| 196 | def _add(bucket: dict[str, int], amount: int, deductible: int | None) -> None: |
| 197 | bucket["count"] += 1 |
| 198 | bucket["amount_cents"] += amount |
| 199 | if deductible is None: |
| 200 | bucket["unclassified_cents"] += amount |
| 201 | else: |
| 202 | bucket["deductible_cents"] += deductible |
| 203 | bucket["nondeductible_cents"] += amount - deductible |
| 204 | |
| 205 | |
| 206 | def deduction_report(expenses: Iterable[Mapping[str, Any]], |
| 207 | categories: Mapping[str, Mapping[str, Any]], |
| 208 | *, period: str = "month", start: str = "", end: str = "") -> dict[str, Any]: |
| 209 | """Deductible and non-deductible totals per period and category. |
| 210 | |
| 211 | Only expenses on the books (approved, billed) inside [start, end] by |
| 212 | `incurred_on`. The deductible share is the STAMP -- what the category |
| 213 | said when the expense was approved -- never the category's number |
| 214 | today. An expense with no category (or no stamp) is `unclassified`: its |
| 215 | amount is reported, its deductibility is not guessed. Every row's |
| 216 | deductible + non-deductible + unclassified equals its amount. |
| 217 | """ |
| 218 | if period not in PERIODS: |
| 219 | raise ValueError(f"period must be one of {', '.join(PERIODS)}") |
| 220 | cells: dict[tuple[str, str], dict[str, int]] = {} |
| 221 | by_category: dict[str, dict[str, int]] = {} |
| 222 | by_period: dict[str, dict[str, int]] = {} |
| 223 | totals = _bucket() |
| 224 | gaps = [] |
| 225 | for expense in expenses: |
| 226 | if text(expense.get("status")) not in ON_THE_BOOKS: |
| 227 | continue |
| 228 | day = text(expense.get("incurred_on")) |
| 229 | if (start and day < start) or (end and day > end): |
| 230 | continue |
| 231 | amount = whole(expense.get("amount_cents"), field="amount_cents") |
| 232 | category_id = text(expense.get("category_id")) |
| 233 | stamped = text(expense.get("deductible_cents")) |
| 234 | deductible = int(stamped) if category_id and stamped.isdigit() else None |
| 235 | key = (period_of(day, period), category_id) |
| 236 | for bucket in (cells.setdefault(key, _bucket()), |
| 237 | by_category.setdefault(category_id, _bucket()), |
| 238 | by_period.setdefault(key[0], _bucket()), |
| 239 | totals): |
| 240 | _add(bucket, amount, deductible) |
| 241 | missing = substantiation_gaps(expense) |
| 242 | if missing: |
| 243 | gaps.append({"expense_id": text(expense.get("id")), "incurred_on": day, |
| 244 | "amount_cents": amount, "missing": missing}) |
| 245 | |
| 246 | def name(category_id: str) -> str: |
| 247 | if not category_id: |
| 248 | return "(no category)" |
| 249 | return text((categories.get(category_id) or {}).get("name")) or category_id |
| 250 | |
| 251 | rows = [{"period": p, "category_id": c, "category": name(c), **cells[(p, c)]} |
| 252 | for p, c in sorted(cells)] |
| 253 | return { |
| 254 | "period": period, "from": start, "to": end, |
| 255 | "rows": rows, |
| 256 | "by_category": [{"category_id": c, "category": name(c), **by_category[c]} |
| 257 | for c in sorted(by_category)], |
| 258 | "by_period": [{"period": p, **by_period[p]} for p in sorted(by_period)], |
| 259 | "totals": totals, |
| 260 | "gaps": sorted(gaps, key=lambda g: (g["incurred_on"], g["expense_id"])), |
| 261 | } |
| 262 | |
| 263 | |
| 264 | REPORT_CSV_COLUMNS = ("period", "category_id", "category", "count", "amount_cents", |
| 265 | "deductible_cents", "nondeductible_cents", "unclassified_cents") |
| 266 | |
| 267 | |
| 268 | def report_csv(report: Mapping[str, Any]) -> str: |
| 269 | out = io.StringIO() |
| 270 | writer = csv.writer(out, lineterminator="\n") |
| 271 | writer.writerow(REPORT_CSV_COLUMNS) |
| 272 | for row in report.get("rows", []): |
| 273 | writer.writerow([_csv_safe(row.get(column, "")) if isinstance(row.get(column), str) |
| 274 | else row.get(column, "") for column in REPORT_CSV_COLUMNS]) |
| 275 | return out.getvalue() |
| 276 | |
| 277 | |
| 278 | # --- mileage ------------------------------------------------------------------ |
| 279 | |
| 280 | def odometer_miles(start: Any, end: Any) -> int | None: |
| 281 | """end - start, or None when neither reading was given. Raises ValueError |
| 282 | when only one was, or when end is not past start: a trip that ends |
| 283 | before it began is a typo, and a zero-mile trip reimburses nothing.""" |
| 284 | first = optional_whole(start, field="start_odometer") |
| 285 | last = optional_whole(end, field="end_odometer") |
| 286 | if first is None and last is None: |
| 287 | return None |
| 288 | if first is None or last is None: |
| 289 | raise ValueError("give both odometer readings, or neither and the miles") |
| 290 | if first < 0: |
| 291 | raise ValueError("an odometer reading is not negative") |
| 292 | if last <= first: |
| 293 | raise ValueError(f"the end reading ({last}) must be greater than the start ({first})") |
| 294 | return last - first |
| 295 | |
| 296 | |
| 297 | def overlapping_log(log: Mapping[str, Any], others: Iterable[Mapping[str, Any]]) -> Mapping[str, Any] | None: |
| 298 | """The first other live log on the same vehicle whose odometer range |
| 299 | overlaps this one's, or None. Ranges are half-open: a trip may start at |
| 300 | the reading the last one ended on. Rejected logs and logs without both |
| 301 | readings occupy no range.""" |
| 302 | if odometer_miles(log.get("start_odometer"), log.get("end_odometer")) is None: |
| 303 | return None |
| 304 | start = whole(log.get("start_odometer")) |
| 305 | end = whole(log.get("end_odometer")) |
| 306 | vehicle = text(log.get("vehicle_id")) |
| 307 | for other in others: |
| 308 | if text(other.get("id")) == text(log.get("id")): |
| 309 | continue |
| 310 | if text(other.get("vehicle_id")) != vehicle or text(other.get("status")) == "rejected": |
| 311 | continue |
| 312 | try: |
| 313 | if odometer_miles(other.get("start_odometer"), other.get("end_odometer")) is None: |
| 314 | continue |
| 315 | except ValueError: |
| 316 | continue |
| 317 | o_start, o_end = whole(other.get("start_odometer")), whole(other.get("end_odometer")) |
| 318 | if start < o_end and o_start < end: |
| 319 | return other |
| 320 | return None |
| 321 | |
| 322 | |
| 323 | def mileage_reimbursement(miles: int, rate_hundredths: int) -> int: |
| 324 | """Cents owed for `miles` at a rate in hundredths of a cent per mile |
| 325 | (7000 is 70 cents a mile; 6550 is 65.5), half-up once.""" |
| 326 | if miles < 0 or rate_hundredths < 0: |
| 327 | raise ValueError("miles and rate are not negative") |
| 328 | return half_up(miles * rate_hundredths, 100) |
| 329 | |
| 330 | |
| 331 | def rate_for_year(rates: Iterable[Mapping[str, Any]], year: str) -> Mapping[str, Any] | None: |
| 332 | """The operator's business-mileage rate row for a calendar year.""" |
| 333 | matches = [row for row in rates if text(row.get("year")) == text(year)] |
| 334 | if len(matches) > 1: |
| 335 | raise ValueError(f"more than one mileage rate for {year}") |
| 336 | return matches[0] if matches else None |
| 337 | |
| 338 | |
| 339 | # --- fringe benefits ---------------------------------------------------------- |
| 340 | |
| 341 | FRINGE_EXPORT_COLUMNS = ("id", "employee_id", "employee_name", "benefit_type", |
| 342 | "period_start", "period_end", "value_cents", "taxable", |
| 343 | "valuation_method", "source", "notes") |
| 344 | |
| 345 | |
| 346 | def fringe_export_rows(rows: Iterable[Mapping[str, Any]], *, start: str = "", end: str = "") -> list[dict[str, str]]: |
| 347 | """The register rows whose period overlaps [start, end], in a stable |
| 348 | order, with exactly the export columns. Values are handed over as |
| 349 | recorded; nothing is computed (the payroll provider withholds).""" |
| 350 | picked = [] |
| 351 | for row in rows: |
| 352 | p_start, p_end = text(row.get("period_start")), text(row.get("period_end")) |
| 353 | if end and p_start and p_start > end: |
| 354 | continue |
| 355 | if start and p_end and p_end < start: |
| 356 | continue |
| 357 | picked.append({column: text(row.get(column)) for column in FRINGE_EXPORT_COLUMNS}) |
| 358 | return sorted(picked, key=lambda r: (r["employee_id"], r["period_start"], r["benefit_type"], r["id"])) |
| 359 | |
| 360 | |
| 361 | def fringe_csv(rows: Iterable[Mapping[str, str]]) -> str: |
| 362 | out = io.StringIO() |
| 363 | writer = csv.writer(out, lineterminator="\n") |
| 364 | writer.writerow(FRINGE_EXPORT_COLUMNS) |
| 365 | for row in rows: |
| 366 | writer.writerow([_csv_safe(row.get(column, "")) for column in FRINGE_EXPORT_COLUMNS]) |
| 367 | return out.getvalue() |
| 368 | |
| 369 | |
| 370 | def _csv_safe(value: str) -> str: |
| 371 | """A cell a spreadsheet would run as a formula is prefixed with a quote |
| 372 | (the CSV-injection guard): the export is opened by payroll staff.""" |
| 373 | return "'" + value if value[:1] in ("=", "+", "-", "@", "\t", "\r") else value |