Skip to content

3. Token-Based Onboarding & Member Declaration Forms — Token Mode

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

1. Business Purpose & Actors

  • Problem Solved: Delivers secure, time-limited, multi-step declaration and onboarding forms to cooperative members (for joining an energy cooperative or correcting rejected declarations), new SaaS company admins (post-Stripe legal data collection: NIP/KRS/address), and board members (previewing templates or filling/editing paper declarations on a member’s behalf with full change history).
  • Actors:
    • Supabase Edge Functions (planovi-backend): send-onboarding-invitation, send-correction-request-notice, create-form-preview (via _shared/form_link.ts) write token JSON payloads via dealflow/api/form-writer.php.
    • Cooperative Member / Prospective Company Admin: Opens dealflow/offer.php?token={64-hex}, completes multi-step fields (including handwritten signature canvas), consents to RODO, and submits.
    • Cooperative Board Admin: Opens preview (preview: true) or board-edit (mode: 'admin_edit') links generated from the Planovi panel.

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

  • Feature A: Write Token Form Snapshot (POST dealflow/api/form-writer.php)
    • Trigger: Edge Functions in planovi-backend call POST /dealflow/api/form-writer.php with X-Api-Secret header.
    • Validation: Constant-time hash_equals($expectedSecret, $providedSecret) against DEALFLOW_API_SECRET (401) → POST only (405) → JSON body must contain token and data (400) → token stripped to lowercase hex [a-f0-9] must be >= 32 chars (400) → ../data must exist (500).
    • State Change: Writes dealflow/data/{token}.json using LOCK_EX and JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE.
    • Response: HTTP 200 {"success": true, "file": "{token}.json", "bytes": N}.
  • Feature B: Token Validation & Mode Resolution (GET dealflow/offer.php?token={hex})
    • Trigger: Visitor opens link with >= 32 lowercase hex chars in ?token=.
    • Validation Pipeline (ordered, short-circuiting):
      1. File dealflow/data/{cleanToken}.json must exist → else "Link wygasł lub jest nieprawidłowy. Poproś o nowe zaproszenie."
      2. JSON must decode to array → else "Błąd odczytu danych formularza. Skontaktuj się z administratorem."
      3. !empty($tokenFormData['revoked']) → "Ten link został zastąpiony nowym. Użyj linku z najnowszego e-maila."
      4. isset($tokenFormData['expires_at']) && strtotime($tokenFormData['expires_at']) < time() → preview: "Podgląd wygasł. Otwórz podgląd ponownie z panelu."; standard: "Ten link wygasł (ważny 72h). Poproś o nowe zaproszenie."
      5. Live DB usage check (skipped for IS_PREVIEW and IS_ADMIN_EDIT): POST {SUPABASE_URL}/rest/v1/rpc/onboarding_token_status with {"p_token": $cleanToken} (timeout 5s, SUPABASE_ANON_KEY). If $dbRes[0]['used_at'] is non-empty → "Ta deklaracja została już wysłana. Dziękujemy!"
    • Mode & Target Function Resolution (offer.php:98, 138-150):
      • Default: submit-member-declaration
      • If mode === 'admin_edit': IS_ADMIN_EDIT = true → update-member-declaration
      • If !empty($tokenFormData['deal_id']): overrides to submit-company-details
      • If !empty($tokenFormData['preview']): IS_PREVIEW = true (submission disabled)
  • Feature C: Multi-Step Form Rendering, Rich Labels, Prefill & Signature Pad
    • Step Grouping: Groups visible fields by step_id according to steps[] order; fields with unknown/missing step_id append to a final fallback step. Empty steps are dropped. If > 1 step, renders clickable step chips (compact numeric chips when > 4 steps), "Krok X z N", "← Wstecz", "Dalej →". Consent/board options and submit button appear only on the last step.
    • Field Types: info (read-only notice box, no data-fid, never validated/submitted), text, email, phone (tel), number (type="text" inputmode="decimal" accepting Polish decimal comma), date, boolean (Tak/Nie radio pair), address (3-row textarea), signature (HTML5 <canvas> 600×150 CSS scaled by devicePixelRatio || 2, with preview/change/clear controls and legacy text-signature compatibility).
    • Prefill & Correction Banner: Pre-populates answers from values[field_id]. If correction_reason is non-empty, renders amber "Uwagi zarządu" callout banner.
  • Feature D: Client Validation, Signature Upload & Submission
    • Validation: Advancing via "Dalej" or clicking a forward step chip validates every prior step (goToStep() stops at first failing step unless IS_PREVIEW). Final submit validates ALL fields across ALL steps at once (skipping required checks in IS_ADMIN_EDIT so board can save partial paper declarations) plus #tok-rodo checkbox (non-admin modes only). Pressing Enter before the last step triggers goNext() instead of submitting.
    • Signature Upload: Before calling the Edge Function, iterates values[]; any string starting with data:image/png;base64, is decoded to binary Blob (image/png) and uploaded via POST {SUPABASE_URL}/storage/v1/object/company-media/{COMPANY_ID}/signatures/{SESSION_ID}_{field_id}_{timestamp}.png (x-upsert: true, SUPABASE_ANON_KEY). On HTTP 2xx, replaces base64 with public Storage URL; on failure/exception, silently falls back to inline base64 data URL (offer.php:1388-1424).
    • Submission: POST {submitFnUrl} with apikey + Authorization: Bearer {ANON_KEY}:
      • Member / Company mode: { token, values }
      • Admin edit mode: { admin_edit_token, values, notify, submit_on_behalf, note }
    • Response & Error Handling:
      • data.success: Hides form, shows #tok-success (in admin mode displays changed field count, submitted_on_behalf badge, email_sent badge, and any data.warnings).
      • data.already_submitted OR (!IS_ADMIN_EDIT && res.status === 409): Hides form, shows "Deklaracja już wysłana ✓".
      • 422 / other server error: Keeps form open with all typed data intact, maps data.errors[] ({field_id, message}) to per-field inline errors, jumps to the step containing the first error, and shows summary banner.
      • Network error: Keeps form and typed values intact, shows "Brak połączenia z serwerem." banner.

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

  • BR-DEC-01 (Token Format & Security): Tokens must be >= 32 lowercase hex chars ([a-f0-9]). form-writer.php:37 uses constant-time hash_equals on X-Api-Secret vs DEALFLOW_API_SECRET and writes with LOCK_EX (form-writer.php:81).
  • BR-DEC-02 (Field Visibility & Calculated Field Filtering): offer.php:176-181 always strips fields with field_type === 'calculated'. Fields with field_visibility === 'admin' are stripped unless $IS_ADMIN_EDIT === true (in which case they display an orange "zarząd" badge, offer.php:738-740).
  • BR-DEC-03 (Dual-Pass HTML Allowlist Sanitizer): planovi_clean_label_html() (offer.php:39-86) truncates input to 20,000 bytes, strips <script>/<style> blocks, allows ONLY tags p, br, b (strong→b), i (em→i), u, a, ul, ol, li, enforces href matching ^(https://|mailto:) (injecting target="_blank" rel="noopener noreferrer nofollow"), balances unclosed tags via a stack, and returns '' if stripped text is empty.
  • BR-DEC-04 (Preview URL Allowlist): planovi_clean_preview_url() (offer.php:89-93) accepts only https:// URLs <= 2048 chars with a real domain TLD (\.[A-Za-z]{2,}), rejecting HTTP, IPs, localhost, and credentialed URLs.
  • BR-DEC-05 (Field Type Validation Parity with _shared/declaration_values.ts): fieldProblem() (offer.php:1176-1203):
    • Empty value: error 'To pole jest wymagane.' only if !IS_ADMIN_EDIT && data-req === '1'.
    • number: strips spaces & NBSP (\u00A0), converts , to ., checks Number.isFinite(n) → else 'Wpisz liczbę (np. 12 lub 12,5).'.
    • date: matches /^(\d{4})-(\d{2})-(\d{2})/ and verifies exact UTC calendar validity (rejects e.g. 2026-02-30) → else 'Wpisz poprawną datę (RRRR-MM-DD).'.
    • email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ → else 'Nieprawidłowy adres e-mail.'.
    • phone: >= 7 digits AND matches /^[+\d][\d\s\-()]*$/ → else 'Nieprawidłowy numer telefonu.'.
    • boolean, address, signature, text: any non-empty value accepted.
  • BR-DEC-06 (Emptied Optional Fields Clear Prior Values): During corrections or board edits, empty optional fields explicitly emit { field_id, value: null } (offer.php:1376-1379) so backend clears previously stored values instead of ignoring them.
  • BR-DEC-07 (Board Paper-Declaration Checkbox Gate): The "Deklaracja złożona na papierze – przekaż do recenzji" checkbox (#adm-paper, default checked) is rendered ONLY in IS_ADMIN_EDIT when session_status is in ['started', 'declaration_uploaded', 'form_ready'] (offer.php:863).
  • BR-DEC-08 (Compact Step Chips Threshold): When count($tokenSteps) > 4, .tok-steps receives class .compact, displaying step numbers only with full titles in title/aria-label tooltips (offer.php:679, 536-537).
  • BR-DEC-09 (Signature Preview Classification): Existing signature value renders as <img> if it starts with http://, https://, data:image, or contains /storage/; otherwise renders as italicized legacy text with "(tekst z poprzedniej wersji formularza)" (offer.php:767-786).
  • BR-DEC-10 (Live Error Recheck Without Blur Layout Shift): Field errors re-validate on input (or change for radios) ONLY while the error element is currently visible (offer.php:1309-1319), explicitly avoiding blur so layout shift does not swallow clicks on the next input.

4. State Machines & Data Lifecycle

Token Link Lifecycle:

stateDiagram-v2
    [*] --> Written: POST form-writer.php -> data/{token}.json
    Written --> Active: Valid, not revoked, not expired, used_at IS NULL
    Written --> Revoked: Re-written with revoked=true (resend/correction)
    Written --> Expired: now() > expires_at (72h member / preview TTL)
    Active --> Submitted: Edge Function returns success=true (sets used_at in DB)
    Active --> AlreadyUsed: RPC onboarding_token_status returns used_at != null OR 409
    Active --> PreviewOnly: preview=true (no DB check, submit disabled)
    Active --> BoardSaved: mode=admin_edit -> update-member-declaration
    Revoked --> [*]
    Expired --> [*]
    Submitted --> [*]
    AlreadyUsed --> [*]
    BoardSaved --> [*]

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

  • Endpoints:
    • POST /dealflow/api/form-writer.php → Header X-Api-Secret, Body {token, data} → Writes dealflow/data/{token}.json (200/400/401/405/500).
    • GET /dealflow/offer.php?token={64-hex} → Server-side reads JSON, calls RPC onboarding_token_status, renders HTML form.
  • RPCs / Edge Functions / Storage Called:
    • POST {SUPABASE_URL}/rest/v1/rpc/onboarding_token_status (p_token) — server-side PHP cURL (5s timeout, SUPABASE_ANON_KEY).
    • POST {SUPABASE_URL}/storage/v1/object/company-media/{company_id}/signatures/{session_id}_{field_id}_{timestamp}.png — client-side fetch (SUPABASE_ANON_KEY, x-upsert: true).
    • POST {SUPABASE_URL}/functions/v1/submit-member-declaration — client-side fetch ({token, values}).
    • POST {SUPABASE_URL}/functions/v1/update-member-declaration — client-side fetch ({admin_edit_token, values, notify, submit_on_behalf, note}).
    • POST {SUPABASE_URL}/functions/v1/submit-company-details — client-side fetch ({token, values}).

6. Cross-Repository Dependencies

CallerCalleeProtocol & AuthExact Endpoint / Contract
planovi-backend (_shared/form_link.ts via send-onboarding-invitation, send-correction-request-notice, create-form-preview)planovi-microservices (dealflow)HTTPS POST + X-Api-Secret (DEALFLOW_API_SECRET)POST /dealflow/api/form-writer.php
dealflow/offer.php (PHP server)planovi-backend (Supabase RPC)HTTPS POST + apikey/Bearer (SUPABASE_ANON_KEY)POST /rest/v1/rpc/onboarding_token_status
dealflow/offer.php (browser JS)planovi-backend (Supabase Storage)HTTPS POST + apikey/Bearer (SUPABASE_ANON_KEY)POST /storage/v1/object/company-media/{company_id}/signatures/...
dealflow/offer.php (browser JS)planovi-backend (Supabase Edge Functions)HTTPS POST + apikey/Bearer (SUPABASE_ANON_KEY)POST /functions/v1/{submit-member-declaration|update-member-declaration|submit-company-details}

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

  • RPC onboarding_token_status Instead of Direct Table Read (9467cfe4): Token JSON files on disk cannot know if a member already submitted the form; an RPC is used instead of opening direct anon SELECT on onboarding token tables.
  • Text Input with inputmode="decimal" for Numbers (1cc09803): Native <input type="number"> silently dropped non-numeric/comma input in browsers; switching to type="text" inputmode="decimal" allows Polish commas ("12,5") and surfaces explicit inline validation errors.
  • Quoted .env Fix (25fcdc97): offer.php and form-writer.php strip surrounding " / ' from .env values after quoted secrets caused 401 failures.
  • Step Hiding Without Tailwind CDN Dependency (offer.php:555-556): .tok-step.hidden, #tok-final.hidden, .tok-nav .hidden { display: none !important; } is defined in inline CSS so multi-step visibility never breaks if cdn.tailwindcss.com loads slowly or fails.
  • Signature Base64 Fallback (00b9b20a): If direct browser upload to company-media Storage fails, the inline data:image/png;base64,... string is submitted directly to the Edge Function instead of blocking form submission.
  • [TEAM_WHY_NEEDED: Does Supabase Storage bucket company-media allow unauthenticated anon uploads via SUPABASE_ANON_KEY with x-upsert: true for any {company_id}/signatures/* path? Is there an RLS policy scoping uploads to valid active onboarding sessions, or can an attacker overwrite signatures?]
  • [TEAM_WHY_NEEDED: In offer.php:141-150, if a token ever contained both mode='admin_edit' and deal_id, deal_id would overwrite submitFnUrl to submit-company-details while sending the admin_edit_token payload — confirm those two flags are mutually exclusive in planovi-backend.]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Log or QueryFix
form-writer.php returns HTTP 401X-Api-Secret header does not match DEALFLOW_API_SECRET in root .env (form-writer.php:33-41). Note header name is X-Api-Secret, NOT X-Secret-Key.Check Edge Function logs in planovi-backend and verify .env DEALFLOW_API_SECRET.Sync DEALFLOW_API_SECRET between VPS .env and Supabase Edge Function secrets.
"Ta deklaracja została już wysłana. Dziękujemy!" unexpectedlyonboarding_token_status RPC returned non-null used_at (offer.php:169-171).Run SELECT * FROM onboarding_token_status('<token>'); in Supabase SQL editor.Issue a new resend/correction token from the panel.
Signature canvas appears blank or distorted after clicking "Dalej"Canvas was hidden (display:none) during initial initSignaturePads(), giving rect.width === 0; showStep() calls resizeVisibleCanvases() (offer.php:1252, 1515-1523).Verify canvas width/height attributes in DOM inspector when step becomes active.Only resizes if !canvas._hasStrokes; window resize after drawing is not re-scaled.
"Nie zapisano." on submit with field errorsEdge Function returned HTTP 422 with errors: [{field_id, message}] (offer.php:1487-1497).Inspect Network tab response JSON from submit-member-declaration / update-member-declaration.Fix highlighted fields; form preserves all entered data.