# Import Contract Controller Documentation

**File**: `/controllers/importContractController.php`  
**Purpose**: Manages import contracts for vehicles including chassis numbers, contract details, and client associations  
**Last Updated**: December 20, 2024  
**Total Functions**: 8+  
**Lines of Code**: ~279

---

## 📋 Overview

The Import Contract Controller manages vehicle import contracts and related documentation. It handles:
- Import contract creation and management
- Vehicle chassis number tracking and validation
- Contract document uploads and storage
- Client-contract associations
- Contract search and filtering
- Vehicle details (brand, model, color, motor, etc.)
- Contract value and payment tracking
- Integration with product serial numbers

### Primary Functions
- [x] Create new import contracts
- [x] Edit existing contracts  
- [x] Delete/archive contracts
- [x] Upload contract images/documents
- [x] Validate chassis number uniqueness
- [x] Search and filter contracts
- [x] Link contracts to clients
- [x] Track vehicle specifications
- [x] Ajax-based data loading
- [x] User permission management

### Related Controllers
- [sellbillController.php](sellbillController.md) - Vehicle sales
- [clientController.php](#) - Customer management
- [productController.php](#) - Product management
- [buybillController.php](#) - Purchase operations

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **importcontract** | Main contract records | id, clientid, chasisno, brand, carmodel, carcolor, cartype, contractvalue, carnumber, carmotor, contractimage, notes, sysdate, user_id, del |
| **client** | Customer information | clientid, clientname, conditions, delegateid |

### Referenced Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **productserial** | Vehicle serial tracking | billid, chassisNo, del, conditions |
| **buybill** | Purchase bills | buybillid, conditions |
| **user** | System users | userid, delegateid |

---

## 🔑 Key Functions

### 1. **Default Action (empty $do)** - Add Contract Form
**Location**: Line 25  
**Purpose**: Display form for creating new import contracts

**Process Flow**:
1. Load user permissions and client data
2. Query available chassis numbers from product serials
3. Display add contract form with dropdown data
4. Set Smarty template variables

**Template Variables**:
- `$allClients` - Available customers
- `$allChasis` - Available chassis numbers
- `$customsellbillModel` - UI flag

---

### 2. **show** - Contract Listing
**Location**: Line 43  
**Purpose**: Display contracts with search and filter capabilities

**Features**:
- Permission-based client filtering
- Date range filtering
- Show/hide deleted contracts
- Ajax-powered data tables

---

### 3. **edit** - Edit Contract Form  
**Location**: Line 63  
**Purpose**: Load and display contract for editing

**Process Flow**:
1. Load contract data by ID
2. Load related client information
3. Populate form with existing data
4. Display edit template

---

### 4. **savedata()** - Save/Update Contract
**Location**: Line 124  
**Purpose**: Create new contract or update existing one

**Function Signature**:
```php
function savedata()
```

**Process Flow**:
1. Extract form data from POST
2. Handle image upload using upload class
3. Create new contract record or load existing
4. Set contract properties
5. Store to database with error handling

**Key Fields**:
- `clientid` - Associated customer
- `brand`, `carmodel`, `carcolor` - Vehicle specifications
- `chasisno` - Unique chassis identifier
- `cartype` - New (0) or Used (1)
- `contractvalue` - Contract monetary value
- `carnumber`, `carmotor` - Vehicle identifiers
- `contractimage` - Uploaded document image

**Image Handling**:
```php
$handle = new upload($_FILES['contractimage']);
$contractimage = uploadImages($handle, "../views/default/images/importcontract", 300, 300);
```

---

### 5. **showajax()** - Ajax Data Provider
**Location**: Line 180  
**Purpose**: Provide contract data for DataTables with server-side processing

**Function Signature**:
```php
function showajax()
```

**Features**:
- Server-side pagination
- Search functionality
- Date range filtering
- Client-based filtering
- Sorting capabilities
- Permission-based data access

**Search Filters**:
- `start_date`, `end_date` - Date range
- `del` - Deletion status filter
- `data1` - Client ID filter
- Global search across ID, date, client name

**Response Format**:
```php
$output = array(
    "draw" => intval($_POST["draw"]),
    "recordsTotal" => intval($apps),
    "recordsFiltered" => $totals,
    "data" => array()
);
```

---

### 6. **removecontroller()** - Soft Delete
**Location**: Line 262  
**Purpose**: Mark contract as deleted without physical removal

**Process Flow**:
1. Load contract record by ID
2. Set deletion flag (del = 2)
3. Record deletion date and user
4. Save changes

---

### 7. **getChasisData** - Chassis Information Lookup
**Location**: Line 96  
**Purpose**: Retrieve vehicle data by chassis number

**Returns**:
```json
{
    "carnumber": "ABC123",
    "carmotor": "V6-2.5L", 
    "cartype": "جديد"
}
```

---

### 8. **checkExist** - Chassis Uniqueness Validation
**Location**: Line 108  
**Purpose**: Validate chassis number uniqueness during creation/editing

**Logic**:
```php
$exist = R::getCell('SELECT COUNT(*) FROM importcontract WHERE chasisno = ? '.$qs, [$chasisNo]);
echo $exist > 0 ? 1 : 0;
```

---

## 🔄 Workflows

### Workflow 1: Create New Import Contract
```
┌─────────────────────────────────────────────────────────────┐
│                    START: Access Add Form                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Form Data                                          │
│     - Load user permissions                                 │
│     - Query available clients                               │
│     - Load chassis numbers from product serials            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Fills Contract Form                                │
│     - Select client                                         │
│     - Enter vehicle details                                 │
│     - Upload contract image                                 │
│     - Set contract value                                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Validate Data (Ajax)                                    │
│     - Check chassis uniqueness                              │
│     - Validate required fields                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Contract                                           │
│     - Process image upload                                  │
│     - Create database record                                │
│     - Set audit fields                                      │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Contract Management
```
┌─────────────────────────────────────────────────────────────┐
│                START: View Contracts                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Apply Filters                                           │
│     - Date range                                            │
│     - Client selection                                      │
│     - Status (active/deleted)                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Results                                         │
│     - Paginated table view                                  │
│     - Search functionality                                  │
│     - Action buttons (edit/delete)                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Contract Actions                                        │
│     - Edit → Load edit form                                 │
│     - Delete → Soft delete with confirmation                │
│     - View Image → Display contract document                │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Show add contract form |
| `do=show` | show | Display contracts list |
| `do=edit` | edit | Show edit contract form |
| `do=savedata` | `savedata()` | Save/update contract |
| `do=showajax` | `showajax()` | Ajax data provider |
| `do=removecontroller` | `removecontroller()` | Soft delete contract |
| `do=getChasisData` | - | Get vehicle data by chassis |
| `do=checkExist` | - | Validate chassis uniqueness |

---

## 🔒 Security & Permissions

### User Permission Levels
```php
$userData = R::getRow('SELECT * FROM user WHERE userid = ?', [$_SESSION['userid']]);
if ($userData['viewclients'] == 1) {
    $allClients = R::getAll('select * from client where conditions = 0');
} else {
    $allClients = R::getAll('select * from client where conditions = 0 and delegateid = ?', [$_SESSION['userid']]);
}
```

**Permission Logic**:
- Users see all clients if `viewclients = 1`
- Restricted users only see clients assigned to them (`delegateid`)

### Input Validation
- All POST inputs filtered with `filter_input(INPUT_POST, 'field')`
- Chassis number uniqueness validation
- File upload validation through upload class
- SQL injection prevention via parameterized queries

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Required**:
   - `importcontract(chasisno)` - Unique constraint
   - `importcontract(clientid)` - Foreign key
   - `importcontract(sysdate)` - Date filtering
   - `client(delegateid)` - Permission filtering

2. **Query Efficiency**:
   - Ajax pagination reduces memory usage
   - JOIN queries combine related data
   - Proper WHERE clauses for filtering

### File Storage
- Images resized to 300x300 for consistency
- Organized in `/images/importcontract/` directory
- Old images removed during updates

---

## 🐛 Common Issues & Troubleshooting

### 1. **Chassis Number Conflicts**
**Issue**: Duplicate chassis numbers not allowed  
**Solution**: Real-time validation via `checkExist` action

### 2. **Image Upload Failures**
**Issue**: Contract images not saving  
**Debug**: Check upload directory permissions and file size limits

### 3. **Permission Issues**
**Issue**: Users can't see contracts  
**Check**: User's `viewclients` setting and `delegateid` assignments

### 4. **Ajax Loading Problems**
**Issue**: Contract table not loading  
**Debug**: Check browser console for JavaScript errors and server response

---

## 🧪 Testing Scenarios

### Test Case 1: Contract Creation
```
1. Access add form
2. Fill required fields
3. Upload valid contract image
4. Submit form
5. Verify database record created
6. Check image file saved
```

### Test Case 2: Chassis Validation
```
1. Enter existing chassis number
2. Verify validation error appears
3. Enter unique chassis number
4. Verify validation passes
```

### Test Case 3: Permission Enforcement
```
1. Login as restricted user
2. Verify only assigned clients appear
3. Test contract access restrictions
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientController.php](#) - Customer management
- [sellbillController.md](sellbillController.md) - Vehicle sales operations
- [Upload Images Documentation](#) - File upload handling

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur