# MODAVA Business Flows

This document outlines the key business flows in the MODAVA platform, showing the sequence of API endpoints and business logic required to complete each process.

## 1. User Onboarding Flow

### 1.1 User Registration & Vendor Creation
**Flow:** New user registration → Vendor profile creation → Onboarding completion

**Endpoints in sequence:**
1. `POST /api/auth/signup`
   - Creates Supabase auth user
   - Automatically creates vendor profile
   - Returns session tokens
   - **Response:** User + Vendor + Access/Refresh tokens

2. `GET /api/auth/profile`
   - Verify user session
   - Get complete user + vendor data
   - **Response:** Current user profile

3. `POST /api/vendors/onboarding`
   - Complete business profile setup
   - Update onboarding status
   - **Response:** Updated vendor profile

**Business Logic:**
- User account created with 'vendor' role
- Vendor profile created with 'incomplete' onboarding status
- Default subscription plan: 'free'
- Automatic session generation after signup

**Error Handling:**
- Email already exists → 409 Conflict
- Invalid business data → 400 Bad Request
- Onboarding failure → 500 Internal Server Error

### 1.2 KYC Submission (Optional)
**Flow:** KYC document upload → Admin review → Approval/Rejection

**Endpoints in sequence:**
1. `POST /api/kyc/submit`
   - Upload KYC documents
   - Set status to 'pending'
   - **Response:** KYC submission created

2. `GET /api/kyc/status` (vendor)
   - Check KYC review status
   - **Response:** Current KYC status

3. `GET /api/kyc/admin/pending` (admin)
   - Admin views pending submissions
   - **Response:** List of pending KYC submissions

4. `POST /api/kyc/admin/:vendorId/review` (admin)
   - Admin approves/rejects KYC
   - Updates vendor KYC status
   - **Response:** Review decision

**Business Logic:**
- KYC required for certain subscription plans
- Admin review process for compliance
- Vendor status updated based on KYC outcome

## 2. Customer Management Flow

### 2.1 Customer Lifecycle
**Flow:** Customer creation → Profile management → Measurements → CRM

**Endpoints in sequence:**
1. `POST /api/customers`
   - Create new customer or link existing
   - **Response:** Customer profile created

2. `GET /api/customers`
   - List all customers with search/filter
   - **Response:** Array of customer profiles

3. `GET /api/customers/:customerId`
   - View customer details
   - **Response:** Complete customer profile

4. `PUT /api/customers/:customerId`
   - Update customer information
   - **Response:** Updated customer profile

5. `POST /api/customers/:customerId/measurements`
   - Add/update customer measurements
   - **Response:** Updated measurements

6. `DELETE /api/customers/:customerId`
   - Unlink customer (soft delete)
   - **Response:** Success confirmation

**Business Logic:**
- Feature gate: `customer_management` required
- Vendor isolation enforced via RLS
- Customer measurements stored separately
- Soft delete maintains data integrity

**Error Handling:**
- Feature not available → 403 Forbidden
- Customer not found → 404 Not Found
- Invalid data → 400 Bad Request

### 2.2 Customer Flagging System
**Flow:** Flag creation → Admin review → Global flag application

**Business Logic:**
- Vendors can flag problematic customers
- Admin review required for global flags
- Flagged customers visible across vendors
- Evidence/proof required for flags

## 3. Invoice Management Flow

### 3.1 Invoice Creation & Management
**Flow:** Invoice creation → Customer assignment → Payment processing → Status tracking

**Endpoints in sequence:**
1. `POST /api/invoices`
   - Create new invoice
   - Assign to customer
   - **Response:** Invoice created

2. `GET /api/invoices`
   - List vendor invoices
   - **Response:** Array of invoices

3. `GET /api/invoices/:id/download`
   - Download PDF invoice
   - **Response:** PDF file

4. `POST /api/invoices/:id/mark-paid`
   - Webhook: Mark invoice as paid
   - **Response:** Payment confirmation

5. `GET /api/invoices/transactions`
   - View payment history
   - **Response:** Transaction list

