7. Dealflow Sales Pipeline & Embedded Offer/Agreement Workbench
Repository:
Flutter App (planovi-flutter-app)• Rule Prefix:BR-DEAL• Documented Rules: 24 • Open[TEAM_WHY_NEEDED]Questions: 2
1. Business Purpose & Actors
End-to-end lead capture and sales pipeline platform: (1) builds public interactive lead forms and real-time price calculators (“Dealflows”) published to an external Hostinger PHP server for direct links or <iframe> embeds; (2) manages incoming leads (dealflow_entries) on a 7-stage Realtime Kanban board with notes, attachments, CRM conversion/sync, and automated stage transitions; (3) generates, versions (with OCC), previews, and sends Offers and e-Signature Agreements directly from lead cards.
- Actors:
- Dealflow Form Admin/Sales:
ListOfDealflowsScreenchecksdealflow:CREATE|UPDATE|DELETE; RBAC MISMATCH:CreateDealflowScreencheckssales:CREATE|UPDATEinstead! - Sales Rep (Kanban & Details Panel): Gated by
dealflow_entries:UPDATE(move stage, edit lead/notes/files),dealflow_entries:DELETE, andoffers:CREATE(Edit Offer / new version inDealPdfButtons). - External Prospect: Submits public PHP form at
{DEALFLOW_FRONTEND_URL}/offer.php?id={dealflowId}, writing rows intodealflow_entries.
- Dealflow Form Admin/Sales:
2. All Features & End-to-End Flows (Happy Path + Error Paths)
- Dealflow List & Embed Sharing (
list_of_dealflows_screen.dart): Queriesdealflowsbycompany_id(sorts in-memory bycreated_at DESCto avoid Postgres42703). Expanding a card copies Direct URL ({dealflowFrontendUrl}/offer.php?id=$trueId) or<iframe>snippet. Delete removes Supabase row, then best-effort callsDELETE {DEALFLOW_BASE_URL}/save_dealflow.php?id={hostingerId}AND a hardcoded dev URLPOST https://dev-dealflow.planovi.app/backend/delete_json.php(no auth!). - Dealflow Form & Calculator Builder (
create_dealflow_screen.dart): Configures metadata, branding colors, logo upload (<= 2.0 MB,1024×1024, bucketlogos), mode (questionsOnlyvsboth), standard & 10-type custom contact fields, reorderable question steps (6 UI types; 4 architecture defaults on create), pricing calculator (PLN/EUR/USD/GBP), andis_default.- Save Order (PHP-First): Reads
companyIdfromTenantSessionProvider.activeWorkspaceId(differs from list screen’sCompanyProvider!), preserves existing public ID on edit (or'deal_<ts>'), posts to PHPsave_dealflow.phpFIRST (status == 'success'required), then saves to Supabasedealflows. Aborts DB write if PHP fails.
- Save Order (PHP-First): Reads
- Kanban Board (
dealflow_entries_screen.dart): 7 stages (new_lead,in_talks,bid_sent,agreement_sent,approved,rejected,archived). Desktop/Tablet (>=600px) renderDragTargetcolumns; Mobile renders 7 tabs. Realtimepublic:dealflow_entries_$companyIduses 600ms debounce. Supports inline edit, delete, CRM client creation/sync (handles Postgres23505conflict by linking existing client, deduplicates notes/attachments), stage-specific action buttons (OfferActionButton,AgreementActionButton, disabledProvisionActionButton), andDealPdfButtons. - Lead Details Panel (
dealflow_entry_details_panel.dart): Displays client card (withNowa Oferta/Nowa UmowaCTAs when linked),price_breakdown, form answers (maps question IDs — buggy lookup, falls back to strippingq_), anddealflow_notestimeline (system events immutable; user notes upload files todealflow_attachments; edit/delete note/attachment mutates DB only without removing storage blobs). - Stage Side-Effect Automation (
dealflow_stage_service.dart):in_talks→ auto-create/link'Lead'client + migrate text notes (drops attachments!).bid_sent→ ensure client + resolve template → push full-screenCreateOfferScreen.agreement_sent→ find latest active offer → push full-screenCreateAgreementScreen.approved→ mark latestpending/draftagreement (matched byclient_emailonly!) as'accepted', triggering DBauto_create_fulfillment_order.rejected→ mark allpending/viewedoffers forclient_idas'declined'.
- Embedded Offer Workbench (
offer_generator_panel.dart): Loads active offertemplates(htmlorcanvas; blocksempty), pre-fills 1 item fromdeal_valueas NET + 23% VAT (valid_until = +14d), substitutes 50+{{var}}keys (longest-first), insertsoffers(draft) +offer_items, invokesgenerate-offer. Only advances stage tobid_sentaftergenerate-offerreturnssuccess: true; on failure keeps offer asdraftand closes panel to prevent duplicates. - Versioned Offer HTML Editor (
offer_edit_panel.dart): Loads latest offer (concurrency_version,version_number), provides HTML editor + 17 tag chips + Web-only Blob preview (dart:js_interop/package:web), saves ONLY by creating a new immutable version viacreateOfferVersion(..., expectedConcurrencyVersion)(catchesOfferVersionConflict→ reload dialog), then prompts to invokegenerate-offer. - Embedded Agreement Workbench (
agreement_generator_panel.dart): 5-step tracked pipeline: (1) insertagreements(draft, raw template), (2) insertagreement_signatories(1..N,serial/parallel,SES/AES/QES), (3) invokegenerate-agreement, (4) invoke externalsend-signature-request, (5) setagreements.status = 'pending'&dealflow_entries.current_stage = 'agreement_sent'. Failure after Step 1 keeps agreement as'draft', shows failed step in 10s snackbar, and closes panel.
3. Hard Business Rules (BR-DEAL-01..24)
- BR-DEAL-01 (PHP API Auth): All
DealflowApiServicerequests send header'X-Secret-Key': dotenv.env['DEALFLOW_API_SECRET'] ?? ''(dealflow_api_service.dart:11,27-28,60,88,115-116,148,188-189,221). - BR-DEAL-02 (PHP-First Save Atomicity):
save_dealflow.phpmust returnstatus == 'success'before writing Supabasedealflows(create_dealflow_screen.dart:1439-1467). - BR-DEAL-03 (Immutable Public Dealflow ID): Edit preserves existing public ID (
direct_url ?id=→json['id']→ rowid); create generates'deal_<epochMs>'(create_dealflow_screen.dart:1307-1334). - BR-DEAL-04 (Single Default Dealflow): Saving with
is_default = trueclearsis_default = falseon all other company rows indealflows(supabase_service.dart:96-102). - BR-DEAL-05 (Logo Upload Constraints): Max
1024×1024px and client-side cap2.0 MB, uploaded to bucketlogos(create_dealflow_screen.dart:469-497). - BR-DEAL-06 (Dual Pricing Serialization):
DealflowStepModel.toJson()emits both legacy flat keys and nestedpricingobject;CreateDealflowScreen._saveDealflow()emits only nestedpricingwhenhasPricing && _isPricingMode(dealflow_step_model.dart:70-116,create_dealflow_screen.dart:1418-1434). - BR-DEAL-07 (Step Price Calculation):
perUnit = qty * unitPrice;optionPrices = optionPrices[answer] ?? 0;yesNo = answer ? yesPrice : noPrice;percentagereturns0locally (computed externally) (dealflow_step_model.dart:224-244). - BR-DEAL-08 (Pricing Mode & Currency Guard):
text/textareasteps cannot enable pricing; currencies allowed:PLN, EUR, USD, GBP(defaultPLN) (create_dealflow_screen.dart:673-675,718,1867). - BR-DEAL-09 (7 Stages & RBAC): Valid Kanban stages:
new_lead, in_talks, bid_sent, agreement_sent, approved, rejected, archived(DealPdfButtons._stageOrderalso recognizes legacy'quote_sent'). Moving leads requiresdealflow_entries:UPDATE; deleting requiresdealflow_entries:DELETE(dealflow_entries_screen.dart:40-76,203,dealflow_pdf_buttons.dart:26-29). - BR-DEAL-10 (System Audit Notes): Every stage transition writes
'Zmieniono etap na: $stageTitle'(note_type: 'system') todealflow_notes; system notes are immutable in UI (dealflow_entries_screen.dart:225-231,dealflow_entry_details_panel.dart:221-227,1993,2069). - BR-DEAL-11 (Stage Transition Side Effects):
in_talks(ensure client + text notes),bid_sent(openCreateOfferScreen),agreement_sent(openCreateAgreementScreen),approved(mark agreement'accepted'→ DBauto_create_fulfillment_order),rejected(mark pending/viewed offers'declined') (dealflow_stage_service.dart:34-252). - BR-DEAL-12 (Lead-to-CRM Deduplication): Matches
clientsby exactemailorphonewithincompany_id; catches Postgres23505/'duplicate'to link existing client (dealflow_entries_screen.dart:961-995,dealflow_stage_service.dart:85-100). - BR-DEAL-13 (Idempotent CRM Note/File Sync): Deduplicates notes by exact Quill JSON/raw string and attachments by exact
file_pathURL; attachment-only notes create placeholder client note (dealflow_entries_screen.dart:1144-1250). - BR-DEAL-14 (Offer VAT & Validity Math — Divergence):
OfferGeneratorPaneltreatsdeal_valueas NET (+23% VAT,valid_until = +14d), whereas unusedOfferGeneratorServicetreatsdeal_valueas GROSS (net = gross / 1.23,valid_until = +30d) (offer_generator_panel.dart:79-117,456-460vsoffer_generator_service.dart:67,78-83). - BR-DEAL-15 (Empty Template Guard): Templates are
'html'(layout_json.html_code),'canvas'(layout_json.items), or'empty';'empty'blocks generation (offer_generator_panel.dart:52-58,500-507,agreement_generator_panel.dart:91-97,206-214). - BR-DEAL-16 (Longest-Key-First Substitution): Variable keys are sorted by descending length before
replaceAll('{{$key}}', val)(offer_generator_panel.dart:485-494). - BR-DEAL-17 (Immutable Offer Versioning + OCC):
OfferEditPanelnever mutatesoffers.locked_layoutin place; creates new version withexpectedConcurrencyVersionand trapsOfferVersionConflict(offer_edit_panel.dart:190-228). - BR-DEAL-18 (Post-EF Stage Advancement): Stage advances to
bid_sentonly aftergenerate-offerreturnssuccess: true, and toagreement_sentonly after BOTHgenerate-agreementANDsend-signature-requestsucceed (offer_generator_panel.dart:610-642,agreement_generator_panel.dart:301-337). - BR-DEAL-19 (Signatory & e-Signature Validation): Requires ≥1 signatory (
namenon-empty,emailcontains'@'),signing_mode ∈ {serial, parallel},signature_level ∈ {SES, AES, QES}, 1-basedsigning_order(agreement_generator_panel.dart:24-25,71-74,216-224,286-298). - BR-DEAL-20 (Provisioning Kill Switch):
kProvisionEnergyCoopEnabled = falsedisablesProvisionActionButtonbecauseprovision-energy-coopEdge Function does not exist (dealflow_offer_widgets.dart:20,115-129). - BR-DEAL-21 (Preview Precedence): Active
DealPdfButtonsprefers HTML over PDF; unusedViewOfferButton/ViewAgreementButtonprefer PDF over HTML (dealflow_pdf_buttons.dart:40,210-214vsdealflow_offer_widgets.dart:277-293). - BR-DEAL-22 (Lead Attachment Sanitization): Transliterates Polish chars and strips non-
[a-zA-Z0-9.-]to_underdealflow_attachments/{company_id}/{deal_id}/{ts}_{cleanName}(dealflow_entry_details_panel.dart:847-908). - BR-DEAL-23 (Lead Title Prefix Rewrite): Kanban cards rewrite leading
'nowa oferta:'to'Oferta: 'oncecurrent_stage != 'new_lead'(dealflow_entries_screen.dart:1293-1297;dealflow_entry_details_panel.dart:1251-1255computes then ignoresdisplayTitle). - BR-DEAL-24 (Strict Edge Function Contract):
invokeEdgeFunctionrequires HTTP 2xx AND JSON{'success': true}(lib/core/utils/edge_functions.dart:18-37).
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> new_lead: Prospect submits offer.php
new_lead --> in_talks: Drag/Dropdown (creates Lead client)
in_talks --> bid_sent: OfferGeneratorPanel / Drag (opens CreateOfferScreen)
bid_sent --> agreement_sent: AgreementGeneratorPanel / Drag (opens CreateAgreementScreen)
agreement_sent --> approved: Drag/Dropdown (accepts agreement -> fulfillment_orders)
new_lead --> rejected: Drag/Dropdown (declines pending/viewed offers)
in_talks --> rejected
bid_sent --> rejected
agreement_sent --> rejected
new_lead --> archived
in_talks --> archived
bid_sent --> archived
agreement_sent --> archived
approved --> archived
rejected --> archived
- Transition Guard: None enforced in DB/UI — any stage can jump to any stage (
dealflow_entries:UPDATErequired).
5. Technical Contract (Inputs → Processing → Side Effects)
- Tables:
dealflows,dealflow_entries,dealflow_notes,templates,offers,offer_items,agreements,agreement_signatories,clients,client_notes,client_attachments,companies. - Storage Buckets:
logos(builder logos),dealflow_attachments(lead note files),offer_images&offer_pdfs(unusedCanvasPdfService). - Realtime:
public:dealflow_entries_$companyId(dealflow_entries, 600ms debounce).
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
CreateDealflowScreen / DealflowApiService / KonfiguracjeBrandinguScreen -> Hostinger PHP Dealflow Backend | HTTPS / X-Secret-Key (DEALFLOW_API_SECRET) | POST/PUT/DELETE {DEALFLOW_BASE_URL}/save_dealflow.php (toApiJson() wrapper or flat JSON from branding screen); unused get_dealflows.php, submit_response.php, get_responses.php |
ListOfDealflowsScreen -> Hardcoded Dev PHP Delete | HTTPS / NONE | POST https://dev-dealflow.planovi.app/backend/delete_json.php (body: {id}) |
External Prospects -> Hostinger PHP Frontend (offer.php) -> Supabase dealflow_entries | HTTPS Public -> Supabase Insert | {DEALFLOW_FRONTEND_URL}/offer.php?id={publicDealflowId} writes leads + price_breakdown into dealflow_entries |
OfferGeneratorPanel / DealPdfButtons -> supabase/functions/generate-offer | HTTPS / User JWT | Generates PDF + sends offer email |
AgreementGeneratorPanel -> supabase/functions/generate-agreement & External send-signature-request (absent from repo!) | HTTPS / User JWT | Generates PDF; send-signature-request({agreementId, mode}) dispatches e-signature emails |
DealflowStageService -> Postgres Trigger auto_create_fulfillment_order | DB Trigger on agreements.status = 'accepted' | Auto-creates row in fulfillment_orders |
7. Why It Works This Way
- External Hostinger PHP server renders lightweight zero-auth
<iframe>calculators without loading Flutter Web for external leads. dealflowsomits SQL.order('created_at')to prevent Postgres42703across older schema variants (list_of_dealflows_screen.dart:91).- 600ms Realtime debounce prevents thrashing during multi-write stage transitions (
dealflow_entries_screen.dart:134-142). [TEAM_WHY_NEEDED: Why do two parallel Offer/Agreement creation UX flows coexist (embedded OfferGeneratorPanel/AgreementGeneratorPanel on Kanban cards vs full-screen CreateOfferScreen/CreateAgreementScreen triggered by DealflowStageService on drag/dropdown)?][TEAM_WHY_NEEDED: Why does CreateDealflowScreen read companyId from TenantSessionProvider.activeWorkspaceId while ListOfDealflowsScreen, DealflowEntriesScreen, OfferGeneratorPanel, and AgreementGeneratorPanel read CompanyProvider.currentCompany?.id?]
8. Debugging, Logs & Common Failure Modes
- RBAC lockout in
CreateDealflowScreen: List checksdealflow:*while editor checkssales:CREATE|UPDATE(create_dealflow_screen.dart:1537-1539,1767,1812,2135,2343) — users withdealflowpermission only lose the Save button! - Production delete hits hardcoded dev URL:
list_of_dealflows_screen.dart:196posts tohttps://dev-dealflow.planovi.app/backend/delete_json.phpwith no auth. - Native build break in
OfferEditPanel: Unconditionalimport 'dart:js_interop'/package:web/web.dart(offer_edit_panel.dart:9-10) breaks iOS/Android/macOS builds. - Native lead attachment uploads silently skipped:
FilePicker.platform.pickFiles()atdealflow_entry_details_panel.dart:838omitswithData: true→file.bytesisnullon native platforms → line 887 silently skips upload. - Question label mapping always misses:
_fetchQuestionMapping()(dealflow_entry_details_panel.dart:143-162) looks for nestedstep['fields'|'elements'|'questions'], whereasCreateDealflowScreensaves flat{id, question}. - Cross-deal agreement acceptance bug:
DealflowStageService._handleApproved(dealflow_stage_service.dart:214-236) matchesagreementsbyclient_emailignoringdeal_id. - Package picker doesn’t update monthly fee: Selecting
Starter/Standard/ProfessionalinAgreementGeneratorPanel(line 792-793) leaves_monthlyFeeCtrlat'599'. - Dead code & color bug:
CanvasPdfService,OfferGeneratorService,DealflowOfferModel,ViewOfferButton/ViewAgreementButtonhave 0 callers;CanvasPdfServicedivides Flutter 3.27 normalizedColor.r/g/bby255(producing near-black PDFs). - Log grep:
🔥 SZUKAM DEALFLOWÓW,Usuwanie oferty dealflow,Error fetching dealflow entries,Error mapping questions,Note migration error.