# Cash Flows Controller Documentation

**File**: `/controllers/cashflowsController.php`  
**Purpose**: Simplified daily treasury report focusing on cash flow transactions and summaries  
**Last Updated**: December 20, 2024  
**Total Functions**: 6  
**Lines of Code**: ~731

---

## 📋 Overview

The Cash Flows Controller is a streamlined treasury reporting module that provides focused daily cash flow reports. It serves as a simplified alternative to the more comprehensive `savedailyController.php`, offering:
- Basic daily cash register transaction reports
- Process-based transaction filtering
- Date range reporting with simplified parameters
- Transaction linking to source documents
- Cash flow categorization and summaries
- Essential treasury oversight functionality

### Primary Functions
- [x] Generate basic daily cash flow reports
- [x] Process-based transaction filtering
- [x] Date range cash flow analysis
- [x] Transaction source document linking
- [x] Cash inflow/outflow categorization
- [x] Simple cash register selection
- [x] Transaction detail drill-down

### Related Controllers
- [savedailyController.php](savedailyController.md) - Comprehensive treasury reports
- [saveController.php](saveController.md) - Cash register management
- [expensesController.php](expensesController.md) - Expense tracking
- [sellbillController.php](sellbillController.md) - Sales operations
- [buyBillController.php](buyBillController.md) - Purchase operations

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **savedaily** | Daily cash register transactions | savedailyid, saveid, savedailychangeamount, savedailychangetype, savedailydate, processname, tablename, savedailymodelid |
| **save** | Cash registers/safes master data | saveid, savename, savecurrentvalue, conditions |

### Transaction Source Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **sellbill** | Sales transactions | sellbillid, sellbillclientid, sellbilldate |
| **buybill** | Purchase transactions | buybillid, buybillsupplierid, buybilldate |
| **returnsellbill** | Sales returns | returnsellbillid, returnsellbillclientid |
| **returnbuybill** | Purchase returns | returnbuybillid, returnbuybillsupplierid |
| **sellbillandrutern** | Combined sell/return bills | sellbillid, sellbillclientid |
| **buyandruternbill** | Combined buy/return bills | buyandruternbillid, buyandruternbillsupplierid |
| **expenses** | Expense transactions | expensesid, expensesname, expensesValue |
| **bills** | Service bills | billid, clientid, billdate |
| **billsreturn** | Service bill returns | billsreturnid, billid |

### Personnel Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeepersonnel** | Employee personal transactions | employeepersonnelid, employeeid |
| **employee** | Employee master data | employeeid, employeeName |

### Configuration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **usergroup** | User group settings | usergroupid, savedailydate |
| **programsettings** | System configuration | programsettingsid, reportsPlusHours |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **show() / Default Action** - Basic Cash Flow Report
**Location**: Line 232  
**Purpose**: Generate daily cash flow report with basic filtering

**Function Signature**:
```php
// Triggered when: do=show or empty $do
$saveId = $_REQUEST['saveid'];
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$processid = filter_input(INPUT_POST, 'processid', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
```

**Process Flow**:
1. Load cash registers for selection dropdown
2. Load process types for filtering
3. Parse date and filter parameters
4. Apply timezone adjustments if configured
5. Call `search()` with parameters
6. Display results via `show.html` template

**Key Features**:
- Simple cash register selection
- Process type filtering
- Date range with timezone support
- YouTube tutorial integration

---

### 2. **search()** - Core Search Function
**Location**: Line 411  
**Purpose**: Query cash register transactions and build transaction details

**Function Signature**:
```php
function search($saveId, $processid, $startDate, $endDate)
```

**Process Flow**:
1. Build dynamic WHERE clause based on filters
2. Query `savedaily` table using extension DAO
3. Process each transaction record:
   - Generate document links
   - Load related party information
   - Calculate running totals
4. Assign results to template

