# Electronic Invoice Controller Documentation

**File**: `/controllers/electronicinvoice.php`  
**Purpose**: Frontend interface for Egyptian electronic invoicing system integration and e-bill management  
**Last Updated**: December 20, 2024  
**Total Functions**: 3  
**Lines of Code**: ~147

---

## 📋 Overview

The Electronic Invoice Controller serves as the frontend interface for the Egyptian electronic invoicing system. It provides a user-friendly dashboard for viewing, filtering, and managing e-bills that have been submitted to the Egyptian Tax Authority (ETA). The controller handles bill searches, client filtering, and detail viewing while communicating with the backend eBillRequests.php API for actual data processing.

### Primary Functions
- [x] Display electronic invoicing dashboard with search and filter capabilities
- [x] Show paginated lists of submitted electronic invoices with status
- [x] Filter invoices by export/import status and client
- [x] Display detailed invoice information including tax calculations
- [x] Handle invoice cancellation requests
- [x] Provide client search functionality for filtering
- [x] Display invoice status (Valid, Cancelled, Rejected)
- [x] Generate PDF documents for valid invoices

### Related Controllers
- [eBillRequests.php](eBillRequests.md) - Backend API for electronic invoicing operations
- [sellbillController.php](sellbillController.md) - Sales bill generation and management
- [gt4setting.php](gt4setting.md) - Electronic invoicing configuration
- [clientController.php](clientController.md) - Client management

---

## 🗄️ Database Tables

### Primary Tables (Read Access)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **ebillsetting** | Electronic invoicing configuration | ebillsettingid, eTaxNum, eTaxNumBranch, eGovernorate, eCity, eStreet, eBuildingNum, eCompanyNameInTaxCard, eTaxTypeNum |
| **eclientsetting** | Client electronic invoicing details | id, clientid, etax_num, etax_type, egovernorate, ecity, estreet, ebuilding_num |
| **client** | Client master data | clientid, clientname, taxnumber |

### External API Data
| Data Source | Purpose | Key Fields |
|-------------|---------|------------|
| **Egyptian Tax Authority API** | Electronic invoice data | uuid, internalId, issuerName, receiverName, status, dateTimeReceived, documentTypeNameSecondaryLang |

---

## 🔑 Key Functions

### 1. **Default Action** - Electronic Invoicing Dashboard
**Location**: Lines 7-10  
**Purpose**: Display main electronic invoicing interface with search and filter capabilities

**Function Signature**:
```php
// Triggered when: empty $do
$smarty->display("header.html");
$smarty->display("electronicinvoiceview/index.html");
$smarty->display("footer.html");
```

**Features**:
- Client search functionality
- Export/Import filtering options
- Paginated invoice display
- Status-based filtering
- Date range selection
- Real-time search capabilities

---

### 2. **showajax()** - Invoice Data Retrieval
**Location**: Lines 55-111  
**Purpose**: Handle AJAX requests for paginated invoice data with filtering

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

**Process Flow**:
1. Get filter parameters from POST:
   ```php
   $eexport = filter_input(INPUT_POST, 'eexport');
   $emport = filter_input(INPUT_POST, 'emport');
   $client = filter_input(INPUT_POST, 'client');
   ```

2. Call backend API with pagination:
   ```php
   $response = CURL_IT2(array(
       'pageNo'=> ($_POST['length'] + $_POST['start']) / $_POST['length'],
       'pageSize'=>$_POST['length'], 
       'eexport'=>$eexport, 
       'emport'=>$emport, 
       'client'=>$client, 
       'eTaxNum'=>$ebillsetting['eTaxNum']
   ), "eBillRequests.php?do=bills");
   ```

3. Process response data for DataTable format
4. Add status indicators and action buttons
5. Return JSON response for frontend table

