# Shipping Files Controller Documentation

**File**: `/controllers/shippingFilesController.php`  
**Purpose**: Manages shipping documentation, file uploads, and delivery tracking for import contracts  
**Last Updated**: December 19, 2024  
**Total Functions**: 3 main actions + 12 file type handlers  
**Lines of Code**: 161

---

## 📋 Overview

The Shipping Files Controller manages the complete documentation workflow for shipping and import operations. It handles:
- Tracking shipping documents by chassis number
- Managing multiple file types for each shipment
- File upload and storage for shipping documents
- User tracking for document uploads
- Integration with import contracts and inventory
- Real-time file status updates via AJAX
- Document versioning and user audit trails

### Primary Functions
- [x] Initialize shipping file records by chassis number
- [x] Upload and manage 12 different document types
- [x] Track which user uploaded each document and when
- [x] Display file management interface with real-time updates
- [x] Handle both file uploads and note updates
- [x] Print-ready document views
- [x] Integration with import contract system

### Document Types Managed
- **buybillfile** - Purchase order documents
- **performafile** - Performa invoice documents
- **cocfile** - Certificate of Conformity
- **finalbillfile** - Final invoice documents
- **warehousefile** - Warehouse receipts
- **shippolicyfile** - Shipping policy documents
- **eurofile** - European compliance documents
- **customevalfile** - Customs evaluation documents
- **model4file** - Model 4 certification documents
- **endrosementfile** - Endorsement documents
- **batchreleasefile** - Batch release certificates
- **trafficnotifyfile** - Traffic notification documents
- **saleagreementfile** - Sale agreement documents
- **taxinvoicefile** - Tax invoice documents
- **other** - Other miscellaneous documents

### Related Controllers
- [buyBillController.md](buyBillController.md) - Purchase order integration
- [supplierController.md](supplierController.md) - Supplier documentation
- [storeController.md](storeController.md) - Warehouse receipt management
- [productController.md](productController.md) - Product import documentation
- [userController.md](userController.md) - User audit trails
- [employeeController.md](employeeController.md) - Employee document handling

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **shippingfile** | Main shipping documents | id, chasis, buybillfile, cocfile, finalbillfile, warehousefile, etc. |
| **shippingfile (user columns)** | User tracking | buybilluserid, cocuserid, finalbilluserid, warehouseuserid, etc. |
| **shippingfile (date columns)** | Date tracking | buybilldate, cocdate, finalbilldate, warehousedate, etc. |

### Integration Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **importcontract** | Import chassis data | Source of chassis numbers |
| **user** | User information | User who uploaded files |

### File Storage Structure
| Directory | Purpose | File Types |
|-----------|---------|------------|
| **../upload/shippingFiles** | Document storage | PDF, DOC, JPG, PNG, etc. |

### Document Tracking Schema
Each document type has 3 associated columns:
- **{type}file** - File name/path
- **{type}userid** - User who uploaded
- **{type}date** - Upload timestamp

Example for Buy Bill documents:
- `buybillfile` - stores filename
- `buybilluserid` - stores uploader user ID  
- `buybilldate` - stores upload datetime

---

## 🔧 Key Functions

### 1. Main Interface (empty $do)
**Purpose**: Display chassis selection and main shipping files interface  
**Called By**: Direct navigation to controller  
**Line**: 8

**Process Flow**:
```
Load Chassis Numbers
         ↓
Filter Active Contracts (del < 2)
         ↓
Display Chassis Selection
         ↓
Await User Selection
```

**Business Logic**:
1. Queries distinct chassis numbers from `importcontract` table
2. Filters only active contracts (not deleted: `del < 2`)
3. Displays chassis selection dropdown
4. Provides interface for file management

**Database Query**:
```sql
SELECT DISTINCT chasisno FROM importcontract 
WHERE chasisno != '' AND del < 2
```

### 2. getFiles
**Purpose**: Load or create shipping file record for specific chassis  
**Called By**: AJAX request with chassis selection  
**Line**: 18

**Parameters** (via $_POST):
- `chasis` (string) - Chassis number to manage

**Process Flow**:
```
Check if File Record Exists
         ↓
┌─────────────────────────┐
│ If Not Exists:         │
│ - Create new record    │
│ - Set chassis number   │
│ - Set creation date    │
│ - Set creating user    │
└─────────────────────────┘
         ↓
┌─────────────────────────┐
│ Enhance with Usernames │
│ - Load all user names  │
│ - Map to file types    │
│ - Prepare display data │
└─────────────────────────┘
         ↓
Display File Management Interface
```