**Dynamic Query Building**:
```php
$queryString = ' WHERE';

if (isset($saveId) && $saveId != '-1') {
    $queryString .= ' savedaily.saveid = ' . $saveId . ' AND';
}

if (!empty($startDate) && !empty($endDate)) {
    $queryString .= ' savedaily.savedailydate >= "' . $startDate . '" AND savedaily.savedailydate <= "' . $endDate . '" AND';
}

if (isset($processid) && !empty($processid)) {
    $queryString .= ' savedaily.processname in( "' . implode('","', $processid) . '") AND';
}
```

**Transaction Processing**:
```php
foreach ($savedailyData as $data) {
    // Generate document links
    if ($data->tablename == 'bills.php' || $data->tablename == 'billsreturn.php') {
        $data->link = '' . $data->tablename . '?do=details&id=' . $data->savedailymodelid;
    } else {
        $data->link = '' . $data->tablename . '?do=editprint&id=' . $data->savedailymodelid;
    }
    
    // Calculate running totals
    if ($data->savedailychangetype == 0) { // Income
        $changeAmountSum += $data->savedailychangeamount;
        $changeAmountSumpluse += $data->savedailychangeamount;
    } else { // Expense
        $changeAmountSum -= $data->savedailychangeamount;
        $changeAmountminse += $data->savedailychangeamount;
    }
}
```

---

### 3. **loadSave()** - Cash Register Loading
**Location**: Line 343  
**Purpose**: Load all active cash registers for selection

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

**Process Flow**:
1. Query `save` table for active registers (conditions = 0)
2. Return array of cash register objects

---

### 4. **loadprocess()** - Process Type Loading
**Location**: Line 355  
**Purpose**: Load all available process types for filtering

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

**Process Flow**:
1. Query distinct process names from `savedaily` table
2. Return array of process types for dropdown

---

### 5. **sumCredit() / sumCreditById()** - Balance Calculations
**Location**: Lines 363, 381  
**Purpose**: Calculate current cash register balances

**Function Signatures**:
```php
function sumCredit()           // Total across all registers
function sumCreditById($id)    // Total for specific register
```

**Process Flow**:
1. Load cash register data
2. Sum current values
3. Return total balance

---

### 6. **showDetail()** - Transaction Details
**Location**: Line 397  
**Purpose**: Load detailed transaction records for drill-down

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

**Process Flow**:
1. Get `savedailyid` from URL parameter
2. Query detailed transaction records
3. Return detail array

---

## 🔄 Workflows

### Workflow 1: Basic Cash Flow Report
```
┌─────────────────────────────────────────────────────────────┐
│                START: Access Cash Flow Report              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Dropdown Data                                      │
│     - Load active cash registers                            │
│     - Load process types                                    │
│     - Load YouTube tutorials                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Parse User Filters                                      │
│     - Cash register selection                               │
│     - Date range (with timezone)                            │
│     - Process type filters                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Execute Search                                          │
│     - Build WHERE clause                                    │
│     - Query savedaily table                                 │
│     - Apply filters                                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Process Results                                         │
│     FOR EACH transaction:                                   │
│       │                                                     │
│       ├─→ Determine source table                           │
│       │                                                     │
│       ├─→ Load related party name                          │
│       │   ├─ Customer names (for sales)                    │
│       │   ├─ Supplier names (for purchases)                │
│       │   ├─ Employee names (for personnel)                │
│       │   └─ Expense names (for expenses)                  │
│       │                                                     │
│       ├─→ Generate document link                           │
│       │                                                     │
│       └─→ Update running totals                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Display Report                                          │
│     - Show transactions with links                          │
│     - Display income/expense totals                         │
│     - Include cash register balances                        │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) or `do=show` | Default action | Basic cash flow report |
| `do=success` | Static template | Success message display |
| `do=error` | Static template | Error message display |

### Required Parameters

**Cash Flow Report** (`do=show`):
- `saveid` - Cash register ID (-1 for all)
- `from` - Start date (YYYY-MM-DD)
- `to` - End date (YYYY-MM-DD)
- `processid[]` - Array of process type filters

---

## 🧮 Calculation Methods

### Cash Flow Totals
```php
$changeAmountSum = 0;      // Net cash flow
$changeAmountSumpluse = 0; // Total income
$changeAmountminse = 0;    // Total expenses

