# Product Requirements Document (PRD)
# Taskco CRM — Multi-Industry Customer Relationship Platform

> **Audience:** Product, developers, QA
> **Purpose:** What exactly are we building, for whom, and when is it done?
> **Version:** 1.0 — May 2026
> **Scope:** All phases — v1 · v1.5 · v2

---

## 1. Product Summary

Taskco CRM is a configurable, multi-tenant CRM platform that serves five industries from a single codebase. Every screen, label, pipeline stage, and automation is defined by the industry profile selected at setup. The product ships as a SaaS with full data isolation between tenants.

---

## 2. User Roles & Permissions

### Role definitions

| Role | Also called | What they own |
|---|---|---|
| **Admin** | Owner, Director | Full access — all branches, all users, all data, all settings |
| **Branch Manager** | Manager, Team Lead | Their branch only — all leads and deals within that branch |
| **Salesperson** | Counselor, Agent, MR, Sales Executive | Their own assigned leads and deals only |

### Permission matrix

| Action | Admin | Manager | Salesperson |
|---|---|---|---|
| View all leads (all branches) | ✅ | ❌ | ❌ |
| View branch leads | ✅ | ✅ (own branch) | ❌ |
| View own leads | ✅ | ✅ | ✅ |
| Create lead | ✅ | ✅ | ✅ |
| Edit any lead | ✅ | ✅ (branch) | ❌ |
| Edit own lead | ✅ | ✅ | ✅ |
| Delete lead | ✅ | ❌ | ❌ |
| Convert lead | ✅ | ✅ | ✅ (own only) |
| Reassign lead | ✅ | ✅ (branch) | ❌ |
| View all deals | ✅ | ❌ | ❌ |
| View branch deals | ✅ | ✅ (own branch) | ❌ |
| View own deals | ✅ | ✅ | ✅ |
| Move deal stage | ✅ | ✅ | ✅ (own only) |
| Invite users | ✅ | ❌ | ❌ |
| Change product profile | ✅ | ❌ | ❌ |
| Manage branches | ✅ | ❌ | ❌ |

---

## 3. Industry Profiles

Each profile configures: vocabulary (labels), pipeline stages, custom fields, and business flow.

### Profile map

| Profile slug | Industry | Lead called | Deal called | Contact called |
|---|---|---|---|---|
| `crm-default` | General Sales | Lead | Deal | Contact |
| `crm-education` | Study-Abroad Consultancy | Application | Enrollment | Student |
| `crm-realstate` | Real Estate Agency | Enquiry | Property Deal | Client |
| `crm-pharma` | Pharma Sales | Doctor | Order | Contact |
| `crm-garments` | Garments Export | Buyer | Order | Buyer Contact |

### Business flows per profile

| Profile | Step 1 | Step 2 | Step 3 | Step 4 |
|---|---|---|---|---|
| `crm-default` | Lead → Deal (manual convert) | Deal Won → Invoice (v1.5) | — | — |
| `crm-education` | Application → Enrollment (convert) | Enrollment: Offer Accepted → email student | Enrollment Won → Invoice (v1.5) | Invoice Paid → notify admin |
| `crm-realstate` | Enquiry → Property Deal (convert) | Deal: Booking stage → Invoice (v1.5) | Deal Closed → notify manager | — |
| `crm-pharma` | Doctor → Order (convert) | Order Delivered → notify manager | — | — |
| `crm-garments` | Buyer → Order (convert) | Order: Sample stage → create task | Order: Shipment stage → Invoice (v1.5) | — |

---

## 4. Module Features

### 4.1 Lead Module

**Purpose:** Capture and qualify every incoming inquiry before it becomes a deal.

**Core features:**
- Create, view, edit, delete leads
- Assign to a salesperson (auto via workflow or manual)
- Move lead through pipeline stages
- Log activities (calls, emails, meetings, notes) against a lead
- Filter and search leads by stage, status, owner, date, and custom fields
- Bulk status update across multiple leads
- Convert lead to a deal (creates deal + contact in one transaction)
- Soft delete (leads are never permanently deleted in v1)

**Industry-specific fields per profile:**

