From 74df1625e6528f00ed4e3d0b94fdc5b24404d806 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Sat, 17 Oct 2026 00:11:25 -0400 Subject: [PATCH] Accounts: let an account's first statement start from the bank's balance on a start date, bringing everything before it forward as reconciled and locked in an opening reconciliation, with a one-time Correct the opening balance for any gap with the bank, and Undo removing it and restoring the opening balance; add a deposit picker to new transfers out of a Cash account that lists the waiting payments and other income, fills the amount and notes from the ticked ones and links them so they are not offered again, shows the deposit on the transfer, payment and income quick looks, and releases the links when the transfer is deleted, moved to another account, or an item moves account; DB 3.0.9 adds reconciliation_opening, reconciliation_adjustment, payment_deposit_transfer_id and revenue_deposit_transfer_id; changelog updated --- CHANGELOG.md | 28 ++++- admin/database_updates/3.0.9.php | 27 ++++ agent/modals/payment/payment.php | 2 + agent/modals/revenue/revenue.php | 2 + agent/modals/transfer/transfer.php | 20 +++ agent/modals/transfer/transfer_form.php | 90 ++++++++++++++ agent/post/income.php | 6 + agent/post/payment.php | 2 + agent/post/reconcile.php | 49 +++++++- agent/post/transfer.php | 1 + agent/reconcile.php | 123 +++++++++++++++++-- agent/transactions.php | 4 +- css/itflow_custom.css | 6 + db.sql | 10 +- functions/accounts.php | 157 +++++++++++++++++++++++- functions/income.php | 1 + functions/reconcile.php | 144 ++++++++++++++++++++-- 17 files changed, 634 insertions(+), 38 deletions(-) create mode 100644 admin/database_updates/3.0.9.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 199afe473..eb3750a8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.11 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 3.0.8) in the same pass. Nothing else is required. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 3.0.9) in the same pass. Nothing else is required. -This is a big release, with twenty-nine database steps in one go, so take a backup before you update. +This is a big release, with thirty database steps in one go, so take a backup before you update. The update also clears out data that deletes in older versions left behind, all of it pointing at something that no longer exists: @@ -29,7 +29,7 @@ Trips already logged keep the miles they were entered with (see Breaking Changes Other income already entered (money in that isn't for an invoice, which used to be called revenue) takes who entered it from the audit log, where it has a record of it. Income with no category now counts in the dashboard and reports, so their totals can go up by that much (see Breaking Changes, Income). -Every account is given a kind - checking, savings, credit card, cash or payment processor - guessed from its name: Visa, Amex or card is a credit card, savings or reserve is savings, cash or petty cash is cash, and Stripe, PayPal, Square or merchant is a payment processor. An account given a liability type back when accounts had types (2023) is a credit card, so what is on it reads as owed. Anything else is checking. Change any that came out wrong with Edit on the Accounts page. An account's balance now leaves out archived payments, income and expenses everywhere, so the Accounts page can show less or more than before (see Bug Fixes). No account is reconciled after the update - the first statement you reconcile on each starts from its opening balance (see New Features, Accounts and transactions). +Every account is given a kind - checking, savings, credit card, cash or payment processor - guessed from its name: Visa, Amex or card is a credit card, savings or reserve is savings, cash or petty cash is cash, and Stripe, PayPal, Square or merchant is a payment processor. An account given a liability type back when accounts had types (2023) is a credit card, so what is on it reads as owed. Anything else is checking. Change any that came out wrong with Edit on the Accounts page. An account's balance now leaves out archived payments, income and expenses everywhere, so the Accounts page can show less or more than before (see Bug Fixes). No account is reconciled after the update. The first statement you reconcile on each can start from the bank's balance on the day it starts, bringing everything before it forward as reconciled, or from the account's opening balance (see New Features, Accounts and transactions). Transfers already made out of a cash account count as having taken everything in it up to then to the bank, so the first deposit you make after the update only offers the checks and cash taken in since the last one. If you are coming from 26.08 or earlier, the database update still has to be run from the command line one time, exactly as described under Upgrading to 26.09 below. @@ -117,7 +117,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run - deleting a client with cleared payments or other income, from ITFlow or through the API (keep the client archived instead) - Bulk Set Account and Bulk Delete on the Income and Expenses lists, which leave cleared ones as they are and say how many - undoing a reimbursement whose money out has cleared - - An account's opening balance can't be changed once a statement on it is reconciled, as the first statement starts from it. + - An account brought forward as reconciled (see New Features, Accounts and transactions) has everything before the day it was brought forward to locked the same way, until that is undone. + - An account's opening balance can't be changed by hand once a statement on it is reconciled, as the first statement starts from it. On an account brought forward from the bank's balance, Correct the opening balance can still move it once. - Notifications now follow access too. An agent only sees notifications for clients and areas they can open, so someone without sales access no longer sees invoice and quote notifications. - Drop-downs: Tom Select is gone, replaced by ITFlow's own picker. It works the way you are used to: type to search, tick several in a multi-select, and type a new value in fields that allow it, such as ticket watchers. See Developer Updates if you have custom pages that used Tom Select. - Several small windows are gone because the change is now made where the value is shown: @@ -647,18 +648,26 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Transfers keep their place in the menu, which opens the Transfers pill for every account. Each transfer shows once there, from the account it left, and the cards show what was moved, what paid off cards and what payment processors paid out. - New Transfer, Pay the Card and Edit are one form: where it comes from and where it goes, each with what it holds now, a Swap button to turn it round, the amount in the currency of the account it leaves, the date, how it was moved and notes. Every field is checked when it is saved: two different open accounts, an amount, a real date and one of your payment methods. Editing moves both sides together. - A transfer into a credit card is a card payment, and says so on the ledger and in its quick look. Clicking a transfer opens its quick look: what came out of one account and went into the other, with what each holds now and a link to its ledger, how it was moved, who entered it, notes, and Edit and Delete. A transfer's expense opens it too. + - **Deposits** out of a cash account: a new transfer out of a cash account lists the payments and other income taken into it that haven't gone to the bank yet, oldest first, each with its date, what it is for, the client, how it was paid and the amount. Tick the checks and cash going to the bank, and the amount and notes fill in, until either is typed over. What is ticked goes with the transfer and isn't offered again. A transfer out of it with nothing ticked - every one made before the update, and any made since without ticking - counts as taking everything up to it, so only what came in after it is listed. + - A deposit's quick look lists what was in it, and says so when they don't add up to the amount. The quick look of a payment or other income in one says which deposit it went in, opening it. + - Deleting the transfer, or changing it to come out of another account, puts what it carried back to waiting. So does moving one of them to another account, with Edit or Bulk Set Account. - The dashboard's accounts open their ledgers, and a card shows what is owed on it. - Adding and changing accounts and transfers needs write access to Financial, and deleting full access, as before. Restoring an archived account needs write access. - The demo data adds a Business Visa for software, hosting, supplies, meals and the other small costs, paid off from Operating Checking each month. - **Reconcile**, from an account's menu on the Accounts page or Transactions, checks the account against its bank or card statement: - - Enter the statement's ending date and balance (for a card, what the statement says is owed), with notes such as the statement's number. It starts from where the last statement ended, or the opening balance the first time. + - Enter the statement's ending date and balance (for a card, what the statement says is owed), with notes such as the statement's number. It starts from where the last statement ended. + - The first statement on an account starts from the bank's balance or the opening balance: + - From the bank's balance, enter the day the statement starts and the balance it starts from (for a card, what was owed then). Everything on the account before that day is brought forward as reconciled - cleared and locked as if a statement had been reconciled to the day before - so an account with years of history starts matching the bank from that statement on, without ticking its past. This is picked for you when the account has lines from before the statement's month. + - From the opening balance, every line since the account was opened is listed to tick, as before. + - Where ITFlow had the account at a different balance from the bank's on the day it was brought forward to, the statement says how far apart they were. Correct the opening balance moves the account's opening balance by that much, once, so ITFlow's balance matches the bank's from then on. Leave it, and the statements still reconcile from the bank's balance. + - Brought forward shows in the history with everything before the day it covers, and what the opening balance was corrected by or how far ITFlow was off. While it is the latest and nothing is in progress, Undo takes it away, frees its lines and puts the opening balance back. - Every line on the account up to the statement's date that hasn't cleared yet is listed, oldest first. Tick each one the statement shows. Lines brought in with Import Statement or Import Deposits start ticked. - The cards show where it started, the statement, what is ticked (cleared) and the difference, and the bar at the bottom keeps the difference and Finish in view down a long statement. Finish opens once the difference is nothing. - Pills for Money in, Money out, Not ticked and Ticked, a search by who, reference or amount, and Tick all shown and Untick all shown for what they leave. - Ticks are saved as they are made, so a statement can be left and finished later. Change the statement's date or balance from its menu, or Discard it. - Add what the statement has and ITFlow doesn't - a bank fee, interest - with New Expense, New Income or New Transfer from its menu, starting on the account. - With nothing in progress, Reconcile shows where the account is reconciled to, how much hasn't cleared yet, and the statements reconciled before - each with its ending balance, the lines it cleared, what came in and went out, and who reconciled it when. The latest can be undone, which puts it back in progress with what was ticked. - - On Transactions, a line cleared on a statement has a tick by its date, opening the lines that statement cleared. The Uncleared pill lists what no statement has cleared yet, and the export has a Cleared column with the statement's date. The Accounts page shows where each account is reconciled to, or that one is being reconciled. + - On Transactions, a line cleared on a statement has a tick by its date, opening the lines that statement cleared - or saying it was brought forward. The Uncleared pill lists what no statement has cleared yet, and the export has a Cleared column with the statement's date. The Accounts page shows where each account is reconciled to, or that one is being reconciled. - A cleared line's quick look says which statement it cleared on, and its Edit window keeps its amount, date and account as they are (see Breaking Changes, Accounts, transactions and transfers). - Reconciling needs write access to Financial, and undoing a reconciled statement full access. Agents with read access can look at the statements. - The demo data reconciles Operating Checking and the Business Visa to each month's statement through last month. @@ -777,6 +786,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - 3.0.6: `payments.payment_import_key` and `revenues.revenue_import_key` (keyed), and `income_import_rules` (`import_rule_match` unique, `import_rule_action` - payment, income or transfer - `import_rule_client_id`, `import_rule_category_id`, `import_rule_account_id`, `import_rule_used_count`). - 3.0.7: no schema change. `accounts.account_type` is set from the name for every account without a kind from 1 to 6 (1 checking, 2 savings, 3 credit card, 4 cash, 5 payment processor, 6 other), the same way as `accountTypeGuess()`, with the 2023 liability types (20 to 29) as 3. Setup and `scripts/setup_cli.php` create the Cash account as type 4. - 3.0.8: `account_reconciliations` (`reconciliation_account_id` and `reconciliation_statement_date` keyed together, `reconciliation_starting_balance`, `reconciliation_ending_balance`, `reconciliation_notes`, `reconciliation_created_by`, `reconciliation_created_at`, `reconciliation_finished_by`, `reconciliation_finished_at` - NULL while in progress), and `payments.payment_reconciliation_id`, `revenues.revenue_reconciliation_id` and `expenses.expense_reconciliation_id` (keyed). + - 3.0.9: `account_reconciliations.reconciliation_opening` (0, 1 for an account brought forward as reconciled) and `reconciliation_adjustment` (`decimal(15,2)`, 0.00 - what its opening balance was corrected by), and `payments.payment_deposit_transfer_id` and `revenues.revenue_deposit_transfer_id` (NULL, keyed - the transfer out of a cash account they were deposited with). - New shared function files, loaded by `functions.php`: `functions/asset.php`, `asset_interface.php`, `certificate.php`, `client_overview.php`, `contact.php`, `credential.php`, `dashboard.php`, `links.php`, `location.php`, `notifications.php`, `project.php`, `rack.php`, `search.php`, `service.php`, `software.php`, `tags.php`, `ticket.php`, `ticket_fields.php`, `user.php` and `vendor.php`. They hold the queries and rules, so the pages, the API and cron share one definition. - Removed post models: `agent/post/{asset_interface,certificate,credential,domain,event,location,network_ip,network,recurring_ticket,vendor}_model.php`, `admin/post/user_model.php` and `api/v1/certificates/certificate_model.php`. Their handlers call the shared functions above. Interface handlers moved to `agent/post/asset_interface.php`. - New scripts: `js/itflow_select.js`, `quick_pick.js`, `tag_picker.js`, `global_search.js`, `notifications.js`, `dashboard.js`, `client_overview.js`, `client_switcher.js`, `credentials.js` and `autosubmit.js`, and `agent/js/calendar.js`, `calendar_event_modal.js`, `files.js`, `interface_form.js`, `network_form.js`, `project_modal.js` and `ticket_schedule_modal.js`. @@ -1024,6 +1034,12 @@ If you are coming from 26.08 or earlier, the database update still has to be run - `agent/transactions.php` takes `?reconciliation=` and `?show=uncleared`, and the `transactions` export adds `transaction_cleared` (off by default). `agent/modals/expense/expense_add.php` and `agent/modals/revenue/revenue_add.php` take `?account_id=`. - Seeds: `demoReconcileAccounts()` reconciles Operating Checking and the Business Visa monthly, and `demoDataRemove()` removes the reconciliations on the demo's accounts. - CSS: `.itflow-reconcile-table`, `.itflow-reconcile-ticked`, `.itflow-reconcile-balanced` and `.itflow-reconcile-bar`, which sticks to the bottom of the window - `.app-main` is `overflow: visible` on that page so it can. + - Brought forward: on an account never reconciled, `reconcileStart()` takes `start_from` ('statement'; anything else starts from the opening balance), `start_date` (on or before `statement_date`) and `start_balance` (owed, for a card), and first calls `reconcileBringForward($account, $to, $balance)` - a finished reconciliation with `reconciliation_opening` 1, starting at the opening balance and ending at the bank's, clearing every line up to the day before `start_date`. `reconcileOpening($account_id)` is that row, `reconcileOpeningGap($opening)` the bank's balance less ITFlow's there, and `reconcileCorrectOpening($id, &$error)` adds the gap to `accounts.opening_balance` and the row's starting balance once, keeping it in `reconciliation_adjustment`. `reconcileUndo()` deletes a brought forward row, freeing its lines and taking the adjustment back off the opening balance. `reconcileRow()` adds `opening`, `reconcileLock()` returns `reconciliation_opening` (worded by `reconcileLockText()` and `reconcileGlanceHtml()`), and the statement after it pre-ticks only the imported lines after the day brought forward to. `accountLedgerSql()` adds `txn_cleared_opening`. + - GET `reconcile_correct_opening` (the brought forward reconciliation's id) in `agent/post/reconcile.php`, at Financial 2, logged as an Account Edit. `reconcilePostInput()` adds `start_from`, `start_date` and `start_balance`. +- Deposits, in `functions/accounts.php`: `transferDepositCandidates($account_id, $limit = 200)` (payments and non-transfer revenues on the account, not in a deposit or archived, after the latest transfer out of it with nothing linked, by date then `*_created_at` - each with `kind`, `id`, `key`, `date`, `amount`, `what`, `client_name`, `method` and `reference`), `transferDepositLink($transfer_id, $from_account_id, $keys)`, `transferDepositItems($transfer_id)`, `transferDepositedIn($kind, $id)`, `transferDepositedGlanceHtml($deposit)` and `transferDepositRelease($kind, $id, $account_id)`. + - `transferSave()` takes `deposit` (`payment-12`, `revenue-5`; only on a new transfer, only lines on the account it leaves) and clears the links when an edit moves the account it leaves. `transferDelete()` clears them. `transferPostInput()` adds `deposit[]`. `edit_payment`, `bulk_edit_income` (Set Account) and `incomeRevenueSave()` call `transferDepositRelease()` before a line moves account. Linking and clearing leave `*_updated_at` as it was. + - `agent/modals/transfer/transfer_form.php` puts each cash account's waiting lines (account type 4) in `[data-transfer-deposit]`'s `data-deposits` JSON for a new transfer, and renders them as `deposit[]` checkboxes. `transfer.php` lists the deposit, and `payment.php` and `revenue.php` show the deposit it went in. + - CSS: `.itflow-deposit-list`. - The billing helpers (`billingTimeInvoice()`, `quoteConvert()`, `recurringInvoiceGenerate()` and the rest) take the agent's name as plain text. Their handlers now pass `stripslashes($session_name)`, so a name with an apostrophe no longer shows a backslash in history and the audit log. - Sidebar brand: `agent/css/sidebar_brand_fix.css` and `agent/js/sidebar_brand_fix.js` from 26.10 are replaced by CSS in `css/itflow_custom.css`. `includes/load_company_settings.php` now sets `$session_company_logo`. - `alertMessageHtml()` no longer double-encodes, and save messages built from `escapeSql()` values use `stripslashes()` at the flash. diff --git a/admin/database_updates/3.0.9.php b/admin/database_updates/3.0.9.php new file mode 100644 index 000000000..245cb587a --- /dev/null +++ b/admin/database_updates/3.0.9.php @@ -0,0 +1,27 @@ + from a bank statement +
diff --git a/agent/modals/revenue/revenue.php b/agent/modals/revenue/revenue.php index dae191a48..d1e642ee8 100644 --- a/agent/modals/revenue/revenue.php +++ b/agent/modals/revenue/revenue.php @@ -19,6 +19,7 @@ if (!$row) { $revenue_id = intval($row['revenue_id']); $cleared = reconcileLock('revenue', $revenue_id); +$deposited = transferDepositedIn('revenue', $revenue_id); $client_id = intval($row['revenue_client_id']); $amount = floatval($row['revenue_amount']); $currency = (string) $row['revenue_currency_code']; @@ -78,6 +79,7 @@ ob_start(); by from a bank statement
+
diff --git a/agent/modals/transfer/transfer.php b/agent/modals/transfer/transfer.php index fb86ef951..229cde5c3 100644 --- a/agent/modals/transfer/transfer.php +++ b/agent/modals/transfer/transfer.php @@ -20,6 +20,7 @@ if (!$row) { $transfer_id = intval($row['transfer_id']); $cleared_out = reconcileLock('expense', $row['transfer_expense_id']); $cleared_in = reconcileLock('revenue', $row['transfer_revenue_id']); +$deposit = transferDepositItems($transfer_id); $what = transferWhat($row); $from = accountRow($row['transfer_from_id']); $to = accountRow($row['transfer_to_id']); @@ -77,6 +78,25 @@ ob_start();
+ +
+
In this deposit
+ +
+ + + - + + +
+ + = 0.005) { ?> +
They come to - the deposit is .
+ +
+ +
Notes
diff --git a/agent/modals/transfer/transfer_form.php b/agent/modals/transfer/transfer_form.php index 4f20053df..cd6f41acd 100644 --- a/agent/modals/transfer/transfer_form.php +++ b/agent/modals/transfer/transfer_form.php @@ -45,6 +45,20 @@ $form_types = accountTypes(); $form_lock_out = $form_row ? reconcileLock('expense', $form_row['transfer_expense_id']) : null; $form_lock_in = $form_row ? reconcileLock('revenue', $form_row['transfer_revenue_id']) : null; $form_lock = $form_lock_out ?: $form_lock_in; +// A new transfer out of a cash account can carry the checks and cash waiting in it to the bank +$form_deposits = []; +if (!$form_row) { + foreach ($form_accounts as $id => $account) { + if ($account['type'] !== 4 || $account['account_archived_at']) { + continue; + } + foreach (transferDepositCandidates($id) as $item) { + $form_deposits[$id][] = ['key' => $item['key'], 'date' => $item['date'], 'what' => $item['what'], 'client' => (string) $item['client_name'], + 'method' => trim((string) $item['method'] . ((string) $item['reference'] !== '' ? ' #' . $item['reference'] : '')), + 'amount' => number_format($item['amount'], 2, '.', ''), 'money' => billingMoney($item['amount'], $account['account_currency_code'])]; + } + } +} $form_currency = isset($form_accounts[$form_from]) ? ($form_accounts[$form_from]['account_currency_code'] ?: $session_company_currency) : $session_company_currency; $form_account_options = function ($selected) use ($form_accounts, $form_types) { $html = ''; @@ -91,6 +105,14 @@ $form_account_options = function ($selected) use ($form_accounts, $form_types) {
+ + + +
@@ -164,5 +186,73 @@ $form_account_options = function ($selected) use ($form_accounts, $form_types) { from.addEventListener('change', update); to.addEventListener('change', update); update(); + + // A deposit out of a cash account: tick what goes to the bank, and the amount and notes follow + var deposit = root.querySelector('[data-transfer-deposit]'); + if (!deposit) { + return; + } + var waiting = JSON.parse(deposit.dataset.deposits || '{}'); + var list = deposit.querySelector('[data-transfer-deposit-list]'); + var amount = root.querySelector('input[name="amount"]'); + var notes = root.querySelector('textarea[name="notes"]'); + var filledAmount = ''; + var filledNotes = ''; + function line(item) { + return [item.what, item.client, item.method, item.money].filter(function (part) { return part; }).join(' - '); + } + function fill() { + var ticked = []; + list.querySelectorAll('input:checked').forEach(function (box) { + ticked.push(box.item); + }); + var cents = ticked.reduce(function (sum, item) { return sum + Math.round(parseFloat(item.amount) * 100); }, 0); + var total = ticked.length ? (cents / 100).toFixed(2) : ''; + if (amount.value === '' || amount.value === filledAmount) { + amount.value = total; + filledAmount = total; + } + var text = ticked.length ? 'Deposit of ' + ticked.length + (ticked.length === 1 ? ' item' : ' items') + ':\n' + ticked.map(line).join('\n') : ''; + if (notes.value === '' || notes.value === filledNotes) { + notes.value = text; + filledNotes = text; + } + } + function show() { + var items = waiting[from.value] || []; + list.textContent = ''; + items.forEach(function (item) { + var row = document.createElement('label'); + row.className = 'list-group-item d-flex align-items-center gap-2'; + var box = document.createElement('input'); + box.type = 'checkbox'; + box.className = 'form-check-input mt-0'; + box.name = 'deposit[]'; + box.value = item.key; + box.item = item; + var date = document.createElement('span'); + date.className = 'text-body-secondary small text-nowrap'; + date.textContent = item.date; + var what = document.createElement('span'); + what.className = 'text-truncate'; + what.textContent = [item.what, item.client].filter(function (part) { return part; }).join(' - '); + if (item.method) { + var method = document.createElement('span'); + method.className = 'text-body-secondary small ms-1'; + method.textContent = item.method; + what.appendChild(method); + } + var money = document.createElement('span'); + money.className = 'ms-auto fw-semibold itflow-money text-nowrap'; + money.textContent = item.money; + row.append(box, date, what, money); + list.appendChild(row); + }); + deposit.hidden = items.length === 0; + fill(); + } + list.addEventListener('change', fill); + from.addEventListener('change', show); + show(); })(); diff --git a/agent/post/income.php b/agent/post/income.php index 452bfb829..2ff9ee4c6 100644 --- a/agent/post/income.php +++ b/agent/post/income.php @@ -75,6 +75,9 @@ if (isset($_POST['bulk_edit_income'])) { $cleared++; continue; } + if ($field === 'account') { + transferDepositRelease('revenue', $revenue_id, $value); + } mysqli_query($mysqli, "UPDATE revenues SET $revenue_set WHERE revenue_id = $revenue_id"); logAudit("Revenue", "Edit", "$session_name set $label_sql on other income " . escapeSql(incomeRevenueLabel($row)), intval($row['revenue_client_id']), $revenue_id); $count++; @@ -111,6 +114,9 @@ if (isset($_POST['bulk_edit_income'])) { $cleared++; continue; } + if ($field === 'account') { + transferDepositRelease('payment', $payment_id, $value); + } mysqli_query($mysqli, "UPDATE payments SET $payment_set WHERE payment_id = $payment_id"); logAudit("Payment", "Edit", "$session_name set $label_sql on the payment " . escapeSql(incomePaymentLabel($row)), intval($row['invoice_client_id']), $payment_id); $count++; diff --git a/agent/post/payment.php b/agent/post/payment.php index 94a6baeb9..6278f76a8 100644 --- a/agent/post/payment.php +++ b/agent/post/payment.php @@ -106,6 +106,8 @@ if (isset($_POST['edit_payment'])) { flashAlert(escapeHtml($error), 'error'); redirect(); } + // Moved to another account - out of the deposit it was in + transferDepositRelease('payment', $payment_id, $account); mysqli_query($mysqli,"UPDATE payments SET payment_date = '$date', payment_amount = $amount, payment_account_id = $account, payment_method = '$payment_method', payment_reference = '$reference' WHERE payment_id = $payment_id"); diff --git a/agent/post/reconcile.php b/agent/post/reconcile.php index 75b8a61d8..370fcaee7 100644 --- a/agent/post/reconcile.php +++ b/agent/post/reconcile.php @@ -3,8 +3,9 @@ /* * ITFlow - reconciling an account against a statement (functions/reconcile.php * does the work; ticking lines is agent/ajax.php's reconcile_tick). Write - * access to Financial starts, changes, finishes and discards one; undoing a - * finished one takes full access. + * access to Financial starts, changes, finishes and discards one, and + * corrects the opening balance where an account was brought forward; + * undoing a finished one takes full access. */ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); @@ -15,6 +16,9 @@ function reconcilePostInput() { 'statement_date' => (string) ($_POST['statement_date'] ?? ''), 'ending_balance' => (string) ($_POST['ending_balance'] ?? ''), 'notes' => (string) ($_POST['notes'] ?? ''), + 'start_from' => (string) ($_POST['start_from'] ?? ''), + 'start_date' => (string) ($_POST['start_date'] ?? ''), + 'start_balance' => (string) ($_POST['start_balance'] ?? ''), ]; } @@ -30,6 +34,7 @@ if (isset($_POST['reconcile_start'])) { enforceUserPermission('module_financial', 2); $account_id = intval($_POST['account_id'] ?? 0); + $had_opening = (bool) reconcileOpening($account_id); $id = reconcileStart($account_id, reconcilePostInput(), $error); if (!$id) { flashAlert(escapeHtml($error), 'error'); @@ -37,6 +42,11 @@ if (isset($_POST['reconcile_start'])) { } $row = reconcileRow($id); $totals = reconcileTotals($row); + $opening = reconcileOpening($row['reconciliation_account_id']); + if ($opening && !$had_opening) { + logAudit("Reconciliation", "Create", "$session_name brought " . escapeSql($row['account']['account_name']) . " forward as reconciled to " + . date('M j, Y', strtotime($opening['reconciliation_statement_date'])) . " at a bank balance of " . escapeSql(reconcileBalanceText($row['account'], $opening['reconciliation_ending_balance'])), 0, intval($opening['reconciliation_id'])); + } logAudit("Reconciliation", "Create", "$session_name started reconciling the " . escapeSql(reconcileLabel($row)), 0, $id); @@ -125,6 +135,13 @@ if (isset($_GET['reconcile_undo'])) { redirect(); } + if ($row['opening']) { + logAudit("Reconciliation", "Undo", "$session_name took away " . escapeSql($row['account']['account_name']) . " being brought forward as reconciled to " . date('M j, Y', strtotime($row['reconciliation_statement_date'])) + . (abs(floatval($row['reconciliation_adjustment'])) >= 0.005 ? ', the opening balance back to ' . escapeSql(billingMoney(accountRow($row['reconciliation_account_id'])['opening_balance'], $row['account']['account_currency_code'])) : ''), 0, intval($row['reconciliation_id'])); + flashAlert("" . escapeHtml($row['account']['account_name']) . " is no longer brought forward - its next statement can start from either balance", 'warning'); + redirect('reconcile.php?account=' . intval($row['reconciliation_account_id'])); + } + logAudit("Reconciliation", "Undo", "$session_name undid the reconciliation of the " . escapeSql(reconcileLabel($row)) . " - back to in progress", 0, intval($row['reconciliation_id'])); flashAlert("The " . escapeHtml(reconcileLabel($row)) . " is being reconciled again - its lines can change, and it can be finished or discarded", 'warning'); @@ -132,3 +149,31 @@ if (isset($_GET['reconcile_undo'])) { redirect('reconcile.php?account=' . intval($row['reconciliation_account_id'])); } + +/* + * Correct an account's opening balance by how far ITFlow was off the bank on + * the day it was brought forward, so the two match from then on. + */ +if (isset($_GET['reconcile_correct_opening'])) { + + validateCSRFToken(); + + enforceUserPermission('module_financial', 2); + + $row = reconcileRow(intval($_GET['reconcile_correct_opening'])); + $gap = $row ? reconcileCorrectOpening($row['reconciliation_id'], $error) : null; + if ($gap === null) { + flashAlert(escapeHtml($row ? $error : 'That reconciliation no longer exists'), 'error'); + redirect(); + } + $account = accountRow($row['reconciliation_account_id']); + $moved = billingMoney($gap, $account['account_currency_code']); + + logAudit("Account", "Edit", "$session_name corrected the opening balance of " . escapeSql($account['account_name']) . " by " . escapeSql($moved) . ", to " + . escapeSql(billingMoney($account['opening_balance'], $account['account_currency_code'])) . ", to match the bank on " . date('M j, Y', strtotime($row['reconciliation_statement_date'])), 0, intval($account['account_id'])); + + flashAlert("" . escapeHtml($account['account_name']) . "'s opening balance is corrected by " . escapeHtml($moved) . " - ITFlow matches the bank from " . escapeHtml(date('M j, Y', strtotime($row['reconciliation_statement_date']))) . " on"); + + redirect('reconcile.php?account=' . intval($account['account_id'])); + +} diff --git a/agent/post/transfer.php b/agent/post/transfer.php index 5e37b4b0e..1096b2477 100644 --- a/agent/post/transfer.php +++ b/agent/post/transfer.php @@ -19,6 +19,7 @@ function transferPostInput() { 'to' => intval($_POST['account_to'] ?? 0), 'method' => (string) ($_POST['transfer_method'] ?? ''), 'notes' => (string) ($_POST['notes'] ?? ''), + 'deposit' => array_map('strval', (array) ($_POST['deposit'] ?? [])), ]; } diff --git a/agent/reconcile.php b/agent/reconcile.php index 8e9a88a2d..28cc7d662 100644 --- a/agent/reconcile.php +++ b/agent/reconcile.php @@ -11,6 +11,9 @@ * With nothing in progress: where the account is reconciled to, the form to * start the next statement, and the statements reconciled before - each * opening the lines it cleared on Transactions, the latest one with Undo. + * An account's first statement can start from the bank's balance the day it + * starts, bringing everything before it forward as reconciled; where ITFlow + * was off the bank that day, the opening balance can be corrected to match. * * Takes ?account= - or the account being reconciled, the default account * payments go into, or the first. @@ -60,6 +63,10 @@ $open = $account ? reconcileOpen($account_id) : null; $last = $account ? reconcileLast($account_id) : null; $history = $account && !$open ? reconcileHistory($account_id) : []; $starting = $account ? reconcileStartingBalance($account_id) : 0.0; +// Brought forward from the bank's balance - and how far ITFlow was from it that day +$opening = $account ? reconcileOpening($account_id) : null; +$opening_totals = $opening ? reconcileTotals($opening) : null; +$opening_gap = $opening ? round($opening_totals['difference'], 2) : 0.0; // The next statement most likely ends at the end of last month $suggest = date('Y-m-t', strtotime('first day of last month')); @@ -74,9 +81,67 @@ if ($open) { $uncleared = $account ? mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*), COALESCE(SUM(ledger.txn_amount), 0) FROM (" . accountLedgerSql($account_id) . ") AS ledger WHERE ledger.txn_cleared_id IS NULL")) : [0, 0]; } -$statement_form = function ($row) use ($account, $is_card, $suggest, $last, $starting, $money, $statement_money) { +$statement_form = function ($row) use ($mysqli, $account, $is_card, $suggest, $last, $starting, $money, $statement_money) { $date = $row ? $row['reconciliation_statement_date'] : $suggest; $ending = $row ? floatval($row['reconciliation_ending_balance']) * ($is_card ? -1 : 1) : null; + $first = !$row && !$last; + if ($first) { + // An account with history before the statement most likely starts from the bank's balance + $start = date('Y-m-01', strtotime($date)); + $account_id = intval($account['account_id']); + $earlier = mysqli_fetch_row(mysqli_query($mysqli, "SELECT EXISTS (SELECT 1 FROM payments WHERE payment_account_id = $account_id AND payment_date < '$start') + OR EXISTS (SELECT 1 FROM revenues WHERE revenue_account_id = $account_id AND revenue_date < '$start') + OR EXISTS (SELECT 1 FROM expenses WHERE expense_account_id = $account_id AND expense_date < '$start')"))[0]; + $from_statement = intval($earlier) === 1; + ?> +
+
Its first statement starts from
+
+ > + +
+
+ > + +
+
+
> +
+ +
+ + > +
+
+
+ +
+ + > + +
+
+
+
+ +
@@ -104,9 +169,32 @@ $statement_form = function ($row) use ($account, $is_card, $suggest, $last, $sta
-
- It starts from - - . + +
+ It starts from - + . +
+ + = 0.005) { + return; + } + $day = date('M j, Y', strtotime($opening['reconciliation_statement_date'])); + ?> +
+ + On ITFlow had at and the bank at + - apart. Correct the opening balance by that so ITFlow matches the bank from then on, or leave it - the statements reconcile from the bank's balance either way. + + Correct the opening balance +
+ +
Starting from
-
+
@@ -315,6 +406,8 @@ $statement_form = function ($row) use ($account, $is_card, $suggest, $last, $sta + +
@@ -328,7 +421,8 @@ $statement_form = function ($row) use ($account, $is_card, $suggest, $last, $sta
Reconciled to
-
+
@@ -390,9 +484,17 @@ $statement_form = function ($row) use ($account, $is_card, $suggest, $last, $sta $t = $row['totals']; ?> -
+ +
Brought forward - everything before
+
+ + + = 0.005) { ?> +
opening balance corrected by
+ = 0.005) { ?> +
off ITFlow's
+ - line
from
@@ -405,8 +507,9 @@ $statement_form = function ($row) use ($account, $is_card, $suggest, $last, $sta Undo + data-confirm-title="Undo this reconciliation?" data-confirm-button="Undo" + data-confirm-text="= 0.005 ? ', and the opening balance goes back' : '') . ' - the next statement can start again from either balance.' : 'It goes back to being reconciled, with what was ticked - its lines can change again until it is finished.' ?>" + title="">Undo diff --git a/agent/transactions.php b/agent/transactions.php index 2e301b0be..b0bf00f21 100644 --- a/agent/transactions.php +++ b/agent/transactions.php @@ -336,7 +336,7 @@ if ($transfer_cards) {
- The lines cleared on + The lines on brought forward as reconciled - everything before The lines cleared on Show every line
@@ -380,7 +380,7 @@ if ($transfer_cards) { $meta = array_filter([(string) $row['txn_method'], $row['txn_reference'] ? '#' . $row['txn_reference'] : '']); ?> - + diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 4c7086745..632be2372 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -6397,6 +6397,12 @@ a.itflow-billing-stat:hover { max-width: 0; min-width: 14rem; } +/* A deposit out of a cash account - what is waiting in it, to tick (agent/modals/transfer/transfer_form.php) */ +.itflow-deposit-list { + max-height: 16rem; + overflow-y: auto; +} + /* Reconcile - agent/reconcile.php. A line ticked as cleared on the statement takes the success tint; the Difference card turns green once it balances. */ .itflow-reconcile-table > tbody > tr.itflow-reconcile-ticked > * { diff --git a/db.sql b/db.sql index 6841a92c6..18fad43e6 100644 --- a/db.sql +++ b/db.sql @@ -30,6 +30,8 @@ CREATE TABLE `account_reconciliations` ( `reconciliation_starting_balance` decimal(15,2) NOT NULL DEFAULT 0.00, `reconciliation_ending_balance` decimal(15,2) NOT NULL DEFAULT 0.00, `reconciliation_notes` varchar(250) DEFAULT NULL, + `reconciliation_opening` tinyint(1) NOT NULL DEFAULT 0, + `reconciliation_adjustment` decimal(15,2) NOT NULL DEFAULT 0.00, `reconciliation_created_by` int(11) NOT NULL DEFAULT 0, `reconciliation_created_at` datetime NOT NULL DEFAULT current_timestamp(), `reconciliation_finished_by` int(11) NOT NULL DEFAULT 0, @@ -1837,11 +1839,13 @@ CREATE TABLE `payments` ( `payment_invoice_id` int(11) NOT NULL DEFAULT 0, `payment_import_key` varchar(64) DEFAULT NULL, `payment_reconciliation_id` int(11) DEFAULT NULL, + `payment_deposit_transfer_id` int(11) DEFAULT NULL, PRIMARY KEY (`payment_id`), KEY `payment_invoice_id` (`payment_invoice_id`), KEY `payment_date` (`payment_date`), KEY `payment_import_key` (`payment_import_key`), - KEY `payment_reconciliation_id` (`payment_reconciliation_id`) + KEY `payment_reconciliation_id` (`payment_reconciliation_id`), + KEY `payment_deposit_transfer_id` (`payment_deposit_transfer_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -2407,11 +2411,13 @@ CREATE TABLE `revenues` ( `revenue_created_by` int(11) NOT NULL DEFAULT 0, `revenue_import_key` varchar(64) DEFAULT NULL, `revenue_reconciliation_id` int(11) DEFAULT NULL, + `revenue_deposit_transfer_id` int(11) DEFAULT NULL, PRIMARY KEY (`revenue_id`), KEY `revenue_client_id` (`revenue_client_id`,`revenue_archived_at`), KEY `revenue_date` (`revenue_date`), KEY `revenue_import_key` (`revenue_import_key`), - KEY `revenue_reconciliation_id` (`revenue_reconciliation_id`) + KEY `revenue_reconciliation_id` (`revenue_reconciliation_id`), + KEY `revenue_deposit_transfer_id` (`revenue_deposit_transfer_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; diff --git a/functions/accounts.php b/functions/accounts.php index a10439001..3e92c756a 100644 --- a/functions/accounts.php +++ b/functions/accounts.php @@ -354,6 +354,7 @@ function accountLedgerKinds() { * behind it - payment-12, revenue-5 or expense-9), txn_reconciliation_id (the * reconciliation it is ticked on, finished or not), txn_cleared_id and * txn_cleared_date (the finished one it cleared on, and its statement date), + * txn_cleared_opening (1 when that is an account brought forward), * txn_method, txn_reference, txn_invoice_id, txn_currency, txn_imported and * txn_balance - the account's balance after the line, in date order. Select * from it as a derived table. @@ -406,7 +407,7 @@ function accountLedgerSql($account_id = 0) { WHERE expenses.expense_archived_at IS NULL AND " . $on('expenses.expense_account_id'); return "SELECT ledger_lines.*, accounts.account_name, accounts.account_type, accounts.account_currency_code, category_name, category_color, client_name, ledger_lines.txn_other_name AS other_account_name, other_account.account_type AS other_account_type, - cleared.reconciliation_id AS txn_cleared_id, cleared.reconciliation_statement_date AS txn_cleared_date, + cleared.reconciliation_id AS txn_cleared_id, cleared.reconciliation_statement_date AS txn_cleared_date, cleared.reconciliation_opening AS txn_cleared_opening, accounts.opening_balance + SUM(ledger_lines.txn_amount) OVER (PARTITION BY ledger_lines.txn_account_id ORDER BY ledger_lines.txn_date ASC, ledger_lines.txn_created_at ASC, ledger_lines.txn_order ASC, ledger_lines.txn_id ASC) AS txn_balance FROM ($rows) AS ledger_lines @@ -511,7 +512,8 @@ function accountLedgerFiltersSql(array $src, &$summary = [], $with_show = true, if ($reconciliation_id) { $sql .= " AND ledger.txn_cleared_id = $reconciliation_id"; $statement = getFieldById('account_reconciliations', $reconciliation_id, 'reconciliation_statement_date'); - $summary['Cleared on'] = $statement ? 'the statement to ' . date('M j, Y', strtotime($statement)) : 'a statement since undone'; + $brought = intval(getFieldById('account_reconciliations', $reconciliation_id, 'reconciliation_opening')) === 1; + $summary['Cleared on'] = $statement ? ($brought ? 'brought forward to ' : 'the statement to ') . date('M j, Y', strtotime($statement)) : 'a statement since undone'; } $show = (string) ($src['show'] ?? ''); $shows = accountLedgerShows($all_accounts); @@ -657,6 +659,11 @@ function transferSave(array $in, $transfer_id = 0, &$error = '') { mysqli_query($mysqli, "UPDATE revenues SET revenue_date = '$date', revenue_amount = $amount_sql, revenue_account_id = $to, revenue_currency_code = '$currency' WHERE revenue_id = " . intval($existing['transfer_revenue_id'])); mysqli_query($mysqli, "UPDATE transfers SET transfer_method = $method_sql, transfer_notes = $notes_sql WHERE transfer_id = $transfer_id"); + // A deposit moved to come out of another account no longer carries what was waiting in the first + if ($from !== intval($existing['transfer_from_id'])) { + mysqli_query($mysqli, "UPDATE payments SET payment_deposit_transfer_id = NULL, payment_updated_at = payment_updated_at WHERE payment_deposit_transfer_id = $transfer_id"); + mysqli_query($mysqli, "UPDATE revenues SET revenue_deposit_transfer_id = NULL, revenue_updated_at = revenue_updated_at WHERE revenue_deposit_transfer_id = $transfer_id"); + } return $transfer_id; } mysqli_query($mysqli, "INSERT INTO expenses SET expense_date = '$date', expense_amount = $amount_sql, expense_currency_code = '$currency', expense_vendor_id = 0, @@ -666,7 +673,9 @@ function transferSave(array $in, $transfer_id = 0, &$error = '') { revenue_account_id = $to, revenue_created_by = " . intval($session_user_id)); $revenue_id = mysqli_insert_id($mysqli); mysqli_query($mysqli, "INSERT INTO transfers SET transfer_expense_id = $expense_id, transfer_revenue_id = $revenue_id, transfer_method = $method_sql, transfer_notes = $notes_sql"); - return mysqli_insert_id($mysqli); + $transfer_id = mysqli_insert_id($mysqli); + transferDepositLink($transfer_id, $from, (array) ($in['deposit'] ?? [])); + return $transfer_id; } /** Delete a transfer - both sides of it. The row it deleted, or null with $error. */ @@ -684,5 +693,147 @@ function transferDelete($transfer_id, &$error = '') { mysqli_query($mysqli, "DELETE FROM expenses WHERE expense_id = " . intval($row['transfer_expense_id'])); mysqli_query($mysqli, "DELETE FROM revenues WHERE revenue_id = " . intval($row['transfer_revenue_id'])); mysqli_query($mysqli, "DELETE FROM transfers WHERE transfer_id = " . intval($row['transfer_id'])); + // What was in the deposit waits to be deposited again + mysqli_query($mysqli, "UPDATE payments SET payment_deposit_transfer_id = NULL, payment_updated_at = payment_updated_at WHERE payment_deposit_transfer_id = " . intval($row['transfer_id'])); + mysqli_query($mysqli, "UPDATE revenues SET revenue_deposit_transfer_id = NULL, revenue_updated_at = revenue_updated_at WHERE revenue_deposit_transfer_id = " . intval($row['transfer_id'])); + return $row; +} + +/* + * Deposits - checks and cash taken in to a cash account, then moved to the + * bank with a transfer. The payments and other income in a deposit carry its + * transfer (payment_deposit_transfer_id, revenue_deposit_transfer_id), so + * the next one offers only what is still waiting. + */ + +/** + * The payments and other income waiting in an account to be deposited, + * oldest first: not in a deposit yet, and not before the latest transfer out + * of it that had nothing picked - every transfer out before deposits were + * picked moved everything up to it. Each with kind, id, key (payment-12), + * date, amount, what, client_name, method and reference. + */ +function transferDepositCandidates($account_id, $limit = 200) { + global $mysqli; + $account_id = intval($account_id); + $cutoff = mysqli_fetch_row(mysqli_query($mysqli, "SELECT expenses.expense_date, expenses.expense_created_at FROM transfers + JOIN expenses ON expenses.expense_id = transfer_expense_id + WHERE expenses.expense_account_id = $account_id + AND NOT EXISTS (SELECT 1 FROM payments WHERE payment_deposit_transfer_id = transfer_id) + AND NOT EXISTS (SELECT 1 FROM revenues WHERE revenue_deposit_transfer_id = transfer_id) + ORDER BY expenses.expense_date DESC, expenses.expense_created_at DESC LIMIT 1")); + $after = function ($date, $created) use ($cutoff) { + return $cutoff ? " AND ($date > '" . escapeSql($cutoff[0]) . "' OR ($date = '" . escapeSql($cutoff[0]) . "' AND $created > '" . escapeSql($cutoff[1]) . "'))" : ''; + }; + $sql = mysqli_query($mysqli, "SELECT * FROM ( + SELECT 'payment' AS kind, payment_id AS id, payment_date AS date, payment_created_at AS created_at, payment_amount AS amount, + CONCAT(COALESCE(invoice_prefix, ''), COALESCE(invoice_number, '')) AS what, client_name, payment_method AS method, payment_reference AS reference + FROM payments + LEFT JOIN invoices ON invoice_id = payment_invoice_id + LEFT JOIN clients ON client_id = invoice_client_id + WHERE payment_account_id = $account_id AND payment_deposit_transfer_id IS NULL AND payment_archived_at IS NULL" . $after('payment_date', 'payment_created_at') . " + UNION ALL + SELECT 'revenue', revenue_id, revenue_date, revenue_created_at, revenue_amount, revenue_description, client_name, revenue_payment_method, revenue_reference + FROM revenues + LEFT JOIN clients ON client_id = revenue_client_id + WHERE revenue_account_id = $account_id AND revenue_deposit_transfer_id IS NULL AND revenue_archived_at IS NULL + AND NOT EXISTS (SELECT 1 FROM transfers WHERE transfer_revenue_id = revenue_id)" . $after('revenue_date', 'revenue_created_at') . " + ) AS waiting ORDER BY date ASC, created_at ASC, id ASC LIMIT " . intval($limit)); + $rows = []; + while ($row = mysqli_fetch_assoc($sql)) { + $row['id'] = intval($row['id']); + $row['key'] = $row['kind'] . '-' . $row['id']; + $row['amount'] = round(floatval($row['amount']), 2); + $what = trim((string) strtok((string) $row['what'], "\n")); + $row['what'] = $row['kind'] === 'payment' ? ($what !== '' ? "Payment on $what" : 'A payment') : ($what !== '' ? $what : 'Other income'); + $rows[] = $row; + } + return $rows; +} + +/** Put the picked payments and other income ('payment-12', 'revenue-5') waiting in the account it left in a new deposit's transfer. Returns how many. */ +function transferDepositLink($transfer_id, $from_account_id, array $keys) { + global $mysqli; + $transfer_id = intval($transfer_id); + $from = intval($from_account_id); + $count = 0; + foreach (array_unique(array_map('strval', $keys)) as $key) { + if (!preg_match('/^(payment|revenue)-(\d+)$/', $key, $m)) { + continue; + } + $id = intval($m[2]); + if ($m[1] === 'payment') { + mysqli_query($mysqli, "UPDATE payments SET payment_deposit_transfer_id = $transfer_id, payment_updated_at = payment_updated_at + WHERE payment_id = $id AND payment_account_id = $from AND payment_deposit_transfer_id IS NULL AND payment_archived_at IS NULL"); + } else { + mysqli_query($mysqli, "UPDATE revenues SET revenue_deposit_transfer_id = $transfer_id, revenue_updated_at = revenue_updated_at + WHERE revenue_id = $id AND revenue_account_id = $from AND revenue_deposit_transfer_id IS NULL AND revenue_archived_at IS NULL + AND NOT EXISTS (SELECT 1 FROM transfers WHERE transfer_revenue_id = revenue_id)"); + } + $count += mysqli_affected_rows($mysqli); + } + return $count; +} + +/** Before a payment or other income moves to another account: it comes out of the deposit it was in, which took it from the old one. */ +function transferDepositRelease($kind, $id, $account_id) { + global $mysqli; + $id = intval($id); + $account_id = intval($account_id); + if ($kind === 'payment') { + mysqli_query($mysqli, "UPDATE payments SET payment_deposit_transfer_id = NULL, payment_updated_at = payment_updated_at + WHERE payment_id = $id AND payment_account_id <> $account_id AND payment_deposit_transfer_id IS NOT NULL"); + } elseif ($kind === 'revenue') { + mysqli_query($mysqli, "UPDATE revenues SET revenue_deposit_transfer_id = NULL, revenue_updated_at = revenue_updated_at + WHERE revenue_id = $id AND revenue_account_id <> $account_id AND revenue_deposit_transfer_id IS NOT NULL"); + } +} + +/** What a deposit's transfer carried, oldest first - each with kind, id, date, amount, what and client_name. */ +function transferDepositItems($transfer_id) { + global $mysqli; + $id = intval($transfer_id); + $sql = mysqli_query($mysqli, "SELECT * FROM ( + SELECT 'payment' AS kind, payment_id AS id, payment_date AS date, payment_amount AS amount, CONCAT(COALESCE(invoice_prefix, ''), COALESCE(invoice_number, '')) AS what, + client_name, payment_method AS method, payment_reference AS reference + FROM payments LEFT JOIN invoices ON invoice_id = payment_invoice_id LEFT JOIN clients ON client_id = invoice_client_id + WHERE payment_deposit_transfer_id = $id + UNION ALL + SELECT 'revenue', revenue_id, revenue_date, revenue_amount, revenue_description, client_name, revenue_payment_method, revenue_reference + FROM revenues LEFT JOIN clients ON client_id = revenue_client_id + WHERE revenue_deposit_transfer_id = $id + ) AS deposit ORDER BY date ASC, id ASC"); + $rows = []; + while ($row = mysqli_fetch_assoc($sql)) { + $what = trim((string) strtok((string) $row['what'], "\n")); + $row['what'] = $row['kind'] === 'payment' ? ($what !== '' ? "Payment on $what" : 'A payment') : ($what !== '' ? $what : 'Other income'); + $rows[] = $row; + } + return $rows; +} + +/** A quick look's line for one deposited - where to and when, opening the deposit. '' for null. */ +function transferDepositedGlanceHtml($deposit) { + if (!$deposit) { + return ''; + } + $others = intval($deposit['count']) - 1; + return ''; +} + +/** The deposit a payment or other income went to the bank in - transfer_id, transfer_date, to_account_name and count (in it all) - or null. */ +function transferDepositedIn($kind, $id) { + global $mysqli; + $column = $kind === 'payment' ? 'payment_deposit_transfer_id' : 'revenue_deposit_transfer_id'; + $table = $kind === 'payment' ? 'payments' : 'revenues'; + $key = $kind === 'payment' ? 'payment_id' : 'revenue_id'; + $transfer_id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT $column FROM $table WHERE $key = " . intval($id)))[0] ?? 0); + $row = $transfer_id ? transferRow($transfer_id) : null; + if (!$row) { + return null; + } + $row['count'] = count(transferDepositItems($transfer_id)); return $row; } diff --git a/functions/income.php b/functions/income.php index 99845a7f1..ca2b053fe 100644 --- a/functions/income.php +++ b/functions/income.php @@ -306,6 +306,7 @@ function incomeRevenueSave(array $in, $revenue_id = 0, &$error = '') { if (!reconcileCheckChange('revenue', $revenue_id, $date, $amount, $account_id, $error)) { return 0; } + transferDepositRelease('revenue', $revenue_id, $account_id); mysqli_query($mysqli, "UPDATE revenues SET $set WHERE revenue_id = $revenue_id"); return $revenue_id; } diff --git a/functions/reconcile.php b/functions/reconcile.php index 5ba332456..f831c019c 100644 --- a/functions/reconcile.php +++ b/functions/reconcile.php @@ -18,6 +18,16 @@ * goes back to in progress with its ticks, to be fixed and finished again * or discarded. An account has one in progress at a time. * + * An account's first statement can start from the bank's balance on the day + * it starts rather than the opening balance - the way in for an account with + * years of history that won't all match the bank. Everything before that day + * is brought forward as reconciled, in a reconciliation of its own + * (reconciliation_opening) ending at the bank's balance. Where ITFlow had the + * account at something else that day, the opening balance can be corrected + * by the difference (reconciliation_adjustment), so the two match from then + * on. Undoing it - the latest, with nothing in progress - takes it away and + * puts the opening balance back. + * * Reconciling needs write access to Financial; undoing a finished one, full * access. */ @@ -62,6 +72,7 @@ function reconcileRow($reconciliation_id) { return null; } $row['finished'] = $row['reconciliation_finished_at'] !== null; + $row['opening'] = intval($row['reconciliation_opening']) === 1; $row['card'] = $row['account']['type'] === 3; return $row; } @@ -232,8 +243,11 @@ function reconcileStatementInput(array $account, array $in, &$error = '') { /** * Start reconciling an account against a statement. Lines brought in from a - * bank statement up to its date start ticked. Returns the new id, or 0 with - * $error. + * bank statement up to its date start ticked. On an account never reconciled, + * $in start_from 'statement' starts it from the bank's balance (start_balance + * - owed, for a card) on the day it starts (start_date): everything before + * that is brought forward as reconciled first (reconcileBringForward()). + * Returns the new id, or 0 with $error. */ function reconcileStart($account_id, array $in, &$error = '') { global $mysqli, $session_user_id; @@ -253,14 +267,101 @@ function reconcileStart($account_id, array $in, &$error = '') { } [$date, $ending, $notes] = $statement; $account_id = intval($account['account_id']); + + // The first statement, from the bank's balance the day it starts + $from = '1000-01-01'; + if (($in['start_from'] ?? '') === 'statement' && !reconcileLast($account_id)) { + $start = reconcileDateInput($in['start_date'] ?? ''); + if ($start === '' || $start > $date) { + $error = "Enter the day the statement starts - on or before the day it ends"; + return 0; + } + $balance = reconcileEndingInput($in['start_balance'] ?? '', $account['type'] === 3); + if ($balance === null || trim((string) ($in['start_balance'] ?? '')) === '') { + $error = $account['type'] === 3 ? 'Enter what the statement says was owed when it started' : 'Enter the balance the statement starts from'; + return 0; + } + $from = date('Y-m-d', strtotime("$start -1 day")); + reconcileBringForward($account, $from, $balance); + } + mysqli_query($mysqli, "INSERT INTO account_reconciliations SET reconciliation_account_id = $account_id, reconciliation_statement_date = '$date', reconciliation_starting_balance = " . number_format(reconcileStartingBalance($account_id), 2, '.', '') . ", reconciliation_ending_balance = " . number_format($ending, 2, '.', '') . ", reconciliation_notes = " . ($notes === '' ? 'NULL' : "'" . escapeSql($notes) . "'") . ", reconciliation_created_by = " . intval($session_user_id)); $id = mysqli_insert_id($mysqli); - reconcileTickImported(reconcileRow($id), '1000-01-01', $date); + reconcileTickImported(reconcileRow($id), $from, $date); return $id; } +/** + * Bring an account forward as reconciled to a day ($to): a finished + * reconciliation, marked as the opening one, ending at the bank's balance + * that day, with every line on the account up to it cleared on it. Its + * starting balance is the opening balance, so its difference is how far + * ITFlow's balance that day is from the bank's (reconcileCorrectOpening()). + * Returns its id. + */ +function reconcileBringForward(array $account, $to, $balance) { + global $mysqli, $session_user_id; + $account_id = intval($account['account_id']); + $to = escapeSql($to); + mysqli_query($mysqli, "INSERT INTO account_reconciliations SET reconciliation_account_id = $account_id, reconciliation_statement_date = '$to', + reconciliation_starting_balance = " . number_format(floatval($account['opening_balance']), 2, '.', '') . ", reconciliation_ending_balance = " . number_format($balance, 2, '.', '') . ", + reconciliation_opening = 1, reconciliation_created_by = " . intval($session_user_id) . ", reconciliation_finished_by = " . intval($session_user_id) . ", reconciliation_finished_at = NOW()"); + $id = mysqli_insert_id($mysqli); + foreach (reconcileKinds() as $k) { + mysqli_query($mysqli, "UPDATE {$k['table']} SET {$k['rec']} = $id, {$k['updated']} = {$k['updated']} + WHERE {$k['account']} = $account_id AND {$k['rec']} IS NULL AND {$k['archived']} IS NULL AND {$k['date']} <= '$to'"); + } + return $id; +} + +/** The brought forward reconciliation on an account (reconcileRow()), or null. */ +function reconcileOpening($account_id) { + global $mysqli; + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT reconciliation_id FROM account_reconciliations + WHERE reconciliation_account_id = " . intval($account_id) . " AND reconciliation_opening = 1 LIMIT 1")); + return $row ? reconcileRow($row[0]) : null; +} + +/** + * How far ITFlow's balance was from the bank's on the day an account was + * brought forward to - the bank's less ITFlow's - or 0.00. + */ +function reconcileOpeningGap(array $opening) { + return round(reconcileTotals($opening)['difference'], 2); +} + +/** + * Correct an account's opening balance by the gap where it was brought + * forward, so ITFlow's balance matches the bank's from that day on. Once + * only; undoing the brought forward reconciliation puts it back. Returns the + * amount it moved by, or null with $error. + */ +function reconcileCorrectOpening($reconciliation_id, &$error = '') { + global $mysqli; + $error = ''; + $row = reconcileRow($reconciliation_id); + if (!$row || !$row['opening']) { + $error = 'That reconciliation no longer exists'; + return null; + } + if (abs(floatval($row['reconciliation_adjustment'])) >= 0.005) { + $error = 'The opening balance was corrected already'; + return null; + } + $gap = reconcileOpeningGap($row); + if (abs($gap) < 0.005) { + $error = 'ITFlow matches the bank there already'; + return null; + } + $gap_sql = number_format($gap, 2, '.', ''); + mysqli_query($mysqli, "UPDATE accounts SET opening_balance = opening_balance + $gap_sql WHERE account_id = " . intval($row['reconciliation_account_id'])); + mysqli_query($mysqli, "UPDATE account_reconciliations SET reconciliation_starting_balance = reconciliation_starting_balance + $gap_sql, reconciliation_adjustment = $gap_sql + WHERE reconciliation_id = " . intval($row['reconciliation_id'])); + return $gap; +} + /** * Change the statement of one in progress. Lines ticked on it dated after a * new, earlier date are unticked; lines brought in from a bank statement up @@ -368,7 +469,8 @@ function reconcileDiscard($reconciliation_id, &$error = '') { /** * Undo a finished reconciliation - only the latest on its account, and not * while another is in progress there. It goes back to in progress with what - * was ticked, its lines free to change. Returns its row, or null with $error. + * was ticked, its lines free to change - or, brought forward, it goes and + * the opening balance goes back. Returns its row, or null with $error. */ function reconcileUndo($reconciliation_id, &$error = '') { global $mysqli; @@ -387,14 +489,25 @@ function reconcileUndo($reconciliation_id, &$error = '') { $error = 'Another statement is being reconciled on ' . $row['account']['account_name'] . ' - discard it first'; return null; } - mysqli_query($mysqli, "UPDATE account_reconciliations SET reconciliation_finished_at = NULL, reconciliation_finished_by = 0 WHERE reconciliation_id = " . intval($row['reconciliation_id'])); + $id = intval($row['reconciliation_id']); + // Brought forward: it goes, its lines with it, and the opening balance goes back + if ($row['opening']) { + foreach (reconcileKinds() as $k) { + mysqli_query($mysqli, "UPDATE {$k['table']} SET {$k['rec']} = NULL, {$k['updated']} = {$k['updated']} WHERE {$k['rec']} = $id"); + } + mysqli_query($mysqli, "UPDATE accounts SET opening_balance = opening_balance - " . number_format(floatval($row['reconciliation_adjustment']), 2, '.', '') . " + WHERE account_id = " . intval($row['reconciliation_account_id'])); + mysqli_query($mysqli, "DELETE FROM account_reconciliations WHERE reconciliation_id = $id"); + return $row; + } + mysqli_query($mysqli, "UPDATE account_reconciliations SET reconciliation_finished_at = NULL, reconciliation_finished_by = 0 WHERE reconciliation_id = $id"); return $row; } /** * The finished reconciliation a line is cleared on (reconciliation_id, - * reconciliation_account_id, reconciliation_statement_date, account_name), - * or null when it isn't. + * reconciliation_account_id, reconciliation_statement_date, + * reconciliation_opening, account_name), or null when it isn't. */ function reconcileLock($kind, $id) { global $mysqli; @@ -403,7 +516,7 @@ function reconcileLock($kind, $id) { return null; } $k = $kinds[$kind]; - return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT reconciliation_id, reconciliation_account_id, reconciliation_statement_date, account_name + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT reconciliation_id, reconciliation_account_id, reconciliation_statement_date, reconciliation_opening, account_name FROM {$k['table']} JOIN account_reconciliations ON reconciliation_id = {$k['rec']} AND reconciliation_finished_at IS NOT NULL JOIN accounts ON account_id = reconciliation_account_id @@ -412,8 +525,11 @@ function reconcileLock($kind, $id) { /** What to say about a cleared line - "It cleared on the Operating Checking statement to Sep 30, 2026 - undo that reconciliation to ..." */ function reconcileLockText(array $lock, $to = 'change its amount, date or account') { - return 'It cleared on the ' . $lock['account_name'] . ' statement to ' . date('M j, Y', strtotime($lock['reconciliation_statement_date'])) - . " - undo that reconciliation to $to"; + $day = date('M j, Y', strtotime($lock['reconciliation_statement_date'])); + if (!empty($lock['reconciliation_opening'])) { + return "It is before $day, when {$lock['account_name']} was brought forward as reconciled - undo that to $to"; + } + return 'It cleared on the ' . $lock['account_name'] . " statement to $day - undo that reconciliation to $to"; } /** A quick look's line for a cleared one - the statement it cleared on, opening the lines it cleared. '' for null. */ @@ -421,9 +537,11 @@ function reconcileGlanceHtml($lock) { if (!$lock) { return ''; } - return '
Cleared on the ' - . escapeHtml($lock['account_name']) . ' statement to ' . escapeHtml(date('M j, Y', strtotime($lock['reconciliation_statement_date']))) . '
'; + $link = '' + . escapeHtml(date('M j, Y', strtotime($lock['reconciliation_statement_date']))) . ''; + return '
' + . (!empty($lock['reconciliation_opening']) ? 'Brought forward as reconciled on ' . escapeHtml($lock['account_name']) . ' to ' . $link + : 'Cleared on the ' . escapeHtml($lock['account_name']) . ' statement to ' . $link) . '
'; } /** An edit form's note for a cleared one - its amount, date and account are locked. '' for null. */