File size: 45,798 Bytes
393804b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 | """EveryPlate offline clone.
Every route resolves against the bound local SQLite database opened through
``backend.site_backend_integration``. No request ever reaches the source site.
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
from typing import Any
from fastapi import FastAPI, Form, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
# Deployment contract: when the harness supplies an isolated data directory,
# the bound database lives there rather than in the checked-out site tree.
_DATA_DIR = os.environ.get("WEBSITEBENCH_DATA_DIR") or os.environ.get("CLAWBENCH_DATA_DIR")
if _DATA_DIR and not os.environ.get("WEBSITEBENCH_SITE_BACKEND_DATABASE"):
_data_root = Path(_DATA_DIR) / "everyplate"
_data_root.mkdir(parents=True, exist_ok=True)
os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(_data_root / "everyplate.sqlite3")
from backend.site_backend_integration import open_site_services # noqa: E402
SITE_ID = "everyplate"
DISPLAY_NAME = "EveryPlate"
LOGO_SRC = "/static/logo.svg"
app = FastAPI(title=DISPLAY_NAME)
app.mount("/static", StaticFiles(directory=HERE / "static"), name="static")
templates = Jinja2Templates(directory=HERE / "frontend" / "templates")
_backend, _auth = open_site_services()
DB_PATH = _backend.lifecycle.database_path
# Session cookie derived from the site id, exactly as the runtime contract
# requires: __Host- prefixed, host-only, Secure, HttpOnly, SameSite.
_SESSION = _backend.config.session if hasattr(_backend.config, "session") else None
COOKIE_NAME = f"__Host-{SITE_ID}_session"
DEMO_ACCOUNTS = [
{"subject_id": "sub-demo-1", "email": "demo@everyplate.offline.invalid",
"display_name": "Alex", "password": "OfflineClone!2026"},
]
def _ensure_demo_accounts() -> None:
for account in DEMO_ACCOUNTS:
if not _auth.account_exists(account["email"]):
_auth.seed_account(**account)
_ensure_demo_accounts()
def current_account(request: Request) -> dict | None:
token = request.cookies.get(COOKIE_NAME)
if not token:
return None
try:
session = _auth.resolve_session(token)
except Exception:
return None
if not session or not session.get("authenticated"):
return None
account = session.get("account") or {}
email = account.get("email_normalized") or account.get("email")
if not email:
return None
return {
"email": email,
"display_name": account.get("display_name") or email.split("@")[0],
"account_id": account.get("account_id"),
"subject_id": account.get("subject_id"),
}
def _set_session_cookie(response, token: str) -> None:
response.set_cookie(
COOKIE_NAME, token, httponly=True, secure=True, samesite="lax", path="/"
)
def db():
import sqlite3
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
return connection
NAV = [
("Weekly Menu", "/weekly-menu"),
("Our Plans", "/plans"),
("FAQs", "/about/faq"),
("Gift Cards", "/gift"),
("EveryPlate for Teams", "/pages/everyplate-for-teams"),
]
def shell(request: Request, **extra: Any) -> dict[str, Any]:
path = request.url.path
return {
"logo_src": LOGO_SRC,
"nav_items": [
{"label": label, "href": href, "active": path.startswith(href)}
for label, href in NAV
],
"account": current_account(request),
"appstore_badge": HOME_ASSETS["appstore_badge"],
"playstore_badge": HOME_ASSETS["playstore_badge"],
**extra,
}
def _recipe_row(connection, slug: str) -> dict[str, Any] | None:
row = connection.execute("SELECT * FROM recipes WHERE slug = ?", (slug,)).fetchone()
if row is None:
return None
recipe = dict(row)
recipe["tags"] = [
r["tag"]
for r in connection.execute(
"SELECT tag FROM recipe_tags WHERE recipe_id=? ORDER BY position",
(row["id"],),
)
]
recipe["badges"] = [
r["badge"]
for r in connection.execute(
"SELECT badge FROM recipe_badges WHERE recipe_id=? ORDER BY position",
(row["id"],),
)
]
recipe["ingredients"] = [
dict(r)
for r in connection.execute(
"SELECT name, measurement FROM recipe_ingredients WHERE recipe_id=? ORDER BY position",
(row["id"],),
)
]
recipe["nutrition"] = [
dict(r)
for r in connection.execute(
"SELECT label, value FROM recipe_nutrition WHERE recipe_id=? ORDER BY position",
(row["id"],),
)
]
recipe["steps"] = [
dict(r)
for r in connection.execute(
"SELECT position, body FROM recipe_steps WHERE recipe_id=? ORDER BY position",
(row["id"],),
)
]
return recipe
HOME_ASSETS = json.loads((HERE / "backend" / "home_assets.json").read_text(encoding="utf-8"))
PAGE_ASSETS = json.loads((HERE / "backend" / "page_assets.json").read_text(encoding="utf-8"))
PREF_ICONS = {
"smart-fit": "smart-fit", "meat-veggie": "meat-veggie", "quick-easy": "quick-easy",
"family-faves": "family-faves", "veggie": "veggie",
}
def _faq_rows(connection, scope: str, open_id: str | None):
return [
dict(r, open=(r["id"] == open_id))
for r in connection.execute(
"SELECT id, question, answer FROM faq_entries WHERE scope=? ORDER BY position", (scope,)
)
]
HOME_CONTENT = {
# Copy captured verbatim from the source home route on 2026-08-31.
"ticker": [
"2x The Veggie Variety", "35+ Weekly Recipes",
"Our Biggest and Boldest Menu Yet", "50% More Chicken Recipes",
"America\u2019s Lowest Priced Home Cooking Box",
],
"comparison": [
{"label": "Fresh ingredients", "others": True, "exclusive": False},
{"label": "Delivered to your door", "others": True, "exclusive": False},
{"label": "Craveworthy meals under $7.00", "others": False, "exclusive": True},
{"label": "BONUS Weekly $1, $2, $3 deal drops", "others": False, "exclusive": True},
],
"claims": [
{"title": "98% say EveryPlate makes dinner less stressful",
"body": "Now serving more Minimal Cleanup meals every week. With reduced prep and one-pan, sheet pan, and low-dish recipes, you can get the dishes done in just 5 minutes."},
{"title": "98% say EveryPlate meals are delicious",
"body": "From comfort classics to restaurant-worthy meals anyone can pull off, we help you put mouthwatering dinners on the table every single night."},
{"title": "94% of families say EveryPlate reduces mealtime conflict",
"body": "Kid-friendly flavors and classic recipes make dinner smoother for the whole family."},
],
"how_it_works": [
{"title": "Pick Your Meals", "body": "Take your pick from crowd-pleasing meals, snacks, and sides every week."},
{"title": "Everything, Delivered", "body": "Fresh, pre-portioned ingredients show up at your door\u2014chilled and ready to roll."},
{"title": "Cook. Enjoy. Relax.", "body": "Follow easy, 6-step recipes and get dinner on the table in just about 30 minutes."},
],
"discover": {
"tabs": [
{"id": "global-flavors", "label": "New Global Flavors"},
{"id": "veggie-variety", "label": "More Veggie Variety"},
{"id": "chicken-options", "label": "More Chicken Options"},
],
"heading": "Now With Even More Global Flavors",
"body": "From tacos to stir-fries, we\u2019ve added more international favorites to the mix. So you can cook any cuisine your craving, easily.",
},
# The source lists these twelve on the home route; answers live on /about/faq.
"faqs": [
"What types of meals does EveryPlate offer?",
"How much does EveryPlate cost?",
"Does EveryPlate cater to specific dietary needs?",
"Are there any additional add-ons or offerings?",
"Do I commit myself permanently with my order?",
"How do my meal kits stay fresh during transit?",
"Can I customize my meal plan?",
"Are meal kits safe for those with allergies or dietary restrictions?",
"How does delivery work?",
"How do I prepare the meals?",
"How do I know you deliver to my area?",
"How do I know the ingredients will actually be fresh?",
],
}
def _home_context() -> dict:
"""Bind the captured copy to the localized source images."""
content = dict(HOME_CONTENT)
content["claims"] = [
dict(claim, image=HOME_ASSETS["claim_images"][index])
for index, claim in enumerate(HOME_CONTENT["claims"])
]
content["how_it_works"] = [
dict(step, image=HOME_ASSETS["how_images"][index])
for index, step in enumerate(HOME_CONTENT["how_it_works"])
]
content["discover"] = dict(HOME_CONTENT["discover"], image=HOME_ASSETS["discover_image"])
content["faqs"] = [
{"id": f"q{index + 1}", "question": question}
for index, question in enumerate(HOME_CONTENT["faqs"])
]
# The source ticker animates; its observed resting frame shows these three.
content["ticker_visible"] = [
"35+ Weekly Recipes",
"Our Biggest and Boldest Menu Yet",
"50% More Chicken Recipes",
]
content["hero_image"] = HOME_ASSETS["hero_image"]
content["bottom_image"] = HOME_ASSETS["bottom_image"]
content["headlines_image"] = HOME_ASSETS["headlines_image"]
content["logo_white"] = LOGO_SRC
return content
@app.get("/", response_class=HTMLResponse)
def home(request: Request, faq: str | None = None):
with db() as connection:
week = connection.execute(
"SELECT * FROM weeks ORDER BY is_current DESC, position LIMIT 1"
).fetchone()
featured = []
if week is not None:
rows = connection.execute(
"SELECT r.* FROM menu_items m JOIN recipes r ON r.id = m.recipe_id "
"WHERE m.week_id = ? AND m.category = 'Meals' ORDER BY m.position LIMIT 30",
(week["id"],),
).fetchall()
for row in rows:
item = dict(row)
item["badges"] = [
b["badge"]
for b in connection.execute(
"SELECT badge FROM recipe_badges WHERE recipe_id=? ORDER BY position",
(row["id"],),
)
]
featured.append(item)
faqs = [
dict(r, open=(r["id"] == faq))
for r in connection.execute(
"SELECT id, question, answer FROM faq_entries WHERE scope='home' ORDER BY position"
)
]
context = _home_context()
context["faqs"] = faqs or context["faqs"]
return templates.TemplateResponse(
request, "home.html",
shell(request, featured=featured, open_faq=faq,
featured_week=week["id"] if week is not None else "", **context),
)
FUNNEL = ["Select Plan", "Register", "Address", "Payment Details", "Pick Meals"]
PLAN_FAQS = [
"How can I see the recipes before I sign up?",
"Why does EveryPlate cost less than other meal kits?",
"Is there a commitment?",
"What comes in each delivery?",
"What if I don\u2019t cook for 2 or 4 people?",
"Why do I have to pay for shipping?",
]
# Review text as the source renders it on /plans.
PLANS_REVIEW = {
"body": ("Absolutely nothing beats the price, recipe and quality of ingredients!! With grocery "
"store prices sky rocketing, I\u2019m actually able to stay on budget and still have "
"amazing, well thought out meals. I would definitely recommend EveryPlate to anyone and "
"everyone. Every single meal (I\u2019ve tried 30 recipes so far) has been great!"),
"author": "Mady",
}
DELIVERY_DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
SETTINGS_TABS = [
("Account Settings", "/settings/account"),
("Notifications", "/settings/notifications"),
("Order History", "/settings/orders"),
]
# Email preference rows, in the order the source lists them.
EMAIL_PREFS = [
("weekly-menu-reminders", "Weekly menu reminders"),
("upcoming-recipes", "Upcoming recipes"),
("general-feedback", "General EveryPlate feedback"),
("recipe-surveys", "Weekly recipe surveys"),
("partner-offers", "Partner Offers"),
("announcements", "EveryPlate announcements"),
("special-offers", "Special offers"),
("kitchen-tips", "Kitchen tips and tricks"),
("gifts", "EveryPlate Gifts"),
("all-emails", "All emails"),
]
SMS_PREF = ("sms-offers", "SMS with exclusive offers")
CONTENT_ROUTES = {
"/about/app": "app",
"/pages/students": "students",
"/eat": "eat", "/stories": "stories", "/contact": "contact",
"/accessibility": "accessibility", "/terms": "terms", "/privacy-policy": "privacy",
}
def _money(cents: int) -> str:
return f"${cents / 100:,.2f}"
def _require_account(request: Request, next_path: str):
account = current_account(request)
if account is None:
return None, RedirectResponse(f"/login?next={next_path}", status_code=303)
return account, None
def _prefs(connection, account_id: str) -> dict[str, bool]:
stored = {
r["key"]: bool(r["enabled"])
for r in connection.execute(
"SELECT key, enabled FROM notification_preferences WHERE account_id=?", (account_id,)
)
}
keys = [k for k, _ in EMAIL_PREFS] + [SMS_PREF[0]]
return {k: stored.get(k, k != SMS_PREF[0]) for k in keys}
def _settings_shell(request, **extra):
return shell(request, tabs=SETTINGS_TABS, active=request.url.path, **extra)
@app.get("/plans", response_class=HTMLResponse)
def plans(request: Request, people: int = 4, recipes: int = 3,
preference: str = "meat-veggie", promo: str | None = None, faq: str | None = None):
with db() as connection:
people_options = [
r["people"] for r in connection.execute(
"SELECT DISTINCT people FROM plan_prices ORDER BY people")
]
recipe_options = [
r["recipes_per_week"] for r in connection.execute(
"SELECT DISTINCT recipes_per_week FROM plan_prices ORDER BY recipes_per_week")
]
if people not in people_options:
people = people_options[1] if len(people_options) > 1 else people_options[0]
if recipes not in recipe_options:
recipes = recipe_options[0]
prefs = [dict(r) for r in connection.execute("SELECT * FROM preferences ORDER BY position")]
for pref in prefs:
icon = PREF_ICONS.get(pref["id"])
pref["icon"] = PAGE_ASSETS["icons"].get(icon) if icon else None
if preference not in {p["id"] for p in prefs}:
preference = prefs[0]["id"]
chosen_pref = next(p for p in prefs if p["id"] == preference)
row = connection.execute(
"SELECT * FROM plan_prices WHERE people=? AND recipes_per_week=?", (people, recipes)
).fetchone()
box_cents = row["box_price_cents"]
per_cents = row["price_per_serving_cents"]
promo_state = {"code": promo, "applied": False, "error": None,
"description": "", "discount": ""}
first_cents = box_cents
if promo:
code = promo.strip().upper()
promo_state["code"] = code
found = connection.execute(
"SELECT * FROM promo_codes WHERE code=? AND active=1", (code,)
).fetchone()
if found is None:
promo_state["error"] = f"{code} is not a valid promo code."
else:
promo_state["applied"] = True
promo_state["description"] = found["description"]
discount = box_cents * found["value"] // 100
first_cents = box_cents - discount
promo_state["discount"] = _money(discount)
return templates.TemplateResponse(
request, "plans.html",
shell(request, funnel=FUNNEL, step="Select Plan",
checkout_logo=PAGE_ASSETS["plans"]["logo"],
preferences=prefs,
people_options=people_options, recipe_options=recipe_options,
recipe_types=PAGE_ASSETS["plans"]["carousel"],
trustpilot=PAGE_ASSETS["plans"]["trustpilot"],
review=PLANS_REVIEW,
faqs=_faq_rows(connection, "plans", faq),
plan_query=f"people={people}&recipes={recipes}&preference={preference}",
selected={"people": people, "recipes": recipes, "preference": preference,
"preference_label": chosen_pref["label"],
"preference_description": chosen_pref["description"]},
price={"box_price": _money(box_cents), "per_serving": _money(per_cents),
"first_box": _money(first_cents)},
promo=promo_state),
)
@app.post("/plans/select")
def plans_select(request: Request, people: int = Form(4), recipes: int = Form(3),
preference: str = Form("meat-veggie"), promo: str | None = Form(None)):
query = f"?people={people}&recipes={recipes}&preference={preference}"
if promo:
query += f"&promo={promo}"
return RedirectResponse(f"/checkout/register{query}", status_code=303)
@app.get("/checkout/register", response_class=HTMLResponse)
def checkout_register(request: Request, people: int = 4, recipes: int = 3,
preference: str = "meat-veggie", promo: str | None = None):
with db() as connection:
row = connection.execute(
"SELECT * FROM plan_prices WHERE people=? AND recipes_per_week=?", (people, recipes)
).fetchone()
return templates.TemplateResponse(
request, "checkout_register.html",
shell(request, funnel=FUNNEL, step="Register",
checkout_logo=PAGE_ASSETS["plans"]["logo"],
selected={"people": people, "recipes": recipes, "preference": preference},
price={"box_price": _money(row["box_price_cents"]) if row else "-"},
promo=promo or ""),
)
@app.get("/recipes", response_class=HTMLResponse)
def recipes_index(request: Request, q: str | None = None, tag: str | None = None):
with db() as connection:
sql = ("SELECT DISTINCT r.* FROM recipes r "
"LEFT JOIN recipe_tags t ON t.recipe_id = r.id WHERE 1=1")
params: list = []
if q:
sql += " AND (r.name LIKE ? OR r.subtitle LIKE ?)"
params += [f"%{q}%", f"%{q}%"]
if tag:
sql += " AND t.tag = ?"
params.append(tag)
sql += " ORDER BY r.name LIMIT 120"
rows = [dict(r) for r in connection.execute(sql, params)]
tags = [
r["tag"] for r in connection.execute(
"SELECT tag, COUNT(*) n FROM recipe_tags GROUP BY tag ORDER BY n DESC LIMIT 12")
]
return templates.TemplateResponse(
request, "recipes_index.html",
shell(request, items=rows, tags=tags, q=q or "", active_tag=tag or ""),
)
@app.get("/login", response_class=HTMLResponse)
def login_form(request: Request, next: str = "/weekly-menu", error: str | None = None):
if current_account(request):
return RedirectResponse(next, status_code=303)
return templates.TemplateResponse(
request, "login.html", shell(request, next=next, error=error, demo=DEMO_ACCOUNTS[0])
)
@app.post("/login")
def login_submit(request: Request, email: str = Form(...), password: str = Form(...),
next: str = Form("/weekly-menu")):
token, _ = _auth.ensure_session(request.cookies.get(COOKIE_NAME))
try:
# sign_in rotates the session token; the cookie must carry the new one.
result = _auth.sign_in(token, email=email.strip(), password=password)
token = result.get("session_token", token)
except Exception:
return templates.TemplateResponse(
request, "login.html",
shell(request, next=next, demo=DEMO_ACCOUNTS[0],
error="That email and password combination is not recognised."),
status_code=401,
)
response = RedirectResponse(next, status_code=303)
_set_session_cookie(response, token)
return response
@app.post("/logout")
def logout(request: Request):
_auth.sign_out(request.cookies.get(COOKIE_NAME))
response = RedirectResponse("/", status_code=303)
response.delete_cookie(COOKIE_NAME, path="/")
return response
@app.get("/settings")
def settings_root(request: Request):
"""The source redirects /settings to /settings/account."""
return RedirectResponse("/settings/account", status_code=303)
@app.get("/settings/account", response_class=HTMLResponse)
def settings_account(request: Request, saved: str | None = None):
account, redirect = _require_account(request, "/settings/account")
if redirect:
return redirect
with db() as connection:
plan = _subscription(connection, account["account_id"])
prefs = [dict(r) for r in connection.execute("SELECT * FROM preferences ORDER BY position")]
price = connection.execute(
"SELECT * FROM plan_prices WHERE people=? AND recipes_per_week=?",
(plan["people"], plan["recipes_per_week"]),
).fetchone()
return templates.TemplateResponse(
request, "settings_account.html",
_settings_shell(request, plan=plan, preferences=prefs, saved=saved,
people_options=[2, 4, 6], recipe_options=[3, 4, 5],
delivery_days=DELIVERY_DAYS,
customer_id=f"1{abs(hash(account['email'])) % 100000000:08d}",
box_price=_money(price["box_price_cents"]) if price else "-"),
)
@app.post("/settings/plan")
def settings_plan(request: Request, people: int = Form(...), recipes: int = Form(...),
preference: str = Form(...)):
account, redirect = _require_account(request, "/settings/account")
if redirect:
return redirect
with db() as connection:
valid = connection.execute(
"SELECT 1 FROM plan_prices WHERE people=? AND recipes_per_week=?", (people, recipes)
).fetchone()
if valid is None:
return RedirectResponse("/settings/account?saved=invalid", status_code=303)
connection.execute(
"UPDATE subscriptions SET people=?, recipes_per_week=?, preference_id=?"
" WHERE account_id=?",
(people, recipes, preference, account["account_id"]),
)
# Shrinking the box must drop selections that no longer fit.
for week in connection.execute("SELECT id FROM weeks"):
chosen = list(_selections(connection, account["account_id"], week["id"]))
for extra in chosen[recipes:]:
connection.execute(
"DELETE FROM selections WHERE account_id=? AND week_id=? AND recipe_id=?",
(account["account_id"], week["id"], extra),
)
connection.commit()
return RedirectResponse("/settings/account?saved=plan", status_code=303)
@app.post("/settings/delivery")
def settings_delivery(request: Request, delivery_day: str = Form(...),
address_line1: str = Form(""), address_city: str = Form(""),
address_state: str = Form(""), address_zip: str = Form("")):
account, redirect = _require_account(request, "/settings/account")
if redirect:
return redirect
if delivery_day not in DELIVERY_DAYS:
return RedirectResponse("/settings/account?saved=invalid", status_code=303)
with db() as connection:
connection.execute(
"UPDATE subscriptions SET delivery_day=?, address_line1=?, address_city=?,"
" address_state=?, address_zip=? WHERE account_id=?",
(delivery_day, address_line1, address_city, address_state, address_zip,
account["account_id"]),
)
connection.commit()
return RedirectResponse("/settings/account?saved=delivery", status_code=303)
@app.post("/settings/subscription")
def settings_subscription(request: Request, status: str = Form(...)):
account, redirect = _require_account(request, "/settings/account")
if redirect:
return redirect
if status not in ("active", "paused"):
return RedirectResponse("/settings/account?saved=invalid", status_code=303)
with db() as connection:
connection.execute(
"UPDATE subscriptions SET status=? WHERE account_id=?", (status, account["account_id"])
)
connection.commit()
return RedirectResponse("/settings/account?saved=subscription", status_code=303)
@app.get("/settings/notifications", response_class=HTMLResponse)
def settings_notifications(request: Request, saved: str | None = None):
account, redirect = _require_account(request, "/settings/notifications")
if redirect:
return redirect
with db() as connection:
state = _prefs(connection, account["account_id"])
return templates.TemplateResponse(
request, "settings_notifications.html",
_settings_shell(request, email_prefs=EMAIL_PREFS, sms_pref=SMS_PREF,
state=state, saved=saved),
)
@app.post("/settings/notifications")
async def settings_notifications_save(request: Request):
account, redirect = _require_account(request, "/settings/notifications")
if redirect:
return redirect
form = await request.form()
keys = [k for k, _ in EMAIL_PREFS] + [SMS_PREF[0]]
with db() as connection:
for key in keys:
connection.execute(
"INSERT OR REPLACE INTO notification_preferences (account_id, key, enabled)"
" VALUES (?,?,?)",
(account["account_id"], key, 1 if form.get(key) else 0),
)
connection.commit()
return RedirectResponse("/settings/notifications?saved=1", status_code=303)
@app.get("/settings/orders", response_class=HTMLResponse)
def settings_orders(request: Request):
account, redirect = _require_account(request, "/settings/orders")
if redirect:
return redirect
with db() as connection:
orders = []
for row in connection.execute(
"SELECT o.*, w.label, w.range_label FROM orders o JOIN weeks w ON w.id=o.week_id"
" WHERE o.account_id=? ORDER BY o.placed_at DESC", (account["account_id"],)
):
order = dict(row)
order["items"] = [
dict(i) for i in connection.execute(
"SELECT r.name, r.slug, i.quantity FROM order_items i"
" JOIN recipes r ON r.id=i.recipe_id WHERE i.order_id=? ORDER BY i.position",
(row["id"],),
)
]
order["total"] = _money(row["total_cents"])
orders.append(order)
return templates.TemplateResponse(
request, "settings_orders.html", _settings_shell(request, orders=orders)
)
@app.post("/settings/orders/place")
def place_order(request: Request, week_id: str = Form(...)):
"""Confirm a week's selections into a local order. No payment is taken."""
account, redirect = _require_account(request, "/settings/orders")
if redirect:
return redirect
with db() as connection:
chosen = _selections(connection, account["account_id"], week_id)
if not chosen:
return RedirectResponse(f"/weekly-menu/{week_id}?error=empty", status_code=303)
plan = _subscription(connection, account["account_id"])
price = connection.execute(
"SELECT box_price_cents FROM plan_prices WHERE people=? AND recipes_per_week=?",
(plan["people"], plan["recipes_per_week"]),
).fetchone()
order_id = f"ord-{account['account_id'][-8:]}-{week_id}"
connection.execute(
"INSERT OR REPLACE INTO orders (id, account_id, week_id, status, total_cents, placed_at)"
" VALUES (?,?,?,?,?,datetime('now'))",
(order_id, account["account_id"], week_id, "confirmed", price["box_price_cents"]),
)
connection.execute("DELETE FROM order_items WHERE order_id=?", (order_id,))
for position, recipe_id in enumerate(chosen):
connection.execute(
"INSERT INTO order_items (order_id, position, recipe_id, quantity) VALUES (?,?,?,1)",
(order_id, position, recipe_id),
)
connection.commit()
return RedirectResponse("/settings/orders", status_code=303)
def _content_page(request: Request, slug: str):
with db() as connection:
row = connection.execute("SELECT * FROM pages WHERE slug = ?", (slug,)).fetchone()
if row is None:
return HTMLResponse("<h1>Page not found</h1>", status_code=404)
page = dict(row)
return templates.TemplateResponse(
request, "page.html",
shell(request, page=page, blocks=json.loads(page["blocks_json"])),
)
# Copy captured from the source Teams page on 2026-08-31.
TEAMS_VALUES = ["America's Best Value Meal Kit", "High-Quality Ingredients",
"Meals Ready in 6 Simple Steps"]
TEAMS_WELLNESS = [
"EveryPlate has satisfying recipes at an affordable price that help promote a healthy lifestyle.",
"We get to know our suppliers and ensure we source the highest-quality ingredients. So, you know your"
" employees are getting the best.",
"EveryPlate takes the hard work out of meal planning and prepping and helps reduce stress while"
" bringing people together.",
]
TEAMS_FOOD_OPTIONS = [
("Catering", "With 26 recipes each week, EveryPlate has solutions for all meal occasions - at an"
" unbeatable price."),
("Takeout & Restaurants", "EveryPlate is 50% cheaper than the average fast-casual meal, allowing your"
" employees to enjoy a flavor-filled meal for less."),
("Groceries", "EveryPlate is 25% cheaper than grocery shopping. In addition to money, save your"
" employees time by taking meal planning off their plate."),
]
TEAMS_SOLUTIONS = [
("E-GIFT CODE", "Send a one-time e-gift code your team can redeem on any EveryPlate plan."),
("MEALS ON DEMAND", "Let employees order the meals they want, when they want them."),
("MEAL SUBSIDY", "Subsidise part of every box as an ongoing benefit for your team."),
]
TEAMS_STEPS = [
("Connect with Us", "Fill out our inquiry form and we'll connect with you one-on-one to learn about"
" your organization and better understand your needs."),
("Develop a Tailored Solution", "We'll partner with you to design a solution that fits your needs and"
" nourishes your team."),
("Let Us Do the Rest", "Sit back, relax, and let us do the rest. We will provide fresh, pre-portioned"
" ingredients right to your team's door."),
]
TEAMS_RECIPE_BLURBS = {
"Meat & Veggies": "Mouthwatering meat, seafood, & veggie options",
"Quick & Easy": "No fuss meals ready in 30 minutes or less!",
"Vegetarian": "Flavor-forward veggie & plant-based meals",
"Nutrish & Delish": "Satisfying flavors around 650 calories or less",
"Family Friendly": "Family-friendly dinners for picky eaters",
"Premium": "For when you're feeling fancy",
}
PARTNERSHIP_OPTIONS = ["Please select", "E-Gift Code", "Meals on Demand", "Meal Subsidy", "Other"]
HEADCOUNT_OPTIONS = ["Please select", "1-50", "51-200", "201-500", "501-1000", "1000+"]
def _teams_context(request: Request, submitted: bool = False) -> dict:
a = PAGE_ASSETS["teams"]
# The source Teams landing page ships without the marketing nav.
return shell(
request,
hide_nav=True,
assets=a,
values=[{"label": label, "image": image}
for label, image in zip(TEAMS_VALUES, a["value_icons"])],
wellness=[{"body": body, "image": image}
for body, image in zip(TEAMS_WELLNESS, a["wellness_icons"])],
food_options=[{"title": t, "body": b, "image": image}
for (t, b), image in zip(TEAMS_FOOD_OPTIONS, a["food_options"])],
solutions=[{"title": t, "body": b, "image": image}
for (t, b), image in zip(TEAMS_SOLUTIONS, a["solutions_icons"])],
steps=[{"title": t, "body": b, "image": image}
for (t, b), image in zip(TEAMS_STEPS, a["steps"])],
recipe_types=[dict(c, blurb=TEAMS_RECIPE_BLURBS.get(c["name"], "")) for c in a["carousel"]],
partnership_options=PARTNERSHIP_OPTIONS, headcount_options=HEADCOUNT_OPTIONS,
submitted=submitted,
)
@app.get("/pages/everyplate-for-teams", response_class=HTMLResponse)
def teams_page(request: Request, submitted: str | None = None):
return templates.TemplateResponse(
request, "teams.html", _teams_context(request, submitted == "1")
)
@app.post("/pages/everyplate-for-teams")
async def teams_submit(request: Request):
"""Record the enquiry in the local outbox. Nothing leaves the machine."""
form = await request.form()
with db() as connection:
connection.execute(
"INSERT INTO team_enquiries (email, first_name, last_name, partnership, headcount,"
" company, job_title, notes) VALUES (?,?,?,?,?,?,?,?)",
(str(form.get("email", "")), str(form.get("first_name", "")),
str(form.get("last_name", "")), str(form.get("partnership", "")),
str(form.get("headcount", "")), str(form.get("company", "")),
str(form.get("job_title", "")), str(form.get("notes", ""))),
)
connection.commit()
return RedirectResponse("/pages/everyplate-for-teams?submitted=1#teams-form", status_code=303)
# The six FAQ categories the source lists, in its own order.
FAQ_CATEGORIES = [
("FOOD SAFETY", "fresh"), ("ABOUT EVERYPLATE", "EveryPlate"),
("RECIPES & INGREDIENTS", "recipes"), ("SHIPPING & DELIVERY", "delivery"),
("BILLING", "cost"), ("ACCOUNT MANAGEMENT", "account"),
]
@app.get("/about/faq", response_class=HTMLResponse)
def faq_page(request: Request, q: str | None = None, faq: str | None = None):
with db() as connection:
results = []
if q:
like = f"%{q}%"
results = [
dict(r, open=(r["id"] == faq))
for r in connection.execute(
"SELECT id, question, answer FROM faq_entries"
" WHERE question LIKE ? OR answer LIKE ? ORDER BY scope, position",
(like, like),
)
]
icons = PAGE_ASSETS["faq"]["icons"]
categories = [
{"name": name, "query": query, "icon": icons[index] if index < len(icons) else None}
for index, (name, query) in enumerate(FAQ_CATEGORIES)
]
return templates.TemplateResponse(
request, "faq.html", shell(request, q=q or "", results=results, categories=categories)
)
GIFT_WHY = [
("Save them time and money", "Quick meals without the grocery trip"),
("The gift of choice", "Meals for their lifestyle"),
("Easy-to-follow recipes", "Making home-cooking simple"),
("Make their special day", "Scheduled delivery for the occasion"),
]
GIFT_HOW = ["Choose a date for us to email the gift card", "They choose their meals",
"We deliver to their doorstep"]
@app.get("/gift", response_class=HTMLResponse)
def gift_page(request: Request, faq: str | None = None):
with db() as connection:
a = PAGE_ASSETS["gift"]
return templates.TemplateResponse(
request, "gift.html",
shell(request,
hero_art=PAGE_ASSETS["icons"]["gift-hero"],
why=[{"title": t, "body": b, "image": img}
for (t, b), img in zip(GIFT_WHY, a["why_images"])],
how=[{"title": t, "image": img} for t, img in zip(GIFT_HOW, a["how_images"])],
faqs=_faq_rows(connection, "gift", faq)),
)
@app.get("/gift/selection", response_class=HTMLResponse)
def gift_selection(request: Request):
"""Local gift-card flow entry. No real purchase is possible in this clone."""
return templates.TemplateResponse(
request, "gift_selection.html", shell(request)
)
def _register_content_routes() -> None:
for path, slug in CONTENT_ROUTES.items():
def make(bound_slug: str):
def handler(request: Request):
return _content_page(request, bound_slug)
return handler
app.get(path, response_class=HTMLResponse)(make(slug))
_register_content_routes()
@app.get("/__websitebench/health")
def health() -> JSONResponse:
return JSONResponse({"status": "ok", "site_id": SITE_ID})
@app.get("/healthz")
def healthz() -> dict[str, object]:
return {"ok": True, "site_id": SITE_ID}
@app.get("/weekly-menu", response_class=HTMLResponse)
def weekly_menu(request: Request):
with db() as connection:
weeks = [dict(r) for r in connection.execute("SELECT * FROM weeks ORDER BY position")]
current = next((w for w in weeks if w["is_current"]), weeks[0] if weeks else None)
if current is None:
return HTMLResponse("<h1>No menu</h1>", status_code=404)
return _render_week(request, connection, weeks, current)
@app.get("/weekly-menu/{week_id}", response_class=HTMLResponse)
def weekly_menu_week(request: Request, week_id: str):
with db() as connection:
weeks = [dict(r) for r in connection.execute("SELECT * FROM weeks ORDER BY position")]
week = next((w for w in weeks if w["id"] == week_id), None)
if week is None:
return HTMLResponse("<h1>Week not found</h1>", status_code=404)
return _render_week(request, connection, weeks, week)
DEFAULT_PLAN = {"people": 4, "recipes_per_week": 3, "preference_id": "meat-veggie",
"delivery_day": "Wednesday", "status": "active"}
def _subscription(connection, account_id: str) -> dict:
row = connection.execute(
"SELECT * FROM subscriptions WHERE account_id = ?", (account_id,)
).fetchone()
if row is None:
connection.execute(
"INSERT INTO subscriptions (account_id, people, recipes_per_week, preference_id,"
" delivery_day, status, address_line1, address_city, address_state, address_zip)"
" VALUES (?,?,?,?,?,?,?,?,?,?)",
(account_id, DEFAULT_PLAN["people"], DEFAULT_PLAN["recipes_per_week"],
DEFAULT_PLAN["preference_id"], DEFAULT_PLAN["delivery_day"], "active",
"1 Offline Way", "Testville", "NY", "10001"),
)
connection.commit()
row = connection.execute(
"SELECT * FROM subscriptions WHERE account_id = ?", (account_id,)
).fetchone()
return dict(row)
def _week_status(connection, account_id: str, week_id: str) -> str:
row = connection.execute(
"SELECT status FROM week_status WHERE account_id=? AND week_id=?", (account_id, week_id)
).fetchone()
return row["status"] if row else "open"
def _selections(connection, account_id: str, week_id: str) -> dict[str, int]:
return {
r["recipe_id"]: r["quantity"]
for r in connection.execute(
"SELECT recipe_id, quantity FROM selections WHERE account_id=? AND week_id=?",
(account_id, week_id),
)
}
@app.post("/weekly-menu/{week_id}/select")
def select_meal(request: Request, week_id: str, recipe_id: str = Form(...),
action: str = Form("add")):
account = current_account(request)
if account is None:
return RedirectResponse(f"/login?next=/weekly-menu/{week_id}", status_code=303)
with db() as connection:
week = connection.execute("SELECT id FROM weeks WHERE id=?", (week_id,)).fetchone()
recipe = connection.execute("SELECT id FROM recipes WHERE id=?", (recipe_id,)).fetchone()
if week is None or recipe is None:
return HTMLResponse("<h1>Not found</h1>", status_code=404)
if _week_status(connection, account["account_id"], week_id) == "skipped":
return RedirectResponse(f"/weekly-menu/{week_id}?error=skipped", status_code=303)
plan = _subscription(connection, account["account_id"])
chosen = _selections(connection, account["account_id"], week_id)
if action == "remove":
connection.execute(
"DELETE FROM selections WHERE account_id=? AND week_id=? AND recipe_id=?",
(account["account_id"], week_id, recipe_id),
)
else:
if recipe_id not in chosen and len(chosen) >= plan["recipes_per_week"]:
connection.commit()
return RedirectResponse(f"/weekly-menu/{week_id}?error=full", status_code=303)
connection.execute(
"INSERT OR REPLACE INTO selections (account_id, week_id, recipe_id, quantity)"
" VALUES (?,?,?,1)",
(account["account_id"], week_id, recipe_id),
)
connection.commit()
return RedirectResponse(f"/weekly-menu/{week_id}", status_code=303)
@app.post("/weekly-menu/{week_id}/skip")
def skip_week(request: Request, week_id: str, action: str = Form("skip")):
account = current_account(request)
if account is None:
return RedirectResponse(f"/login?next=/weekly-menu/{week_id}", status_code=303)
with db() as connection:
status = "skipped" if action == "skip" else "open"
connection.execute(
"INSERT OR REPLACE INTO week_status (account_id, week_id, status) VALUES (?,?,?)",
(account["account_id"], week_id, status),
)
if status == "skipped":
connection.execute(
"DELETE FROM selections WHERE account_id=? AND week_id=?",
(account["account_id"], week_id),
)
connection.commit()
return RedirectResponse(f"/weekly-menu/{week_id}", status_code=303)
def _render_week(request, connection, weeks, week):
rows = connection.execute(
"SELECT r.*, m.category FROM menu_items m JOIN recipes r ON r.id = m.recipe_id "
"WHERE m.week_id = ? ORDER BY m.position",
(week["id"],),
).fetchall()
items = []
for row in rows:
item = dict(row)
item["tags"] = [
r["tag"]
for r in connection.execute(
"SELECT tag FROM recipe_tags WHERE recipe_id=? ORDER BY position", (row["id"],)
)
]
item["badges"] = [
r["badge"]
for r in connection.execute(
"SELECT badge FROM recipe_badges WHERE recipe_id=? ORDER BY position", (row["id"],)
)
]
items.append(item)
# The source groups the week into "Meals" and "Add-ons", each with its own
# heading, lede and carousel; the headline count covers meals only.
groups = []
for title, lede in (
("Meals", "Get cooking with these easy-to-follow recipes."),
("Add-ons", "Compliment your meals and grab the essentials each week with these handy add-ons."),
):
members = [i for i in items if i.get("category") == title]
if members:
groups.append({"title": title, "lede": lede, "cards": members})
meals = [i for i in items if i.get("category") == "Meals"]
account = current_account(request)
basket = None
if account is not None:
plan = _subscription(connection, account["account_id"])
chosen = _selections(connection, account["account_id"], week["id"])
basket = {
"chosen": chosen,
"count": len(chosen),
"allowance": plan["recipes_per_week"],
"people": plan["people"],
"status": _week_status(connection, account["account_id"], week["id"]),
}
error = request.query_params.get("error")
return templates.TemplateResponse(
request, "weekly_menu.html",
shell(request, weeks=weeks, week=week, items=items, groups=groups, meals=meals,
basket=basket, error=error),
)
@app.get("/recipes/{slug}", response_class=HTMLResponse)
def recipe_detail(request: Request, slug: str, week: str | None = None, steps: str | None = Query(None)):
with db() as connection:
recipe = _recipe_row(connection, slug)
if recipe is None:
return HTMLResponse("<h1>Recipe not found</h1>", status_code=404)
expanded = steps == "open"
query = [] if expanded else ["steps=open"]
if week:
query.append(f"week={week}")
return templates.TemplateResponse(
request,
"recipe.html",
shell(
request,
recipe=recipe,
steps_expanded=expanded,
toggle_query="&".join(query),
),
)
|