Save Daily Controller Documentation
File: /controllers/savedailyController.php
Purpose: Generates comprehensive daily treasury reports and cash flow tracking for cash registers and bank accounts
Last Updated: December 20, 2024
Total Functions: 13+
Lines of Code: ~2,050
---
๐ Overview
The Save Daily Controller is a critical treasury reporting module that provides detailed daily cash register reports, cash flow analysis, and transaction tracking. It handles:
- โข Daily cash register transaction reports
- โข Multi-cash register consolidated reports
- โข Bank payment tracking and analysis
- โข Process-based filtering and search capabilities
- โข User privilege-based data access
- โข Royal/external system integration for payment data
- โข Real-time cash flow calculations
- โข Transaction type categorization and analysis
Primary Functions
- โ Generate daily cash register reports
- โ Track cash inflow/outflow transactions
- โ Multi-register consolidated reporting
- โ Process-based filtering (sales, payments, expenses)
- โ User-specific cash register access control
- โ Bank payment integration
- โ Date range reporting with time zone support
- โ Real-time balance calculations
- โ External system API integration
- โ Transaction linking to source documents
Related Controllers
- โข cashflowsController.php - Cash flow summary
- โข saveController.php - Cash register management
- โข sellbillController.php - Sales operations
- โข buyBillController.php - Purchase operations
- โข expensesController.php - Expense management
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **savedaily** | Daily cash register transactions | savedailyid, saveid, savedailychangeamount, savedailychangetype, savedailydate, processname, tablename | |
| **save** | Cash registers/safes master data | saveid, savename, savecurrentvalue, userid, conditions | |
| **accountmovement** | Bank account movements | accountmovementid, accountid, amount, movementtype, movementdate |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **sellbill** | Sales transactions | sellbillid, sellbillclientid, sellbilltotalpayed, sellbilldate | |
| **buybill** | Purchase transactions | buybillid, buybillsupplierid, buybilltotalpayed, buybilldate | |
| **expenses** | Expense transactions | expensesid, expensesValue, expensesdate, saveid | |
| **income** | Income transactions | incomeid, incomeValue, incomedate, saveid | |
| **bills** | Service bills | billid, clientid, finalnetbillvalue, billdate | |
| **clientdebtchange** | Customer debt changes | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **usergroup** | User group settings | usergroupid, savedailydate, usergroupname | |
| **programsettings** | System configuration | programsettingsid, reportsPlusHours, settingkey, settingvalue | |
| **user** | System users | userid, username, usergroupid | |
| **branch** | Business branches | branchid, branchname, branchcode |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer master data | clientid, clientname, clientdebt | |
| **supplier** | Supplier master data | supplierid, suppliername | |
| **youtubelink** | Tutorial links | youtubelinkid, title, url |
๐ Key Functions
1. show() / Default Action - Daily Treasury Report
Location: Line 303
Purpose: Generate comprehensive daily cash register report with filtering capabilities
Function Signature:
// Triggered when: do=show or empty $do
$saveId = $_REQUEST['saveId']; // Cash register ID
$userId = $_REQUEST['userId']; // User filter
$startDate = $_REQUEST['from']; // Start date
$endDate = $_REQUEST['to']; // End date
$processid = $_REQUEST['processid']; // Process type filter
Process Flow:
1. Load cash registers based on user privileges
2. Load process types for filtering
3. Parse date parameters with timezone handling
4. Apply search filters or default to today's data
5. Call search() with parameters
6. Handle CURL/API requests for external systems
7. Display via show.html template
Features:
- โข User privilege-based cash register access
- โข Process type filtering (sales, payments, expenses)
- โข Date range with timezone support
- โข Real-time vs historical reporting
- โข External API integration
---
2. search() - Core Search and Data Processing
Location: Line 1150
Purpose: Query and process cash register transactions with comprehensive filtering
Function Signature:
function search($saveid, $processid, $startDate, $endDate, $userId = 0)
Process Flow:
1. Build dynamic WHERE clause based on filters
2. Apply user privilege restrictions
3. Query savedaily table with filters
4. Process each transaction record:
- Link to source documents
- Load related party information
- Calculate running totals
- Categorize transaction types
5. Calculate summary statistics
6. Return structured data arrays
Transaction Processing Logic:
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;
} else { // Expense
$changeAmountSum -= $data->savedailychangeamount;
}
}
---
3. loadSaveByUserPrivileg() - User-Based Cash Register Loading
Location: Line 1021
Purpose: Load cash registers based on user privileges and session settings
Function Signature:
function loadSaveByUserPrivileg()
Process Flow:
1. Check session setting searchinonesave
2. If restricted (=1): Load only user's assigned cash register
3. If unrestricted (=0): Load all active cash registers
4. Return filtered cash register array
Access Control Logic:
if ($_SESSION['searchinonesave'] == 1) {
// Restricted: user's cash register only
$saveData = $mySaveRecord->queryByUserid($_SESSION['userid']);
} else {
// Full access: all cash registers
$saveData = $mySaveRecord->queryByConditions(0);
}
---
4. getRoyalData() - External System Integration
Location: Line 2031
Purpose: Format transaction data for Royal/external system API consumption
Function Signature:
function getRoyalData($savedailyData, $allMovements)
Process Flow:
1. Process cash register transactions
2. Format for external API compatibility
3. Include bank movement data
4. Return JSON-formatted response
API Response Format:
return array(
"savePayments" => $savedailyData, // Cash transactions
"bankPayments" => $allMovements // Bank transactions
);
---
5. getOpticData() - Specialized Optical System Report
Location: Line 1818
Purpose: Generate reports for optical/medical businesses with insurance integration
Function Signature:
function getOpticData($saveId, $startDate, $endDate, $cash, $insurance, $network)
Process Flow:
1. Query sales bills within date range
2. Filter by payment method (cash/insurance/network)
3. Calculate totals and commissions
4. Format for optical business requirements
---
6. operationName() - Transaction Type Identification
Location: Line 2031
Purpose: Standardize transaction type names for consistent reporting
Function Signature:
function operationName($data)
Process Flow:
1. Analyze processname field
2. Map to standardized operation categories
3. Return localized operation name
Operation Mapping:
switch ($data->processname) {
case 'sellbillController.php':
return 'ู
ุจูุนุงุช ููุฏู';
case 'clientPayedDeptController.php':
return 'ุชุญุตูู ู
ู ุนู
ูู';
case 'expensesController.php':
return 'ู
ุตุฑูู';
// ... additional mappings
}
---
7. Helper Functions
sumCredit() - Calculate total across all cash registers
sumCreditById($id) - Calculate total for specific cash register
loadSave() - Load all active cash registers
loadprocess() - Load process types for filtering
showDetail() - Load detailed transaction records
---
๐ Workflows
Workflow 1: Daily Treasury Report Generation
---
Workflow 2: External System API Integration
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) or `do=show` | Default action | Daily treasury report | |
| `do=showByDay` | `showByDay()` | Single day summary view | |
| `do=opticdata` | `getOpticData()` | Optical business report |
Daily Report (do=show):
- โข
saveId- Cash register ID (-1 for all) - โข
userId- User filter (0 for all users) - โข
from- Start date (YYYY-MM-DD) - โข
to- End date (YYYY-MM-DD) - โข
processid- Process type filter - โข
search- Search type ("dateOnly" for date-only filtering)
API Integration:
- โข
curlpost- Set to 1 for API requests - โข All standard report parameters
---
๐งฎ Calculation Methods
Running Balance Calculation
$changeAmountSum = 0;
$changeAmountSumplus = 0;
$changeAmountminus = 0;
foreach ($savedailyData as $data) {
if ($data->savedailychangetype == 0) { // Income
$changeAmountSum += $data->savedailychangeamount;
$changeAmountSumplus += $data->savedailychangeamount;
} else { // Expense
$changeAmountSum -= $data->savedailychangeamount;
$changeAmountminus += $data->savedailychangeamount;
}
}
Timezone-Aware Date Processing
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
User Access Control
// Cash register access control
if ($_SESSION['searchinonesave'] == 1) {
// User restricted to specific cash register
$saveData = $mySaveRecord->queryByUserid($_SESSION['userid']);
} else {
// User has access to all cash registers
$saveData = $mySaveRecord->queryByConditions(0);
}
Input Sanitization
- โข Cash register IDs validated as integers
- โข Date strings validated before SQL inclusion
- โข Process filters sanitized through array checking
- โข All DAO operations use parameterized queries
---
๐ Performance Considerations
Database Optimization Tips
1. Critical Indexes:
- savedaily(saveid, savedailydate)
- savedaily(savedailychangetype, processname)
- save(userid, conditions)
2. Query Optimization:
- Date range filtering with proper timezone handling
- User-based filtering to reduce dataset size
- Process type filtering for focused reports
3. Memory Management:
- Large date ranges may return thousands of records
- User privilege filtering reduces memory usage
- Transaction linking optimized for batch processing
---
๐ Common Issues & Troubleshooting
1. Incorrect Balance Calculations
Issue: Running totals don't match expected values
Cause: Mixed transaction types or timezone issues
Debug:
SELECT
SUM(CASE WHEN savedailychangetype = 0 THEN savedailychangeamount ELSE 0 END) as income,
SUM(CASE WHEN savedailychangetype = 1 THEN savedailychangeamount ELSE 0 END) as expenses
FROM savedaily WHERE saveid = [ID] AND savedailydate BETWEEN '[DATE1]' AND '[DATE2]';
2. Missing Transaction Links
Issue: Transaction shows "#" link instead of document link
Cause: savedailymodelid = -1 or unrecognized tablename
3. User Access Issues
Issue: User cannot see expected cash registers
Cause: Session variable searchinonesave restrictions
Fix: Check user group settings and cash register assignments
---
๐งช Testing Scenarios
Test Case 1: Basic Daily Report
1. Select cash register with recent transactions
2. Set today's date range
3. Verify transaction count and totals
4. Check transaction links work properly
Test Case 2: Multi-Register Report
1. Select "All Cash Registers" option
2. Set date range covering multiple registers
3. Verify totals are properly segregated
4. Check user access restrictions
Test Case 3: API Integration
1. Send CURL request with curlpost=1
2. Verify JSON response format
3. Check data accuracy vs web interface
4. Test error handling for invalid parameters
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข cashflowsController.md - Cash flow reports
- โข saveController.md - Cash register management
- โข Database Schema Documentation - Table relationships
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur