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.
invoice_aging.py · 8.5 KB · 201 lines
| 1 | """system_invoice_aging -- the time-driven half of the late-payment story. |
| 2 | |
| 3 | Time changes an invoice's meaning with no write happening, so this runs as a |
| 4 | daemon-scheduled pass (docs/logic-decisions.md #2), like |
| 5 | system_fin_recurring_runner: register a daily scheduler task with |
| 6 | object_id="system_invoice_aging", method="POST"; also manually runnable. |
| 7 | |
| 8 | Per pass: |
| 9 | - sent/partial invoices past due_date + grace (payments.grace_days, default 0) |
| 10 | with a positive balance flip to OVERDUE, dunning_level=1, last_dunned_on set, |
| 11 | and a dunning email is queued to customer_email via the generic outbox |
| 12 | (raw address -> outbox directly; notify's user-mapping is for user ids). |
| 13 | - overdue invoices re-dun every payments.dunning_repeat_days (default 7) up to |
| 14 | payments.dunning_max_level (default 3): bump dunning_level + re-queue email. |
| 15 | Each bump is an ordinary record update, so notify_rules (owner in_app) and |
| 16 | realtime fire like any other change -- escalation steps ARE state changes |
| 17 | (docs/business-logic-patterns.md, dunning walkthrough). |
| 18 | - overdue invoices whose balance cleared some other way take the status their |
| 19 | money says (object_corrections.money_status: paid, credited, refunded, |
| 20 | credit_owed) -- belt to system_invoice_status's suspenders. |
| 21 | """ |
| 22 | |
| 23 | import os |
| 24 | import secrets |
| 25 | from datetime import date, timedelta |
| 26 | |
| 27 | import object_corrections |
| 28 | import object_ids |
| 29 | import object_records |
| 30 | |
| 31 | ACTOR = "system_invoice_aging" |
| 32 | |
| 33 | |
| 34 | def _base_dir(): |
| 35 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 36 | |
| 37 | |
| 38 | def _setting(base, key, default): |
| 39 | try: |
| 40 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 41 | if row.get("key") == key and row.get("value"): |
| 42 | return row["value"].strip() |
| 43 | except Exception: |
| 44 | pass |
| 45 | return default |
| 46 | |
| 47 | |
| 48 | def _int_setting(base, key, default): |
| 49 | try: |
| 50 | return int(_setting(base, key, str(default))) |
| 51 | except ValueError: |
| 52 | return default |
| 53 | |
| 54 | |
| 55 | def _parse(day): |
| 56 | try: |
| 57 | y, m, d = (int(x) for x in str(day).split("-")) |
| 58 | return date(y, m, d) |
| 59 | except (ValueError, AttributeError): |
| 60 | return None |
| 61 | |
| 62 | |
| 63 | def _portal_link(base, invoice): |
| 64 | """The door this dunning email points at |
| 65 | (plan/customer-payment-portal-spec.md): closes the loop that makes |
| 66 | dunning ACTIONABLE -- an email that says "you owe X" with nowhere to |
| 67 | go is the exact gap this whole feature exists to close. |
| 68 | |
| 69 | Mints invoices.portal_token lazily, right here, the first time an |
| 70 | invoice needs a working link. action_regenerate_portal_link is the |
| 71 | owner-facing way to mint or rotate one on demand, but wiring EAGER |
| 72 | issuance into the invoice "send" flow (draft -> sent) lives in objects |
| 73 | outside this file's edit boundary (site_invoices / a hook on the |
| 74 | invoices collection -- see that action object's own docstring), so |
| 75 | without this fallback an invoice could reach its first overdue dunning |
| 76 | email with no token yet and no way to get one. Dunning is the moment a |
| 77 | working link is most needed, so this is where the fallback lives. |
| 78 | |
| 79 | Returns "" -- never a broken relative URL -- when portal.base_url is |
| 80 | unset, or when the mint fails to persist. A dunning email with no link |
| 81 | at all is honest about what this deployment has configured; one with a |
| 82 | guaranteed-404 link would be worse than the plain amount-owed text it |
| 83 | replaces. |
| 84 | """ |
| 85 | base_url = str(_setting(base, "portal.base_url", "") or "").rstrip("/") |
| 86 | if not base_url: |
| 87 | return "" |
| 88 | token = str(invoice.get("portal_token") or "").strip() |
| 89 | if not token: |
| 90 | token = secrets.token_urlsafe(32) |
| 91 | try: |
| 92 | object_records.update_collection_record( |
| 93 | "invoices", invoice["id"], {"portal_token": token}, |
| 94 | base_dir=base, actor=ACTOR, preserve_read_only=True, |
| 95 | ) |
| 96 | except Exception: |
| 97 | return "" # could not persist a token: don't mail a dead link |
| 98 | return f"{base_url}/pay/{token}" |
| 99 | |
| 100 | |
| 101 | def _queue_dunning_email(base, invoice, level): |
| 102 | to = (invoice.get("customer_email") or "").strip() |
| 103 | if not to: |
| 104 | return False |
| 105 | link = _portal_link(base, invoice) |
| 106 | pay_line = f"\nView and pay this invoice online: {link}\n" if link else "" |
| 107 | try: |
| 108 | object_records.create_collection_record( |
| 109 | "email_outbox", |
| 110 | { |
| 111 | "id": object_ids.new_uuid4(), |
| 112 | "to": to, |
| 113 | "from_addr": _setting(base, "payments.dunning_from", ""), |
| 114 | "subject": f"Invoice {invoice.get('number') or invoice.get('id')} is overdue" |
| 115 | + (f" (reminder {level})" if level > 1 else ""), |
| 116 | "text_body": ( |
| 117 | f"Hello {invoice.get('customer_name') or ''},\n\n" |
| 118 | f"Invoice {invoice.get('number') or invoice.get('id')} for " |
| 119 | f"{invoice.get('total_cents') or '0'} cents was due on " |
| 120 | f"{invoice.get('due_date') or 'its due date'} and has an outstanding " |
| 121 | f"balance of {invoice.get('balance_due_cents') or '?'} cents.\n" |
| 122 | f"{pay_line}\n" |
| 123 | "Please arrange payment at your earliest convenience.\n" |
| 124 | ), |
| 125 | "source_object_id": ACTOR, |
| 126 | }, |
| 127 | base_dir=base, |
| 128 | actor=ACTOR, |
| 129 | ) |
| 130 | return True |
| 131 | except Exception: |
| 132 | return False # outbox not installed / bad row: dunning is best-effort |
| 133 | |
| 134 | |
| 135 | def POST(request): |
| 136 | base = _base_dir() |
| 137 | today = _parse(request.get("today")) or date.today() |
| 138 | grace = _int_setting(base, "payments.grace_days", 0) |
| 139 | repeat = max(1, _int_setting(base, "payments.dunning_repeat_days", 7)) |
| 140 | max_level = _int_setting(base, "payments.dunning_max_level", 3) |
| 141 | |
| 142 | flipped, dunned, results = 0, 0, [] |
| 143 | try: |
| 144 | invoices = object_records.read_collection_records("invoices", base_dir=base) |
| 145 | except Exception: |
| 146 | return {"ok": True, "skipped": "invoices not installed"} |
| 147 | |
| 148 | for inv in invoices: |
| 149 | status = inv.get("status") or "" |
| 150 | try: |
| 151 | balance = int(inv.get("balance_due_cents") or 0) |
| 152 | paid = int(inv.get("amount_paid_cents") or 0) |
| 153 | total = int(inv.get("total_cents") or 0) |
| 154 | except ValueError: |
| 155 | continue |
| 156 | |
| 157 | if status in ("sent", "partial"): |
| 158 | due = _parse(inv.get("due_date")) |
| 159 | if due is None or balance <= 0 or total <= 0: |
| 160 | continue |
| 161 | if today <= due + timedelta(days=grace): |
| 162 | continue |
| 163 | changes = {"status": "overdue", "dunning_level": "1", |
| 164 | "last_dunned_on": today.isoformat()} |
| 165 | object_records.update_collection_record( |
| 166 | "invoices", inv["id"], changes, base_dir=base, actor=ACTOR) |
| 167 | emailed = _queue_dunning_email(base, {**inv, **changes}, 1) |
| 168 | flipped += 1 |
| 169 | results.append({"invoice": inv["id"], "action": "overdue", "emailed": emailed}) |
| 170 | |
| 171 | elif status == "overdue": |
| 172 | if total > 0 and balance <= 0: |
| 173 | # Status follows the money (object_corrections.money_status, |
| 174 | # the owner's decision of 2026-11-30): a balance cleared by |
| 175 | # a credit note reads credited/refunded, an overpaid one |
| 176 | # credit_owed -- not "paid" for money that never came. |
| 177 | new_status = object_corrections.money_status( |
| 178 | status, total=total, received=inv.get("payments_received_cents"), |
| 179 | refunded=inv.get("refunded_cents"), credited=inv.get("credited_cents")) |
| 180 | if new_status == status: |
| 181 | continue |
| 182 | object_records.update_collection_record( |
| 183 | "invoices", inv["id"], {"status": new_status}, |
| 184 | base_dir=base, actor=ACTOR) |
| 185 | results.append({"invoice": inv["id"], "action": new_status}) |
| 186 | continue |
| 187 | level = int(inv.get("dunning_level") or 1) |
| 188 | last = _parse(inv.get("last_dunned_on")) or today |
| 189 | if level >= max_level or today < last + timedelta(days=repeat): |
| 190 | continue |
| 191 | changes = {"dunning_level": str(level + 1), |
| 192 | "last_dunned_on": today.isoformat()} |
| 193 | object_records.update_collection_record( |
| 194 | "invoices", inv["id"], changes, base_dir=base, actor=ACTOR) |
| 195 | emailed = _queue_dunning_email(base, {**inv, **changes}, level + 1) |
| 196 | dunned += 1 |
| 197 | results.append({"invoice": inv["id"], "action": f"dun-level-{level + 1}", |
| 198 | "emailed": emailed}) |
| 199 | |
| 200 | return {"ok": True, "flipped_overdue": flipped, "escalated": dunned, |
| 201 | "today": today.isoformat(), "results": results} |