foreach ($savedailyData as $data) {
    if ($data->savedailychangetype == 0) { // Income
        if ($data->savedailychangeamount > 0) {
            $changeAmountSum += $data->savedailychangeamount;
            $changeAmountSumpluse += $data->savedailychangeamount;
        } else {
            $changeAmountSum -= $data->savedailychangeamount;
            $changeAmountSumpluse += $data->savedailychangeamount;
        }
    } else { // Expense
        if ($data->savedailychangeamount > 0) {
            $changeAmountSum -= $data->savedailychangeamount;
            $changeAmountminse += $data->savedailychangeamount;
        } else {
            $changeAmountSum += $data->savedailychangeamount;
            $changeAmountminse -= $data->savedailychangeamount;
        }
    }
}
```

### Timezone Handling
```php
if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
    $reportsPlusHours = $Programsetting->reportsPlusHours + 24;
    $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
    $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
} else {
    $endDate = $endDate . ' 23:59:59';
    $startDate = $startDate . " 00:00:00";
}
```

---

## 🔒 Security & Permissions

### Input Validation
```php
// Array input filtering for process types
$processid = filter_input(INPUT_POST, 'processid', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

// Basic parameter sanitization
$saveId = $_REQUEST['saveid'];
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
```

### Access Control
- Basic authentication check via `../public/authentication.php`
- No advanced user privilege restrictions (unlike savedailyController)
- All users see all cash registers and data

---

## 📊 Performance Considerations

### Database Optimization
1. **Essential Indexes**:
   - `savedaily(saveid, savedailydate)`
   - `savedaily(processname)`
   - `save(conditions)`

2. **Query Efficiency**:
   - Simple WHERE clause construction
   - Limited JOIN operations
   - Direct table queries without complex aggregations

3. **Memory Usage**:
   - Smaller dataset compared to comprehensive treasury reports
   - Basic transaction processing without complex calculations

---

## 🐛 Common Issues & Troubleshooting

### 1. **Incorrect Transaction Links**
**Issue**: Links point to wrong pages or show errors  
**Cause**: Incorrect `tablename` values or missing `savedailymodelid`

**Debug**:
```sql
SELECT tablename, COUNT(*) 
FROM savedaily 
WHERE savedailymodelid = -1 OR tablename IS NULL
GROUP BY tablename;
```

### 2. **Missing Process Types**
**Issue**: Process filter dropdown is empty  
**Cause**: No distinct process names in `savedaily` table

**Fix**: Check data population in `savedaily.processname`

### 3. **Timezone Issues**
**Issue**: Date ranges return unexpected results  
**Cause**: `reportsPlusHours` setting conflicts

**Fix**: Verify `programsettings.reportsPlusHours` configuration

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Report Generation
```
1. Access controller without parameters
2. Verify dropdown data loads correctly
3. Select cash register and date range
4. Confirm transactions display with proper links
```

### Test Case 2: Process Filtering
```
1. Select specific process types
2. Verify only matching transactions appear
3. Check totals calculate correctly
4. Confirm filter persistence
```

### Test Case 3: Date Range Validation
```
1. Test various date ranges
2. Verify timezone handling
3. Check edge cases (same day, month boundaries)
4. Confirm proper SQL date formatting
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [savedailyController.md](savedailyController.md) - Comprehensive treasury reports
- [saveController.md](saveController.md) - Cash register management
- [Database Schema Documentation](#) - Table relationships

---

## 🔍 Key Differences from savedailyController

### Simplified Features
- **No user privilege restrictions** (all users see all data)
- **Basic filtering only** (no advanced search options)
- **Simple transaction processing** (no external API integration)
- **Limited calculation methods** (basic totals only)
- **Streamlined UI** (focused on essential information)

### Use Cases
- **Quick daily cash flow checks**
- **Simple transaction lookups**
- **Basic treasury oversight**
- **Entry-level user access**

### When to Use Each Controller
- **cashflowsController**: Simple daily checks, basic reporting
- **savedailyController**: Comprehensive analysis, advanced filtering, API integration

---

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