| Profile | Key custom fields |
|---|---|
| `crm-default` | Source Channel |
| `crm-education` | Preferred Country, Study Level, English Test, GPA, Sponsor Type, Visa Refusal, University Choices |
| `crm-realstate` | Preferred Location, Property Type, Budget Min/Max, Bedrooms, Purchase Purpose, Timeline |
| `crm-pharma` | Territory, Medical Specialty, Hospital, Monthly Prescriptions, Visit Frequency |
| `crm-garments` | Source Country, Product Category, Annual Volume, Payment Terms, Lead Time |

**Lead pipeline stages per profile:**

| Profile | Stages |
|---|---|
| `crm-default` | New → Contacted → Qualified → Proposal → Negotiation → Converted |
| `crm-education` | Enquiry → Assessment → Shortlisting → Application → Offer Received |
| `crm-realstate` | New Enquiry → Site Visit Scheduled → Site Visit Done → Offer Made → Converted |
| `crm-pharma` | Identification → First Visit → Follow Up → Prescription Started → Key Account |
| `crm-garments` | New Buyer → Sample Requested → Sample Approved → Price Negotiation → Order Placed |

---

### 4.2 Deal Module

**Purpose:** Track committed business from conversion through to close. Visualised as a Kanban board.

**Core features:**
- Created automatically on lead conversion (cannot be created standalone in v1)
- Kanban board view — deals grouped by stage, draggable between stages
- List view with filters
- Move deal to next/previous stage
- Log activities against a deal
- Close deal as Won or Lost
- View linked contact and originating lead
- Custom fields per industry profile

**Deal pipeline stages per profile:**

| Profile | Stages |
|---|---|
| `crm-default` | Discovery → Proposal → Negotiation → Won / Lost |
| `crm-education` | Offer Accepted → Visa Applied → Visa Approved → Enrolled / Visa Rejected |
| `crm-realstate` | Negotiation → Paperwork → Payment → Closed |
| `crm-pharma` | Order Received → Processing → Dispatched → Delivered |
| `crm-garments` | Order Confirmed → In Production → QC / Inspection → Shipped → Delivered |

---

### 4.3 Contact Module

**Purpose:** One source of truth for every person the business interacts with.

**Core features:**
- Contact record created automatically when a lead is converted (matched on email — no duplicates)
- View all leads and deals linked to a contact
- View activity timeline for a contact
- Edit contact details and custom fields
- CRM contact list at `/crm/contacts` (separate from the general contacts module)

**Note:** Contacts are never deleted — only the link to leads/deals can change.

---

### 4.4 Activity Module

**Purpose:** Log and track every interaction with a lead, deal, or contact.

**Activity types:**
- Call (inbound / outbound)
- Email (sent / received)
- Meeting
- Note
- Stage change (auto-logged by system)
- Task (links to Productivity module)

**Core features:**
- Log an activity from the lead/deal/contact Show page
- Activity appears in the entity's timeline in reverse-chronological order
- Global activity feed at `/crm/activity` — all activities across all leads and deals the user can see
- Stage changes are auto-logged with old stage → new stage
- Workflow-triggered actions are logged as system activities (auto_assign, auto_notify)

---

### 4.5 Pipeline Module

**Purpose:** Read-only configuration endpoint consumed by Lead and Deal modules.

- Exposes current active pipeline stages for the tenant's profile
- Used by: Lead Create/Edit forms (stage selector), Deal Kanban board (column headers), Lead conversion (first deal stage)
- No pipeline management UI in v1 — stages are seeded from profile JSON and readable only

---

### 4.6 Support Module

**Purpose:** Track customer support requests and complaints linked to existing contacts and deals.

**Core features:**
- Create, view, edit, delete support tickets
- Assign to a team member
- Pipeline stages: Open → In Progress → Waiting → Resolved → Closed
- Link ticket to an existing contact or deal
- Log activities against a ticket
- Priority levels: Low / Medium / High / Critical
- Status: Open / In Progress / Resolved / Closed

**Note:** Support module has its own `pipeline_type = 'support'` pipeline, separate from lead and deal pipelines.

---

### 4.7 Document Module

**Purpose:** Attach and verify files against leads, deals, contacts, and support tickets.

**Core features:**
- Upload documents (PDF, image, Word, Excel — max 10 MB per file)
- Attach to any entity: lead, deal, contact, support ticket
- Categorize: Passport, Academic Certificate, Offer Letter, Agreement, Invoice, Other
- Mark document as verified (admin/manager only)
- View document list per entity on the Show page
- Download document

