Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Webpage (planovi.app) v1.0 (frozen on 2026-11-23, commit 69f9463). Switch to Latest →

4. Two-Step Waitlist & Lead Qualification Engine

Repository: Webpage (planovi-webpage) • Rule Prefix: BR-WLT • Documented Rules: 10 • Open [TEAM_WHY_NEEDED] Questions: 1

1. Business Purpose & Actors

  • Problem solved: Captures pre-launch prospective customer emails with GDPR consent and bot protection (Step 1), then enriches the lead with qualification metadata—role, company size, and optional problem description—using a one-time expiring token without requiring authentication (Step 2). Also serves as the production /login/ landing gate while the platform is in closed development.
  • Actors: Prospective users arriving on / (#waitlist, source='home') or /login/ (source='login'); Cloudflare Turnstile; Supabase PostgreSQL (website.waitlist); Resend API (optional marketing contact sync + welcome email).

2. All Features & End-to-End Flows

  • Flow A — UI Entry Points (index.php:413-415, login/index.php:1-48, components/waitlist-form.php:1-83):
    • Renders [data-waitlist] container with data-source, data-lang, data-sitekey (waitlist.turnstile_site_key), and JSON-encoded data-i18n error/status dictionary. Uses $GLOBALS['__waitlist_instance'] counter to generate unique element IDs (wl1-email, etc.) if included multiple times.
    • /login/index.php sets <meta name="robots" content="noindex">, loads Turnstile with ?render=explicit, wraps notice + form in .waitlist-panel.
    • js/waitlist.js:26-69 polls window.turnstile.render every 100ms (max 100 attempts = 10s) and explicitly renders widget with action: 'waitlist', theme: 'auto', language: lang, 'response-field': false.
  • Flow B — Step 1 Email Signup (js/waitlist.js:112-152 → POST /waitlist-handler.php):
    • Trigger: User submits email + checks consent checkbox + completes Turnstile.
    • Client Validation: Non-empty valid HTML5 email, consent.checked === true, and turnstileToken non-empty (when data-sitekey is configured; if sitekey is absent, submits anyway so server responds 503 err_unavailable).
    • Server Validation (waitlist-handler.php:12-29):
      1. wl_input() enforces POST (405) and valid JSON object (400).
      2. Lowercases/trims email; checks non-empty, strlen <= 254, FILTER_VALIDATE_EMAIL → 400 err_email.
      3. Strict boolean $input['consent'] === true → 400 err_consent.
      4. Coerces source to 'other' unless strictly in ['home', 'login'].
      5. wl_require_config() verifies all 4 waitlist.* keys exist → 503 err_unavailable.
      6. wl_turnstile_verify($token, $cfg, 'waitlist') verifies token (1..2048 bytes), success === true, action === 'waitlist', and hostname in allowed list → 400 err_captcha.
    • Persistence (waitlist-handler.php:31-95):
      1. GET website.waitlist?select=id,qualified_at&limit=1&email=eq.<email>.
      2. Generates 32-byte random hex token (64 hex chars) + sha256 hash + expiresAt = now + 86400s.
      3. New email ($row === null): POST website.waitlist with status='pending', locale, source, consent_at, country (validated /^[A-Z]{2}$/ from HTTP_CF_IPCOUNTRY else null), update_token_hash, update_token_expires_at. On HTTP 409 race conflict, re-queries existing row and falls into existing-row logic.
      4. Existing & unqualified (empty($row['qualified_at'])): PATCH website.waitlist?id=eq.<id> rotates update_token_hash, update_token_expires_at, updated_at.
      5. Existing & already qualified (!empty($row['qualified_at'])): No DB mutation; omits token from response.
    • Response & Async Side Effects (waitlist-handler.php:98-112):
      • Returns HTTP 200 {"success": true, "message": "...", "token": "<64-hex>"} (with token omitted if already qualified) and Cache-Control: no-store.
      • Client advances to Step 2 if result.token is present, or skips directly to Step 3 thank-you screen if omitted. Always resets Turnstile in finally.
      • Server flushes response (fastcgi_finish_request() or ob_end_flush()/flush()), then only if $isNew && wl_resend_enabled(): creates Resend contact (POST /contacts with optional segment), patches contact properties (PATCH /contacts/{email} with {locale, source}), and sends bilingual welcome email (POST /emails).
  • Flow C — Step 2 Qualification (js/waitlist.js:155-190 → POST /waitlist-qualify-handler.php):
    • Trigger: User selects role radio, enters company size integer, optionally enters problem description, submits Step 2.
    • Server Validation (waitlist-qualify-handler.php:14-45):
      1. token matches /^[0-9a-f]{64}$/ → 400 err_token_invalid.
      2. role strictly in WL_ROLES (['manager', 'company_owner', 'cooperative_owner', 'other']) → 400 err_role.
      3. company_size integer (or digits-only string cast to int) in 1..1000000 → 400 err_company_size.
      4. problem_description trimmed UTF-8 length <= 2000 → 400 err_problem_too_long.
      5. wl_require_config() → 503 err_unavailable.
    • Token Verification & Atomic CAS Update (waitlist-qualify-handler.php:48-90):
      1. Looks up row by update_token_hash=eq.<sha256(token)>.
      2. Missing row or non-null qualified_at → 400 err_token_invalid.
      3. strtotime(update_token_expires_at) < time() → 400 err_token_expired.
      4. Executes conditional PATCH website.waitlist?id=eq.<id>&update_token_hash=eq.<hash>&qualified_at=is.null with Prefer: return=representation, setting role, company_size, problem_description (null if empty string), status='qualified', qualified_at=now, updated_at=now, update_token_hash=null, update_token_expires_at=null.
      5. If count($updated) === 0 (concurrent replay), responds 400 err_token_invalid.
    • Response & Async Side Effects (waitlist-qualify-handler.php:92-101):
      • Returns HTTP 200 {"success": true, "message": "<waitlist.final_success>"}.
      • Client clears in-memory updateToken, shows Step 3 final screen.
      • Server flushes response, then if wl_resend_enabled(), calls PATCH /contacts/{email} (create=false) with properties: {role, company_size}.

3. Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-WLT-01 (Strict Config Fail-Closed): Missing any of waitlist.supabase_url, waitlist.supabase_service_key, waitlist.turnstile_site_key, or waitlist.turnstile_secret_key immediately aborts with HTTP 503 (code: 'err_unavailable'); no fallback (includes/waitlist.php:77-86).
  • BR-WLT-02 (Anti-Enumeration & Idempotent Re-Signup): Submitting an already-registered email returns the exact same HTTP 200 message (waitlist.step1_success) as a new signup. If unqualified, a fresh 24h update token is issued; if already qualified, no token is returned and Resend welcome email is NOT re-sent (waitlist-handler.php:77-111).
  • BR-WLT-03 (One-Time Token Security & TTL): Update tokens are 32 random bytes (bin2hex(random_bytes(32)) = 64 lowercase hex chars), stored exclusively as SHA-256 hex (VARCHAR(64)), valid for WL_TOKEN_TTL = 86400 seconds (24 hours), invalidated upon Step 2 submission or Step 1 re-submission (includes/waitlist.php:15,193-196, waitlist-handler.php:45-46,79-95, waitlist-qualify-handler.php:80-81).
  • BR-WLT-04 (Atomic Concurrent Replay Guard): Step 2 PATCH includes update_token_hash=eq.<hash>&qualified_at=is.null predicates and verifies count($updated) > 0; concurrent submissions with the same token produce 400 err_token_invalid for the loser (waitlist-qualify-handler.php:67-90).
  • BR-WLT-05 (Turnstile Strict Action & Hostname Binding): wl_turnstile_verify() rejects tokens > 2048 bytes, requires success === true, action === 'waitlist', and strtolower(hostname) in waitlist.turnstile_hostnames (defaulting to current HTTP_HOST stripped of :port). Fails closed on any network/HTTP != 200 error (includes/waitlist.php:102-147).
  • BR-WLT-06 (Field Validation Bounds):
    • email: lowercased, trimmed, 1..254 bytes, FILTER_VALIDATE_EMAIL (waitlist-handler.php:16-19).
    • consent: strict === true (waitlist-handler.php:20-22).
    • source: allowlist WL_SOURCES = ['home', 'login'], fallback 'other' (includes/waitlist.php:14, waitlist-handler.php:23).
    • role: allowlist WL_ROLES = ['manager', 'company_owner', 'cooperative_owner', 'other'] (includes/waitlist.php:13, waitlist-qualify-handler.php:20-23).
    • company_size: integer 1..1,000,000 (waitlist-qualify-handler.php:25-31).
    • problem_description: optional, max WL_PROBLEM_MAXLEN = 2000 UTF-8 characters (includes/waitlist.php:16, waitlist-qualify-handler.php:33-41).
    • country: regex /^[A-Z]{2}$/ from HTTP_CF_IPCOUNTRY, else null (waitlist-handler.php:51,58).
  • BR-WLT-07 (Resend Isolation & Fire-and-Forget Policy): Resend is enabled iff both resend.api_key and resend.from are non-empty. All Resend calls happen after wl_finish_response(), have a 5s cURL timeout, catch \Throwable, and never alter the HTTP 200 response. Contact creation (POST /contacts) and custom property assignment (PATCH /contacts/{email}) are deliberately split into two API calls so undefined custom properties in Resend cannot block contact creation (includes/waitlist.php:214-270).
  • BR-WLT-08 (Zero-PII Error Logging): includes/waitlist.php explicitly logs only HTTP status codes, PostgREST error codes, Resend error name, or exception class names — never keys, tokens, or emails (includes/waitlist.php:8,81,123,132,142,186,241,245).
  • BR-WLT-09 (Hostinger Redirect-POST Retry): js/waitlist.js:10-23 repeats the POST to response.url if fetch() encounters a redirect (response.redirected), compensating for hosting clean-URL .php rewrites that convert POST to GET on 301/302.
  • BR-WLT-10 (Invalid JSON Language Fallback): If wl_input() receives malformed JSON, it returns HTTP 400 (err_server) hardcoding 'pl' because $input['lang'] could not be parsed (includes/waitlist.php:48-50).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> NewRequest: Step 1 POST (email + consent + Turnstile)
    NewRequest --> Pending: INSERT website.waitlist\n(status='pending', token_hash set, TTL=24h)\n+ Async Resend Contact & Welcome Email
    Pending --> Pending: Re-submit Step 1\n(rotate token_hash, reset TTL=24h,\nno duplicate welcome email)
    Pending --> TokenExpired: 24h elapsed without Step 2
    TokenExpired --> Pending: Re-submit Step 1\n(new token_hash issued)
    TokenExpired --> Rejected400: Step 2 POST -> HTTP 400 err_token_expired
    Pending --> Qualified: Step 2 POST (valid token + role + size)\nAtomic CAS PATCH (status='qualified',\nqualified_at=now, token_hash=NULL)\n+ Async Resend PATCH properties
    Qualified --> Qualified: Re-submit Step 1 -> HTTP 200\n(no token returned; UI jumps to Step 3)
    Qualified --> Rejected400: Replay Step 2 -> HTTP 400 err_token_invalid

5. Technical Contract (Inputs → Processing → Side Effects)

  • Endpoints:
    • POST /waitlist-handler.php: JSON {email, turnstileToken, consent, source, lang} → 200 {success, message, token?} | 400/405/500/503 {success: false, code, message}.
    • POST /waitlist-qualify-handler.php: JSON {token, role, company_size, problem_description, lang} → 200 {success, message} | 400/405/500/503 {success: false, code, message}.
    • GET /login/: HTML page (noindex) hosting the waitlist component with $waitlist_source = 'login'.
  • DB Table (supabase/website_schema.sql:102-167): website.waitlist (id UUID PK, created_at, created_by, updated_at with trigger trg_waitlist_updated_at, email TEXT UNIQUE NOT NULL, status VARCHAR(30) DEFAULT 'pending', locale, source, role, company_size INT, problem_description TEXT, consent_at, update_token_hash VARCHAR(64), update_token_expires_at, qualified_at, country VARCHAR(10)). Indexed on email and update_token_hash. RLS enabled: only service_role has access (anon blocked completely).
  • External APIs:
    • POST https://challenges.cloudflare.com/turnstile/v0/siteverify (10s timeout)
    • GET/POST/PATCH {waitlist.supabase_url}/rest/v1/waitlist (10s timeout, service_role, Accept-Profile/Content-Profile: website)
    • POST https://api.resend.com/contacts, PATCH https://api.resend.com/contacts/{email}, POST https://api.resend.com/emails (5s timeout, optional).

6. Cross-Repository Dependencies

Caller → CalleeProtocol & AuthExact Endpoint / Contract
planovi-webpage → Supabase (planovi-backend DB)HTTPS PostgREST (apikey + Authorization: Bearer <service_role>)/rest/v1/waitlist in schema website
planovi-webpage → Cloudflare TurnstileHTTPS form-urlencoded (secret)https://challenges.cloudflare.com/turnstile/v0/siteverify
planovi-webpage → Resend APIHTTPS JSON (Authorization: Bearer <resend.api_key>)/contacts, /contacts/{email}, /emails

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • Two-step funnel: Captures low-friction email first so drop-offs during qualification still convert into waitlist leads (waitlist-handler.php:3-7).
  • Separate Turnstile widget & config namespace (waitlist.turnstile_*): index.php hosts both the contact form (implicit Turnstile) and the waitlist form (explicit Turnstile with 'response-field': false and action: 'waitlist'). Keeping them separate prevents token collision and enforces explicit action/hostname verification.
  • No anon RLS on website.waitlist: Prevents direct scraping of waitlist emails or unauthorized inserts bypassing Turnstile; all access goes through PHP server-side with service_role (supabase/website_schema.sql:155-166).
  • [TEAM_WHY_NEEDED: In includes/waitlist.php:279-282, the waitlist welcome email uses a minimal inline HTML div without the official PLANOVI email shell (logo-white.png header + #32CA42 bar) specified in BRANDING_GUIDE.md Section 5.5. Is this intentional for deliverability or pending redesign?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to VerifyFix
HTTP 503 err_unavailableMissing one of the 4 waitlist.* keys in ../config/{dev,prod}.php (includes/waitlist.php:79-84)grep '\[waitlist\]' /var/log/php*.logPopulate all 4 waitlist.* keys in out-of-webroot config
HTTP 400 err_captcha on localhost/staging with Cloudflare test keysTurnstile test keys return hostname 'example.com', failing wl_turnstile_verify() hostname check (includes/waitlist.php:136-144)Check PHP error log for [waitlist] turnstile hostname mismatchSet 'turnstile_hostnames' => ['example.com'] in ../config/dev.php
Step 1 returns 200 but jumps straight to Step 3 (skips Step 2)Email already exists in website.waitlist with non-null qualified_at (waitlist-handler.php:77,102-104)Query SELECT email, status, qualified_at FROM website.waitlist WHERE email = ...Expected anti-enumeration & idempotency behavior
Welcome email not delivered while Step 1 succeededresend.api_key or resend.from empty, or Resend returned non-2xx (silently logged post-response)Check PHP error log for [waitlist] resend send_welcome failed:Verify Resend domain/API key in ../config/<env>.php