# Complete Shipment System Summary

## 📊 System Architecture Overview

```
┌──────────────────────────────────────────────────────────────────┐
│                    STEVE SHIPMENT SYSTEM                          │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│  CREATE SHIPMENT          →    STATUS UPDATE        →    DELIVERY│
│  (shipment-create.php)         (Status-Update.php)               │
│       ↓                              ↓                            │
│  Own/External Courier       Manual/Live Tracking               │
│                                                                   │
│  Database Tables:                                                 │
│  ├─ tbl_bookings (Main)                                          │
│  ├─ tbl_shipments (Package Details)                              │
│  ├─ tbl_tracking (Status History)   ← Updates by Status Form     │
│  └─ tbl_courier_partner (Courier Info)                           │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘
```

---

## 🎯 Two Main Workflows

### WORKFLOW 1: CREATE OWN BOOKING
```
USER CREATES BOOKING
        ↓
[shipment-create.php]
    ├─ Select Pickup Point
    ├─ Enter Consignee Details
    ├─ Add Package Details
    ├─ Select Courier (Own Courier)
    └─ Enter Invoice & Payment Info
        ↓
[api/shipment/create.php]
    ├─ Validate all inputs
    ├─ INSERT into tbl_bookings
    ├─ INSERT into tbl_shipments (packages)
    └─ Generate Booking ID
        ↓
BOOKING CREATED & READY
    ├─ Status: PENDING
    └─ Awaiting manual updates
        ↓
[shipment-status-update.php]
    ├─ Scan AWB Number
    ├─ View Details & History
    ├─ Update Status manually
    └─ Create tbl_tracking records
```

### WORKFLOW 2: UPDATE SHIPMENT STATUS
```
USER SCANS AWB NUMBER
        ↓
[shipment-status-update.php]
    ├─ Search booking by AWB/Ref ID
    ├─ Display shipment card
    │  ├─ AWB Details
    │  ├─ Consignee Info
    │  ├─ Current Status
    │  └─ View History (clickable)
    └─ Show tracking history if clicked
        ↓
USER SELECTS NEW STATUS
    ├─ Choose from dropdown
    ├─ Set date (defaults to today)
    ├─ Add location (optional)
    └─ Add remarks (optional)
        ↓
SUBMIT BULK UPDATE
    ├─ Confirmation dialog
    └─ Process all scanned AWBs
        ↓
[api/tracking/create.php]
    ├─ Validate all inputs
    ├─ Check for duplicates
    ├─ INSERT into tbl_tracking
    ├─ UPDATE tbl_bookings.last_status
    └─ Return success response
        ↓
UPDATE CONFIRMED
    ├─ Toast notification
    ├─ Card status badge updates
    └─ Tracking history refreshes (if visible)
```

---

## 📋 Database Schema Reference

### Table: tbl_bookings
```
Core Booking Information
├─ id (PK)
├─ courier_id (FK) ← Links to tbl_courier_partner
├─ pickup_point_id (FK) → tbl_pickup_points
├─ booking_ref_id (Unique) ← ORD-timestamp
├─ waybill_no (AWB Number, nullable)
│
├─ CONSIGNEE (Recipient)
│  ├─ consignee_name
│  ├─ consignee_phone
│  ├─ consignee_address
│  ├─ consignee_pincode
│  ├─ consignee_city
│  ├─ consignee_state
│  ├─ consignee_email
│  └─ consignee_gst
│
├─ CONSIGNOR (Shipper)
│  ├─ shipper_name
│  ├─ shipper_phone
│  ├─ shipper_address
│  ├─ shipper_city
│  ├─ shipper_state
│
├─ PAYMENT & INVOICE
│  ├─ payment_mode (Prepaid/COD)
│  ├─ cod_amount
│  ├─ invoice_no
│  ├─ invoice_value
│
├─ STATUS & TRACKING
│  ├─ last_status (Current status)
│  ├─ api_response (JSON from courier)
│
└─ AUDIT
   ├─ created_by
   ├─ created_at
   ├─ updated_by
   └─ updated_at
```

### Table: tbl_shipments
```
Package/Box Details (Multiple per booking)
├─ id (PK)
├─ booking_id (FK) → tbl_bookings
├─ length (cm)
├─ width (cm)
├─ height (cm)
├─ boxes (Quantity)
├─ actual_weight (kg)
├─ charged_weight (kg)
├─ product_desc
└─ created_at
```

