# Save Controller (Cash Management) Documentation

**File**: `/controllers/saveController.php`  
**Purpose**: Manages cash registers (safes) and cash flow operations  
**Last Updated**: December 19, 2024  
**Total Functions**: 9  
**Lines of Code**: 628

---

## 📋 Overview

The Save Controller manages cash registers (safes/vaults) in the ERP system. It handles:
- Cash register creation and management
- Multi-currency cash register support
- Cash flow tracking and reconciliation
- Opening balance management for cash registers
- Cash register categorization by type
- Automatic chart of accounts integration
- Cash movement logging (savedaily)
- Currency conversion handling
- Cash register sorting and organization
- Integration with daily journal entries

### Primary Functions
- [x] Create and configure cash registers
- [x] Manage multiple currencies per cash register
- [x] Track cash movements and balances
- [x] Handle opening balances with journal entries
- [x] Categorize cash registers by type
- [x] Sort and organize cash registers
- [x] Generate chart of accounts entries
- [x] Log all cash movements for audit
- [x] Support CURL API operations
- [x] Multi-language support

### Related Controllers
- [dailyentry.php](dailyentry.md) - Auto journal entries for cash operations
- [expensesController.php](expensesController.md) - Cash expense payments
- [sellbillController.php](sellbillController.md) - Cash sales receipts
- [buyBillController.php](buyBillController.md) - Cash purchase payments
- [bankController.php](#) - Bank account integration
- [accountstree.php](accountstree.md) - Chart of accounts integration

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Main cash registers | saveid, savename, savecurrentvalue, currencyId, savetypeid, treeId, conditions, sortby |
| **savedaily** | Cash movement history | savedailydate, saveid, savedailychangeamount, savedailychangetype, processname, userid |
| **savetype** | Cash register categories | id, name, del |

### Integration Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **currency** | Multi-currency support | Used by save.currencyId |
| **accountstree** | Chart of accounts | Auto-created for each cash register |
| **dailyentry** | Journal entries | Auto-generated for cash operations |
| **dailyentrycreditor** | Credit entries | Cash account credits |
| **dailyentrydebtor** | Debit entries | Cash account debits |

### Tracking Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **user** | User management | Tracks who creates/modifies cash registers |
| **branch** | Branch management | Multi-branch cash register support |

---

## 🔧 Key Functions

### 1. Main Display (Default Action)
**Purpose**: Display cash register creation form  
**Line**: 116

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Authentication  │───▶│ Load Currencies  │───▶│ Load Save Types │
│ Check           │    │ List             │    │ List            │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Set Breadcrumb  │    │ Assign to        │    │ Display Add     │
│ Navigation      │    │ Smarty Template  │    │ Form            │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### 2. add()
**Purpose**: Create new cash register with opening balance  
**Line**: 338

**Parameters** (via $_POST):
- `savename` - Cash register name
- `savecurrentvalue` - Opening balance amount
- `savedetails` - Additional details
- `currencyId` - Currency ID
- `sortby` - Display sort order
- `saveTreeParentType` - Account tree parent type (0=assets, 1=liabilities)
- `savetypeid` - Cash register type/category

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Validate Name   │───▶│ Calculate        │───▶│ Create Chart    │
│ Uniqueness      │    │ Currency Value   │    │ Account Element │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Insert Cash     │    │ Log Initial      │    │ Create Opening  │
│ Register Record │    │ Movement         │    │ Journal Entry   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Critical Business Logic**:
1. **Name Validation**: Checks for duplicate cash register names
2. **Currency Conversion**: Converts amounts to main currency using conversion factor
3. **Chart of Accounts**: Auto-creates account tree element
4. **Journal Entry**: Creates opening balance entry (Dr. Cash, Cr. Capital)
5. **Movement Logging**: Records initial cash movement

**Account Tree Integration**:
```php
// Parent assignment based on type
$parent = 40;  // Assets (default)
if ($saveTreeParentType == 1) {
    $parent = 408;  // Liabilities
}
```

### 3. show()
**Purpose**: Display cash register listing with filtering  
**Line**: 428

**Filtering Options**:
- Cash register type filtering
- User permission-based filtering
- Single vs. multiple cash register view

**Access Control**:
```php
if ($_SESSION['searchinonesave'] == 0) {
    // User can see multiple cash registers
    if ($_SESSION['saveids'] == 0) {
        // See all cash registers
    } else {
        // See specific cash register IDs
    }
} else {
    // User restricted to single cash register
}
```

### 4. delete()
**Purpose**: Soft delete/restore cash register  
**Line**: 460

**Parameters**:
- `condition` - Delete flag (0=active, 1=deleted)
- `saveid` - Cash register ID

**Process**: Changes condition status without removing data

### 5. deleteFinaly()
**Purpose**: Permanently delete cash register  
**Line**: 485

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Cash       │───▶│ Delete Database  │───▶│ Delete Chart    │
│ Register Data   │    │ Record           │    │ Account Element │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Warning**: Permanent deletion removes all associated data including chart of accounts element.

### 6. edit()
**Purpose**: Load cash register data for editing  
**Line**: 502

**Returns**: Cash register data with currency information

### 7. editprint()
**Purpose**: Load cash register data for print view  
**Line**: 520

**Similar to edit() but optimized for printing

### 8. update()
**Purpose**: Update existing cash register  
**Line**: 539

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Existing   │───▶│ Update Database  │───▶│ Update Chart    │
│ Record          │    │ Record           │    │ Account Element │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Chart Account Sync**:
```php
$oldTree->name = $saveName;
$oldTree->customName = $saveName;
$parent = 40;  // Assets
if ($saveTreeParentType == 1) {
    $parent = 408;  // Liabilities
}
$oldTree->parent = $parent;
```

### 9. insertSavedaily(...)
**Purpose**: Log cash movement in daily cash log  
**Line**: 608

**Parameters**:
- `$savedailysavebefore` - Balance before transaction
- `$savedailychangeamount` - Transaction amount
- `$savedailychangetype` - Change type (0=decrease, 1=increase)
- `$saveid` - Cash register ID
- `$processname` - Description of operation
- `$savedailymodelid` - Related record ID
- `$savedailysaveafter` - Balance after transaction
- `$tablename` - Source table name

**Usage**: Called by all cash operations for audit trail

---

## 🔄 Business Logic Flow

### Cash Register Creation Workflow
```
User Input
    │
    ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Name Uniqueness │───▶│ Currency         │───▶│ Chart Account   │
│ Validation      │    │ Conversion       │    │ Creation        │
└─────────────────┘    └──────────────────┘    └─────────────────┘
    │                           │                       │
    ▼                           ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Database Insert │    │ Opening Journal  │    │ Movement        │
│ (Transaction)   │    │ Entry            │    │ Logging         │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### Currency Conversion Logic
```php
$saveConversionFactor = R::getCell("select conversionFactor from currency where id = ?", [$currencyId]);
$savecurrentValueInMainCurrency = $savecurrentValue / $saveConversionFactor;
```

### Journal Entry for Opening Balance
```
Dr. Cash Account (Auto-created)    $amount
    Cr. Capital Account (121)           $amount

Entry Comment: "إضافة في [Cash Register Name]"
```

### Access Control Patterns
1. **Single Cash Register**: User restricted to one cash register
2. **Multiple Cash Registers**: User can access all or specific subset
3. **Permission-Based**: Filter based on user's assigned cash registers

---

## ⚠️ Common Issues

### 1. Duplicate Cash Register Names
**Issue**: Attempting to create cash register with existing name  
**Prevention**: Name uniqueness validation in add() function:
```php
$checkName = $mySaveRecord->queryBySavename($saveName);
if (!empty($checkName)) {
    return 1; // Name exists error
}
```

### 2. Currency Conversion Errors
**Issue**: Incorrect currency conversions  
**Solution**: Verify currency conversion factors:
```php
$saveConversionFactor = R::getCell("select conversionFactor from currency where id = ?", [$currencyId]);
```

### 3. Chart of Accounts Sync Issues
**Issue**: Cash register name changes not reflected in accounts  
**Solution**: Update both save record and chart account:
```php
$oldTree->name = $saveName;
$oldTree->customName = $saveName;
editTreeElement($oldTree);
```

### 4. Transaction Rollback Failures
**Issue**: Partial updates on transaction failure  
**Prevention**: Proper transaction handling:
```php
$mytransactions = new Transaction();
try {
    // Operations
    $mytransactions->commit();
} catch (Exception $ex) {
    $mytransactions->rollback();
}
```

### 5. Cash Movement Audit Gaps
**Issue**: Missing cash movement logs  
**Solution**: Always call insertSavedaily() for cash operations

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/authentication.php` - Security
- `../public/include_dao.php` - Database layer
- `dailyentryfun.php` - Journal entry utilities
- `initiateStaticSessionCommingWithCurl.php` - API session

### Critical DAOs
- `SaveDAO` - Cash register CRUD operations
- `SavedailyDAO` - Cash movement logging
- `CurrencyDAO` - Multi-currency support
- `AccountstreeDAO` - Chart of accounts integration

### JavaScript Integration
- Form validation (customValidation flag)
- AJAX operations for CURL posts
- Sorting functionality

---

## 🎯 Cash Register Types and Categories

### Standard Categories
- **Operating Cash** - Daily operational cash
- **Petty Cash** - Small expense cash
- **Change Fund** - Customer change reserves
- **Foreign Currency** - Multi-currency holdings

### Save Tree Parent Types
- **0**: Assets (نقدية في الصندوق) - Standard cash assets
- **1**: Liabilities (أمانات نقدية) - Cash held in trust

### Sort Order Management
- Numeric sorting for display order
- Can be updated via AJAX (sortby action)

---

## 🎲 Best Practices

### 1. Cash Register Setup
- Use descriptive names for easy identification
- Set appropriate currency for multi-currency operations
- Assign correct parent type (assets vs. liabilities)
- Set logical sort order for user interface

### 2. Opening Balances
- Verify opening balances before creation
- Document source of opening cash
- Ensure currency conversions are accurate

### 3. Access Control
- Configure user access to appropriate cash registers
- Use single vs. multiple cash register permissions
- Regular review of cash register access rights

### 4. Audit and Reconciliation
- Regular review of savedaily movement logs
- Reconcile physical cash with system balances
- Monitor currency conversion impacts

---

## 🔄 API Support

### CURL Integration
The controller supports API operations via CURL posts:

```php
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    // API response format
    $data = array(
        'status' => 1,  // 1=success, 2=error
        'message' => 'تمت العمليه بنجاح',
        'message_en' => 'Success'
    );
    echo json_encode($data);
}
```

**API Actions Supported**:
- Add cash register
- Update cash register
- Delete cash register
- Sort order updates

---

**Critical Note**: Cash registers are the foundation of cash management in the system. All cash transactions (sales, purchases, expenses, receipts) ultimately affect cash register balances. Changes to cash registers impact the chart of accounts and require careful consideration of existing transaction history.