# Pickup Point Management System with Delhivery Integration

## Overview
This module provides comprehensive pickup point (warehouse) management with Delhivery API integration for syncing warehouse data.

## Features Implemented

### 1. Database Schema
**File:** `database/pickup_point_setup.sql`

**Table:** `tbl_pickup_points`

**Key Fields:**
- `company_id` - Links pickup point to a company
- `pickup_point_code` - Non-unique identifier for the pickup point
- `name` - Warehouse name (case-sensitive for Delhivery)
- `phone`, `email`, `address`, `city`, `pin`, `country` - Contact and location details
- `return_address`, `return_city`, `return_pin`, `return_state`, `return_country` - Return address configuration
- `courier_id` - Links to courier partner (e.g., Delhivery)
- `delhivery_synced` - Boolean flag indicating if synced with Delhivery
- `delhivery_response` - Stores last API response from Delhivery
- `status` - Active/Inactive status

### 2. API Endpoints

#### Standard CRUD Operations

**`api/pickuppoint/read.php`**
- Lists all pickup points with DataTables support
- Supports filtering by:
  - Company
  - Courier partner
  - Status (active/inactive)
  - Delhivery sync status
- Includes search functionality across all fields
- Returns joined data with company and courier names

**`api/pickuppoint/readone.php`**
- Fetches single pickup point by ID
- Returns complete details with company and courier information

**`api/pickuppoint/delete.php`**
- Deletes pickup point from database
- Provides warning about Delhivery deactivation requirement

#### Delhivery Integration APIs

**`api/pickuppoint/delhivery/create.php`**
- Syncs pickup point with Delhivery warehouse creation API
- **Endpoint:** `POST /api/backend/clientwarehouse/create/`
- **Process:**
  1. Fetches pickup point details from database
  2. Validates courier is Delhivery
  3. Retrieves API token and URL from courier partner settings
  4. Sends warehouse creation request to Delhivery
  5. Updates `delhivery_synced` flag based on response
  6. Stores API response in `delhivery_response` field
- **Required Fields:**
  - `phone` (mandatory)
  - `city`
  - `name` (case-sensitive)
  - `pin` (mandatory)
  - `address`
  - `country` (defaults to 'India')
  - `email`
  - `registered_name`
  - `return_address` (mandatory)
  - `return_pin`
  - `return_city`
  - `return_state`
  - `return_country` (defaults to 'India')

**`api/pickuppoint/delhivery/update.php`**
- Updates existing warehouse in Delhivery
- Uses same endpoint as create (Delhivery API design)
- Updates sync status based on response

**`api/pickuppoint/delhivery/delete.php`**
- Marks pickup point as inactive in local database
- **Note:** Delhivery does not provide a delete API
- Users must contact Delhivery support to deactivate warehouses

### 3. Frontend Pages

**`pickuppoint-list.php`**
- Main listing page with DataTables
- **Features:**
  - Multi-column filtering (Company, Courier, Status, Sync Status)
  - Real-time search
  - Sync/Re-sync buttons for Delhivery warehouses
  - Color-coded sync status badges:
    - Green: Synced
    - Yellow: Not Synced
    - Gray: N/A (non-Delhivery courier)
  - Permission-based action buttons (View, Edit, Sync, Delete)
  - Responsive design

**Sync Button Behavior:**
- Displays "Sync" button for warehouses not yet synced
- Displays "Re-sync" button for already synced warehouses
- Shows loading state during API call
- Automatically reloads table on successful sync
- Shows error messages if sync fails

### 4. Navigation

**Sidebar Integration:**
- Added "Pickup Points" menu item under "Master Data Module"
- Located after "Consignee" menu item
- Follows existing navigation pattern

## Delhivery API Integration Details

### Authentication
- Uses Token-based authentication
- Token retrieved from `tbl_courier_partner.api_token`
- Header format: `Authorization: Token XXXXXXXXXXXXXXXXX`

### API Configuration
- Base URL stored in `tbl_courier_partner.api_url`
- Supports both staging and production environments
- Staging: `https://staging-express.delhivery.com`
- Production: `https://express.delhivery.com`