### Table: tbl_tracking
```
Status History (Multiple scans per booking)
├─ id (PK)
├─ booking_id (FK) → tbl_bookings
├─ waybill_no (AWB)
├─ scan_type (Status: Pending, In Transit, etc.)
├─ scan_location (Where scanned)
├─ scan_datetime (When scanned)
├─ status_code (Code version of status)
├─ remarks (Additional notes)
├─ raw_response (JSON payload)
├─ UNIQUE KEY (booking_id, scan_type, scan_datetime)
└─ created_at
```

### Table: tbl_courier_partner
```
Courier Information
├─ id (PK)
├─ partner_name (e.g., "Own Courier")
├─ partner_code (e.g., "OC")
├─ api_key (For external APIs)
├─ api_url (For external APIs)
└─ ... (other config)
```

---

## 🔗 API Endpoints

### 1. Create Shipment
```
POST /api/shipment/create.php
Input:  All shipment details (see form fields)
Output: { status, booking_id, booking_ref_id, waybill_no }
Tables: Inserts tbl_bookings, tbl_shipments
```

### 2. Read Shipments (List)
```
GET /api/shipment/read.php?length=-1
Input:  (optional) search filters
Output: { data: [{...shipment}, ...] }
Tables: Reads tbl_bookings JOIN tbl_shipments
```

### 3. Create Tracking (Status Update)
```
POST /api/tracking/create.php
Input:  booking_id, status, status_date, location, remarks
Output: { status, tracking_id, new_status }
Tables: Inserts tbl_tracking, Updates tbl_bookings
```

### 4. Read Tracking (History)
```
GET /api/tracking/read.php?id=<booking_id>
Input:  booking_id or waybill_no
Output: { current_status, scans: [{...}, ...] }
Tables: Reads tbl_tracking, tbl_bookings
```

---

## 🎨 UI Components

### Page: shipment-create.php
**Purpose**: Create new bookings
**Courier**: Own Courier or External
**Features**:
- Multi-step form
- Auto-fill from pickup point
- Package detail builder
- Validation on submit
- Success confirmation

### Page: shipment-list.php
**Purpose**: View all bookings
**Features**:
- DataTables with pagination
- Search by AWB/RefID
- Filter by status/courier
- Bulk actions
- Edit/Delete options

### Page: shipment-status-update.php ✅ **ENHANCED**
**Purpose**: Manual status tracking for Own Courier
**Features**:
- ✓ Real-time AWB search
- ✓ Rich shipment detail cards
- ✓ Color-coded status badges (8 types)
- ✓ Expandable tracking history
- ✓ Bulk status update
- ✓ Toast notifications
- ✓ Validation & error handling
- ✓ Full database integration

---

## 📝 Key Features Summary

### ✅ Shipment Creation
```
✓ Own Courier support
✓ Multiple packages per booking
✓ Consignee/Consignor details
✓ Invoice & payment tracking
✓ Return address support
✓ E-way bill integration
```

### ✅ Status Management
```
✓ 8 Status types (Pending, Manifested, In Transit, etc.)
✓ Manual status updates
✓ Location tracking
✓ Remarks/Instructions
✓ Tracking history with all scans
✓ Color-coded visual indicators
```

### ✅ User Experience
```
✓ Real-time search
✓ Expandable/Collapsible sections
✓ Toast notifications
✓ Progress indicators
✓ Bulk operations
✓ Responsive design
✓ Professional card-based layout
```

### ✅ Data Integrity
```
✓ Transaction support
✓ Duplicate prevention
✓ Audit trail (created_by, updated_by)
✓ Timestamps on all records
✓ Foreign key relationships
✓ Unique constraints
```

---

## 📊 Status Types

```
┌────────────────┬──────────┬────────────────────────┐
│ Status         │ Badge    │ Use Case               │
├────────────────┼──────────┼────────────────────────┤
│ PENDING        │ 🟠 Orange │ Initial state          │
│ NOT PICKED     │ 🔴 Pink   │ Pickup failed          │
│ MANIFESTED     │ 🟣 Purple │ Added to manifest      │
│ IN TRANSIT     │ 🔵 Blue   │ On the way             │
│ OUT FOR DELIVERY│ 🟢 Teal  │ With delivery agent    │
│ DELIVERED      │ ✅ Green  │ Successfully delivered │
│ LOST           │ ❌ Red    │ Package lost           │
│ RTO            │ 🟡 Amber  │ Return to origin       │
└────────────────┴──────────┴────────────────────────┘
```

---

## 🚀 Quick Start Guide

