Enterprise Grade · Lead Flow Management

LeadFlow PM
System Design Document

Three-portal platform for managing channel partner onboarding, lead flow, commission tracking, and platform fee settlement — built for scale.

3 PortalsLead PipelineCommission Engine Platform Fee SettlementReal-time NotificationsFile Management
01 — Platform Overview

Three portals, one unified backend

Each portal serves a distinct role in the lead and commission lifecycle. All portals share a single API and database — access is enforced by role-based guards.

Channel Partner
Email signup + approval flow
Dashboard overview
Customer view — categories (full page)
Originated + assigned leads
List view + kanban view
Commission analysis
Settlement payments (card/bank)
Company profile + bank details
Notifications + user avatar
Admin
Dashboard + announcements
Channel partner management
Category management
All leads + allocation
Platform fee config (global + per lead)
Platform fee amounts per lead
Settle commission to CPs (+ slip)
Settle platform fee to super admin (+ slip)
Notifications + user avatar
Super Admin (You)
Platform fee income overview
Settled vs outstanding amounts
Settlement history + receipts
All leads — read-only
Delete leads (exclusive privilege)
All CP profiles — read-only
Full commission reports
Platform analytics + export
Notifications + user avatar
Money flow rule: Admin collects the full client payment externally → settles net commission to CP (commission − platform fee) → separately settles platform fee to Super Admin (you). Super Admin sees all platform fee income, settled amounts, outstanding balances, and attached receipts in real time.
02 — Technology

Recommended tech stack

Chosen for enterprise reliability, TypeScript-first type safety across every layer, and developer velocity.

Frontend
Next.js 14TypeScriptTailwindCSSshadcn/uiTanStack QueryZustand
App Router with SSR. One shared component library across all 3 portals routed via subdomains: app. / admin. / super.
Backend API
NestJSTypeScriptPrisma ORMJWT + RefreshPassport.js
Enterprise-grade modular architecture. Role guards, interceptors, and DI built in. REST API with auto-generated OpenAPI docs.
Database & Cache
PostgreSQL 16RedisBullMQ
PostgreSQL for all relational data. Redis for session caching. BullMQ for async email and notification job queues.
File Storage
AWS S3Presigned URLsCloudFront CDN
All receipts, evidence files, category images stored in S3. Direct client-to-S3 uploads via presigned URLs reduce server load.
Payments & Comms
StripeResendSocket.io
Stripe for card payments. Resend for transactional emails (approval, assignment, settlement). Socket.io for real-time in-app notifications.
Infrastructure
DockerAWS ECSGitHub ActionsSentry
Containerised deployment on ECS Fargate. CI/CD via GitHub Actions. Sentry for error tracking across all 3 portals and the API.
app.leadflowpm.com  →  Channel Partner Portal
admin.leadflowpm.com  →  Admin Portal
super.leadflowpm.com  →  Super Admin Portal
api.leadflowpm.com  →  NestJS API (shared by all portals)
03 — Channel Partner Portal

Channel Partner portal

Signup & onboarding flow

1
Self-registration

CP signs up with email + password. Account created with status pending. Portal shows "Approval Pending" screen — no further access until approved.

2
Admin reviews in pending list

Admin portal shows the signup in the Pending Approval tab. Admin can approve or reject with an optional note.

3
Approval email triggered

On approval, system sends a branded welcome email with a login link. CP status changes to active. Portal unlocks full access.

4
Complete company profile

CP fills in company name, logo, bank details, and submits category-specific content for admin to review and publish in the customer view.

Sidebar navigation

SectionDescriptionSpecial behaviour
DashboardKPI cards: active leads, total commission earned, pending settlements, platform fees deducted
CategoriesFull-page customer-facing showcase of all categories with descriptions and images — used to pitch to prospects and submit leadsSidebar hides on enter; hamburger to reopen
LeadsTwo sub-sections: Originated Leads and Assigned Leads. Two views: List and Kanban
CommissionsFull commission analysis, settlement history, payment initiation, received transactions
Company ProfileCompany info, logo, bank account details, category content submission form

Lead section — two sub-sections

Originated Leads
Leads this CP submitted via the customer view. Shows lead title, category, submission date, and allocation status (Pending or Allocated). Read-only — admin allocates originated leads to whichever CP they choose.
Assigned Leads
List view: update status, upload evidence photos/PDFs, add notes. Kanban view: drag cards across pipeline stages. CP can update lead value, commission amount — platform fee and net commission shown instantly. Evidence upload available in list view.