**Note:** Uses existing Spatie MediaLibrary integration. No new file storage infrastructure.

---

## 5. User Stories

### Role: Admin

| ID | User Story | Acceptance Criteria |
|---|---|---|
| A-01 | As an admin, I want to select my industry profile at setup so the CRM uses my business's vocabulary from day one | Given I select `crm-education`, all labels show "Applications", "Enrollments", "Students" everywhere in the UI |
| A-02 | As an admin, I want to invite team members and assign them roles so they see only what they're allowed to | Given I invite a user as Salesperson, they can log in and see only their own assigned leads |
| A-03 | As an admin, I want to view all leads across all branches so I can monitor company-wide pipeline | Given I am admin, the leads index shows leads from every branch with a branch filter |
| A-04 | As an admin, I want to reassign a lead to a different salesperson so I can rebalance workloads | Given I open any lead, I can change the owner to any active salesperson in the company |
| A-05 | As an admin, I want to delete a lead that was created in error so the pipeline stays clean | Given I delete a lead, it is soft-deleted and no longer visible in list views; linked deals and contacts are not deleted |

### Role: Branch Manager

| ID | User Story | Acceptance Criteria |
|---|---|---|
| M-01 | As a branch manager, I want to see all leads assigned to my branch so I can monitor my team's pipeline | Given I am manager of Branch A, I see only Branch A leads; Branch B leads are not visible even if I navigate directly |
| M-02 | As a branch manager, I want to see which leads have been untouched for 7+ days so I can follow up with my team | Given I filter leads by "no activity in 7 days", I see the list and can identify at-risk leads |
| M-03 | As a branch manager, I want to reassign a deal from one salesperson to another so I can respond to staff changes | Given I open a deal in my branch, I can change the owner to any salesperson in my branch |
| M-04 | As a branch manager, I want to see branch-wide conversion rate and deal value on the dashboard so I can report to management | Given I log in, my dashboard shows: total leads, leads converted this month, total open deal value, conversion rate |

### Role: Salesperson (Counselor / Agent / MR / Sales Exec)

| ID | User Story | Acceptance Criteria |
|---|---|---|
| S-01 | As a salesperson, I want to see only my assigned leads when I log in so I'm not distracted by other team members' work | Given I am a salesperson, the leads index shows only leads where I am the owner |
| S-02 | As a salesperson, I want to create a new lead with the relevant fields for my industry so I capture the right information | Given I am on `crm-education`, the create lead form shows IELTS score, preferred country, GPA — not generic fields |
| S-03 | As a salesperson, I want to log a call against a lead so I have a record of every interaction | Given I log a call with notes, it appears in the lead's activity timeline with timestamp and my name |
| S-04 | As a salesperson, I want to move a lead to the next pipeline stage so the pipeline reflects current status | Given I move a lead from "Assessment" to "Shortlisting", the stage change is recorded in the activity timeline automatically |
| S-05 | As a salesperson, I want to convert a qualified lead into a deal so I can start tracking the committed opportunity | Given I click "Convert to Enrollment" on an education lead, a new Enrollment (deal) is created, a Student (contact) record is created or linked, and the lead is marked Converted |
| S-06 | As a salesperson, I want to see my deals on a Kanban board so I can visually manage my pipeline | Given I open the Deals board, columns show the deal pipeline stages and my deals appear as cards with value and contact name |
| S-07 | As a salesperson, I want to drag a deal card to a new stage on the Kanban board so I can update deal status without opening the detail page | Given I drag a deal from "Visa Applied" to "Visa Approved", the stage updates and an activity log entry is created |
| S-08 | As a salesperson, I want to see all activities for a lead in one timeline so I know exactly where the relationship stands | Given I open a lead's Show page, I see all calls, notes, emails, stage changes in reverse-chronological order |
| S-09 | As a salesperson, I want to attach a student's passport and offer letter to their enrollment so all documents are in one place | Given I upload a PDF to an enrollment, it appears in the document list with a category tag |

### Role: System (Automations)