### Error Handling
- Captures HTTP status codes
- Stores full API response for debugging
- Provides user-friendly error messages
- Common errors handled:
  - Authentication failures
  - Missing required fields
  - Non-serviceable pincodes
  - Duplicate warehouse names
  - Insufficient balance

### Important Notes
1. **Warehouse Name is Case-Sensitive:** The exact same name must be used when creating orders
2. **No Delete API:** Delhivery doesn't provide warehouse deletion via API
3. **Return Address Required:** Must be configured for each warehouse
4. **Sync Status:** Only updates to "synced" on successful API response (HTTP 200-299)

## Workflow

### Creating a New Pickup Point with Delhivery Sync

1. **Create Pickup Point Record**
   - Navigate to Pickup Points → Add New
   - Fill in all required fields
   - Select Delhivery as courier partner
   - Save the record

2. **Sync with Delhivery**
   - Go to Pickup Point List
   - Find the newly created pickup point
   - Click "Sync" button
   - System will:
     - Send data to Delhivery API
     - Update sync status
     - Store API response
     - Show success/error message

3. **Verify Sync**
   - Check for green "Synced" badge
   - View API response if needed
   - Re-sync if necessary

### Updating Pickup Point

1. Edit pickup point details in the system
2. Click "Re-sync" to update Delhivery
3. System uses same create endpoint (Delhivery API design)

### Filtering and Search

- **Company Filter:** View pickup points for specific company
- **Courier Filter:** Filter by courier partner
- **Status Filter:** Active/Inactive pickup points
- **Sync Filter:** Show only synced or unsynced warehouses
- **Search:** Real-time search across all fields

## Database Setup

Run the SQL file to create the table:
```bash
mysql -u username -p database_name < database/pickup_point_setup.sql
```

Or execute in phpMyAdmin/MySQL client.

## Permissions Required

The module uses the following permission keys:
- `pickuppoint.is_view` - View pickup points
- `pickuppoint.is_add` - Add new pickup points and sync with Delhivery
- `pickuppoint.is_edit` - Edit pickup points and re-sync
- `pickuppoint.is_delete` - Delete pickup points

Ensure these permissions are configured in your role management system.

## API Response Examples

### Successful Sync
```json
{
  "status": "success",
  "message": "Pickup point synced with Delhivery successfully",
  "response": {
    "success": true,
    "warehouse_id": "12345"
  }
}
```

### Failed Sync
```json
{
  "status": "error",
  "message": "Failed to sync with Delhivery",
  "response": {
    "error": "ClientWarehouse matching query does not exist."
  },
  "http_code": 400
}
```

## Troubleshooting

### Common Issues

1. **"Authentication credentials were not provided"**
   - Check API token in courier partner settings
   - Verify token is correctly passed in header

2. **"ClientWarehouse matching query does not exist"**
   - Warehouse name mismatch
   - Check registered name in Delhivery account

3. **"Client-Warehouse is not active"**
   - Contact Delhivery account POC
   - Warehouse may need activation

4. **"Non serviceable pincode"**
   - Use Delhivery pincode serviceability API first
   - Verify pincode is in serviceable area

5. **Sync button not showing**
   - Ensure courier partner is set to "Delhivery"
   - Check edit permissions

## Future Enhancements

- Bulk sync functionality
- Automatic sync on create/update
- Pincode serviceability check integration
- Sync history/audit log
- Webhook integration for status updates
- Multi-courier support expansion

## Files Created/Modified

### New Files
- `database/pickup_point_setup.sql`
- `api/pickuppoint/read.php`
- `api/pickuppoint/readone.php`
- `api/pickuppoint/delete.php`
- `api/pickuppoint/delhivery/create.php`
- `api/pickuppoint/delhivery/update.php`
- `api/pickuppoint/delhivery/delete.php`
- `pickuppoint-list.php`

### Modified Files
- `sidebar.php` - Added Pickup Points menu item

## Dependencies

- PHP 7.4+
- MySQL/MariaDB
- jQuery
- DataTables
- Bootstrap 5
- cURL extension enabled

## Security Considerations

- All API endpoints check permissions
- SQL injection prevention using PDO prepared statements
- XSS prevention with proper output escaping
- API tokens stored securely in database
- Session-based authentication required

---

**Version:** 1.0  
**Last Updated:** 2026-02-10  
**Author:** Development Team