Kanban pipeline stages

New
Sample lead
Just assigned
Contacted
ABC Corp
2 days ago
Qualified
XYZ Ltd
5 days ago
Proposal
MegaDeal
$12,000
Negotiation
Won ✓
Lost

Commission section

Analysis
Total commissions, platform fees deducted, net receivable. Per-lead breakdown table.
Settlements
Every settled row links to payment detail. Shows date, amount, method, bank slip admin uploaded.
Received
Confirmed received payments. Initiate settlement request: choose card (Stripe) or bank transfer (upload receipt PDF).
Live fee preview: CP enters lead value ($10,000) and commission ($1,000) → platform fee ($100 at 10%) → net to receive ($900) shown instantly. Uses per-lead override if set by admin, otherwise global default.
04 — Admin Portal

Admin portal

Sidebar navigation

SectionKey capabilities
DashboardOverview metrics, recent leads, pending approvals, outstanding commissions, platform fee summary. Announcements panel — create, target CPs, broadcast.
Channel PartnersThree tabs: Approved, Pending Approval, Manually Add. View full company profile including bank details. Approve/reject with email trigger. Send welcome email button for manual adds.
CategoriesCreate, edit, delete categories. Upload and reorder images. Review and approve/reject CP-submitted category content. Publish approved content to customer view.
LeadsAll leads in one view. Allocate any lead to a CP. Set per-lead platform fee override. Full list + kanban view. Update status, upload evidence, add notes. Cannot delete leads — super admin only.
CommissionsSettle net commission to CP — select transaction, upload bank slip PDF, mark settled. Full settlement history per CP. CP bank details shown from their profile for manual transfer reference.
Platform FeesConfigure global fee (% or fixed). View platform fee amount for every lead. Batch or individual settle platform fees to Super Admin. Upload bank slip PDF per settlement. Full settled + outstanding history.
AnnouncementsCompose announcement, choose target (all CPs or specific ones), send. Delivered as in-app notification and optional email via BullMQ queue.

Manual CP creation flow

Auto-generated credentials
Admin enters name + email. System auto-generates a secure temporary password. A Send Welcome Email button dispatches an email with the login credentials. CP logs in → forced to change password on first login (must_change_password: true flag).
CP bank details in profile
When settling commission, admin opens the CP's profile to see their bank name, account number, account holder name, branch, and SWIFT code — shown inline to facilitate manual bank transfer without leaving the platform.

Two settlement types admin performs

Settlement typeFromToEvidenceVisible to
CP Commission SettlementAdminChannel PartnerBank slip PDF/image uploaded by adminCP — received transactions section
Platform Fee SettlementAdminSuper Admin (you)Bank slip PDF/image uploaded by adminSuper Admin — income dashboard + settlement history

Platform fee configuration

Global default
Admin sets one active global rule: percentage (e.g. 10%) or fixed amount (e.g. $50). Applied automatically to every new lead. History of changes kept with timestamps.
Per-lead override
When allocating or editing a specific lead, admin can override the fee type and value for that lead only. Override takes precedence over global default and is clearly labelled "overridden" on the lead detail page.
05 — Super Admin Portal

Super Admin portal (you)

Analytics and oversight portal. Full read access to all data. The only destructive action available is lead deletion. Everything financial is read-only — settlements are initiated by admin and visible here.

You are the platform owner. This portal shows your total platform fee income across all leads, how much admin has settled to you, what is still outstanding, and the full history of settlements with attached bank slip receipts.

Sidebar sections

SectionWhat you seeActions
Income DashboardTotal platform fee generated, total received (settled by admin), total outstanding. Month-by-month chart. Per-lead fee breakdown.Read-only
Platform Fee SettlementsEvery settlement admin has made to you. Date, amount, leads covered, bank slip PDF attached by admin.View/download receipts
Outstanding FeesAll platform fees not yet settled by admin. Grouped by lead with lead value and commission context. Overdue indicators.Read-only
All LeadsComplete lead database across all CPs. Filter by status, date, CP, category. Full detail view.Delete lead (only role)
Channel PartnersAll CP profiles, approval status, commission history, bank details.Read-only
Commission ReportsFull commission flow: gross → platform fee → net CP payment. Filterable by date, CP, lead status.Export CSV/PDF
AnalyticsLead volume over time, win rate, top-performing CPs, category performance, revenue trends.Export charts

