Skip to content

6. Clients CRM, Products & Sets

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-CRM • Documented Rules: 18 • Open [TEAM_WHY_NEEDED] Questions: 2

1. Business Purpose & Actors

Multi-tenant B2C/B2B CRM scoped by company_id, supporting natural persons (Osoba Fizyczna) and legal entities (Osoba Prawna with NIP), dynamic tenant-defined JSONB custom fields, Notion-style Quill rich-text client notes with inline attachments and source attribution (Dealflow, Jarvis Voice), categorized file vaults (Multimedia & Documents), client-level Offers & Agreements history, and bulk CSV import/export with 3-layer deduplication. Also contains unused model definitions for a future/external Product/Category/Set catalog (products, categories, sets, set_contents).

  • Actors:
    • Tenant CRM User / Sales Rep: Gated by PermissionProvider.hasAccess('clients', 'CREATE'|'UPDATE'|'DELETE'), plus offers:CREATE and agreements:CREATE on ClientProfileDetailScreen.
    • Cross-Module Producers: Jarvis Voice writes plain-text client_notes and client_attachments (created_by == 'Jarvis Voice'); Dealflow creates 'Lead' clients and migrates dealflow_notes wrapped as {"source":"dealflow","ops":[...]} + client_attachments.

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

  • Clients List & Filtering (clients_list_screen.dart): Watches CompanyProvider.currentCompany?.id; on tenant switch, wipes _clients/_filtered/_selectedClient and reloads via ClientService.getClients(companyId). Client-side search across displayName, email, phone, companyName, taxId + status dropdown (Wszystkie, Aktywny, Nieaktywny, Lead).
  • Client Create / Edit Side Panel (client_form.dart): Loads custom_field_definitions (module_name = 'clients', ordered by order_index). Toggles 'natural' (requires firstName + lastName, nulls company/NIP) vs 'legal' (requires companyName, optional unvalidated NIP, nulls first/last name). No GUS/NIP API lookup exists. Runs _checkForDuplicates against company clients before createClient/updateClient; duplicate returns field-specific error and aborts save.
  • Client Delete (clients_list_screen.dart:356-398): Confirmation dialog → HARD SQL DELETE via ClientService.deleteClient(id, companyId). (Diverges from orphaned ClientRepository.delete, which soft-deletes.)
  • CSV Export & Import (clients_list_screen.dart:136-315, client_service.dart:175-412):
    • Export writes currently _filtered rows (no custom_fields) with UTF-8 BOM (0xEF, 0xBB, 0xBF) for Excel Polish diacritic support across 9 fixed columns.
    • Import decodes UTF-8 RFC-4180 CSV, skips row 0, runs 3-Layer Duplicate Detection against existing company clients. Any duplicate throws DuplicateClientsException pausing UI for 3 choices: Cancel / Skip Duplicates / Update Existing. Bulk insert degrades to row-by-row insert on DB error, silently skipping failing rows.
  • Client Profile Detail (client_profile_screen.dart): Subscribes to Realtime channel public:client_profile_${id} on client_attachments, client_notes, offers (NOT agreements). 5 tabs:
    1. Notatki: flutter_quill editor + inline file uploads to company-media → client_attachments(note_id). Parses JSON content for Dealflow badge, Quill Delta, or plain-text Jarvis Voice badge. Deleting a note executes storage-first deletion (StorageService remove + .list() verification) → client_attachments delete → client_notes delete; storage failure aborts DB deletes.
    2. Oferty i Umowy: CTAs to CreateOfferScreen(preselectedClientId) and CreateAgreementScreen (does not pass client ID). Lists client offers (queried by client_id) and agreements (BUG: queries last 50 company agreements and filters in-memory by client_email!). Cards are read-only (no tap handler).
    3. Zadania: Construction placeholder ("Work in progress").
    4. Multimedia & Dokumenty: Upload dropzones + image InteractiveViewer / VideoPlayerDialog / download links. No UI delete button for individual attachments despite ClientService.deleteAttachment existing.
    • Right sidebar shows disk usage breakdown (_othersSize hardcoded 0) and a placeholder Quick Actions card.