**Invoice Status Processing**:
```php
// Status indicator logic
if ($row->cancelRequestDate && $row->status == 'Valid'){
    $sub_array[] = $row->status . ' ->  cancel';
    $sub_array[] = '';
} elseif ($row->status == 'Valid'){ 
    $sub_array[] = $row->status;    
    $sub_array[] = '<div id="cancel'.$row->uuid.'"><a data-uuid="'.$row->uuid.'" data-sellbillid="'.$row->internalId.'" type="button" class="btn btn-default sendcancel" target="_blank">cancel</a><div>';
} else {
   $sub_array[] = $row->status; 
   $sub_array[] = '';
}
```

**Direction Determination**:
```php
// Determine if invoice is outgoing or incoming
if ($ebillsetting['eTaxNum'] == $row->issuerId){
    $sub_array[] = 'صادر';  // Outgoing
} else {
    $sub_array[] = 'وارد';   // Incoming
}
```

---

### 3. **select2client()** - Client Search AJAX
**Location**: Lines 38-53  
**Purpose**: Provide client search functionality for filtering invoices

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

**Process Flow**:
1. Get search term from POST request
2. Query client table with LIKE search:
   ```php
   $productsData = R::getAll("SELECT taxnumber, clientname as name
   FROM client 
   WHERE clientname LIKE '%" . $name . "%' limit 50");
   ```
3. Format results for Select2 dropdown:
   ```php
   foreach ($productsData as $pro) {
       $row_array['id'] = $pro['taxnumber'];
       $row_array['text'] = $pro['name'];
       array_push($return_arr, $row_array);
   }
   ```
4. Return JSON array for autocomplete functionality

---

### 4. **detail()** - Invoice Detail View
**Location**: Lines 15-24  
**Purpose**: Display detailed information for specific electronic invoice

**Function Signature**:
```php
// Triggered when: do=detail&uuid=X
$uuid = $_GET['uuid'];
$response = CURL_IT2(array('uuid'=> $uuid), "eBillRequests.php?do=bills_detail");
```

**Process Flow**:
1. Get invoice UUID from URL parameter
2. Load e-bill system configuration
3. Call backend API for detailed invoice data
4. Decode JSON response and assign to template
5. Display via `electronicinvoiceview/detail.html`

---

### 5. **cancel()** - Invoice Cancellation View
**Location**: Lines 25-35  
**Purpose**: Display invoice details for cancellation processing

**Function Signature**:
```php
// Triggered when: do=cancel&uuid=X
$uuid = $_GET['uuid'];
$response = CURL_IT2(array('uuid'=> $uuid), "eBillRequests.php?do=bills_detail");
```

**Note**: Currently identical to detail view - cancellation logic handled by backend API

---

### 6. **CURL_IT2()** - Internal API Communication
**Location**: Lines 112-147  
**Purpose**: Handle communication with backend eBillRequests.php API

**Function Signature**:
```php
function CURL_IT2($data_arr, $url)
```

**Process Flow**:
1. Build full URL for internal API call
2. Append session data for authentication:
   ```php
   $data_arr['curlpost'] = '1';
   $data_arr['sessionlist'] = json_encode($_SESSION);
   ```
3. Execute cURL request with SSL verification disabled
4. Return response data for processing

**Security Configuration**:
```php
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
```

---

## 🔄 Workflows