Income summary view (example)

Total generated
$4,800
Settled to you
$3,200
+
Outstanding
$1,600
06 — Data Architecture

Core data models

PostgreSQL relational schema. PK primary key   FK foreign key   enum enumerated type   computed derived field.

usersauth
iduuid PK
emailvarchar unique
password_hashvarchar
roleenum(super_admin,admin,channel_partner)
statusenum(pending,active,suspended)
must_change_passwordboolean
avatar_urlvarchar nullable
created_at, updated_attimestamp
channel_partnersprofile
iduuid PK
user_idFK → users
company_namevarchar
company_logo_urlvarchar nullable
statusenum(pending,approved,rejected,suspended)
approved_byFK → users(admin) nullable
approved_attimestamp nullable
bank_namevarchar nullable
bank_account_numbervarchar nullable
bank_account_namevarchar nullable
bank_branchvarchar nullable
bank_swift_codevarchar nullable
categoriescontent
iduuid PK
namevarchar
descriptiontext
imagestext[] (S3 URLs)
is_activeboolean
sort_orderinteger
created_byFK → users(admin)
created_at, updated_attimestamp
cp_category_contentcontent
iduuid PK
cp_idFK → channel_partners
category_idFK → categories
descriptiontext
imagestext[] (S3 URLs)
statusenum(draft,submitted,approved,rejected)
reviewed_byFK → users(admin) nullable
leadscore
iduuid PK
title, descriptionvarchar, text
originated_byFK → channel_partners
allocated_toFK → channel_partners nullable
allocation_statusenum(pending,allocated)
kanban_stageenum(new,contacted,qualified,proposal,negotiation,won,lost)
lead_valuedecimal nullable
commission_amountdecimal nullable
fee_override_typeenum(percentage,fixed) nullable
fee_override_valuedecimal nullable
platform_fee_amountdecimal (computed + stored)
net_commissiondecimal (computed + stored)
created_at, updated_attimestamp
platform_fee_configfees
iduuid PK
fee_typeenum(percentage,fixed)
fee_valuedecimal
is_activeboolean
created_byFK → users(admin)
effective_fromtimestamp
notestext nullable
commission_transactionsfinance
iduuid PK
lead_idFK → leads
cp_idFK → channel_partners
gross_commissiondecimal
platform_feedecimal
net_commissiondecimal
statusenum(pending,due,paid)
bank_slip_urlvarchar nullable (admin uploads)
settled_byFK → users(admin) nullable
settled_attimestamp nullable
platform_fee_settlementsfinance
iduuid PK
amountdecimal
leads_covereduuid[] (lead IDs included)
settled_byFK → users(admin)
bank_slip_urlvarchar (admin uploads PDF/image)
notestext nullable
settled_attimestamp
lead_evidencefiles
iduuid PK
lead_idFK → leads
file_urlvarchar (S3 URL)
file_typeenum(image,pdf,document)
uploaded_byFK → users
descriptionvarchar nullable
created_attimestamp
cp_paymentsfinance
iduuid PK
commission_tx_idFK → commission_transactions
cp_idFK → channel_partners
payment_methodenum(card,bank_transfer)
amountdecimal
statusenum(pending,completed,failed)
receipt_urlvarchar nullable (CP uploads for bank transfer)
stripe_payment_idvarchar nullable
announcementscomms
iduuid PK
titlevarchar
contenttext
target_typeenum(all,specific)
target_cp_idsuuid[] nullable
created_byFK → users(admin)
sent_attimestamp
notificationsrealtime
iduuid PK
user_idFK → users
title, messagevarchar, text
typeenum(lead,commission,approval,announcement,system)
is_readboolean default false
reference_iduuid nullable
reference_typeenum(lead,commission,cp) nullable
created_attimestamp
07 — Commission Engine

Commission & platform fee flow

1
Lead marked Won

CP drags lead to Won on kanban or updates status in list view. System creates a commission_transaction record automatically.

2
CP sets lead value & commission

CP enters the deal size and their commission amount. Platform fee and net commission are calculated instantly using the active fee rule (per-lead override if set, otherwise global default).

3
Admin receives client payment (external)

Client pays admin outside the system via bank transfer or other means. Admin manually records this against the lead if needed.

4
Admin settles net commission → CP

Admin opens Commissions panel, selects the transaction, marks as paid, uploads bank transfer slip PDF. CP receives in-app notification + email. Shows in CP's Received Transactions.

