Skip to content

6. Declaration Templates, OCR, Form Builder & Member Onboarding

Repository: Backend (planovi-backend) • Rule Prefix: BR-DECL • Documented Rules: 8 • Open [TEAM_WHY_NEEDED] Questions: 5

1. Business Purpose & Actors

End-to-end member accession declaration workflow for Polish energy cooperatives: uploading DOCX/PDF declaration templates, AI OCR extraction of form fields in document reading order, organizing fields into multi-step wizards (with AI step proposals and atomic DB replacement), generating external web-form preview/invitation/correction/board-edit links hosted on dealflow.planovi.app (offer.php), validating and storing typed member answers, rendering prefilled private DOCX documents, and recording board reviews, correction loops, and rejections.

  • Actors:
    • Cooperative Staff / Board (owner, admin, or RBAC team_declarations|OTHERS / VIEW): manages templates, runs OCR & AI step suggestions, sends invitations/corrections/rejections, edits declarations (via JWT or 1h admin_edit_token), records reviews, and generates/downloads prefilled DOCX.
    • Prospective / Cooperative Member (Token Holder — Unauthenticated): fills/resubmits web form via 72h single-use onboarding_tokens.token on offer.php -> submit-member-declaration.
    • Authenticated Company Member (Self): reads own completion status (member-onboarding-status), answers (get-member-declaration), submits answers (non-token mode), or generates/downloads own prefilled DOCX (generate-prefilled-docx).
    • External DealFlow Form Server (form-writer.php / offer.php): stores {token}.json and renders stepped forms.

