{body}{MENU_SCRIPT}'''
class App(BaseHTTPRequestHandler):
server_version = "FreshDirectOffline/1.0"
def log_message(self, fmt, *args):
sys.stderr.write(f"{self.log_date_time_string()} - {fmt % args}\n")
def session_setup(self):
self.backend, self.auth = services()
cookie = SimpleCookie(self.headers.get("Cookie", ""))
m = cookie.get(self.backend.config.cookie_name)
old = m.value if m else None
self.token, self.session = self.auth.ensure_session(old)
self.set_cookie = old != self.token
self.owner = self.auth.session_owner_digest(self.token)
with self.backend.lifecycle.connection(transaction=True) as db:
if self.session.get("authenticated"):
self.owner = self.account_owner(db, self.session["account"]["account_id"])
db.execute(
"INSERT OR IGNORE INTO fd_state(owner,updated) VALUES(?,?)",
(self.owner, stamp()),
)
self.state = dict(
db.execute(
"SELECT * FROM fd_state WHERE owner=?", (self.owner,)
).fetchone()
)
self.count = int(
db.execute(
"SELECT COALESCE(SUM(qty),0) FROM fd_cart WHERE owner=?",
(self.owner,),
).fetchone()[0]
)
self.favs = {
r[0]
for r in db.execute(
"SELECT product_id FROM fd_favorites WHERE owner=?", (self.owner,)
)
}
def send(self, status, data, mime="text/html; charset=utf-8", headers=None):
if isinstance(data, str):
data = data.encode()
self.send_response(status)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
if getattr(self, "set_cookie", False):
options = self.backend.session_cookie
attributes = [
f"{options['name']}={self.token}",
f"Path={options['path']}",
f"SameSite={options['samesite']}",
]
if options["secure"]:
attributes.append("Secure")
if options["httponly"]:
attributes.append("HttpOnly")
self.send_header("Set-Cookie", "; ".join(attributes))
for k, v in (headers or {}).items():
self.send_header(k, v)
self.end_headers()
if self.command != "HEAD":
self.wfile.write(data)
def page(self, title, body, q=""):
notice = parse_qs(urlparse(self.path).query).get("notice", [])
if notice:
body = f'
{esc(notice[-1])}
' + body
self.send(200, shell(title, body, self.session, self.state, self.count, q))
def redirect(self, path, msg=""):
if msg:
path += ("&" if "?" in path else "?") + urlencode({"notice": msg})
self.send(303, b"", "text/plain", {"Location": path})
def return_path(self, fallback):
raw = self.headers.get("Referer", "")
parsed = urlparse(raw)
if raw.startswith("/") and not raw.startswith("//"):
return raw
if parsed.scheme in {"http", "https"} and parsed.netloc == self.headers.get(
"Host"
):
return parsed.path + (f"?{parsed.query}" if parsed.query else "")
return fallback
def form(self):
try:
n = int(self.headers.get("Content-Length", "0"))
except ValueError:
raise FormError(400, "Invalid Content-Length")
if n < 0:
raise FormError(400, "Invalid Content-Length")
if n > 100000:
raise FormError(413, "Form body is too large")
content_type = self.headers.get_content_type()
if content_type != "application/x-www-form-urlencoded":
raise FormError(415, "Expected URL-encoded form data")
try:
body = self.rfile.read(n).decode("utf-8")
except UnicodeDecodeError:
raise FormError(400, "Form body must be valid UTF-8")
return {k: v[-1] for k, v in parse_qs(body, keep_blank_values=True).items()}
def cart_rows(self):
with self.backend.lifecycle.connection() as db:
rows = db.execute(
"SELECT * FROM fd_cart WHERE owner=? ORDER BY product_id", (self.owner,)
).fetchall()
return [(BY_ID[r["product_id"]], r) for r in rows if r["product_id"] in BY_ID]
def totals(self, rows):
sub = sum(
p["price"] * r["qty"]
for p, r in rows
if product_available(p, self.state)
)
disc = (
sub * 0.1
if self.state["coupon"] == "FRESH10"
else min(50, sub)
if self.state["coupon"] == "NEW50"
and sub >= 99
and self.new50_eligible()
else 0
)
mode = self.state["fulfillment"]
fee = (
0
if mode == "pickup" or (mode == "delivery" and sub >= 99)
else 9.99
if mode == "express"
else 5.99
)
return sub, disc, fee, max(0, sub - disc + fee)
def new50_eligible(self):
if not self.session.get("authenticated"):
return True
account_id = self.session["account"]["account_id"]
with self.backend.lifecycle.connection() as db:
prior_order = db.execute(
"SELECT 1 FROM fd_orders WHERE account_id=? LIMIT 1", (account_id,)
).fetchone()
return prior_order is None
def account_owner(self, db: sqlite3.Connection, account_id):
"""A login token rotates; the account's grocery state must not."""
owner = "account:" + account_id
# Adopt rows written by older reference versions, including revoked sessions.
# The enclosing lifecycle transaction makes adoption safe to repeat.
sessions = db.execute(
"SELECT session_digest FROM local_auth_sessions WHERE account_id=? "
"ORDER BY created_at,session_digest", (account_id,)
).fetchall()
for session in sessions:
self.merge_owner_state(db, session["session_digest"], owner)
return owner
def rotate_owner_state(self, db: sqlite3.Connection, old, new):
account = db.execute(
"SELECT account_id FROM local_auth_sessions WHERE session_digest=?", (new,)
).fetchone()
if not account or not account["account_id"]:
raise ValueError("Authenticated session has no account")
owner = self.account_owner(db, account["account_id"])
previous = db.execute(
"SELECT account_id FROM local_auth_sessions WHERE session_digest=?", (old,)
).fetchone()
# Anonymous shopping transfers on sign-in. Another account's state never does.
if not previous or not previous["account_id"]:
self.merge_owner_state(db, old, owner)
def merge_owner_state(self, db: sqlite3.Connection, old, new):
if old == new:
return
for table in ("fd_cart", "fd_favorites"):
rows = db.execute(f"SELECT * FROM {table} WHERE owner=?", (old,)).fetchall()
for row in rows:
if table == "fd_cart":
db.execute(
"INSERT INTO fd_cart VALUES(?,?,?,?) "
"ON CONFLICT(owner,product_id) DO UPDATE SET "
"qty=MIN(20,fd_cart.qty+excluded.qty),"
"substitution=excluded.substitution",
(new, row["product_id"], row["qty"], row["substitution"]),
)
else:
db.execute(
"INSERT OR IGNORE INTO fd_favorites VALUES(?,?)",
(new, row["product_id"]),
)
db.execute(f"DELETE FROM {table} WHERE owner=?", (old,))
db.execute("UPDATE fd_support SET owner=? WHERE owner=?", (new, old))
state = db.execute("SELECT * FROM fd_state WHERE owner=?", (old,)).fetchone()
if state:
existing = db.execute("SELECT * FROM fd_state WHERE owner=?", (new,)).fetchone()
# Coupon choice is independent of delivery. A coupon-only anonymous
# cart must not clear a returning account's ZIP, slot or address.
if existing and not (state["zip"] or state["address"] != "{}"):
if state["coupon"]:
db.execute("UPDATE fd_state SET coupon=?,updated=? WHERE owner=?",
(state["coupon"], stamp(), new))
db.execute("DELETE FROM fd_state WHERE owner=?", (old,))
return
db.execute(
"INSERT OR REPLACE INTO fd_state VALUES(?,?,?,?,?,?,?)",
(
new,
state["zip"],
state["fulfillment"],
state["slot"],
state["coupon"],
state["address"],
stamp(),
),
)
db.execute("DELETE FROM fd_state WHERE owner=?", (old,))
def valid_address(self):
try:
address = json.loads(self.state["address"] or "{}")
except json.JSONDecodeError:
return None
if (
all(address.get(key) for key in ("name", "street", "city", "state", "zip"))
and address.get("zip") == self.state.get("zip")
and address.get("state", "").upper() == "NY"
and address.get("zip") in SERVICE_AREAS
):
return address
return None
def do_GET(self):
path = urlparse(self.path).path
if path == "/static/styles.css":
stylesheet = ROOT / "static" / "styles.css"
if not stylesheet.is_file():
return self.send(404, "Not found")
return self.send(200, stylesheet.read_bytes(), "text/css; charset=utf-8")
if path.startswith("/static/assets/"):
name = path.rsplit("/", 1)[-1]
if not re.fullmatch(r"[a-z0-9-]+\.png", name):
return self.send(404, "Not found")
asset = ROOT / "static" / "assets" / name
if not asset.is_file():
return self.send(404, "Not found")
return self.send(200, asset.read_bytes(), "image/png")
if path == "/favicon.ico":
return self.send(204, b"", "image/x-icon")
if path in ("/healthz", "/__websitebench/health"):
backend, _ = services()
return self.send(
200,
json.dumps(
{
"status": "ok",
"site_id": "freshdirect",
"database": backend.lifecycle.health()["status"],
}
),
"application/json",
)
self.session_setup()
qs = parse_qs(urlparse(self.path).query)
if path == "/":
def shelf(title, items, href):
return f'
{shortcut_html}{shelf("Popular now", PRODUCTS[:12], "/search")}{shelf("Fresh Deals: The week's best for less", [p for p in PRODUCTS if p["sale"]][:10], "/search?deal=1")}
Now accepting SNAP/EBT
Fresh food should be within reach
Shop pantry essentials, dairy, produce, and more with local SNAP eligibility indicators.
'
heading = f"{esc(title)} ({len(items)})"
promo = (
''
if items
else ""
)
return self.page(
title,
f'
{heading}
{filters}{promo}{"".join(card(p, self.favs, self.state) for p in items) if items else empty}',
q,
)
if path.startswith("/product/"):
p = BY_ID.get(path.rsplit("/", 1)[-1])
if not p:
return self.not_found()
choices = "".join(f"" for i in range(1, 7))
available = product_available(p, self.state)
disabled = "" if available else " disabled"
area = service_area(self.state)
availability = (
f'Available in {esc(area["label"])}'
if available and area
else f'Unavailable for Express in {esc(area["label"])} (limited assortment)'
if area
and self.state.get("fulfillment") == "express"
and p["id"] not in EXPRESS_PRODUCT_IDS
else f'Currently unavailable in {esc(area["label"])}'
if area and not available
else "Set a supported ZIP to confirm availability"
)
gallery = f'
{product_media(p, True)}
'
if p["id"] == "p001":
gallery += '
'
if p["id"] == "p001":
variant_options = []
variant_labels = {
"classic": "Classic pack",
"organic": "Organic pack",
"family": "Organic family pack",
}
for value, product_id in PRODUCT_VARIANTS[p["id"]].items():
variant = BY_ID[product_id]
variant_options.append(
f''
)
variant_control = (
'"
)
else:
variant_control = ""
description = {
"produce": "Selected for ripe flavor and inspected for freshness. Keep refrigerated and rinse before serving.",
"dairy-eggs": "A refrigerated grocery item with clear pack sizing for meal planning.",
"bakery": "A ready-to-enjoy bakery item; serving size and storage directions appear on the package.",
"frozen": "Ships frozen. Keep frozen until preparation and follow the package cooking directions.",
"beverages": "A packaged beverage with the stated container size and serving information.",
"pantry": "A shelf-stable grocery item; check the package for serving and storage directions.",
"prepared": "Prepared for convenient serving; refrigerate promptly and follow the package directions.",
"meat-seafood": "Keep refrigerated and cook to the safe temperature printed on the package.",
}[p["category"]]
nutrition = (
"One cup of raw blueberries provides about 84 calories, 3.6 g fiber, and 14.7 g naturally occurring sugars."
if "blueberr" in p["name"].casefold() and p["category"] == "produce"
else "Nutrition varies by serving. Consult the package label for calories, allergens, and daily values."
)
ingredients = (
"Blueberries."
if "blueberr" in p["name"].casefold() and p["category"] == "produce"
else "See the sealed package label for the complete ingredient and allergen statement."
)
express_copy = (
'
EXPRESS available for this location
'
if area
and "express" in area["modes"]
and product_available(p, self.state, "express")
else ""
)
detail_script = ''''''
body = f'''
{detail_script}'''
return self.page(p["name"], body)
if path == "/favorites":
items = [BY_ID[x] for x in sorted(self.favs) if x in BY_ID]
body = (
'
Your Shopping Lists
Saved separately from your cart.
'
+ (
'{"".join(card(p,self.favs,self.state) for p in items)}'
if False
else (
""
+ "".join(card(p, self.favs, self.state) for p in items)
+ ""
if items
else '
""",
)
if path == "/register":
if self.session["authenticated"]:
return self.redirect("/account", "You already have a local account")
return self.page("Create a local account", self.registration_page())
if path == "/recover":
if self.session["authenticated"]:
return self.redirect("/account", "You are already signed in")
return self.page("Recover local access", self.recovery_page())
if path == "/account":
if not self.session["authenticated"]:
return self.redirect("/signin", "Sign in to view your account")
a = self.session["account"]
return self.page(
"Your account",
f"""
""",
)
if path == "/orders":
if not self.session["authenticated"]:
return self.redirect("/signin", "Sign in to see past orders")
with self.backend.lifecycle.connection() as db:
rows = db.execute(
"SELECT * FROM fd_orders WHERE account_id=?",
(self.session["account"]["account_id"],),
).fetchall()
cards = []
for r in rows:
names = ", ".join(
BY_ID[x[0]]["name"] for x in json.loads(r["items"]) if x[0] in BY_ID
)
cards.append(
f'{esc(r["status"])}
'
+ "".join(cards),
)
if path.startswith("/orders/"):
if not self.session["authenticated"]:
return self.redirect("/signin", "Sign in to see past orders")
order_id = path.rsplit("/", 1)[-1]
with self.backend.lifecycle.connection() as db:
row = db.execute(
"SELECT * FROM fd_orders WHERE order_id=? AND account_id=?",
(order_id, self.session["account"]["account_id"]),
).fetchone()
if not row:
return self.not_found()
return self.page(f"Order {order_id}", self.order_detail_page(row))
if path == "/support":
with self.backend.lifecycle.connection() as db:
requests = db.execute(
"SELECT * FROM fd_support WHERE owner=? ORDER BY id DESC",
(self.owner,),
).fetchall()
cards = "".join(
f'{esc(row["status"])}'
f'
{esc(row["topic"])}
{esc(row["details"])}
'
f'{esc(row["created"])}'
+ (
f''
if row["status"] != "Cancelled locally"
else ""
)
+ ""
for row in requests
)
return self.page(
"Local support requests",
'
Local support requests
These records stay in this sandbox; no message is sent.
Answers for shopping, delivery, substitutions, and recovery.
How do I place an order?
Browse or search, choose products, review the cart, then select delivery. This clone stops before submission.
How do substitutions work?
Choose the best replacement, request contact, or decline substitutions per item.
What delivery options exist?
Standard delivery uses tomorrow two-hour windows and the full local assortment. Express uses a limited assortment and today’s one-hour 6–7 PM window. ZIP 11201 pickup uses tomorrow’s 10 AM–12 PM window.
What is DeliveryPass?
The source promotes delivery membership benefits. Membership enrollment and billing are intentionally unavailable in this local sandbox.
""",
)
return self.not_found()
def do_HEAD(self):
return self.do_GET()
def do_POST(self):
self.session_setup()
path = urlparse(self.path).path
try:
f = self.form()
if path == "/location":
zip_code = f.get("zip", "")
mode = f.get("fulfillment", "")
if not re.fullmatch(r"\d{5}", zip_code) or mode not in {
"delivery",
"pickup",
}:
raise ValueError("Enter a valid five-digit ZIP")
area = SERVICE_AREAS.get(zip_code)
if not area:
raise ValueError(
f"ZIP {zip_code} is not in the local service area; try synthetic ZIP 11201 or 10001"
)
if mode not in area["modes"]:
raise ValueError(f"{FULFILLMENT_LABELS[mode]} is unavailable in {area['label']}")
try:
old_address = json.loads(self.state["address"] or "{}")
except json.JSONDecodeError:
old_address = {}
address = old_address if old_address.get("zip") == zip_code else {}
with self.backend.lifecycle.connection(transaction=True) as db:
db.execute(
"UPDATE fd_state SET zip=?,fulfillment=?,slot='',address=?,updated=? WHERE owner=?",
(zip_code, mode, json.dumps(address), stamp(), self.owner),
)
return self.redirect("/", f"{area['label']} service area updated")
if path == "/cart/add":
p = BY_ID.get(f.get("product_id", ""))
variants = PRODUCT_VARIANTS.get(p["id"] if p else "")
if variants and f.get("variant"):
p = BY_ID.get(variants.get(f["variant"], ""))
qty = int(f.get("qty", "1"))
sub = f.get("substitution", "best")
if not p or qty not in range(1, 21) or sub not in {
"best",
"contact",
"none",
}:
raise ValueError("That item or option is unavailable")
if not p["available"]:
raise ValueError("That item or option is unavailable")
if not product_available(p, self.state):
raise ValueError("That item is unavailable for this location")
with self.backend.lifecycle.connection(transaction=True) as db:
db.execute(
"INSERT INTO fd_cart VALUES(?,?,?,?) ON CONFLICT(owner,product_id) DO UPDATE SET qty=MIN(20,fd_cart.qty+excluded.qty),substitution=excluded.substitution",
(self.owner, p["id"], qty, sub),
)
return self.redirect(self.return_path("/cart"), f"{p['name']} added")
if path == "/cart/update":
pid = f.get("product_id", "")
qty = int(f.get("qty", "1"))
sub = f.get("substitution", "best")
if (
pid not in BY_ID
or qty not in range(0, 21)
or sub not in {"best", "contact", "none"}
):
raise ValueError("Invalid cart update")
with self.backend.lifecycle.connection(transaction=True) as db:
if qty == 0:
db.execute(
"DELETE FROM fd_cart WHERE owner=? AND product_id=?",
(self.owner, pid),
)
else:
db.execute(
"UPDATE fd_cart SET qty=?,substitution=? WHERE owner=? AND product_id=?",
(qty, sub, self.owner, pid),
)
return self.redirect("/cart", "Cart updated")
if path == "/favorite/toggle":
pid = f.get("product_id", "")
if pid not in BY_ID:
raise ValueError("Unknown product")
with self.backend.lifecycle.connection(transaction=True) as db:
if db.execute(
"SELECT 1 FROM fd_favorites WHERE owner=? AND product_id=?",
(self.owner, pid),
).fetchone():
db.execute(
"DELETE FROM fd_favorites WHERE owner=? AND product_id=?",
(self.owner, pid),
)
else:
db.execute(
"INSERT INTO fd_favorites VALUES(?,?)", (self.owner, pid)
)
return self.redirect(
self.return_path("/favorites"), "Shopping list updated"
)
if path == "/coupon":
code = f.get("coupon", "").upper()
if code not in {"FRESH10", "NEW50"}:
return self.redirect("/cart", "Promotion unavailable")
subtotal, *_ = self.totals(self.cart_rows())
if code == "NEW50" and not self.new50_eligible():
return self.redirect(
"/cart", "Promotion NEW50 is available on first orders only"
)
if code == "NEW50" and subtotal < 99:
return self.redirect(
"/cart", "Promotion NEW50 requires a $99 subtotal"
)
with self.backend.lifecycle.connection(transaction=True) as db:
db.execute(
"UPDATE fd_state SET coupon=?,updated=? WHERE owner=?",
(code, stamp(), self.owner),
)
return self.redirect("/cart", f"Promotion {code} applied")
if path == "/fulfillment":
mode = f.get("fulfillment", "")
slot = f.get("slot", "")
area = service_area(self.state)
if (
not area
or mode not in area["modes"]
or slot not in SLOTS_BY_MODE.get(mode, frozenset())
):
raise ValueError("Choose a valid method and time")
if mode in {"delivery", "express"} and not self.valid_address():
raise ValueError(
"Save a supported delivery address before choosing a delivery time"
)
if any(
not product_available(product, self.state, mode)
for product, _ in self.cart_rows()
):
raise ValueError(
"Remove items unavailable for the selected fulfillment method"
)
with self.backend.lifecycle.connection(transaction=True) as db:
db.execute(
"UPDATE fd_state SET fulfillment=?,slot=?,updated=? WHERE owner=?",
(mode, slot, stamp(), self.owner),
)
return self.redirect("/checkout", "Fulfillment saved")
if path == "/address":
a = {
k: f.get(k, "").strip()
for k in ("name", "street", "city", "state", "zip")
}
if any(not x for x in a.values()) or not re.fullmatch(
r"\d{5}", a["zip"]
):
raise ValueError("Complete every address field")
if a["state"].upper() != "NY" or a["zip"] not in SERVICE_AREAS:
raise ValueError(
"That address is not in the local service area; use a supported New York synthetic address"
)
a["state"] = "NY"
area = SERVICE_AREAS[a["zip"]]
mode = self.state["fulfillment"]
if mode not in area["modes"] or mode == "pickup":
mode = "delivery"
slot = self.state["slot"] if a["zip"] == self.state["zip"] else ""
with self.backend.lifecycle.connection(transaction=True) as db:
db.execute(
"UPDATE fd_state SET address=?,zip=?,fulfillment=?,slot=?,updated=? WHERE owner=?",
(json.dumps(a), a["zip"], mode, slot, stamp(), self.owner),
)
return self.redirect("/checkout", "Synthetic address saved")
if path == "/signin":
result = self.auth.sign_in(
self.token,
email=f.get("email", ""),
password=f.get("password", ""),
session_rotation_callback=self.rotate_owner_state,
)
self.token = result["session_token"]
self.set_cookie = True
return self.redirect("/account", "Signed in locally")
if path == "/register":
self.auth.start_registration(
self.token,
email=f.get("email", ""),
display_name=f.get("display_name", ""),
password=f.get("password", ""),
)
return self.redirect(
"/register", "Local verification challenge created; no email was sent"
)
if path == "/register/verify":
self.auth.verify_registration_code(self.token, f.get("code", ""))
result = self.auth.complete_registration(
self.token, session_rotation_callback=self.rotate_owner_state
)
self.token = result["session_token"]
self.set_cookie = True
return self.redirect("/account", "Local account created")
if path == "/recover":
result = self.auth.start_password_reset(
self.token, email=f.get("email", "")
)
return self.redirect("/recover", result["message"])
if path == "/recover/verify":
self.auth.verify_password_reset_code(self.token, f.get("code", ""))
return self.redirect("/recover", "Verification accepted locally")
if path == "/recover/complete":
password = f.get("new_password", "")
if password != f.get("confirm_password", ""):
raise ValueError("Passwords do not match")
self.token = self.auth.complete_password_reset(
self.token,
new_password=password,
session_rotation_callback=self.rotate_owner_state,
)
self.set_cookie = True
return self.redirect("/account", "Password updated locally")
if path == "/signout":
self.auth.sign_out(self.token)
self.token, self.session = self.auth.ensure_session(None)
self.set_cookie = True
return self.redirect("/", "Signed out")
if path == "/reorder":
if not self.session["authenticated"]:
return self.redirect("/signin", "Sign in to reorder")
with self.backend.lifecycle.connection(transaction=True) as db:
row = db.execute(
"SELECT * FROM fd_orders WHERE order_id=? AND account_id=?",
(f.get("order_id"), self.session["account"]["account_id"]),
).fetchone()
if not row:
raise ValueError("Order not found")
added = 0
skipped = 0
for pid, qty in json.loads(row["items"]):
product = BY_ID.get(pid)
if not product or not product_available(product, self.state):
skipped += 1
continue
db.execute(
"INSERT INTO fd_cart VALUES(?,?,?,?) ON CONFLICT(owner,product_id) DO UPDATE SET qty=MIN(20,fd_cart.qty+excluded.qty)",
(self.owner, pid, qty, "best"),
)
added += 1
message = f"{added} past-order products added to cart"
if skipped:
message += f"; {skipped} unavailable item skipped"
return self.redirect("/cart", message)
if path == "/support":
topic, details = f.get("topic", ""), f.get("details", "").strip()
if (
topic
not in {"Order question", "Substitution", "Delivery", "Account"}
or len(details) < 10
):
raise ValueError("Provide at least 10 characters")
with self.backend.lifecycle.connection(transaction=True) as db:
db.execute(
"INSERT INTO fd_support(owner,topic,details,status,created) VALUES(?,?,?,?,?)",
(self.owner, topic, details, "Saved locally", stamp()),
)
return self.redirect("/support", "Saved locally; no message was sent")
if path == "/support/cancel":
request_id = int(f.get("request_id", "0"))
with self.backend.lifecycle.connection(transaction=True) as db:
changed = db.execute(
"UPDATE fd_support SET status='Cancelled locally' WHERE id=? AND owner=?",
(request_id, self.owner),
).rowcount
if not changed:
raise ValueError("Local support request not found")
return self.redirect("/support", "Cancelled locally; no message was sent")
except FormError as e:
return self.send(
e.status, f"Request rejected: {esc(e)}", "text/plain; charset=utf-8"
)
except (ValueError, AuthError) as e:
error_target = {
"/signin": "/signin",
"/register": "/register",
"/register/verify": "/register",
"/recover": "/recover",
"/recover/verify": "/recover",
"/recover/complete": "/recover",
}.get(path, self.return_path("/"))
message = "Enter a valid email address" if str(e) == "email is invalid" else str(e)
return self.redirect(error_target, message)
return self.send(404, "Not found")
def registration_page(self):
status = self.auth.session_flow_status(self.token, purpose="registration")
if status["state"] == "challenge":
mail = self.auth.local_mail_for_session(
self.token, purpose="registration"
)
local_code = (
f'
Local-only inbox
Local verification code: {esc(mail["verification_code"])}
No email or external message was sent.
'
if mail
else ""
)
return f'''
freshdirect.
Verify your local account
Enter the six-digit code from this session’s local-only inbox.
'''
def order_detail_page(self, row):
items = []
current_items_total = 0.0
for product_id, qty in json.loads(row["items"]):
product = BY_ID.get(product_id)
if not product:
items.append(
f'
'
sub, disc, fee, total = self.totals(rows)
area = service_area(self.state)
items = []
for p, r in rows:
available = product_available(p, self.state)
availability = (
f'Available in {esc(area["label"])}'
if available and area
else f'Unavailable for Express in {esc(area["label"])} (limited assortment)'
if area
and self.state.get("fulfillment") == "express"
and p["id"] not in EXPRESS_PRODUCT_IDS
else f'Unavailable in {esc(area["label"])}; excluded from subtotal'
if area and not available
else "Set a supported ZIP to confirm availability"
)
line_total = money(p["price"] * r["qty"]) if available else "Excluded"
items.append(
f'''
'
sub, disc, fee, total = self.totals(rows)
try:
a = json.loads(self.state["address"] or "{}")
except json.JSONDecodeError:
a = {}
area = service_area(self.state)
address = self.valid_address()
mode = self.state["fulfillment"]
slot = self.state["slot"]
methods = "".join(
f''
for method, label in FULFILLMENT_LABELS.items()
)
address_defaults = {
"name": "Alex Shopper",
"street": "123 Market Street",
"city": area["label"] if area else "Brooklyn",
"state": "NY",
"zip": self.state["zip"] or "11201",
}
address_fields = "".join(
f''
for key in ("name", "street", "city", "state", "zip")
)
summary_items = "".join(
f'
{row["qty"]} × {esc(product["name"])}{esc(product["size"])} · {dict(best="Best available",contact="Contact me",none="No substitute")[row["substitution"]]} · {"Available" if product_available(product, self.state) else ("Unavailable for Express (limited assortment)" if mode == "express" and product["id"] not in EXPRESS_PRODUCT_IDS else "Unavailable; excluded from subtotal")}{money(product["price"] * row["qty"]) if product_available(product, self.state) else "Excluded"}
'
for product, row in rows
)
slot_options = '' + "".join(
f''
for slot_mode, allowed_slots in SLOTS_BY_MODE.items()
for slot_id, label in SLOT_LABELS.items()
if slot_id in allowed_slots
)
fee_label = {
"pickup": "Pickup fee",
"express": "Express fee",
"delivery": "Delivery fee",
}.get(mode, "Delivery fee")
promotion_review = self.state["coupon"] or "None"
if self.state["coupon"] == "NEW50" and not self.new50_eligible():
promotion_review += " (first-order eligibility not met)"
elif self.state["coupon"] == "NEW50" and sub < 99:
promotion_review += " ($99 minimum not met)"
fulfillment_review = FULFILLMENT_LABELS.get(mode, "Not selected")
slot_review = (
SLOT_LABELS[slot]
if slot in SLOTS_BY_MODE.get(mode, frozenset())
else "Not selected"
)
if mode == "pickup" and area:
address_review = area["pickup_location"]
elif address:
address_review = f'{address["name"]}, {address["street"]}, {address["city"]}, {address["state"]} {address["zip"]}'
else:
address_review = "Not saved"
blockers = []
if not area:
blockers.append("Set a supported synthetic ZIP.")
if mode in {"delivery", "express"} and not address:
blockers.append("Save a matching supported delivery address.")
if slot_review == "Not selected":
blockers.append("Save a valid time for the selected fulfillment method.")
if any(not product_available(product, self.state) for product, _ in rows):
blockers.append("Remove items unavailable for this location.")
blocker_html = (
'
Review needed
'
+ "".join(f"
{esc(item)}
" for item in blockers)
+ "
"
if blockers
else '
Local review complete. Order placement remains disabled.
'
)
fulfillment_script = ''''''
return f'''
Checkout review
Delivery and order details
This sandbox stops before submission.
{blocker_html}
1
Delivery address
Required for Standard and Express delivery. Pickup uses the local test hub.
2
Fulfillment
3
Payment and placement
Real payment and order placement are intentionally unavailable.
{fulfillment_script}'''
def not_found(self):
self.send(
404,
shell(
"Page not found",
'