5
Admin settles platform fee → Super Admin

Admin opens Platform Fees panel, selects outstanding fee(s) (can batch multiple leads), transfers to Super Admin's bank account, uploads bank slip PDF. Super Admin income dashboard updates in real time.

Fee calculation logic

// Resolve active fee rule for this lead
fee_rule = lead.fee_override ?? active_global_platform_fee_config

// Calculate platform fee amount
if fee_rule.type === 'percentage':
  platform_fee = commission_amount × (fee_rule.value / 100)
else: // fixed
  platform_fee = fee_rule.value

// Net commission paid to CP
net_commission = commission_amount − platform_fee

Example

Lead value
$10,000
Commission
$1,000
Platform fee 10%
$100
=
CP receives
$900
+
You receive
$100
08 — Lead Pipeline

Lead lifecycle & pipeline stages

StageWho sets itDescriptionNotifies
NewSystem (on allocation)Default starting stage when admin allocates the lead to CPCP → "Lead assigned"
ContactedCP / AdminFirst contact made with the prospect
QualifiedCP / AdminProspect confirmed as a real opportunity
Proposal SentCP / AdminFormal proposal or quote submitted
NegotiationCP / AdminActive discussion on terms and pricing
WonCP / AdminDeal closed. Commission record created automaticallyAdmin → "Lead won"
LostCP / AdminDeal did not proceed. CP can add reason noteAdmin → "Lead lost"
List view
Tabular view with sortable columns: title, category, value, commission, platform fee, net commission, stage, last updated. Inline status dropdown, evidence upload, notes field. Expand row for full evidence gallery.
Kanban view
7-column board. Drag and drop to change stage. Cards show lead title, value, and last update. Clicking a card opens a slide-over panel with full details, evidence files, and activity history.
09 — Access Control

Role & permission matrix

ActionCPAdminSuper Admin
AUTH
Self-register via email
Login (including forced password change)
CHANNEL PARTNERS
Edit own profile + bank details
View all CP profiles + bank details
Approve / reject CPs
Manually add CP with temp password + welcome email
CATEGORIES
View customer-facing categories
Submit category content (description + images)
Create / edit / delete categories
Approve / publish CP category content
LEADS
Submit lead from customer view
View own originated leads
View all leads
Allocate lead to CP
Update pipeline stageassigned only
Update lead value + commissionassigned only
Upload evidence photos / filesassigned only
Set per-lead platform fee override
Delete lead✗ blocked✓ only role
COMMISSIONS & FEES
View own commission analysis
View all commission transactions
Settle commission to CP (upload slip)
Initiate payment request (card / bank transfer)
Configure global platform fee
Settle platform fee to super admin (upload slip)
View platform fee income + settlement historyown actions✓ full
ANNOUNCEMENTS & REPORTS
Create & broadcast announcements
Receive notifications
Export reports (CSV / PDF)limited✓ full
Lead deletion is a super admin exclusive. Enforced at the API route guard level — no admin or CP token can reach the DELETE /leads/:id endpoint. This protects the full financial audit trail.
10 — Notifications

Notification events

All notifications delivered in-app via Socket.io (real-time) and optionally via email through a BullMQ queue. Bell icon in header shows unread count.

CP account approved
To CP: "Your account has been approved. You can now access your portal."
CP
!
New CP awaiting approval
To Admin: "A new channel partner [company name] has signed up and requires approval."
Admin
Lead assigned to you
To CP: "A new lead '[title]' has been assigned to you. Start working on it now."
CP
$
Lead marked as Won
To Admin: "CP [name] marked lead '[title]' as won. Commission record has been created."
Admin
Commission settled to you
To CP: "Admin has settled $900 net commission for lead '[title]'. View your receipt."
CP
$
Platform fee settled to you
To Super Admin: "Admin settled $100 platform fee covering 1 lead. Receipt is attached."
Super Admin
📢
New announcement
To targeted CPs: "[Announcement title] — click to read the full message from admin."
CP
11 — API Design

API route structure

RESTful NestJS API. All routes prefixed /api/v1. JWT bearer token auth. Role guards applied at controller level.

