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'), plusoffers:CREATEandagreements:CREATEonClientProfileDetailScreen. - Cross-Module Producers: Jarvis Voice writes plain-text
client_notesandclient_attachments(created_by == 'Jarvis Voice'); Dealflow creates'Lead'clients and migratesdealflow_noteswrapped as{"source":"dealflow","ops":[...]}+client_attachments.
- Tenant CRM User / Sales Rep: Gated by
2. All Features & End-to-End Flows (Happy Path + Error Paths)
- Clients List & Filtering (
clients_list_screen.dart): WatchesCompanyProvider.currentCompany?.id; on tenant switch, wipes_clients/_filtered/_selectedClientand reloads viaClientService.getClients(companyId). Client-side search acrossdisplayName,email,phone,companyName,taxId+ status dropdown (Wszystkie,Aktywny,Nieaktywny,Lead). - Client Create / Edit Side Panel (
client_form.dart): Loadscustom_field_definitions(module_name = 'clients', ordered byorder_index). Toggles'natural'(requiresfirstName+lastName, nulls company/NIP) vs'legal'(requirescompanyName, optional unvalidated NIP, nulls first/last name). No GUS/NIP API lookup exists. Runs_checkForDuplicatesagainst companyclientsbeforecreateClient/updateClient; duplicate returns field-specific error and aborts save. - Client Delete (
clients_list_screen.dart:356-398): Confirmation dialog → HARD SQL DELETE viaClientService.deleteClient(id, companyId). (Diverges from orphanedClientRepository.delete, which soft-deletes.) - CSV Export & Import (
clients_list_screen.dart:136-315,client_service.dart:175-412):- Export writes currently
_filteredrows (nocustom_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
DuplicateClientsExceptionpausing UI for 3 choices: Cancel / Skip Duplicates / Update Existing. Bulk insert degrades to row-by-row insert on DB error, silently skipping failing rows.
- Export writes currently
- Client Profile Detail (
client_profile_screen.dart): Subscribes to Realtime channelpublic:client_profile_${id}onclient_attachments,client_notes,offers(NOTagreements). 5 tabs:Notatki:flutter_quilleditor + inline file uploads tocompany-media→client_attachments(note_id). Parses JSON content forDealflowbadge, Quill Delta, or plain-textJarvis Voicebadge. Deleting a note executes storage-first deletion (StorageServiceremove +.list()verification) →client_attachmentsdelete →client_notesdelete; storage failure aborts DB deletes.Oferty i Umowy: CTAs toCreateOfferScreen(preselectedClientId)andCreateAgreementScreen(does not pass client ID). Lists client offers (queried byclient_id) and agreements (BUG: queries last 50 company agreements and filters in-memory byclient_email!). Cards are read-only (no tap handler).Zadania: Construction placeholder ("Work in progress").Multimedia&Dokumenty: Upload dropzones + imageInteractiveViewer/VideoPlayerDialog/ download links. No UI delete button for individual attachments despiteClientService.deleteAttachmentexisting.
- Right sidebar shows disk usage breakdown (
_othersSizehardcoded0) and a placeholder Quick Actions card.
3. Hard Business Rules (BR-CRM-01..18)
- BR-CRM-01 (Client Type Exclusivity):
'natural'requiresfirst_name+last_nameand forcescompany_name = null, tax_id = null;'legal'requirescompany_nameand forcesfirst_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 ofemail,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_requiredis enforced only on text inputs (enumusesDropdownButtonwith no validator, ignoringis_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), mappinglegal ↔ 'Osoba Prawna'andnatural ↔ '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.deleteClientexecutes hardDELETE; unusedClientRepository.deleteexecutes soft delete (deleted_at = now(), is_active = false) (client_service.dart:59-61vsclient_repository.dart:50-55). - BR-CRM-10 (Storage-First Note Deletion):
deleteNoteWithAttachmentsdeletes and verifies Storage blobs BEFORE deletingclient_attachmentsandclient_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.contentparses as: (a) JSON Map withsource == 'dealflow'→ Dealflow badge; (b) JSON List → normal Quill note; (c) invalid JSON →Jarvis Voicebadge. 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/*andvideo/*; 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 byoffers:CREATEandagreements: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) specifiestax_rate_percentis snapshotted intooffers.locked_dataat offer creation and never read frompublic.productsat render time. - BR-CRM-17 (Catalog Soft-Delete Schema):
CategoryModel,ProductModel,SetModelcarrydeleted_at(andis_activedefaulttrue);SetContentModellinks sets to products withqty(double) andsort_order. All 4 models currently have 0 callers inlib/. - 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_fieldsJSONB) → Hard Deleted (ClientService.deleteClient). - Note/File Lifecycle: Created → Storage upload (
company-media) →client_attachmentsinsert → Realtime sync → Edited → Deleted (Storage verified-delete → DB attachments → DB note).
5. Technical Contract (Inputs → Processing → Side Effects)
- Tables:
clients,client_notes(joineduser_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 -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
jarvis Edge Function / JarvisDocumentService -> client_notes & client_attachments | Supabase PostgREST (service_role / User JWT) | Writes raw plain-text notes and attachments tagged created_by: 'Jarvis Voice' |
Module 7 (Dealflow) -> clients, client_notes, client_attachments | Supabase 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.safeKeytransliterates diacritics because Supabase Storage rejects non-ASCII keys with400 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 incompanyName(e.g.,"Sp. z o.o., S.K.") breakClientForm._checkForDuplicates.or(orQuery), returninglblErrorVerifyingClientData(client_form.dart:118-136). - Empty-email agreement leak: If
_client.email == null,clientEmailbecomes'', matching every company agreement with an empty email (client_profile_screen.dart:249-253). - Orphaned Dealflow files on note delete:
StorageService.objectPathFromUrlonly recognizescompany-mediaURLs, so deleting a note containing files synced fromdealflow_attachmentsleaves blobs behind in storage. - QuillController memory leak:
_buildNoteBlock(client_profile_screen.dart:1405) allocates a newQuillControllerinsidebuild()without ever disposing it. - Dead duplicate layer:
ClientProvider(not registered inmain.dart) +ClientRepository+products/setsmodels have 0 active callers. - Log grep:
📡 [REALTIME],⚠️ Initial batch insert failed,Error checking duplicates,Error loading custom fields.