**Business Logic**:
1. **Auto-Creation**: Creates shipping file record if doesn't exist
2. **User Resolution**: Loads employee names for all document types
3. **Complete Data**: Provides full file status for interface
4. **Real-time Updates**: Supports dynamic file management

**Username Resolution Example**:
```php
$files['buybillusername'] = R::getCell(
    "SELECT employeename FROM user WHERE userid = ?", 
    [$files['buybilluserid']]
);
```

### 3. updateFilesData
**Purpose**: Handle file uploads and note updates with comprehensive type mapping  
**Called By**: AJAX file upload or note update  
**Line**: 68

**Parameters** (via $_POST):
- `fileid` (int) - Shipping file record ID
- `col` (string) - Column to update (file type)
- `type` (string) - 'note' or 'file'
- `value` (string) - Note content (for notes only)
- `uploadedFile` (file) - File to upload (for files only)

**Process Flow**:
```
Validate File ID
         ↓
┌─────────────────────┐
│ Determine Type      │
│ - Note Update       │
│ - File Upload       │
└─────────────────────┘
         ↓
┌─────────────────────┐
│ For File Uploads:   │
│ - Process file      │
│ - Map column names  │
│ - Update database   │
│ - Return file info  │
└─────────────────────┘
         ↓
┌─────────────────────┐
│ For Note Updates:   │
│ - Update text field │
│ - No user tracking  │
└─────────────────────┘
         ↓
Return Success/Failure Response
```

**Business Logic**:
1. **Type Detection**: Handles both file uploads and note updates
2. **Column Mapping**: Maps file types to database columns and user tracking fields
3. **User Audit**: Tracks who uploaded what and when
4. **Error Handling**: Provides proper response codes for AJAX
5. **File Management**: Uses custom upload library for file processing

**Column Mapping Logic**:
```php
switch ($col) {
    case 'buybillfile':
        $userCol = 'buybilluserid';
        $dateCol = 'buybilldate';
        break;
    case 'cocfile':
        $userCol = 'cocuserid';
        $dateCol = 'cocdate';
        break;
    // ... continues for all 12+ document types
}
```

**Database Update with Audit Trail**:
```php
R::exec("UPDATE shippingfile SET $col = '$fileName', 
         $userCol = " . $_SESSION['userid'] . ", 
         $dateCol = '$date' WHERE id = $fileid");
```

---

## 🔄 Business Logic Flow

### Complete Shipping Documentation Workflow
```
Import Contract Created
         ↓
┌─────────────────────────────┐
│ Initialize Shipping Files  │
│ - Create file record        │
│ - Link to chassis number    │
│ - Set initial status        │
└─────────────────────────────┘
         ↓
┌─────────────────────────────┐
│ Document Collection Phase   │
│ - Purchase orders          │
│ - Certificates             │
│ - Compliance docs          │
└─────────────────────────────┘
         ↓
┌─────────────────────────────┐
│ Upload Documents           │
│ - Multiple file types      │
│ - User tracking           │
│ - Date stamping           │
└─────────────────────────────┘
         ↓
┌─────────────────────────────┐
│ Document Review            │
│ - Completeness check       │
│ - Compliance verification  │
│ - Approval process         │
└─────────────────────────────┘
         ↓
┌─────────────────────────────┐
│ Shipping Clearance         │
│ - All documents uploaded   │
│ - Ready for shipment       │
│ - Track progress           │
└─────────────────────────────┘
         ↓
    Shipment Processed
```

### File Upload Process
```
User Selects Document
         ↓
┌──────────────────────────┐
│ Validate File            │
│ - Check file type        │
│ - Verify file size       │
│ - Ensure permissions     │
└──────────────────────────┘
         ↓
┌──────────────────────────┐
│ Process Upload           │
│ - Move to server         │
│ - Generate filename      │
│ - Update database        │
└──────────────────────────┘
         ↓
┌──────────────────────────┐
│ Update Audit Trail       │
│ - Record uploader        │
│ - Timestamp upload       │
│ - Log activity           │
└──────────────────────────┘
         ↓
┌──────────────────────────┐
│ Return Status            │
│ - File URL               │
│ - Upload date            │
│ - Uploader name          │
└──────────────────────────┘
         ↓
    Interface Updated
```

---

## ⚠️ Common Issues

### 1. **File Upload Failures**
**Symptoms**: Files not uploading, error responses  
**Causes**: 
- Directory permission issues on ../upload/shippingFiles
- File size exceeding PHP limits
- Invalid file types
- Insufficient disk space