### To Create an Own Booking:
1. Go to `shipment-create.php`
2. Select Branch → Pickup Point
3. Fill Consignee Details (Name, Phone, Address, Pin)
4. Add Package Details (Dimensions, Weight, Boxes)
5. Select "Own Courier" as courier
6. Enter Invoice & Payment Info
7. Click "Create Shipment"
8. Note the Booking ID/Reference ID

### To Update Status:
1. Go to `shipment-status-update.php`
2. Scan/Type AWB Number → Press Enter
3. Shipment card appears with all details
4. Click "View History" to see previous scans
5. Select New Status from dropdown
6. Set date (defaults to today)
7. (Optional) Add location and remarks
8. Click "Update All (n)"
9. Confirm in popup
10. Done! Status saved and history updated

---

## 💾 Data Flow Diagram

```
┌─────────────────────────┐
│  USER INPUT             │
│  (Create Shipment Form) │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  VALIDATION             │
│  (Client + Server)      │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  DATABASE INSERT        │
│  tbl_bookings           │
│  tbl_shipments          │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  BOOKING CREATED        │
│  Ready for tracking     │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  USER SCAN AWB          │
│  (Status Update Page)   │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  DISPLAY SHIPMENT       │
│  Card with Details      │
│  & Tracking History     │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  SELECT NEW STATUS      │
│  Add location/remarks   │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  SUBMIT STATUS UPDATE   │
│  (Bulk or Individual)   │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  VALIDATION & INSERT    │
│  tbl_tracking           │
│  UPDATE tbl_bookings    │
└────────────┬────────────┘
             ↓
┌─────────────────────────┐
│  CONFIRMATION & TOAST   │
│  History Refreshed      │
└─────────────────────────┘
```

---

## 📱 Responsive Breakpoints

```
Mobile (< 768px):
├─ Card layout stacks vertically
├─ Details in 1 column
└─ Full-width buttons

Tablet (768px - 1024px):
├─ Card layout side-by-side
├─ 2-column details
└─ Optimized spacing

Desktop (> 1024px):
├─ Full card layout
├─ Side-by-side panels
└─ Hover effects enabled
```

---

## 🔐 Security & Validation

### Input Validation:
```
✓ Pincode verification (valid Indian postcodes)
✓ Phone number validation (10 digits)
✓ Required field checks
✓ Data type validation
✓ SQL injection prevention (prepared statements)
```

### Access Control:
```
✓ Session-based authentication
✓ Permission checks (require_permission)
✓ User tracking (created_by, updated_by)
✓ Audit trail (timestamps)
```

### Data Integrity:
```
✓ Transaction support
✓ Unique constraints
✓ Foreign key relationships
✓ Duplicate prevention
```

---

## 📈 Performance Optimization

```
✓ Lazy loading of tracking history
✓ Debounced search operations
✓ Efficient database queries
✓ Pagination support
✓ Minimal DOM manipulation
✓ CSS animations (smooth)
```

---

## 🐛 Debugging Tips

### Check Booking Creation:
```sql
SELECT * FROM tbl_bookings
WHERE booking_ref_id = 'ORD-xxx';
```

### Check Package Details:
```sql
SELECT * FROM tbl_shipments
WHERE booking_id = 12345;
```

### Check Status History:
```sql
SELECT * FROM tbl_tracking
WHERE booking_id = 12345
ORDER BY scan_datetime DESC;
```

### Check Last Status:
```sql
SELECT id, waybill_no, last_status, updated_at
FROM tbl_bookings
WHERE id = 12345;
```

---

## 📞 Support & Maintenance

### Version Information:
- **Status Page Version**: 2.0 (Enhanced)
- **Last Updated**: 2026-02-14
- **Status**: Production Ready ✅

### Related Documentation:
1. **SHIPMENT_STATUS_UPDATE_FIXED.md** - Status update page details
2. **STATUS_UPDATE_QUICK_GUIDE.md** - User-friendly reference
3. **OWN_BOOKING_SHIPMENT_GUIDE.md** - Booking creation guide
4. **projectskill.md** - Overall project architecture

### Contact:
For technical issues or feature requests, contact your development team.

---

## ✅ Checklist for Implementation

- [x] Status update page enhanced with card layout
- [x] 8 status types with color coding
- [x] Expandable tracking history
- [x] Real-time search by AWB/RefID
- [x] Bulk status update functionality
- [x] Database integration (tbl_tracking)
- [x] Toast notifications
- [x] Responsive design
- [x] Comprehensive documentation
- [x] Testing & verification

---

**System Ready for Production Use** ✅
