# Sirus Infotech CRM Technical Specification & Development Roadmap

## 1. Overview

Build a custom web-based CRM targeted at small service businesses such as taxation firms. The system will be designed for client lifecycle management, automated communications, payment tracking, and operational efficiency. The solution will be built from scratch using a modern tech stack and will integrate Brevo for mass WhatsApp messaging, WhatsApp automation, and email automation.

### Goals
- Centralize client contact, status, service history, and payment workflows.
- Automate communication with clients through WhatsApp and email.
- Provide a clean user experience for lead management, service delivery, and follow-ups.
- Support bulk import/export and data-driven reporting.

## 2. Tech Stack

### Frontend
- React.js (Vite or Create React App)
- TypeScript
- Tailwind CSS or Chakra UI for component styling
- React Router for navigation
- React Query / TanStack Query for data fetching
- Zod + React Hook Form for forms and validation
- Chart.js or Recharts for dashboards and analytics

### Backend
- Node.js with Express
- TypeScript
- REST API architecture
- JWT authentication with refresh tokens
- Role-based access control
- Input validation via Zod or Joi
- Logging with Winston or Pino
- Error handling middleware

### Database
- Primary: PostgreSQL
- Alternative/optional: MongoDB for flexible activity logs or message storing
- ORM: Prisma for PostgreSQL (recommended) or Sequelize
- Database hosting: AWS RDS/Aurora or managed PostgreSQL on AWS

### Hosting & Infrastructure
- Frontend: Vercel
- Backend: AWS Elastic Beanstalk / AWS Fargate / AWS Lambda (API Gateway) or Vercel Serverless Functions
- Database: AWS RDS PostgreSQL
- File storage: AWS S3 for any attachments or bulk CSV exports/imports
- Secrets: AWS Secrets Manager or Vercel environment variables

### Third-Party Services
- Brevo (formerly Sendinblue)
  - WhatsApp Business API integration for mass messages and automation
  - Email transactional automation
  - Template management and event-driven campaigns
- Stripe / Razorpay (optional) for payment collection if required
- Twilio not used; Brevo is the core messaging service

## 3. Architecture

### Logical Layers
1. Presentation (React SPA)
2. API Layer (Express REST endpoints)
3. Business Logic Layer (service modules)
4. Data Access Layer (Prisma ORM)
5. External Integration Layer (Brevo client)

### Key Modules
- Authentication & Authorization
- Client Management
- Interaction Timeline & Reminders
- Payment History
- Bulk Import/Export
- Communication Automation (WhatsApp + Email)
- Reporting and Dashboard
- System Settings and Tags

## 4. Feature Specification

### 4.1 Client Management

#### Core Client Record
Fields:
- `id`
- `name`
- `phone`
- `email`
- `whatsappNumber`
- `company`
- `location` (`Jaipur` default)
- `services` (array of service types such as GST, FSSAI, Incorporation, BIS)
- `status` (`Lead`, `Active`, `Follow-up`)
- `tags` (custom tags)
- `createdAt`
- `updatedAt`
- `ownerId` (user/account manager)
- `notes`

#### UI pages/components
- Client list table with filters: status, service, location, tags
- Client detail view with tabbed sections for profile, timeline, reminders, payments
- Client create/edit drawer or modal
- Quick action buttons: send WhatsApp, send email, add note, schedule reminder

#### Dashboard view
- Timeline of interactions
- Upcoming reminders
- Payment history summary
- Service status insights
- Recent client activity cards

### 4.2 Interaction Timeline

Capture all client-facing events:
- WhatsApp messages sent
- Emails sent
- Calls logged
- Notes added
- Reminders created
- Payment events

Data model:
- `Interaction` with fields: `type`, `subject`, `content`, `clientId`, `userId`, `timestamp`, `meta`
- `Reminder` with fields: `dueDate`, `status`, `clientId`, `createdBy`, `note`

UI:
- Timeline feed on client details
- Filter by type and date
- Create reminder from timeline entry

### 4.3 Payment History

Payment record fields:
- `paymentId`
- `clientId`
- `amount`
- `currency`
- `paymentDate`
- `paymentMethod`
- `serviceType`
- `status`
- `invoiceNumber`
- `notes`

UI:
- Payment history table on client page
- Payment summary card on dashboard
- Exportable payment list

### 4.4 Bulk Import/Export via CSV

Import flow:
- CSV upload page
- Mapping step for CSV columns to fields
- Validation and preview of row results
- Create new client records or update existing ones based on email/phone
- Error report for invalid rows

Export flow:
- Export current client list or selected clients
- Select columns and filters
- Download CSV file

