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.
billing_runner.py · 25.7 KB · 567 lines
| 1 | """system_billing_runner -- close periods, raise invoices, move the ladder. |
| 2 | |
| 3 | POST {today?, dry_run?} -- the daily pass that turns subscriptions into |
| 4 | money owed. Three jobs, in this order: |
| 5 | |
| 6 | 1. **Trials that ended** become active (or move on unpaid, below). |
| 7 | 2. **The base fee is billed in advance, usage in arrears** (decision 4, |
| 8 | owner, 2026-11-30). A period that has begun with its base fee unbilled |
| 9 | -- a new subscription's first, or the one current when billing moved |
| 10 | from arrears to advance -- is billed at once (marker |
| 11 | subscriptions/{id}:{start}:base, number ...-ADV). Each base-fee line is |
| 12 | stamped with the service period it bills (invoice_lines.service_start/ |
| 13 | service_end); that stamp is how a period's fee is known to be billed, |
| 14 | and how accrual books defer it. Revenue billed in advance is released |
| 15 | from Deferred Revenue month by month as it is earned, by this pass, on |
| 16 | accrual books only. |
| 17 | 3. **Periods that closed** raise ONE invoice -- the closed period's rated |
| 18 | usage plus the NEXT period's base fee, or the usage alone for a |
| 19 | subscription cancelling at that period's end (cancellation runs to the |
| 20 | period's end; staff may end one now with a pro-rata credit note, |
| 21 | action_subscription_credit_unused) -- and advance the subscription's |
| 22 | dates. Idempotent by provenance: |
| 23 | generated_from = "subscriptions/{id}:{period_start}", so a biller that |
| 24 | runs twice, or is re-run after a crash, cannot double-bill. That |
| 25 | property is not a nicety -- double-billing is the failure customers |
| 26 | never forgive, and a dedup table would be one more thing to get wrong. |
| 27 | 4. **Unpaid invoices age the subscription**: past due beyond a grace |
| 28 | window moves active -> past_due, and further silence -> suspended. |
| 29 | Paying restores service, because the ladder must be climbable in both |
| 30 | directions or a paying customer stays cut off. |
| 31 | |
| 32 | What it deliberately does NOT do: cancel anything on its own beyond |
| 33 | suspension, prorate arithmetic inside a line (a plan change closes the |
| 34 | period early and opens a new one -- see the spec), or bill wallet-mode |
| 35 | subscriptions, which have no periodic invoice by definition; their money |
| 36 | moved when the usage did. |
| 37 | |
| 38 | Everything downstream is the machinery that already ships: the invoice |
| 39 | gets its portal token, its dunning schedule, its books entry when paid. |
| 40 | The biller's whole job is to decide that money is owed and say so once. |
| 41 | |
| 42 | A period is consumed only on a DEFINITE answer. Advancing the dates is |
| 43 | what makes a month disappear for good, so the pass leaves a subscription |
| 44 | on its period -- and says why in its results -- whenever it could not |
| 45 | look: billing_plans, invoices or usage_summaries unreadable, or the plan |
| 46 | the subscription names no longer exists. Each of those used to be read as |
| 47 | an answer ("nothing to bill", "already invoiced", "no usage") and the |
| 48 | month was advanced past, unbilled. Every subscription is also isolated: |
| 49 | one that raises is reported and the rest are still billed, where one bad |
| 50 | row used to abort the whole pass every day. |
| 51 | |
| 52 | The dedup marker lives in invoices.generated_from (read_only), not only in |
| 53 | the editable notes: an ordinary edit of a note used to let a re-run bill |
| 54 | the same period twice. Invoices raised before that column existed are |
| 55 | still found by the old notes marker. |
| 56 | """ |
| 57 | |
| 58 | import json |
| 59 | import os |
| 60 | from datetime import date, timedelta |
| 61 | |
| 62 | import object_billing |
| 63 | import object_ids |
| 64 | import object_records |
| 65 | |
| 66 | ACTOR = "system_billing_runner" |
| 67 | |
| 68 | DEFAULT_GRACE_DAYS = 7 |
| 69 | DEFAULT_SUSPEND_AFTER_DAYS = 30 |
| 70 | |
| 71 | _UNREADABLE = object() # "could not look", never an answer |
| 72 | |
| 73 | |
| 74 | def _base_dir(): |
| 75 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 76 | |
| 77 | |
| 78 | def _setting(base, key, default): |
| 79 | try: |
| 80 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 81 | if row.get("key") == key and str(row.get("value") or "").strip(): |
| 82 | return row["value"].strip() |
| 83 | except Exception: |
| 84 | pass |
| 85 | return default |
| 86 | |
| 87 | |
| 88 | def _int(value, default=0): |
| 89 | try: |
| 90 | return int(str(value or "").strip() or default) |
| 91 | except (TypeError, ValueError): |
| 92 | return default |
| 93 | |
| 94 | |
| 95 | def _truthy(value): |
| 96 | return str(value or "").strip().lower() in ("true", "1", "yes", "on") |
| 97 | |
| 98 | |
| 99 | def _advance(day_iso, period): |
| 100 | """Same day next month/year, clamped -- the 31st of a 30-day month |
| 101 | bills on the 30th rather than skipping a cycle.""" |
| 102 | try: |
| 103 | y, m, d = (int(x) for x in str(day_iso)[:10].split("-")) |
| 104 | except (ValueError, AttributeError): |
| 105 | return "" |
| 106 | if period == "year": |
| 107 | for day in (d, 28): |
| 108 | try: |
| 109 | return date(y + 1, m, day).isoformat() |
| 110 | except ValueError: |
| 111 | continue |
| 112 | return "" |
| 113 | month = m + 1 |
| 114 | year = y + (1 if month > 12 else 0) |
| 115 | month = 1 if month > 12 else month |
| 116 | for day in (d, 30, 29, 28): |
| 117 | try: |
| 118 | return date(year, month, day).isoformat() |
| 119 | except ValueError: |
| 120 | continue |
| 121 | return "" |
| 122 | |
| 123 | |
| 124 | def _is_subscription_invoice(row, marker): |
| 125 | """True when `row` was raised by this biller for `marker` (an exact |
| 126 | period marker) or, with a trailing ':', for any period of that |
| 127 | subscription. generated_from is authoritative; the notes marker is the |
| 128 | fallback for invoices raised before the column existed.""" |
| 129 | stamped = str(row.get("generated_from") or "") |
| 130 | if stamped: |
| 131 | return stamped == marker or (marker.endswith(":") and stamped.startswith(marker)) |
| 132 | return f"[{marker}" in str(row.get("notes") or "") |
| 133 | |
| 134 | |
| 135 | def _existing_invoice(base, marker): |
| 136 | """The invoice already raised for this period, None when there is |
| 137 | none, or _UNREADABLE when invoices could not be read. The caller must |
| 138 | neither raise a second invoice nor advance the period on _UNREADABLE.""" |
| 139 | try: |
| 140 | rows = object_records.read_collection_records("invoices", base_dir=base) |
| 141 | except Exception: |
| 142 | return _UNREADABLE |
| 143 | for row in rows: |
| 144 | if _is_subscription_invoice(row, marker): |
| 145 | return row |
| 146 | return None |
| 147 | |
| 148 | |
| 149 | def _usage_lines(base, subscription, plan, period_start, period_end): |
| 150 | """Rated overage for the period, from SUMMARIES not raw events. |
| 151 | |
| 152 | Allowances and tiers are properties of a period's total, so this can |
| 153 | only happen at close -- rating each event as it landed would charge |
| 154 | the first calls at retail and never apply the included quantity. |
| 155 | """ |
| 156 | prices = object_billing.parse_prices(plan.get("prices")) |
| 157 | if not prices: |
| 158 | return [], 0, [], [] |
| 159 | try: |
| 160 | rows = object_records.read_collection_records("usage_summaries", base_dir=base) |
| 161 | except Exception: |
| 162 | return None # could not look: billing the base fee alone loses the overage |
| 163 | mine = [r for r in rows |
| 164 | if r.get("subscription_id") == subscription.get("id") |
| 165 | and str(r.get("period_start") or "")[:10] == period_start |
| 166 | and not _truthy(r.get("invoiced"))] |
| 167 | rated = object_billing.rate_period(mine, prices) |
| 168 | return rated["lines"], rated["total_minor"], rated["unpriced"], [r["id"] for r in mine] |
| 169 | |
| 170 | |
| 171 | def _base_billed(base, subscription_id, period_start): |
| 172 | """Has this subscription's base fee for the period starting |
| 173 | `period_start` been billed? True/False, or _UNREADABLE. A base-fee line |
| 174 | is the only line the biller stamps with service_start (usage is billed |
| 175 | in arrears for service already delivered), so the question is whether |
| 176 | any of this subscription's invoices carries one for that day.""" |
| 177 | marker = f"subscriptions/{subscription_id}:" |
| 178 | try: |
| 179 | invoices = {row["id"] for row in object_records.read_collection_records( |
| 180 | "invoices", base_dir=base) if _is_subscription_invoice(row, marker) |
| 181 | and str(row.get("status") or "") != "void"} |
| 182 | if not invoices: |
| 183 | return False |
| 184 | lines = object_records.read_collection_records("invoice_lines", base_dir=base) |
| 185 | except Exception: |
| 186 | return _UNREADABLE |
| 187 | return any(line.get("invoice_id") in invoices |
| 188 | and str(line.get("service_start") or "")[:10] == period_start |
| 189 | for line in lines) |
| 190 | |
| 191 | |
| 192 | def _write_invoice(base, subscription, *, marker, number, today, lines): |
| 193 | """One biller invoice with its lines. Each line is |
| 194 | (description, quantity, unit_minor, amount_minor, service_start, service_end).""" |
| 195 | total_minor = sum(line[3] for line in lines) |
| 196 | grace = _int(_setting(base, "billing.invoice_due_days", "14"), 14) |
| 197 | invoice_id = object_ids.new_uuid4() |
| 198 | object_records.create_collection_record( |
| 199 | "invoices", |
| 200 | { |
| 201 | "id": invoice_id, |
| 202 | "number": number, |
| 203 | "customer_id": subscription.get("customer_id", ""), |
| 204 | "customer_name": subscription.get("customer_name") or "Customer", |
| 205 | "customer_email": subscription.get("customer_email", ""), |
| 206 | "status": "sent", |
| 207 | "issue_date": today, |
| 208 | "due_date": (date.fromisoformat(today) + timedelta(days=grace)).isoformat(), |
| 209 | "subtotal_cents": str(total_minor), |
| 210 | "total_cents": str(total_minor), |
| 211 | # generated_from is the marker that makes a re-run a no-op; |
| 212 | # it is read_only so no ordinary edit can remove it. The note |
| 213 | # keeps the human-readable copy. |
| 214 | "generated_from": marker, |
| 215 | "notes": f"Generated by {ACTOR} [{marker}]", |
| 216 | "owner_id": subscription.get("owner_id", ""), |
| 217 | }, |
| 218 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 219 | for description, quantity, unit_minor, amount_minor, start, end in lines: |
| 220 | row = {"id": object_ids.new_uuid4(), "invoice_id": invoice_id, |
| 221 | "description": description, "quantity": str(quantity), |
| 222 | "unit_price_cents": str(unit_minor or 0), |
| 223 | "line_total_cents": str(amount_minor), |
| 224 | "owner_id": subscription.get("owner_id", "")} |
| 225 | if start: |
| 226 | row["service_start"], row["service_end"] = start, end |
| 227 | object_records.create_collection_record( |
| 228 | "invoice_lines", row, base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 229 | return invoice_id, total_minor |
| 230 | |
| 231 | |
| 232 | def _base_line(plan, start, end): |
| 233 | base_minor = _int(plan.get("base_minor")) |
| 234 | return (f"{plan.get('name') or 'Subscription'} ({start} to {end})", 1, base_minor, |
| 235 | base_minor, start, end) |
| 236 | |
| 237 | |
| 238 | def _open_period(base, subscription, plan, period_start, period_end, today): |
| 239 | """Bill the current period's base fee IN ADVANCE when nothing has |
| 240 | (decision 4): a new subscription's first period, or the period that was |
| 241 | current when billing moved from arrears to advance. Idempotent by its |
| 242 | own marker and by the base-billed check.""" |
| 243 | base_minor = _int(plan.get("base_minor")) |
| 244 | if base_minor <= 0: |
| 245 | return None |
| 246 | billed = _base_billed(base, subscription["id"], period_start) |
| 247 | if billed is _UNREADABLE: |
| 248 | return {"error": "invoices unreadable; the period's base fee was not billed in " |
| 249 | "advance, left for the next pass", "retry": True} |
| 250 | if billed: |
| 251 | return None |
| 252 | marker = f"subscriptions/{subscription['id']}:{period_start}:base" |
| 253 | existing = _existing_invoice(base, marker) |
| 254 | if existing is _UNREADABLE: |
| 255 | return {"error": "invoices unreadable; not risking a second invoice", |
| 256 | "marker": marker, "retry": True} |
| 257 | if existing: |
| 258 | return None |
| 259 | invoice_id, total = _write_invoice( |
| 260 | base, subscription, marker=marker, today=today, |
| 261 | number=f"SUB-{str(subscription['id'])[:8]}-{period_start[:7]}-ADV", |
| 262 | lines=[_base_line(plan, period_start, period_end)]) |
| 263 | return {"invoice_id": invoice_id, "billed_in_advance": period_start, |
| 264 | "amount_minor": total, "base_minor": total, "usage_minor": 0} |
| 265 | |
| 266 | |
| 267 | def _raise_invoice(base, subscription, plan, period_start, period_end, today, |
| 268 | next_period=None): |
| 269 | """One invoice at the close of a period: that period's rated usage (in |
| 270 | ARREARS -- it has been used) plus the NEXT period's base fee (in ADVANCE |
| 271 | -- decision 4, owner, 2026-11-30), unless the subscription is cancelling |
| 272 | at this period's end, in which case only the usage.""" |
| 273 | marker = f"subscriptions/{subscription['id']}:{period_start}" |
| 274 | existing = _existing_invoice(base, marker) |
| 275 | if existing is _UNREADABLE: |
| 276 | return {"error": "invoices unreadable; not risking a second invoice, " |
| 277 | "period left open for the next pass", |
| 278 | "marker": marker, "retry": True} |
| 279 | if existing: |
| 280 | return {"skipped": "already invoiced", "marker": marker} |
| 281 | |
| 282 | usage = _usage_lines(base, subscription, plan, period_start, period_end) |
| 283 | if usage is None: |
| 284 | return {"error": "usage_summaries unreadable; period left open for " |
| 285 | "the next pass", "marker": marker, "retry": True} |
| 286 | usage_lines, usage_minor, unpriced, summary_ids = usage |
| 287 | lines = [] |
| 288 | base_minor = 0 |
| 289 | if next_period is not None and _int(plan.get("base_minor")) > 0: |
| 290 | billed = _base_billed(base, subscription["id"], next_period[0]) |
| 291 | if billed is _UNREADABLE: |
| 292 | return {"error": "invoices unreadable; period left open for the next pass", |
| 293 | "marker": marker, "retry": True} |
| 294 | if not billed: |
| 295 | lines.append(_base_line(plan, *next_period)) |
| 296 | base_minor = lines[-1][3] |
| 297 | for line in usage_lines: |
| 298 | # The line says what was used, what the plan included, and what |
| 299 | # the overage cost -- a bill a customer can check rather than |
| 300 | # a single opaque "usage" figure they can only dispute. |
| 301 | lines.append((f"{line['metric']}: {line['quantity']} used, " |
| 302 | f"{line['included']} included, {line['overage']} billable", |
| 303 | line["overage"], line["unit_minor"], line["amount_minor"], "", "")) |
| 304 | if base_minor <= 0 and usage_minor <= 0: |
| 305 | return {"skipped": "nothing to bill for this period", |
| 306 | **({"unpriced_metrics": unpriced} if unpriced else {})} |
| 307 | number = f"SUB-{str(subscription['id'])[:8]}-{period_start[:7]}" |
| 308 | try: |
| 309 | invoice_id, total_minor = _write_invoice( |
| 310 | base, subscription, marker=marker, number=number, today=today, lines=lines) |
| 311 | for summary_id in summary_ids: |
| 312 | object_records.update_collection_record( |
| 313 | "usage_summaries", summary_id, {"invoiced": "true"}, |
| 314 | base_dir=base, actor=ACTOR) |
| 315 | except Exception as exc: |
| 316 | return {"warning": f"invoice not fully written: {str(exc)[:100]}"} |
| 317 | return {"invoice_id": invoice_id, "number": number, "amount_minor": total_minor, |
| 318 | "base_minor": base_minor, "usage_minor": usage_minor, |
| 319 | **({"base_for": next_period[0]} if base_minor else {}), |
| 320 | **({"unpriced_metrics": unpriced} if unpriced else {})} |
| 321 | |
| 322 | |
| 323 | def _release_deferred(base, today): |
| 324 | """Accrual books: release revenue billed in advance as it is earned, |
| 325 | one installment per service month (decision 4). Each base-fee line whose |
| 326 | invoice was booked with a Deferred Revenue part is released in n parts |
| 327 | over its service period (n = its months, at least 1), part k due on the |
| 328 | service start advanced k months (the last on service_end), amount |
| 329 | half-up(total*k/n) - half-up(total*(k-1)/n), so the parts add up to the |
| 330 | line exactly. Idempotent by provenance invoice_lines/<id>:released:<k>.""" |
| 331 | if _setting(base, "payments.accounting_basis", "cash") != "accrual": |
| 332 | return [] |
| 333 | deferred = _setting(base, "payments.journal.deferred_revenue_account", "") |
| 334 | revenue = _setting(base, "payments.journal.revenue_account", "") |
| 335 | if not deferred or not revenue: |
| 336 | return [] |
| 337 | try: |
| 338 | import object_finance |
| 339 | invoices = {row["id"]: row for row in object_records.read_collection_records( |
| 340 | "invoices", base_dir=base)} |
| 341 | lines = object_records.read_collection_records("invoice_lines", base_dir=base) |
| 342 | deferring = {row.get("journal_id") for row in object_records.read_collection_records( |
| 343 | "fin_journal_lines", base_dir=base) |
| 344 | if row.get("account_id") == deferred and _int(row.get("credit_cents")) > 0} |
| 345 | except Exception: |
| 346 | return [] |
| 347 | out = [] |
| 348 | for line in lines: |
| 349 | start = str(line.get("service_start") or "")[:10] |
| 350 | end = str(line.get("service_end") or "")[:10] |
| 351 | invoice = invoices.get(line.get("invoice_id")) |
| 352 | if not start or not end or invoice is None or invoice.get("status") == "void": |
| 353 | continue |
| 354 | issued = object_finance.find_journal_by_provenance( |
| 355 | base, f"invoices/{invoice['id']}:issued") |
| 356 | if not issued or issued.get("id") not in deferring: |
| 357 | # Only revenue that was booked as deferred is released. |
| 358 | continue |
| 359 | total = _int(line.get("line_total_cents")) |
| 360 | dues = [] |
| 361 | step = start |
| 362 | while True: |
| 363 | step = _advance(step, "month") |
| 364 | if not step or step >= end: |
| 365 | dues.append(end) |
| 366 | break |
| 367 | dues.append(step) |
| 368 | if len(dues) > 120: |
| 369 | break |
| 370 | n = len(dues) |
| 371 | for k, due in enumerate(dues, start=1): |
| 372 | if due > today: |
| 373 | break |
| 374 | amount = _half_up(total * k, n) - _half_up(total * (k - 1), n) |
| 375 | if amount <= 0: |
| 376 | continue |
| 377 | result = object_finance.compose_posted_journal( |
| 378 | base, generated_from=f"invoice_lines/{line['id']}:released:{k}", |
| 379 | date=due, description=(f"Revenue earned: {line.get('description') or ''} " |
| 380 | f"({k} of {n})"), |
| 381 | lines=[{"account_id": deferred, "debit_cents": amount, "credit_cents": 0}, |
| 382 | {"account_id": revenue, "debit_cents": 0, "credit_cents": amount}], |
| 383 | owner_id=invoice.get("owner_id", ""), entity_id=invoice.get("entity_id", ""), |
| 384 | actor=ACTOR) |
| 385 | if result.get("journal_id") and not result.get("skipped"): |
| 386 | out.append({"line": line["id"], "released": amount, "part": k, "of": n}) |
| 387 | return out |
| 388 | |
| 389 | |
| 390 | def _half_up(numerator, denominator): |
| 391 | return (2 * numerator + denominator) // (2 * denominator) |
| 392 | def _unpaid_days(base, subscription, today): |
| 393 | """Days past due of the oldest unpaid invoice for this subscriber. Only |
| 394 | an invoice that still owes something counts (status follows the money: |
| 395 | sent, partial, overdue).""" |
| 396 | worst = 0 |
| 397 | marker = f"subscriptions/{subscription['id']}:" |
| 398 | try: |
| 399 | rows = object_records.read_collection_records("invoices", base_dir=base) |
| 400 | except Exception: |
| 401 | return 0 |
| 402 | for row in rows: |
| 403 | if not _is_subscription_invoice(row, marker): |
| 404 | continue |
| 405 | if row.get("status") not in ("sent", "partial", "overdue"): |
| 406 | continue |
| 407 | due = str(row.get("due_date") or "")[:10] |
| 408 | if not due or due >= today: |
| 409 | continue |
| 410 | try: |
| 411 | days = (date.fromisoformat(today) - date.fromisoformat(due)).days |
| 412 | except ValueError: |
| 413 | continue |
| 414 | worst = max(worst, days) |
| 415 | return worst |
| 416 | |
| 417 | |
| 418 | def _close_period(base, sub, plan, period_start, period_end, today): |
| 419 | """Raise the period's invoice, then advance -- only on a definite answer. |
| 420 | |
| 421 | Returns (outcome, invoiced, advanced). `plan` is None when billing_plans |
| 422 | could not be read, {} when the plan the subscription names is gone.""" |
| 423 | if plan is None: |
| 424 | return ({"error": "billing_plans unreadable; period left open for the " |
| 425 | "next pass", "retry": True}, 0, 0) |
| 426 | if not plan: |
| 427 | return ({"error": f"plan {sub.get('plan_id')!r} not found; period left " |
| 428 | "open until the subscription names a plan that exists"}, |
| 429 | 0, 0) |
| 430 | next_end = _advance(period_end, plan.get("period") or "month") |
| 431 | if not next_end: |
| 432 | return {"warning": "could not compute the next period"}, 0, 0 |
| 433 | # Cancellation runs to the period's end: the period was paid in |
| 434 | # advance, so the closing invoice carries only its usage and no next |
| 435 | # base fee (decision 4). |
| 436 | next_period = None if _truthy(sub.get("cancel_at_period_end")) else (period_end, next_end) |
| 437 | outcome = _raise_invoice(base, sub, plan, period_start, period_end, today, |
| 438 | next_period=next_period) |
| 439 | invoiced = 1 if outcome.get("invoice_id") else 0 |
| 440 | if outcome.get("error"): |
| 441 | return outcome, invoiced, 0 |
| 442 | object_records.update_collection_record( |
| 443 | "subscriptions", sub["id"], |
| 444 | {"current_period_start": period_end, "current_period_end": next_end}, |
| 445 | base_dir=base, actor=ACTOR) |
| 446 | return outcome, invoiced, 1 |
| 447 | |
| 448 | |
| 449 | def _bill_subscription(base, sub, plans, today, dry_run, grace, suspend_after): |
| 450 | """One subscription's jobs. Returns (results, invoiced, advanced, |
| 451 | status_moves).""" |
| 452 | results = [] |
| 453 | invoiced = advanced = laddered = 0 |
| 454 | sub_id = sub.get("id") |
| 455 | status = sub.get("status") or "trialing" |
| 456 | if status == "canceled": |
| 457 | return results, 0, 0, 0 |
| 458 | plan = None if plans is None else (plans.get(sub.get("plan_id")) or {}) |
| 459 | mode = sub.get("billing_mode") or "subscription" |
| 460 | |
| 461 | # 1. trial expiry |
| 462 | trial_end = str(sub.get("trial_ends_on") or "")[:10] |
| 463 | if status == "trialing" and trial_end and trial_end <= today: |
| 464 | if not dry_run: |
| 465 | object_records.update_collection_record( |
| 466 | "subscriptions", sub_id, {"status": "active"}, |
| 467 | base_dir=base, actor=ACTOR) |
| 468 | status = "active" |
| 469 | laddered += 1 |
| 470 | results.append({"subscription": sub_id, "trial_ended": trial_end}) |
| 471 | |
| 472 | billable = mode in ("subscription", "hybrid") and status in ("active", "past_due") |
| 473 | period_start = str(sub.get("current_period_start") or "")[:10] |
| 474 | period_end = str(sub.get("current_period_end") or "")[:10] |
| 475 | |
| 476 | # 2. the base fee is billed IN ADVANCE (decision 4): a period that has |
| 477 | # begun with its base fee unbilled -- a new subscription's first, or |
| 478 | # the one current when billing moved from arrears -- is billed now. |
| 479 | # Later periods' base fees ride on the invoice that closes the one |
| 480 | # before. A subscription cancelling at period end is not billed for |
| 481 | # a period it will not have. |
| 482 | if (billable and plan and period_start and period_end and period_start <= today |
| 483 | and not dry_run): |
| 484 | opened = _open_period(base, sub, plan, period_start, period_end, today) |
| 485 | if opened: |
| 486 | results.append({"subscription": sub_id, **opened}) |
| 487 | invoiced += 1 if opened.get("invoice_id") else 0 |
| 488 | |
| 489 | # 3. close the period -- wallet mode never gets a periodic invoice, |
| 490 | # because its money already moved when the usage did. |
| 491 | if billable and period_end and period_end <= today: |
| 492 | period_start = period_start or period_end |
| 493 | if dry_run: |
| 494 | results.append({"subscription": sub_id, "would_invoice_period": period_start}) |
| 495 | else: |
| 496 | outcome, did_invoice, did_advance = _close_period( |
| 497 | base, sub, plan, period_start, period_end, today) |
| 498 | results.append({"subscription": sub_id, **outcome}) |
| 499 | invoiced += did_invoice |
| 500 | advanced += did_advance |
| 501 | if did_advance and _truthy(sub.get("cancel_at_period_end")): |
| 502 | object_records.update_collection_record( |
| 503 | "subscriptions", sub_id, {"status": "canceled"}, |
| 504 | base_dir=base, actor=ACTOR) |
| 505 | results.append({"subscription": sub_id, |
| 506 | "canceled": "at period end, as requested"}) |
| 507 | return results, invoiced, advanced, laddered |
| 508 | |
| 509 | # 4. the ladder: unpaid invoices age the subscription |
| 510 | overdue_days = _unpaid_days(base, sub, today) |
| 511 | if not dry_run and overdue_days: |
| 512 | if status == "active" and overdue_days > grace: |
| 513 | object_records.update_collection_record( |
| 514 | "subscriptions", sub_id, {"status": "past_due"}, |
| 515 | base_dir=base, actor=ACTOR) |
| 516 | laddered += 1 |
| 517 | results.append({"subscription": sub_id, "past_due_after_days": overdue_days}) |
| 518 | elif status == "past_due" and overdue_days > suspend_after: |
| 519 | object_records.update_collection_record( |
| 520 | "subscriptions", sub_id, {"status": "suspended"}, |
| 521 | base_dir=base, actor=ACTOR) |
| 522 | laddered += 1 |
| 523 | results.append({"subscription": sub_id, "suspended_after_days": overdue_days}) |
| 524 | return results, invoiced, advanced, laddered |
| 525 | |
| 526 | def POST(request): |
| 527 | base = _base_dir() |
| 528 | today = str(request.get("today") or date.today().isoformat()) |
| 529 | dry_run = _truthy(request.get("dry_run")) |
| 530 | |
| 531 | try: |
| 532 | subscriptions = object_records.read_collection_records("subscriptions", base_dir=base) |
| 533 | except Exception: |
| 534 | return {"ok": True, "skipped": "billing not installed (subscriptions absent)"} |
| 535 | try: |
| 536 | plans = {p["id"]: p for p in |
| 537 | object_records.read_collection_records("billing_plans", base_dir=base)} |
| 538 | except Exception: |
| 539 | plans = None # could not look -- NOT "every plan is missing" |
| 540 | |
| 541 | grace = _int(_setting(base, "billing.past_due_grace_days", DEFAULT_GRACE_DAYS), |
| 542 | DEFAULT_GRACE_DAYS) |
| 543 | suspend_after = _int(_setting(base, "billing.suspend_after_days", |
| 544 | DEFAULT_SUSPEND_AFTER_DAYS), DEFAULT_SUSPEND_AFTER_DAYS) |
| 545 | |
| 546 | invoiced = advanced = laddered = 0 |
| 547 | results = [] |
| 548 | for sub in subscriptions: |
| 549 | try: |
| 550 | sub_results, did_invoice, did_advance, did_ladder = _bill_subscription( |
| 551 | base, sub, plans, today, dry_run, grace, suspend_after) |
| 552 | except Exception as exc: # noqa: BLE001 -- one bad row must not stop the rest |
| 553 | results.append({"subscription": sub.get("id"), |
| 554 | "error": f"{type(exc).__name__}: {str(exc)[:200]}"}) |
| 555 | continue |
| 556 | results.extend(sub_results) |
| 557 | invoiced += did_invoice |
| 558 | advanced += did_advance |
| 559 | laddered += did_ladder |
| 560 | |
| 561 | out = {"ok": True, "today": today, "invoiced": invoiced, "advanced": advanced, |
| 562 | "status_moves": laddered, "results": results} |
| 563 | if not dry_run: |
| 564 | released = _release_deferred(base, today) |
| 565 | if released: |
| 566 | out["revenue_released"] = released |
| 567 | return out |