Skip to content

2. Dealflow Interactive Offer & Live Pricing Calculator — Offer Mode

Repository: Microservices (planovi-microservices) • Rule Prefix: BR-OFF • Documented Rules: 10 • Open [TEAM_WHY_NEEDED] Questions: 3

1. Business Purpose & Actors

  • Problem Solved: Provides white-labeled, embeddable interactive lead-capture wizards and real-time price-estimation calculators (2-panel normal mode or 3-panel live pricing mode) that submit qualified leads directly into each tenant’s Dealflow pipeline in Supabase (dealflow_entries).
  • Actors:
    • Tenant Admin (via planovi-flutter-app): Designs offer/calculator forms and publishes or deletes their JSON definitions.
    • Prospective Customer: Opens dealflow/offer.php?id={offer_id} (standalone or <iframe>), completes contact details and step-by-step questions, views live price breakdown (if enabled), and submits lead.

2. All Features & End-to-End Flows (Happy Path + Error Paths)

  • Feature A: Save / Publish Dealflow Config (POST dealflow/api/save_dealflow.php)
    • Trigger: Flutter app sends JSON config with X-Secret-Key header.
    • Validation: OPTIONS (200) → POST only (405) → root .env must exist (500) → X-Secret-Key === DEALFLOW_API_SECRET and non-empty (401) → non-empty valid JSON (400) → non-empty id sanitized to [a-zA-Z0-9_-] (400).
    • State Change: Hoists company_id and user_id from json_data to root if missing (save_dealflow.php:165-172), adds saved_at and server_timestamp, writes dealflow/data/{id}.json (chmod 0644).
    • Response: HTTP 200 with data.id, data.url ({DEALFLOW_FRONTEND_URL}/offer.php?id={id}), data.iframe_code, data.file_size, data.saved_at.
  • Feature B: Create Offer with Server-Generated ID (POST dealflow/api/create_offer.php)
    • Trigger: Flutter app posts offer payload with X-Secret-Key.
    • Validation: Same POST (405), X-Secret-Key (401), valid JSON (400) checks (does NOT fail if .env is missing until empty SECRET_KEY triggers 401).
    • State Change: Hoists company_id/user_id from json_data, adds created_at, generates ID uniqid('offer_') . '_' . bin2hex(random_bytes(2)), writes dealflow/data/{offer_id}.json.
    • Response: HTTP 201 {"status":"success","offer_id":"...","url":"..."}.
  • Feature C: Delete Dealflow Config (POST dealflow/backend/delete_json.php)
    • Trigger: Unauthenticated POST {"id": "..."}.
    • State Change: Logs raw body to dealflow/backend/delete_log.txt and unlinks dealflow/data/{cleanId}.json.
    • Response: HTTP 200 {"status":"success",...} (idempotent if already absent) or HTTP 400 on error.
  • Feature D: Render Offer Wizard & Live Pricing Calculator (GET dealflow/offer.php?id={offer_id})
    • Trigger: Visitor opens URL without a valid 32+ hex ?token=.
    • Validation: Sanitizes id to [a-zA-Z0-9_-]. Loads ./data/{offer_id}.json (unwrapping json_data if present), strips legacy responses key, merges onto $default_data. If file not found, renders "Strona niedostępna" / "Ten formularz ofertowy został usunięty lub nie istnieje.".
    • Flow (Normal Mode — meta.pricing.enabled falsy): Hero screen → Contact step (name, email, phone, rodo per standard_fields) → One-by-one questions (text, email, tel, number, textarea, radio, checkbox, grid, info) with optional right media panel (image/iframe video/description) → Cloudflare Turnstile rendered on last question → finalSubmit() posts to api/save_response.php with X-CSRF-TOKEN header → Success view.
    • Flow (Pricing Mode — meta.pricing.enabled truthy): 3-panel layout (28% info, 42% wizard, 30% live calculator). After Contact step, live calculator activates and updates on every input/selection (base_price + sum of unit_price * value and option_prices). Visitor can click "💬 Zapisz i skontaktuj się" (submitPricingOffer()) at any time after Contact step, posting calculated_price and price_breakdown (without Turnstile token) to api/save_response.php.
  • Feature E: Persist Lead Submission (POST dealflow/api/save_response.php)
    • Trigger: fetch('api/save_response.php') from offer.php.
    • Validation: Requires JSON body with offer_id (400) → verifies X-CSRF-TOKEN against $_SESSION['csrf_token'] via verify_csrf_token() (403 "Błąd weryfikacji sesji (CSRF)") → if turnstile_token AND turnstile_secret are non-empty, verifies via Cloudflare siteverify (403 "Wykryto aktywność bota").
    • State Change: Extracts name/email/phone from answers (removing name, email, phone, rodo from custom_field_data), attaches currency, price_breakdown, and source_ip ($_SERVER['REMOTE_ADDR']), and sends POST {SUPABASE_URL}/rest/v1/dealflow_entries with SUPABASE_SERVICE_KEY (timeout 5s).
    • Response: HTTP 200 {"status":"success","message":"Lead zapisany pomyślnie!"} when Supabase returns 201; otherwise HTTP 500 with error: "Błąd bazy danych" and raw debug: $supabase_response.
  • Feature F: Dev Sample Generator (GET dealflow/test_generator.php)
    • Trigger: Direct browser access (no auth, no environment guard).
    • State Change: Immediately writes 3 JSON files (test_normal_{ts}.json, test_pricing_{ts}.json, test_it_{ts+1}.json) into dealflow/data/ and displays direct links to offer.php?id=....

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

  • BR-OFF-01 (Mode Routing Precedence): offer.php:103-105 enters Offer Mode whenever strlen(preg_replace('/[^a-f0-9]/', '', strtolower($_GET['token'] ?? ''))) < 32.
  • BR-OFF-02 (Offer ID Hyphen Preservation — BUG-V45): save_response.php:69, offer.php:216, save_dealflow.php:151 sanitize offer_id/dealflow_id using /[^a-zA-Z0-9_-]/, preserving hyphens so UUID/slug dealflow_id values remain linked to their form in Supabase.
  • BR-OFF-03 (Theme / Background Auto-Heal): offer.php:321-325 overrides $bg_color to #F8FAFC if $theme === 'light' && strtoupper($bg_color) === '#0F172A', and to #0F172A if $theme === 'dark' && strtoupper($bg_color) === '#FFFFFF'.
  • BR-OFF-04 (Hero Heading & Subheading Fallback Chain): Heading resolves hero.heading → meta.title → decoded.tytul_oferty → decoded.nazwa_deal → 'Oferta'. Subheading resolves hero.subheading → meta.description → decoded.opis_oferty → 'Wypełnij formularz i skontaktujemy się z Tobą.' (offer.php:299-313).
  • BR-OFF-05 (Live Pricing Formula): computeTotal() (offer.php:1869-1878) calculates: $$\text{total} = \text{base_price} + \sum_{\text{step.pricing.enabled}} \text{stepValue}$$ where numeric steps compute (parseFloat(value) || 0) * unit_price, radio steps look up option_prices[value] ?? 0, and checkbox steps sum option_prices[v] ?? 0 (supports negative option values for discounts, as demonstrated in test_generator.php:296). Values are formatted rounded to integer via Intl.NumberFormat('pl-PL').
  • BR-OFF-06 (Contact Step Validation): submitContact() (offer.php:1784-1793) checks each enabled standard_fields entry when required !== false: name non-empty, email non-empty and contains '@', phone non-empty, rodo checkbox checked. Validation errors flash a red border for 2500ms.
  • BR-OFF-07 (Lead Schema Defaults in dealflow_entries): save_response.php:56-79 writes source = 'website_form', current_stage = 'new_lead', client_name = $answers['name'] ?? 'Klient z WWW', client_email = $answers['email'] ?? 'Brak', client_phone = $answers['phone'] ?? null, deal_title = 'Nowa oferta: ' . $client_name, deal_value = $new_response['calculated_price'] ?? 0, company_id = !empty(...) ? ... : null, and custom_field_data containing remaining answers + currency (default 'PLN'), price_breakdown, and source_ip.
  • BR-OFF-08 (CSRF Required; Turnstile Conditionally Skipped): save_response.php:36-53 strictly requires a valid session CSRF token (403 on failure) if includes/security.php loaded. Turnstile is ONLY verified when !empty($turnstile_token) && !empty($turnstile_secret). In Pricing Mode (submitPricingOffer()), no Turnstile widget is rendered and no turnstile_token is sent (offer.php:1805, 1900).
  • BR-OFF-09 (Button Contrast Calculation): offer.php:1722 sets CTA button text color to getLuminance(primary) > 0.5 ? '#000' : '#fff' using linear RGB coefficients (0.2126 R + 0.7152 G + 0.0722 B). (Deviates from BRANDING_GUIDE.md sRGB threshold 0.42 and #09090B.)
  • BR-OFF-10 (Direct Data Directory Protection): dealflow/data/.htaccess:1-11 blocks all external HTTP access (Require all denied / Deny from all) and disables directory indexing (Options -Indexes).

4. State Machines & Data Lifecycle

Offer Wizard UI Flow (Offer Mode):

stateDiagram-v2
    [*] --> Unavailable: JSON file missing
    [*] --> Hero: JSON loaded (progress 0%)
    Hero --> Contact: startWizard() (progress 25%)
    Contact --> Hero: goToHero()
    Contact --> Questions: submitContact() valid (progress 60%)
    Questions --> Contact: goToContact()
    Questions --> Questions: nextQuestion() (index < total - 1)
    Questions --> Submitting: Last step finalSubmit() OR Pricing Mode submitPricingOffer()
    Submitting --> Success: save_response.php status=success (progress 100%)
    Submitting --> Questions: Network / 403 / 500 error (alert + retry)
    Success --> [*]

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

  • Endpoints:
    • GET /dealflow/offer.php?id={offer_id} → HTML wizard; starts PLANOVI_MS session (SameSite=None; Secure; HttpOnly) and embeds CSRF token.
    • POST /dealflow/api/save_response.php → Header X-CSRF-TOKEN, Body {offer_id, company_id, user_id, answers, calculated_price?, price_breakdown?, currency?, turnstile_token?, submitted_at} → Inserts row in Supabase dealflow_entries (200/400/403/500).
    • POST /dealflow/api/save_dealflow.php → Header X-Secret-Key, Body {id, ...} → Writes dealflow/data/{id}.json (200/400/401/405/500).
    • POST /dealflow/api/create_offer.php → Header X-Secret-Key, Body {...} → Writes dealflow/data/offer_{uniqid}_{hex}.json (201/400/401/405/500).
    • POST /dealflow/backend/delete_json.php → Body {id} → Deletes dealflow/data/{id}.json, logs to dealflow/backend/delete_log.txt (200/400).
    • GET /dealflow/test_generator.php → Creates 3 sample files in dealflow/data/ (200).
  • Database Tables Touched: dealflow_entries (POST via PostgREST).
  • External APIs: Cloudflare Turnstile (POST https://challenges.cloudflare.com/turnstile/v0/siteverify, timeout 8s).

6. Cross-Repository Dependencies

CallerCalleeProtocol & AuthExact Endpoint / Contract
planovi-flutter-appplanovi-microservices (dealflow)HTTPS POST + X-Secret-Key (DEALFLOW_API_SECRET)POST /api/save_dealflow.php, POST /api/create_offer.php
planovi-flutter-appplanovi-microservices (dealflow)HTTPS POST (No Auth)POST /backend/delete_json.php
dealflow/api/save_response.phpplanovi-backend (Supabase PostgREST)HTTPS POST + apikey & Bearer (SUPABASE_SERVICE_KEY)POST /rest/v1/dealflow_entries (Prefer: return=minimal)
includes/security.phpCloudflare TurnstileHTTPS POST form-urlencoded (TURNSTILE_SECRET_KEY)POST https://challenges.cloudflare.com/turnstile/v0/siteverify

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

  • SameSite=None Session Cookie (includes/security.php:41-55): Offer pages are embedded in third-party <iframe>s; without SameSite=None; Secure, browsers drop the PHP session cookie and every CSRF check fails (403).
  • Tenant ID Hoisting (save_dealflow.php:163-172, create_offer.php:77-85): Flutter occasionally nests company_id and user_id inside json_data; hoisting them ensures root-level availability.
  • Keep Hyphens in dealflow_id (de9b3725, BUG-V45): Previously stripping hyphens broke UUID foreign/logical references between submitted leads and their source forms.
  • [TEAM_WHY_NEEDED: Why do both create_offer.php (generates random offer_ ID, returns 201) and save_dealflow.php (accepts caller-supplied id, returns 200) coexist — are both still called by planovi-flutter-app?]
  • [TEAM_WHY_NEEDED: Why is Turnstile omitted in Pricing Mode (offer.php:1805, 1900) and skipped in save_response.php:47 whenever turnstile_token is empty, allowing bots to bypass Turnstile on Normal Mode as well?]
  • [TEAM_WHY_NEEDED: Why is dealflow/test_generator.php deployed without an environment/auth guard, allowing anyone hitting it to write files into dealflow/data/?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Log or QueryFix
HTTP 403 "Błąd weryfikacji sesji (CSRF)" on submitBrowser blocked third-party cookie in iframe, or site served over plain HTTP (breaking Secure flag on PLANOVI_MS cookie, includes/security.php:49-51).Check DevTools → Application → Cookies for PLANOVI_MS and verify X-CSRF-TOKEN request header.Serve strictly over HTTPS; ensure browser allows partitioned/third-party cookies or link out of iframe.
Tenant logo never displays in Offer ModeBug at dealflow/offer.php:945: checks $branding['logo_url'] instead of $offer_data['branding']['logo_url'] ($branding is undefined in Offer Mode).Inspect rendered HTML of .panel-left for <img> tag.Change $branding['logo_url'] to $offer_data['branding']['logo_url'].
HTTP 500 "Błąd bazy danych" with debug payloadSupabase rejected dealflow_entries insert (e.g., invalid UUID in company_id or missing SUPABASE_SERVICE_KEY).Read debug field in response body from save_response.php:121.Fix payload / .env key, and remove raw debug leakage in production.
offer.php?id=... shows "Strona niedostępna"Missing JSON file in dealflow/data/ or ID mismatch.Check ls dealflow/data/{id}.json and dealflow/backend/delete_log.txt.Re-publish form from Flutter app.