CSV fields supported:
- Name, Email, Phone, WhatsApp, Company, Location, Services, Status, Tags

### 4.5 Communication Automation (Brevo)

#### WhatsApp Mass Messaging
- Create WhatsApp campaigns from scratch
- Send targeted campaigns by status, service, tag, or custom segment
- Use Brevo message templates
- Track success/failure response from Brevo

#### WhatsApp Automation
- Configure automated triggers such as:
  - New lead created
  - Follow-up due
  - Payment reminder
  - Service completion
- Use Brevo templates and variable substitution
- Save automation workflows customized by client segment

#### Email Automation
- Send transactional emails for:
  - New client welcome
  - Document request
  - Payment invoice or receipt
  - Follow-up reminders
- Automated email workflows via Brevo
- Support personalization fields: client name, company, service, next action

#### Brevo Integration Details
- Use Brevo REST API and SDK
- Store Brevo templates IDs and webhook subscriptions
- Maintain message logs in the CRM
- Manage opt-ins for WhatsApp and email
- Use Brevo event webhooks for delivery status and replies

### 4.6 Security & Compliance

- Role-based access: Admin, Manager, Sales, Accountant
- Authentication: email/password, optional 2FA
- Secure session management with JWT
- Data validation and sanitization everywhere
- HTTPS required
- Audit logs for user actions
- Privacy and consent tracking for WhatsApp/email

## 5. Data Models

### 5.1 Prisma schema example

```prisma
model User {
  id String @id @default(uuid())
  email String @unique
  password String
  name String
  role UserRole @default(USER)
  clients Client[]
  interactions Interaction[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

enum UserRole {
  ADMIN
  MANAGER
  SALES
  ACCOUNTANT
}

model Client {
  id String @id @default(uuid())
  name String
  phone String
  email String
  whatsappNumber String?
  company String?
  location String @default("Jaipur")
  services String[]
  status ClientStatus
  tags String[]
  notes String?
  owner User? @relation(fields: [ownerId], references: [id])
  ownerId String?
  interactions Interaction[]
  reminders Reminder[]
  payments Payment[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

enum ClientStatus {
  LEAD
  ACTIVE
  FOLLOW_UP
}

model Interaction {
  id String @id @default(uuid())
  type InteractionType
  subject String?
  content String?
  client Client @relation(fields: [clientId], references: [id])
  clientId String
  user User @relation(fields: [userId], references: [id])
  userId String
  metadata Json?
  createdAt DateTime @default(now())
}

enum InteractionType {
  NOTE
  CALL
  EMAIL
  WHATSAPP
  REMINDER
  PAYMENT
}

model Reminder {
  id String @id @default(uuid())
  client Client @relation(fields: [clientId], references: [id])
  clientId String
  note String
  dueDate DateTime
  status ReminderStatus @default(PENDING)
  createdBy User @relation(fields: [createdById], references: [id])
  createdById String
  createdAt DateTime @default(now())
}

enum ReminderStatus {
  PENDING
  COMPLETED
  CANCELLED
}

model Payment {
  id String @id @default(uuid())
  client Client @relation(fields: [clientId], references: [id])
  clientId String
  amount Float
  currency String @default("INR")
  paymentDate DateTime
  paymentMethod String
  status String
  invoiceNumber String?
  notes String?
  createdAt DateTime @default(now())
}

model BrevoMessageLog {
  id String @id @default(uuid())
  client Client @relation(fields: [clientId], references: [id])
  clientId String
  channel MessageChannel
  templateId String?
  brevoMessageId String?
  status String
  response Json?
  createdAt DateTime @default(now())
}

enum MessageChannel {
  WHATSAPP
  EMAIL
}
```

## 6. API Design

### Authentication
- `POST /api/auth/login`
- `POST /api/auth/refresh`
- `POST /api/auth/logout`
- `GET /api/auth/me`

### Clients
- `GET /api/clients`
- `GET /api/clients/:id`
- `POST /api/clients`
- `PUT /api/clients/:id`
- `DELETE /api/clients/:id`
- `POST /api/clients/bulk-import`
- `GET /api/clients/export`

### Interactions
- `GET /api/clients/:clientId/interactions`
- `POST /api/clients/:clientId/interactions`
- `GET /api/interactions/:id`

### Reminders
- `GET /api/clients/:clientId/reminders`
- `POST /api/clients/:clientId/reminders`
- `PATCH /api/reminders/:id`
- `DELETE /api/reminders/:id`

### Payments
- `GET /api/clients/:clientId/payments`
- `POST /api/clients/:clientId/payments`
- `PATCH /api/payments/:id`
- `GET /api/payments/export`

