# MR App Backend API Documentation

## Overview
This document provides comprehensive API documentation for the MR App Backend, covering all controllers and routes for franchise management, brand management, product management, order management, biller management, and dashboard analytics.

## Base URL
```
http://localhost:5000/api
```

## Authentication
All routes (except auth routes) require authentication. Include the JWT token in the Authorization header:
```
Authorization: Bearer <your-jwt-token>
```

---

## 1. Franchise Management

### Base Path: `/franchises`

#### Get All Franchises
- **GET** `/franchises`
- **Query Parameters:**
  - `page` (default: 1) - Page number
  - `limit` (default: 10) - Items per page
  - `search` - Search in name, code, email, or POC name
  - `city` - Filter by city
  - `state` - Filter by state
  - `isActive` - Filter by active status
  - `brand` - Filter by assigned brand
  - `division` - Filter by assigned division
  - `sortBy` (default: createdAt) - Sort field
  - `sortOrder` (default: desc) - Sort direction

#### Get Franchise by ID
- **GET** `/franchises/:id`

#### Create New Franchise
- **POST** `/franchises`
- **Body:** Franchise data including name, logo, POC details, address, GSTIN, etc.

#### Update Franchise
- **PUT** `/franchises/:id`
- **Body:** Updated franchise data

#### Delete Franchise
- **DELETE** `/franchises/:id`

#### Bulk Import Franchises
- **POST** `/franchises/bulk-import`
- **Body:** Excel file upload
- **Headers:** `Content-Type: multipart/form-data`

#### Franchise Alias Management
- **POST** `/franchises/:franchiseId/aliases` - Create alias user
- **PUT** `/franchises/:franchiseId/aliases/:aliasId` - Update alias user
- **DELETE** `/franchises/:franchiseId/aliases/:aliasId` - Delete alias user

#### Statistics
- **GET** `/franchises/stats/overview` - Get franchise statistics

#### Assignments
- **POST** `/franchises/:franchiseId/assign-brands` - Assign brands to franchise
- **POST** `/franchises/:franchiseId/assign-divisions` - Assign divisions to franchise

---

## 2. Company Management

### Base Path: `/brands`

#### Get All Brands
- **GET** `/brands`
- **Query Parameters:**
  - `page` (default: 1) - Page number
  - `limit` (default: 10) - Items per page
  - `search` - Search in name, code, or description
  - `isActive` - Filter by active status
  - `sortBy` (default: createdAt) - Sort field
  - `sortOrder` (default: desc) - Sort direction

#### Get Company by ID
- **GET** `/brands/:id`

#### Create New Company
- **POST** `/brands`
- **Body:** Company data including name, description, logo, etc.

#### Update Company
- **PUT** `/brands/:id`
- **Body:** Updated brand data

#### Delete Company
- **DELETE** `/brands/:id`

#### Bulk Import Brands
- **POST** `/brands/bulk-import`
- **Body:** Excel file upload
- **Headers:** `Content-Type: multipart/form-data`

#### Statistics
- **GET** `/brands/stats/overview` - Get brand statistics

#### Division Management
- **POST** `/brands/:brandId/divisions` - Add division to brand
- **PUT** `/brands/:brandId/divisions/:divisionId` - Update division
- **DELETE** `/brands/:brandId/divisions/:divisionId` - Remove division
- **GET** `/brands/:brandId/divisions` - Get divisions by brand
- **GET** `/brands/divisions/all` - Get all divisions across brands

#### Franchise Assignment
- **POST** `/brands/:brandId/assign-franchises` - Assign franchises to brand

---

## 3. Product Management

### Base Path: `/products`

#### Get All Products
- **GET** `/products`
- **Query Parameters:**
  - `page` (default: 1) - Page number
  - `limit` (default: 10) - Items per page
  - `search` - Search in name, code, description, or category
  - `brand` - Filter by brand
  - `division` - Filter by division
  - `category` - Filter by category
  - `subcategory` - Filter by subcategory
  - `specialty` - Filter by specialty
  - `formulation` - Filter by formulation
  - `strength` - Filter by strength
  - `packSize` - Filter by pack size
  - `formFactor` - Filter by form factor
  - `isActive` - Filter by active status
  - `isNew` - Filter by new product flag
  - `stockStatus` - Filter by stock status
  - `sortBy` (default: createdAt) - Sort field
  - `sortOrder` (default: desc) - Sort direction

#### Get Product by ID
- **GET** `/products/:id`

#### Create New Product
- **POST** `/products`
- **Body:** Product data including name, description, brand, category, variants, etc.

#### Update Product
- **PUT** `/products/:id`
- **Body:** Updated product data

#### Delete Product
- **DELETE** `/products/:id`

