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.
generate_tm_invoice.py · 20.0 KB · 484 lines
| 1 | """action_generate_tm_invoice -- approved hours and costs become one invoice. |
| 2 | |
| 3 | POST {project_id?, customer_name?, through_date?, grouping?, dry_run?} |
| 4 | |
| 5 | The last mile of time-and-materials billing -- both halves of it, since |
| 6 | the materials are half the name. Deliberately the same shape as the |
| 7 | period biller: collect what is owed, raise ONE invoice, mark the sources |
| 8 | so a re-run raises nothing. Everything downstream is the machinery that |
| 9 | already ships -- totals rollup, portal link, send, aging, dunning, |
| 10 | payment, books. |
| 11 | |
| 12 | Time and expenses land on the SAME invoice rather than two, because a |
| 13 | client engaged one firm for one project and should receive one bill for |
| 14 | it. Expenses bill at their stamped billable amount (cost plus whatever |
| 15 | markup was approved), and the line says so when there is a markup: a |
| 16 | pass-through cost quietly grossed up is the thing clients discover later |
| 17 | and remember. |
| 18 | |
| 19 | Idempotency lives on the entries rather than in a dedup table. An entry |
| 20 | that already carries an invoice_id is never billed again, which means a |
| 21 | generator that crashed halfway through can simply be run again: the |
| 22 | entries it already stamped are skipped, the rest are picked up. Double |
| 23 | billing a client for the same hours is the failure a consultancy does not |
| 24 | get to explain twice. |
| 25 | |
| 26 | Claims, not just stamps (2026-11-28). The stamp alone is checked only by |
| 27 | a run that starts after another finished. Two runs that overlapped both |
| 28 | read the same approved hours as unbilled and billed them on two invoices |
| 29 | (bug-reports/2026-11-28-06-14-52-CST-tm-invoice-concurrent-double-billing), |
| 30 | and two runs for one project and cut-off date produced two invoices with |
| 31 | the same number (bug-reports/2026-11-28-06-14-51-CST-tm-invoice-duplicate- |
| 32 | numbers). So a run now: |
| 33 | |
| 34 | 1. writes the invoice header first, as a draft with a zero total. The |
| 35 | header carries `number_key`, which invoices.json declares unique, so |
| 36 | the header write IS the number claim: a taken number (another run's, or |
| 37 | one already on any invoice) moves on to the next suffix, -2, -3, ... |
| 38 | 2. claims each entry and expense with a compare-and-set |
| 39 | (expected_rev = the row it read): status billed + this invoice's id. |
| 40 | An entry another run claimed first fails the compare and is left to |
| 41 | that run's invoice. |
| 42 | 3. writes lines for exactly what it claimed, then the totals. A run that |
| 43 | claimed nothing deletes its empty header (which frees the number). |
| 44 | |
| 45 | A run that dies between 2 and 3 leaves a DRAFT invoice whose notes say it |
| 46 | is incomplete, with the claimed entries pointing at it -- visible, never |
| 47 | sent on its own, and never billed twice. The old order (invoice, lines, |
| 48 | then stamps) could instead die after a line and before its stamp, and the |
| 49 | re-run billed that line again. |
| 50 | |
| 51 | What it will not do: rate anything. Rates were stamped at approval, back |
| 52 | when a human looked at the hours; re-deriving them here would let a rate |
| 53 | card edited last week silently reprice work approved last month. This |
| 54 | object only adds up numbers other people already agreed to. |
| 55 | """ |
| 56 | |
| 57 | import os |
| 58 | from datetime import date, timedelta |
| 59 | |
| 60 | import object_access |
| 61 | import object_collections |
| 62 | import object_ids |
| 63 | import object_rates |
| 64 | import object_records |
| 65 | |
| 66 | ACTOR = "action_generate_tm_invoice" |
| 67 | |
| 68 | GROUPINGS = ("detail", "by_person", "by_task") |
| 69 | |
| 70 | |
| 71 | def _base_dir(): |
| 72 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 73 | |
| 74 | |
| 75 | def _setting(base, key, default): |
| 76 | try: |
| 77 | # access: role-only object (execute grant role:manager) |
| 78 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 79 | if row.get("key") == key and str(row.get("value") or "").strip(): |
| 80 | return row["value"].strip() |
| 81 | except Exception: |
| 82 | pass |
| 83 | return default |
| 84 | |
| 85 | |
| 86 | def _int(value, default=0): |
| 87 | try: |
| 88 | return int(str(value or "").strip() or default) |
| 89 | except (TypeError, ValueError): |
| 90 | return default |
| 91 | |
| 92 | |
| 93 | def _truthy(value): |
| 94 | return str(value or "").strip().lower() in ("true", "1", "yes", "on") |
| 95 | |
| 96 | |
| 97 | def _text(value): |
| 98 | return str(value if value is not None else "").strip() |
| 99 | |
| 100 | |
| 101 | def _billable_entries(base, project_id, through): |
| 102 | """Approved, unbilled hours for this project up to a date. |
| 103 | |
| 104 | An entry with an invoice_id is skipped no matter what its status says: |
| 105 | the stamp is the fact, and trusting status alone would re-bill an |
| 106 | entry somebody had hand-edited. |
| 107 | """ |
| 108 | try: |
| 109 | # access: role-only object (execute grant role:manager) |
| 110 | rows = object_records.read_collection_records("time_logs", base_dir=base) |
| 111 | except object_collections.CollectionNotFoundError: |
| 112 | return None |
| 113 | except Exception as exc: |
| 114 | raise Unreadable(f"time_logs: {str(exc)[:160]}") from exc |
| 115 | out = [] |
| 116 | for row in rows: |
| 117 | if _text(row.get("status")) != "approved": |
| 118 | continue |
| 119 | if _text(row.get("invoice_id")): |
| 120 | continue |
| 121 | if project_id and _text(row.get("project_id")) != project_id: |
| 122 | continue |
| 123 | worked = _text(row.get("started_at"))[:10] |
| 124 | if through and worked and worked > through: |
| 125 | continue |
| 126 | if _int(row.get("amount_cents")) <= 0: |
| 127 | continue |
| 128 | out.append(row) |
| 129 | return out |
| 130 | |
| 131 | |
| 132 | class Unreadable(Exception): |
| 133 | """What is billable could not be read: an unknown, not "nothing".""" |
| 134 | |
| 135 | |
| 136 | def _billable_expenses(base, project_id, through): |
| 137 | """Approved, unbilled, billable costs for this project up to a date. |
| 138 | |
| 139 | Unbillable expenses are skipped here and only here: they still posted |
| 140 | to the books when they were approved, which is where a cost the |
| 141 | client never sees belongs. |
| 142 | """ |
| 143 | try: |
| 144 | # access: role-only object (execute grant role:manager) |
| 145 | rows = object_records.read_collection_records("expenses", base_dir=base) |
| 146 | except object_collections.CollectionNotFoundError: |
| 147 | return [] |
| 148 | except Exception as exc: |
| 149 | # Read as "no expenses", the invoice went out with the hours alone |
| 150 | # and the costs silently waited for a later one. |
| 151 | raise Unreadable(f"expenses: {str(exc)[:160]}") from exc |
| 152 | out = [] |
| 153 | for row in rows: |
| 154 | if _text(row.get("status")) != "approved": |
| 155 | continue |
| 156 | if _text(row.get("invoice_id")): |
| 157 | continue |
| 158 | if not _truthy(row.get("billable")): |
| 159 | continue |
| 160 | if project_id and _text(row.get("project_id")) != project_id: |
| 161 | continue |
| 162 | incurred = _text(row.get("incurred_on"))[:10] |
| 163 | if through and incurred and incurred > through: |
| 164 | continue |
| 165 | if _int(row.get("billable_amount_cents")) <= 0: |
| 166 | continue |
| 167 | out.append(row) |
| 168 | return out |
| 169 | |
| 170 | |
| 171 | def _expense_description(expense): |
| 172 | incurred = _text(expense.get("incurred_on"))[:10] |
| 173 | what = _text(expense.get("description")) or "Expense" |
| 174 | markup = _int(expense.get("markup_bps")) |
| 175 | if markup <= 0: |
| 176 | return f"{incurred} {what} (at cost)" |
| 177 | return f"{incurred} {what} (cost plus {markup / 100:g}%)" |
| 178 | |
| 179 | |
| 180 | def _group_key(entry, grouping): |
| 181 | if grouping == "by_person": |
| 182 | return _text(entry.get("owner_id")) or "unassigned" |
| 183 | if grouping == "by_task": |
| 184 | return _text(entry.get("task_id")) or "unassigned" |
| 185 | return _text(entry.get("id")) |
| 186 | |
| 187 | |
| 188 | def _describe(entries, grouping, base): |
| 189 | """One line's worth of English. |
| 190 | |
| 191 | A T&M line names the work, the hours and the rate, because the hours |
| 192 | are the whole argument for the number. A client who cannot see what |
| 193 | they are paying for can only dispute the total. |
| 194 | """ |
| 195 | first = entries[0] |
| 196 | seconds = sum(_int(e.get("duration_seconds")) for e in entries) |
| 197 | increment = 0 # already applied per entry at approval |
| 198 | worked_hours = object_rates.hours(seconds, increment) |
| 199 | rates = {_int(e.get("hourly_rate_cents")) for e in entries} |
| 200 | rate_note = (f" at {rates.pop() / 100:.2f}/hr" if len(rates) == 1 else |
| 201 | " at mixed rates") |
| 202 | |
| 203 | if grouping == "by_person": |
| 204 | who = _text(first.get("owner_id")) or "Unassigned" |
| 205 | return f"{who}: {worked_hours} hours{rate_note}" |
| 206 | if grouping == "by_task": |
| 207 | task = _text(first.get("task_id")) or "Unassigned" |
| 208 | title = _lookup(base, "tasks", task, "title") or task or "Work" |
| 209 | return f"{title}: {worked_hours} hours{rate_note}" |
| 210 | notes = _text(first.get("notes")) |
| 211 | worked_on = _text(first.get("started_at"))[:10] |
| 212 | label = notes or _lookup(base, "tasks", _text(first.get("task_id")), "title") or "Work" |
| 213 | return f"{worked_on} {label}: {worked_hours} hours{rate_note}" |
| 214 | |
| 215 | |
| 216 | def _lookup(base, collection, record_id, field): |
| 217 | if not record_id: |
| 218 | return "" |
| 219 | try: |
| 220 | # access: role-only object (execute grant role:manager) |
| 221 | row = object_records.get_collection_record(collection, record_id, base_dir=base) |
| 222 | except Exception: |
| 223 | return "" |
| 224 | return _text((row or {}).get(field)) |
| 225 | |
| 226 | |
| 227 | def _owner(request, base): |
| 228 | """Whose invoice this is: (owner, refusal). None for an in-process |
| 229 | call, which names its owner itself (or takes the first entry's). |
| 230 | |
| 231 | Over HTTP the server sets `_identity` (a client cannot), and the |
| 232 | invoice is the caller's, the rule the record API applies to a create: |
| 233 | an `owner_id` in the body naming somebody else is refused unless the |
| 234 | caller is an admin. It used to win outright, and with no owner_id the |
| 235 | first billed entry's owner (the person who logged the hours) owned the |
| 236 | client's invoice and its lines, so a manager's run handed somebody else |
| 237 | an invoice their own-rows grant lets them update. |
| 238 | """ |
| 239 | asked = _text(request.get("owner_id")) |
| 240 | if "_identity" not in request: |
| 241 | return None, None |
| 242 | identity = request.get("_identity") or {} |
| 243 | caller = _text(identity.get("user_id")) |
| 244 | if not asked or asked == caller: |
| 245 | return caller, None |
| 246 | access = object_access.Access(identity, base_dir=base) |
| 247 | if identity.get("auth_method") == "admin_token" or access.is_admin: |
| 248 | return asked, None |
| 249 | return "", {"status": 403, "code": "forbidden", "field": "owner_id", |
| 250 | "error": ("owner_id names another user. An invoice you raise is " |
| 251 | "yours: leave owner_id out (or send your own id). " |
| 252 | "Nothing was billed.")} |
| 253 | |
| 254 | |
| 255 | def POST(request): |
| 256 | base = _base_dir() |
| 257 | owner, refusal = _owner(request, base) |
| 258 | if refusal: |
| 259 | return refusal |
| 260 | # invoices.customer_id declares relation.requires read: the record API |
| 261 | # lets a caller name only a contact they may read. Asked before |
| 262 | # anything is read or written; a hidden contact and a missing one get |
| 263 | # its one 400. |
| 264 | refusal = object_access.Access(request.get("_identity"), base_dir=base).relation_refusal( |
| 265 | "invoices", {"customer_id": _text(request.get("customer_id"))}) |
| 266 | if refusal: |
| 267 | status, answer = refusal |
| 268 | return {**answer, "status": status} |
| 269 | project_id = _text(request.get("project_id")) |
| 270 | through = _text(request.get("through_date"))[:10] or date.today().isoformat() |
| 271 | dry_run = _truthy(request.get("dry_run")) |
| 272 | grouping = _text(request.get("grouping")) or _setting( |
| 273 | base, "billing.tm_line_grouping", "detail") |
| 274 | if grouping not in GROUPINGS: |
| 275 | return {"status": 400, |
| 276 | "error": f"grouping must be one of {', '.join(GROUPINGS)}"} |
| 277 | |
| 278 | try: |
| 279 | entries = _billable_entries(base, project_id, through) |
| 280 | if entries is None: |
| 281 | return {"ok": True, "skipped": "time tracking not installed (time_logs absent)"} |
| 282 | expenses = _billable_expenses(base, project_id, through) |
| 283 | except Unreadable as exc: |
| 284 | return {"status": 503, |
| 285 | "error": (f"What is billable could not be read ({exc}), so no " |
| 286 | f"invoice was raised: one raised now could leave out " |
| 287 | f"work or costs the client owes. Try again once it " |
| 288 | f"is readable.")} |
| 289 | if not entries and not expenses: |
| 290 | return {"ok": True, "invoiced": 0, |
| 291 | "note": "no approved, unbilled time or expenses in range"} |
| 292 | |
| 293 | buckets = {} |
| 294 | for entry in entries: |
| 295 | buckets.setdefault(_group_key(entry, grouping), []).append(entry) |
| 296 | |
| 297 | time_cents = sum(_int(e.get("amount_cents")) for e in entries) |
| 298 | expense_cents = sum(_int(e.get("billable_amount_cents")) for e in expenses) |
| 299 | total_cents = time_cents + expense_cents |
| 300 | if dry_run: |
| 301 | return {"ok": True, "would_invoice": len(entries) + len(expenses), |
| 302 | "time_entries": len(entries), "expenses": len(expenses), |
| 303 | "lines": len(buckets) + len(expenses), |
| 304 | "time_cents": time_cents, "expense_cents": expense_cents, |
| 305 | "total_cents": total_cents, "through_date": through, |
| 306 | "grouping": grouping} |
| 307 | |
| 308 | customer_name = (_text(request.get("customer_name")) |
| 309 | or _lookup(base, "projects", project_id, "name") |
| 310 | or "Customer") |
| 311 | due_days = _int(_setting(base, "billing.invoice_due_days", "14"), 14) |
| 312 | invoice_id = object_ids.new_uuid4() |
| 313 | if owner is None: |
| 314 | owner = (_text(request.get("owner_id")) |
| 315 | or _text((entries or expenses)[0].get("owner_id"))) |
| 316 | marker = f"time_logs:{project_id or 'all'}:{through}" |
| 317 | |
| 318 | header = { |
| 319 | "id": invoice_id, |
| 320 | "customer_id": _text(request.get("customer_id")), |
| 321 | "customer_name": customer_name, |
| 322 | "customer_email": _text(request.get("customer_email")), |
| 323 | "status": "draft", |
| 324 | "issue_date": through, |
| 325 | "due_date": (date.fromisoformat(through) |
| 326 | + timedelta(days=due_days)).isoformat(), |
| 327 | "subtotal_cents": "0", |
| 328 | "total_cents": "0", |
| 329 | "notes": (f"Generated by {ACTOR} [{marker}] -- INCOMPLETE: the run " |
| 330 | "that raised this draft did not finish; check its lines " |
| 331 | "against the time entries that point at it"), |
| 332 | "owner_id": owner, |
| 333 | } |
| 334 | number = _claim_number(base, header, f"TM-{(project_id or 'ALL')[:8]}-{through}") |
| 335 | if number is None: |
| 336 | return {"status": 409, |
| 337 | "error": ("Could not find a free invoice number for this run; " |
| 338 | "nothing was billed.")} |
| 339 | |
| 340 | claimed_entries, claim_error = _claim_all(base, "time_logs", entries, invoice_id) |
| 341 | claimed_expenses, expense_error = ( |
| 342 | _claim_all(base, "expenses", expenses, invoice_id) |
| 343 | if claim_error is None else ([], None)) |
| 344 | claim_error = claim_error or expense_error |
| 345 | if not claimed_entries and not claimed_expenses: |
| 346 | try: |
| 347 | # access: role-only object (execute grant role:manager) |
| 348 | object_records.delete_collection_record( |
| 349 | "invoices", invoice_id, base_dir=base, actor=ACTOR) |
| 350 | except Exception: |
| 351 | pass |
| 352 | if claim_error: |
| 353 | return {"status": 409, |
| 354 | "error": f"Could not claim the entries: {claim_error}"} |
| 355 | return {"ok": True, "invoiced": 0, |
| 356 | "note": ("another run billed these entries first; nothing " |
| 357 | "is left to invoice")} |
| 358 | |
| 359 | buckets = {} |
| 360 | for entry in claimed_entries: |
| 361 | buckets.setdefault(_group_key(entry, grouping), []).append(entry) |
| 362 | time_cents = sum(_int(e.get("amount_cents")) for e in claimed_entries) |
| 363 | expense_cents = sum(_int(e.get("billable_amount_cents")) for e in claimed_expenses) |
| 364 | total_cents = time_cents + expense_cents |
| 365 | |
| 366 | lines = 0 |
| 367 | for key in sorted(buckets): |
| 368 | group = buckets[key] |
| 369 | amount = sum(_int(e.get("amount_cents")) for e in group) |
| 370 | seconds = sum(_int(e.get("duration_seconds")) for e in group) |
| 371 | # access: role-only object (execute grant role:manager) |
| 372 | object_records.create_collection_record( |
| 373 | "invoice_lines", |
| 374 | { |
| 375 | "id": object_ids.new_uuid4(), |
| 376 | "invoice_id": invoice_id, |
| 377 | "description": _describe(group, grouping, base), |
| 378 | "quantity": object_rates.hours(seconds), |
| 379 | "unit_price_cents": str(_int(group[0].get("hourly_rate_cents"))), |
| 380 | "line_total_cents": str(amount), |
| 381 | "owner_id": owner, |
| 382 | }, |
| 383 | base_dir=base, actor=ACTOR) |
| 384 | lines += 1 |
| 385 | |
| 386 | # Expenses are never grouped: one receipt, one line. Collapsing them |
| 387 | # would hide exactly what a client wants to see itemised. |
| 388 | for expense in sorted(claimed_expenses, |
| 389 | key=lambda e: (_text(e.get("incurred_on")), |
| 390 | _text(e.get("id")))): |
| 391 | amount = _int(expense.get("billable_amount_cents")) |
| 392 | # access: role-only object (execute grant role:manager) |
| 393 | object_records.create_collection_record( |
| 394 | "invoice_lines", |
| 395 | { |
| 396 | "id": object_ids.new_uuid4(), |
| 397 | "invoice_id": invoice_id, |
| 398 | "description": _expense_description(expense), |
| 399 | "quantity": "1", |
| 400 | "unit_price_cents": str(amount), |
| 401 | "line_total_cents": str(amount), |
| 402 | "owner_id": owner, |
| 403 | }, |
| 404 | base_dir=base, actor=ACTOR) |
| 405 | lines += 1 |
| 406 | |
| 407 | # access: role-only object (execute grant role:manager) |
| 408 | object_records.update_collection_record( |
| 409 | "invoices", invoice_id, |
| 410 | {"subtotal_cents": str(total_cents), "total_cents": str(total_cents), |
| 411 | "notes": f"Generated by {ACTOR} [{marker}]"}, |
| 412 | base_dir=base, actor=ACTOR) |
| 413 | |
| 414 | result = {"ok": True, "invoiced": 1, "invoice_id": invoice_id, |
| 415 | "number": number, |
| 416 | "entries_billed": len(claimed_entries), |
| 417 | "expenses_billed": len(claimed_expenses), |
| 418 | "lines": lines, "time_cents": time_cents, |
| 419 | "expense_cents": expense_cents, |
| 420 | "total_cents": total_cents, "through_date": through, |
| 421 | "grouping": grouping} |
| 422 | skipped = (len(entries) - len(claimed_entries)) + (len(expenses) - len(claimed_expenses)) |
| 423 | if claim_error: |
| 424 | result["warning"] = (f"stopped claiming after an error ({claim_error}); " |
| 425 | "the entries not on this invoice are still unbilled " |
| 426 | "and the next run picks them up") |
| 427 | elif skipped: |
| 428 | result["note"] = (f"{skipped} entr{'y' if skipped == 1 else 'ies'} " |
| 429 | "seen at the start were billed by another run first") |
| 430 | return result |
| 431 | |
| 432 | |
| 433 | MAX_NUMBER_SUFFIX = 99 |
| 434 | |
| 435 | |
| 436 | def _claim_number(base, header, base_number): |
| 437 | """Write the header under the first free number: base, base-2, ... |
| 438 | |
| 439 | The unique key on number_key makes the write itself the claim. A number |
| 440 | already on ANY invoice (a hand-typed one, or one generated before the |
| 441 | key existed) is skipped as well, by reading -- advisory, since typed |
| 442 | numbers are not constrained, but it keeps old duplicates from growing. |
| 443 | Returns the number, or None when every candidate is taken. |
| 444 | """ |
| 445 | try: |
| 446 | # access: role-only object (execute grant role:manager) |
| 447 | taken = {_text(r.get("number")) for r in |
| 448 | object_records.read_collection_records("invoices", base_dir=base)} |
| 449 | except Exception: |
| 450 | taken = set() |
| 451 | for n in range(1, MAX_NUMBER_SUFFIX + 1): |
| 452 | number = base_number if n == 1 else f"{base_number}-{n}" |
| 453 | if number in taken: |
| 454 | continue |
| 455 | try: |
| 456 | # access: role-only object (execute grant role:manager) |
| 457 | object_records.create_collection_record( |
| 458 | "invoices", {**header, "number": number, "number_key": number}, |
| 459 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 460 | except object_records.UniqueConstraintError: |
| 461 | continue |
| 462 | return number |
| 463 | return None |
| 464 | |
| 465 | |
| 466 | def _claim_all(base, collection, rows, invoice_id): |
| 467 | """Compare-and-set each row to billed on this invoice. Returns the rows |
| 468 | this run won, and the first unexpected error (claiming stops there).""" |
| 469 | won = [] |
| 470 | for row in rows: |
| 471 | try: |
| 472 | # access: role-only object (execute grant role:manager) |
| 473 | object_records.update_collection_record( |
| 474 | collection, row["id"], |
| 475 | {"status": "billed", "invoice_id": invoice_id}, |
| 476 | base_dir=base, actor=ACTOR, |
| 477 | expected_rev=object_records.compute_record_rev(row)) |
| 478 | except (object_records.VersionConflictError, |
| 479 | object_records.RecordNotFoundError): |
| 480 | continue # another run (or an edit) got there first |
| 481 | except Exception as exc: |
| 482 | return won, str(exc)[:200] |
| 483 | won.append(row) |
| 484 | return won, None |