2. All Features & End-to-End Flows

  1. Template Upload (upload-declaration/index.ts): multipart/form-data (file, company_id, template_name) -> requireStaff(OTHERS) -> uploads to PUBLIC bucket declaration-templates/${companyId}/${uuid}.${ext} (upsert: false) -> inserts declaration_templates (template_status: "active", created_by: user.id) + legacy ocr_extraction_sessions (extraction_status: "uploaded", ai_model: "gemini-1.5-pro").
  2. AI OCR Extraction (process-declaration-ocr/index.ts): requireStaff(OTHERS) + tenant template check -> downloads from declaration-templates -> .pdf sent natively as base64 inlineData (application/pdf) to gemini-2.5-flash; non-.pdf unzipped via npm:fflate@0.8.2 (word/document.xml only, stripped XML >= 10 chars) and sent as text to gemini-2.5-flash -> deletes existing created_from_ocr = true rows for template -> inserts extracted declaration_fields (field_order = index + 1; DB trigger assigns default step_id). Ignores ocr_extraction_sessions.
  3. Legacy Schema Approval (approve-declaration-schema/index.ts): Reads legacy ocr_extraction_sessions + ocr_extracted_fields (review_status ∈ {'approved','pending','edited'}), deactivates ALL other company templates, activates target, inserts declaration_fields, marks session 'approved'. (Orphaned by current process-declaration-ocr.)
  4. AI Step Suggestion (suggest-declaration-steps/index.ts) & Atomic Save (apply_declaration_steps RPC in 20261102100000):
    • suggest-declaration-steps: POST only (405), requireStaff(OTHERS), loads 1..300 active fields in formOrder, calls gemini-2.5-flash (temperature: 0.2, JSON mode; max 2 attempts on parse/validation errors, 0 retries on provider HTTP error) to return 1..12 contiguous from..to index slices without mutating DB.
    • apply_declaration_steps(p_template_id, p_steps) (SECURITY INVOKER, requires planovi_is_admin(v_company)): enforces exact bijection over all active fields, inserts new steps at temporary step_order = 100000 + i, moves active fields (field_order = 1..k), parks inactive fields on first new step (100000 + old), deletes old steps, normalizes step_order = 0..n-1.
  5. Template Migration (change-declaration-template/index.ts): requireStaff(OTHERS) -> validates target template active & unarchived, session not archived/rejected, not already on template -> carryAnswersToTemplate copies matching field_key values into empty target fields (number -> text if target non-numeric) -> updates onboarding_sessions.declaration_template_id -> returns carried_over count & missing_required[].
  6. Form Preview & Board Edit Links (create-form-preview/index.ts, create-admin-edit-link/index.ts):
    • create-form-preview (requireStaff(VIEW)): loads member-visible fields + steps (loadMemberForm), generates 64-hex-char 60-min token (not in DB), writes { preview: true, ... } to FORM_WRITER_URL, returns preview_url.
    • create-admin-edit-link (requireStaff(OTHERS)): loads member + board-only (field_visibility: "admin") fields + current answers (loadMemberValues), inserts 60-min token into admin_edit_tokens, writes { mode: "admin_edit", ... } to FORM_WRITER_URL, returns edit_url.
  7. DOCX Preview & Prefilled DOCX (docx-to-html/index.ts, generate-prefilled-docx/{index.ts,fill_form.ts}, 20261105140000):
    • docx-to-html: validateAuth(req) (any user JWT) -> mammoth@1.6.0 converts uploaded DOCX to styled A4 HTML with base64 images.
    • generate-prefilled-docx: requireStaffOrSelf(OTHERS). action: "sign" validates declaration-documents:<companyId>/<userProfileId>/... and returns 1h signed URL (origin rewritten to PUBLIC_SUPABASE_URL). Generate mode loads template + user_metadata + user_profiles fallbacks; runs Docxtemplater if hasTags(docXml) else plain-form fill_form.ts (dot-line/checkbox slot matcher + "Pozostałe odpowiedzi" appendix); uploads to PRIVATE bucket declaration-documents; stores opaque ref "declaration-documents:<path>" on onboarding_sessions.generated_document_url; returns 1h signed URL.
  8. Member Onboarding Invite (send-onboarding-invitation/index.ts): requireStaff(OTHERS) -> verifies active/unarchived template -> finds/creates Auth user + user_profiles (blocks filled unless resend: true -> 409; blocks email_opt_out -> 409; rolls back Auth user on profile failure) -> reuses latest open session (NOT IN (completed,archived,rejected)) with carryAnswersToTemplate if template changed -> calls issueFormLink (72h TTL; writes {token}.json BEFORE revoking old live tokens; fails 502 with no email if write fails) -> emails member via Resend (502 on failure).
  9. Declaration Submission (submit-member-declaration/index.ts):
    • Token mode (public): validates onboarding_tokens (used -> 409 already_submitted: true; expired -> sets user_profiles.onboarding_status = "expired", throws 500) -> validates every answer via _shared/declaration_values.ts (410 stale template, 422 all field errors together, checks all active required member fields) -> snapshots & replaces user_metadata rows -> updates user_profiles (onboarding_status: "filled", is_energy_coop_member: true), onboarding_sessions (review_pending, admin_review_required: true), onboarding_tokens (used_at) -> runs non-fatal handleEmails (downloads template, extracts text via mammoth, asks gemini-2.5-flash for find/replace pairs, patches word/document.xml in PizZip, emails member + optional ADMIN_NOTIFICATION_EMAIL).
    • Authenticated mode (requireStaffOrSelf(OTHERS)): validates & replaces only submitted values; does NOT check missing required fields, transition status, or send emails.
  10. Status, Read, Board Edit, Review, Correction & Rejection:
    • get-company-declaration-schema: any active member -> returns all is_active = true declaration_fields for company_id.
    • member-onboarding-status & get-member-declaration: requireStaffOrSelf(VIEW) -> completion metrics & coalesced user_metadata values.
    • update-member-declaration: admin_edit_token (1h, single-use) OR JWT; both enforce requireStaff(OTHERS) -> validates all values upfront (422) -> diff-only writes to user_metadata + logs declaration_change_log (source: "admin_edit") -> if submit_on_behalf: true and session in ["started","declaration_uploaded","form_ready"], transitions session to review_pending, closes unused onboarding_tokens, sets user_profiles.onboarding_status = "filled" -> if notify !== false and non-admin changes/submitted, regenerates deterministic DOCX via _shared/docx.ts (Docxtemplater) and emails diff table -> marks admin_edit_tokens.used_at.
    • review-member-declaration: requireStaff(OTHERS) + targetInCompany -> inserts immutable member_declaration_reviews (reviewed_by = user.id, review_status ∈ {approved, rejected, pending_review, correction_required}).
    • send-correction-request-notice: requireStaff(OTHERS) -> blocks email_opt_out (409) -> calls issueFormLink(forceNew: true, values: loadMemberValues(), correctionReason) (502 on write fail) -> resets session to "started", profile to "correction_required" (fallback "pending") -> emails member (502 on failure).
    • send-rejection-notice: requireStaff(OTHERS) + targetInCompany -> sets user_profiles (onboarding_status: "rejected", is_energy_coop_member: false) -> emails member unless email_opt_out (non-fatal warning).

