Skip to content

8. Offers, Agreements, Templates, Document Archive & DOCX/PDF Engine

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-DOCS • Documented Rules: 30 • Open [TEAM_WHY_NEEDED] Questions: 4

1. Business Purpose & Actors

Owns the commercial and internal document lifecycle: (1) drafting, pricing (per-item VAT & discounts), version-forking, snapshot-locking, PDF rendering, and sharing of commercial Offers; (2) creating offer-linked or direct Agreements with multi-signatory serial/parallel e-signature (SES/AES/QES) workflows; (3) visual A4 Canvas (794×1123 px) + raw HTML/CSS Template authoring with Zone 2 presets (template_styles.dart) and Gemini AI generation; (4) internal Document Archive (company_documents) with Draft/Published workflow, VIP access, read receipts, version history, interactive Quill tables, client-side DOCX XML parsing, Microsoft Office Online viewer, PDF/TXT export, and Knowledge Base PDF bridging.

  • Actors:
    • Tenant Sales / Admin Staff: Governed by PermissionProvider resources offers, agreements, offer_templates, agreement_templates, documents (CREATE, UPDATE, DELETE).
    • Document Author: Implicit edit/delete rights on own company_documents (doc.authorId == currentUserId) and sole viewer of own DRAFT documents.
    • Company Members: Read global or document_access-permitted PUBLISHED documents and submit read receipts (document_read_receipts).
    • External Clients / Signatories: Receive Resend emails with 7-day signed PDF URLs, view public offers (https://app.planovi.app/offer/{tracking_token}), and sign agreements.
    • Edge Functions: generate-offer, generate-agreement (service role), and docx-to-html (stateless Mammoth converter).

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

  • Offers (offers_list_screen.dart, create_offer_screen.dart):
    • List loads offers + clients, displays tokenized share link (non-drafts), open_count, locale, vN, and internal offer_notes (2-step author fetch; delete checks .select('id') to detect silent RLS block). Deleting an offer is blocked in UI unless status == 'draft'.
    • Editor: Desktop 2-pane (38% form / 62% live browser preview with 375px mobile toggle) or Mobile 4-step wizard (<900px). Supports blank, edit, fork, and Dealflow prefill (+14d expiry, price_breakdown). Banner uploads to offer_images (<= 5.0 MB, 1920×1080).
    • Save Draft / Send: Updates use OCC (.eq('concurrency_version', _currentVersion)), replace offer_items, insert changed offer_notes. Sending additionally requires _expiresAt != null & _pricingItems.isNotEmpty, invokes generate-offer, locks UI (_sentHere = true), and writes one-time locked_data/locked_layout using .isFilter(..., null). Failure leaves offer as 'draft'.
    • Version Fork (createOfferVersion): Optional OCC guard (OfferVersionConflict), walks parent_offer_id to root + BFS across all descendants to compute maxVersion + 1, copies header + offer_items (fallback _itemsFromLockedData), compensates by deleting the new offer row if item copy fails.
  • Agreements (agreements_list_screen.dart, create_agreement_screen.dart):
    • List loads agreements + agreement_signatories. Actions: Edit (draft only), Send for Signature (not accepted/declined + ≥1 pending signatory → invokes external send-signature-request, updates status = 'pending'), Open PDF (signed_pdf_url if accepted else pdf_url), Copy Signed Link, Delete (blocked if accepted; RPC delete_agreement with direct-delete fallback).
    • Editor: offer_based (picker lists pending/viewed/accepted offers) or direct; SES/AES/QES; serial (1..N) or parallel (1 for all); signatories locked once non-draft; entire form locked when accepted/declined. Save & Send invokes generate-agreement then send-signature-request, then sets status = 'pending'.
  • Templates (templates_combined_screen.dart, create_template_screen.dart, template_styles.dart, template_gallery_screen.dart, dealflow_blanks_service.dart, gemini_*_service.dart):
    • Lists filter templates by template_type (offer/agreement) and deleted_at IS NULL; soft-delete sets deleted_at + is_active = false.
    • Editor (5,123 LOC): A4 Canvas (794×1123 px, 20px snap, 0.1–4.0× zoom, undo/redo, 7 active item types, offer_images uploads, watermark opacity 0.05–1.0) + raw HTML mode (24 variable chips, inline Web iframe / Mobile WebView preview, new-tab Blob preview, 7-preset Zone 2 gallery). Saving _selectedType == 'both' inserts two rows on create (falls back to 'offer' on edit).
    • Dealflow variable extraction calls GeminiPlaceholderService (direct client-side Gemini REST call!) falling back to DealflowBlanksService (Hostinger data/{id}.json → Supabase dealflows.json).
  • Document Archive, Quill Editor & DOCX/PDF Engine (documents_list_screen.dart, document_reader_screen.dart, document_editor_screen.dart, docx_viewer_*.dart):
    • List shows Published vs Drafts tabs (is_pinned DESC, created_at DESC), client-filtered by visibility (author, is_global, document_access). RecentDocumentsWidget shows top 3 published docs.
    • Reader auto-detects raw HTML (<!DOCTYPE/<html): mobile/desktop uses WebViewController, Web falls back to raw monospace SelectableText. Otherwise read-only Quill + image/YouTube embeds + attachments + idempotent read-receipt bar (document_read_receipts).
    • Editor (5,344 LOC): Side panel or A4 Word fullscreen (50%–200% zoom), 10s autosave, custom InteractiveTableWidget (resizable cols min 0.04, merge right, 1.5s debounced sync), resizable images (orphan-cleaned from documents bucket on save), YouTube cards, publish-time snapshots (document_versions), 6 built-in + company_templates CRUD, client-side DOCX import (ZipDecoder+XmlDocument parser + preserved header/footer/watermark warning + original uploaded to public URL for Microsoft Office Online viewer), client-side PDF/TXT export (PdfGoogleFonts.roboto*, diagonal watermark), and Knowledge Base bridge (PDF + SHA-256 → governance_documents + row in company_documents).
  • Edge Functions:
    • generate-offer & generate-agreement: Render A4 PDF via pdf-lib (Roboto from documents/fonts/ or Helvetica fallback), upload to documents, mint 7-day signed URL, update DB (offers/agreements + dealflow_entries.current_stage), insert activity_log & webhook_deliveries, send Resend email (dual_dispatch: true writes _final.pdf and emails both client and sender).
    • docx-to-html: Accepts multipart/form-data file, converts via mammoth@1.6.0 (mapping EN/PL headings + inline base64 images) into 794×1123 HTML.

3. Hard Business Rules (BR-DOCS-01..30)

  • BR-DOCS-01 (Offer Pricing & VAT): Allowed VAT rates [23, 8, 5, 0]; discount = percent ? net * val / 100 : val.clamp(0, net); netAfter = (net - discount).clamp(0, ∞); vat = netAfter * rate / 100; gross = netAfter + vat (create_offer_screen.dart:65-72,373).
  • BR-DOCS-02 (Offer Required Fields): Draft requires title + client; Send also requires _expiresAt != null + _pricingItems.isNotEmpty (create_offer_screen.dart:752-767).
  • BR-DOCS-03 (Offer Immutability & Locking): Non-draft offers cannot be edited or deleted (only forked); locked_data/locked_layout written once via .isFilter(..., null) (create_offer_screen.dart:105,361,901-910, offers_list_screen.dart:125-133).
  • BR-DOCS-04 (Offer OCC): Updates require .eq('concurrency_version', currentVersion) and increment +1 (create_offer_screen.dart:807-821).
  • BR-DOCS-05 (Offer Version Numbering): Root-walk + BFS over parent_offer_id tree assigns maxVersion + 1 as new 'draft' (create_offer_screen.dart:125-190).
  • BR-DOCS-06 (Offer Share URL & Ref): Share URL https://app.planovi.app/offer/{tracking_token}; PDF Ref (tracking_token ?? id).substring(0, 8).toUpperCase() (offers_list_screen.dart:315-318, generate-offer/index.ts:227).
  • BR-DOCS-07 (Offer Currencies & Locales): Currencies ['PLN', 'EUR', 'USD', 'GBP'] (default 'PLN'); locales ['pl-PL', 'de-DE', 'en-GB'] (default 'pl-PL'); Dealflow default expiry +14 days (create_offer_screen.dart:318-319,475,1965,1987-1989).
  • BR-DOCS-08 (Banner Upload Limits): Max 1920×1080 px, <= 5.0 MB, public bucket offer_images (create_offer_screen.dart:641-666, create_agreement_screen.dart:330-351).
  • BR-DOCS-09 (Agreement Locking & Delete Guard): Locked on accepted/declined; delete blocked on accepted; offer_based picker allows only pending/viewed/accepted offers (create_agreement_screen.dart:128-139,300,427-446, agreements_list_screen.dart:117-125).
  • BR-DOCS-10 (Signatory Modes & Levels): SES/AES/QES (default SES); serial (1..N) or parallel (all 1); signatories immutable after draft; default Dealflow deadline +7 days (create_agreement_screen.dart:89-91,139,245,532-533).
  • BR-DOCS-11 (Agreement OCC): Gates updates on concurrency_version (agreement_repository.dart:80-98, create_agreement_screen.dart:487-501).
  • BR-DOCS-12 (Agreement Dual Dispatch): dual_dispatch: true writes agreements/{id}_final.pdf, sets signed_pdf_url (leaving status untouched), triggers agreement_accepted email + webhook, and emails both client_email and sender_email (generate-agreement/index.ts:515,552,564-569,603-657).
  • BR-DOCS-13 (Agreement PDF Fee Math): Hardcodes 23% VAT (setup * 1.23, monthly * 1.23); total net = monthly * duration + setup (default 12 months) (generate-agreement/index.ts:233-236,335-343).
  • BR-DOCS-14 (Signed PDF TTL): Both PDF Edge Functions mint 7-day (604800s) signed URLs (generate-offer/index.ts:500-507, generate-agreement/index.ts:553-560).
  • BR-DOCS-15 (Resend Email Dispatch): from: "Planovi <${FROM_EMAIL ?? 'noreply@planovi.pl'}>"; replaces /\{\{(\w+)\}\}/g; non-fatal on missing key/send error in generate-offer (generate-offer/index.ts:161,407-419,560-601).
  • BR-DOCS-16 (Zone 2 Presets — Immutable): 7 presets in template_styles.dart:75-146: planovi_modern, modern_blue, minimal_white, dark_premium, green_energy, teal_planowi, commercial_offer.
  • BR-DOCS-17 (Placeholder Regex & Key Sanitization): Regex \{\{(\w+)\}\}; safe key transliterates Polish [ąćęłńóśźż], strips [^a-z0-9_] to _; custom fields prefix field_; priced steps emit {varKey}_price (variable_extractor_service.dart:377,398, dealflow_blanks_service.dart:267,319-344).
  • BR-DOCS-18 (Template Auto-Numbering): Fallback OF/yyyy/MM/<ms>; validity +14d (dd.MM.yyyy) (variable_extractor_service.dart:273-278).
  • BR-DOCS-19 (Canvas Editor Bounds): 794×1123 px, 20px snap, zoom 0.1–4.0, images png/jpg/jpeg/webp, table 1–20 rows / 1–8 cols, watermark opacity 0.05–1.0, soft delete (create_template_screen.dart:325-326,565,813,839,3110-3113,3508-3527).
  • BR-DOCS-20 (Document Visibility): Author sees own DRAFT & PUBLISHED; non-authors never see DRAFT; is_global visible to all company members; private visible only to document_access.user_id; pinned first (document_service.dart:22-38).
  • BR-DOCS-21 (Autosave & Versioning): Autosaves every 10s when dirty & titled (off in templateMode); document_versions written ONLY on publish: true (document_editor_screen.dart:2741-2747,3060,3087-3093).
  • BR-DOCS-22 (Storage ASCII Sanitization): _storageSafe transliterates Polish diacritics and replaces [^a-zA-Z0-9._-] with _ (document_editor_screen.dart:2436-2449).
  • BR-DOCS-23 (DOCX Upload Path & MIME): .docx only → documents/{companyId}/originals/{ts}_{safeName} (document_editor_screen.dart:3346-3347,3724-3732).
  • BR-DOCS-24 (DOCX XML Parser): Parses word/document.xml w:p/w:tbl, heading regex [Hh]eading\s*1|^1$, numeric cell auto-center ^[\d\s\.,%]+$, flags preserved headers/footers/watermarks (document_editor_screen.dart:381,789,1206,3431-3506).
  • BR-DOCS-25 (Reader HTML Auto-Detection): Content starting with <!DOCTYPE, <html, or <!doctype switches to HTML mode (document_reader_screen.dart:194-199).
  • BR-DOCS-26 (Knowledge Base Bridge): Maps 'uchwały'→'resolution', 'regulaminy'→'regulation', 'formularze'→'form', else 'general'; uploads PDF + SHA-256 to governance_documents (upsert: false) (document_editor_screen.dart:3131-3199).
  • BR-DOCS-27 (Read Receipt Idempotency): Upserts document_read_receipts on onConflict: 'document_id, user_id' (document_service.dart:95-99).
  • BR-DOCS-28 (Edge Function Strict Wrapper): invokeEdgeFunction requires success == true (edge_functions.dart:18-37).
  • BR-DOCS-29 (docx-to-html Contract): Missing file → HTTP 400; success → 200 {html, messages}; error → 500; maps EN & PL Heading 1–3 (docx-to-html/index.ts:9-51,111-122).
  • BR-DOCS-30 (YouTube Embed Extraction): Extracts 11-char ID for https://img.youtube.com/vi/{ytId}/hqdefault.jpg (document_reader_screen.dart:83-86).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> draft
    draft --> pending: generate-offer / send-signature-request
    pending --> viewed: Client opens tracking link (offers)
    pending --> accepted: Client accepts / all signatories sign
    viewed --> accepted: Client accepts (offers)
    pending --> declined: Client / signatory declines
    viewed --> declined: Client declines (offers)
    pending --> expired: expires_at < now (offers)
    viewed --> expired: expires_at < now (offers)
    pending --> draft: createOfferVersion() forks NEW row (offers)
  • agreement_signatories.status: pending → signed | declined.
  • company_documents.status: DRAFT (author-only) → PUBLISHED (visible per is_global/document_access, snapshots document_versions). (Bug: KB bridge writes lowercase 'draft'.)

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

  • Tables: offers, offer_items, offer_notes, offer_views, agreements, agreement_signatories, templates, dealflows, dealflow_entries, company_settings, email_templates, activity_log, webhook_deliveries, company_documents, document_access, document_attachments, document_read_receipts, document_versions, company_templates, clients, user_profiles, company_members.
  • RPCs: delete_agreement(p_agreement_id); unused increment_offer_view(offer_id).
  • Storage Buckets: offer_images (public banners/canvas images), documents (fonts/Roboto-*.ttf, offers/{id}.pdf, agreements/{id}[_final].pdf, {companyId}/images/..., {companyId}/originals/...), governance_documents (KB bridged PDFs).
  • In-Repo Edge Functions: generate-offer, generate-agreement (SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, RESEND_API_KEY, FROM_EMAIL), docx-to-html (no env vars).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
AgreementsListScreen / CreateAgreementScreen -> External send-signature-request (absent from repo!)HTTPS / User JWT{agreementId, mode} -> {success: true, notified}
DealflowBlanksService -> Hostinger Dealflow FrontendHTTPS / Public (8s timeout)GET {dealflowFrontendUrl}/data/{dealflowId}.json
GeminiPlaceholderService / GeminiTemplateService / CreateTemplateScreen -> Google Gemini APIHTTPS / CLIENT-SIDE GEMINI_API_KEYPOST .../v1beta/models/gemini-3.6-flash:generateContent?key=...
DocxViewerScreen -> Microsoft Office OnlineHTTPS Public Iframe/WebViewhttps://view.officeapps.live.com/op/embed.aspx?src={encodedPublicUrl}
OffersListScreen -> External Public Offer AppHTTPS Public Linkhttps://app.planovi.app/offer/{tracking_token}
generate-offer / generate-agreement -> Resend APIHTTPS / RESEND_API_KEYPOST https://api.resend.com/emails

7. Why It Works This Way

  • OCC (concurrency_version) prevents silent overwrites across concurrent editors; immutable offer snapshots + version forking satisfy a DB trigger blocking mutation of sent offers (create_offer_screen.dart:105,806,899).
  • DocxViewerScreen opens as a Dialog rather than inside SidePanelOverlay to avoid Flutter Web HTML iframe platform-view navigation crashes (docx_viewer_screen.dart:33-34).
  • [TEAM_WHY_NEEDED: Why do generate-offer and generate-agreement render hardcoded Planovi pdf-lib layouts instead of the HTML/Canvas templates stored in public.templates?]
  • [TEAM_WHY_NEEDED: Why is docx-to-html deployed in supabase/functions/ when it has zero callers (editor parses DOCX locally and viewer uses Microsoft Office Online)?]
  • [TEAM_WHY_NEEDED: Where is send-signature-request source code hosted, and what external e-sign webhook triggers dual_dispatch: true?]
  • [TEAM_WHY_NEEDED: Why does _bridgeToKnowledgeBase insert a duplicate row with lowercase status='draft' into company_documents (the same table displayed by DocumentsListScreen)?]

8. Debugging, Logs & Common Failure Modes

  • CRITICAL SECURITY — Client-side GEMINI_API_KEY leak + broken model: gemini_placeholder_service.dart:16-20 ships GEMINI_API_KEY in the client bundle AND hardcodes invalid model 'gemini-3.6-flash' (HTTP 404).
  • CRITICAL SECURITY — Zero auth on Service-Role Edge Functions: generate-offer, generate-agreement, and docx-to-html are absent from supabase/config.toml and perform zero JWT or tenant membership checks (generate-offer/generate-agreement use service_role, accept arbitrary IDs & email overrides, send Resend emails, and return signed PDFs).
  • CRITICAL SECURITY — Confidential DOCX exposed to public URL & Microsoft Cloud: document_editor_screen.dart:3724-3735 passes a public storage URL of uploaded .docx files to view.officeapps.live.com.
  • 0% VAT & discounts broken in generate-offer: parseFloat(item.vat_rate) || 23 (generate-offer/index.ts:283) converts 0% VAT to 23%, and lines 280-287/565-568 ignore discount_percent/discount_amount completely.
  • Locale ordering bug: .in('locale', [locale, 'pl-PL']).order('locale', {ascending: false}).limit(1) (generate-offer/index.ts:141-143, generate-agreement/index.ts:153-155) ensures 'pl-PL' always beats 'en-GB' and 'de-DE'.
  • Hardcoded dummy provider details & misrouted webhook URL: Both PDF functions hardcode 'ul. Przykladowa 1, 00-001 Warszawa', 'NIP: 000-000-00-00', 'hello@planovi.pl', and write company_settings.website as webhook_deliveries.target_url!
  • Double-save bug in CreateAgreementScreen: Never caches created ID or increments _currentVersion in state — 2nd save duplicates (create) or throws false OCC conflict (edit).
  • Quill table corruption + missing reader builder + KB draft leak: InteractiveTableWidget._scheduleSync() double-wraps 'custom_table'; DocumentReaderScreen lacks _TableEmbedBuilder; _bridgeToKnowledgeBase writes lowercase 'draft' which leaks into DocumentsListScreen’s Published tab; _cleanupOrphanedImages breaks historical document_versions.
  • Gallery bakes sample data: create_template_screen.dart:4772 loads selected.generateHtml(defaultPreviewVars), baking 'Jan Kowalski' into the template instead of {{placeholders}}.
  • 7-day signed URL expiry: Stored offers.pdf_url / agreements.pdf_url expire after 7 days (604800s).
  • Log grep: [generate-offer], [generate-agreement], DealflowBlanksService, GeminiPlaceholderService, GeminiTemplateService.