3. Hard Business Rules (BR-CRM-01..18)

  • BR-CRM-01 (Client Type Exclusivity): 'natural' requires first_name + last_name and forces company_name = null, tax_id = null; 'legal' requires company_name and forces first_name = null, last_name = null (client_form.dart:212-215,341-368, client_model.dart:10,36).
  • BR-CRM-02 (Display Name & Initials): Legal uses companyName (2 uppercase chars); natural uses '$firstName $lastName'.trim() (fallback 'Nieznany Klient') (client_model.dart:50-68).
  • BR-CRM-03 (Allowed Client Statuses): 'Aktywny' (default, #34D399), 'Nieaktywny' (grey), 'Lead' (orange) (client_model.dart:34, client_form.dart:39-40).
  • BR-CRM-04 (Manual Form Duplicate Blocking): Blocks save within same company_id (excluding self on edit) on exact match of email, phone, tax_id (legal), company_name (legal), or (first_name AND last_name) (natural), checking errors in that exact priority order (client_form.dart:106-175).
  • BR-CRM-05 (Dynamic Custom Fields): Stored as flat JSONB in clients.custom_fields. is_required is enforced only on text inputs (enum uses DropdownButton with no validator, ignoring is_required) (client_form.dart:72-92,505-571).
  • BR-CRM-06 (CSV Export Format): UTF-8 BOM + 9 fixed columns (Typ Klienta,Imię,Nazwisko,Nazwa Firmy,NIP,Email,Telefon,Adres,Status), mapping legal ↔ 'Osoba Prawna' and natural ↔ 'Osoba Fizyczna' (clients_list_screen.dart:273, client_service.dart:184-207).
  • BR-CRM-07 (CSV 3-Layer Deduplication): Case-insensitive trimmed matching (null == ''): Layer 1 (Name + NIP + Email + Phone + Address all match) → Layer 2 (non-empty NIP matches) → Layer 3 (any 2 non-empty fields among Email/Phone/Address match) (client_service.dart:236-347).
  • BR-CRM-08 (CSV Bulk Insert Degradation): On batch insert error, retries row-by-row and silently logs/skips failed rows (client_service.dart:351-363,383-396).
  • BR-CRM-09 (Hard vs Soft Delete Divergence): Active ClientService.deleteClient executes hard DELETE; unused ClientRepository.delete executes soft delete (deleted_at = now(), is_active = false) (client_service.dart:59-61 vs client_repository.dart:50-55).
  • BR-CRM-10 (Storage-First Note Deletion): deleteNoteWithAttachments deletes and verifies Storage blobs BEFORE deleting client_attachments and client_notes; storage failure throws 'Nie udało się usunąć X z Y plików z serwera.' and aborts DB deletion (client_service.dart:95-118, storage_service.dart:175-201).
  • BR-CRM-11 (Storage Path & ASCII Key Sanitization): Uploads to company-media/{companyId}/clients/{clientId}/{multimedia|docs|others}/{timestampMs}_{safeKey}; Polish diacritics transliterated to ASCII and non-[a-zA-Z0-9._-] replaced with _ (storage_service.dart:10,72-85,122-131,208-219).
  • BR-CRM-12 (Empty Note Guard): Note submission requires non-empty Quill text OR ≥1 pending attachment (client_profile_screen.dart:286-290).
  • BR-CRM-13 (Note Origin Attribution & Loss on Edit): client_notes.content parses as: (a) JSON Map with source == 'dealflow' → Dealflow badge; (b) JSON List → normal Quill note; (c) invalid JSON → Jarvis Voice badge. Editing a Dealflow/Jarvis note rewrites it as plain Quill Delta List, stripping attribution (client_profile_screen.dart:294-301,1388-1403,1519-1532).
  • BR-CRM-14 (Attachment MIME Routing): Multimedia tab shows image/* and video/*; Documents tab shows all other MIME types (client_model.dart:250, client_profile_screen.dart:188-193,267-274).
  • BR-CRM-15 (RBAC Gatekeeping): All CRM mutations gated by clients:CREATE|UPDATE|DELETE; profile offer/agreement buttons gated by offers:CREATE and agreements:CREATE (clients_list_screen.dart:419-421, client_profile_screen.dart:514-515,835-836).
  • BR-CRM-16 (Product VAT Snapshot Rule — Model Contract): ProductModel (product.dart:2-3) specifies tax_rate_percent is snapshotted into offers.locked_data at offer creation and never read from public.products at render time.
  • BR-CRM-17 (Catalog Soft-Delete Schema): CategoryModel, ProductModel, SetModel carry deleted_at (and is_active default true); SetContentModel links sets to products with qty (double) and sort_order. All 4 models currently have 0 callers in lib/.
  • BR-CRM-18 (Profile Offer/Agreement Status Badges): Offers display 6 statuses (draft, pending, viewed, accepted, declined, expired); Agreements display 4 (draft, pending, accepted, declined) (client_profile_screen.dart:1086-1166).

4. State Machines & Data Lifecycle

  • Client Status: Unconstrained dropdown transitions 'Lead' ↔ 'Aktywny' ↔ 'Nieaktywny' (Dealflow auto-creates 'Lead'; manual form defaults to 'Aktywny').
  • Record Lifecycle: Created → Updated (custom_fields JSONB) → Hard Deleted (ClientService.deleteClient).
  • Note/File Lifecycle: Created → Storage upload (company-media) → client_attachments insert → Realtime sync → Edited → Deleted (Storage verified-delete → DB attachments → DB note).

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

  • Tables: clients, client_notes (joined user_profiles, client_attachments), client_attachments, custom_field_definitions, offers (read), agreements (read). Model-only (0 queries): categories, products, sets, set_contents.
  • Storage: Bucket company-media ({companyId}/clients/{clientId}/{multimedia|docs|others}/{ts}_{safeKey}).
  • Realtime: public:client_profile_${clientId} (client_attachments, client_notes, offers).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
jarvis Edge Function / JarvisDocumentService -> client_notes & client_attachmentsSupabase PostgREST (service_role / User JWT)Writes raw plain-text notes and attachments tagged created_by: 'Jarvis Voice'
Module 7 (Dealflow) -> clients, client_notes, client_attachmentsSupabase PostgREST (User JWT)Creates 'Lead' clients, writes {"source":"dealflow","ops":[...]} notes, links URLs from dealflow_attachments bucket

7. Why It Works This Way

  • UTF-8 BOM (0xEF, 0xBB, 0xBF) guarantees Excel detects Polish characters in CSV exports (clients_list_screen.dart:273).
  • StorageService.safeKey transliterates diacritics because Supabase Storage rejects non-ASCII keys with 400 InvalidKey (storage_service.dart:205-207).
  • Storage-first deletion with .list() verification works around Supabase Storage .remove() silently returning [] when RLS blocks deletion (storage_service.dart:171-201).
  • [TEAM_WHY_NEEDED: Why does ClientProfileDetailScreen match agreements in-memory by client_email (capped at last 50 company agreements) instead of querying client_id, and why is ClientService.deleteAttachment not exposed in Multimedia/Documents UI?]
  • [TEAM_WHY_NEEDED: Why does ClientService.deleteClient hard-delete while unused ClientRepository.delete soft-deletes (deleted_at + is_active = false)?]

8. Debugging, Logs & Common Failure Modes

  • PostgREST .or() syntax error permanently blocks client save: Unescaped commas/parentheses/dots in companyName (e.g., "Sp. z o.o., S.K.") break ClientForm._checkForDuplicates .or(orQuery), returning lblErrorVerifyingClientData (client_form.dart:118-136).
  • Empty-email agreement leak: If _client.email == null, clientEmail becomes '', matching every company agreement with an empty email (client_profile_screen.dart:249-253).
  • Orphaned Dealflow files on note delete: StorageService.objectPathFromUrl only recognizes company-media URLs, so deleting a note containing files synced from dealflow_attachments leaves blobs behind in storage.
  • QuillController memory leak: _buildNoteBlock (client_profile_screen.dart:1405) allocates a new QuillController inside build() without ever disposing it.
  • Dead duplicate layer: ClientProvider (not registered in main.dart) + ClientRepository + products/sets models have 0 active callers.
  • Log grep: 📡 [REALTIME], ⚠️ Initial batch insert failed, Error checking duplicates, Error loading custom fields.