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
wallet_replenish.py · 7.2 KB · 184 lines
| 1 | """system_wallet_replenish -- top up a low wallet from the saved card. |
| 2 | |
| 3 | POST {today?, dry_run?} -- a daemon pass (schedulable hourly): for each |
| 4 | wallet with auto top-up enabled and a balance under its threshold, charge |
| 5 | the saved payment method off-session and record the credit. |
| 6 | |
| 7 | Three safeguards, and the middle one is the whole reason this object is |
| 8 | written carefully rather than quickly: |
| 9 | |
| 10 | 1. **A monthly cap, enforced by summing this month's auto top-ups.** |
| 11 | The predecessor tracked replenished-this-month for the same reason: |
| 12 | auto-charging plus one runaway metering bug is how a customer wakes up |
| 13 | to a four-figure surprise. The cap turns that into a bounded annoyance |
| 14 | somebody notices. A cap of zero means auto top-up is off -- the safe |
| 15 | default, since a blank number must never read as "unlimited". |
| 16 | 2. **Idempotency by provenance.** Each charge stamps |
| 17 | generated_from = "auto_topup/{wallet}/{period}", and a wallet that |
| 18 | already has an entry for this period+attempt is skipped. A daemon that |
| 19 | runs twice, or restarts mid-pass, must not charge twice. |
| 20 | 3. **Failure is reported, never retried blindly.** A declined card -- and |
| 21 | especially one needing authentication (SCA), which off-session charges |
| 22 | cannot satisfy -- disables nothing and loops nothing: it records the |
| 23 | attempt so a human (or a dunning email with a pay link) can act. A |
| 24 | retry loop against a declining card is how a business gets its |
| 25 | processor account flagged. |
| 26 | |
| 27 | Stripe is optional: unconfigured, the pass reports what it WOULD charge |
| 28 | and writes nothing, so the rule can be tuned before any money moves. |
| 29 | """ |
| 30 | |
| 31 | import os |
| 32 | from datetime import date |
| 33 | |
| 34 | import object_records |
| 35 | import object_stripe |
| 36 | |
| 37 | ACTOR = "system_wallet_replenish" |
| 38 | |
| 39 | |
| 40 | def _base_dir(): |
| 41 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 42 | |
| 43 | |
| 44 | def _int(value, default=0): |
| 45 | try: |
| 46 | return int(str(value or "0").strip() or default) |
| 47 | except (TypeError, ValueError): |
| 48 | return default |
| 49 | |
| 50 | |
| 51 | def _truthy(value): |
| 52 | return str(value or "").strip().lower() in ("true", "1", "yes", "on") |
| 53 | |
| 54 | |
| 55 | def _entries(base): |
| 56 | try: |
| 57 | return object_records.read_collection_records("wallet_entries", base_dir=base) |
| 58 | except Exception: |
| 59 | return [] |
| 60 | |
| 61 | |
| 62 | def POST(request): |
| 63 | base = _base_dir() |
| 64 | today = str(request.get("today") or date.today().isoformat()) |
| 65 | period = today[:7] # calendar month, the cap's window |
| 66 | dry_run = _truthy(request.get("dry_run")) |
| 67 | config = object_stripe.stripe_config_from_env() |
| 68 | |
| 69 | try: |
| 70 | wallets = object_records.read_collection_records("wallets", base_dir=base) |
| 71 | except Exception: |
| 72 | return {"ok": True, "skipped": "billing not installed (wallets absent)"} |
| 73 | |
| 74 | entries = _entries(base) |
| 75 | by_wallet = {} |
| 76 | for row in entries: |
| 77 | by_wallet.setdefault(row.get("wallet_id"), []).append(row) |
| 78 | |
| 79 | charged = skipped = failed = 0 |
| 80 | results = [] |
| 81 | for wallet in wallets: |
| 82 | wallet_id = wallet.get("id") |
| 83 | if not _truthy(wallet.get("auto_replenish_enabled")) or \ |
| 84 | not _truthy(wallet.get("is_active") or "true"): |
| 85 | continue |
| 86 | |
| 87 | rows = by_wallet.get(wallet_id, []) |
| 88 | balance = sum(_int(r.get("amount_minor")) for r in rows) |
| 89 | threshold = _int(wallet.get("auto_replenish_threshold_minor")) |
| 90 | amount = _int(wallet.get("auto_replenish_amount_minor")) |
| 91 | cap = _int(wallet.get("auto_replenish_monthly_cap_minor")) |
| 92 | |
| 93 | if balance >= threshold: |
| 94 | continue |
| 95 | if amount <= 0: |
| 96 | results.append({"wallet": wallet_id, "skipped": "no top-up amount set"}) |
| 97 | skipped += 1 |
| 98 | continue |
| 99 | |
| 100 | marker = f"auto_topup/{wallet_id}/{period}" |
| 101 | # Already topped up this month at this attempt count? The marker |
| 102 | # carries the running total so repeated top-ups in one month each |
| 103 | # get their own, while a replayed pass gets none. |
| 104 | this_month = sum(_int(r.get("amount_minor")) for r in rows |
| 105 | if r.get("kind") == "auto_topup" |
| 106 | and str(r.get("created_at") or "")[:7] == period) |
| 107 | if cap <= 0: |
| 108 | results.append({"wallet": wallet_id, |
| 109 | "skipped": "monthly cap is zero -- auto top-up is off"}) |
| 110 | skipped += 1 |
| 111 | continue |
| 112 | if this_month + amount > cap: |
| 113 | results.append({ |
| 114 | "wallet": wallet_id, "skipped": "monthly cap reached", |
| 115 | "capped_at_minor": cap, "already_this_month_minor": this_month, |
| 116 | "note": ("the cap did its job: a customer is not being charged " |
| 117 | "beyond what they agreed to this month"), |
| 118 | }) |
| 119 | skipped += 1 |
| 120 | continue |
| 121 | |
| 122 | attempt_marker = f"{marker}/{this_month + amount}" |
| 123 | if any(r.get("generated_from") == attempt_marker for r in rows): |
| 124 | skipped += 1 |
| 125 | continue |
| 126 | |
| 127 | if dry_run or not config.configured: |
| 128 | results.append({ |
| 129 | "wallet": wallet_id, "would_charge_minor": amount, |
| 130 | "balance_minor": balance, |
| 131 | "reason": "dry run" if dry_run else "Stripe not configured", |
| 132 | }) |
| 133 | skipped += 1 |
| 134 | continue |
| 135 | |
| 136 | customer = str(wallet.get("stripe_customer_id") or "").strip() |
| 137 | method = str(wallet.get("payment_method_ref") or "").strip() |
| 138 | if not customer or not method: |
| 139 | results.append({"wallet": wallet_id, |
| 140 | "skipped": "no saved card; top-up needs a payment method on file"}) |
| 141 | skipped += 1 |
| 142 | continue |
| 143 | |
| 144 | try: |
| 145 | intent = object_stripe.api_request( |
| 146 | config, "POST", "/v1/payment_intents", |
| 147 | { |
| 148 | "amount": amount, |
| 149 | "currency": "usd", |
| 150 | "customer": customer, |
| 151 | "payment_method": method, |
| 152 | "off_session": True, |
| 153 | "confirm": True, |
| 154 | "metadata": {"wallet_id": wallet_id, "period": period}, |
| 155 | }, |
| 156 | idempotency_key=attempt_marker, |
| 157 | ) |
| 158 | except object_stripe.StripeError as exc: |
| 159 | # Declines -- especially authentication_required, which an |
| 160 | # off-session charge cannot satisfy -- are reported, not |
| 161 | # retried. The customer needs a pay link, not a loop. |
| 162 | failed += 1 |
| 163 | results.append({"wallet": wallet_id, "failed": str(exc)[:160], |
| 164 | "next": "ask the customer to top up interactively"}) |
| 165 | continue |
| 166 | |
| 167 | object_records.create_collection_record( |
| 168 | "wallet_entries", |
| 169 | { |
| 170 | "wallet_id": wallet_id, |
| 171 | "amount_minor": str(amount), |
| 172 | "kind": "auto_topup", |
| 173 | "description": f"Automatic top-up ({period})", |
| 174 | "reference": str(intent.get("id") or ""), |
| 175 | "generated_from": attempt_marker, |
| 176 | "owner_id": wallet.get("owner_id", ""), |
| 177 | }, |
| 178 | base_dir=base, actor=ACTOR) |
| 179 | charged += 1 |
| 180 | results.append({"wallet": wallet_id, "charged_minor": amount, |
| 181 | "intent": intent.get("id"), "balance_was_minor": balance}) |
| 182 | |
| 183 | return {"ok": True, "charged": charged, "skipped": skipped, "failed": failed, |
| 184 | "period": period, "results": results} |