File size: 62,464 Bytes
5961e41 | 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 | """Insureon offline clone — FastAPI route hub.
This module is the single convergence point: it owns the site backend, the
session boundary and route registration. Page markup lives in `views/`, copy in
`content/`, domain logic in `backend/business.py`.
The runtime makes no remote requests. Every asset is served from
`static/assets/`, downloaded during the 2026-08-23 source capture.
"""
from __future__ import annotations
import os
import re
import secrets
import sys
from pathlib import Path
from typing import Any, Mapping
from urllib.parse import urlsplit
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from backend import business # noqa: E402
from backend.site_backend_integration import open_site_services # noqa: E402
from content import professions as P # noqa: E402
from views import account as account_views # noqa: E402
from views import marketing # noqa: E402
from views import quote as quote_views # noqa: E402
from websitebench.local_clone_auth import ( # noqa: E402
AuthConflict,
AuthError,
AuthRateLimited,
AuthRejected,
)
SITE_ID = "insureon"
BACKEND, AUTH = open_site_services()
with BACKEND.lifecycle.connection(transaction=True) as connection:
business.migrate(connection)
ADMIN_TOKEN = (os.environ.get("WEBSITEBENCH_INSUREON_ADMIN_TOKEN")
or secrets.token_urlsafe(32))
DEPLOYED_COOKIE = str(BACKEND.session_cookie["name"])
LOCAL_COOKIE = "websitebench-insureon-session"
APP = FastAPI(title="Insureon offline clone", docs_url=None, redoc_url=None,
openapi_url=None)
APP.state.backend = BACKEND
APP.state.auth = AUTH
APP.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static")
CSP = ("default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "
"script-src 'self'; connect-src 'self'; form-action 'self'; "
"frame-ancestors 'none'; base-uri 'self'")
# --------------------------------------------------------------------------- #
# session boundary
# --------------------------------------------------------------------------- #
def _loopback(request: Request) -> bool:
host = (request.url.hostname or "").casefold()
return host in {"127.0.0.1", "localhost", "::1", "[::1]"}
def _cookie_name(request: Request) -> str:
return LOCAL_COOKIE if _loopback(request) else DEPLOYED_COOKIE
def _origin_tuple(value: str) -> tuple[str, str, int]:
parts = urlsplit(value)
scheme = parts.scheme.casefold()
return scheme, (parts.hostname or "").casefold(), parts.port or (
443 if scheme == "https" else 80)
def _request_origin(request: Request) -> tuple[str, str, int]:
scheme = request.url.scheme.casefold()
return scheme, (request.url.hostname or "").casefold(), request.url.port or (
443 if scheme == "https" else 80)
def _set_session_cookie(request: Request, response: Response, token: str) -> None:
response.set_cookie(_cookie_name(request), token, secure=not _loopback(request),
httponly=True, samesite="lax", path="/")
@APP.middleware("http")
async def runtime_boundary(request: Request, call_next):
if request.method == "POST":
origin = request.headers.get("origin") or request.headers.get("referer")
if origin == "null":
invalid = not _loopback(request)
elif origin:
invalid = _origin_tuple(origin) != _request_origin(request)
else:
invalid = not _loopback(request)
if invalid:
return JSONResponse(
{"error": "cross-origin state changes are not allowed"},
status_code=403)
supplied = request.cookies.get(_cookie_name(request))
token, session = AUTH.ensure_session(supplied)
request.state.auth_token = token
request.state.auth_info = session
response = await call_next(request)
response.headers["Content-Security-Policy"] = CSP
response.headers["Referrer-Policy"] = "no-referrer"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
current = str(getattr(request.state, "auth_token", token))
if current != supplied:
_set_session_cookie(request, response, current)
return response
def account_of(request: Request) -> dict | None:
session = getattr(request.state, "auth_info", {}) or {}
return session.get("account") if session.get("authenticated") else None
def account_id_of(request: Request) -> str | None:
acct = account_of(request)
return str(acct["account_id"]) if acct else None
def _session_key(request: Request) -> str:
"""Stable owner digest of the caller's current session, or "" if none."""
try:
return AUTH.session_owner_digest(str(request.state.auth_token))
except Exception: # noqa: BLE001 - an absent/expired session is not an error here
return ""
def _claim_anonymous_work(session_key: str, session_token: str) -> None:
"""Attach work done while logged out to the account that just signed in.
``session_key`` is the digest captured *before* authentication rotated the
session; ``session_token`` is the freshly authenticated token. Any
applications, policies, documents and payments the anonymous session
created are reassigned to the account so its history is not empty.
"""
if not session_key:
return
session = AUTH.resolve_session(session_token) or {}
account = session.get("account") if session.get("authenticated") else None
if not account:
return
with db() as connection:
business.claim_session_data(connection, session_key,
str(account["account_id"]))
def account_name_of(request: Request) -> str:
acct = account_of(request)
if not acct:
return ""
return str(acct.get("display_name") or acct.get("email") or "")
def db():
return BACKEND.lifecycle.connection(transaction=True)
def html(markup: str, status: int = 200) -> HTMLResponse:
return HTMLResponse(markup, status_code=status)
def see_other(url: str) -> RedirectResponse:
return RedirectResponse(url, status_code=303)
# --------------------------------------------------------------------------- #
# validation helpers
# --------------------------------------------------------------------------- #
ZIP_RE = re.compile(r"^\d{5}(-\d{4})?$")
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
def _int_or_none(value: Any) -> int | None:
try:
return int(str(value).replace(",", "").replace("$", "").strip())
except (TypeError, ValueError):
return None
# --------------------------------------------------------------------------- #
# health
# --------------------------------------------------------------------------- #
@APP.get("/__websitebench/health", response_class=JSONResponse)
def websitebench_health() -> JSONResponse:
"""Harbor compile-executable readiness probe: exact JSON, nothing else."""
return JSONResponse({"status": "ok"})
@APP.get("/healthz")
def healthz() -> dict[str, object]:
return {"ok": True, "site_id": SITE_ID, "status": "ok"}
# --------------------------------------------------------------------------- #
# marketing
# --------------------------------------------------------------------------- #
@APP.get("/", response_class=HTMLResponse)
def home(request: Request):
return html(marketing.home())
@APP.get("/search", response_class=HTMLResponse)
def search(request: Request, q: str = ""):
return html(marketing.search(q, logged_in=bool(account_of(request))))
@APP.get("/start-quote", response_class=HTMLResponse)
def start_quote(request: Request, product: str = "", q: str = ""):
return html(quote_views.start_quote(query=q, product=product,
logged_in=bool(account_of(request))))
@APP.get("/small-business-insurance", response_class=HTMLResponse)
def products_hub(request: Request):
return html(marketing.products_hub(logged_in=bool(account_of(request))))
@APP.get("/small-business-insurance/{slug}", response_class=HTMLResponse)
def product_page(request: Request, slug: str):
logged_in = bool(account_of(request))
page = marketing.product(slug, logged_in=logged_in)
if page:
return html(page)
page = marketing.content_page(f"/small-business-insurance/{slug}",
logged_in=logged_in)
if page:
return html(page)
return html(marketing.not_found(logged_in=logged_in), 404)
@APP.get("/small-business-insurance/{slug}/cost", response_class=HTMLResponse)
def product_cost_page(request: Request, slug: str):
logged_in = bool(account_of(request))
page = marketing.content_page(f"/small-business-insurance/{slug}/cost",
logged_in=logged_in)
if page:
return html(page)
return html(marketing.not_found(logged_in=logged_in), 404)
# --------------------------------------------------------------------------- #
# quote wizard
# --------------------------------------------------------------------------- #
def _app_or_404(connection, application_id: str, request: Request):
return business.get_application(connection, application_id)
def _limits_view(app: Mapping[str, Any]) -> dict[str, Any]:
"""Coverage-step choices for the application's primary product.
`limit_options` are (per-occurrence, aggregate) pairs; the select carries the
per-occurrence value and the aggregate is derived from the matching pair on
submit, so the two can never drift apart.
"""
slugs = app.get("requested_products") or ["general-liability"]
primary = business.PRODUCT_CATALOG.get(
slugs[0] if isinstance(slugs, (list, tuple)) else str(slugs),
business.PRODUCT_CATALOG["general-liability"])
return {
"limit": app.get("per_occurrence_limit_cents"),
"deductible": app.get("deductible_cents"),
"limit_options": [
(str(each), f"{business._format_limit(each)} per occurrence / "
f"{business._format_limit(aggregate)} aggregate")
for each, aggregate in primary["limit_options"]
],
"deductible_options": [
(str(v), business._format_money(v)) for v in primary["deductible_options"]
],
}
def _aggregate_for(app: Mapping[str, Any], per_occurrence: int) -> int:
"""Aggregate limit paired with `per_occurrence` in the product's ladder."""
slugs = app.get("requested_products") or ["general-liability"]
primary = business.PRODUCT_CATALOG.get(
slugs[0] if isinstance(slugs, (list, tuple)) else str(slugs),
business.PRODUCT_CATALOG["general-liability"])
for each, aggregate in primary["limit_options"]:
if each == per_occurrence:
return aggregate
return per_occurrence * 2
@APP.get("/app/quote/new")
def quote_new_get(request: Request):
"""The quote-start form posts here; a direct GET returns to the picker."""
product = str(request.query_params.get("product") or "")
target = "/start-quote"
if product:
target += f"?product={product}"
return see_other(target)
@APP.post("/app/quote/new")
async def quote_new(request: Request):
form = await request.form()
profession_id = _int_or_none(form.get("profession_id"))
svc = P.service(profession_id) if profession_id is not None else None
if not svc:
return html(quote_views.start_quote(
error="Select the business type that most closely matches your work.",
product=str(form.get("product") or ""),
logged_in=bool(account_of(request))), 400)
product = str(form.get("product") or "").strip()
requested = [product] if product in business.PRODUCT_CATALOG else ["general-liability"]
account_id = account_id_of(request)
with db() as connection:
app_row = business.create_application(
connection,
industry_id=svc["industry_id"], industry_name=svc["industry_name"],
profession_id=svc["id"], profession_name=svc["name"],
requested_products=requested, account_id=account_id,
session_key=None if account_id else _session_key(request),
)
return see_other(f"/app/quote/{app_row['id']}/company-information")
@APP.get("/app/quote/{application_id}/company-information", response_class=HTMLResponse)
def quote_company_information(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
return html(quote_views.company_information(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/company-information")
async def quote_company_information_post(request: Request, application_id: str):
form = await request.form()
name = str(form.get("business_name") or "").strip()
zip_code = str(form.get("zip_code") or "").strip()
month = _int_or_none(form.get("start_month"))
year = _int_or_none(form.get("start_year"))
errors: dict[str, str] = {}
if not name:
errors["business_name"] = "Enter the name of your business."
if not ZIP_RE.match(zip_code):
errors["zip_code"] = "Enter a valid 5-digit US ZIP code."
if month is None or month < 1 or month > 12:
errors["start_month"] = "Select the month your business started."
if year is None or year < 1900 or year > 2026:
errors["start_year"] = "Enter a start year from 1900 through 2026."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
if errors:
return html(quote_views.company_information(dict(app_row, business_name=name, zip_code=zip_code), errors, logged_in=bool(account_of(request))), 400)
business.update_application(connection, application_id, {
"business_name": name, "zip_code": zip_code,
"years_in_business": max(0, 2026 - int(year)),
})
return see_other(f"/app/quote/{application_id}/protection-options")
@APP.get("/app/quote/{application_id}/protection-options", response_class=HTMLResponse)
def quote_protection_options(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
selected = list(app_row.get("requested_products") or ["general-liability"])
return html(quote_views.protection_options(app_row, business.PRODUCT_CATALOG, selected, _limits_view(app_row), logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/protection-options")
async def quote_protection_options_post(request: Request, application_id: str):
form = await request.form()
products = [p for p in form.getlist("products") if p in business.PRODUCT_CATALOG]
limit = _int_or_none(form.get("limit"))
deductible = _int_or_none(form.get("deductible"))
errors = {} if products else {"products": "Select at least one protection option."}
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
if errors:
limits = _limits_view(app_row); limits.update({"limit": limit, "deductible": deductible})
return html(quote_views.protection_options(app_row, business.PRODUCT_CATALOG, products, limits, errors, logged_in=bool(account_of(request))), 400)
changes: dict[str, Any] = {"requested_products": products}
if limit:
changes["per_occurrence_limit_cents"] = limit
changes["aggregate_limit_cents"] = _aggregate_for(dict(app_row, requested_products=products), limit)
if deductible is not None:
changes["deductible_cents"] = deductible
business.update_application(connection, application_id, changes)
return see_other(f"/app/quote/{application_id}/contact-information")
@APP.get("/app/quote/{application_id}/contact-information", response_class=HTMLResponse)
def quote_contact_information(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
return html(quote_views.contact_information(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/contact-information")
async def quote_contact_information_post(request: Request, application_id: str):
form = await request.form()
values = {key: str(form.get(key) or "").strip() for key in ("contact_first", "contact_last", "email", "phone")}
errors: dict[str, str] = {}
for key, label in (("contact_first", "first name"), ("contact_last", "last name"), ("phone", "phone number")):
if not values[key]: errors[key] = f"Enter your {label}."
if not values["email"]: errors["email"] = "Enter your email address."
elif not EMAIL_RE.match(values["email"]): errors["email"] = "Enter a valid email address."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
if errors:
return html(quote_views.contact_information(dict(app_row, **values), errors, logged_in=bool(account_of(request))), 400)
business.update_application(connection, application_id, values)
return see_other(f"/app/quote/{application_id}/business-details")
@APP.get("/app/quote/{application_id}/business-details", response_class=HTMLResponse)
def quote_source_business_details(request: Request, application_id: str):
with db() as connection: app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
return html(quote_views.source_business_details(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/business-details")
async def quote_source_business_details_post(request: Request, application_id: str):
form = await request.form(); entity = str(form.get("entity_type") or "").strip()
errors = {} if entity in dict(quote_views.ENTITY_TYPES) else {"entity_type": "Select your business structure."}
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
if errors: return html(quote_views.source_business_details(dict(app_row, entity_type=entity), errors, logged_in=bool(account_of(request))), 400)
business.update_application(connection, application_id, {"entity_type": entity})
return see_other(f"/app/quote/{application_id}/locations")
@APP.get("/app/quote/{application_id}/locations", response_class=HTMLResponse)
def quote_locations(request: Request, application_id: str):
with db() as connection: app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
return html(quote_views.locations(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/locations")
async def quote_locations_post(request: Request, application_id: str):
form = await request.form(); zip_code = str(form.get("zip_code") or "").strip(); state = str(form.get("state") or "").strip(); city = str(form.get("city") or "").strip()
errors: dict[str, str] = {}
if not ZIP_RE.match(zip_code): errors["zip_code"] = "Enter a valid 5-digit US ZIP code."
if not state: errors["state"] = "Select a state."
if not city: errors["city"] = "Enter the city."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
if errors: return html(quote_views.locations(dict(app_row, zip_code=zip_code, state=state, city=city), errors, logged_in=bool(account_of(request))), 400)
business.update_application(connection, application_id, {"zip_code": zip_code, "state": state, "city": city})
return see_other(f"/app/quote/{application_id}/sales-operations")
@APP.get("/app/quote/{application_id}/sales-operations", response_class=HTMLResponse)
def quote_sales_operations(request: Request, application_id: str):
with db() as connection: app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
return html(quote_views.sales_operations(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/sales-operations")
async def quote_sales_operations_post(request: Request, application_id: str):
form = await request.form(); revenue = _int_or_none(form.get("annual_revenue")); errors = {}
if revenue is None or revenue < 0: errors["annual_revenue"] = "Enter your estimated annual sales."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
if errors: return html(quote_views.sales_operations(dict(app_row, annual_revenue=form.get("annual_revenue") or ""), errors, logged_in=bool(account_of(request))), 400)
business.update_application(connection, application_id, {"annual_revenue": revenue})
target = "workers-compensation" if "workers-compensation" in list(app_row.get("requested_products") or []) else "business-operations-practices"
return see_other(f"/app/quote/{application_id}/{target}")
@APP.get("/app/quote/{application_id}/workers-compensation", response_class=HTMLResponse)
def quote_workers_compensation(request: Request, application_id: str):
with db() as connection: app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
if "workers-compensation" not in list(app_row.get("requested_products") or []): return see_other(f"/app/quote/{application_id}/business-operations-practices")
return html(quote_views.workers_compensation(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/workers-compensation")
async def quote_workers_compensation_post(request: Request, application_id: str):
form = await request.form(); employees = _int_or_none(form.get("employees")); errors = {}
if employees is None or employees < 0 or employees > 500: errors["employees"] = "Enter an employee count from 0 to 500."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
if errors: return html(quote_views.workers_compensation(dict(app_row, employees=form.get("employees") or ""), errors, logged_in=bool(account_of(request))), 400)
business.update_application(connection, application_id, {"employees": employees})
return see_other(f"/app/quote/{application_id}/business-operations-practices")
@APP.get("/app/quote/{application_id}/business-operations-practices", response_class=HTMLResponse)
def quote_business_practices(request: Request, application_id: str):
with db() as connection: app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
return html(quote_views.business_practices(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/business-operations-practices")
async def quote_business_practices_post(request: Request, application_id: str):
form = await request.form()
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row: return html(marketing.not_found(), 404)
business.update_application(connection, application_id, {"has_prior_claims": str(form.get("has_prior_claims") or "0") == "1", "needs_certificate": bool(form.get("needs_certificate"))})
business.generate_quotes(connection, application_id)
return see_other(f"/app/quote/{application_id}/quotes")
@APP.get("/app/quote/{application_id}/location", response_class=HTMLResponse)
def quote_location(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
return html(quote_views.location(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/location")
async def quote_location_post(request: Request, application_id: str):
form = await request.form()
zip_code = str(form.get("zip_code") or "").strip()
state = str(form.get("state") or "").strip()
city = str(form.get("city") or "").strip()
errors: dict[str, str] = {}
if not zip_code:
errors["zip_code"] = "Enter your business ZIP code."
elif not ZIP_RE.match(zip_code):
errors["zip_code"] = "Enter a valid 5-digit US ZIP code, for example 60601."
if not state:
errors["state"] = "Select the state your business operates in."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
if errors:
merged = dict(app_row, zip_code=zip_code, state=state, city=city)
return html(quote_views.location(merged, errors,
logged_in=bool(account_of(request))), 400)
business.update_application(connection, application_id,
{"zip_code": zip_code, "state": state, "city": city})
return see_other(f"/app/quote/{application_id}/business")
@APP.get("/app/quote/{application_id}/business", response_class=HTMLResponse)
def quote_business(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
return html(quote_views.business(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/business")
async def quote_business_post(request: Request, application_id: str):
form = await request.form()
name = str(form.get("business_name") or "").strip()
employees = _int_or_none(form.get("employees"))
revenue = _int_or_none(form.get("annual_revenue"))
years = _int_or_none(form.get("years_in_business"))
entity = str(form.get("entity_type") or "").strip()
errors: dict[str, str] = {}
if not name:
errors["business_name"] = "Enter the legal or trading name of your business."
if employees is None:
errors["employees"] = "Enter how many people your business employs."
elif employees < 0 or employees > 500:
errors["employees"] = "Enter a number of employees between 0 and 500."
if revenue is None:
errors["annual_revenue"] = "Enter your annual revenue in US dollars."
elif revenue < 0:
errors["annual_revenue"] = "Annual revenue cannot be negative."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
if errors:
merged = dict(app_row, business_name=name,
employees="" if employees is None else employees,
annual_revenue="" if revenue is None else revenue,
years_in_business=years or "", entity_type=entity)
return html(quote_views.business(merged, errors,
logged_in=bool(account_of(request))), 400)
changes: dict[str, Any] = {"business_name": name, "employees": employees,
"annual_revenue": revenue}
if years is not None:
changes["years_in_business"] = years
if entity:
changes["entity_type"] = entity
business.update_application(connection, application_id, changes)
return see_other(f"/app/quote/{application_id}/risk")
@APP.get("/app/quote/{application_id}/risk", response_class=HTMLResponse)
def quote_risk(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
return html(quote_views.risk(app_row, logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/risk")
async def quote_risk_post(request: Request, application_id: str):
form = await request.form()
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
business.update_application(connection, application_id, {
"has_prior_claims": str(form.get("has_prior_claims") or "0") == "1",
"needs_certificate": bool(form.get("needs_certificate")),
})
return see_other(f"/app/quote/{application_id}/coverage")
@APP.get("/app/quote/{application_id}/coverage", response_class=HTMLResponse)
def quote_coverage(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
selected = list(app_row.get("requested_products") or ["general-liability"])
return html(quote_views.coverage(app_row, business.PRODUCT_CATALOG, selected,
_limits_view(app_row),
logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/coverage")
async def quote_coverage_post(request: Request, application_id: str):
form = await request.form()
products = [p for p in form.getlist("products") if p in business.PRODUCT_CATALOG]
limit = _int_or_none(form.get("limit"))
deductible = _int_or_none(form.get("deductible"))
errors: dict[str, str] = {}
if not products:
errors["products"] = "Select at least one policy to quote."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
if errors:
limits = _limits_view(app_row)
limits["limit"] = limit
limits["deductible"] = deductible
return html(quote_views.coverage(app_row, business.PRODUCT_CATALOG,
products, limits, errors,
logged_in=bool(account_of(request))), 400)
changes: dict[str, Any] = {"requested_products": products}
if limit:
changes["per_occurrence_limit_cents"] = limit
changes["aggregate_limit_cents"] = _aggregate_for(
dict(app_row, requested_products=products), limit)
if deductible is not None:
changes["deductible_cents"] = deductible
business.update_application(connection, application_id, changes)
business.generate_quotes(connection, application_id)
return see_other(f"/app/quote/{application_id}/quotes")
@APP.get("/app/quote/{application_id}/quotes", response_class=HTMLResponse)
def quote_list(request: Request, application_id: str, notice: str = ""):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
options = business.list_quote_options(connection, application_id)
selected = [s["id"] for s in business.get_selection(connection, application_id)]
return html(quote_views.quotes(app_row, options, selected, notice=notice,
logged_in=bool(account_of(request))))
@APP.get("/app/quote/{application_id}/quotes/{option_id}", response_class=HTMLResponse)
def quote_option_detail(request: Request, application_id: str, option_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
options = business.list_quote_options(connection, application_id)
selected = [s["id"] for s in business.get_selection(connection, application_id)]
match = next((o for o in options if o["id"] == option_id), None)
if not match:
return html(marketing.not_found(), 404)
product = marketing.PRODUCTS.get(match["product_slug"])
return html(quote_views.quote_detail(app_row, match, product,
match["id"] in selected,
logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/select")
async def quote_select(request: Request, application_id: str):
form = await request.form()
option_id = str(form.get("option_id") or "")
with db() as connection:
if not _app_or_404(connection, application_id, request):
return html(marketing.not_found(), 404)
try:
business.select_quote(connection, application_id, option_id)
except (LookupError, ValueError):
return see_other(f"/app/quote/{application_id}/quotes")
return see_other(f"/app/quote/{application_id}/quotes")
@APP.post("/app/quote/{application_id}/save")
async def quote_save(request: Request, application_id: str):
acct = account_id_of(request)
if not acct:
return see_other(f"/account/login?next=/app/quote/{application_id}/quotes")
with db() as connection:
if not _app_or_404(connection, application_id, request):
return html(marketing.not_found(), 404)
business.update_application(connection, application_id, {"account_id": acct})
business.save_quote_for_account(connection, acct, application_id)
return see_other("/account/quotes?saved=1")
def _totals(selected) -> dict[str, int]:
return {
"annual_cents": sum(int(q["annual_premium_cents"]) for q in selected),
"monthly_cents": sum(int(q["monthly_premium_cents"]) for q in selected),
}
@APP.get("/app/quote/{application_id}/review", response_class=HTMLResponse)
def quote_review(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
selected = business.get_selection(connection, application_id)
return html(quote_views.review(app_row, selected, _totals(selected),
logged_in=bool(account_of(request))))
@APP.get("/app/quote/{application_id}/enroll", response_class=HTMLResponse)
def quote_enroll(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
selected = business.get_selection(connection, application_id)
if not selected:
return see_other(f"/app/quote/{application_id}/quotes")
return html(quote_views.enroll(app_row, _totals(selected),
logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/enroll")
async def quote_enroll_post(request: Request, application_id: str):
form = await request.form()
first = str(form.get("contact_first") or "").strip()
last = str(form.get("contact_last") or "").strip()
email = str(form.get("email") or "").strip()
phone = str(form.get("phone") or "").strip()
effective = str(form.get("effective_date") or "").strip()
errors: dict[str, str] = {}
if not first:
errors["contact_first"] = "Enter the policyholder's first name."
if not last:
errors["contact_last"] = "Enter the policyholder's last name."
if not email:
errors["email"] = "Enter an email address for your policy documents."
elif not EMAIL_RE.match(email):
errors["email"] = "Enter a valid email address, for example owner@example.com."
if not phone:
errors["phone"] = "Enter a phone number a licensed agent can reach you on."
if not effective:
errors["effective_date"] = "Choose the date you want coverage to start."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
selected = business.get_selection(connection, application_id)
if errors:
merged = dict(app_row, contact_first=first, contact_last=last,
email=email, phone=phone, effective_date=effective)
return html(quote_views.enroll(merged, _totals(selected), errors,
logged_in=bool(account_of(request))), 400)
business.enroll(connection, application_id, contact={
"contact_first": first, "contact_last": last,
"email": email, "phone": phone})
# The requested start date belongs to the policy, not to the application
# row, so it travels with the request until bind_policy consumes it.
return see_other(f"/app/quote/{application_id}/payment?effective={effective}")
@APP.get("/app/quote/{application_id}/payment", response_class=HTMLResponse)
def quote_payment(request: Request, application_id: str, effective: str = ""):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
selected = business.get_selection(connection, application_id)
if not selected:
return see_other(f"/app/quote/{application_id}/quotes")
return html(quote_views.payment(app_row, _totals(selected),
effective_date=effective,
logged_in=bool(account_of(request))))
@APP.post("/app/quote/{application_id}/payment")
async def quote_payment_post(request: Request, application_id: str):
form = await request.form()
billing_name = str(form.get("billing_name") or "").strip()
billing_zip = str(form.get("billing_zip") or "").strip()
method = str(form.get("method_label") or "card-sandbox")
effective = str(form.get("effective_date") or "").strip()
errors: dict[str, str] = {}
if not billing_name:
errors["billing_name"] = "Enter the name on the billing account."
if not billing_zip:
errors["billing_zip"] = "Enter the billing ZIP code."
elif not ZIP_RE.match(billing_zip):
errors["billing_zip"] = "Enter a valid 5-digit US ZIP code."
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
selected = business.get_selection(connection, application_id)
totals = _totals(selected)
if errors:
return html(quote_views.payment(app_row, totals, errors,
effective_date=effective,
logged_in=bool(account_of(request))), 400)
acct = account_id_of(request)
try:
business.bind_policy(connection, application_id,
effective_date=effective or None, account_id=acct)
except ValueError as exc:
return html(quote_views.payment(
app_row, totals, {"enrollment": str(exc)},
effective_date=effective,
logged_in=bool(account_of(request))), 400)
business.record_payment(
connection, account_id=acct, application_id=application_id,
amount_cents=totals["annual_cents"],
method_label={"card-sandbox": "Sandbox card",
"ach-sandbox": "Sandbox bank transfer"}.get(
method, "Local sandbox payment"))
return see_other(f"/app/quote/{application_id}/confirmation")
@APP.get("/app/quote/{application_id}/confirmation", response_class=HTMLResponse)
def quote_confirmation(request: Request, application_id: str):
with db() as connection:
app_row = _app_or_404(connection, application_id, request)
if not app_row:
return html(marketing.not_found(), 404)
policies = business.list_policies_for_application(connection, application_id)
docs = business.list_documents(
connection, str(app_row.get("account_id") or ""),
application_id=application_id) if app_row.get("account_id") else []
totals = {"annual_cents": sum(int(p["annual_premium_cents"]) for p in policies),
"monthly_cents": 0}
return html(quote_views.confirmation(app_row, policies, totals, docs,
logged_in=bool(account_of(request))))
# --------------------------------------------------------------------------- #
# authentication
# --------------------------------------------------------------------------- #
def _safe_next(value: str) -> str:
value = (value or "").strip()
return value if value.startswith("/") and not value.startswith("//") else "/account"
@APP.get("/account/login", response_class=HTMLResponse)
def login_page(request: Request, next: str = "", reset: str = ""):
if account_of(request):
return see_other(_safe_next(next))
notice = ("Your password was updated. Log in with your new password."
if reset else "")
return html(account_views.login(next_url=next, notice=notice))
@APP.post("/account/login")
async def login_post(request: Request):
form = await request.form()
email = str(form.get("email") or "").strip()
password = str(form.get("password") or "")
next_url = str(form.get("next") or "")
errors: dict[str, str] = {}
if not email:
errors["email"] = "Enter the email address on your account."
elif not EMAIL_RE.match(email):
errors["email"] = "Enter a valid email address."
if not password:
errors["password"] = "Enter your password."
if errors:
return html(account_views.login(errors, email=email, next_url=next_url), 400)
prior_key = _session_key(request)
try:
result = AUTH.sign_in(str(request.state.auth_token), email=email,
password=password)
request.state.auth_token = str(result["session_token"])
except AuthRateLimited:
return html(account_views.login(
{"password": "Too many attempts. Wait a moment and try again."},
email=email, next_url=next_url), 429)
except (AuthRejected, AuthError):
return html(account_views.login(
{"password": "That email and password combination is not recognised."},
email=email, next_url=next_url), 400)
_claim_anonymous_work(prior_key, str(request.state.auth_token))
return see_other(_safe_next(next_url))
@APP.get("/account/logout")
@APP.post("/account/logout")
def logout(request: Request):
AUTH.sign_out(str(request.state.auth_token))
request.state.auth_token = AUTH.create_anonymous_session()
return see_other("/")
@APP.get("/account/register", response_class=HTMLResponse)
def register_page(request: Request, next: str = ""):
if account_of(request):
return see_other(_safe_next(next))
status = AUTH.session_flow_status(str(request.state.auth_token),
purpose="registration") or {}
if status.get("stage") in {"awaiting-code", "code-verified"}:
mail = AUTH.local_mail_for_session(str(request.state.auth_token),
purpose="registration") or {}
return html(account_views.register(
stage="verify", next_url=next, email=str(status.get("email") or ""),
code_hint=_code_hint(mail)))
return html(account_views.register(next_url=next))
def _code_hint(mail: Mapping[str, Any] | None) -> str:
"""Offline sites deliver confirmation codes in-page, never by real email."""
if not mail:
return ""
code = mail.get("code") or mail.get("verification_code") or ""
if not code:
body = str(mail.get("body") or "")
match = re.search(r"\b(\d{6})\b", body)
code = match.group(1) if match else ""
if not code:
return ""
return (f"Offline demonstration site: no real email is sent. "
f"Your confirmation code is {code}.")
@APP.post("/account/register")
async def register_post(request: Request):
form = await request.form()
stage = str(form.get("stage") or "details")
next_url = str(form.get("next") or "")
token = str(request.state.auth_token)
if stage == "verify":
code = str(form.get("code") or "").strip()
status = AUTH.session_flow_status(token, purpose="registration") or {}
email = str(status.get("email") or "")
if not code:
mail = AUTH.local_mail_for_session(token, purpose="registration") or {}
return html(account_views.register(
{"code": "Enter the 6-digit code we sent to your email address."},
stage="verify", next_url=next_url, email=email,
code_hint=_code_hint(mail)), 400)
prior_key = _session_key(request)
try:
AUTH.verify_registration_code(token, code)
created = AUTH.complete_registration(token)
request.state.auth_token = str(created["session_token"])
except (AuthRejected, AuthRateLimited, AuthError):
mail = AUTH.local_mail_for_session(token, purpose="registration") or {}
return html(account_views.register(
{"code": "That code is not valid. Check the code and try again."},
stage="verify", next_url=next_url, email=email,
code_hint=_code_hint(mail)), 400)
_claim_anonymous_work(prior_key, str(request.state.auth_token))
return see_other(_safe_next(next_url))
name = str(form.get("name") or "").strip()
email = str(form.get("email") or "").strip()
password = str(form.get("password") or "")
errors: dict[str, str] = {}
if not name:
errors["name"] = "Enter your full name."
if not email:
errors["email"] = "Enter an email address."
elif not EMAIL_RE.match(email):
errors["email"] = "Enter a valid email address."
if not password:
errors["password"] = "Choose a password."
elif len(password) < 12:
errors["password"] = "Use a password of at least 12 characters."
if errors:
return html(account_views.register(errors, {"name": name, "email": email},
next_url=next_url), 400)
try:
AUTH.start_registration(token, email=email, display_name=name,
password=password, restart_invalid_flow=True)
except AuthConflict:
return html(account_views.register(
{"email": "An account already exists for that email address."},
{"name": name, "email": email}, next_url=next_url), 409)
except (AuthRejected, AuthError) as exc:
return html(account_views.register(
{"password": str(exc) or "That registration could not be started."},
{"name": name, "email": email}, next_url=next_url), 400)
mail = AUTH.local_mail_for_session(token, purpose="registration") or {}
return html(account_views.register(stage="verify", next_url=next_url,
email=email, code_hint=_code_hint(mail)))
@APP.get("/account/forgot-password", response_class=HTMLResponse)
def forgot_page(request: Request):
status = AUTH.session_flow_status(str(request.state.auth_token),
purpose="password-reset") or {}
if status.get("stage") in {"awaiting-code", "code-verified"}:
mail = AUTH.local_mail_for_session(str(request.state.auth_token),
purpose="password-reset") or {}
return html(account_views.forgot_password(
stage="verify", email=str(status.get("email") or ""),
code_hint=_code_hint(mail)))
return html(account_views.forgot_password())
@APP.post("/account/forgot-password")
async def forgot_post(request: Request):
form = await request.form()
stage = str(form.get("stage") or "request")
token = str(request.state.auth_token)
if stage == "verify":
code = str(form.get("code") or "").strip()
new_password = str(form.get("new_password") or "")
status = AUTH.session_flow_status(token, purpose="password-reset") or {}
email = str(status.get("email") or "")
errors: dict[str, str] = {}
if not code:
errors["code"] = "Enter the 6-digit reset code."
if not new_password:
errors["new_password"] = "Choose a new password."
elif len(new_password) < 12:
errors["new_password"] = "Use a password of at least 12 characters."
if errors:
mail = AUTH.local_mail_for_session(token, purpose="password-reset") or {}
return html(account_views.forgot_password(errors, stage="verify",
email=email,
code_hint=_code_hint(mail)), 400)
try:
AUTH.verify_password_reset_code(token, code)
request.state.auth_token = str(
AUTH.complete_password_reset(token, new_password=new_password))
except (AuthRejected, AuthRateLimited, AuthError):
mail = AUTH.local_mail_for_session(token, purpose="password-reset") or {}
return html(account_views.forgot_password(
{"code": "That reset code is not valid. Check it and try again."},
stage="verify", email=email, code_hint=_code_hint(mail)), 400)
return see_other("/account/login?reset=1")
email = str(form.get("email") or "").strip()
if not email or not EMAIL_RE.match(email):
return html(account_views.forgot_password(
{"email": "Enter the email address on your account."}, email=email), 400)
try:
AUTH.start_password_reset(token, email=email, restart_invalid_flow=True)
except AuthRateLimited:
return html(account_views.forgot_password(
{"email": "Too many reset requests. Wait a moment and try again."},
email=email), 429)
except (AuthRejected, AuthError):
# Same response whether or not the account exists.
return html(account_views.forgot_password(stage="verify", email=email))
mail = AUTH.local_mail_for_session(token, purpose="password-reset") or {}
return html(account_views.forgot_password(stage="verify", email=email,
code_hint=_code_hint(mail)))
# --------------------------------------------------------------------------- #
# account portal
# --------------------------------------------------------------------------- #
def _require_account(request: Request, path: str, what: str):
if account_of(request):
return None
return html(account_views.sign_in_required(path, what), 401)
@APP.get("/account", response_class=HTMLResponse)
def account_overview(request: Request):
guard = _require_account(request, "/account", "your account")
if guard:
return guard
acct = account_id_of(request)
with db() as connection:
apps = business.list_applications_for_account(connection, acct)
pols = business.list_policies(connection, acct)
docs = business.list_documents(connection, acct)
return html(account_views.overview(account_name_of(request), apps, pols, docs))
@APP.get("/account/quotes", response_class=HTMLResponse)
def account_quotes(request: Request, saved: str = ""):
guard = _require_account(request, "/account/quotes", "your saved quotes")
if guard:
return guard
acct = account_id_of(request)
with db() as connection:
rows = business.list_saved_quotes(connection, acct)
if not rows:
rows = business.list_applications_for_account(connection, acct)
notice = "Your quote was saved to your account." if saved else ""
return html(account_views.quotes(account_name_of(request), rows, notice=notice))
@APP.get("/account/policies", response_class=HTMLResponse)
def account_policies(request: Request, cancelled: str = ""):
guard = _require_account(request, "/account/policies", "your policies")
if guard:
return guard
with db() as connection:
rows = business.list_policies(connection, account_id_of(request))
notice = "That policy has been cancelled." if cancelled else ""
return html(account_views.policies(account_name_of(request), rows, notice=notice))
@APP.get("/account/policies/{policy_id}", response_class=HTMLResponse)
def account_policy_detail(request: Request, policy_id: str, issued: str = ""):
guard = _require_account(request, f"/account/policies/{policy_id}", "that policy")
if guard:
return guard
acct = account_id_of(request)
with db() as connection:
pol = business.get_policy(connection, policy_id, account_id=acct)
if not pol:
return html(marketing.not_found(logged_in=True), 404)
docs = business.list_documents(connection, acct, policy_id=policy_id)
notice = "Your certificate of insurance has been issued." if issued else ""
return html(account_views.policy_detail(account_name_of(request), pol, docs,
notice=notice))
@APP.post("/account/policies/{policy_id}/cancel")
def account_policy_cancel(request: Request, policy_id: str):
guard = _require_account(request, f"/account/policies/{policy_id}", "that policy")
if guard:
return guard
with db() as connection:
try:
business.cancel_policy(connection, policy_id,
account_id=account_id_of(request))
except (LookupError, ValueError):
return see_other(f"/account/policies/{policy_id}")
return see_other("/account/policies?cancelled=1")
@APP.post("/account/policies/{policy_id}/certificate")
async def account_policy_certificate(request: Request, policy_id: str):
guard = _require_account(request, f"/account/policies/{policy_id}", "that policy")
if guard:
return guard
form = await request.form()
holder = str(form.get("holder_name") or "").strip()
with db() as connection:
try:
business.issue_certificate_of_insurance(
connection, policy_id, holder_name=holder,
account_id=account_id_of(request))
except (LookupError, ValueError):
return see_other(f"/account/policies/{policy_id}")
return see_other(f"/account/policies/{policy_id}?issued=1")
@APP.get("/account/documents", response_class=HTMLResponse)
def account_documents(request: Request):
guard = _require_account(request, "/account/documents", "your documents")
if guard:
return guard
with db() as connection:
rows = business.list_documents(connection, account_id_of(request))
return html(account_views.documents(account_name_of(request), rows))
@APP.get("/account/documents/{document_id}", response_class=HTMLResponse)
def account_document(request: Request, document_id: str):
guard = _require_account(request, f"/account/documents/{document_id}",
"that document")
if guard:
return guard
with db() as connection:
doc = business.get_document(connection, document_id,
account_id=account_id_of(request))
if not doc:
return html(marketing.not_found(logged_in=True), 404)
return html(account_views.document_detail(account_name_of(request), doc))
@APP.get("/account/profile", response_class=HTMLResponse)
def account_profile(request: Request, saved: str = ""):
guard = _require_account(request, "/account/profile", "your profile")
if guard:
return guard
acct = account_of(request) or {}
with db() as connection:
payments = business.list_payments(connection, account_id_of(request))
notice = "Your profile has been updated." if saved else ""
return html(account_views.profile(account_name_of(request),
str(acct.get("email") or ""), payments,
notice=notice))
@APP.post("/account/profile")
async def account_profile_post(request: Request):
guard = _require_account(request, "/account/profile", "your profile")
if guard:
return guard
return see_other("/account/profile?saved=1")
# --------------------------------------------------------------------------- #
# deterministic fixtures (loopback + admin token only)
# --------------------------------------------------------------------------- #
# Fixed identities so a diagnostic can deep-link the wizard and portal without
# first walking the whole funnel. Synthetic values only: no real person, no real
# business, no payment instrument.
DEMO_APPLICATION_ID = "00000000-0000-4000-8000-00000000d001"
DEMO_EMAIL = "demo.owner@insureon-offline.test"
DEMO_PASSWORD = "offline-demo-passphrase"
DEMO_DISPLAY_NAME = "Dana Reyes"
DEMO_SUBJECT_ID = "insureon-demo-owner"
def _seed_fixtures() -> dict[str, Any]:
"""Create the demo account, its seeded history and one fixed application."""
account_id = AUTH.seed_account(
subject_id=DEMO_SUBJECT_ID, email=DEMO_EMAIL,
display_name=DEMO_DISPLAY_NAME, password=DEMO_PASSWORD,
email_verified=True)
with db() as connection:
seeded = business.seed_demo_data(connection, account_id)
existing = business.get_application(connection, DEMO_APPLICATION_ID)
if existing is None:
business.create_application(
connection,
application_id=DEMO_APPLICATION_ID,
industry_id=4000,
industry_name="Consultants—Management & Marketing",
profession_id=4009, profession_name="Marketing Consulting",
business_name="Northside Consulting LLC",
employees=5, annual_revenue=200_000, years_in_business=5,
entity_type="llc", zip_code="60601", state="IL", city="Chicago",
requested_products=["general-liability"],
account_id=account_id,
)
options = business.generate_quotes(connection, DEMO_APPLICATION_ID)
if options:
business.select_quote(connection, DEMO_APPLICATION_ID,
options[0]["id"])
business.save_quote_for_account(connection, account_id,
DEMO_APPLICATION_ID)
return {"account_id": account_id, "application_id": DEMO_APPLICATION_ID,
"seeded": seeded}
@APP.post("/__admin/reset", response_class=JSONResponse)
def admin_reset(request: Request) -> JSONResponse:
if not _loopback(request):
return JSONResponse({"error": "loopback only"}, status_code=403)
import hmac as _hmac
if not _hmac.compare_digest(
request.headers.get("X-WebsiteBench-Admin-Token", ""), ADMIN_TOKEN):
return JSONResponse({"error": "forbidden"}, status_code=403)
def reset_all(connection) -> None:
BACKEND.lifecycle.reset_embedded(connection, confirm_site_id=SITE_ID)
business.migrate(connection)
AUTH.reset_site_state(site_reset=reset_all, seed_accounts=[])
info = _seed_fixtures()
response = JSONResponse({"reset": True, "site_id": SITE_ID, **info})
_set_session_cookie(request, response, AUTH.create_anonymous_session())
return response
@APP.post("/__admin/session", response_class=JSONResponse)
async def admin_session(request: Request) -> JSONResponse:
"""Sign the caller into the seeded demo account (loopback + token only)."""
if not _loopback(request):
return JSONResponse({"error": "loopback only"}, status_code=403)
import hmac as _hmac
if not _hmac.compare_digest(
request.headers.get("X-WebsiteBench-Admin-Token", ""), ADMIN_TOKEN):
return JSONResponse({"error": "forbidden"}, status_code=403)
try:
result = AUTH.sign_in(str(request.state.auth_token), email=DEMO_EMAIL,
password=DEMO_PASSWORD)
request.state.auth_token = str(result["session_token"])
except AuthError as exc:
return JSONResponse({"error": f"{type(exc).__name__}"}, status_code=409)
return JSONResponse({"signed_in": True, "email": DEMO_EMAIL})
# --------------------------------------------------------------------------- #
# catch-all content pages and 404
# --------------------------------------------------------------------------- #
@APP.get("/{path:path}", response_class=HTMLResponse)
def catch_all(request: Request, path: str):
logged_in = bool(account_of(request))
page = marketing.content_page("/" + path.strip("/"), logged_in=logged_in)
if page:
return html(page)
return html(marketing.not_found(logged_in=logged_in), 404)
app = APP
def main() -> None:
"""Run the clone directly.
`ACCEPTANCE.md` documents the human acceptance step as
`cd <site>/clone && python app.py`, so that command has to actually serve
the site rather than import the module and exit.
"""
import uvicorn
uvicorn.run(
APP,
host=os.environ.get("WEBSITEBENCH_INSUREON_HOST", "127.0.0.1"),
port=int(os.environ.get("WEBSITEBENCH_INSUREON_PORT", "8472")),
log_level=os.environ.get("WEBSITEBENCH_INSUREON_LOG_LEVEL", "info"),
)
if __name__ == "__main__":
main()
|