Supplier Documentation
Supplier Controller Documentation
File: /controllers/supplierController.php
Purpose: Manages supplier/vendor operations, debt tracking, and supplier-client relationships
Last Updated: December 19, 2024
Total Functions: 14
Lines of Code: 1113
---
๐ Overview
The Supplier Controller is responsible for comprehensive supplier/vendor management in the ERP system. It handles:
- โข Creating and editing supplier records with detailed information
- โข Managing supplier debt tracking in multiple currencies
- โข Supplier categorization and type management
- โข Supplier-client relationship linking (bidirectional business relationships)
- โข Excel import/export for bulk supplier operations
- โข Supplier geographical and contact management
- โข Accounting integration for supplier transactions
- โข Multi-currency debt management
Primary Functions
- โ Create new suppliers with full profile information
- โ Edit existing supplier records
- โ Delete suppliers (with validation)
- โ View supplier lists with filtering and debt summaries
- โ Supplier debt management with currency support
- โ Excel import for bulk supplier creation
- โ Supplier-client linking functionality
- โ Batch operations on suppliers
- โ Print supplier details and records
- โ Multi-currency debt tracking and conversion
- โ Category and type-based supplier organization
Related Controllers
- โข buyBillController.php - Purchase operations from suppliers
- โข clientController.php - Client-supplier linking
- โข productController.php - Product management (supplier products)
- โข sellbillController.php - Sales-related supplier operations
- โข dailyentryController.php - Supplier accounting entries
- โข supplierdebtchangeController.php - Debt change tracking
- โข currencyController.php - Currency management for supplier debts
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **supplier** | Main supplier records | supplierid, suppliername, suppliercurrentDebt, supplieraddress, supplierphone | |
| **supplierdebtchange** | Supplier debt tracking | supplierdebtchangeid, supplierid, supplierdebtchangeamount, debtchangamountInSupplierCurrency | |
| **productcat** | Product categories | Links suppliers to product categories they supply | |
| **typesupplier** | Supplier types | Categorizes suppliers by business type |
| Table Name | Purpose | Usage | |
|---|---|---|---|
| **goverarea** | Supplier geographical areas | Supplier location management | |
| **government** | Government/state data | Geographical hierarchy | |
| **clientarea** | Area details | Location subdivision | |
| **client** | Client records | Supplier-client linking (linkedSupplierId) | |
| **accountstree** | Accounting integration | Supplier accounts (treeId) | |
| **dailyentry** | Accounting entries | Supplier transaction records | |
| **currency** | Currency management | Multi-currency debt support |
| Table Name | Usage | |
|---|---|---|
| **user** | Supplier creation/modification tracking | |
| **programsetting** | System configuration settings | |
| **youtubelink** | Help video links |
๐ง Key Functions
1. add() - Create New Supplier
Signature: add(): void
Purpose: Creates a comprehensive supplier record with accounting integration
Parameters: Gets extensive data from $_POST array
Process Flow:
Key Features:
- โข Category Assignment: Links suppliers to product categories they supply
- โข Type Management: Assigns suppliers to business type categories
- โข Geographic Data: Stores detailed location information
- โข Contact Management: Handles multiple contact persons (warranty officer, seller)
- โข Currency Support: Manages debt in supplier's preferred currency
- โข Client Linking: Three options: no link, create new client, link to existing client
- โข Accounting Integration: Creates tree element and daily entry for initial debt
- โข Tax Management: Stores tax numbers and related information
Client Linking Logic:
if ($suppIsClientToo == 2) {
// Link to existing client
CURL_IT2(array('clientid' => $client, 'supplierid' => $supplierid), 'clientControllerAjax.php?do=linkToSupplier');
} elseif ($suppIsClientToo == 1) {
// Create new client linked to this supplier
$linkedClientId = CURL_IT2(array('txtName' => $supplier->suppliername, 'linkedSupplierId' => $supplierid, ...), 'clientController.php?do=addSimpleReturn');
} else {
// No client link
CURL_IT2(array('clientid' => 0, 'supplierid' => $supplierid), 'clientControllerAjax.php?do=linkToSupplier');
}
2. addFromExcel() - Bulk Supplier Import
Signature: addFromExcel(): void
Purpose: Imports suppliers from Excel file with transaction support
Parameters: Excel file from $_FILES and options from $_POST
Process Flow:
Excel Format Support:
- โข Supplier name, address, phone, debt amount
- โข Contact details and notes
- โข Automatic tree element creation
- โข Transaction rollback on errors
- โข Duplicate name checking
3. show() - Display Supplier List
Signature: show(): void
Purpose: Displays comprehensive supplier list with debt summaries
Parameters: Filter options from $_REQUEST
Features:
- โข Status Filtering: Active vs deleted suppliers
- โข Debt Calculation: Sums total supplier debts
- โข Extended Information: Shows categories, contacts, and payment details
- โข Responsive Display: Adapts to different view requirements
Status Control:
if ($_REQUEST['showdelete'] == 1) {
$alldata = $supplierDAO->queryAll(); // Include deleted
$shownData = $supplierExt->queryAllForShow();
} else {
$alldata = $supplierDAO->queryByCondition(0); // Active only
$shownData = $supplierExt->queryAllForShowWithCondition();
}
4. showwithsearch($supplierid) - Show Specific Supplier
Signature: showwithsearch($supplierid): void
Purpose: Displays details for a specific supplier with debt information
Parameters:
- โข
$supplierid(int): Supplier ID to display
5. edit() - Load Supplier for Editing
Signature: edit(): object
Purpose: Retrieves supplier data with related information for editing
Parameters: Gets id from $_GET
Returns: Supplier object with parsed categories and types
Data Processing:
// Parse categories
$loadData->category_id = explode(',', $loadData->category_id);
// Parse supplier types
$loadData->typesupplier_id = explode(',', $loadData->typesupplier_id);
// Get linked client information
if ($loadData->linkedClientId > 0) {
$clientData = $clientDAO->load($loadData->linkedClientId);
$loadData->linkedClientName = $clientData->clientname;
}
6. update() - Update Supplier Record
Signature: update(): void
Purpose: Updates existing supplier with new information
Parameters: Gets data from $_POST array
Update Process:
Tree Element Update:
$treeId = $oldSupplier->treeId;
$getRow = $accountsTreeDAO->load($treeId);
$accountsTree->name = $suppliername;
$accountsTree->customName = $suppliername;
$accountsTree->parent = ($supplierTypeForTree == 0) ? 81 : 87;
editTreeElement($accountsTree);
7. deleteFinaly() - Permanent Supplier Deletion
Signature: deleteFinaly(): array
Purpose: Permanently deletes supplier after validation
Parameters: Gets id from $_GET
Returns: Array [message, status_code]
Validation Process:
$supplierData = $SupplierdebtchangeEX->queryBySupplierIdNotDeleted($id);
if (count($supplierData) <= 1) { // Only initial debt record
// Safe to delete
$supplierExt->deleteFinallyWithName($id, $rowDelData->suppliername . '-del');
reverseEntryWithItsID($action);
delTreeElementById($rowDelData->treeId);
} else {
// Has transactions, cannot delete
}
Protection Logic:
- โข Prevents deletion of supplier ID 1 (system supplier)
- โข Checks for existing transactions beyond initial debt
- โข Reverses accounting entries before deletion
- โข Removes tree elements from chart of accounts
8. tempdelete($supplierid) - Hide Supplier
Signature: tempdelete($supplierid): string
Purpose: Hides supplier (soft delete) by appending '-del' to name
Parameters:
- โข
$supplierid(int): Supplier ID to hide
Returns: "success" or error message
Implementation:
$supplier = $supplierDAO->load($supplierid);
$supplierExt->deletetempWithName($supplierid, $supplier->suppliername . '-del');
9. returndelete($supplierid) - Restore Supplier
Signature: returndelete($supplierid): void
Purpose: Restores hidden supplier by removing '-del' from name
Parameters:
- โข
$supplierid(int): Supplier ID to restore
Implementation:
$supplier = $supplierDAO->load($supplierid);
if (strpos($supplier->suppliername, "-del") !== false) {
$name = str_replace("-del", "", $supplier->suppliername);
$supplierExt->returndeleteWithName($supplierid, $name);
} else {
$supplierExt->returndelete($supplierid);
}
10. executeOperation() - Batch Operations
Signature: executeOperation(): void
Purpose: Performs batch operations on selected suppliers
Parameters: Gets operation type and selected items from $_POST
Supported Operations:
1. Hide Suppliers (1): Soft delete multiple suppliers
2. Restore Suppliers (2): Restore hidden suppliers
11. getCategoriesWithProducts() - Get Product Categories
Signature: getCategoriesWithProducts(): array
Purpose: Retrieves product categories that have products
Returns: Array of categories for supplier assignment
12. getTypeSupplier() - Get Supplier Types
Signature: getTypeSupplier(): array
Purpose: Retrieves all available supplier types
Returns: Array of supplier types for categorization
13. CURL_IT2($data_arr, $url) - Internal API Communication
Signature: CURL_IT2($data_arr, $url): string
Purpose: Handles internal CURL requests for inter-controller communication
Parameters:
- โข
$data_arr(array): Data to send - โข
$url(string): Target controller endpoint
Returns: Response from target controller
Usage Examples:
// Link supplier to client
CURL_IT2(array('clientid' => $client, 'supplierid' => $supplierid), 'clientControllerAjax.php?do=linkToSupplier');
// Create linked client
CURL_IT2(array('txtName' => $supplier->suppliername, 'linkedSupplierId' => $supplierid, ...), 'clientController.php?do=addSimpleReturn');
---
๐ Workflows
Supplier Registration Workflow
Supplier-Client Linking Workflow
Supplier Deletion Workflow
---
๐ URL Routes & Actions
| Route | Action | Purpose | Authentication | |
|---|---|---|---|---|
| `supplierController.php` | Default (empty do) | Show add supplier form | Required | |
| `?do=add` | `add()` | Process supplier creation | Required | |
| `?do=addexcel` | N/A | Show Excel upload form | Required | |
| `?do=addfromexcel` | `addFromExcel()` | Process Excel import | Required | |
| `?do=show&supplierid={id}` | `show()` | Display supplier list or specific supplier | Required | |
| `?do=edit&id={id}` | `edit()` | Show edit supplier form | Required | |
| `?do=update` | `update()` | Process supplier update | Required | |
| `?do=deleteFinaly&id={id}` | `deleteFinaly()` | Delete supplier permanently | Required | |
| `?do=tempdelete&id={id}` | `tempdelete()` | Hide supplier (soft delete) | Required | |
| `?do=returndelete&id={id}` | `returndelete()` | Restore hidden supplier | Required | |
| `?do=executeOperation` | `executeOperation()` | Batch operations | Required | |
| `?do=editprint&id={id}` | `edit()` | Show printable edit form | Required | |
| `?do=updateDebtsInTermsOfCurrency` | N/A | Update all supplier debts based on currency | Required | |
| `?do=success` | N/A | Show success message | None | |
| `?do=error` | N/A | Show error message | None |
All main actions support CURL requests by setting $_POST['curlpost'] = 1:
- โข Returns JSON responses with status codes
- โข Includes Arabic and English error messages
- โข Supports integration with other controllers
- โข Used for internal supplier-client linking operations
---
๐ Known Issues & Fixes
1. Currency Debt Management
Issue: Multi-currency debt calculations can become inconsistent
Fix: Implement regular currency debt synchronization
Code Fix:
// Add currency validation
if ($sullpierCurrencyid > 0) {
$currency = $currencyDAO->load($sullpierCurrencyid);
if (!$currency) {
throw new Exception("Invalid currency selected");
}
}
2. Supplier Name Soft Delete
Issue: Name collision when restoring suppliers with '-del' suffix
Fix: Improved name handling for soft delete/restore
Code Fix:
function tempdelete($supplierid) {
$supplier = $supplierDAO->load($supplierid);
$newName = $supplier->suppliername . '-del-' . time(); // Add timestamp
$supplierExt->deletetempWithName($supplierid, $newName);
}
3. Client Linking Race Conditions
Issue: Concurrent client-supplier linking operations can cause conflicts
Fix: Add transaction locks and validation
Code Fix:
// Wrap linking operations in transactions
$mytransactions = new Transaction();
try {
$clientExt->removeAnyClientLinkForASupplier($supplierid);
CURL_IT2($linkData, $linkUrl);
$mytransactions->commit();
} catch (Exception $e) {
$mytransactions->rollback();
throw $e;
}
4. Excel Import Validation
Issue: Excel import needs better validation for required fields
Fix: Comprehensive validation before processing
Code Fix:
// Validate required fields
if (empty($suppliername) || empty($supplieraddress)) {
continue; // Skip invalid rows
}
// Check for valid numeric debt
if (!is_numeric($suppliercurrentDebt)) {
$suppliercurrentDebt = 0;
}
---
๐ Security & Permissions
Authentication Requirements
- โข All operations require valid user session
- โข Authentication checked via
../public/authentication.php - โข User ID tracked in all database operations
- โข Session validation for internal CURL requests
Data Validation
- โข Supplier name validation (required, uniqueness check)
- โข Phone number format validation
- โข Debt amount validation (numeric, proper formatting)
- โข Category and type ID validation against existing records
- โข Currency ID validation for multi-currency support
SQL Injection Prevention
- โข Uses DAO pattern with prepared statements
- โข RedBean ORM for additional query safety
- โข Parameter binding for all database operations
- โข CURL parameter sanitization for internal requests
Permission Controls
include_once("../public/authentication.php");
// All supplier operations require authentication
Internal API Security
function CURL_IT2($data_arr, $url) {
// Add session data for internal requests
$data_arr['curlpost'] = '1';
$data_arr['sessionlist'] = json_encode($_SESSION);
// Disable SSL verification for internal calls
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
---
๐งช Testing & Debugging
Test Cases
Supplier Creation
1. Valid Supplier Creation
- Input: Complete supplier data with categories and types
- Expected: Supplier created, tree element added, debt change recorded
2. Duplicate Supplier Name
- Input: Existing supplier name
- Expected: No insertion, proper error handling
3. Client Linking Test
- Input: Supplier with client linking option
- Expected: Supplier and client created/linked properly
Multi-Currency Support
1. Currency Debt Creation
- Input: Supplier with specific currency and debt amount
- Expected: Both local and currency debt amounts stored
2. Currency Conversion Updates
- Input: Trigger currency update function
- Expected: All supplier debts updated based on current rates
Bulk Operations
1. Excel Import
- Input: Valid Excel file with supplier data
- Expected: All valid suppliers created, duplicates skipped
2. Batch Hide/Restore
- Input: Multiple supplier IDs for operation
- Expected: All selected suppliers processed correctly
Debugging Tips
1. Check Supplier Dependencies:
SELECT COUNT(*) FROM supplierdebtchange
WHERE supplierid = ? AND processname != 'ุฅุถุงูุฉ ู
ูุฑุฏ ุฌุฏูุฏ'
2. Verify Tree Integration:
SELECT * FROM accountstree WHERE id IN (SELECT treeId FROM supplier WHERE supplierid = ?)
3. Monitor Debt Changes:
SELECT * FROM supplierdebtchange
WHERE supplierid = ?
ORDER BY supplierdebtchangedate DESC
4. Debug Client Linking:
SELECT c.clientname, s.suppliername
FROM client c
JOIN supplier s ON c.linkedSupplierId = s.supplierid
WHERE s.supplierid = ?
5. Check Category Assignments:
SELECT pc.productcatname
FROM productcat pc
WHERE FIND_IN_SET(pc.productcatid, (SELECT category_id FROM supplier WHERE supplierid = ?))
---
โก Performance Considerations
Query Optimization
- โข Supplier List: Implement pagination for large datasets
- โข Category Filtering: Use proper indexes on category_id field
- โข Debt Calculations: Consider caching debt summaries
- โข Client Linking: Optimize CURL request handling
Indexing Recommendations
-- Supplier table indexes
CREATE INDEX idx_supplier_name ON supplier(suppliername);
CREATE INDEX idx_supplier_conditions ON supplier(conditions);
CREATE INDEX idx_supplier_category ON supplier(category_id);
CREATE INDEX idx_supplier_type ON supplier(typesupplier_id);
CREATE INDEX idx_supplier_currency ON supplier(sullpierCurrencyid);
-- Debt change indexes
CREATE INDEX idx_supplierdebt_supplier ON supplierdebtchange(supplierid);
CREATE INDEX idx_supplierdebt_date ON supplierdebtchange(supplierdebtchangedate);
Memory Management
- โข Stream large Excel files instead of loading entirely
- โข Use result set pagination for supplier lists
- โข Optimize CURL request handling
- โข Implement proper session management for internal requests
Caching Strategy
- โข Cache supplier type and category lists
- โข Store calculated debt totals temporarily
- โข Cache currency conversion rates
- โข Use session caching for user permissions
CURL Optimization
- โข Implement connection pooling for internal requests
- โข Add timeout controls for CURL operations
- โข Use async requests where possible
- โข Monitor and log CURL performance
---
๐ Related Documentation
- โข Buy Bill Controller - Purchase operations from suppliers
- โข Client Controller - Client-supplier relationship management
- โข Sell Bill Controller - Sales-related operations
- โข Daily Entry Controller - Supplier accounting entries
- โข Supplier Debt Change Controller - Detailed debt tracking
- โข Currency Management - Multi-currency support
- โข Product Category Management - Category assignment system
- โข Excel Import/Export - Bulk operations documentation
- โข Internal API Documentation - CURL communication between controllers
---
Last Updated: December 19, 2024
Version: 1.0
Maintainer: ERP Development Team