| ID | Automation Story | Acceptance Criteria |
|---|---|---|
| SYS-01 | When a new lead is created on `crm-education`, it is automatically assigned to the next available counselor (round-robin) | Given lead is created, `owner_id` is set within the same request; the workflow run is logged in `workflow_runs` |
| SYS-02 | When a lead is created on `crm-default`, it is automatically assigned to the next available salesperson (round-robin) | Same as SYS-01 for the default profile |
| SYS-03 | When a deal moves to Won, a workflow run is logged (invoice creation is v1.5) | Given deal stage changes to `is_won = true`, a `workflow_runs` entry exists for the event |
| SYS-04 | When any stage change occurs, it is recorded as an activity log entry automatically | Given stage changes on lead or deal, `activity_logs` row exists with `action_type = stage_changed` |

---

## 6. Edge Cases & Data Behaviour

### Lead conversion
- A lead that has already been converted cannot be converted again — the system shows "Already Converted" and the Convert button is disabled
- Converting a lead where the contact email already exists links the existing contact — no duplicate is created
- If conversion fails mid-transaction (e.g. DB error during deal creation), no records are created — the lead remains unconverted
- A converted lead is read-only — its stage is locked at the conversion stage

### Pipeline stage movement
- A lead or deal can only move to a stage that belongs to its own pipeline — cross-pipeline moves are rejected
- Moving to an `is_won` stage marks the entity status as Won
- Moving to an `is_lost` stage marks the entity status as Lost
- A Won or Lost deal cannot have its stage changed unless the admin reopens it (v1: manual status edit by admin only)

### Bulk actions
- Bulk status update applies only to records the current user is authorized to edit
- Records outside the user's scope are silently skipped — no error shown per record, but the count of updated records reflects the actual number changed

### Custom fields
- Custom fields defined in the industry profile appear in Create, Edit, and Show pages automatically
- A custom field with no value is displayed as "—" in Show — never as an error
- Custom field values are never deleted by a pack re-seed

### Contact deduplication
- Contacts are matched on `email` at conversion time
- If two leads with the same email are converted, they both link to the same contact record
- A contact with no email can be created manually — deduplication does not apply

### Auto-assignment (round-robin)
- If no salesperson with the required role exists in the tenant at lead creation time, `owner_id` is set to null and admin is notified
- If the round-robin Redis cursor is missing (fresh tenant), it starts at index 0

---

## 7. Acceptance Criteria — Module-Level

### Lead module done-when:
- [ ] Create form renders all custom fields for the active profile
- [ ] Lead can be moved through all pipeline stages
- [ ] Stage change creates an activity log entry automatically
- [ ] Bulk status update works on selected leads
- [ ] Search and filter work on: name, email, stage, status, owner, custom searchable fields
- [ ] Convert creates deal + contact in one transaction; failure leaves no orphaned records
- [ ] Converted lead shows "Converted" badge and disabled Convert button
- [ ] Salesperson sees only own leads; manager sees only branch leads; admin sees all

### Deal module done-when:
- [ ] Kanban board groups deals correctly by stage
- [ ] Drag-and-drop stage move updates the deal and logs activity
- [ ] Won stage closes deal with `status = won`; Lost stage closes with `status = lost`
- [ ] Custom fields for the active profile appear in deal Create/Edit/Show
- [ ] Board loads max 50 deals per column with load-more for large stages

### Contact module done-when:
- [ ] Contact is created or linked on lead conversion — never duplicated on same email
- [ ] Contact Show page lists linked leads and deals
- [ ] Contact activity timeline shows all activities from linked leads and deals

### Activity module done-when:
- [ ] All 6 activity types can be logged from Lead/Deal/Contact Show pages
- [ ] Activities appear in reverse-chronological order on timeline
- [ ] Global activity feed at `/crm/activity` shows all activities the user is authorized to see
- [ ] System activities (auto_assign, stage_change) appear in timeline without manual entry

### Support module done-when:
- [ ] Ticket can be created, assigned, prioritized, and linked to a contact or deal
- [ ] Ticket moves through support pipeline stages
- [ ] Activities can be logged against a ticket

### Document module done-when:
- [ ] File upload works for PDF, image, Word, Excel — max 10 MB
- [ ] Document can be attached to lead, deal, contact, or support ticket
- [ ] Category can be set at upload or edited after
- [ ] Verified flag can be toggled by admin/manager
- [ ] Download works for all file types

---

## 8. v1 — Deferred to Later Phases