**Solutions**:
- Ensure upload directory has 755 permissions
- Check `upload_max_filesize` and `post_max_size` in php.ini
- Validate file types before upload
- Monitor disk space usage

### 2. **Chassis Number Not Found**
**Symptoms**: No chassis numbers appear in dropdown  
**Causes**: 
- No active import contracts
- Data in importcontract table marked as deleted
- Database connection issues

**Solutions**:
- Verify import contracts exist with `del < 2`
- Check importcontract table data integrity
- Ensure database connectivity

### 3. **User Name Resolution Failures**
**Symptoms**: Blank user names in file upload tracking  
**Causes**: 
- Missing user records
- Invalid user IDs in session
- Deleted user accounts

**Solutions**:
- Validate user existence before file operations
- Implement fallback for missing user data
- Handle deleted user accounts gracefully

### 4. **AJAX Response Errors**
**Symptoms**: File upload interface not updating  
**Causes**: 
- Invalid JSON responses
- PHP errors during upload
- Network connectivity issues

**Solutions**:
- Add proper error handling in AJAX calls
- Validate server responses
- Implement retry mechanisms for failed uploads

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core system operations
- `../library/uploadImages.php` - File upload utilities

### Database Dependencies
- **RedBeanPHP**: Used for all database operations (R::getAll, R::exec, etc.)
- **Session Management**: User tracking via $_SESSION['userid']

### File System Dependencies
- **Upload Directory**: `../upload/shippingFiles/` must be writable
- **File Processing**: Custom upload class for file handling

### Frontend Dependencies
- **AJAX Support**: For real-time file uploads and updates
- **JavaScript**: File upload interface and progress tracking
- **Smarty Templates**: For displaying file management interface

### Template Files
- `shippingFilesView/add.html` - Main chassis selection interface
- `shippingFilesView/files.html` - File management interface
- `shippingFilesView/editprint.html` - Print-ready document view
- `header.html` - Standard page header
- `footer.html` - Standard page footer

---

## 🎯 Integration Points

### Import Contract Integration
- **Chassis Tracking**: Direct link to import contract chassis numbers
- **Status Updates**: Shipping file status affects contract completion
- **Document Requirements**: Different contracts may require different documents

### User Management Integration
- **Audit Trails**: Complete tracking of who uploaded what when
- **Permissions**: Role-based access to different document types
- **Employee Names**: Real-time resolution of user information

### File Management Integration
- **Storage**: Centralized file storage with organized structure
- **Versioning**: Support for document updates and replacements
- **Access Control**: Secure file access based on user permissions

### Workflow Integration
- **Process Tracking**: Document completion affects overall import workflow
- **Notifications**: Alert systems for missing or expired documents
- **Reporting**: Status reports on shipping documentation progress

---

## 💡 Best Practices

### File Management
1. **Organize files systematically** by chassis number and document type
2. **Implement file versioning** for updated documents
3. **Regular backup** of critical shipping documents
4. **Monitor storage space** usage
5. **Validate file integrity** after uploads

### Security Considerations
1. **Validate file types** to prevent malicious uploads
2. **Scan uploaded files** for viruses if possible
3. **Implement access controls** based on user roles
4. **Log all file access** for security auditing
5. **Regular security reviews** of upload directory

### Performance Optimization
1. **Compress large files** before storage when possible
2. **Use efficient file formats** (PDF over images when applicable)
3. **Implement lazy loading** for file listings
4. **Cache user information** to reduce database queries
5. **Monitor upload times** and optimize as needed

### Data Management
1. **Maintain complete audit trails** for all document changes
2. **Regular cleanup** of obsolete or duplicate files
3. **Document retention policies** based on legal requirements
4. **Backup strategies** for critical shipping documents
5. **Disaster recovery plans** for document loss scenarios

---

## 🔧 Technical Implementation Details

### File Upload Process
```php
// File upload with custom library
$handle = new upload($_FILES['uploadedFile']);
$fileName = uploadfile($handle, '../upload/shippingFiles');

// Database update with audit trail
R::exec("UPDATE shippingfile SET $col = '$fileName', 
         $userCol = " . $_SESSION['userid'] . ", 
         $dateCol = '$date' WHERE id = $fileid");
```

### AJAX Response Format
```json
{
    "success": true,
    "data": [
        "file_url",
        "upload_date", 
        "uploader_name"
    ]
}
```

### Database Schema Pattern
For each document type, the system maintains:
- **File column**: Stores actual filename
- **User column**: Tracks who uploaded
- **Date column**: Timestamps the upload

This provides complete audit trail for all shipping documents.