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

0 downloads

dbbasic-object-server/object_promotions.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_promotions.py · 12.9 KB · 316 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_redemptions(promo: dict | None, redemptions: Iterable[dict],
223 customer_email: Any) -> list[dict]:
224 """This customer's uses of this promotion, matched case-insensitively
225 on the email -- the same address typed with a capital letter is the
226 same person, and a per-customer limit that Shift keys around is not a
227 limit."""
228 email = _text(customer_email).lower()
229 if not email:
230 return []
231 return [row for row in redemptions_of(promo, redemptions)
232 if _text(row.get("customer_email")).lower() == email]
233
234
235def blockers(promo: dict | None, subtotal_cents: Any, customer_email: Any,
236 redemptions: Iterable[dict], *, on_date: Any = "",
237 code: Any = "", others: Iterable[Any] = ()) -> list[str]:
238 """EVERY reason this code cannot be used, gathered in one pass.
239
240 A list of sentences, never a first-failure return. The full-report
241 rule is the same one action_checkout follows for prices, stock and
242 collection times, and it exists because a checkout that reveals one
243 problem at a time is a checkout people abandon.
244
245 Each sentence carries the NUMBER or the DATE that caused it. "This
246 code has expired" makes somebody write in; "this code ended on
247 2026-06-30" ends the conversation.
248 """
249 typed = normalize_code(code)
250 if promo is None:
251 return [f"There is no promotion with the code '{typed}'." if typed
252 else "No promotion code was given."]
253
254 day = _text(on_date)[:10]
255 subtotal = max(0, _int(subtotal_cents))
256 used = redemptions_of(promo, redemptions)
257 shown = normalize_code(promo.get("code")) or typed
258 reasons: list[str] = []
259
260 if not _active(promo):
261 reasons.append(f"The code {shown} is not active.")
262
263 starts = _text(promo.get("starts_on"))[:10]
264 if not _started(promo, day):
265 reasons.append(f"The code {shown} does not start until {starts}.")
266 if _ended(promo, day):
267 reasons.append(f"The code {shown} ended on "
268 f"{_text(promo.get('ends_on'))[:10]}.")
269
270 minimum = max(0, _int(promo.get("minimum_spend_cents")))
271 if minimum and subtotal < minimum:
272 reasons.append(f"The code {shown} needs a basket of at least "
273 f"{minimum / 100:.2f}; this one is {subtotal / 100:.2f}.")
274
275 cap = max(0, _int(promo.get("max_redemptions")))
276 if cap and len(used) >= cap:
277 reasons.append(f"The code {shown} has been used {len(used)} times and "
278 f"its limit is {cap}.")
279
280 per_customer = max(0, _int(promo.get("per_customer_limit")))
281 if per_customer:
282 mine = customer_redemptions(promo, used, customer_email)
283 if len(mine) >= per_customer:
284 reasons.append(
285 f"The code {shown} has already been used {len(mine)} times by "
286 f"{_text(customer_email)} and allows {per_customer} per "
287 f"customer.")
288
289 stacking = _text(promo.get("stacking")) or "never"
290 combined = [normalize_code(other) for other in others
291 if normalize_code(other) and normalize_code(other) != shown]
292 if combined and stacking == "never":
293 reasons.append(f"The code {shown} cannot be combined with "
294 f"{', '.join(sorted(set(combined)))}.")
295
296 return reasons
297
298
299def terms(promo: dict | None) -> dict:
300 """What gets STAMPED on the redemption row, so a later edit to the
301 promotion can never restate what somebody already got.
302
303 Doctrine #1, the same act as stamping a rate on an approved time entry
304 and a price on an invoice line. The redemption is the record of an
305 agreement; the promotion is only where the agreement was published.
306 """
307 if not promo:
308 return {}
309 return {
310 "promotion_id": _text(promo.get("id")),
311 "code_used": normalize_code(promo.get("code")),
312 "kind": _text(promo.get("kind")),
313 "value": str(_int(promo.get("value"))),
314 "minimum_spend_cents": str(_int(promo.get("minimum_spend_cents"))),
315 "stacking": _text(promo.get("stacking")) or "never",
316 }