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 RBACteam_declarations|OTHERS/VIEW): manages templates, runs OCR & AI step suggestions, sends invitations/corrections/rejections, edits declarations (via JWT or 1hadmin_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.tokenonoffer.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}.jsonand renders stepped forms.
- Cooperative Staff / Board (
2. All Features & End-to-End Flows
- Template Upload (
upload-declaration/index.ts):multipart/form-data(file,company_id,template_name) ->requireStaff(OTHERS)-> uploads to PUBLIC bucketdeclaration-templates/${companyId}/${uuid}.${ext}(upsert: false) -> insertsdeclaration_templates(template_status: "active",created_by: user.id) + legacyocr_extraction_sessions(extraction_status: "uploaded",ai_model: "gemini-1.5-pro"). - AI OCR Extraction (
process-declaration-ocr/index.ts):requireStaff(OTHERS)+ tenant template check -> downloads fromdeclaration-templates->.pdfsent natively as base64inlineData(application/pdf) togemini-2.5-flash; non-.pdfunzipped vianpm:fflate@0.8.2(word/document.xmlonly, stripped XML >= 10 chars) and sent as text togemini-2.5-flash-> deletes existingcreated_from_ocr = truerows for template -> inserts extracteddeclaration_fields(field_order = index + 1; DB trigger assigns defaultstep_id). Ignoresocr_extraction_sessions. - Legacy Schema Approval (
approve-declaration-schema/index.ts): Reads legacyocr_extraction_sessions+ocr_extracted_fields(review_status ∈ {'approved','pending','edited'}), deactivates ALL other company templates, activates target, insertsdeclaration_fields, marks session'approved'. (Orphaned by currentprocess-declaration-ocr.) - AI Step Suggestion (
suggest-declaration-steps/index.ts) & Atomic Save (apply_declaration_stepsRPC in20261102100000):suggest-declaration-steps:POSTonly (405),requireStaff(OTHERS), loads1..300active fields informOrder, callsgemini-2.5-flash(temperature: 0.2, JSON mode; max 2 attempts on parse/validation errors, 0 retries on provider HTTP error) to return1..12contiguousfrom..toindex slices without mutating DB.apply_declaration_steps(p_template_id, p_steps)(SECURITY INVOKER, requiresplanovi_is_admin(v_company)): enforces exact bijection over all active fields, inserts new steps at temporarystep_order = 100000 + i, moves active fields (field_order = 1..k), parks inactive fields on first new step (100000 + old), deletes old steps, normalizesstep_order = 0..n-1.
- Template Migration (
change-declaration-template/index.ts):requireStaff(OTHERS)-> validates target template active & unarchived, session notarchived/rejected, not already on template ->carryAnswersToTemplatecopies matchingfield_keyvalues into empty target fields (number -> textif target non-numeric) -> updatesonboarding_sessions.declaration_template_id-> returnscarried_overcount &missing_required[]. - 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, ... }toFORM_WRITER_URL, returnspreview_url.create-admin-edit-link(requireStaff(OTHERS)): loads member + board-only (field_visibility: "admin") fields + current answers (loadMemberValues), inserts 60-min token intoadmin_edit_tokens, writes{ mode: "admin_edit", ... }toFORM_WRITER_URL, returnsedit_url.
- 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.0converts uploaded DOCX to styled A4 HTML with base64 images.generate-prefilled-docx:requireStaffOrSelf(OTHERS).action: "sign"validatesdeclaration-documents:<companyId>/<userProfileId>/...and returns 1h signed URL (origin rewritten toPUBLIC_SUPABASE_URL). Generate mode loads template +user_metadata+user_profilesfallbacks; runsDocxtemplaterifhasTags(docXml)else plain-formfill_form.ts(dot-line/checkbox slot matcher +"Pozostałe odpowiedzi"appendix); uploads to PRIVATE bucketdeclaration-documents; stores opaque ref"declaration-documents:<path>"ononboarding_sessions.generated_document_url; returns 1h signed URL.
- Member Onboarding Invite (
send-onboarding-invitation/index.ts):requireStaff(OTHERS)-> verifies active/unarchived template -> finds/creates Auth user +user_profiles(blocksfilledunlessresend: true->409; blocksemail_opt_out->409; rolls back Auth user on profile failure) -> reuses latest open session (NOT IN (completed,archived,rejected)) withcarryAnswersToTemplateif template changed -> callsissueFormLink(72h TTL; writes{token}.jsonBEFORE revoking old live tokens; fails502with no email if write fails) -> emails member via Resend (502on failure). - Declaration Submission (
submit-member-declaration/index.ts):- Token mode (public): validates
onboarding_tokens(used ->409 already_submitted: true; expired -> setsuser_profiles.onboarding_status = "expired", throws500) -> validates every answer via_shared/declaration_values.ts(410stale template,422all field errors together, checks all active required member fields) -> snapshots & replacesuser_metadatarows -> updatesuser_profiles(onboarding_status: "filled",is_energy_coop_member: true),onboarding_sessions(review_pending,admin_review_required: true),onboarding_tokens(used_at) -> runs non-fatalhandleEmails(downloads template, extracts text viamammoth, asksgemini-2.5-flashfor find/replace pairs, patchesword/document.xmlinPizZip, emails member + optionalADMIN_NOTIFICATION_EMAIL). - Authenticated mode (
requireStaffOrSelf(OTHERS)): validates & replaces only submittedvalues; does NOT check missing required fields, transition status, or send emails.
- Token mode (public): validates
- Status, Read, Board Edit, Review, Correction & Rejection:
get-company-declaration-schema: any active member -> returns allis_active = truedeclaration_fieldsforcompany_id.member-onboarding-status&get-member-declaration:requireStaffOrSelf(VIEW)-> completion metrics & coalesceduser_metadatavalues.update-member-declaration:admin_edit_token(1h, single-use) OR JWT; both enforcerequireStaff(OTHERS)-> validates all values upfront (422) -> diff-only writes touser_metadata+ logsdeclaration_change_log(source: "admin_edit") -> ifsubmit_on_behalf: trueand session in["started","declaration_uploaded","form_ready"], transitions session toreview_pending, closes unusedonboarding_tokens, setsuser_profiles.onboarding_status = "filled"-> ifnotify !== falseand non-admin changes/submitted, regenerates deterministic DOCX via_shared/docx.ts(Docxtemplater) and emails diff table -> marksadmin_edit_tokens.used_at.review-member-declaration:requireStaff(OTHERS)+targetInCompany-> inserts immutablemember_declaration_reviews(reviewed_by = user.id,review_status ∈ {approved, rejected, pending_review, correction_required}).send-correction-request-notice:requireStaff(OTHERS)-> blocksemail_opt_out(409) -> callsissueFormLink(forceNew: true, values: loadMemberValues(), correctionReason)(502on write fail) -> resets session to"started", profile to"correction_required"(fallback"pending") -> emails member (502on failure).send-rejection-notice:requireStaff(OTHERS)+targetInCompany-> setsuser_profiles(onboarding_status: "rejected",is_energy_coop_member: false) -> emails member unlessemail_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); everydeclaration_fieldsrow hasstep_id NOT NULLin 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.tscapslabel_htmlatMAX_LABEL_HTML = 20000, strips<script>/<style>, allowlistsp, br, b/strong->b, i/em->i, u, a[href https://|mailto:], ul, ol, li, balances tags, and forcesis_required = falseforinfo.BR-DECL-03(OCR Reading Order & Re-run Preservation):process-declaration-ocrpreserves paper reading order (field_order = index + 1) and deletes ONLYcreated_from_ocr = trueon re-run (preserving manual fields).BR-DECL-04(AI Step Proposal & Atomic Bijection Bounds):suggest-declaration-steps:1..300fields,1..12contiguous ranges covering1..nwith no reordering/dropping, title<= 60, description<= 300.apply_declaration_steps: exact bijection over allis_active = truefields.BR-DECL-05(Form-First Atomicity & Token TTLs): Preview & admin-edit tokens expire in60 min; member onboarding tokens expire inTOKEN_TTL_HOURS = 72. Old live onboarding tokens are revoked (DB + remote{old}.jsonoverwritten withexpires_at: "2000-01-01T00:00:00Z") ONLY AFTER the new{token}.jsonwrite succeeds (_shared/form_link.ts:349-355).BR-DECL-06(All-or-Nothing Typed Value Validation — HTTP 422):_shared/declaration_values.tschecks every field upfront:number(strip space/NBSP,,->.),boolean(true/false/1/0/tak/nie/yes/no),date(YYYY-MM-DDorDD[./-]MM[./-]YYYY, UTC calendar-valid),address(object or{ address }),email(lowercased regex),phone(>=7 digits,/^[+\d][\d\s\-()]*$/), defaulttext. Empty values clear all 5 columns tonull.BR-DECL-07(Template Integrity & Visibility): Token submit rejects fields from a different template (410). Member forms excludefield_visibility = 'admin'&field_type = 'calculated', and require >= 1 non-infofield (422). Board edit forms includeadminfields 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 formatDD.MM.YYYY; booleans format"Tak"/"Nie"(generate-prefilled-docx) or"TAK"/"NIE"(_shared/docx.ts).fill_form.tsskipssignature/info, usesLOOKAHEAD = 12slots, 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), anddeclaration_templates.template_status(active,inactive, plusis_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 bucketdeclaration-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-flashinprocess-declaration-ocr,suggest-declaration-steps,submit-member-declaration), DealFlowFORM_WRITER_URL(X-Api-Secret), Resend API.
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact 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-declaration | HTTPS POST / token (onboarding_tokens) or admin_edit_token | Submits { token, values } -> handles 200, 409, 410, 422 |
planovi-flutter-app -> Module 6 Functions & apply_declaration_steps | HTTPS POST + PostgREST / User JWT | Orchestrates template setup, invites, review + direct RLS session updates + grant-portal-access |
7. Why It Works This Way
- fflate
word/document.xmlunzipping inprocess-declaration-ocr: Replacedmammoth, which trippededge-runtimeCPU hard limits on large DOCX templates. - Consecutive
{from, to}slicing insuggest-declaration-steps: Makes it structurally impossible for Gemini to drop, invent, or reorder admin-curated fields. - Dual DOCX engines (
Docxtemplatervsfill_form.ts): Cooperatives upload standard Word files withLabel: .....and☐rather than{tag}templates;fill_form.tshandles plain documents without AI. - Private
declaration-documentsbucket +PUBLIC_SUPABASE_URLrewrite: 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 Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
Non-admin staff can preview AI steps (suggest-declaration-steps) but fail saving (42501 Forbidden) | suggest-declaration-steps checks `team_declarations | OTHERS, 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 templates | member-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 filters | Compare missing_fields vs active template’s declaration_fields | Filter 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 back | submit-member-declaration:177-206 doesn’t reject admin/calculated/inactive fields; get-member-declaration & get-company-declaration-schema return admin fields to plain members | Inspect 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 404 | send-rejection-notice:182 passes ?token=${user_profile_id} instead of onboarding_tokens.token | Click unsubscribe link in rejection email -> unsubscribe:57 404 | Pass actual token or update unsubscribe contract |
Rejected member can still submit old <72h form link and become is_energy_coop_member = true | send-rejection-notice does NOT revoke live onboarding_tokens or update onboarding_sessions | Check onboarding_tokens where used_at IS NULL after rejection | Revoke 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–43 | Fix UTF-8 strings to Nagłówek 1/2/3 and add tenant/size checks |
HTML injection in submit-member-declaration & send-rejection-notice emails | Unescaped name, value, rejectionReason interpolated directly into HTML | Inspect submit-member-declaration:610-661, send-rejection-notice:317-324 | Migrate 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 empty | SELECT 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_declarations | VIEW 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 |