Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
wallet_replenish.py · 8.8 KB · 211 lines
1"""system_wallet_replenish -- top up a low wallet from the saved card.
2
3POST {today?, dry_run?} -- a daemon pass (schedulable hourly): for each
4wallet with auto top-up enabled and a balance under its threshold, charge
5the saved payment method off-session and record the credit.
6
7Three safeguards, and the middle one is the whole reason this object is
8written carefully rather than quickly:
9
101. **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".
162. **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. The marker is
20 Stripe's idempotency key, so the CARD is charged once even by two
21 overlapping passes; the CREDIT is protected by wallet_entries declaring
22 generated_from unique, so the second pass's entry is refused inside the
23 write lock and the pass reports "already credited" (the read-first check
24 alone let both passes credit one charge).
253. **Failure is reported, never retried blindly.** A declined card -- and
26 especially one needing authentication (SCA), which off-session charges
27 cannot satisfy -- disables nothing and loops nothing: it records the
28 attempt so a human (or a dunning email with a pay link) can act. A
29 retry loop against a declining card is how a business gets its
30 processor account flagged.
31
32Stripe is optional: unconfigured, the pass reports what it WOULD charge
33and writes nothing, so the rule can be tuned before any money moves.
34"""
35
36import os
37from datetime import date
38
39import object_records
40import object_stripe
41
42ACTOR = "system_wallet_replenish"
43
44
45def _base_dir():
46 return os.environ.get("DBBASIC_DATA_DIR", "data")
47
48
49def _int(value, default=0):
50 try:
51 return int(str(value or "0").strip() or default)
52 except (TypeError, ValueError):
53 return default
54
55
56def _truthy(value):
57 return str(value or "").strip().lower() in ("true", "1", "yes", "on")
58
59
60def _entries(base):
61 """The ledger, or None when it cannot be read.
62
63 It used to fold a read error to "no entries", which reads as a zero
64 balance, nothing topped up this month and no marker: every wallet
65 would be charged, uncapped by what was already charged this month.
66 """
67 try:
68 return object_records.read_collection_records("wallet_entries", base_dir=base)
69 except Exception:
70 return None
71
72
73def POST(request):
74 base = _base_dir()
75 today = str(request.get("today") or date.today().isoformat())
76 period = today[:7] # calendar month, the cap's window
77 dry_run = _truthy(request.get("dry_run"))
78 config = object_stripe.stripe_config_from_env()
79
80 try:
81 wallets = object_records.read_collection_records("wallets", base_dir=base)
82 except Exception:
83 return {"ok": True, "skipped": "billing not installed (wallets absent)"}
84
85 entries = _entries(base)
86 if entries is None:
87 # A definite non-answer: charge nobody. The next pass tries again.
88 return {"ok": False, "charged": 0, "period": period,
89 "error": ("the wallet ledger is unreadable, so balances, this "
90 "month's top-ups and the replay markers are all "
91 "unknown; nothing was charged")}
92 by_wallet = {}
93 for row in entries:
94 by_wallet.setdefault(row.get("wallet_id"), []).append(row)
95
96 charged = skipped = failed = 0
97 results = []
98 for wallet in wallets:
99 wallet_id = wallet.get("id")
100 if not _truthy(wallet.get("auto_replenish_enabled")) or \
101 not _truthy(wallet.get("is_active") or "true"):
102 continue
103
104 rows = by_wallet.get(wallet_id, [])
105 balance = sum(_int(r.get("amount_minor")) for r in rows)
106 threshold = _int(wallet.get("auto_replenish_threshold_minor"))
107 amount = _int(wallet.get("auto_replenish_amount_minor"))
108 cap = _int(wallet.get("auto_replenish_monthly_cap_minor"))
109
110 if balance >= threshold:
111 continue
112 if amount <= 0:
113 results.append({"wallet": wallet_id, "skipped": "no top-up amount set"})
114 skipped += 1
115 continue
116
117 marker = f"auto_topup/{wallet_id}/{period}"
118 # Already topped up this month at this attempt count? The marker
119 # carries the running total so repeated top-ups in one month each
120 # get their own, while a replayed pass gets none.
121 this_month = sum(_int(r.get("amount_minor")) for r in rows
122 if r.get("kind") == "auto_topup"
123 and str(r.get("created_at") or "")[:7] == period)
124 if cap <= 0:
125 results.append({"wallet": wallet_id,
126 "skipped": "monthly cap is zero -- auto top-up is off"})
127 skipped += 1
128 continue
129 if this_month + amount > cap:
130 results.append({
131 "wallet": wallet_id, "skipped": "monthly cap reached",
132 "capped_at_minor": cap, "already_this_month_minor": this_month,
133 "note": ("the cap did its job: a customer is not being charged "
134 "beyond what they agreed to this month"),
135 })
136 skipped += 1
137 continue
138
139 attempt_marker = f"{marker}/{this_month + amount}"
140 if any(r.get("generated_from") == attempt_marker for r in rows):
141 skipped += 1
142 continue
143
144 if dry_run or not config.configured:
145 results.append({
146 "wallet": wallet_id, "would_charge_minor": amount,
147 "balance_minor": balance,
148 "reason": "dry run" if dry_run else "Stripe not configured",
149 })
150 skipped += 1
151 continue
152
153 customer = str(wallet.get("stripe_customer_id") or "").strip()
154 method = str(wallet.get("payment_method_ref") or "").strip()
155 if not customer or not method:
156 results.append({"wallet": wallet_id,
157 "skipped": "no saved card; top-up needs a payment method on file"})
158 skipped += 1
159 continue
160
161 try:
162 intent = object_stripe.api_request(
163 config, "POST", "/v1/payment_intents",
164 {
165 "amount": amount,
166 "currency": "usd",
167 "customer": customer,
168 "payment_method": method,
169 "off_session": True,
170 "confirm": True,
171 "metadata": {"wallet_id": wallet_id, "period": period},
172 },
173 idempotency_key=attempt_marker,
174 )
175 except object_stripe.StripeError as exc:
176 # Declines -- especially authentication_required, which an
177 # off-session charge cannot satisfy -- are reported, not
178 # retried. The customer needs a pay link, not a loop.
179 failed += 1
180 results.append({"wallet": wallet_id, "failed": str(exc)[:160],
181 "next": "ask the customer to top up interactively"})
182 continue
183
184 try:
185 object_records.create_collection_record(
186 "wallet_entries",
187 {
188 "wallet_id": wallet_id,
189 "amount_minor": str(amount),
190 "kind": "auto_topup",
191 "description": f"Automatic top-up ({period})",
192 "reference": str(intent.get("id") or ""),
193 "generated_from": attempt_marker,
194 "owner_id": wallet.get("owner_id", ""),
195 },
196 base_dir=base, actor=ACTOR)
197 except object_records.UniqueConstraintError:
198 # An overlapping pass credited this exact top-up while this one
199 # waited on Stripe. Stripe saw one idempotency key and charged
200 # once, and the ledger's unique marker (checked inside the
201 # write lock) has just refused the second credit: already done.
202 skipped += 1
203 results.append({"wallet": wallet_id, "skipped": "already credited",
204 "intent": intent.get("id")})
205 continue
206 charged += 1
207 results.append({"wallet": wallet_id, "charged_minor": amount,
208 "intent": intent.get("id"), "balance_was_minor": balance})
209
210 return {"ok": True, "charged": charged, "skipped": skipped, "failed": failed,
211 "period": period, "results": results}