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

9 downloads

dbbasic-object-server/object_promotions.py
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, 8 minutes ago History
object_promotions.py · 14.4 KB · 350 lines
1"""Promotions: a code, what it takes off, and every reason it cannot.
2
3The pure half of discounting, kept out of the objects so it can be tested
4exhaustively without a data directory -- the same posture as
5object_rates, object_billing, object_money and object_cart. Nothing here
6reads a file, writes a row or knows what a shop is; the object renders
7and writes, this module decides.
8
9**A code is a version, not a setting.** Promotions resolve the way rate
10cards do (object_rates.find_rate): the terms in force are the newest ones
11that had ALREADY STARTED, and resolution never looks forward. A code
12whose terms change in September must not restate August's baskets, and a
13September row must not discount an August order because somebody typed
14the same word. Two rows may therefore share a code -- that is a re-run of
15a campaign on new terms, and it is the ordinary case, not an error.
16
17**The terms are stamped at redemption.** What a promotion said when
18somebody used it belongs to the redemption, exactly as a rate belongs to
19the approved time entry and a price belongs to the invoice line. Editing
20the promotion next month then changes what the NEXT shopper gets and
21nothing else, which is the only behaviour a shop can defend when a
22customer emails asking why their receipt says 20% and the page says 10%.
23`terms()` is what the writer copies onto the row.
24
25**The count of redemptions is a fold over the redemptions.** promotions
26carries a redemptions_used caption, and it is a rollup over the same rows
27this module counts -- the identical argument wallets.balance_minor makes
28about wallet_entries. A gate that trusted the caption would authorise a
291001st use of a 1000-use code the moment that caption went stale, so
30`blockers` counts the rows.
31
32**Every reason at once.** `blockers` returns a LIST and never returns
33early. A shopper told their code has expired, who then finds a new one
34and is told the basket is too small, and then that they have already used
35it, is a shopper who has left. This is the same rule action_checkout
36follows for prices, stock and collection times, and it is easy to break
37by writing the obvious `if ...: return`.
38
39**Rounded once.** A percentage is applied to the whole discountable base
40and rounded a single time, for the reason object_cart.tax_cents states
41about tax: rounding per line accumulates a cent of error per row that
42nobody can reconcile, and the single rounding is the only version a
43customer can check with a calculator.
44"""
45
46from __future__ import annotations
47
48from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
49from typing import Any, Iterable
50
51# What a promotion can do. `value` means basis points for percent (2000 =
52# 20%), integer cents for fixed, and nothing at all for free_shipping --
53# the postage is whatever the postage is, and a "free shipping worth up to
54# $5" promotion is a fixed discount wearing a costume.
55KINDS = ("percent", "fixed", "free_shipping")
56
57STACKING = ("never", "with_others")
58
59
60def _text(value: Any) -> str:
61 return str(value if value is not None else "").strip()
62
63
64def _num(value: Any, default: int = 0) -> Decimal:
65 try:
66 return Decimal(_text(value) or str(default))
67 except (InvalidOperation, TypeError, ValueError):
68 return Decimal(default)
69
70
71def _int(value: Any, default: int = 0) -> int:
72 try:
73 return int(_text(value) or default)
74 except (TypeError, ValueError):
75 return default
76
77
78def _truthy(value: Any) -> bool:
79 return _text(value).lower() in ("true", "1", "yes", "on")
80
81
82def normalize_code(value: Any) -> str:
83 """A code as it is COMPARED: trimmed and upper-cased.
84
85 Case-insensitive at redemption because a code is something a human
86 retypes off a postcard, an email footer or a podcast advert, and
87 refusing `spring20` because the shop typed `SPRING20` is a shop
88 losing a sale to its own shift key. Stored as the seller wrote it,
89 compared as this function says.
90 """
91 return _text(value).upper()
92
93
94def _active(promo: dict) -> bool:
95 # Absent is_active means active: a promotion written without the flag
96 # is one somebody meant to run, same reading object_rates gives a rate
97 # card.
98 raw = promo.get("is_active")
99 return True if raw in (None, "") else _truthy(raw)
100
101
102def _started(promo: dict, day: str) -> bool:
103 starts = _text(promo.get("starts_on"))[:10]
104 return not (starts and day and starts > day)
105
106
107def _ended(promo: dict, day: str) -> bool:
108 ends = _text(promo.get("ends_on"))[:10]
109 return bool(ends and day and ends < day)
110
111
112def resolve(code: Any, promotions: list[dict], *, on_date: Any) -> dict | None:
113 """The promotion this code names on this day, or None.
114
115 NEVER LOOKS FORWARD. Where several rows share a code -- a campaign
116 re-run on new terms -- the answer is the newest one that had already
117 started on `on_date`, exactly as object_rates picks the newest card
118 already in force. Picking the future row would discount today's
119 basket at terms nobody has published yet.
120
121 When NO row has started, the soonest-starting one is returned anyway
122 rather than None, and that is deliberate: `blockers` has to be able
123 to say "that code starts on the 3rd of June" instead of "no such
124 code". A refusal that names the date keeps the customer; a refusal
125 that denies the code exists sends them to support.
126
127 Matching is case-insensitive (see normalize_code). Expiry is NOT
128 filtered here for the same reason a future start is not: an expired
129 code must be refused with its end date, and a resolver that returned
130 None could only say the code was wrong.
131 """
132 wanted = normalize_code(code)
133 if not wanted:
134 return None
135 day = _text(on_date)[:10]
136
137 matches = [row for row in promotions
138 if normalize_code(row.get("code")) == wanted]
139 if not matches:
140 return None
141
142 def _order(row: dict) -> tuple[str, str]:
143 return (_text(row.get("starts_on"))[:10], _text(row.get("id")))
144
145 in_force = [row for row in matches if _started(row, day)]
146 if in_force:
147 return max(in_force, key=_order)
148 # Nothing has started yet: hand back the one that starts soonest so the
149 # refusal can name its date.
150 return min(matches, key=_order)
151
152
153def applies_to(promo: dict | None) -> str:
154 """Which half of the bill this promotion comes off: "goods" or
155 "shipping".
156
157 It matters because tax does. A discount on goods reduces the taxable
158 base; free postage reduces the postage, and where a jurisdiction taxes
159 delivery it reduces that tax too. One string, read once, so
160 object_cart.checkout_totals does not have to know what a promotion is.
161 """
162 if promo and _text(promo.get("kind")) == "free_shipping":
163 return "shipping"
164 return "goods"
165
166
167def discount_for(subtotal_cents: Any, shipping_cents: Any,
168 promo: dict | None) -> int:
169 """What this promotion takes off, in whole cents, ROUNDED ONCE.
170
171 Applied to the whole base rather than per line, for the reason
172 object_cart.tax_cents gives about tax: four separately-rounded lines
173 accumulate an error nobody can reconcile against the percentage
174 printed on the receipt.
175
176 CLAMPED TO THE BASE IT COMES OFF, always. A $50 code against a $30
177 basket takes off $30 and not a cent more -- a shop does not owe money
178 to somebody for shopping, and a negative total would propagate into an
179 invoice, a payment and eventually a refund of money nobody paid. The
180 clamp lives here rather than in the caller so that every caller gets
181 it, including the ones written later.
182 """
183 if not promo:
184 return 0
185 kind = _text(promo.get("kind"))
186 subtotal = max(0, _int(subtotal_cents))
187 postage = max(0, _int(shipping_cents))
188
189 if kind == "free_shipping":
190 return postage
191 if kind == "fixed":
192 return min(max(0, _int(promo.get("value"))), subtotal)
193 if kind == "percent":
194 bps = max(0, _int(promo.get("value")))
195 if not bps or not subtotal:
196 return 0
197 cut = (Decimal(subtotal) * Decimal(bps) / Decimal(10000)).to_integral_value(
198 rounding=ROUND_HALF_UP)
199 return min(int(cut), subtotal)
200 # An unknown kind discounts nothing. A promotion whose terms cannot be
201 # read must not guess in the customer's favour or the shop's.
202 return 0
203
204
205def redemptions_of(promo: dict | None, redemptions: Iterable[dict]) -> list[dict]:
206 """Every row recording a use of this promotion.
207
208 Folded, never counted from promotions.redemptions_used: that number is
209 a rollup over exactly these rows, and a gate that reads a derived
210 caption it could recompute is a gate that authorises the 1001st use of
211 a 1000-use code the moment the caption goes stale. Identical argument
212 to hook_wallet_entries summing the ledger instead of reading the
213 wallet's balance.
214 """
215 if not promo:
216 return []
217 promotion_id = _text(promo.get("id"))
218 return [row for row in redemptions
219 if _text(row.get("promotion_id")) == promotion_id]
220
221
222def customer_key(email: Any) -> str:
223 """The person a per-customer limit counts, from an email address.
224
225 Lower-cased and trimmed (the same address with a capital letter is the
226 same person), and with any plus-tag stripped from the local part:
227 `ada+spring@example.com` and `ada@example.com` are one mailbox, and a
228 limit that a `+1`, `+2`... suffix walks around is not a limit.
229
230 Deliberately NOT done: removing dots from the local part (only some
231 providers ignore them, and treating `a.b@` and `ab@` as one person
232 would refuse two real people at the others), or following domain
233 aliases. A determined shopper with a second mailbox is out of scope
234 for an email-keyed limit; a casual `+tag` or Shift key is not.
235 Stored rows keep the address as typed; both sides are keyed here at
236 comparison time, so rows written before this rule are counted too.
237 """
238 text = _text(email).lower()
239 local, at, domain = text.rpartition("@")
240 if not at:
241 return text
242 return local.split("+", 1)[0] + "@" + domain
243
244
245def customer_redemptions(promo: dict | None, redemptions: Iterable[dict],
246 customer_email: Any) -> list[dict]:
247 """This customer's uses of this promotion, matched on customer_key."""
248 key = customer_key(customer_email)
249 if not key:
250 return []
251 return [row for row in redemptions_of(promo, redemptions)
252 if customer_key(row.get("customer_email")) == key]
253
254
255def capacity_blockers(promo: dict | None, customer_email: Any,
256 redemptions: Iterable[dict]) -> list[str]:
257 """The reasons a code is USED UP: its overall cap and its per-customer
258 limit, nothing else. The one place those two rules are written; both
259 `blockers` (the early, advisory answer) and the schema's locked check
260 (the answer inside the write lock) call it, so they cannot drift."""
261 if promo is None:
262 return []
263 used = redemptions_of(promo, redemptions)
264 shown = normalize_code(promo.get("code"))
265 reasons: list[str] = []
266 cap = max(0, _int(promo.get("max_redemptions")))
267 if cap and len(used) >= cap:
268 reasons.append(f"The code {shown} has been used {len(used)} times and "
269 f"its limit is {cap}.")
270 per_customer = max(0, _int(promo.get("per_customer_limit")))
271 if per_customer:
272 mine = customer_redemptions(promo, used, customer_email)
273 if len(mine) >= per_customer:
274 reasons.append(
275 f"The code {shown} has already been used {len(mine)} times by "
276 f"{_text(customer_email)} and allows {per_customer} per "
277 f"customer.")
278 return reasons
279
280
281def blockers(promo: dict | None, subtotal_cents: Any, customer_email: Any,
282 redemptions: Iterable[dict], *, on_date: Any = "",
283 code: Any = "", others: Iterable[Any] = ()) -> list[str]:
284 """EVERY reason this code cannot be used, gathered in one pass.
285
286 A list of sentences, never a first-failure return. The full-report
287 rule is the same one action_checkout follows for prices, stock and
288 collection times, and it exists because a checkout that reveals one
289 problem at a time is a checkout people abandon.
290
291 Each sentence carries the NUMBER or the DATE that caused it. "This
292 code has expired" makes somebody write in; "this code ended on
293 2026-06-30" ends the conversation.
294 """
295 typed = normalize_code(code)
296 if promo is None:
297 return [f"There is no promotion with the code '{typed}'." if typed
298 else "No promotion code was given."]
299
300 day = _text(on_date)[:10]
301 subtotal = max(0, _int(subtotal_cents))
302 used = redemptions_of(promo, redemptions)
303 shown = normalize_code(promo.get("code")) or typed
304 reasons: list[str] = []
305
306 if not _active(promo):
307 reasons.append(f"The code {shown} is not active.")
308
309 starts = _text(promo.get("starts_on"))[:10]
310 if not _started(promo, day):
311 reasons.append(f"The code {shown} does not start until {starts}.")
312 if _ended(promo, day):
313 reasons.append(f"The code {shown} ended on "
314 f"{_text(promo.get('ends_on'))[:10]}.")
315
316 minimum = max(0, _int(promo.get("minimum_spend_cents")))
317 if minimum and subtotal < minimum:
318 reasons.append(f"The code {shown} needs a basket of at least "
319 f"{minimum / 100:.2f}; this one is {subtotal / 100:.2f}.")
320
321 reasons.extend(capacity_blockers(promo, customer_email, used))
322
323 stacking = _text(promo.get("stacking")) or "never"
324 combined = [normalize_code(other) for other in others
325 if normalize_code(other) and normalize_code(other) != shown]
326 if combined and stacking == "never":
327 reasons.append(f"The code {shown} cannot be combined with "
328 f"{', '.join(sorted(set(combined)))}.")
329
330 return reasons
331
332
333def terms(promo: dict | None) -> dict:
334 """What gets STAMPED on the redemption row, so a later edit to the
335 promotion can never restate what somebody already got.
336
337 Doctrine #1, the same act as stamping a rate on an approved time entry
338 and a price on an invoice line. The redemption is the record of an
339 agreement; the promotion is only where the agreement was published.
340 """
341 if not promo:
342 return {}
343 return {
344 "promotion_id": _text(promo.get("id")),
345 "code_used": normalize_code(promo.get("code")),
346 "kind": _text(promo.get("kind")),
347 "value": str(_int(promo.get("value"))),
348 "minimum_spend_cents": str(_int(promo.get("minimum_spend_cents"))),
349 "stacking": _text(promo.get("stacking")) or "never",
350 }