ModuleKey endpointsGuard
authPOST /auth/register POST /auth/login POST /auth/refresh POST /auth/change-passwordPublic / JWT
channel-partnersGET /channel-partners POST /channel-partners/approve/:id POST /channel-partners/manual-add PATCH /channel-partners/:id/bank-detailsAdmin / CP
categoriesGET /categories POST /categories PATCH /categories/:id DELETE /categories/:id POST /categories/:id/content PATCH /categories/:id/content/approveAdmin / JWT
leadsGET /leads POST /leads GET /leads/:id PATCH /leads/:id POST /leads/:id/allocate PATCH /leads/:id/stage POST /leads/:id/evidence DELETE /leads/:idJWT (role-filtered) / SuperAdmin only for DELETE
platform-feesGET /platform-fees/config POST /platform-fees/config GET /platform-fees/summary GET /platform-fees/settlements POST /platform-fees/settleAdmin / Super Admin
commissionsGET /commissions GET /commissions/analysis POST /commissions/:id/settle GET /commissions/:id/receiptAdmin / CP
paymentsPOST /payments/card POST /payments/bank-transfer POST /payments/:id/receipt GET /payments/historyCP
announcementsGET /announcements POST /announcements POST /announcements/:id/sendAdmin / CP
notificationsGET /notifications PATCH /notifications/:id/read PATCH /notifications/read-allJWT
uploadsPOST /uploads/presign → returns S3 presigned URL for direct browser-to-S3 uploadJWT
analyticsGET /analytics/overview GET /analytics/leads GET /analytics/commissions GET /analytics/platform-fees GET /analytics/exportSuper Admin
12 — Build Roadmap

Phased development plan

5 phases, each delivering a working deployable increment. Estimated at 14 weeks for full production launch.

Phase 01Foundation & Auth
Weeks 1–3
Project setup: Next.js 14, NestJS, PostgreSQL, Prisma, Docker Compose, monorepo
Full database schema with all tables, enums, and migrations
Auth module: JWT, refresh tokens, bcrypt, role guards (CP / Admin / Super Admin)
CP self-registration → pending status → admin approval → welcome email
Admin manual CP creation: auto-generated temp password, Send Welcome Email button
Force password change on first login (must_change_password flag)
Three portal scaffolds with shared component library and subdomain routing
User avatar upload via S3 presigned URL
Phase 02Categories, Profiles & Customer View
Weeks 4–5
Admin category CRUD with image upload, reorder, and publish toggle
CP category content submission form (choose category, add description + images)
Admin review, approve, and publish CP category content
CP customer view: full-page category showcase, sidebar hide with hamburger toggle
Lead submission form from customer view (title, category, description)
CP company profile page: business info, bank details form
Admin CP profile viewer with full bank details display
Phase 03Lead Management & Pipeline
Weeks 6–8
Full lead CRUD with allocation workflow: admin allocates originated lead to CP
Originated leads vs assigned leads separation in CP portal
Kanban board with 7 stages and drag-and-drop stage changes
List view with inline status update, evidence file upload, and notes
Lead value + commission input with live platform fee and net commission preview
Global platform fee config (% or fixed) + per-lead admin override
Lead deletion API endpoint restricted to Super Admin role guard only
Evidence gallery viewer (images, PDFs, documents)
Phase 04Commission Engine & Payments
Weeks 9–11
Commission transaction auto-creation when lead is marked Won
CP commission analysis dashboard: gross, fee, net, per-lead table
Admin settle commission to CP: select transaction, upload bank slip PDF, mark paid
CP payment initiation: card (Stripe) or bank transfer (receipt PDF upload)
CP received transactions history view
Admin platform fee settlement to Super Admin: batch or individual, upload bank slip PDF
Super Admin income dashboard: total generated, settled, outstanding
Super Admin settlement history with bank slip receipt viewer
Phase 05Notifications, Announcements & Analytics
Weeks 12–14
Real-time Socket.io notifications for all 7 notification event types
Email notifications via BullMQ + Resend: approval, assignment, settlement events
Admin announcement composer: write, target CPs (all or specific), send
Full KPI dashboards for all 3 portals
Super Admin analytics: lead volume, win rate, top CPs, revenue trends, category performance
Report export (CSV + PDF) for Super Admin
Sentry error tracking, structured logging, GitHub Actions CI/CD pipeline
Load testing, security audit (OWASP), staging to production deployment on AWS ECS
Estimated total: 14 weeks to full production across all 3 portals, complete commission engine, real-time notifications, Stripe payments, and Super Admin analytics. Acceleratable with parallel frontend/backend teams to 10 weeks.