PRD: Company Master CRUD (CRM Phase 1)¶
Version: 1.0
Date: 2026-01-17
Status: Draft
Owner: Pebble Business Orchestrator Team
1. Introduction¶
This PRD defines the requirements for the Company Master module, the foundation of the custom CRM system that will replace the existing D365 instance. The Company Master provides comprehensive customer relationship management through an 8-tab interface, supporting complex multi-entity relationships, social media integration, and vendor empanelment workflows for chemical distribution operations.
Problem Statement: The current D365 CRM lacks flexibility for Southern Spechem's complex business model (3 legal entities, multi-location customers, chemical compliance tracking). Customizations are expensive and slow, limiting operational agility.
Solution: A custom Django-based Company Master that provides the 8-tab interface shown in the CRM Requirements, enabling rapid iteration and full control over data models and workflows.
2. Goals¶
- G1: Enable CRUD operations for the complete 8-tab Company Master interface
- G2: Support multi-location tracking (plants, warehouses, branches) per customer
- G3: Integrate social media channels (WhatsApp, Skype, LinkedIn, Facebook, Telegram)
- G4: Track vendor empanelment status (FEP workflow) and compliance (Drug License, GST, PAN)
- G5: Enable comprehensive D365 data migration (customers, transactions, documents, users, activities)
- G6: Provide cascading Country → State → City dropdowns for address entry
- G7: Support multi-employee assignment per customer for accountability tracking
- G8: Ensure zero data loss during D365 to custom CRM transition
3. User Stories¶
US-CRM-001: Create New Company Record¶
Description: As a Sales Rep, I want to create a new company record with basic information so that I can start tracking a potential customer.
Acceptance Criteria:
- User can access "Add Customer" button from main interface
- Form displays Company Name, Address (Country/State/City cascading dropdowns), Mobile (4 fields), Email (3 fields), Website, SAP Code
- Country dropdown auto-populates State dropdown; State auto-populates City dropdown
- Form validates required fields (Company Name, Country, at least 1 mobile)
- On save, system generates unique Customer ID
- System displays success message and redirects to view mode of created company
- Verify in browser using dev-browser skill
US-CRM-002: Manage Company Information Tabs¶
Description: As a Sales Manager, I want to navigate between 8 company information tabs so that I can view and edit different aspects of customer data.
Acceptance Criteria:
- Interface displays 8 tabs: Main Company Information, Branches/Plants/Warehouses, Contacts in Department, Content Broadcasted, Products Purchased, Present Suppliers, Agents, Employee Handling
- Clicking a tab switches the view without page reload
- Active tab is visually highlighted
- Tab content loads data specific to that customer
- Unsaved changes warning appears if user tries to switch tabs with pending edits
- Verify in browser using dev-browser skill
US-CRM-003: Add Social Media Channels¶
Description: As a Sales Rep, I want to add WhatsApp, Skype, LinkedIn, Facebook, and Telegram handles so that I can track all communication channels for a customer.
Acceptance Criteria:
- Main Company Information tab displays fields for WhatsApp (3 numbers), Skype ID, Telegram, Facebook, LinkedIn
- WhatsApp fields validate phone number format
- LinkedIn/Facebook fields accept URLs or profile handles
- All social media fields are optional
- System saves social media data to
Companymodel - Verify in browser using dev-browser skill
US-CRM-004: Track Multi-Location Customers¶
Description: As a Sales Manager, I want to add and manage multiple branches/plants/warehouses for a single customer so that I can track their distributed operations.
Acceptance Criteria:
- "Branches/Plants/Warehouses" tab displays a table of locations with columns: Location Type, Location Name, Contact Person, Department, Address, FEP Status
- User can click "Add Location" to open location entry form
- Location form includes: Location Type (dropdown: Office/Plant/Warehouse), Location Name, Contact Person, Department, Address (Country/State/City cascading), Geographic Location (map integration deferred to Phase 2)
- User can edit or delete existing locations
- Each location is associated with the parent company via foreign key
- Table displays all locations for current company
- Verify in browser using dev-browser skill
US-CRM-005: Manage Vendor Empanelment Status¶
Description: As a Commercial team member, I want to track Factory Empanelment Process (FEP) status for customer locations so that I can ensure compliance before shipping.
Acceptance Criteria:
- Location form displays FEP Status dropdown (Pending/Approved/Rejected)
- Location form displays Attestation Status dropdown
- Location form displays Drug License Number, Grades, Monthly Consumption fields
- FEP Status field is searchable/filterable across all customers
- System alerts if attempting to create order for location with FEP Status = Pending
- Verify in browser using dev-browser skill
US-CRM-006: Track Department-Wise Contacts¶
Description: As a Sales Rep, I want to add contacts organized by department and location so that I can reach the right person for different needs.
Acceptance Criteria:
- "Contacts in Department" tab displays table with columns: Location Type, Company Name, Location Details, Contact Person (Name, Position), Communication (Mobile, Email, Phone)
- User can click "Add to Outlook" button to export contact
- User can add new contact via "Add Contact" button
- Contact form links to parent Location (via foreign key)
- Contact form includes: Contact Person Name, Position, Department, Mobile, Email, Office Phone, Home Phone
- Table displays hierarchy: Company → Location → Department → Contact
- Verify in browser using dev-browser skill
US-CRM-007: Track Content Broadcasts¶
Description: As a Marketing team member, I want to log all quotes, brochures, and marketing materials sent to customers so that I can track engagement history.
Acceptance Criteria:
- "Content Broadcasted" tab displays table with columns: Content Type, Date Sent, Time Sent, Sent By, Enquire No, Action, Content Location
- User can click "Send Selected Content" to attach content file
- Content file uploads to designated storage location (S3 or local filesystem)
- System auto-populates Date Sent, Time Sent, Sent By (current user)
- User can manually enter Enquire No to link to sales pipeline
- Action dropdown includes: Attach, Details, Open, Delete
- Table is searchable by Enquire No and filterable by date range
- Verify in browser using dev-browser skill
US-CRM-008: Track Products Purchased¶
Description: As a Sales Manager, I want to see which products a customer has purchased and at what rates so that I can negotiate effectively.
Acceptance Criteria:
- "Products Purchased" tab displays table with columns: Products Purchased, Maker, Currently Buying from us (Yes/No), General Rate, Customer Specific Rate
- Products Purchased field is autocomplete dropdown populated from Product Master
- System highlights rows where Currently Buying = No (churn risk)
- User can add new product purchase record
- System calculates price variance (Customer Specific Rate vs. General Rate)
- Table is sortable by product name, maker, rates
- Verify in browser using dev-browser skill
US-CRM-009: Track Competitor Suppliers¶
Description: As a Sales Manager, I want to know which suppliers the customer currently buys from so that I can identify replacement opportunities.
Acceptance Criteria:
- "Present Suppliers" tab displays table with column: Supplier (autocomplete dropdown)
- User can add multiple suppliers
- Supplier field links to Supplier Master (via foreign key or text field if master not available)
- User can delete suppliers
- Table displays all current suppliers for the customer
- Verify in browser using dev-browser skill
US-CRM-010: Track Agents/Brokers¶
Description: As a Commercial team member, I want to track third-party agents associated with customers so that I can manage commissions.
Acceptance Criteria:
- "Agents" tab displays table with columns: Agents (name), Country
- User can add multiple agents
- Country field is dropdown populated from standard country list
- User can edit or delete agents
- System links agent to customer via many-to-many relationship
- Verify in browser using dev-browser skill
US-CRM-011: Track Employee Accountability¶
Description: As a Sales Manager, I want to assign employees to customer accounts so that I can track accountability and manage handovers.
Acceptance Criteria:
- "Employee Handling" tab displays table with columns: Employee developing this Customer (name), Email
- User can assign multiple employees to a single customer
- Employee field is dropdown populated from active employees
- System auto-populates employee email from employee master
- User can remove employee assignments
- System logs assignment history (audit trail)
- Verify in browser using dev-browser skill
US-CRM-012: Add Customer Comments¶
Description: As any CRM user, I want to add free-form notes about a customer so that I can capture context and history.
Acceptance Criteria:
- "Customer Comments" tab displays large text area
- User can enter multi-line comments with basic formatting (line breaks)
- System auto-saves comments on blur or explicit save
- System displays comment history with timestamp and author
- Comments are searchable
- Verify in browser using dev-browser skill
US-CRM-013: Migrate D365 Customer Data¶
Description: As a System Admin, I want to migrate existing customer data from D365 so that the team can start using the new CRM immediately.
Acceptance Criteria:
- Django management command
python manage.py migrate_d365_customersexists - Script connects to D365 API or exports CSV from D365
- Script maps D365 fields to Company model fields (see mapping table in Technical Considerations)
- Script creates Company records with basic info (Main tab only)
- Script logs any import errors to
migration_errors.log - Script provides summary report: X records imported, Y errors
- Migration is idempotent (can be run multiple times without duplicates)
US-CRM-014: Dashboard Metrics Overview¶
Description: As a Sales Manager, I want to see key CRM metrics on a dashboard so that I can monitor team performance at a glance.
Acceptance Criteria:
- Dashboard displays 4 metric cards: Total Customers, Active Customers (last 30 days activity), Pending FEP Approvals, Average Credit Utilization %
- Each metric card shows current value and trend indicator (up/down arrow)
- Dashboard includes "Top 10 Customers by Revenue" table
- Dashboard includes "Churn Risk" section (customers with no activity in 90 days)
- Metrics update in real-time or on page refresh
- Verify in browser using dev-browser skill
US-CRM-015: AI Assistant for Customer Queries (High Priority)¶
Description: As any CRM user, I want to ask natural language questions about customer data so that I can get insights quickly without complex queries.
Acceptance Criteria:
- AI Assistant input box available on every page (floating button or sidebar)
- User can type questions like "Show me all customers in Maharashtra with credit limit > 10L"
- AI Assistant parses query and returns results in table or card format
- AI Assistant can answer: "What was the last price we quoted for Product X to Company Y?"
- AI Assistant can suggest follow-up questions
- System logs all AI queries for audit/training
- Verify in browser using dev-browser skill
US-CRM-016: Advanced Search & Filters (High Priority)¶
Description: As a Sales Rep, I want to filter customers by multiple criteria simultaneously so that I can segment my pipeline.
Acceptance Criteria:
- Search bar supports multi-field search (Name, SAP Code, Mobile, Email)
- Filter panel includes: Country/State/City dropdowns, FEP Status, Customer Class, Credit Limit range, Last Activity Date
- Filters are combinable (AND logic, e.g., "Maharashtra AND FEP=Pending AND Credit>10L")
- Applied filters display as removable chips/tags
- System saves last used filter set per user
- "Clear All Filters" button resets to default view
- Verify in browser using dev-browser skill
US-CRM-017: Activity Timeline View (High Priority)¶
Description: As a Sales Manager, I want to see a chronological timeline of all customer interactions so that I can understand the complete relationship history.
Acceptance Criteria:
- Timeline view accessible from Company Master detail page
- Timeline displays: Content Broadcasts, Follow-Up Visits (if integrated), Quotes Sent, Orders Placed, Comments Added
- Each timeline entry shows: Date/Time, Event Type (icon), Description, User who created it
- Timeline entries are filterable by Event Type
- Timeline loads last 50 entries by default with "Load More" button
- Verify in browser using dev-browser skill
US-CRM-018: Bulk Operations¶
Description: As a Sales Manager, I want to perform bulk actions on multiple customers simultaneously so that I can manage territories efficiently.
Acceptance Criteria:
- Customer list view includes checkboxes for multi-select
- "Select All" checkbox selects all visible customers (with warning if >50)
- Bulk actions menu appears when >1 customer selected
- Available bulk actions: Reassign to Employee, Mark as Inactive, Export to Excel, Delete
- System displays confirmation dialog before executing bulk delete
- Bulk operations execute asynchronously with progress indicator
- System sends notification when bulk operation completes
US-CRM-019: Audit Trail Viewer¶
Description: As a Compliance Officer, I want to view the complete audit log for a customer so that I can track who changed what and when.
Acceptance Criteria:
- "Audit Log" link available on Company Master detail page
- Audit log displays table with columns: Timestamp, User, Action (Created/Updated/Deleted), Field Changed, Old Value, New Value
- Audit log is filterable by Date Range, User, Action Type
- Audit log entries are immutable (cannot be edited or deleted)
- Audit log exports to CSV for compliance reporting
- Verify in browser using dev-browser skill
US-CRM-020: Notifications & Alerts¶
Description: As a Sales Rep, I want to receive notifications when important customer events occur so that I can respond promptly.
Acceptance Criteria:
- Notification bell icon in header shows unread count
- Notifications triggered for: FEP Status changed to Approved/Rejected, Customer assigned to me, Credit limit exceeded, No activity in 30 days (churn risk)
- Clicking notification navigates to relevant customer record
- User can mark notifications as read or dismiss
- User can configure notification preferences (email vs. in-app)
- Verify in browser using dev-browser skill
US-CRM-021: Document Repository with OCR (High Priority)¶
Description: As a Commercial team member, I want to upload documents (COA, MSDS, contracts) with automatic data extraction so that compliance data is captured without manual entry.
Acceptance Criteria:
- "Documents" tab on Company Master displays uploaded files (table: Filename, Type, Upload Date, Extracted Data)
- User can drag-and-drop PDF/JPG files for upload
- System runs OCR on uploaded documents to extract: Drug License No, GST No, PAN, Expiry Dates
- Extracted data auto-populates corresponding fields in Location or Company record
- User can review and approve extracted data before saving
- System displays OCR confidence score (e.g., "98% confidence")
- Verify in browser using dev-browser skill
US-CRM-022: Duplicate Detection (High Priority)¶
Description: As a Sales Rep, I want the system to warn me if I'm creating a duplicate customer so that I can merge or abort the creation.
Acceptance Criteria:
- On Company Name entry, system performs fuzzy match against existing customers
- If >80% match found, system displays warning: "Similar customer exists: [Name] (SAP Code: [Code])"
- Warning includes "View Existing" link to open matching customer
- On GST/PAN entry, system performs exact match and blocks duplicate if found
- User can override warning and proceed with creation (logged in audit trail)
- Verify in browser using dev-browser skill
US-CRM-023: Quick Actions & Keyboard Shortcuts¶
Description: As a power user, I want keyboard shortcuts for common actions so that I can navigate faster.
Acceptance Criteria:
- Pressing
Nopens "Add New Customer" form - Pressing
/focuses the search bar - Pressing
Ctrl+E(orCmd+Eon Mac) exports current view to Excel - Pressing
Esccloses open modals or cancels current edit - "Keyboard Shortcuts" help dialog accessible via
?key - Shortcuts work globally across all pages
US-CRM-024: Export & Reporting¶
Description: As a Sales Manager, I want to export customer lists with applied filters to Excel so that I can share reports with leadership.
Acceptance Criteria:
- "Export to Excel" button available on customer list view
- Export includes all visible columns plus any active filters
- Export file named:
customers_[YYYY-MM-DD].xlsx - Export includes metadata sheet: Export Date, Exported By, Filter Criteria Applied
- System supports exporting up to 10,000 records (warning if exceeded)
- Export executes asynchronously with download link sent via email if >1000 records
US-CRM-025: Mobile Responsive Views¶
Description: As a field sales rep, I want to access customer information on my mobile device so that I can update records during site visits.
Acceptance Criteria:
- Customer list view adapts to mobile screen (single column, card layout)
- Company Master detail view uses collapsible sections on mobile
- Form inputs are touch-friendly (minimum 44px tap targets)
- Mobile view includes "Call" button that triggers phone dialer with customer mobile number
- Mobile view includes "Navigate" button that opens Google Maps with customer address
- Verify in browser using dev-browser skill on mobile viewport
US-CRM-026: Role-Based Dashboards¶
Description: As a Sales Rep, I want to see a personalized dashboard showing only my assigned customers so that I can focus on my accounts.
Acceptance Criteria:
- Sales Rep dashboard displays: My Customers (assigned to me), My Follow-Ups (from PRD 2), My Pending Tasks
- Sales Manager dashboard displays: Team Performance, All Customers, Territory Coverage Map
- Admin dashboard displays: System Health, User Activity, Data Quality Metrics
- User can switch between "My View" and "Team View" (if permissions allow)
- Dashboard is customizable (user can add/remove widgets)
- Verify in browser using dev-browser skill
US-CRM-027: Customer Risk Scoring¶
Description: As a Sales Manager, I want to see a risk score for each customer so that I can prioritize retention efforts.
Acceptance Criteria:
- Risk score (0-100) displayed as color-coded badge: Green (0-30), Yellow (31-70), Red (71-100)
- Risk score calculated based on: Days since last activity, Payment delay history, Credit utilization %, Declining order volume
- Risk score updates nightly via background job
- Customer list sortable by Risk Score
- High-risk customers (>70) automatically added to "Churn Risk" dashboard widget
- System provides explainability: "Risk score 85 due to: No activity in 90 days, 2 late payments"
US-CRM-028: Voice Input & Dictation¶
Description: As a field sales rep, I want to dictate customer comments using voice input so that I can capture notes hands-free after a site visit.
Acceptance Criteria:
- "Dictate" button (microphone icon) available on Customer Comments field
- Clicking button activates browser's speech recognition API
- Spoken words appear in real-time in the text field
- User can pause/resume dictation with button toggle
- System supports English and Hindi (configurable in user settings)
- Dictation auto-saves on 5-second pause
- Verify in browser using dev-browser skill
US-CRM-029: Input Format Validation¶
Description: As a Data Quality Officer, I want the system to validate email, phone, and URL formats on input so that we maintain clean data.
Acceptance Criteria:
- Email fields validate format using regex:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ - Mobile/Phone fields validate format: 10 digits for India, international format supported
- WhatsApp fields validate as phone numbers
- Website/FTP fields validate as valid URLs (http:// or https://index.md)
- LinkedIn/Facebook fields validate as URLs or usernames (flexible)
- System displays inline error message immediately on blur: "Invalid email format"
- Form submit button disabled until all validations pass
- Verify in browser using dev-browser skill
US-CRM-030: GST/PAN Validation with Government API¶
Description: As a Compliance Officer, I want the system to validate GST and PAN numbers against government APIs so that we prevent fraudulent entities.
Acceptance Criteria:
- On GST entry, system calls GSTIN Verification API (if available) to validate authenticity
- On PAN entry, system validates format:
[A-Z]{5}[0-9]{4}[A-Z]{1}(10 characters) - System displays validation status: "Verified ✓" or "Invalid ✗"
- If API unavailable, system performs format-only validation
- System stores API response (Legal Name, Business Type) and pre-fills Company Name if empty
- Validation failure blocks save with error: "Invalid GST/PAN. Cannot proceed."
- System logs all validation attempts for audit
US-CRM-031: Credit Limit Business Rules¶
Description: As a Credit Manager, I want the system to enforce credit limit rules so that we prevent over-exposure.
Acceptance Criteria:
- Credit Limit field accepts only positive decimal values
- System calculates Credit Utilization % = (Outstanding Amount / Credit Limit) * 100
- If Credit Utilization > 100%, system displays warning badge: "Credit Exceeded"
- If Credit Utilization > 80%, system displays caution badge: "Near Limit"
- System prevents order creation if Credit Utilization > 100% (configurable override for Admin)
- Credit Limit changes require approval workflow if > 20% increase
- System sends notification to Credit Manager when customer exceeds 90% utilization
US-CRM-032: FEP Workflow State Validation¶
Description: As a Commercial team member, I want the system to enforce FEP workflow rules so that compliance steps are followed in sequence.
Acceptance Criteria:
- FEP Status can only transition: Pending → Approved or Pending → Rejected (no reverse)
- Transition to "Approved" requires Drug License No, GST No, PAN to be filled
- Transition to "Approved" requires at least 1 uploaded document (COA/MSDS)
- Rejected FEP can be reset to Pending only by Admin role
- System logs FEP status change with timestamp, user, and reason (text field)
- System sends email notification to customer when FEP Status = Approved
- Verify in browser using dev-browser skill
US-CRM-033: Date Field Validation¶
Description: As a Sales Rep, I want the system to validate date fields so that I don't enter impossible dates.
Acceptance Criteria:
- Birthday field validates: Must be in the past, not future
- Anniversary field validates: Must be in the past, not future
- System displays date picker with max date = today for Birthday/Anniversary
- System displays warning if Birthday indicates age > 100 years: "Please verify date"
- System auto-calculates "Days to Birthday/Anniversary" and displays reminder 7 days before
- Date fields accept format: DD-MM-YYYY or YYYY-MM-DD (auto-convert)
US-CRM-034: Migrate D365 Transaction History¶
Description: As a Sales Manager, I want to migrate historical transactions from D365 (quotes, orders, invoices) so that I can see complete customer purchase history for pricing negotiations.
Acceptance Criteria:
- Django management command
python manage.py migrate_d365_transactionsexists - Script migrates Quotes: Quote ID, Date, Customer, Products, Quoted Price, Status (Won/Lost/Pending)
- Script migrates Orders: Order ID, Date, Customer, Products, Ordered Quantity, Unit Price, Total Amount
- Script migrates Invoices: Invoice ID, Date, Customer, Products, Amount, Payment Status (Paid/Pending/Overdue)
- Script establishes relationships: Quote → Order → Invoice for same transaction
- Script links transactions to migrated Company records via Customer ID
- Transaction history viewable in "Products Purchased" tab (augments US-CRM-008)
- Script provides summary: X quotes, Y orders, Z invoices migrated
US-CRM-035: Migrate D365 Document Attachments¶
Description: As a Compliance Officer, I want to migrate all document attachments from D365 (COA, MSDS, contracts) so that we maintain regulatory compliance.
Acceptance Criteria:
- Django management command
python manage.py migrate_d365_documentsexists - Script identifies all attachments in D365: COA, MSDS, Purchase Orders, Contracts
- Script downloads documents from D365 storage (OneDrive/SharePoint)
- Script uploads documents to custom CRM storage (S3 or local filesystem)
- Script creates Document records linked to Company or Location
- Document metadata preserved: Filename, Upload Date, Document Type, Uploaded By
- Documents appear in "Documents" tab (US-CRM-021)
- Script handles large files (>10MB) with chunked upload
- Script provides summary: X documents migrated, Y failed (with error log)
US-CRM-036: D365 Custom Field Discovery & Mapping¶
Description: As a System Admin, I want to discover all custom fields in D365 before migration so that no customer data is lost during the transition.
Acceptance Criteria:
- Django management command
python manage.py discover_d365_schemaexists - Script connects to D365 API and retrieves entity schema for Account (Customer)
- Script lists all standard fields + custom fields with field type (text/number/date/picklist)
- Script generates mapping report:
d365_schema_report.csvwith columns: Field Name, Field Type, Sample Values, Mapped to Custom CRM?, Notes - Report highlights unmapped custom fields requiring manual mapping decision
- Admin reviews report and updates D365 Migration Mapping table (Section 7.3)
- Script validates that all high-priority custom fields are mapped
- MUST run BEFORE US-CRM-013 migration
US-CRM-037: Post-Migration Data Reconciliation¶
Description: As a System Admin, I want to validate that D365 migration was successful by reconciling record counts and data integrity so that we can confidently cut over to the custom CRM.
Acceptance Criteria:
- Django management command
python manage.py validate_d365_migrationexists - Script compares record counts: D365 Customer count vs. Custom CRM Company count (must match 100%)
- Script performs spot check on 10% random sample: compares D365 fields with Custom CRM fields
- Script validates relationships: Every Location has a parent Company, every Contact has a parent Location
- Script checks for orphaned records (e.g., Contact without Company)
- Script generates reconciliation report:
migration_validation_report.pdfwith pass/fail status - Report includes: Total records migrated, Data completeness %, Field-level accuracy %, Issues found
- If validation fails (<95% match), migration is rolled back and issues logged
- System sends email to admin with validation report
US-CRM-038: D365 Bi-Directional Sync (Transition Period)¶
Description: As a Sales Manager, I want changes made in D365 during the transition period to sync to the custom CRM so that both systems remain consistent until full cutover.
Acceptance Criteria:
- Django management command
python manage.py sync_d365_bidirectionalruns every 15 minutes (cron job) - Script detects changes in D365: New customers, updated addresses, deleted customers
- Script applies changes to custom CRM: Creates, updates, or soft-deletes corresponding Company records
- Script detects changes in custom CRM and pushes to D365 (if D365 API allows writes)
- Conflict resolution: If same record changed in both systems, last-write-wins with admin notification
- Sync log table tracks all sync operations: Timestamp, Source, Target, Operation, Status
- Admin dashboard displays sync health: Last sync time, Records synced, Conflicts detected
- Deactivated after final cutover date (configurable cutover date in settings)
US-CRM-039: Migrate D365 User Roles & Permissions¶
Description: As a System Admin, I want to migrate user accounts and role assignments from D365 so that sales reps retain ownership of their assigned customers.
Acceptance Criteria:
- Django management command
python manage.py migrate_d365_usersexists - Script retrieves all active users from D365 with roles: Sales Rep, Sales Manager, Admin
- Script creates Django user accounts with matching emails (password reset email sent)
- Script maps D365 roles to Django roles: D365 "Salesperson" → Custom CRM "Sales Rep"
- Script assigns customers to users: D365 "Owner" field → Custom CRM
assigned_user_id - Script preserves team structures: D365 "Team" → Custom CRM user groups
- Script handles inactive users: D365 inactive users created as inactive in custom CRM
- Script provides summary: X users migrated, Y role assignments, Z customer ownership assignments
US-CRM-040: Migrate D365 Activity Timeline¶
Description: As a Sales Rep, I want to migrate activity history from D365 (call logs, meetings, tasks) so that I have complete context when engaging with customers.
Acceptance Criteria:
- Django management command
python manage.py migrate_d365_activitiesexists - Script migrates Phone Calls: Date, Duration, Subject, Notes, Call Outcome
- Script migrates Appointments (Meetings): Date, Duration, Subject, Attendees, Meeting Notes
- Script migrates Tasks: Due Date, Subject, Status (Completed/Pending), Assigned To
- Script migrates Notes: Created Date, Author, Note Text
- Activities linked to Company records via Customer ID
- Activities appear in Activity Timeline (US-CRM-017)
- Activity type icons preserved (phone, meeting, task, note)
- Script provides summary: X activities migrated by type
4. Functional Requirements¶
FR-1: The system shall provide a Company model with fields for Company Name, SAP Code, Customer Class, Address (Country/State/City), 4 Mobile numbers, 3 Email addresses, Website, FTP, WhatsApp (3), Skype, Telegram, Facebook, LinkedIn, Birthday, Anniversary, GSTN, SGST, UGST, Payment Terms, Potential Rating, Payment Rating, Credit Limit, Primary/Secondary/Tertiary Industry Segments, Product Categories (5).
FR-2: The system shall enforce cascading deletion: when a Company is deleted, all related Locations, Contacts, Content Broadcasts, Product Purchase records, Agents, and Comments shall be deleted.
FR-3: The system shall validate GST/PAN format using regex before saving.
FR-4: The system shall enforce unique constraint on Company Name + SAP Code combination.
FR-5: The system shall provide Django Admin interface for superuser-level data management.
FR-6: The system shall log all CRUD operations (create, update, delete) to an audit trail table with timestamp and user.
FR-7: The system shall support role-based permissions: - Sales Rep: Create, Read, Update own customers - Sales Manager: Create, Read, Update, Delete all customers - Admin: Full access including Django Admin
FR-8: The system shall provide search functionality across Company Name, SAP Code, Mobile numbers, Email addresses.
FR-9: The system shall auto-populate State dropdown based on selected Country, and City dropdown based on selected State.
FR-10: The system shall validate email format using Django's EmailValidator.
FR-11: The system shall display FEP Status badge (color-coded: Pending=Yellow, Approved=Green, Rejected=Red) on location table.
FR-12: The system shall provide export functionality for Contacts (CSV, ODL format for Outlook).
5. Non-Goals (Out of Scope)¶
NG-1: Google Maps integration for geographic location plotting (deferred to Phase 2: CRM Enhancements)
NG-2: Outlook calendar sync for follow-up scheduling (covered in PRD 2: Follow-Up Management)
NG-3: WhatsApp bot integration for automated messaging (Post-MVP feature)
NG-4: Mobile app for field sales reps (Post-MVP feature)
NG-5: AI-powered customer risk scoring (Post-MVP feature)
NG-6: Real-time ERP sync (Focus RT/Business Central integration deferred to Phase 3)
NG-7: Bulk import from Excel (only D365 migration in scope)
6. Design Considerations¶
UI Reference: All UI designs are documented in CRM Requirements - Section 2 with 10 screenshots.
Color Scheme: - Header: Dark red (#8B0000) - Primary buttons: Gray (#808080) - FEP Status badges: Yellow (Pending), Green (Approved), Red (Rejected)
Navigation: - Tabbed interface with 8 tabs - Active tab highlighted - Tab switching without page reload (JavaScript/AJAX)
Form Layout: - Two-column layout for dense information - Cascading dropdowns for Country → State → City - Multi-value fields (4 mobiles, 3 emails) displayed as repeating input groups
Action Buttons (bottom-left): - Add Customer, Save, Delete Customer, Undo, Generate Enquiry, Add to Outlook Contacts, Refresh, Save & Exit
7. Technical Considerations¶
7.1 Technology Stack¶
- Backend: Django 4.2+ with PostgreSQL 14+
- Frontend: Django Templates with Bootstrap 5 (or React/Next.js if decoupled)
- ORM: Django ORM
- Authentication: Django Auth with session-based authentication
- File Storage: Local filesystem or S3 for Content Broadcast attachments
7.2 Database Schema¶
Company Table:
company_id (PK, UUID)
company_name (VARCHAR, NOT NULL)
sap_code (VARCHAR, UNIQUE)
customer_class (VARCHAR)
country (FK to Country)
state (FK to State)
city (FK to City)
zip (VARCHAR)
zone (VARCHAR)
mobile_1, mobile_2, mobile_3, mobile_4 (VARCHAR)
email_1, email_2, email_3 (EmailField)
website (URLField)
ftp_server (URLField)
whatsapp_1, whatsapp_2, whatsapp_3 (VARCHAR)
skype_id, telegram, facebook, linkedin (VARCHAR)
birthday, anniversary (DateField)
gstn, sgst, ugst (VARCHAR)
customer_type, active_type (VARCHAR)
payment_terms (TextField)
potential_rating, payment_rating (IntegerField)
credit_limit (DecimalField)
created_at, updated_at (DateTimeField)
created_by, updated_by (FK to User)
Location Table:
location_id (PK, UUID)
company_id (FK to Company, CASCADE)
location_type (ENUM: Office/Plant/Warehouse)
location_name (VARCHAR)
contact_person_name (VARCHAR)
department (VARCHAR)
address (TextField)
country, state, city (FKs)
fep_status (ENUM: Pending/Approved/Rejected)
attestation_status (VARCHAR)
drug_license_no (VARCHAR)
grades (VARCHAR)
monthly_consumption (DecimalField)
gstin, pan (VARCHAR)
Contact Table:
contact_id (PK, UUID)
location_id (FK to Location, CASCADE)
contact_person_name (VARCHAR)
position (VARCHAR)
department (VARCHAR)
mobile, email, office_phone, home_phone (VARCHAR)
ContentBroadcast Table:
content_id (PK, UUID)
company_id (FK to Company, CASCADE)
content_type (VARCHAR)
date_sent (DateField)
time_sent (TimeField)
sent_by (FK to User)
enquire_no (VARCHAR)
content_location (FileField)
7.3 D365 Migration Mapping¶
| D365 Field | Company Model Field |
|---|---|
| AccountName | company_name |
| AccountNumber | sap_code |
| Address1_Country | country |
| Address1_StateOrProvince | state |
| Address1_City | city |
| Telephone1 | mobile_1 |
| EmailAddress1 | email_1 |
| WebSiteURL | website |
| CreditLimit | credit_limit |
7.4 API Endpoints (if using Django REST Framework)¶
GET /api/companies/ - List all companies
POST /api/companies/ - Create company
GET /api/companies/{id}/ - Get company details
PUT /api/companies/{id}/ - Update company
DELETE /api/companies/{id}/ - Delete company
GET /api/companies/{id}/locations/ - List locations for company
POST /api/companies/{id}/locations/ - Add location to company
8. Success Metrics¶
M1: Data Migration Success - 95% of D365 customer records successfully migrated with no data loss
M2: User Adoption - All 10 sales reps create at least 1 new company record within first week
M3: CRUD Performance - Company creation/update operations complete in <2 seconds
M4: Data Completeness - 80% of company records have at least 1 location and 1 contact added within first month
M5: Zero Downtime - D365 to custom CRM transition completed without service interruption
9. Open Questions¶
Q1: Should we support bulk import from Excel for new customers, or is D365 migration + manual entry sufficient?
Q2: What is the retention policy for deleted companies? Soft delete with archive, or hard delete?
Q3: Should FEP Status approval trigger automated email notifications to Commercial team?
Q4: Do we need multi-currency support for Customer Specific Rate, or is INR sufficient?
Q5: Should the system enforce GST/PAN validation against government APIs, or just format validation?
Q6: ~~What is the data sync strategy if D365 remains active during transition period?~~ ANSWERED: US-CRM-038 provides bi-directional sync.
Q7: **** - What is the final cutover date from D365 to custom CRM? (Required to configure US-CRM-038 sync deactivation)
Q8: **** - Should we perform gradual rollout (e.g., 10 users first week, then all) or hard cutover (all users same day)?
Appendix: Related Documents¶
- CRM Requirements - Full specification with UI screenshots
- Data Integration Specs - Field mapping details
- Architectural Patterns - Alpha Pebble pattern application
Next PRDs in Phase: - PRD 2: Follow-Up Calendar & Scheduling - PRD 3: Analytics & Reporting Dashboard