### Workflow 1: Electronic Invoice Dashboard Usage
```
┌─────────────────────────────────────────────────────────────┐
│              START: Access E-Invoice Dashboard             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Dashboard Interface                                │
│     - Display search and filter controls                   │
│     - Initialize DataTable for invoice display             │
│     - Load client search autocomplete                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Applies Filters                                    │
│     - Select export/import direction                        │
│     - Choose specific client (optional)                     │
│     - Set date range (optional)                            │
│     - Configure pagination settings                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. AJAX Request to Backend                                 │
│     - Send filter parameters to showajax()                 │
│     - Include pagination information                       │
│     - Call eBillRequests.php API via CURL_IT2()           │
│     - Receive paginated invoice data                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Process and Display Results                             │
│     - Format invoice data for DataTable                    │
│     - Add status indicators and action buttons             │
│     - Determine invoice direction (صادر/وارد)               │
│     - Handle cancellation status display                   │
│     - Return JSON response to frontend                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. User Interaction Options                                │
│     - View invoice details (detail view)                   │
│     - Cancel valid invoices (if applicable)                │
│     - Filter by different criteria                         │
│     - Navigate through pagination                          │
│     - Generate PDF for valid invoices                      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Electronic invoicing dashboard |
| `do=showajax` | showajax() | AJAX endpoint for invoice data retrieval |
| `do=select2client` | select2client() | AJAX endpoint for client search |
| `do=detail&uuid=X` | detail() | Display detailed invoice information |
| `do=cancel&uuid=X` | cancel() | Display invoice for cancellation |

### Required Parameters by Action

**Dashboard** (`do=` empty):
- No parameters required
- Loads with default empty state

**Invoice Data AJAX** (`do=showajax`):
- `start` - Pagination start position
- `length` - Number of records per page
- `draw` - DataTable draw counter
- `eexport` - Filter for exported invoices (optional)
- `emport` - Filter for imported invoices (optional)
- `client` - Client tax number for filtering (optional)

**Client Search AJAX** (`do=select2client`):
- `searchTerm` - Client name search string

**Invoice Detail** (`do=detail`):
- `uuid` - Electronic invoice unique identifier

**Invoice Cancel** (`do=cancel`):
- `uuid` - Electronic invoice unique identifier

---

## 🧮 Calculation Methods

### Pagination Logic
```php
// Calculate page number for API
$pageNo = ($_POST['length'] + $_POST['start']) / $_POST['length'];

