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.
subscription_credit_unused.py · 7.3 KB · 148 lines
| 1 | """action_subscription_credit_unused -- staff end a subscription now and |
| 2 | credit the unused part of the period already billed. |
| 3 | |
| 4 | POST {"subscription_id": "...", "as_of": "2026-07-10", "reason": "..."} |
| 5 | |
| 6 | **Decision 4 (owner, 2026-11-30).** The base fee is billed in advance, and |
| 7 | cancellation runs to the end of the period: the subscriber's own |
| 8 | cancel_at_period_end keeps the service they paid for and bills no further |
| 9 | period. Staff MAY instead end it now and issue a pro-rata credit note for |
| 10 | the days not used. That is this action; nothing else gives money back for a |
| 11 | period, and a subscriber cannot run it. |
| 12 | |
| 13 | **The credit.** The invoice line that billed the current period's base fee |
| 14 | in advance (the line the biller stamped with service_start equal to the |
| 15 | period's start) is credited for the days from `as_of` (default today) to |
| 16 | the period's end, of the days in the period: |
| 17 | |
| 18 | credit = round_half_up(line_total x unused_days / period_days) |
| 19 | |
| 20 | by a credit note citing that invoice and line, applied at once with an |
| 21 | invoice_credits row -- so the invoice owes that much less, or reads |
| 22 | credit_owed when it was paid, until a refund citing the credit note pays it |
| 23 | out (status follows the money, decision 1). The subscription is moved to |
| 24 | canceled. On accrual books the credit note reverses revenue; what it |
| 25 | reverses of revenue not yet released from Deferred Revenue is NOT |
| 26 | separated here (see docs/logic-decisions.md, the open questions). |
| 27 | |
| 28 | **Refuses, writing nothing:** a caller who is not signed in or may not |
| 29 | update the subscription, a subscription already canceled, a period whose |
| 30 | base fee was not billed in advance (nothing to credit), an `as_of` outside |
| 31 | the period, and a credit that would be zero. |
| 32 | """ |
| 33 | |
| 34 | from __future__ import annotations |
| 35 | |
| 36 | import os |
| 37 | from datetime import date |
| 38 | |
| 39 | import object_access |
| 40 | import object_ids |
| 41 | import object_records |
| 42 | |
| 43 | ACTOR = "action_subscription_credit_unused" |
| 44 | |
| 45 | |
| 46 | def _base_dir(): |
| 47 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 48 | |
| 49 | |
| 50 | def _text(value): |
| 51 | return str(value if value is not None else "").strip() |
| 52 | |
| 53 | |
| 54 | def _int(value): |
| 55 | try: |
| 56 | return int(_text(value) or "0") |
| 57 | except ValueError: |
| 58 | return 0 |
| 59 | |
| 60 | |
| 61 | def prorata(amount, unused_days, period_days): |
| 62 | """round_half_up(amount x unused / period), in whole minor units.""" |
| 63 | if period_days <= 0 or unused_days <= 0 or amount <= 0: |
| 64 | return 0 |
| 65 | unused_days = min(unused_days, period_days) |
| 66 | return (2 * amount * unused_days + period_days) // (2 * period_days) |
| 67 | |
| 68 | |
| 69 | def POST(request): |
| 70 | base = _base_dir() |
| 71 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 72 | if not access.signed_in: |
| 73 | return {"status": 401, "error": "Sign in to credit a subscription."} |
| 74 | sub_id = _text(request.get("subscription_id")) |
| 75 | sub = access.get("subscriptions", sub_id) if sub_id else None |
| 76 | if sub is None: |
| 77 | return {"status": 404, "error": f"No subscription {sub_id or '(none given)'}."} |
| 78 | if not access.can("update", "subscriptions", sub): |
| 79 | return {"status": 403, "error": "Only staff end a subscription early with a credit."} |
| 80 | if _text(sub.get("status")) == "canceled": |
| 81 | return {"status": 409, "error": "That subscription is already canceled."} |
| 82 | start = _text(sub.get("current_period_start"))[:10] |
| 83 | end = _text(sub.get("current_period_end"))[:10] |
| 84 | as_of = _text(request.get("as_of"))[:10] or date.today().isoformat() |
| 85 | try: |
| 86 | period_days = (date.fromisoformat(end) - date.fromisoformat(start)).days |
| 87 | unused = (date.fromisoformat(end) - date.fromisoformat(as_of)).days |
| 88 | except ValueError: |
| 89 | return {"status": 409, "error": "The subscription's period or as_of is not a date."} |
| 90 | if not (start <= as_of <= end): |
| 91 | return {"status": 409, "error": f"as_of must fall in the current period ({start} to {end})."} |
| 92 | |
| 93 | marker = f"subscriptions/{sub['id']}:" |
| 94 | # access: the subscription was read through access.get above; these are the invoices its biller raised for it |
| 95 | invoices = {row["id"]: row for row in object_records.read_collection_records( |
| 96 | "invoices", base_dir=base) |
| 97 | if (_text(row.get("generated_from")).startswith(marker) |
| 98 | or f"[{marker}" in _text(row.get("notes"))) |
| 99 | and _text(row.get("status")) != "void"} |
| 100 | # access: lines of the invoices above |
| 101 | billed = next((line for line in object_records.read_collection_records( |
| 102 | "invoice_lines", base_dir=base) |
| 103 | if line.get("invoice_id") in invoices |
| 104 | and _text(line.get("service_start"))[:10] == start), None) |
| 105 | if billed is None: |
| 106 | return {"status": 409, |
| 107 | "error": ("This period's base fee was not billed in advance, so there is no " |
| 108 | "unused part of it to credit. Cancel at period end instead.")} |
| 109 | bill = invoices[billed["invoice_id"]] |
| 110 | amount = prorata(_int(billed.get("line_total_cents")), unused, period_days) |
| 111 | if amount <= 0: |
| 112 | return {"status": 409, "error": "Nothing of the period is left unused to credit."} |
| 113 | |
| 114 | who = access.user_id |
| 115 | actor = f"{ACTOR}:{who}" |
| 116 | reason = _text(request.get("reason"))[:300] |
| 117 | note_id, line_id, credit_id = (object_ids.new_uuid4() for _ in range(3)) |
| 118 | number = f"CN-{_text(bill.get('number'))}-{note_id[:6].upper()}" |
| 119 | # access: system write after access check above (staff may update this subscription) |
| 120 | object_records.create_collection_record("invoices", { |
| 121 | "id": note_id, "doc_type": "credit_note", "number": number, |
| 122 | "customer_id": _text(bill.get("customer_id")), |
| 123 | "customer_name": _text(bill.get("customer_name")) or "Customer", |
| 124 | "customer_email": _text(bill.get("customer_email")), |
| 125 | "currency": _text(bill.get("currency")) or "USD", "status": "sent", |
| 126 | "issue_date": as_of, "subtotal_cents": str(amount), "total_cents": str(amount), |
| 127 | "credits_invoice_id": bill["id"], "approved_by": who, |
| 128 | "notes": (f"Unused {unused} of {period_days} days of {start} to {end}, ended early" |
| 129 | + (f": {reason}" if reason else "")), |
| 130 | "owner_id": _text(bill.get("owner_id"))}, base_dir=base, actor=actor) |
| 131 | # access: system write after access check above (the credit note this call just raised) |
| 132 | object_records.create_collection_record("invoice_lines", { |
| 133 | "id": line_id, "invoice_id": note_id, |
| 134 | "description": f"Credit: unused {as_of} to {end}", "quantity": "1", |
| 135 | "unit_price_cents": str(amount), "line_total_cents": str(amount), |
| 136 | "credits_line_id": billed["id"], "owner_id": _text(bill.get("owner_id"))}, |
| 137 | base_dir=base, actor=actor, preserve_read_only=True) |
| 138 | # access: system write after access check above (applying the credit note this call just raised) |
| 139 | object_records.create_collection_record("invoice_credits", { |
| 140 | "id": credit_id, "credit_note_id": note_id, "invoice_id": bill["id"], |
| 141 | "amount_cents": str(amount), "applied_on": as_of, "source": "manual", |
| 142 | "owner_id": _text(bill.get("owner_id"))}, base_dir=base, actor=actor) |
| 143 | # access: system write after access check above (staff may update this subscription) |
| 144 | object_records.update_collection_record( |
| 145 | "subscriptions", sub["id"], {"status": "canceled"}, base_dir=base, actor=actor) |
| 146 | return {"status": 200, "ok": True, "subscription_id": sub["id"], "credit_note_id": note_id, |
| 147 | "number": number, "amount_cents": amount, "unused_days": unused, |
| 148 | "period_days": period_days, "invoice_id": bill["id"]} |