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
invoice_aging.py · 7.9 KB · 191 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 fall back to |
| 19 | paid/partial (belt to system_invoice_status's suspenders). |
| 20 | """ |
| 21 | |
| 22 | import os |
| 23 | import secrets |
| 24 | from datetime import date, timedelta |
| 25 | |
| 26 | import object_ids |
| 27 | import object_records |
| 28 | |
| 29 | ACTOR = "system_invoice_aging" |
| 30 | |
| 31 | |
| 32 | def _base_dir(): |
| 33 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 34 | |
| 35 | |
| 36 | def _setting(base, key, default): |
| 37 | try: |
| 38 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 39 | if row.get("key") == key and row.get("value"): |
| 40 | return row["value"].strip() |
| 41 | except Exception: |
| 42 | pass |
| 43 | return default |
| 44 | |
| 45 | |
| 46 | def _int_setting(base, key, default): |
| 47 | try: |
| 48 | return int(_setting(base, key, str(default))) |
| 49 | except ValueError: |
| 50 | return default |
| 51 | |
| 52 | |
| 53 | def _parse(day): |
| 54 | try: |
| 55 | y, m, d = (int(x) for x in str(day).split("-")) |
| 56 | return date(y, m, d) |
| 57 | except (ValueError, AttributeError): |
| 58 | return None |
| 59 | |
| 60 | |
| 61 | def _portal_link(base, invoice): |
| 62 | """The door this dunning email points at |
| 63 | (plan/customer-payment-portal-spec.md): closes the loop that makes |
| 64 | dunning ACTIONABLE -- an email that says "you owe X" with nowhere to |
| 65 | go is the exact gap this whole feature exists to close. |
| 66 | |
| 67 | Mints invoices.portal_token lazily, right here, the first time an |
| 68 | invoice needs a working link. action_regenerate_portal_link is the |
| 69 | owner-facing way to mint or rotate one on demand, but wiring EAGER |
| 70 | issuance into the invoice "send" flow (draft -> sent) lives in objects |
| 71 | outside this file's edit boundary (site_invoices / a hook on the |
| 72 | invoices collection -- see that action object's own docstring), so |
| 73 | without this fallback an invoice could reach its first overdue dunning |
| 74 | email with no token yet and no way to get one. Dunning is the moment a |
| 75 | working link is most needed, so this is where the fallback lives. |
| 76 | |
| 77 | Returns "" -- never a broken relative URL -- when portal.base_url is |
| 78 | unset, or when the mint fails to persist. A dunning email with no link |
| 79 | at all is honest about what this deployment has configured; one with a |
| 80 | guaranteed-404 link would be worse than the plain amount-owed text it |
| 81 | replaces. |
| 82 | """ |
| 83 | base_url = str(_setting(base, "portal.base_url", "") or "").rstrip("/") |
| 84 | if not base_url: |
| 85 | return "" |
| 86 | token = str(invoice.get("portal_token") or "").strip() |
| 87 | if not token: |
| 88 | token = secrets.token_urlsafe(32) |
| 89 | try: |
| 90 | object_records.update_collection_record( |
| 91 | "invoices", invoice["id"], {"portal_token": token}, |
| 92 | base_dir=base, actor=ACTOR, preserve_read_only=True, |
| 93 | ) |
| 94 | except Exception: |
| 95 | return "" # could not persist a token: don't mail a dead link |
| 96 | return f"{base_url}/pay/{token}" |
| 97 | |
| 98 | |
| 99 | def _queue_dunning_email(base, invoice, level): |
| 100 | to = (invoice.get("customer_email") or "").strip() |
| 101 | if not to: |
| 102 | return False |
| 103 | link = _portal_link(base, invoice) |
| 104 | pay_line = f"\nView and pay this invoice online: {link}\n" if link else "" |
| 105 | try: |
| 106 | object_records.create_collection_record( |
| 107 | "email_outbox", |
| 108 | { |
| 109 | "id": object_ids.new_uuid4(), |
| 110 | "to": to, |
| 111 | "from_addr": _setting(base, "payments.dunning_from", ""), |
| 112 | "subject": f"Invoice {invoice.get('number') or invoice.get('id')} is overdue" |
| 113 | + (f" (reminder {level})" if level > 1 else ""), |
| 114 | "text_body": ( |
| 115 | f"Hello {invoice.get('customer_name') or ''},\n\n" |
| 116 | f"Invoice {invoice.get('number') or invoice.get('id')} for " |
| 117 | f"{invoice.get('total_cents') or '0'} cents was due on " |
| 118 | f"{invoice.get('due_date') or 'its due date'} and has an outstanding " |
| 119 | f"balance of {invoice.get('balance_due_cents') or '?'} cents.\n" |
| 120 | f"{pay_line}\n" |
| 121 | "Please arrange payment at your earliest convenience.\n" |
| 122 | ), |
| 123 | "source_object_id": ACTOR, |
| 124 | }, |
| 125 | base_dir=base, |
| 126 | actor=ACTOR, |
| 127 | ) |
| 128 | return True |
| 129 | except Exception: |
| 130 | return False # outbox not installed / bad row: dunning is best-effort |
| 131 | |
| 132 | |
| 133 | def POST(request): |
| 134 | base = _base_dir() |
| 135 | today = _parse(request.get("today")) or date.today() |
| 136 | grace = _int_setting(base, "payments.grace_days", 0) |
| 137 | repeat = max(1, _int_setting(base, "payments.dunning_repeat_days", 7)) |
| 138 | max_level = _int_setting(base, "payments.dunning_max_level", 3) |
| 139 | |
| 140 | flipped, dunned, results = 0, 0, [] |
| 141 | try: |
| 142 | invoices = object_records.read_collection_records("invoices", base_dir=base) |
| 143 | except Exception: |
| 144 | return {"ok": True, "skipped": "invoices not installed"} |
| 145 | |
| 146 | for inv in invoices: |
| 147 | status = inv.get("status") or "" |
| 148 | try: |
| 149 | balance = int(inv.get("balance_due_cents") or 0) |
| 150 | paid = int(inv.get("amount_paid_cents") or 0) |
| 151 | total = int(inv.get("total_cents") or 0) |
| 152 | except ValueError: |
| 153 | continue |
| 154 | |
| 155 | if status in ("sent", "partial"): |
| 156 | due = _parse(inv.get("due_date")) |
| 157 | if due is None or balance <= 0 or total <= 0: |
| 158 | continue |
| 159 | if today <= due + timedelta(days=grace): |
| 160 | continue |
| 161 | changes = {"status": "overdue", "dunning_level": "1", |
| 162 | "last_dunned_on": today.isoformat()} |
| 163 | object_records.update_collection_record( |
| 164 | "invoices", inv["id"], changes, base_dir=base, actor=ACTOR) |
| 165 | emailed = _queue_dunning_email(base, {**inv, **changes}, 1) |
| 166 | flipped += 1 |
| 167 | results.append({"invoice": inv["id"], "action": "overdue", "emailed": emailed}) |
| 168 | |
| 169 | elif status == "overdue": |
| 170 | if total > 0 and balance <= 0: |
| 171 | new_status = "paid" if paid >= total else "partial" |
| 172 | object_records.update_collection_record( |
| 173 | "invoices", inv["id"], {"status": new_status}, |
| 174 | base_dir=base, actor=ACTOR) |
| 175 | results.append({"invoice": inv["id"], "action": new_status}) |
| 176 | continue |
| 177 | level = int(inv.get("dunning_level") or 1) |
| 178 | last = _parse(inv.get("last_dunned_on")) or today |
| 179 | if level >= max_level or today < last + timedelta(days=repeat): |
| 180 | continue |
| 181 | changes = {"dunning_level": str(level + 1), |
| 182 | "last_dunned_on": today.isoformat()} |
| 183 | object_records.update_collection_record( |
| 184 | "invoices", inv["id"], changes, base_dir=base, actor=ACTOR) |
| 185 | emailed = _queue_dunning_email(base, {**inv, **changes}, level + 1) |
| 186 | dunned += 1 |
| 187 | results.append({"invoice": inv["id"], "action": f"dun-level-{level + 1}", |
| 188 | "emailed": emailed}) |
| 189 | |
| 190 | return {"ok": True, "flipped_overdue": flipped, "escalated": dunned, |
| 191 | "today": today.isoformat(), "results": results} |