~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/checkout-demo

A demo of knotless's review agent

0
0

Orders take a discount code

Open chadtmiller.com wants to merge into main from chadtmiller.com/checkout-demo:discount-codes
checkout.py+20−1
@@ -1,6 +1,7 @@
"""A cart's total and the order it becomes. Money is integer cents."""
import sqlite3
from datetime import date
def subtotal(items):
@@ -8,9 +9,27 @@ def subtotal(items):
return sum(item["price"] * item["quantity"] for item in items)
def place_order(db: sqlite3.Connection, customer_id: int, items) -> int:
def discount(db: sqlite3.Connection, code: str, amount: int):
"""What a discount code takes off `amount`: a percentage, or a fixed
number of cents, until the day it expires."""
row = db.execute(
"SELECT kind, value, expires FROM discounts WHERE code = ?", (code,)
).fetchone()
if row is None:
return 0
kind, value, expires = row
if date.fromisoformat(expires) < date.today():
return 0
if kind == "percent":
return amount * value // 100
checkout.pyline 24

No cap here: a percent value above 100 gives a discount larger than amount, and the total goes negative. Wrap it in min(..., amount).

return min(value, amount)
def place_order(db: sqlite3.Connection, customer_id: int, items, code=None) -> int:
"""Writes the order and returns its id."""
total = subtotal(items)
if code:
total -= discount(db, code, total)
cur = db.execute(
"INSERT INTO orders (customer_id, total) VALUES (?, ?)",
(customer_id, total),