File size: 91,287 Bytes
34be7eb | 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 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 | #!/usr/bin/env python3
from __future__ import annotations
import html
import json
import os
import re
import sqlite3
import sys
from datetime import UTC, datetime
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlencode, urlparse
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
from backend.site_backend_integration import open_site_services # noqa: E402
from websitebench.local_clone_auth import AuthError # noqa: E402
CATS = [
("produce", "Produce"),
("meat-seafood", "Meat & Seafood"),
("dairy-eggs", "Dairy & Eggs"),
("bakery", "Bakery"),
("prepared", "Prepared Meals"),
("pantry", "Pantry"),
("beverages", "Beverages"),
("frozen", "Frozen"),
]
CAT = dict(CATS)
SEED = [
(
"Family Tree Farms",
"Jumbo Ultra-Premium Blueberries",
"produce",
"9.8oz",
8.99,
"organic",
),
("FreshDirect", "Banana Bunch", "produce", "approx. 3 lb", 2.19, "vegan"),
("Rainier", "Organic Honeycrisp Apples", "produce", "4 ct", 8.99, "organic"),
("Fage", "TOTAL 0% Greek Yogurt, Plain", "dairy-eggs", "32 oz", 6.49, "vegetarian"),
(
"Canada Dry",
"Sparkling Seltzer Water, Original",
"beverages",
"12 ct",
9.39,
"vegan",
),
(
"Just FreshDirect",
"Local Organic Large Brown Eggs",
"dairy-eggs",
"1 dozen",
4.99,
"organic",
),
("Ithaca", "Jalapeño Lime Hummus", "prepared", "10 oz", 6.69, "vegan"),
("FreshDirect", "Lemons", "produce", "each", 0.99, "vegan"),
("Driscoll's", "Strawberries", "produce", "16 oz", 4.49, "vegan"),
(
"FreshDirect",
"Wild-Caught Tuna and White Bean Salad",
"prepared",
"14 oz",
12.99,
"high-protein",
),
(
"Pete & Gerry's",
"Organic Pasture Raised Large Eggs",
"dairy-eggs",
"1 dozen",
7.29,
"organic",
),
("FreshDirect", "Seedless Watermelon", "produce", "13–18 lb", 7.99, "vegan"),
(
"Blue Foot",
"White Shrimp, Cleaned",
"meat-seafood",
"1 lb",
15.29,
"high-protein",
),
(
"FreshDirect",
"Wild Alaskan Sockeye Salmon Fillet",
"meat-seafood",
"1 lb",
25.99,
"high-protein",
),
("Momofuku", "Soy & Scallion Noodles", "pantry", "14.2 oz", 12.19, "vegetarian"),
(
"Veselka",
"Classic Potato & Cheese Dumplings",
"frozen",
"10 oz",
12.99,
"vegetarian",
),
("Rao's", "Penne Alla Vodka", "frozen", "9 oz", 8.19, "vegetarian"),
("Deer Run Farms", "Bunched Carrots", "produce", "1 lb", 2.99, "vegan"),
("FreshDirect", "Local Sourdough Boule", "bakery", "18 oz", 6.49, "vegetarian"),
(
"FreshDirect",
"Rotisserie Chicken",
"prepared",
"serves 2–3",
9.99,
"high-protein",
),
("Tropicana", "Pure Premium Orange Juice", "beverages", "89 fl oz", 9.99, "vegan"),
(
"Chobani",
"Non-Fat Greek Yogurt, Plain",
"dairy-eggs",
"32 oz",
7.39,
"vegetarian",
),
(
"Roberta's",
"Wood Fired Margherita Pizza",
"frozen",
"9.8 oz",
13.49,
"vegetarian",
),
]
NOUNS = {
"produce": [
"Avocados",
"Gala Apples",
"Baby Spinach",
"Mini Cucumbers",
"Navel Oranges",
"Romaine Hearts",
],
"meat-seafood": [
"Atlantic Salmon",
"Chicken Breast",
"Grass-Fed Ground Beef",
"Sea Scallops",
"Turkey Cutlets",
"Cod Fillet",
],
"dairy-eggs": [
"Whole Milk",
"Salted Butter",
"Cheddar Cheese",
"Vanilla Yogurt",
"Free Range Eggs",
"Oat Milk",
],
"bakery": [
"French Baguette",
"Everything Bagels",
"Butter Croissants",
"Whole Wheat Bread",
"Blueberry Muffins",
"Brioche Rolls",
],
"prepared": [
"Chicken Noodle Soup",
"Caesar Salad",
"Vegetable Lasagna",
"Turkey Meatballs",
"Quinoa Bowl",
"Macaroni & Cheese",
],
"pantry": [
"Extra Virgin Olive Oil",
"Tomato Sauce",
"Basmati Rice",
"Black Beans",
"Peanut Butter",
"Sea Salt Crackers",
],
"beverages": [
"Sparkling Water",
"Cold Brew Coffee",
"Lemon Iced Tea",
"Apple Juice",
"Coconut Water",
"Ginger Kombucha",
],
"frozen": [
"Mixed Berries",
"Vegetable Dumplings",
"Vanilla Ice Cream",
"French Fries",
"Cheese Ravioli",
"Mango Chunks",
],
}
BRANDS = [
"FreshDirect",
"Green Valley",
"Hudson Market",
"City Pantry",
"Farmstead",
"Good & Gathered",
]
def make_product(
product_number,
brand,
name,
category,
size,
price,
diet,
available=True,
):
return {
"id": f"p{product_number:03d}",
"brand": brand,
"name": name,
"category": category,
"size": size,
"price": price,
"diet": diet,
"available": available,
"sale": product_number % 4 == 0,
"snap": product_number % 7 != 0,
"rating": round(4 + (product_number % 10) / 10, 1),
}
def catalog():
out = [make_product(i, *row, i % 5 != 0) for i, row in enumerate(SEED, 1)]
i = len(out) + 1
while len(out) < 240:
c, _ = CATS[(i - 1) % len(CATS)]
names = NOUNS[c]
n = names[((i - 1) // len(CATS)) % len(names)]
v = ((i - 1) // (len(CATS) * len(names))) + 1
if v > 1:
n += f", {['Classic', 'Organic', 'Family Size', 'Chef Select'][v % 4]}"
out.append(
make_product(
i,
BRANDS[((i - 1) // 7) % len(BRANDS)],
n,
c,
["8 oz", "12 oz", "16 oz", "24 oz", "each", "4 ct"][i % 6],
round(2.49 + ((i * 37) % 1800) / 100, 2),
["vegan", "organic", "vegetarian", "gluten-free", "classic"][i % 5],
i % 17 != 0,
)
)
i += 1
return out
PRODUCTS = catalog()
BLUEBERRY_OVERRIDES = [
(
"p024",
"FreshDirect",
"Organic Blueberries",
"11 oz",
8.99,
"search-blueberries-00.png",
),
(
"p025",
"Naturipe",
"Sweet Selections Blueberries",
"11 oz",
7.99,
"search-blueberries-01.png",
),
("p026", "FreshDirect", "Blueberries", "18 oz", 9.99, "search-blueberries-02.png"),
(
"p027",
"Wyman's",
"Wild Blueberries, Frozen",
"15 oz",
5.39,
"search-blueberries-03.png",
),
(
"p028",
"Driscoll's",
"Limited Edition Sweetest Batch Blueberries",
"11 oz",
7.49,
"search-blueberries-04.png",
),
(
"p029",
"Wyman's",
"Wild Blueberries, Frozen Family Size",
"3 lb",
13.99,
"search-blueberries-05.png",
),
(
"p030",
"Cascadian Farm",
"Organic Blueberries, Frozen",
"28 oz",
10.49,
"search-blueberries-06.png",
),
(
"p031",
"FreshDirect",
"Organic Blueberries, Family Pack",
"18 oz",
12.99,
"search-blueberries-07.png",
),
]
for product_id, brand, name, size, price, _asset in BLUEBERRY_OVERRIDES:
product = next(p for p in PRODUCTS if p["id"] == product_id)
product.update(
brand=brand,
name=name,
size=size,
price=price,
category="produce",
diet="organic",
available=True,
)
BLUEBERRY_NAMES = [
("Wild Maine Blueberries, Frozen", "frozen"),
("Blueberry Pie", "bakery"),
("Blueberry Greek Yogurt", "dairy-eggs"),
("Blueberry Almond Breakfast Bars", "pantry"),
("Blueberry Scones", "bakery"),
("Blueberry Muffins", "bakery"),
("Blueberry Pancakes, Frozen", "frozen"),
("Blueberry Waffles, Frozen", "frozen"),
("Blueberry Bagels", "bakery"),
("Blueberry Cream Cheese", "dairy-eggs"),
("Blueberry Kefir", "dairy-eggs"),
("Blueberry Oatmeal Cups", "pantry"),
("Blueberry Granola", "pantry"),
("Blueberry Preserves", "pantry"),
("Blueberry Fruit Spread", "pantry"),
("Blueberry Lemon Kombucha", "beverages"),
("Blueberry Pomegranate Juice", "beverages"),
("Blueberry Smoothie", "beverages"),
("Blueberry Acai Bowl, Frozen", "frozen"),
("Blueberry Cheesecake", "bakery"),
("Blueberry Hand Pies", "bakery"),
("Blueberry Turnovers", "bakery"),
("Blueberry Pound Cake", "bakery"),
("Blueberry Crumb Cake", "bakery"),
("Blueberry Breakfast Biscuits", "pantry"),
("Blueberry Cashew Bars", "pantry"),
("Blueberry Protein Bars", "pantry"),
("Blueberry Fruit Snacks", "pantry"),
("Blueberry Applesauce Pouches", "pantry"),
("Blueberry Baby Food", "pantry"),
("Blueberry Chia Pudding", "prepared"),
("Blueberry Overnight Oats", "prepared"),
("Blueberry Skyr", "dairy-eggs"),
("Blueberry Cottage Cheese", "dairy-eggs"),
("Blueberry Goat Cheese", "dairy-eggs"),
("Blueberry Ice Cream", "frozen"),
("Blueberry Sorbet", "frozen"),
("Blueberry Frozen Yogurt", "frozen"),
("Blueberry Lemonade", "beverages"),
("Blueberry Sparkling Water", "beverages"),
("Blueberry Herbal Tea", "beverages"),
("Blueberry Coffee Cake", "bakery"),
("Blueberry Donuts", "bakery"),
("Blueberry Mini Tarts", "bakery"),
("Blueberry Galette", "bakery"),
("Blueberry Cobbler", "bakery"),
("Blueberry Crisp", "bakery"),
("Blueberry Pie Filling", "pantry"),
("Blueberry Baking Mix", "pantry"),
("Blueberry Pancake Mix", "pantry"),
("Blueberry Syrup", "pantry"),
("Blueberry Honey", "pantry"),
("Dried Blueberries", "pantry"),
("Chocolate Covered Blueberries", "pantry"),
("Blueberry Trail Mix", "pantry"),
("Blueberry Nut Mix", "pantry"),
("Blueberry Cereal", "pantry"),
("Blueberry Oat Cereal", "pantry"),
("Blueberry Fruit & Grain Bars", "pantry"),
]
assert len(BLUEBERRY_NAMES) == 59
for index, (name, category) in enumerate(BLUEBERRY_NAMES, 32):
product = next(p for p in PRODUCTS if p["id"] == f"p{index:03d}")
product.update(
brand=BRANDS[(index - 32) % len(BRANDS)],
name=name,
category=category,
size=("8 oz", "12 oz", "16 oz", "4 ct")[(index - 32) % 4],
price=round(3.49 + ((index * 29) % 850) / 100, 2),
diet=("vegetarian" if category in {"dairy-eggs", "bakery"} else "vegan"),
available=True,
)
BY_ID = {p["id"]: p for p in PRODUCTS}
# Express intentionally exposes a smaller deterministic assortment than
# Standard delivery. Keep the source-observed blueberry journey inside it.
EXPRESS_PRODUCT_IDS = frozenset(f"p{number:03d}" for number in range(1, 121))
SERVICES = None
ASSET_FOR = {
"p001": "home-00.png",
"p002": "home-01.png",
"p003": "home-02.png",
"p004": "home-03.png",
"p005": "home-04.png",
"p006": "home-05.png",
"p007": "home-06.png",
"p008": "home-07.png",
**{product_id: asset for product_id, *_, asset in BLUEBERRY_OVERRIDES},
}
DETAIL_ASSET_FOR = {"p001": "product-blueberries-00.png"}
SERVICE_AREAS = {
"11201": {
"label": "Brooklyn",
"modes": frozenset({"delivery", "express", "pickup"}),
"unavailable": frozenset(),
"pickup_location": "Brooklyn local test hub",
},
"10001": {
"label": "Manhattan",
"modes": frozenset({"delivery", "express"}),
"unavailable": frozenset({"p001"}),
"pickup_location": "",
},
}
FULFILLMENT_LABELS = {
"delivery": "Standard delivery",
"express": "Express delivery",
"pickup": "Pickup",
}
SLOT_LABELS = {
"today-6-7": "Today, 6–7 PM",
"tomorrow-8-10": "Tomorrow, 8–10 AM",
"tomorrow-10-12": "Tomorrow, 10 AM–12 PM",
}
SLOTS_BY_MODE = {
"delivery": frozenset({"tomorrow-8-10", "tomorrow-10-12"}),
"express": frozenset({"today-6-7"}),
"pickup": frozenset({"tomorrow-10-12"}),
}
PRODUCT_VARIANTS = {
"p001": {
"classic": "p001",
"organic": "p024",
"family": "p031",
}
}
def esc(v):
return html.escape(str(v), quote=True)
def money(v):
return f"${v:,.2f}"
def stamp():
return datetime.now(UTC).isoformat().replace("+00:00", "Z")
def service_area(state):
return SERVICE_AREAS.get(state.get("zip", ""))
def product_available(product, state, fulfillment=None):
area = service_area(state)
if area is None:
# Anonymous browsing may build a provisional cart; service-area
# confirmation is enforced before fulfillment and checkout.
return bool(product["available"])
mode = fulfillment or state.get("fulfillment")
return bool(
product["available"]
and product["id"] not in area["unavailable"]
and (mode != "express" or product["id"] in EXPRESS_PRODUCT_IDS)
)
def query_matches(product, query):
haystack = f"{product['brand']} {product['name']}".casefold()
needle = query.casefold()
if needle == "blueberries" and (
product["id"] == "p001" or "p024" <= product["id"] <= "p090"
):
return "blueberr" in haystack
return needle in haystack
def sub_options(current):
return "".join(
f'<option value="{value}" {"selected" if current == value else ""}>{label}</option>'
for value, label in (
("best", "Best available"),
("contact", "Contact me"),
("none", "No substitute"),
)
)
def product_media(p, detail=False):
asset = (DETAIL_ASSET_FOR if detail else ASSET_FOR).get(p["id"])
if asset:
return f'<img src="/static/assets/{asset}" alt="{esc(p["brand"])} {esc(p["name"])}" loading="{"eager" if detail else "lazy"}">'
return f'<span class="art-fallback" aria-hidden="true">{esc(p["name"][0])}</span>'
def nav_icon(kind):
paths = {
"produce": '<circle cx="12" cy="13" r="7"/><path d="M12 6c0-3 2-5 5-5M13 5c-2-3-5-3-6-1"/>',
"meat-seafood": '<path d="M4 8c5-5 13-3 16 2-2 7-11 9-16 3-2 1-3 0-3-2s1-3 3-3Z"/><circle cx="16" cy="9" r="1"/>',
"dairy-eggs": '<path d="M8 3h8l2 5v13H6V8l2-5Z"/><path d="M8 8h10M9 3v5"/>',
"bakery": '<path d="M3 16c0-6 4-10 9-10s9 4 9 10v3H3v-3Z"/><path d="m8 8 2 3m3-4 2 3"/>',
"beverages": '<path d="M7 3h10l-2 18H9L7 3Z"/><path d="M8 8h8M11 3l4-2"/>',
"frozen": '<path d="M12 1v22M2 6l20 12M2 18 22 6M8 3l4 4 4-4M8 21l4-4 4 4"/>',
"prepared": '<path d="M3 17h18M5 15a7 7 0 0 1 14 0H5ZM12 5V2"/>',
"pantry": '<path d="M5 7h14v14H5V7Zm3 0V3h8v4"/><path d="M9 12h6"/>',
"account": '<circle cx="12" cy="8" r="4"/><path d="M4 22c0-4.5 3.2-7 8-7s8 2.5 8 7"/>',
}
body = paths.get(
kind, '<path d="M3 5h18l-3 16H6L3 5Z"/><path d="M8 5a4 4 0 0 1 8 0"/>'
)
return f'<svg class="nav-svg" viewBox="0 0 24 24" aria-hidden="true">{body}</svg>'
MENU_SCRIPT = """<script>
const departmentTrigger=document.getElementById('department-menu-trigger');
const departmentMenu=document.getElementById('department-menu');
let departmentReturnFocus=null;
function setDepartmentMenu(open){
document.body.classList.toggle('nav-open',open);
departmentTrigger.setAttribute('aria-expanded',String(open));
if(open){
departmentReturnFocus=document.activeElement;
requestAnimationFrame(()=>departmentMenu.querySelector('.mobile-close').focus());
}else if(departmentReturnFocus){
departmentReturnFocus.focus();
}
}
document.addEventListener('keydown',event=>{
if(!document.body.classList.contains('nav-open'))return;
if(event.key==='Escape'){
event.preventDefault();setDepartmentMenu(false);return;
}
if(event.key!=='Tab')return;
const controls=[...departmentMenu.querySelectorAll('a[href],button:not([disabled])')].filter(node=>node.offsetParent!==null);
if(!controls.length)return;
const first=controls[0],last=controls[controls.length-1];
if(event.shiftKey&&document.activeElement===first){event.preventDefault();last.focus();}
else if(!event.shiftKey&&document.activeElement===last){event.preventDefault();first.focus();}
});
</script>"""
class FormError(ValueError):
def __init__(self, status, message):
super().__init__(message)
self.status = status
def services():
global SERVICES
if SERVICES:
return SERVICES
backend, auth = open_site_services()
with backend.lifecycle.connection(transaction=True) as db:
db.executescript(
"""CREATE TABLE IF NOT EXISTS fd_state(owner TEXT PRIMARY KEY,zip TEXT NOT NULL DEFAULT '',fulfillment TEXT NOT NULL DEFAULT 'delivery',slot TEXT NOT NULL DEFAULT '',coupon TEXT NOT NULL DEFAULT '',address TEXT NOT NULL DEFAULT '{}',updated TEXT NOT NULL);CREATE TABLE IF NOT EXISTS fd_cart(owner TEXT NOT NULL,product_id TEXT NOT NULL,qty INTEGER NOT NULL CHECK(qty BETWEEN 1 AND 20),substitution TEXT NOT NULL CHECK(substitution IN('best','contact','none')),PRIMARY KEY(owner,product_id));CREATE TABLE IF NOT EXISTS fd_favorites(owner TEXT NOT NULL,product_id TEXT NOT NULL,PRIMARY KEY(owner,product_id));CREATE TABLE IF NOT EXISTS fd_orders(order_id TEXT PRIMARY KEY,account_id TEXT NOT NULL,status TEXT NOT NULL,delivered TEXT NOT NULL,items TEXT NOT NULL,total INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS fd_support(id INTEGER PRIMARY KEY,owner TEXT NOT NULL,topic TEXT NOT NULL,details TEXT NOT NULL,status TEXT NOT NULL,created TEXT NOT NULL);"""
)
account = auth.seed_account(
subject_id="freshdirect-demo-shopper",
email="shopper@freshdirect.local",
display_name="Alex Shopper",
password="Fresh123!",
)
with backend.lifecycle.connection(transaction=True) as db:
db.execute(
"INSERT OR IGNORE INTO fd_orders VALUES(?,?,?,?,?,?)",
(
"FD-10482",
account,
"Delivered",
"2026-08-18",
json.dumps([["p001", 1], ["p006", 2], ["p018", 1]]),
2196,
),
)
SERVICES = (backend, auth)
return SERVICES
def card(p, favs, state):
available = product_available(p, state)
area = service_area(state)
disabled = "" if available else " disabled"
if available and area:
stock = f'<span class="in-stock">Available in {esc(area["label"])}</span>'
elif area:
stock = (
f'<span class="out">Unavailable for Express in {esc(area["label"])} '
"(limited assortment)</span>"
if state.get("fulfillment") == "express"
and p["id"] not in EXPRESS_PRODUCT_IDS
else f'<span class="out">Currently unavailable in {esc(area["label"])}</span>'
)
else:
stock = '<span class="availability-unknown">Set a supported ZIP to confirm availability</span>'
express = (
'<span class="express">EXPRESS</span>'
if area
and "express" in area["modes"]
and product_available(p, state, "express")
else ""
)
return f'''<article class="card" data-product="{p["id"]}"><div class="product-media">{product_media(p)}<form method="post" action="/favorite/toggle"><input type="hidden" name="product_id" value="{p["id"]}"><button class="save" aria-label="{"Remove" if p["id"] in favs else "Add"} {esc(p["name"])} {"from" if p["id"] in favs else "to"} Shopping List"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3h12v18l-6-4-6 4V3Z"/></svg></button></form>{"<span class='quality'>★★★★ EXCELLENT</span>" if p["rating"] >= 4.8 else ""}{express}<form class="quick-add" method="post" action="/cart/add"><input type="hidden" name="product_id" value="{p["id"]}"><input type="hidden" name="qty" value="1"><input type="hidden" name="substitution" value="best"><button class="add" aria-label="Add {esc(p["name"])} to bag"{disabled}>+</button></form></div><a class="product-copy" href="/product/{p["id"]}"><small>{esc(p["brand"])}</small><h3>{esc(p["name"])}</h3><strong>{money(p["price"])}/ea</strong><span class="size">approx. {esc(p["size"])}</span></a>{stock}{"<span class='badge'>SNAP</span>" if p["snap"] else ""}{"<span class='deal-copy'>Save 18%</span>" if p["sale"] else ""}</article>'''
def shell(title, body, session, state, count, q=""):
acct = session.get("account") if session else None
label = acct["display_name"].split()[0] if acct else "Sign in"
area = service_area(state)
mode_label = FULFILLMENT_LABELS.get(state.get("fulfillment"), "Delivery")
location_label = (
f'{area["label"]} {state["zip"]}' if area else "Enter your address"
)
nav_items = [
("deals", "Deals & Sale", "/search?deal=1"),
("prepared", "Prepared & Deli", "/department/prepared"),
("produce", "Produce", "/department/produce"),
("meat-seafood", "Meat & Poultry", "/department/meat-seafood"),
("meat-seafood", "Seafood", "/department/meat-seafood"),
("dairy-eggs", "Dairy", "/department/dairy-eggs"),
("beverages", "Beverages", "/department/beverages"),
("bakery", "Bakery", "/department/bakery"),
("frozen", "Frozen", "/department/frozen"),
("pantry", "Grocery", "/department/pantry"),
("beverages", "Wine & Spirits", "/search?q=wine"),
("frozen", "Seasonal", "/search?new=1"),
]
dept = "".join(
f'<a href="{href}">{nav_icon(icon)}<span>{name}</span><i aria-hidden="true"></i></a>'
for icon, name, href in nav_items
)
bag_items = (
f'<h2>Your bag <span>({count})</span></h2><a class="drawer-close" href="#" onclick="document.getElementById(\'bag-drawer\').close();return false" aria-label="Close bag">×</a>'
+ (
f'<p class="bag-count">{count} local items are ready to review.</p><a class="btn block" href="/cart">View your bag</a>'
if count
else '<div class="drawer-empty"><h3>Your bag is empty</h3><p>Let’s find something for you to enjoy!</p><a class="btn" href="/search">Start shopping</a></div>'
)
)
return f'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{esc(title)} | FreshDirect</title><link rel="stylesheet" href="/static/styles.css"></head><body><a class="skip" href="#main">Skip to content</a><div class="offer">Get <b>$50 OFF</b> your first order!* Use code: <u>NEW50</u> <span>*Min. order $99</span><button onclick="this.parentElement.hidden=true" aria-label="Dismiss banner">×</button></div><header><div class="mast"><button id="department-menu-trigger" class="menu" onclick="setDepartmentMenu(true)" aria-controls="department-menu" aria-expanded="false" aria-label="Open departments"><span></span><span></span><span></span></button><a class="logo" href="/" aria-label="FreshDirect home"><span>fresh</span><b>direct</b>.</a><button class="delivery" onclick="document.getElementById('loc').showModal()"><b>{esc(mode_label)}</b><u>{esc(location_label)}</u></button><form class="search" action="/search"><label class="sr" for="q">Search groceries</label><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="10" cy="10" r="6"/><path d="m15 15 6 6"/></svg><input id="q" name="q" value="{esc(q)}" placeholder="What's on your shopping list?"><button class="sr">Search</button></form><a class="business" href="/help"><b>Go to</b><span>fd Business ›</span></a><div class="account"><b>Account</b><a href="/account">{esc(label)}</a>{"" if acct else ' <span>or</span> <a href="/signin">create account</a>'}</div><button class="bag" onclick="document.getElementById('bag-drawer').showModal()" aria-label="Your Bag with {count} items"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 8h14l-1 13H6L5 8Zm3 0a4 4 0 0 1 8 0"/></svg><em>{count}</em></button></div><nav id="department-menu" class="dept" aria-label="Departments"><button class="mobile-close" onclick="setDepartmentMenu(false)" aria-label="Close departments">×</button><div class="mobile-delivery">{nav_icon("pantry")}<b>{esc(mode_label)}</b><button onclick="document.getElementById('loc').showModal()"><u>{esc(location_label)}</u></button></div>{dept}<div class="mobile-account">{nav_icon("account")}<span class="mobile-account-links"><a href="/account">{esc(label)}</a>{"" if acct else ' <span>or</span> <a href="/signin">create account</a>'}</span></div></nav></header><dialog id="loc" class="location-dialog"><form method="post" action="/location"><button class="dialog-x" type="button" onclick="document.getElementById('loc').close()" aria-label="Close location">×</button><h2>Where should we deliver?</h2><p>Use synthetic ZIP 11201 (Brooklyn) or 10001 (Manhattan). Pickup is available in 11201.</p><label>ZIP code<input name="zip" pattern="[0-9]{{5}}" value="{esc(state.get("zip", ""))}" required></label><div class="radio-row"><label><input type="radio" name="fulfillment" value="delivery" {"checked" if state.get("fulfillment") != "pickup" else ""}> Delivery</label><label><input type="radio" name="fulfillment" value="pickup" {"checked" if state.get("fulfillment") == "pickup" else ""}> Pickup</label></div><button class="primary">Save location</button></form></dialog><dialog id="bag-drawer" class="bag-drawer">{bag_items}</dialog><main id="main">{body}</main><footer><div><a class="footer-logo" href="/">freshdirect.</a><p>Fresh food and groceries, delivered.</p></div><nav><a href="/help">Customer service</a><a href="/orders">Your orders</a><a href="/support">Local support requests</a><a href="/search">Browse groceries</a></nav><p class="disclosure">Independent offline demonstration. No real orders, payments, emails, or deliveries occur.</p></footer>{MENU_SCRIPT}</body></html>'''
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'<div class="notice" role="status">{esc(notice[-1])}</div>' + 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'<section class="shelf"><div class="shelf-head"><h2>{title}</h2><a href="{href}">View all</a></div><div class="product-row">{"".join(card(p, self.favs, self.state) for p in items)}</div></section>'
shortcuts = [
(
"produce",
"Peak Quality",
"See the season's best",
"/department/produce",
),
("pantry", "New products", "Discover something new", "/search?new=1"),
("deals", "Flash savings", "Last chance! Save big", "/search?deal=1"),
(
"prepared",
"DeliveryPass",
"Get 60 days free delivery",
"/help#delivery-pass",
),
(
"prepared",
"Prepared meals",
"Ready in minutes",
"/department/prepared",
),
]
shortcut_html = "".join(
f'<a href="{href}">{nav_icon(icon)}<span><b>{name}</b><small>{copy}</small></span></a>'
for icon, name, copy, href in shortcuts
)
body = f"""<section class="hero"><div class="hero-copy"><h1>Welcome to FreshDirect</h1><p>Get first-pick produce, custom-cut meat, fresh-caught seafood, and more—delivered up to 7 days fresher than the grocery store.</p><a class="btn" href="/search">Start shopping</a></div><div class="hero-collage"><div>{product_media(BY_ID["p001"], True)}</div><div>{product_media(BY_ID["p002"])}</div><div>{product_media(BY_ID["p003"])}</div></div></section><section class="shortcuts"><div class="express-switch"><b>EXPRESS</b><span></span></div>{shortcut_html}</section><aside class="snap-popover"><button onclick="this.parentElement.hidden=true" aria-label="Close EBT announcement"><span></span></button><h2>Now accepting SNAP EBT!</h2><div class="snap-mark">SNAP</div><p>Shop your FreshDirect favorites and pay with SNAP EBT.</p><a class="btn" href="/search?snap=1">Show SNAP-eligible items</a></aside>{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")}<section class="editorial"><div><span>Now accepting SNAP/EBT</span><h2>Fresh food should be within reach</h2><p>Shop pantry essentials, dairy, produce, and more with local SNAP eligibility indicators.</p><a href="/search?snap=1">View all</a></div></section>{shelf("Peak Quality produce: Get our experts' recommendations.", PRODUCTS[1:13], "/department/produce")}<section class="deliverypass"><h2>Skip the delivery fees</h2><p>Shop whenever you like with local DeliveryPass information.</p><a href="/help#delivery-pass">See delivery details</a></section>"""
return self.page("Grocery Delivery Service", body)
if path == "/search" or path.startswith("/department/"):
category = (
path.split("/", 2)[2]
if path.startswith("/department/")
else qs.get("category", [""])[0]
)
q = qs.get("q", [""])[0].strip()
diet = qs.get("diet", [""])[0]
deal = qs.get("deal", [""])[0] == "1"
snap = qs.get("snap", [""])[0] == "1"
new = qs.get("new", [""])[0] == "1"
sort = qs.get("sort", ["featured"])[0]
items = [
p
for p in PRODUCTS
if (not category or p["category"] == category)
and (not q or query_matches(p, q))
and (not diet or p["diet"] == diet)
and (not deal or p["sale"])
and (not snap or p["snap"])
]
if sort == "price-low":
items.sort(key=lambda p: p["price"])
if sort == "price-high":
items.sort(key=lambda p: -p["price"])
if sort == "name":
items.sort(key=lambda p: p["name"])
if new:
items = list(reversed(items))[:60]
title = q.casefold() if q else CAT.get(category, "All groceries")
opts = "".join(
f'<option value="{s}" {"selected" if s == category else ""}>{n}</option>'
for s, n in CATS
)
diets = "".join(
f"<option {'selected' if d == diet else ''}>{d}</option>"
for d in [
"organic",
"vegan",
"vegetarian",
"gluten-free",
"high-protein",
]
)
sort_options = "".join(
f'<option value="{value}" {"selected" if sort == value else ""}>{label}</option>'
for value, label in (
("featured", "featured"),
("price-low", "price-low"),
("price-high", "price-high"),
("name", "name"),
)
)
filters = f'''<details class="refine"><summary><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 7h16M7 12h10M10 17h4"/></svg>Refine</summary><form class="filters" action="/search"><input type="hidden" name="q" value="{esc(q)}"><label>Department<select name="category"><option value="">All</option>{opts}</select></label><label>Dietary<select name="diet"><option value="">All</option>{diets}</select></label><label>Sort<select name="sort">{sort_options}</select></label><label><input type="checkbox" name="deal" value="1" {"checked" if deal else ""}> Deals</label><label><input type="checkbox" name="snap" value="1" {"checked" if snap else ""}> SNAP</label><button>Apply</button></form></details>'''
empty = '<div class="empty"><h2>No groceries found</h2><p>Try a broader search or clear filters.</p><a class="btn" href="/search">Clear filters</a></div>'
heading = f"{esc(title)} <span>({len(items)})</span>"
promo = (
'<aside class="search-promo"><div><b>High Holiday meals</b><span>Reserve ahead by 9/4. <strong>Pre-order unavailable offline</strong></span></div><i></i><i></i><i></i></aside>'
if items
else ""
)
return self.page(
title,
f'<section class="catalog-head"><h1>{heading}</h1></section>{filters}{promo}<section class="search-grid grid">{"".join(card(p, self.favs, self.state) for p in items) if items else empty}</section>',
q,
)
if path.startswith("/product/"):
p = BY_ID.get(path.rsplit("/", 1)[-1])
if not p:
return self.not_found()
choices = "".join(f"<option>{i}</option>" 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'<div class="gallery-main">{product_media(p, True)}</div>'
if p["id"] == "p001":
gallery += '<div class="gallery-thumbs"><img src="/static/assets/product-blueberries-00.png" alt="Blueberries package view"><img src="/static/assets/product-blueberries-01.png" alt="Blueberries serving view"></div>'
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'<option value="{value}" data-price="{variant["price"]}" '
f'data-size="{esc(variant["size"])}" '
f'data-available="{str(product_available(variant, self.state)).lower()}">'
f'{variant_labels[value]} — {esc(variant["size"])} — {money(variant["price"])}</option>'
)
variant_control = (
'<label>Size / variety<select name="variant" id="variant">'
+ "".join(variant_options)
+ "</select></label>"
)
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 = (
'<p><span class="express">EXPRESS</span> available for this location</p>'
if area
and "express" in area["modes"]
and product_available(p, self.state, "express")
else ""
)
detail_script = '''<script>
const variant=document.getElementById('variant');
const quantity=document.querySelector('.sticky-buy select[name="qty"]');
const priceLine=document.querySelector('.product-price');
const totalLine=document.querySelector('.sticky-buy > strong');
const availabilityLine=document.querySelector('.product-availability');
const addButton=document.querySelector('.sticky-buy .primary');
function refreshPurchase(){
const option=variant?variant.selectedOptions[0]:null;
const price=option?Number(option.dataset.price):Number(document.querySelector('.sticky-buy').dataset.price);
const size=option?option.dataset.size:document.querySelector('.sticky-buy').dataset.size;
const available=option?option.dataset.available==='true':document.querySelector('.sticky-buy').dataset.available==='true';
priceLine.innerHTML=`<b>$${price.toFixed(2)}/ea</b> | approx. ${size}`;
totalLine.textContent=`Total $${(price*Number(quantity.value)).toFixed(2)}`;
addButton.disabled=!available;
addButton.textContent=available?'Add to bag':'Currently unavailable';
if(variant)availabilityLine.textContent=available?'Available for this location':'Currently unavailable for this location';
}
if(variant)variant.addEventListener('change',refreshPurchase);
quantity.addEventListener('change',refreshPurchase);
</script>'''
body = f'''<section class="detail"><div class="detail-copy"><p class="crumb"><a href="/department/{p["category"]}">{CAT[p["category"]]}</a> › <a href="/search?q={urlencode({"q": p["name"].split()[0]})[2:]}">Search similar items</a></p><h1>{esc(p["brand"])} {esc(p["name"])}</h1><a class="brand-link" href="/search?q={urlencode({"q": p["brand"]})[2:]}">Shop all {esc(p["brand"])}</a><p class="product-price"><b>{money(p["price"])}/ea</b> | approx. {esc(p["size"])}</p>{"<span class='badge'>SNAP</span>" if p["snap"] else ""}{express_copy}<p class="product-availability">{availability}</p><form class="list-form" method="post" action="/favorite/toggle"><input type="hidden" name="product_id" value="{p["id"]}"><button>{"Remove from list" if p["id"] in self.favs else "Add to list"}</button></form><div class="detail-info"><details open><summary>Description</summary><p>{esc(description)}</p></details><details><summary>Nutrition</summary><p>{esc(nutrition)}</p></details><details><summary>Ingredients</summary><p>{esc(ingredients)}</p></details></div></div><div class="detail-media">{gallery}</div></section><form class="sticky-buy" method="post" action="/cart/add" data-price="{p["price"]}" data-size="{esc(p["size"])}" data-available="{str(available).lower()}"><input type="hidden" name="product_id" value="{p["id"]}"><div class="purchase-options">{variant_control}<label>Qty<select name="qty">{choices}</select></label><label>Substitution<select name="substitution"><option value="best">Choose best substitute</option><option value="contact">Contact me</option><option value="none">Do not substitute</option></select></label></div><button class="primary"{disabled}>{"Add to bag" if available else "Currently unavailable"}</button><strong>Total {money(p["price"])}</strong></form>{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 = (
'<section class="account-head"><h1>Your Shopping Lists</h1><p>Saved separately from your cart.</p></section>'
+ (
'<section class="grid">{"".join(card(p,self.favs,self.state) for p in items)}</section>'
if False
else (
"<section class='grid'>"
+ "".join(card(p, self.favs, self.state) for p in items)
+ "</section>"
if items
else '<div class="empty"><h2>Your list is empty</h2><a class="btn" href="/search">Find favorites</a></div>'
)
)
)
return self.page("Shopping Lists", body)
if path == "/cart":
return self.page("Your cart", self.cart_page())
if path == "/checkout":
return self.page("Checkout review", self.checkout_page())
if path == "/signin":
return self.page(
"Sign in",
"""<section class="auth"><div class="auth-mark"><span>fresh</span><b>direct</b>.</div><h1>Sign in</h1><p>Sign in to manage your local shopping lists, cart, and account preferences.</p><form method="post" action="/signin"><label>Email address<input name="email" type="email" autocomplete="username" required></label><label>Password<input name="password" type="password" autocomplete="current-password" minlength="8" required></label><a class="forgot" href="/recover">Forgot password?</a><button class="primary">Sign in</button></form><div class="fixture"><b>Public local test account</b><code>shopper@freshdirect.local</code><code>Fresh123!</code><small>No email is sent and no external account is accessed.</small></div><p class="auth-create">New to FreshDirect? <a href="/register">Create a local account</a></p></section>""",
)
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"""<section class="account-head"><h1>Hello, {esc(a["display_name"].split()[0])}</h1><p>{esc(a["email_normalized"])}</p></section><div class="account-grid"><a href="/orders"><b>Your orders</b><span>Track and reorder</span></a><a href="/favorites"><b>Shopping lists</b><span>Plan future carts</span></a><a href="/cart"><b>Your cart</b><span>Review selections</span></a><a href="/help"><b>Customer service</b><span>Help and recovery</span></a></div><form method="post" action="/signout"><button>Sign out</button></form>""",
)
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'<article class="order"><b>{esc(r["status"])}</b><h2>Order {esc(r["order_id"])}</h2><p>{esc(names)} · {money(r["total"] / 100)}</p><a href="/orders/{esc(r["order_id"])}">View order details</a><form method="post" action="/reorder"><input type="hidden" name="order_id" value="{esc(r["order_id"])}"><button class="primary">Reorder these items</button></form></article>'
)
return self.page(
"Your orders",
'<section class="account-head"><h1>Your orders</h1><p>Review past local sandbox purchases.</p></section>'
+ "".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'<article class="support-request"><b>{esc(row["status"])}</b>'
f'<h2>{esc(row["topic"])}</h2><p>{esc(row["details"])}</p>'
f'<small>{esc(row["created"])}</small>'
+ (
f'<form method="post" action="/support/cancel"><input type="hidden" name="request_id" value="{row["id"]}"><button>Cancel local request</button></form>'
if row["status"] != "Cancelled locally"
else ""
)
+ "</article>"
for row in requests
)
return self.page(
"Local support requests",
'<section class="account-head"><h1>Local support requests</h1><p>These records stay in this sandbox; no message is sent.</p></section>'
+ (cards or '<div class="empty"><h2>No saved requests</h2><a class="btn" href="/help">Get local help</a></div>'),
)
if path == "/help":
return self.page(
"Customer service",
"""<section class="account-head"><h1>How can we help?</h1><p>Answers for shopping, delivery, substitutions, and recovery.</p></section><div class="faq"><details open><summary>How do I place an order?</summary><p>Browse or search, choose products, review the cart, then select delivery. This clone stops before submission.</p></details><details><summary>How do substitutions work?</summary><p>Choose the best replacement, request contact, or decline substitutions per item.</p></details><details id="delivery"><summary>What delivery options exist?</summary><p>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.</p></details><details id="delivery-pass"><summary>What is DeliveryPass?</summary><p>The source promotes delivery membership benefits. Membership enrollment and billing are intentionally unavailable in this local sandbox.</p></details></div><section class="support"><h2>Still need help?</h2><p><a href="/support">View or cancel saved local requests</a></p><form method="post" action="/support"><label>Topic<select name="topic"><option>Order question</option><option>Substitution</option><option>Delivery</option><option>Account</option></select></label><label>Details<textarea name="details" minlength="10" required></textarea></label><button class="primary">Save local support request</button></form></section>""",
)
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'<div class="fixture"><b>Local-only inbox</b><p>Local verification code: <code>{esc(mail["verification_code"])}</code></p><small>No email or external message was sent.</small></div>'
if mail
else ""
)
return f'''<section class="auth"><div class="auth-mark"><span>fresh</span><b>direct</b>.</div><h1>Verify your local account</h1><p>Enter the six-digit code from this session’s local-only inbox.</p>{local_code}<form method="post" action="/register/verify"><label>Verification code<input name="code" inputmode="numeric" pattern="[0-9]{{6}}" autocomplete="one-time-code" required></label><button class="primary">Verify and create account</button></form><p class="auth-create"><a href="/signin">Return to sign in</a></p></section>'''
return '''<section class="auth"><div class="auth-mark"><span>fresh</span><b>direct</b>.</div><h1>Create a local account</h1><p>This account exists only in the FreshDirect sandbox.</p><form method="post" action="/register"><label>Name<input name="display_name" autocomplete="name" maxlength="120" required></label><label>Email address<input name="email" type="email" autocomplete="email" required></label><label>Password<input name="password" type="password" autocomplete="new-password" minlength="8" maxlength="128" required></label><button class="primary">Continue locally</button></form><p class="fine">A verification code appears only in this browser’s local inbox. No email is sent.</p><p class="auth-create">Already have an account? <a href="/signin">Sign in</a></p></section>'''
def recovery_page(self):
status = self.auth.session_flow_status(self.token, purpose="password-reset")
if status["state"] == "verified":
return '''<section class="auth"><div class="auth-mark"><span>fresh</span><b>direct</b>.</div><h1>Choose a new local password</h1><p>The local verification challenge is complete.</p><form method="post" action="/recover/complete"><label>New password<input name="new_password" type="password" autocomplete="new-password" minlength="8" maxlength="128" required></label><label>Confirm password<input name="confirm_password" type="password" autocomplete="new-password" minlength="8" maxlength="128" required></label><button class="primary">Update local password</button></form></section>'''
if status["state"] == "challenge":
mail = self.auth.local_mail_for_session(
self.token, purpose="password-reset"
)
local_code = (
f'<div class="fixture"><b>Local-only inbox</b><p>Local verification code: <code>{esc(mail["verification_code"])}</code></p><small>No email or external message was sent.</small></div>'
if mail
else '<p class="fine">No local message is available. The public response is identical for unknown addresses.</p>'
)
return f'''<section class="auth"><div class="auth-mark"><span>fresh</span><b>direct</b>.</div><h1>Check the local inbox</h1><p>If that address belongs to a local account, a verification challenge is available below.</p>{local_code}<form method="post" action="/recover/verify"><label>Verification code<input name="code" inputmode="numeric" pattern="[0-9]{{6}}" autocomplete="one-time-code" required></label><button class="primary">Verify locally</button></form><p class="auth-create"><a href="/signin">Return to sign in</a></p></section>'''
return '''<section class="auth"><div class="auth-mark"><span>fresh</span><b>direct</b>.</div><h1>Recover local access</h1><p>Enter the email for your FreshDirect sandbox account.</p><form method="post" action="/recover"><label>Email address<input name="email" type="email" autocomplete="email" required></label><button class="primary">Continue locally</button></form><p class="fine">No external email is sent. The response does not reveal whether an account exists.</p><p class="auth-create"><a href="/signin">Return to sign in</a></p></section>'''
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'<div><span>{qty} × Retired catalog item</span><b>Unavailable</b></div>'
)
continue
line_total = product["price"] * qty
current_items_total += line_total
items.append(
f'<div><span>{qty} × <a href="/product/{product["id"]}">{esc(product["name"])}</a></span><b>{money(line_total)} today</b></div>'
)
historical_total = row["total"] / 100
historical_savings = max(0, current_items_total - historical_total)
return f'''<section class="account-head"><p>{esc(row["status"])}</p><h1>Order {esc(row["order_id"])}</h1><p>Delivered {esc(row["delivered"])}</p></section><div class="order-detail"><section><h2>Items</h2>{"".join(items)}<p class="fine">Today’s catalog prices are shown for reorder planning; historical prices may differ.</p></section><aside class="summary"><div><span>Items at today’s prices</span><b>{money(current_items_total)}</b></div><div><span>Historical savings</span><b>−{money(historical_savings)}</b></div><div class="total"><span>Historical order total</span><b>{money(historical_total)}</b></div><form method="post" action="/reorder"><input type="hidden" name="order_id" value="{esc(row["order_id"])}"><button class="primary">Reorder available items</button></form><a href="/orders">Back to orders</a></aside></div>'''
def cart_page(self):
rows = self.cart_rows()
if not rows:
return '<div class="empty"><h1>Your cart is empty</h1><p>Browse fresh food to get started.</p><a class="btn" href="/search">Start shopping</a></div>'
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'''<article class="cart-item {"" if available else "cart-item-unavailable"}"><div class="cart-media">{product_media(p)}</div><div><a href="/product/{p["id"]}"><small>{esc(p["brand"])}</small><h2>{esc(p["name"])}</h2></a><p class="cart-availability">{availability}</p><form method="post" action="/cart/update"><input type="hidden" name="product_id" value="{p["id"]}"><label>Qty<input name="qty" type="number" min="0" max="20" value="{r["qty"]}"></label><label>Substitution<select name="substitution">{sub_options(r["substitution"])}</select></label><button>Update</button><button name="qty" value="0">Remove</button></form></div><strong>{line_total}</strong></article>'''
)
mode = self.state["fulfillment"]
fee_label = {
"pickup": "Pickup fee",
"express": "Express fee",
"delivery": "Delivery fee",
}.get(mode, "Delivery fee")
promotion_note = ""
if self.state["coupon"] == "NEW50":
if not self.new50_eligible():
promotion_note = (
'<p class="fine">NEW50 is inactive because it is available '
"on first orders only.</p>"
)
elif sub < 99:
promotion_note = (
'<p class="fine">NEW50 is inactive because the eligible '
"subtotal is below $99.</p>"
)
return f'''<div class="cart-layout"><section><h1>Your cart</h1><p>{sum(r["qty"] for _, r in rows)} items · Review location availability and substitutions.</p>{"".join(items)}</section><aside class="summary"><h2>Order summary</h2><div><span>Eligible subtotal</span><b>{money(sub)}</b></div><div><span>Promotion</span><b>−{money(disc)}</b></div><div><span>{fee_label}</span><b>{money(fee)}</b></div><div class="total"><span>Estimated total</span><b>{money(total)}</b></div>{promotion_note}<form method="post" action="/coupon"><label>Promo code<input name="coupon" value="{esc(self.state["coupon"])}"></label><button>Apply</button></form><a class="btn block" href="/checkout">Continue to checkout review</a><p class="fine">No real payment or order will be submitted.</p></aside></div>'''
def checkout_page(self):
rows = self.cart_rows()
if not rows:
return '<div class="empty"><h1>Checkout review</h1><p>Add an item first.</p><a class="btn" href="/search">Shop groceries</a></div>'
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'<label><input type="radio" name="fulfillment" value="{method}" {"checked" if mode == method else ""} {"" if area and method in area["modes"] else "disabled"}> {label}</label>'
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'<label>{key.title()}<input name="{key}" value="{esc(a.get(key, address_defaults[key]))}" {"pattern=[0-9]{5}" if key == "zip" else ""} required></label>'
for key in ("name", "street", "city", "state", "zip")
)
summary_items = "".join(
f'<div class="review-item"><span>{row["qty"]} × {esc(product["name"])}<small>{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")}</small></span><b>{money(product["price"] * row["qty"]) if product_available(product, self.state) else "Excluded"}</b></div>'
for product, row in rows
)
slot_options = '<option value="">Choose a method-specific time</option>' + "".join(
f'<option value="{slot_id}" data-mode="{slot_mode}" {"selected" if slot == slot_id and mode == slot_mode else ""} {"" if mode == slot_mode else "disabled"}>{FULFILLMENT_LABELS[slot_mode]} — {label}</option>'
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 = (
'<div class="checkout-blockers"><b>Review needed</b><ul>'
+ "".join(f"<li>{esc(item)}</li>" for item in blockers)
+ "</ul></div>"
if blockers
else '<div class="checkout-ready"><b>Local review complete.</b> Order placement remains disabled.</div>'
)
fulfillment_script = '''<script>
const fulfillmentRadios=[...document.querySelectorAll('#fulfillment-form input[name="fulfillment"]')];
const slotSelect=document.querySelector('#fulfillment-form select[name="slot"]');
function syncSlots(){
const selected=fulfillmentRadios.find(radio=>radio.checked)?.value||'';
[...slotSelect.options].forEach(option=>{
if(!option.dataset.mode)return;
option.disabled=option.dataset.mode!==selected;
});
if(slotSelect.selectedOptions[0]?.disabled)slotSelect.value='';
}
fulfillmentRadios.forEach(radio=>radio.addEventListener('change',syncSlots));
</script>'''
return f'''<section class="account-head"><p>Checkout review</p><h1>Delivery and order details</h1><p>This sandbox stops before submission.</p></section>{blocker_html}<div class="checkout"><section><article class="step"><span>1</span><div><h2>Delivery address</h2><p>Required for Standard and Express delivery. Pickup uses the local test hub.</p><form class="address" method="post" action="/address">{address_fields}<button>Save synthetic address</button></form></div></article><article class="step"><span>2</span><div><h2>Fulfillment</h2><form id="fulfillment-form" method="post" action="/fulfillment">{methods}<label>Time<select name="slot" required>{slot_options}</select></label><button>Save fulfillment</button></form></div></article><article class="step disabled-step"><span>3</span><div><h2>Payment and placement</h2><p>Real payment and order placement are intentionally unavailable.</p><button disabled>Place order unavailable offline</button></div></article></section><aside class="summary review-summary"><h2>Review {sum(row["qty"] for _, row in rows)} items</h2>{summary_items}<h3>Fulfillment facts</h3><div><span>Method</span><b>{esc(fulfillment_review)}</b></div><div><span>Time</span><b>{esc(slot_review)}</b></div><div><span>Address / pickup</span><b>{esc(address_review)}</b></div><div><span>Promotion</span><b>{esc(promotion_review)}</b></div><h3>Price breakdown</h3><div><span>Eligible subtotal</span><b>{money(sub)}</b></div><div><span>Promotion discount</span><b>−{money(disc)}</b></div><div><span>{fee_label}</span><b>{money(fee)}</b></div><div class="total"><span>Estimated total</span><b>{money(total)}</b></div><a href="/cart">Edit cart</a></aside></div>{fulfillment_script}'''
def not_found(self):
self.send(
404,
shell(
"Page not found",
'<div class="empty"><h1>We could not find that page</h1><p>Search the catalog or return home.</p><a href="/">Return home</a></div>',
self.session,
self.state,
self.count,
),
)
def main():
services()
host = os.environ.get("HOST", "127.0.0.1")
port = int(os.environ.get("PORT", "8000"))
srv = ThreadingHTTPServer((host, port), App)
print(f"FreshDirect offline clone listening on http://{host}:{port}", flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
srv.server_close()
if __name__ == "__main__":
main()
|