| Feature | When |
|---|---|
| Email / WhatsApp sending from CRM | v1.5 |
| Invoice creation triggered by deal Won | v1.5 |
| Pipeline stage management UI (add/edit/reorder stages) | Phase 3 (admin UI) |
| Workflow rule builder UI | Phase 3 (admin UI) |
| AI lead scoring | v2 |
| University / Property catalog | v2 |
| Mobile app | v2 |
| Public REST API | v2 |
| Profile switching for existing tenants | Unsupported — one-time selection at provisioning |

---

## 9. v1.5 — Communication + Invoice Integration

> **Trigger:** v1 deployed to at least one paying tenant per profile, no P1 bugs for 30 days.

### 9.1 Communication Module

**Purpose:** Send and receive emails and WhatsApp messages directly from within a lead, deal, or contact record. All communication is logged to the activity timeline automatically.

**Channels:**
- **Email** — via SMTP (outbound) and IMAP polling (inbound)
- **WhatsApp** — via WhatsApp Business API

**Core features:**
- Compose and send email from lead/deal/contact Show page
- Receive email replies — linked to the entity via thread ID
- Send WhatsApp message from lead/deal/contact Show page
- All sent/received messages appear in the activity timeline automatically
- Message log table (`communication_logs`) — stores all outbound and inbound messages
- Template support — pre-written message templates selectable at send time
- Two new WorkflowEngine actions unlocked: `SendEmail`, `SendWhatsApp`
  - Example: when deal stage moves to "Offer Received", automatically send a congratulations email to the student

**Industry-specific automation examples:**

| Profile | Trigger | Action |
|---|---|---|
| `crm-education` | Deal stage → Offer Received | Auto-send email: "Your offer letter is ready" |
| `crm-education` | Deal stage → Visa Approved | Auto-send WhatsApp: "Visa approved — next steps" |
| `crm-realstate` | Deal stage → Booking | Auto-send email: "Booking confirmation to client" |
| `crm-garments` | Deal stage → Shipped | Auto-send email: "Shipment dispatch notice to buyer" |

**User stories:**

| ID | User Story | Acceptance Criteria |
|---|---|---|
| C-01 | As a counselor, I want to send an email to a student from within their enrollment record so I don't need to switch to Gmail | Given I compose and send an email from the enrollment Show page, it is sent via SMTP and logged to the activity timeline |
| C-02 | As a counselor, I want to see all email replies from a student in the activity timeline so I have the full conversation in one place | Given the student replies to the email, the reply appears in the timeline within the IMAP polling interval |
| C-03 | As an agent, I want to send a WhatsApp message to a client from within the property deal record | Given I send a WhatsApp message, it is delivered via WhatsApp Business API and logged to the activity timeline |
| C-04 | As an admin, I want the system to automatically send a confirmation email when a deal reaches a key stage so my team doesn't have to do it manually | Given a WorkflowEngine rule is seeded with `SendEmail` action triggered on stage change, the email is sent automatically and logged |

**Acceptance criteria:**
- [ ] Email sent from CRM arrives in the recipient's inbox
- [ ] Reply to that email is picked up by IMAP polling and logged to the correct entity's timeline
- [ ] WhatsApp message delivered and logged
- [ ] `SendEmail` and `SendWhatsApp` WorkflowEngine actions fire correctly from seeded rules
- [ ] Communication logs accessible in activity timeline — not a separate inbox UI
- [ ] Failed sends are logged with error reason — no silent failures

---

### 9.2 Invoice Integration

**Purpose:** When a deal is Won, automatically create an invoice in SalesApp and link it to the deal record.

**How it works:**
- New WorkflowEngine action: `CreateInvoice`
- Seeded in each profile's `business_flows` JSON at the "deal Won" step
- Calls `SalesApp/Invoice` module's existing invoice-create entry point
- Invoice is linked back to the deal via `deal_id` on the invoice record

**Business flow update per profile:**

| Profile | Business flow step added |
|---|---|
| `crm-default` | Deal Won → `CreateInvoice` |
| `crm-education` | Enrollment Won (Enrolled stage) → `CreateInvoice` |
| `crm-realstate` | Property Deal: Booking stage → `CreateInvoice` |
| `crm-garments` | Order: Shipment stage → `CreateInvoice` |
| `crm-pharma` | Order Delivered → `CreateInvoice` |