#### Bulk Import Products
- **POST** `/products/bulk-import`
- **Body:** Excel file upload
- **Headers:** `Content-Type: multipart/form-data`

#### Categories and Filters
- **GET** `/products/categories/all` - Get all product categories and filter options

#### Statistics
- **GET** `/products/stats/overview` - Get product statistics

#### Variant Management
- **POST** `/products/:productId/variants` - Add variant to product
- **PUT** `/products/:productId/variants/:variantId` - Update variant
- **DELETE** `/products/:productId/variants/:variantId` - Remove variant

#### Media Management
- **POST** `/products/:productId/media` - Add media to product
- **PUT** `/products/:productId/media/:mediaId/primary` - Set primary image

#### Product Flags and Status
- **PATCH** `/products/:id/new-flag` - Toggle new product flag
- **PATCH** `/products/:id/stock-status` - Update stock status

#### Mobile App Routes
- **GET** `/products/franchise/:franchiseId` - Get products by franchise (for mobile app)

---

## 4. Order Management

### Base Path: `/orders`

#### Get All Orders
- **GET** `/orders`
- **Query Parameters:**
  - `page` (default: 1) - Page number
  - `limit` (default: 10) - Items per page
  - `search` - Search in order number, franchise name, or product name
  - `franchise` - Filter by franchise
  - `brand` - Filter by brand
  - `division` - Filter by division
  - `status` - Filter by order status
  - `assignedBiller` - Filter by assigned biller
  - `orderDate` - Filter by order date
  - `priority` - Filter by priority
  - `source` - Filter by source
  - `sortBy` (default: orderDate) - Sort field
  - `sortOrder` (default: desc) - Sort direction

#### Get Order by ID
- **GET** `/orders/:id`

#### Create New Order
- **POST** `/orders`
- **Body:** Order data including franchise, brand, division, items, etc.

#### Update Order
- **PUT** `/orders/:id`
- **Body:** Updated order data

#### Delete Order
- **DELETE** `/orders/:id`

#### Update Order Status
- **PATCH** `/orders/:id/status`
- **Body:** `{ "status": "new_status", "remarks": "optional_remarks" }`

#### Order Items Management
- **POST** `/orders/:orderId/items` - Add item to order
- **PUT** `/orders/:orderId/items/:itemId` - Update item in order
- **DELETE** `/orders/:orderId/items/:itemId` - Remove item from order

#### Biller Assignment
- **POST** `/orders/:orderId/assign-biller`
- **Body:** `{ "billerId": "biller_id" }`

#### Statistics
- **GET** `/orders/stats/overview` - Get order statistics

#### Specialized Routes
- **GET** `/orders/franchise/:franchiseId` - Get orders by franchise (for mobile app)
- **GET** `/orders/biller/:billerId` - Get orders by biller
- **GET** `/orders/division/:divisionId` - Get orders by division

---

## 5. Biller Management

### Base Path: `/billers`

#### Get All Billers
- **GET** `/billers`
- **Query Parameters:**
  - `page` (default: 1) - Page number
  - `limit` (default: 10) - Items per page
  - `search` - Search in employee code
  - `isActive` - Filter by active status
  - `sortBy` (default: createdAt) - Sort field
  - `sortOrder` (default: desc) - Sort direction

#### Get Biller by ID
- **GET** `/billers/:id`

#### Create New Biller
- **POST** `/billers`
- **Body:** Biller data including user reference, employee code, etc.

#### Update Biller
- **PUT** `/billers/:id`
- **Body:** Updated biller data

#### Delete Biller
- **DELETE** `/billers/:id`

#### Statistics
- **GET** `/billers/stats/overview` - Get biller statistics

#### Assignment Management
- **POST** `/billers/:billerId/assignments` - Add assignment to biller
- **PUT** `/billers/:billerId/assignments/:assignmentId` - Update assignment
- **DELETE** `/billers/:billerId/assignments/:assignmentId` - Remove assignment

#### Performance and Workload
- **GET** `/billers/:billerId/performance` - Get biller performance metrics
- **PATCH** `/billers/:billerId/workload` - Update biller workload

#### Assignment Queries
- **GET** `/billers/available/list` - Get available billers for assignment
- **GET** `/billers/brand/:brandId/assignments` - Get biller assignments by brand

#### Bulk Operations
- **POST** `/billers/bulk-assign` - Bulk assign billers to brands/divisions

---

## 6. Dashboard Analytics

### Base Path: `/dashboard`

#### Overview Metrics
- **GET** `/dashboard/overview` - Get dashboard overview with counts and recent activity

#### Sales Analytics
- **GET** `/dashboard/analytics/sales`
- **Query Parameters:**
  - `period` (default: month) - Time period (week, month, quarter, year)
  - `startDate` - Custom start date
  - `endDate` - Custom end date

