# Bharat Seva Backend - System Manual

## Table of Contents
1. [System Overview](#system-overview)
2. [Architecture](#architecture)
3. [Technology Stack](#technology-stack)
4. [User Types & Roles](#user-types--roles)
5. [Authentication Flow](#authentication-flow)
6. [Core Modules](#core-modules)
7. [Data Flow](#data-flow)
8. [API Endpoints Structure](#api-endpoints-structure)
9. [Database Models](#database-models)
10. [Key Services](#key-services)
11. [Business Processes](#business-processes)
12. [Configuration](#configuration)

---

## System Overview

**Bharat Seva** is a vendor marketplace platform designed to connect service providers (vendors) with customers seeking their services. The backend is built as a REST API using Laravel 12 with JWT-based authentication.

### Core Purpose
- Enable vendors to register, manage their business profile, and list products/services
- Allow customers to discover vendors and request quotes
- Provide admin controls for KYC verification and platform management
- Generate QR codes for business verification
- Manage inventory and subscriptions

---

## Architecture

### High-Level Architecture Diagram

```
┌─────────────────────────────────────────────────────────────┐
│                     Client Applications                      │
│              (Mobile App / Web Frontend)                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     │ HTTP/REST
                     ▼
┌─────────────────────────────────────────────────────────────┐
│                   API Gateway                                │
│              (JWT Authentication)                            │
└────────────────────┬────────────────────────────────────────┘
                     │
        ┌────────────┼────────────┬──────────────────┐
        │            │            │                  │
        ▼            ▼            ▼                  ▼
   ┌────────┐  ┌──────────┐  ┌────────┐      ┌──────────────┐
   │  Auth  │  │ Vendor   │  │Customer│      │Admin/Master  │
   │ Module │  │ Business │  │ Module │      │    Data      │
   └────────┘  └──────────┘  └────────┘      └──────────────┘
        │            │            │                  │
        └────────────┼────────────┴──────────────────┘
                     │
                     ▼
        ┌────────────────────────────────┐
        │    Service Layer               │
        │  (Business Logic)              │
        └────────────────────────────────┘
                     │
        ┌────────────┼───────────────────┐
        │            │                   │
        ▼            ▼                   ▼
    ┌────────┐  ┌──────────┐       ┌──────────┐
    │Database│  │Firebase  │       │External  │
    │        │  │(Notif)   │       │Services  │
    └────────┘  └──────────┘       │(OpenAI)  │
                                   └──────────┘
```

### Layer Structure
- **Controller Layer**: Handles HTTP requests and responses
- **Service Layer**: Contains business logic and data processing
- **Model Layer**: Represents database tables using Eloquent ORM
- **Helper Layer**: Utility functions and common operations
- **Middleware Layer**: Request validation, authentication, logging

---

## Technology Stack

### Backend Framework
- **Laravel 12**: Web application framework
- **PHP 8.2+**: Server-side language

### Authentication
- **JWT (JSON Web Tokens)**: `php-open-source-saver/jwt-auth` v2.8
- **Token-based authentication** for API requests

### Database
- **MySQL/MariaDB**: Primary data storage
- **Eloquent ORM**: Database abstraction layer
- **Migrations**: Database schema versioning

### External Services
- **Firebase**: Push notifications and real-time messaging
- **OpenAI**: AI-powered features
- **MSG91**: SMS/OTP delivery service

### Additional Libraries
- **Intervention Image**: Image manipulation and resizing
- **Maatwebsite Excel**: Excel file import/export (Product bulk upload)
- **Simple QRCode**: QR code generation for business verification
- **Yajra DataTables**: Server-side data table processing
- **Jenssegers Agent**: User agent detection

---

## User Types & Roles

### 1. **Vendor**
- Registers business on the platform
- Manages business profile and KYC documents
- Lists products/services
- Receives and manages leads
- Views analytics (QR scans, engagement)
- Manages inventory
- Responds to RFQs (Request For Quotation)

### 2. **Customer**
- Registers on the platform
- Searches and discovers vendors
- Views vendor details via QR code verification
- Requests quotes through RFQ
- Manages subscription

### 3. **Admin**
- System administrator functions
- Verifies vendor KYC documents
- Manages business categories and master data
- Controls roles and permissions (UAC)
- Manages activity logs
- Handles referral programs

---

## Authentication Flow

### OTP-Based Registration & Login

```
┌─────────────────────────────────────────────────────────┐
│                   User Initiates Login                   │
└─────────────────┬───────────────────────────────────────┘
                  │
                  ▼
      ┌──────────────────────────┐
      │  User Enters Phone/Email │
      └──────────────┬───────────┘
                     │
                     ▼
        ┌────────────────────────────────┐
        │  Generate OTP (via MSG91)       │
        │  Send OTP to User's Number     │
        └────────────────┬───────────────┘
                         │
                         ▼
          ┌──────────────────────────┐
          │ User Enters OTP          │
          └──────────┬───────────────┘
                     │
                     ▼
        ┌────────────────────────────────┐
        │ Verify OTP                      │
        │ Create/Update User Record       │
        └────────────────┬───────────────┘
                         │
                         ▼
        ┌────────────────────────────────┐
        │ Generate JWT Token              │
        │ Return Token to Client          │
        └────────────────────────────────┘
```

### Endpoint Flow
1. **Generate OTP**: `POST /v1/generate-otp`
   - Input: Email or phone number
   - Output: OTP sent to user

2. **Verify OTP**: `POST /v1/verify-otp`
   - Input: Email/phone + OTP
   - Output: JWT token

3. **Token Refresh**: `POST /v1/auth/refresh`
   - Input: Current JWT token
   - Output: New JWT token

4. **User Profile**: `GET /v1/auth/me`
   - Returns: Current authenticated user data

### Vendor Registration Flow

```
POST /v1/auth/vendor/register
│
├─ Email verification link sent
│
└─ User clicks verification link
   │
   └─ Email verified in database
```

### Customer Registration Flow

```
POST /v1/auth/customer/register
│
├─ Email verification link sent
│
└─ Customer can proceed after verification
```

---

## Core Modules

### 1. **Authentication Module** (`App\Http\Controllers\Api\Auth`)
**Responsibility**: Manages user login, registration, and token operations

**Key Classes**:
- `AuthController`: Main authentication controller
- `AuthService`: Authentication business logic

**Key Methods**:
- `login()`: User login with credentials
- `logout()`: Token invalidation
- `refresh()`: Token refresh
- `generateOtp()`: OTP generation
- `verifyOtp()`: OTP verification
- `customerRegister()`: Customer registration
- `customerverifyEmail()`: Email verification for customers

---

### 2. **Vendor Business Module** (`App\Http\Controllers\Api\VendorBusiness`)
**Responsibility**: Manages vendor business profiles, KYC, products, and operations

**Key Controllers**:
- `VendorBusinessController`: Main vendor business operations
- `ProductDetailController`: Product management
- `RfqController`: Request For Quotation management

**Key Endpoints**:

#### Business Registration
- `POST /v1/vendor/business/register` - Initial business registration
- `POST /v1/vendor/business/details` - Business details
- `POST /v1/vendor/business/operating-hours` - Operating hours
- `POST /v1/vendor/business/serviceable-regions` - Service regions
- `POST /v1/vendor/business/social-links` - Social media links
- `POST /v1/vendor/business/government-id-registration` - Gov ID
- `POST /v1/vendor/business/bank-details` - Banking information

#### Business Information Retrieval
- `GET /v1/vendor/business/{id}/details` - Get business details
- `GET /v1/vendor/business/{id}/staff` - Get staff information
- `GET /v1/vendor/business/{id}/products` - Get business products
- `GET /v1/vendor/kyc-summary/{businessId}` - KYC verification summary
- `GET /v1/vendor/kyc/{businessId}` - KYC detailed data

#### Lead Management
- `GET /v1/vendor/leads` - Retrieve all vendor leads
- `POST /v1/vendor/leads/{leadId}/accept` - Accept a lead
- `POST /v1/vendor/leads/{leadId}/reject` - Reject a lead

#### Product Management
- `POST /v1/vendor/add/product-details` - Add product
- `POST /v1/vendor/edit/{id}/product-details` - Edit product
- `GET /v1/vendor/get-all/product` - Get all products
- `GET /v1/vendor/get-by-id/{id}/product` - Get product by ID
- `POST /v1/vendor/delete/{id}/product` - Delete product
- `POST /v1/vendor/products/bulk-upload` - Bulk product upload via Excel

#### RFQ Management
- `POST /v1/vendor/rfq/store` - Store RFQ
- `GET /v1/vendor/rfqs` - Get all RFQs

#### Dashboard & Analytics
- `GET /v1/vendor/dashboard` - Dashboard data
- `GET /v1/vendor/qr` - Get QR code
- `GET /v1/vendor/qr/analytics` - QR analytics

---

### 3. **Master Data Module** (`App\Http\Controllers\Master`)
**Responsibility**: Manages static/reference data used across the platform

**Controllers**:
- `StateController`: State information
- `CategoryController`: Business categories
- `ServiceCategoryController`: Service categories
- `ZoneController`: Geographic zones
- `ZonalAreaController`: Zonal areas

**Key Endpoints** (Public - No Auth Required):
- `GET /states` - All states
- `GET /districts` - All districts
- `GET /cities` - All cities
- `GET /zones` - All zones
- `GET /zonal-areas` - Zonal areas
- `GET /business-categories` - Business categories
- `GET /categories/{id}/sub-categories` - Subcategories
- `GET /services` - Available services

---

### 4. **Customer Module** (`App\Http\Controllers\Api\Customer`)
**Responsibility**: Customer-specific operations

**Controllers**:
- `CustomerController`: Main customer controller

**Key Features**:
- Customer registration
- Vendor discovery
- Quote requests

---

### 5. **QR Code Module** (`App\Http\Controllers\Api\QR`)
**Responsibility**: QR code generation and verification

**Controllers**:
- `QrController`: QR operations

**Key Endpoints**:
- `GET /verify-business/{code}` - Verify business via QR code
- `GET /v1/vendor/qr` - Get vendor's QR code
- `GET /v1/vendor/qr/analytics` - QR scan analytics

---

### 6. **Inventory Module** (`App\Http\Controllers\Api\Inventory`)
**Responsibility**: Manages inventory for vendors

**Controllers**:
- `InventoryController`: Inventory management

**Key Endpoints**:
- `GET /v1/vendor/inventory` - Get inventory data

---

### 7. **Subscription Module** (`App\Http\Controllers\Subscription`)
**Responsibility**: Subscription plans and management

**Controllers**:
- `SubscriptionController`: Subscription operations

---

### 8. **Admin/UAC Module** (`App\Http\Controllers\Uac`)
**Responsibility**: User Access Control and administrative functions

**Controllers**:
- `RoleController`: Role management
- `PermissionController`: Permission management

**Features**:
- Role-based access control (RBAC)
- Permission assignment
- Activity logging

---

## Data Flow

### Vendor Registration & Business Setup Flow

```
1. AUTHENTICATION PHASE
   ├─ Vendor initiates registration
   ├─ Receives OTP via SMS/Email
   ├─ Verifies OTP
   └─ JWT token generated

2. PROFILE CREATION PHASE
   ├─ Personal details captured
   ├─ Account created in User table
   └─ Email verification link sent

3. BUSINESS REGISTRATION PHASE
   ├─ Business details registered (BusinessRegistration model)
   ├─ Operating hours configured
   ├─ Serviceable regions defined
   ├─ Social media links added
   └─ Banking details stored (encrypted)

4. KYC VERIFICATION PHASE
   ├─ Government ID documents uploaded
   ├─ Admin reviews documents
   ├─ Status updated to verified/rejected
   └─ QR code generated upon approval

5. PRODUCT LISTING PHASE
   ├─ Products added (ProductDetail model)
   ├─ Bulk upload option available (Excel import)
   ├─ Inventory initialized
   └─ Products visible to customers
```

### Customer to Vendor Lead Flow

```
1. CUSTOMER DISCOVERY
   ├─ Browse vendors
   ├─ View vendor profile via QR code
   └─ Request quote (RFQ)

2. LEAD CREATION
   ├─ RFQ stored in RequestForQuotation model
   ├─ Firebase notification sent to vendor
   └─ Lead marked as pending

3. VENDOR RESPONSE
   ├─ Vendor receives lead
   ├─ Can accept/reject lead
   ├─ If accepted, lead moves to LeadVendor
   └─ If rejected, marked as rejected

4. LEAD MANAGEMENT
   ├─ Vendor can track lead status
   ├─ Customer notified of vendor response
   └─ Communication continues
```

### QR Code Verification Flow

```
1. CUSTOMER SCANS QR CODE
   ├─ Unique code is read
   └─ Request sent to backend

2. BACKEND VERIFICATION
   ├─ Look up business by QR code
   ├─ Verify business is active and KYC approved
   ├─ Increment scan counter
   └─ Return business details

3. CUSTOMER VIEWS
   ├─ Vendor profile displayed
   ├─ Products/services shown
   ├─ Contact information available
   └─ Customer can request quote
```

---

## API Endpoints Structure

### Base URL
```
https://api.bharatseva.com/
```

### Authentication Header
```
Authorization: Bearer {JWT_TOKEN}
```

### API Versioning
All endpoints use `/v1/` prefix for version 1

### Endpoint Categories

#### Public Endpoints (No Auth Required)
- Master data retrieval (states, districts, categories, services)
- OTP generation and verification
- QR code verification
- Business verification by code

#### Protected Endpoints (JWT Required)
- All vendor-specific operations
- All customer-specific operations
- User profile operations
- Admin operations

### Response Format

**Success Response** (HTTP 200):
```json
{
  "success": true,
  "message": "Operation successful",
  "data": {
    "key": "value"
  }
}
```

**Error Response** (HTTP 4xx/5xx):
```json
{
  "success": false,
  "message": "Error description",
  "error": "Error details"
}
```

---

## Database Models

### Core Models

#### **User** (`app/Models/User.php`)
- Stores user information (vendors, customers, admins)
- Fields: id, name, email, phone, password, user_type, status
- Relations: Has many BusinessRegistration, Products, Leads

#### **BusinessRegistration** (`app/Models/BusinessRegistration.php`)
- Stores vendor business details
- Fields: id, user_id, business_name, category_id, status
- Relations: Belongs to User, Has many Products

#### **BusinessAddress** (`app/Models/BusinessAddress.php`)
- Vendor business address information
- Fields: id, business_id, address, zone_id, city_id, pincode
- Relations: Belongs to BusinessRegistration

#### **Lead** (`app/Models/Lead.php`)
- Customer RFQ/lead information
- Fields: id, customer_id, service_type, description, status, created_at
- Relations: Belongs to User (customer), Has many LeadVendor

#### **LeadVendor** (`app/Models/LeadVendor.php`)
- Junction table for lead-vendor assignment
- Fields: id, lead_id, vendor_id, status, accepted_at, rejected_at
- Relations: Belongs to Lead, Belongs to User (vendor)

#### **RequestForQuotation** (`app/Models/RequestForQuotation.php`)
- Detailed RFQ/quote request information
- Fields: id, customer_id, vendor_id, description, status, created_at
- Relations: Belongs to User (customer/vendor)

#### **ReferralLink** (`app/Models/ReferralLink.php`)
- Referral program data
- Fields: id, referrer_id, referred_user_id, status, created_at
- Relations: Belongs to User

### Product & Inventory Models

#### **ProductDetail** (`app/Models/VendorBusiness/ProductDetail.php`)
- Product information
- Fields: id, business_id, name, description, price, image, status
- Relations: Belongs to BusinessRegistration

#### **Inventory** Models (in `app/Models/Inventory/`)
- Manages inventory stock and movements
- Tracks product quantities

### Master Data Models (in `app/Models/Master/`)
- **State**: State information
- **District**: District information
- **City**: City information
- **Zone**: Geographic zones
- **ZonalArea**: Areas within zones
- **Category**: Business categories
- **ServiceCategory**: Service categories

### UAC Models (in `app/Models/Uac/`)
- **Role**: User roles
- **Permission**: System permissions
- **RolePermission**: Role-permission mapping

### Subscription Models (in `app/Models/Subscription/`)
- **SubscriptionPlan**: Available plans
- **UserSubscription**: User subscriptions

### Audit/Logging Models (in `app/Models/Logs/`)
- **ActivityLog**: User activity tracking

---

## Key Services

### Service Layer Architecture

```
Controller
    ↓
Service (Business Logic)
    ↓
Repository/Model (Data Access)
    ↓
Database
```

### Main Services

#### 1. **AuthService** (`app/Services/AuthService.php`)
**Responsibility**: Authentication logic

**Methods**:
- `login()`: Validate credentials, generate JWT
- `logout()`: Invalidate token
- `refresh()`: Generate new token
- `me()`: Get current user
- `generateOtp()`: Create and send OTP
- `verifyOtp()`: Verify OTP and create user

**Dependencies**:
- JWT provider
- User model
- OTP service

---

#### 2. **VendorAuthService** (`app/Services/VendorAuthService.php`)
**Responsibility**: Vendor-specific registration and authentication

**Methods**:
- `register()`: Vendor registration
- `verifyEmail()`: Email verification
- `sendVerificationEmail()`: Send verification link

---

#### 3. **VendorBusinessService** (`app/Services/VendorBusiness/`)
**Responsibility**: Vendor business operations

**Operations**:
- Business profile management
- KYC document handling
- Lead management
- Product management
- QR code generation

---

#### 4. **FirebaseService** (`app/Services/FirebaseService.php`)
**Responsibility**: Firebase operations

**Operations**:
- Send push notifications
- Save FCM tokens
- Real-time messaging

---

#### 5. **MSG91Service** (`app/Services/MSG91Service.php`)
**Responsibility**: SMS/OTP delivery

**Operations**:
- Send OTP via SMS
- Send notifications

---

#### 6. **EmblemService** (`app/Services/EmblemService.php`)
**Responsibility**: Business emblem/verification

**Operations**:
- Display business emblem on public page
- QR verification display

---

#### 7. **Inventory Service** (`app/Services/Inventory/`)
**Responsibility**: Inventory management

**Operations**:
- Track stock levels
- Manage inventory movements

---

#### 8. **Subscription Service** (`app/Services/Subscription/`)
**Responsibility**: Subscription management

**Operations**:
- Plan management
- Subscription lifecycle

---

## Business Processes

### Process 1: Vendor Onboarding

**Timeline**: Multi-step process over days

```
Step 1: Registration (30 mins)
   ├─ Phone verification via OTP
   └─ Account created

Step 2: Profile Creation (1 hour)
   ├─ Personal details
   ├─ Email verification
   └─ Password setup

Step 3: Business Registration (1-2 hours)
   ├─ Business details
   ├─ Operating hours
   ├─ Service regions
   └─ Social links

Step 4: KYC Submission (1-2 hours)
   ├─ Government ID upload
   ├─ Bank details
   ├─ Business registration docs
   └─ Admin notification triggered

Step 5: Admin Verification (1-2 days)
   ├─ Admin reviews documents
   ├─ Status updated
   ├─ If approved: QR code generated
   └─ If rejected: Vendor notified with feedback

Step 6: Product Listing (Variable)
   ├─ Can add products one by one
   ├─ Or bulk upload via Excel
   ├─ Set pricing and details
   └─ Products go live
```

---

### Process 2: Lead Generation & Conversion

**Timeline**: Real-time to days

```
Step 1: Customer Discovers Vendor
   ├─ Searches by category
   ├─ Views vendor profile
   └─ Scans QR code for verification

Step 2: Customer Requests Quote
   ├─ Fills RFQ form
   ├─ Describes requirements
   ├─ Specifies location
   └─ Submits request

Step 3: Lead Created & Vendor Notified
   ├─ RequestForQuotation record created
   ├─ Firebase notification sent
   ├─ SMS/Push notification to vendor
   └─ Lead marked as "pending"

Step 4: Vendor Reviews & Responds
   ├─ Vendor views lead details
   ├─ Decides to accept or reject
   ├─ If Accept: Status = "accepted", Lead notification sent to customer
   ├─ If Reject: Status = "rejected", Reason captured
   └─ LeadVendor record created

Step 5: Follow-up Communication
   ├─ Phone/email contact established
   ├─ Quote negotiation
   └─ Deal closure
```

---

### Process 3: QR Code Verification

**Real-time Process**

```
Customer Action         Backend Response
    │                        │
    ├─ Scan QR code ─────────┤
    │                        │
    │                    ├─ Look up business
    │                    ├─ Verify active status
    │                    ├─ Verify KYC approved
    │                    ├─ Increment scan counter
    │                    └─ Log analytics
    │                        │
    │ ◄─ Business details ───┤
    │                        │
    ├─ View profile          │
    ├─ Request quote ────────┤
    │                        │
    │                    └─ Create RFQ
    │                        │
    │ ◄─ Confirmation ───────┤
```

---

### Process 4: Product Management

**Vendor Product Lifecycle**

```
ADD PRODUCT
    ├─ Single Add
    │   ├─ POST /add/product-details
    │   ├─ ProductDetail record created
    │   └─ Status = "active"
    │
    └─ Bulk Add
        ├─ Excel file uploaded
        ├─ File parsed (Maatwebsite\Excel)
        ├─ ProductImport job processes data
        ├─ Multiple ProductDetail records created
        └─ Status = "active"

EDIT PRODUCT
    ├─ POST /edit/{id}/product-details
    ├─ ProductDetail updated
    └─ Changes reflected immediately

DELETE PRODUCT
    ├─ POST /delete/{id}/product
    ├─ Soft delete or hard delete
    └─ Product no longer visible

RETRIEVE PRODUCTS
    ├─ GET /get-all/product (All vendor products)
    ├─ GET /get-by-id/{id}/product (Single product)
    └─ Product details with pricing, inventory
```

---

## Configuration

### Environment Configuration (`.env`)
```env
APP_NAME=BharatSeva
APP_ENV=production
APP_KEY=base64:xxxxx
APP_DEBUG=false
APP_URL=https://api.bharatseva.com

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=bharatseva
DB_USERNAME=root
DB_PASSWORD=secret

JWT_SECRET=your-jwt-secret
JWT_ALGORITHM=HS256

FIREBASE_CREDENTIALS=path/to/firebase.json

MSG91_AUTH_KEY=your-key
MSG91_OTP_TEMPLATE=your-template

OPENAI_API_KEY=your-key

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=password
```

### Database Configuration (`config/database.php`)
- Primary connection: MySQL/MariaDB
- Connection pooling configured
- Query logging available in debug mode

### Cache Configuration (`config/cache.php`)
- Default cache driver: Redis or File
- Cache used for: Session, API responses, rate limiting

### Queue Configuration (`config/queue.php`)
- Job processing for: Email delivery, SMS, Notifications
- Queue driver: Database or Redis

### Authentication Configuration (`config/auth.php`)
- JWT authentication via `php-open-source-saver/jwt-auth`
- Token expiration: Configurable
- Token refresh mechanism enabled

### Filesystem Configuration (`config/filesystems.php`)
- Public disk: `/storage/app/public` (Product images, QR codes)
- Private disk: `/storage/app` (KYC documents, sensitive files)
- S3 integration available

---

## Common Development Tasks

### Adding a New API Endpoint

1. **Create Controller Method** (`app/Http/Controllers/`)
   ```php
   public function newMethod(Request $request)
   {
       // Validation
       // Call Service
       // Return Response
   }
   ```

2. **Register Route** (`routes/api.php`)
   ```php
   Route::post('endpoint', [ControllerName::class, 'newMethod'])->middleware('jwt.auth');
   ```

3. **Create Service Method** (`app/Services/`)
   - Implement business logic

4. **Test Endpoint**
   - Use Postman/Insomnia
   - Test with/without auth
   - Validate response format

---

### Adding Master Data

1. **Create Migration** (`database/migrations/`)
   ```bash
   php artisan make:migration create_new_table
   ```

2. **Define Schema** in migration

3. **Create Model** (`app/Models/Master/`)
   ```bash
   php artisan make:model NewModel
   ```

4. **Seed Data** (`database/seeders/`)

5. **Add Route** for retrieval (`routes/api.php`)

---

### KYC Document Verification Workflow

1. **Document Upload** → Stored in `storage/app/kyc/`
2. **Admin Review** → Navigate admin panel
3. **Verification Status** → Updated in `BusinessRegistration`
4. **Approval Notification** → Firebase notification sent
5. **QR Generation** → Automatic upon approval

---

## Troubleshooting Guide

### Common Issues

#### 1. JWT Token Expired
**Solution**: Refresh token using `/v1/auth/refresh`

#### 2. OTP Not Received
**Check**: MSG91 credentials in `.env`, API key validity

#### 3. Firebase Notification Not Received
**Check**: FCM token saved correctly, Firebase service account configured

#### 4. File Upload Fails
**Check**: File permissions in `storage/` directory, disk configuration

#### 5. Database Connection Error
**Check**: Database credentials, MySQL service running

---

## Performance Considerations

### Optimization Strategies

1. **Database Indexing**
   - Index on frequently queried fields (user_id, business_id)
   - Composite indexes for common filters

2. **Query Optimization**
   - Use eager loading (with()) to prevent N+1 queries
   - Select only required columns

3. **Caching**
   - Cache master data (categories, states, cities)
   - Cache frequently accessed vendor profiles
   - TTL: 24 hours for static data

4. **API Response Pagination**
   - Default page size: 20 records
   - Maximum page size: 100 records
   - Implement cursor-based pagination for large datasets

5. **Image Optimization**
   - Resize product images to standard dimensions
   - Use WebP format for web
   - Implement CDN for static assets

---

## Security Best Practices

### Implemented Security Measures

1. **Authentication**
   - JWT tokens with expiration
   - Secure OTP generation and validation
   - Password hashing using bcrypt

2. **Authorization**
   - Role-based access control (RBAC)
   - Middleware-level permission checks
   - Resource-level ownership validation

3. **Data Protection**
   - Bank details and sensitive data encrypted
   - HTTPS enforced
   - SQL injection prevention via Eloquent ORM

4. **Rate Limiting**
   - OTP generation: 3 attempts per 24 hours
   - Login attempts: 5 attempts per 15 minutes
   - API endpoints: Configurable rate limits

5. **Audit Trail**
   - Activity logging for sensitive operations
   - Change history maintained
   - Admin actions tracked

---

## Deployment

### Production Deployment Checklist

- [ ] Environment variables configured
- [ ] Database migrations run
- [ ] Cache tables created
- [ ] Storage directories created with proper permissions
- [ ] SSL certificate installed
- [ ] Database backups scheduled
- [ ] Error logging configured
- [ ] Email service verified
- [ ] Firebase credentials validated
- [ ] MSG91 service tested
- [ ] Performance optimization reviewed
- [ ] Security audit completed

### Monitoring

- **Error Logs**: `storage/logs/laravel.log`
- **Database**: Monitor connection pool
- **API**: Monitor response times
- **Notifications**: Verify Firebase delivery
- **SMS**: Monitor MSG91 delivery status

---

## Support & Documentation

### Key Files to Reference
- `composer.json` - Dependencies
- `config/app.php` - Application configuration
- `config/auth.php` - Authentication settings
- `.env` - Environment variables
- `routes/api.php` - API route definitions
- `database/migrations/` - Database schema

### External Documentation
- [Laravel Documentation](https://laravel.com/docs)
- [JWT Auth Package](https://github.com/PHP-Open-Source-Saver/jwt-auth)
- [Firebase Laravel Package](https://github.com/kreait/laravel-firebase)

---

**Last Updated**: May 2026  
**Version**: 1.0  
**Maintained By**: Development Team