// DataTable response format
$output = array(  
    "draw" => intval($_POST["draw"]),
    "recordsTotal" => count($receivedata->data->items),
    "recordsFiltered" => $receivedata->data->total,
    "data" => array()
);
```

### Status Processing
```php
// Cancel status detection
if ($row->cancelRequestDate && $row->status == 'Valid'){
    $status_display = $row->status . ' ->  cancel';
    $cancel_button = '';  // No cancel button for pending cancellation
}
```

### Direction Determination
```php
// Determine invoice direction based on issuer
if ($ebillsetting['eTaxNum'] == $row->issuerId){
    $direction = 'صادر';  // Outgoing (company is issuer)
} else {
    $direction = 'وارد';   // Incoming (company is receiver)
}
```

---

## 🔒 Security & Permissions

### Session Management
```php
// Session data passed to backend API
$data_arr['curlpost'] = '1';
$data_arr['sessionlist'] = json_encode($_SESSION);
```

### Input Validation
```php
// Safe input filtering
$eexport = filter_input(INPUT_POST, 'eexport');
$emport = filter_input(INPUT_POST, 'emport');
$client = filter_input(INPUT_POST, 'client');
```

### SQL Injection Prevention
```php
// Parameterized queries using RedBeanPHP
$productsData = R::getAll("SELECT taxnumber, clientname as name
FROM client 
WHERE clientname LIKE '%" . $name . "%' limit 50");
```

**Note**: The above query is vulnerable to SQL injection and should use parameterized queries:
```php
// Secure version:
$productsData = R::getAll("SELECT taxnumber, clientname as name
FROM client 
WHERE clientname LIKE ? limit 50", ["%$name%"]);
```

### SSL Configuration
```php
// SSL verification disabled for internal API calls
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
```

---

## 📊 Performance Considerations

### Frontend Optimization
1. **AJAX Loading**: Invoice data loaded asynchronously to improve page load times
2. **Pagination**: Large invoice lists handled with server-side pagination
3. **Caching**: DataTable caching reduces redundant API calls

### Backend Communication
1. **Internal API**: Uses CURL for communication with backend services
2. **Session Handling**: Session data passed efficiently between controllers
3. **Response Caching**: API responses can be cached at backend level

### Database Considerations
1. **Client Search**: Limited to 50 results to prevent performance issues
2. **Index Requirements**: 
   - `client(clientname)` - For name-based searches
   - `client(taxnumber)` - For tax number lookups

---

## 🐛 Common Issues & Troubleshooting

### 1. **No Invoices Displayed**
**Issue**: Dashboard shows empty table despite having electronic invoices  
**Cause**: Backend API connection issues or configuration problems

**Debug**:
```php
// Check e-bill settings
$ebillsetting = R::getRow("SELECT * FROM `ebillsetting`");
var_dump($ebillsetting);

// Test backend API connection
$response = CURL_IT2(array('test' => 1), "eBillRequests.php?do=bills");
echo $response;
```

### 2. **Client Search Not Working**
**Issue**: Client autocomplete returns no results  
**Cause**: SQL injection vulnerability or database connection issues

**Fix**:
```php
// Secure client search query
$name = filter_var($name, FILTER_SANITIZE_STRING);
$productsData = R::getAll("SELECT taxnumber, clientname as name
FROM client 
WHERE clientname LIKE ? AND del = 0 limit 50", ["%$name%"]);
```

### 3. **Invoice Status Not Updating**
**Issue**: Cancelled invoices still show as valid  
**Cause**: Backend API not synchronizing with Egyptian Tax Authority

**Debug**:
```sql
-- Check recent invoice status updates
SELECT * FROM etasellbillstatus 
WHERE estatus = -1 
ORDER BY today DESC LIMIT 10;
```

### 4. **PDF Generation Fails**
**Issue**: PDF button does not work for valid invoices  
**Cause**: External API connectivity or authentication issues

**Check**:
- Verify Egyptian Tax Authority API token validity
- Check network connectivity to external API
- Validate invoice UUID format

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Dashboard Access
```
1. Navigate to electronic invoice dashboard
2. Verify page loads without errors
3. Check that filter controls are displayed
4. Confirm DataTable initializes properly
```

### Test Case 2: Invoice Filtering
```
1. Select "Exported" invoices filter
2. Choose specific client from dropdown
3. Apply filters and verify results
4. Check pagination works correctly
```

### Test Case 3: Client Search Functionality
```
1. Click on client search dropdown
2. Type partial client name
3. Verify autocomplete suggestions appear
4. Select client and confirm filter applies
```

### Test Case 4: Invoice Detail View
```
1. Click on invoice detail button
2. Verify detail page loads with correct data
3. Check all invoice fields are displayed
4. Confirm back navigation works
```

### Debug Mode Enable
```php
// Add at top of controller for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Debug API responses
echo "<pre>";
print_r($receivedata);
echo "</pre>";

// Debug client search
echo "Search term: " . $name . "<br>";
echo "Results: " . count($productsData) . "<br>";
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [eBillRequests.md](eBillRequests.md) - Backend electronic invoicing API
- [gt4setting.md](gt4setting.md) - System configuration management
- [sellbillController.md](sellbillController.md) - Sales bill generation
- [Egyptian Tax Authority Documentation](https://eta.gov.eg) - Official e-invoicing guidelines

---

## ⚠️ Security Vulnerabilities Identified

### 1. **SQL Injection in Client Search**
**Location**: Line 43-45  
**Risk**: High  
**Fix Required**: Use parameterized queries

### 2. **Cross-Site Scripting (XSS)**
**Location**: Line 45 (client name in query)  
**Risk**: Medium  
**Fix Required**: Sanitize input before database query

### 3. **Session Security**
**Location**: Line 118 (session data in CURL)  
**Risk**: Low  
**Note**: Internal API communication only

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Security Review**: ⚠️ Vulnerabilities identified  
**Next Review**: When electronic invoicing requirements change