6. `DELETE /api/invoices/:id`
   - Cancel/delete invoice
   - **Response:** Success confirmation

**Business Logic:**
- Feature gate: `invoicing_enabled` required
- Public invoice viewing via unique codes
- Payment webhook integration
- PDF generation for invoices

**Error Handling:**
- Feature not available → 403 Forbidden
- Invoice not found → 404 Not Found
- Invalid invoice data → 400 Bad Request

### 3.2 Payment Processing
**Flow:** Payment link generation → Customer payment → Webhook confirmation → Status update

**Business Logic:**
- Payment links generated per invoice
- Webhook security (signature verification needed)
- Payment status tracking
- Transaction history maintenance

## 4. Reminder & CRM Flow

### 4.1 Reminder Management
**Flow:** Reminder creation → Scheduling → Sending → Engagement tracking

**Endpoints in sequence:**
1. `POST /api/reminders/create`
   - Create reminder message
   - Set schedule and customer
   - **Response:** Reminder created

2. `GET /api/reminders/list`
   - View all reminders
   - **Response:** Array of reminders

3. `POST /api/reminders/send/:id`
   - Send reminder immediately
   - **Response:** Send confirmation

**Business Logic:**
- Feature gate: `reminders` required
- AI-generated reminder suggestions
- Customer-specific messaging
- Scheduled sending capability

**Error Handling:**
- Feature not available → 403 Forbidden
- Reminder not found → 404 Not Found
- Send failure → 500 Internal Server Error

### 4.2 Customer Engagement
**Flow:** Reminder scheduling → Message delivery → Response tracking → Follow-up

**Business Logic:**
- Personalized reminder messages
- Time-based scheduling
- Customer response tracking
- Automated follow-up sequences

## 5. Subscription Management Flow

### 5.1 Plan Selection & Activation
**Flow:** Plan browsing → Trial activation → Plan upgrade → Feature access

**Endpoints in sequence:**
1. `GET /api/subscriptions/plans`
   - View available plans
   - **Response:** Array of subscription plans

2. `GET /api/subscriptions/trial-offer`
   - Check trial availability
   - **Response:** Trial offer details

3. `POST /api/subscriptions/accept-trial`
   - Activate trial period
   - **Response:** Trial activated

4. `POST /api/subscriptions/activate`
   - Upgrade to paid plan
   - **Response:** Plan activated

5. `GET /api/subscriptions/my-plan`
   - View current subscription
   - **Response:** Current plan details

6. `GET /api/subscriptions/my-features`
   - Check available features
   - **Response:** Feature list

**Business Logic:**
- Trial periods for new users
- Plan-based feature access
- Automatic feature gate enforcement
- Subscription status tracking

**Error Handling:**
- Trial not available → 400 Bad Request
- Plan activation failure → 500 Internal Server Error
- Invalid plan selection → 400 Bad Request

### 5.2 Feature Access Control
**Flow:** Feature check → Plan validation → Access grant/deny

**Business Logic:**
- Middleware-level feature gates
- Plan-based feature restrictions
- Dynamic feature availability
- Upgrade prompts for restricted features

## 6. Market Pricing Flow

### 6.1 Price Contribution
**Flow:** Market research → Price submission → Admin review → Market data

**Endpoints in sequence:**
1. `POST /api/market-prices`
   - Submit market price
   - **Response:** Price report created

2. `GET /api/market-prices`
   - View market prices
   - **Response:** Array of price reports

3. `GET /api/market-prices/suggestions`
   - Get price recommendations
   - **Response:** Price suggestions

**Business Logic:**
- Vendor price contributions
- Market data aggregation
- Price trend analysis
- Admin approval process

### 6.2 Pricing Agent Management
**Flow:** Agent application → Admin review → Access grant → Contribution tracking

**Endpoints in sequence:**
1. `PATCH /api/market-prices/admin/users/:id/pricing-access` (admin)
   - Grant/revoke pricing access
   - **Response:** Access updated

