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.
- Tenant Admin (via
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-Keyheader. - Validation:
OPTIONS(200) →POSTonly (405) → root.envmust exist (500) →X-Secret-Key === DEALFLOW_API_SECRETand non-empty (401) → non-empty valid JSON (400) → non-emptyidsanitized to[a-zA-Z0-9_-](400). - State Change: Hoists
company_idanduser_idfromjson_datato root if missing (save_dealflow.php:165-172), addssaved_atandserver_timestamp, writesdealflow/data/{id}.json(chmod 0644). - Response: HTTP
200withdata.id,data.url({DEALFLOW_FRONTEND_URL}/offer.php?id={id}),data.iframe_code,data.file_size,data.saved_at.
- Trigger: Flutter app sends JSON config with
- 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.envis missing until emptySECRET_KEYtriggers 401). - State Change: Hoists
company_id/user_idfromjson_data, addscreated_at, generates IDuniqid('offer_') . '_' . bin2hex(random_bytes(2)), writesdealflow/data/{offer_id}.json. - Response: HTTP
201{"status":"success","offer_id":"...","url":"..."}.
- Trigger: Flutter app posts offer payload with
- 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.txtand unlinksdealflow/data/{cleanId}.json. - Response: HTTP
200{"status":"success",...}(idempotent if already absent) or HTTP400on error.
- Trigger: Unauthenticated
- 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
idto[a-zA-Z0-9_-]. Loads./data/{offer_id}.json(unwrappingjson_dataif present), strips legacyresponseskey, 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.enabledfalsy): Hero screen → Contact step (name,email,phone,rodoperstandard_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 toapi/save_response.phpwithX-CSRF-TOKENheader → Success view. - Flow (Pricing Mode —
meta.pricing.enabledtruthy): 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 ofunit_price * valueandoption_prices). Visitor can click"💬 Zapisz i skontaktuj się"(submitPricingOffer()) at any time after Contact step, postingcalculated_priceandprice_breakdown(without Turnstile token) toapi/save_response.php.
- Trigger: Visitor opens URL without a valid 32+ hex
- Feature E: Persist Lead Submission (
POST dealflow/api/save_response.php)- Trigger:
fetch('api/save_response.php')fromoffer.php. - Validation: Requires JSON body with
offer_id(400) → verifiesX-CSRF-TOKENagainst$_SESSION['csrf_token']viaverify_csrf_token()(403"Błąd weryfikacji sesji (CSRF)") → ifturnstile_tokenANDturnstile_secretare non-empty, verifies via Cloudflare siteverify (403"Wykryto aktywność bota"). - State Change: Extracts
name/email/phonefromanswers(removingname,email,phone,rodofromcustom_field_data), attachescurrency,price_breakdown, andsource_ip($_SERVER['REMOTE_ADDR']), and sendsPOST {SUPABASE_URL}/rest/v1/dealflow_entrieswithSUPABASE_SERVICE_KEY(timeout5s). - Response: HTTP
200{"status":"success","message":"Lead zapisany pomyślnie!"}when Supabase returns201; otherwise HTTP500witherror: "Błąd bazy danych"and rawdebug: $supabase_response.
- Trigger:
- 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) intodealflow/data/and displays direct links tooffer.php?id=....
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-OFF-01(Mode Routing Precedence):offer.php:103-105enters Offer Mode wheneverstrlen(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:151sanitizeoffer_id/dealflow_idusing/[^a-zA-Z0-9_-]/, preserving hyphens so UUID/slugdealflow_idvalues remain linked to their form in Supabase.BR-OFF-03(Theme / Background Auto-Heal):offer.php:321-325overrides$bg_colorto#F8FAFCif$theme === 'light' && strtoupper($bg_color) === '#0F172A', and to#0F172Aif$theme === 'dark' && strtoupper($bg_color) === '#FFFFFF'.BR-OFF-04(Hero Heading & Subheading Fallback Chain): Heading resolveshero.heading→meta.title→decoded.tytul_oferty→decoded.nazwa_deal→'Oferta'. Subheading resolveshero.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 upoption_prices[value] ?? 0, and checkbox steps sumoption_prices[v] ?? 0(supports negative option values for discounts, as demonstrated intest_generator.php:296). Values are formatted rounded to integer viaIntl.NumberFormat('pl-PL').BR-OFF-06(Contact Step Validation):submitContact()(offer.php:1784-1793) checks each enabledstandard_fieldsentry whenrequired !== false:namenon-empty,emailnon-empty and contains'@',phonenon-empty,rodocheckbox checked. Validation errors flash a red border for2500ms.BR-OFF-07(Lead Schema Defaults indealflow_entries):save_response.php:56-79writessource = '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, andcustom_field_datacontaining remaining answers +currency(default'PLN'),price_breakdown, andsource_ip.BR-OFF-08(CSRF Required; Turnstile Conditionally Skipped):save_response.php:36-53strictly requires a valid session CSRF token (403on failure) ifincludes/security.phploaded. Turnstile is ONLY verified when!empty($turnstile_token) && !empty($turnstile_secret). In Pricing Mode (submitPricingOffer()), no Turnstile widget is rendered and noturnstile_tokenis sent (offer.php:1805,1900).BR-OFF-09(Button Contrast Calculation):offer.php:1722sets CTA button text color togetLuminance(primary) > 0.5 ? '#000' : '#fff'using linear RGB coefficients (0.2126 R + 0.7152 G + 0.0722 B). (Deviates fromBRANDING_GUIDE.mdsRGB threshold0.42and#09090B.)BR-OFF-10(Direct Data Directory Protection):dealflow/data/.htaccess:1-11blocks 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; startsPLANOVI_MSsession (SameSite=None; Secure; HttpOnly) and embeds CSRF token.POST /dealflow/api/save_response.php→ HeaderX-CSRF-TOKEN, Body{offer_id, company_id, user_id, answers, calculated_price?, price_breakdown?, currency?, turnstile_token?, submitted_at}→ Inserts row in Supabasedealflow_entries(200/400/403/500).POST /dealflow/api/save_dealflow.php→ HeaderX-Secret-Key, Body{id, ...}→ Writesdealflow/data/{id}.json(200/400/401/405/500).POST /dealflow/api/create_offer.php→ HeaderX-Secret-Key, Body{...}→ Writesdealflow/data/offer_{uniqid}_{hex}.json(201/400/401/405/500).POST /dealflow/backend/delete_json.php→ Body{id}→ Deletesdealflow/data/{id}.json, logs todealflow/backend/delete_log.txt(200/400).GET /dealflow/test_generator.php→ Creates 3 sample files indealflow/data/(200).
- Database Tables Touched:
dealflow_entries(POSTvia PostgREST). - External APIs: Cloudflare Turnstile (
POST https://challenges.cloudflare.com/turnstile/v0/siteverify, timeout8s).
6. Cross-Repository Dependencies
| Caller | Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|---|
planovi-flutter-app | planovi-microservices (dealflow) | HTTPS POST + X-Secret-Key (DEALFLOW_API_SECRET) | POST /api/save_dealflow.php, POST /api/create_offer.php |
planovi-flutter-app | planovi-microservices (dealflow) | HTTPS POST (No Auth) | POST /backend/delete_json.php |
dealflow/api/save_response.php | planovi-backend (Supabase PostgREST) | HTTPS POST + apikey & Bearer (SUPABASE_SERVICE_KEY) | POST /rest/v1/dealflow_entries (Prefer: return=minimal) |
includes/security.php | Cloudflare Turnstile | HTTPS 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; withoutSameSite=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 nestscompany_idanduser_idinsidejson_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 Message | Root Cause in Code | How to Verify / Exact Log or Query | Fix |
|---|---|---|---|
HTTP 403 "Błąd weryfikacji sesji (CSRF)" on submit | Browser 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 Mode | Bug 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 payload | Supabase 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. |