**User stories:**

| ID | User Story | Acceptance Criteria |
|---|---|---|
| I-01 | As a counselor, I want an invoice to be generated automatically when I mark an enrollment as Won so I don't have to create it manually | Given I move the enrollment to "Enrolled" (Won stage), an invoice is created in SalesApp and linked to the enrollment |
| I-02 | As an admin, I want to see the linked invoice from within the deal record so I can track payment without leaving the CRM | Given an invoice exists for the deal, a link to it appears on the deal Show page |
| I-03 | As a manager, I want failed invoice creation to be visible so I can follow up | Given invoice creation fails (SalesApp unreachable), the failure is logged in `workflow_runs` and the deal remains Won |

**Acceptance criteria:**
- [ ] Invoice created automatically on deal Won for all 5 profiles
- [ ] Invoice linked to deal — viewable from deal Show page
- [ ] Failed invoice creation logged to `workflow_runs` — deal not rolled back
- [ ] Re-triggering invoice creation (manual retry by admin) does not create duplicate invoices — idempotent

---

## 10. v2 — Domain Apps + AI

> **Trigger:** At least one profile (likely Education or Real Estate) has paying customers requesting vertical depth — typically asking for an industry-specific catalog inside the CRM.

### 10.1 AcademicApp — University & Course Catalog (Education only)

**Purpose:** Give education consultancies a searchable catalog of universities and courses inside the CRM, so counselors can match students to programs without leaving the system.

**Applicable profile:** `crm-education` only

**Core features:**
- University list: name, country, ranking, acceptance rate, intake months, fees
- Course list per university: name, level (Bachelor/Master/PhD), duration, requirements, tuition
- Shortlist — counselor marks programs for a student from the catalog
- Link shortlisted programs to an Application (lead) as candidate universities
- Search and filter: country, level, subject area, budget range, intake month

**How it plugs in:**
- New nwidart app: `AcademicApp`
- Pack JSON declares `"requires_modules": ["AcademicApp"]`
- `setup:crm` enables the module for the tenant
- Sidebar gains "Universities" and "Courses" items under CRM (education profile only)

**User stories:**

| ID | User Story | Acceptance Criteria |
|---|---|---|
| AC-01 | As a counselor, I want to search universities by country and subject so I can find the right fit for a student | Given I search "Canada + Computer Science + Master", I see matching universities with fee and intake info |
| AC-02 | As a counselor, I want to shortlist 3 universities for a student from the catalog and attach them to their application | Given I shortlist universities from the catalog, they appear in the application's custom field "University Choices" |
| AC-03 | As an admin, I want to import the university catalog from a CSV so I don't have to enter each one manually | Given I upload a CSV, universities and courses are imported with no duplicates on re-import |

---

### 10.2 Property Module — Property Listings (Real Estate only)

**Purpose:** Give real estate agencies a property inventory inside the CRM, so agents can match clients to listings without switching to a separate property management system.

**Applicable profile:** `crm-realstate` only

**Core features:**
- Property list: reference number, type (Apartment/Villa/Land/Office), location, price, bedrooms, status (Available/Reserved/Sold)
- Link a property to a Property Deal
- Filter by: type, location, price range, bedrooms, status
- Mark property as Reserved when a deal reaches Booking stage (automated)
- Mark property as Sold when deal reaches Closed (automated)

**User stories:**

| ID | User Story | Acceptance Criteria |
|---|---|---|
| P-01 | As an agent, I want to see available properties and link one to a client's property deal | Given I open a property deal, I can search and attach an available property |
| P-02 | As a branch manager, I want the property status to update to "Reserved" automatically when a booking is made | Given a deal reaches Booking stage, the linked property status changes to Reserved |
| P-03 | As an admin, I want to see a property inventory list with current status so I know what's available | Given I open the Properties list, I see all properties with their current deal status |

---

### 10.3 AI Features (All profiles — domain-tuned)

**Purpose:** Replace the `NullAiHook` placeholder with real AI capabilities per domain. Each industry gets AI-powered insights relevant to their workflow.

**How it plugs in:**
- `NullAiHook` is swapped for a real implementation per domain
- `ComputeScore` WorkflowEngine action becomes active
- AI runs asynchronously — score is written to `leads.score` column, not blocking the request

**AI features per profile:**