**Business Logic:**
- Admin control over pricing agents
- Contribution quality monitoring
- Access level management
- Performance tracking

## 7. Admin Management Flow

### 7.1 User Administration
**Flow:** Admin creation → Permission management → User monitoring → Support

**Endpoints in sequence:**
1. `POST /api/admin/users` (admin)
   - Create admin user
   - **Response:** Admin user created

2. `PATCH /api/admin/users/:id/permissions` (admin)
   - Update user permissions
   - **Response:** Permissions updated

3. `GET /api/admin/users` (admin)
   - List admin users
   - **Response:** Array of admin users

4. `POST /api/admin/impersonate` (admin)
   - Impersonate user for debugging
   - **Response:** Impersonation session

**Business Logic:**
- Role-based access control
- Permission hierarchy
- User activity monitoring
- Debugging capabilities

### 7.2 System Administration
**Flow:** Settings management → Feature control → Monitoring → Maintenance

**Endpoints in sequence:**
1. `GET /api/admin/settings` (admin)
   - View system settings
   - **Response:** Current settings

2. `PATCH /api/admin/settings` (admin)
   - Update system configuration
   - **Response:** Settings updated

3. `PATCH /api/admin/feature-flags` (admin)
   - Control feature availability
   - **Response:** Feature flags updated

4. `GET /api/admin/logs` (admin)
   - View system logs
   - **Response:** System log data

5. `GET /api/admin/audit-trail` (admin)
   - View audit trail
   - **Response:** Audit data

**Business Logic:**
- System configuration management
- Feature flag control
- Logging and monitoring
- Compliance tracking

## 8. Support & Maintenance Flow

### 8.1 Support Ticket Management
**Flow:** Ticket creation → Admin assignment → Resolution → Closure

**Endpoints in sequence:**
1. `GET /api/admin/support-tickets` (admin)
   - View support tickets
   - **Response:** Array of tickets

2. `PATCH /api/admin/support-tickets/:id` (admin)
   - Update ticket status
   - **Response:** Ticket updated

**Business Logic:**
- Ticket lifecycle management
- Admin assignment and tracking
- Resolution documentation
- Customer satisfaction tracking

### 8.2 System Monitoring
**Flow:** Health checks → Performance monitoring → Alert generation → Maintenance

**Endpoints in sequence:**
1. `GET /health`
   - System health check
   - **Response:** System status

**Business Logic:**
- Continuous health monitoring
- Performance metrics collection
- Automated alerting
- Preventive maintenance scheduling

## 9. Data Export & Reporting Flow

### 9.1 Business Intelligence
**Flow:** Data collection → Analysis → Report generation → Export

**Business Logic:**
- Customer analytics
- Revenue tracking
- Usage statistics
- Performance metrics

### 9.2 Compliance & Auditing
**Flow:** Data logging → Audit trail → Compliance checking → Reporting

**Business Logic:**
- Comprehensive audit logging
- Compliance monitoring
- Data retention policies
- Regulatory reporting

## 10. Integration & Webhook Flow

### 10.1 Payment Integration
**Flow:** Payment initiation → Provider processing → Webhook confirmation → Status update

**Business Logic:**
- Payment provider integration
- Webhook signature verification
- Transaction reconciliation
- Error handling and retries

### 10.2 Third-party Integrations
**Flow:** API authentication → Data synchronization → Event handling → Response processing

**Business Logic:**
- OAuth authentication
- Rate limiting compliance
- Data format transformation
- Error handling and logging

## UNKNOWN Areas

The following business flows are referenced but not fully documented:

- **Shopping List Management**: Endpoints exist but flow not detailed
- **Inventory Management**: Schema exists but API endpoints unclear
- **Order Processing**: E-commerce flow not implemented
- **Referral System**: Bonus calculation and distribution unclear
- **Contributor Program**: Discount application and tracking unclear

**File paths to investigate:**
- `src/modules/shoppinglists/`
- `src/modules/withdrawals/`
- `src/modules/consultations/`
- `src/modules/ai/`
- `src/modules/greetings/`
- `src/modules/notifications/`