### Brevo Messaging
- `POST /api/brevo/whatsapp/send`
- `POST /api/brevo/whatsapp/bulk-send`
- `POST /api/brevo/email/send`
- `POST /api/brevo/email/automation`
- `POST /api/brevo/webhook`
- `GET /api/brevo/templates`

### Reports & Dashboard
- `GET /api/dashboard/overview`
- `GET /api/dashboard/activity`
- `GET /api/dashboard/payments`

## 7. Frontend Pages

- Login / Authentication
- Dashboard / Home
- Client Directory
- Client Detail
- Create/Edit Client
- Reminders / Follow-up Calendar
- Payment History / Invoices
- Messaging Console (WhatsApp / Email)
- Automation and Workflows
- Import / Export Wizard
- Settings (User management, tags, services, Brevo config)

## 8. Brevo Integration Workflow

### Setup
- Store Brevo API key securely in backend environment
- Configure WhatsApp sender and email sender profiles in Brevo
- Map CRM client fields to Brevo template variables

### Mass WhatsApp Messaging
1. Select target segment by status, service, tags, date
2. Choose Brevo template or custom message
3. Send via backend `/api/brevo/whatsapp/bulk-send`
4. Save log records in CRM
5. Track delivery and responses by webhook

### WhatsApp Automation
1. Define trigger conditions in CRM
2. Build rule with template IDs and delay settings
3. Execute automatically when event occurs
4. Update client interaction timeline with automation status

### Email Automation
1. Create email sequences for onboarding, reminders, invoices
2. Use Brevo email templates and personalization
3. Dispatch from backend and record in timeline
4. Monitor open/click/delivery via Brevo webhook events

## 9. Non-Functional Requirements

- UI must be responsive and mobile-friendly
- System should support at least 1,000 active clients initially
- API latency target < 200ms for standard operations
- Audit trail and activity logging enabled
- Secure deployment with HTTPS, CORS, rate limiting
- Role-based access control enforced on all resources

## 10. Development Roadmap

### Phase 1: Foundation (Weeks 1-2)
- Project scaffolding for frontend and backend
- Authentication, authorization, and user management
- Database schema design and migrations
- Basic client CRUD
- Client directory and client detail UI
- Initial API routes and testing

### Phase 2: Client Lifecycle & Data
- Interaction timeline and notes
- Reminders module with calendar view
- Payment history model and UI
- Bulk import/export CSV workflows
- Tagging, services, and status filters

### Phase 3: Brevo Messaging Integration
- Brevo API client implementation
- Email send + transactional log
- WhatsApp single and bulk messaging flows
- Webhook listeners for delivery events
- Message history on client timeline

### Phase 4: Automation & Campaigns
- Build automation rule engine and UI
- Campaign builder for WhatsApp and email
- Scheduled reminders and payment follow-up automation
- Template management and personalization

### Phase 5: Reporting & Polish
- Dashboard widgets and KPI cards
- Reports for services, lead conversion, payments
- UI polish, accessibility, and responsive design
- Performance optimization and caching
- QA, security review, and documentation

### Phase 6: Deployment & Launch
- Deploy frontend to Vercel
- Deploy backend to AWS (Fargate / Elastic Beanstalk / Lambda)
- Configure PostgreSQL on AWS RDS
- Set up environment variables and secrets
- Setup Brevo production keys
- Rollout plan and training materials

## 11. Optional Enhancements

- Mobile app wrapper (React Native) for field staff
- Invoice generation / PDF export
- Payment gateway integration (Stripe, Razorpay)
- Customer portal for document exchange
- AI-assisted response suggestions for WhatsApp replies
- Multi-team support and audit approval flows

## 12. Implementation Notes

- Prefer `Prisma` for database migrations and type-safe queries.
- Use `React Query` for efficient caching and background refresh.
- Keep Brevo credentials only on the backend.
- Store message logs and automation events to ensure auditability.
- Keep the client detail page minimal and split into tabs for performance.
- Use reusable React UI components for forms, tables, modals, and cards.

## 13. Success Metrics

- Client creation and lookup latency under 300ms
- 95% of core client management flows completeable in 3 clicks
- Reliable WhatsApp/email delivery tracking across all campaigns
- Export/import error rate under 2% for valid CSV files
- Post-launch support for ongoing feature refinement

---

This specification provides the structure, data model, API endpoints, and development sequence needed to build a custom CRM for a taxation service business using React, Node.js/Express, PostgreSQL, and Brevo for WhatsApp and email automation. The implementation can be adapted to MongoDB for flexible activity recording if a document model is preferred, but PostgreSQL is recommended for structured client and payment data.