| Profile | AI capability | What it predicts |
|---|---|---|
| `crm-education` | Visa success score | Likelihood of visa approval based on IELTS, GPA, sponsor type, destination country, refusal history |
| `crm-education` | University match score | Best-fit universities for a student's profile |
| `crm-education` | Document validation | Flags missing or mismatched documents in the checklist |
| `crm-realstate` | Price prediction | Estimated market price for a property based on location, type, size |
| `crm-realstate` | Buyer intent scoring | Likelihood of a buyer converting based on budget match, engagement history, timeline |
| `crm-pharma` | Prescription volume prediction | Forecasted monthly Rx volume for a doctor based on specialty and visit history |
| `crm-garments` | Buyer intent scoring | Likelihood of a buyer placing an order based on sample history and order volume |
| `crm-default` | Lead scoring | Generic lead quality score based on engagement, source, and activity frequency |

**User stories:**

| ID | User Story | Acceptance Criteria |
|---|---|---|
| AI-01 | As a counselor, I want to see a visa success score on each student application so I can prioritise high-likelihood cases | Given the AI model is active, the Application Show page displays a score (0–100) with a brief reason |
| AI-02 | As a branch manager, I want to filter leads by AI score so my team focuses on the most likely conversions | Given leads have scores, the filter on the leads index accepts a min/max score range |
| AI-03 | As an agent, I want to see a buyer intent score on each property enquiry so I know which clients to follow up with first | Given the AI model is active, the Enquiry Show page displays a score |

**Acceptance criteria (all profiles):**
- [ ] Score is written to `leads.score` asynchronously — UI shows "Calculating…" until ready
- [ ] Score is recalculated when key fields change (IELTS score updated, new activity logged)
- [ ] Score explanation is shown alongside the number — not a black box
- [ ] NullAiHook is still the fallback if AI service is unavailable — no error shown to user

---

### 10.4 Phase 3 — Admin UIs (all profiles)

> Phase 3 runs in parallel with v2 domain apps. It adds management interfaces for configurations that were seed-driven in v1.

| Admin UI | Purpose |
|---|---|
| **Workflow rule builder** | Visual interface to create/edit/delete workflow rules without editing pack JSON |
| **Pipeline management** | Drag-reorder stages, add/rename/delete stages, set Won/Lost flags |
| **Entity relationship manager** | Define new converts_to relationships between entity types |
| **Business flow editor** | Visual editor for the `business_flows` JSON — define cross-module chains via UI |
| **Proposal UI** | Template editor, approval flow, PDF export, attach proposal to deal |
| **Contact segments** | Saved filter groups on the contact list |
| **Pack import/export** | Upload a custom pack JSON; export current tenant configuration as a pack |
| **Activity analytics** | Charts and export for activity volume, response times, stage drop-off |
| **Observability panel** | Workflow run history, failed runs, re-trigger controls |

**User stories:**

| ID | User Story | Acceptance Criteria |
|---|---|---|
| ADM-01 | As an admin, I want to add a new pipeline stage via a UI without editing JSON | Given I open Pipeline Settings, I can add a stage, name it, set a color, and save — it appears immediately in the lead list |
| ADM-02 | As an admin, I want to create a workflow rule via a UI — "when a lead is untouched for 7 days, notify me" | Given I use the rule builder, I can set trigger, condition, and action without writing code |
| ADM-03 | As an admin, I want to define the business flow for my profile visually — seeing Lead → Deal → Invoice as a connected chain | Given I open Business Flow settings, I see the current flow as a step diagram and can add/remove steps |
| ADM-04 | As an admin, I want to see all workflow runs and which ones failed so I can diagnose automation issues | Given I open the Observability panel, I see a log of all workflow runs with status, entity, and error details |

---

## 11. Full Phase Summary

| Phase | Modules / Features | Ships when |
|---|---|---|
| **v1** | Lead, Deal, Contact, Activity, Pipeline, Support, Document | Building now |
| **v1.5** | Communication (Email + WhatsApp), Invoice integration | After v1 stable in production (30 days, no P1 bugs) |
| **v2 + Phase 3** | AcademicApp (education), Property (real estate), AI scoring, Admin UIs (Workflow builder, Pipeline UI, Business Flow editor, Pack import/export) | After paying customers request vertical depth |