3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-DECL)

  • BR-DECL-01 (Mandatory Step Invariant & Last-Step Guard): 20261030130000 & 20261102100000: Every template auto-gets an initial untitled step (step_order = 0); every declaration_fields row has step_id NOT NULL in the same template; deleting the last remaining step of a template raises 'Nie można usunąć ostatniego kroku szablonu (last step cannot be deleted)' (except during template CASCADE delete). Deleting a non-empty step moves fields to previous (or next) step.
  • BR-DECL-02 (Step & Rich-Label Limits): DB checks: declaration_steps.title <= 200, description <= 2000; declaration_fields.label_html <= 50000, preview_url <= 2048 (https:// real TLD only). _shared/form_link.ts caps label_html at MAX_LABEL_HTML = 20000, strips <script>/<style>, allowlists p, br, b/strong->b, i/em->i, u, a[href https://|mailto:], ul, ol, li, balances tags, and forces is_required = false for info.
  • BR-DECL-03 (OCR Reading Order & Re-run Preservation): process-declaration-ocr preserves paper reading order (field_order = index + 1) and deletes ONLY created_from_ocr = true on re-run (preserving manual fields).
  • BR-DECL-04 (AI Step Proposal & Atomic Bijection Bounds): suggest-declaration-steps: 1..300 fields, 1..12 contiguous ranges covering 1..n with no reordering/dropping, title <= 60, description <= 300. apply_declaration_steps: exact bijection over all is_active = true fields.
  • BR-DECL-05 (Form-First Atomicity & Token TTLs): Preview & admin-edit tokens expire in 60 min; member onboarding tokens expire in TOKEN_TTL_HOURS = 72. Old live onboarding tokens are revoked (DB + remote {old}.json overwritten with expires_at: "2000-01-01T00:00:00Z") ONLY AFTER the new {token}.json write succeeds (_shared/form_link.ts:349-355).
  • BR-DECL-06 (All-or-Nothing Typed Value Validation — HTTP 422): _shared/declaration_values.ts checks every field upfront: number (strip space/NBSP, ,->.), boolean (true/false/1/0/tak/nie/yes/no), date (YYYY-MM-DD or DD[./-]MM[./-]YYYY, UTC calendar-valid), address (object or { address }), email (lowercased regex), phone (>=7 digits, /^[+\d][\d\s\-()]*$/), default text. Empty values clear all 5 columns to null.
  • BR-DECL-07 (Template Integrity & Visibility): Token submit rejects fields from a different template (410). Member forms exclude field_visibility = 'admin' & field_type = 'calculated', and require >= 1 non-info field (422). Board edit forms include admin fields but omit them from member change emails.
  • BR-DECL-08 (Private DOCX Storage & Formatting): declaration-documents (20261105140000) is PRIVATE with zero RLS policies (service-role only), paths <companyId>/<userProfileId>/<uuid>.docx, served via 1h (3600s) signed URLs. Dates format DD.MM.YYYY; booleans format "Tak"/"Nie" (generate-prefilled-docx) or "TAK"/"NIE" (_shared/docx.ts). fill_form.ts skips signature/info, uses LOOKAHEAD = 12 slots, and appends unmatched answers under "Pozostałe odpowiedzi".

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> started : send-onboarding-invitation
    started --> review_pending : submit-member-declaration (token) / submit_on_behalf
    review_pending --> started : send-correction-request-notice
    review_pending --> completed : Flutter RLS update + grant-portal-access
    review_pending --> rejected : Flutter RLS update + send-rejection-notice
    started --> archived : Flutter RLS update
    completed --> archived : Flutter RLS update
    rejected --> archived : Flutter RLS update
  • Four decoupled status spaces: onboarding_sessions.onboarding_status (started, declaration_uploaded, form_ready, review_pending, completed, archived, rejected), user_profiles.onboarding_status (pending, filled, expired, correction_required, approved, rejected), member_declaration_reviews.review_status (approved, rejected, pending_review, correction_required), and declaration_templates.template_status (active, inactive, plus is_archived).

5. Technical Contract

  • Endpoints (18): upload-declaration, process-declaration-ocr, approve-declaration-schema, suggest-declaration-steps, get-company-declaration-schema, change-declaration-template, create-form-preview, create-admin-edit-link, docx-to-html, generate-prefilled-docx, send-onboarding-invitation, member-onboarding-status, submit-member-declaration, get-member-declaration, update-member-declaration, review-member-declaration, send-correction-request-notice, send-rejection-notice.
  • SQL Objects: declaration_steps (+ 4 triggers), backup_declaration_fields_2026_10_30, public.apply_declaration_steps(uuid, jsonb), private bucket declaration-documents.
  • Tables Read/Written: declaration_templates, declaration_steps, declaration_fields, ocr_extraction_sessions, ocr_extracted_fields, onboarding_sessions, onboarding_tokens, admin_edit_tokens, user_metadata, declaration_change_log, member_declaration_reviews, user_profiles, company_members, RBAC tables.
  • External APIs: Google Gemini (gemini-2.5-flash in process-declaration-ocr, suggest-declaration-steps, submit-member-declaration), DealFlow FORM_WRITER_URL (X-Api-Secret), Resend API.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
_shared/form_link.ts -> planovi-microservices (api/form-writer.php)HTTPS POST / X-Api-Secret (DEALFLOW_API_SECRET, 15s timeout){ token, data } -> persists {token}.json for offer.php
planovi-microservices (offer.php) -> submit-member-declaration / update-member-declarationHTTPS POST / token (onboarding_tokens) or admin_edit_tokenSubmits { token, values } -> handles 200, 409, 410, 422
planovi-flutter-app -> Module 6 Functions & apply_declaration_stepsHTTPS POST + PostgREST / User JWTOrchestrates template setup, invites, review + direct RLS session updates + grant-portal-access

7. Why It Works This Way

  • fflate word/document.xml unzipping in process-declaration-ocr: Replaced mammoth, which tripped edge-runtime CPU hard limits on large DOCX templates.
  • Consecutive {from, to} slicing in suggest-declaration-steps: Makes it structurally impossible for Gemini to drop, invent, or reorder admin-curated fields.
  • Dual DOCX engines (Docxtemplater vs fill_form.ts): Cooperatives upload standard Word files with Label: ..... and ☐ rather than {tag} templates; fill_form.ts handles plain documents without AI.
  • Private declaration-documents bucket + PUBLIC_SUPABASE_URL rewrite: Protects member PII (PESEL/addresses) and fixes internal Docker signed URLs for browsers.
  • [TEAM_WHY_NEEDED: Is approve-declaration-schema (and ocr_extraction_sessions / ocr_extracted_fields) dead code now that process-declaration-ocr writes directly to declaration_fields?]
  • [TEAM_WHY_NEEDED: Why does submit-member-declaration still use mammoth + gemini-2.5-flash + raw XML regex to patch DOCX instead of generate-prefilled-docx / _shared/docx.ts?]
  • [TEAM_WHY_NEEDED: Why does submit-member-declaration set user_profiles.is_energy_coop_member = true immediately before board approval, whereas update-member-declaration (submit_on_behalf) does not?]
  • [TEAM_WHY_NEEDED: Why do create-form-preview and create-admin-edit-link hardcode Planovi dark colors (#32CA42 / #09090B) instead of loading tenant branding (Zone 2)?]
  • [TEAM_WHY_NEEDED: Why is ADMIN_NOTIFICATION_EMAIL in submit-member-declaration a single global env var rather than per-company owners/admins?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
Non-admin staff can preview AI steps (suggest-declaration-steps) but fail saving (42501 Forbidden)suggest-declaration-steps checks `team_declarationsOTHERS, whereas apply_declaration_steps&declaration_stepsRLS requireplanovi_is_admin(company_id)`Check 20261102100000_apply_declaration_steps.sql & 20261030130000
member-onboarding-status counts cleared/null answers as completed & mixes archived templatesmember-onboarding-status:248-279 checks answerMap.has(id) (even when value is false) and queries ALL declaration_fields for company_id without template/active/visibility filtersCompare missing_fields vs active template’s declaration_fieldsFilter by active session’s declaration_template_id, is_active=true, non-admin/non-info/non-calc, and check answerMap.get(id) === true
Member can overwrite field_visibility = 'admin' fields or read them backsubmit-member-declaration:177-206 doesn’t reject admin/calculated/inactive fields; get-member-declaration & get-company-declaration-schema return admin fields to plain membersInspect POST payload validation in submit-member-declaration & SELECTs in get-*Reject field_visibility === 'admin', calculated, and !is_active for non-staff callers
Unsubscribe link in send-rejection-notice always returns 404send-rejection-notice:182 passes ?token=${user_profile_id} instead of onboarding_tokens.tokenClick unsubscribe link in rejection email -> unsubscribe:57 404Pass actual token or update unsubscribe contract
Rejected member can still submit old <72h form link and become is_energy_coop_member = truesend-rejection-notice does NOT revoke live onboarding_tokens or update onboarding_sessionsCheck onboarding_tokens where used_at IS NULL after rejectionRevoke live onboarding_tokens & overwrite {token}.json on rejection
docx-to-html fails to convert Polish Word headings (Nagłówek 1/2/3)Mojibake in docx-to-html/index.ts:41-43 (Nagłówek 1)Inspect styleMap lines 41–43Fix UTF-8 strings to Nagłówek 1/2/3 and add tenant/size checks
HTML injection in submit-member-declaration & send-rejection-notice emailsUnescaped name, value, rejectionReason interpolated directly into HTMLInspect submit-member-declaration:610-661, send-rejection-notice:317-324Migrate both to _shared/email.ts (escapeHtml/escapeMultiline/emailShell)
approve-declaration-schema always fails 500 "No OCR fields found"Current process-declaration-ocr writes directly to declaration_fields, leaving ocr_extracted_fields emptySELECT count(*) FROM ocr_extracted_fields WHERE ocr_session_id=...;Deprecate/remove approve-declaration-schema & ocr_extraction_sessions creation in upload-declaration
generate-prefilled-docx returns 403 for `team_declarationsVIEW staff trying to download (action: “sign”`)generate-prefilled-docx:202 passes "OTHERS" instead of "VIEW" for action: "sign"Check generate-prefilled-docx/index.ts:202