#### Franchise Analytics
- **GET** `/dashboard/analytics/franchises` - Get franchise performance and distribution data

#### Product Analytics
- **GET** `/dashboard/analytics/products` - Get product performance and category data

#### Order Analytics
- **GET** `/dashboard/analytics/orders` - Get order trends and status distribution

#### Biller Analytics
- **GET** `/dashboard/analytics/billers` - Get biller performance and workload data

#### Real-time Metrics
- **GET** `/dashboard/realtime` - Get real-time metrics for today and current activity

---

## 7. Authentication & User Management

### Base Path: `/auth` and `/users`

#### Authentication
- **POST** `/auth/login` - User login
- **POST** `/auth/register` - User registration
- **POST** `/auth/refresh` - Refresh JWT token
- **POST** `/auth/logout` - User logout

#### User Management
- **GET** `/users` - Get all users (Super Admin only)
- **GET** `/users/:id` - Get user by ID
- **POST** `/users` - Create new user
- **PUT** `/users/:id` - Update user
- **DELETE** `/users/:id` - Delete user
- **PATCH** `/users/:id/status` - Toggle user active status
- **POST** `/users/:id/roles` - Assign roles to user

---

## Data Models

### Franchise Fields
- `name` - Franchise Name
- `logo` - Franchise Logo
- `contactPerson.name` - POC Name
- `contactPerson.phone` - POC Number
- `contactPerson.photo` - POC Photo
- `contactPerson.email` - POC Email ID
- `address` - Complete address object
- `businessDetails.gstNumber` - GSTIN
- `businessDetails.licenseNumber` - Drug License Number
- `assignedDistricts` - Assigned Districts
- `partnershipDeed` - Partnership Deed
- `isActive` - Is Active status
- `assignedBrands` - Brands Assigned
- `assignedDivisions` - Divisions Assigned
- `aliasUsers` - Franchise alias users (name, username, password)

### Company Fields
- `name` - Company Name
- `code` - Company Code
- `description` - Company Description
- `logo` - Company Logo
- `divisions` - Array of divisions within brand
- `assignedFranchises` - Franchises assigned to brand
- `isActive` - Active status

### Product Fields
- `name` - Product Name
- `code` - Product Code
- `description` - Product Description
- `brand` - Company reference
- `division` - Division reference
- `category` - Product Category
- `subcategory` - Product Subcategory
- `specialty` - Medical Specialty
- `formulation` - Formulation Type
- `strength` - Product Strength
- `packSize` - Pack Size
- `formFactor` - Form Factor
- `mrp` - Maximum Retail Price
- `variants` - Product variants array
- `media` - Product media array (images, videos)
- `stockStatus` - In Stock/Out of Stock
- `isNew` - New product flag
- `isActive` - Active status

### Order Fields
- `orderNumber` - Unique order number
- `franchise` - Franchise reference
- `brand` - Company reference
- `division` - Division reference
- `items` - Order items array
- `status` - Order status (pending, confirmed, processing, shipped, delivered, cancelled)
- `totalAmount` - Total order amount
- `assignedBiller` - Assigned biller reference
- `statusHistory` - Status change history
- `isEditable` - Whether order can be edited

### Biller Fields
- `user` - User reference
- `employeeCode` - Employee code
- `assignments` - Company/division/franchise assignments
- `performanceMetrics` - Performance tracking
- `workload` - Workload management
- `isActive` - Active status

---

## Error Handling

All API endpoints return consistent error responses:

```json
{
  "message": "Error description"
}
```

Common HTTP status codes:
- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized
- `404` - Not Found
- `500` - Internal Server Error

---

## File Upload

For bulk import operations, use multipart/form-data with the file field named 'file'.

Supported file formats:
- Excel files (.xlsx, .xls)

---

## Pagination

List endpoints support pagination with the following response format:

```json
{
  "data": [...],
  "totalPages": 10,
  "currentPage": 1,
  "total": 100
}
```

---

## Search and Filtering

Most list endpoints support:
- Text search across relevant fields
- Status filtering
- Date range filtering
- Relationship filtering (brand, division, franchise)
- Sorting by various fields
- Pagination

---

## Mobile App Support

Special routes are provided for mobile app functionality:
- Franchise-specific product listings
- Franchise-specific order management
- Optimized data structures for mobile consumption

---

## Performance Considerations

- All list endpoints support pagination
- Database indexes are optimized for common queries
- Aggregation pipelines are used for analytics
- Real-time metrics are cached where appropriate

---

## Security Features

- JWT-based authentication
- Role-based access control
- Input validation and sanitization
- Rate limiting
- CORS configuration
- Helmet security headers

---

This API provides a comprehensive backend solution for the MR App, supporting both admin panel and mobile app requirements with robust data management, analytics, and user management capabilities.
