diff --git a/CHANGELOG.md b/CHANGELOG.md
index ba02f3c93..73a0a822b 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.5) 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.6) in the same pass. Nothing else is required.
-This is a big release, with twenty-six database steps in one go, so take a backup before you update.
+This is a big release, with twenty-seven 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:
@@ -382,7 +382,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- The review lists every line with the vendor, category and client it matched: what you picked for that merchant last time, or one of your vendors whose name is in it (cut short too, such as THREE RIVERS COLO for Three Rivers Colocation), with the vendor's last category. A line with no match offers a new vendor named from its text - "SQ *JOES COFFEE #123 PITTSBURGH PA" is Joes Coffee.
- Picking a vendor fills in the other lines from the same merchant. Set a category or client for all the ticked lines at once. A line for a client can be billed on to them.
- Lines brought in before are locked, so importing the same statement twice brings nothing in twice - two coffees on one day are still two. A line with the same amount as an expense entered by hand on that account within 4 days is left out unless ticked, and is linked to that expense so the next statement knows it too.
- - Payments to the card, deposits and refunds are left out unless ticked - then they come in as money back.
+ - Payments to the card, deposits and refunds are left out unless ticked - then they come in as money back. Bring them in as income takes the same statement on to Import Deposits (see Income).
+ - Whether charges are positive or negative is worked out from the words on the lines (DEPOSIT, ACH CREDIT, TRANSFER FROM, INTEREST against PURCHASE, WITHDRAWAL, ACH DEBIT) when they say, so a statement with mostly deposits reads the right way round.
- Import brings in the ticked lines, making each new vendor once, and opens the expenses list on that account and those dates. The merchants are remembered for next time - see or forget them from the Import Statement page.
- **Paid personally**: an expense an agent paid for themselves - a hotel, parts from the store - is picked as Paid personally, with who paid it. It counts as spent on its date like any other, but comes out of none of your accounts until they are paid back.
- The list has a To reimburse pill. On it, each agent shows with what they are owed and a Reimburse button. Rows show who paid and whether they have been paid back.
@@ -602,6 +603,22 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Export takes the same filters as the list, including the pills, with Invoice and Paid Online columns.
- Income Summary and Profit & Loss list No category as a line, opening those on the list, and their Invoice payments and Other income figures open those pills. Accounts link to Transactions and the income into each account. Search finds other income by what it was, its reference or its amount, and payments by their reference, opening the quick look.
- The demo data adds the money an MSP takes in besides invoices: a distributor's partner rebate each quarter, interest on the savings account and the odd referral fee.
+ - **Import Deposits**, from the Income list's menu, brings the money in on a bank statement in as payments and income:
+ - Upload the CSV your bank exports, and pick the account the deposits went into and how clients usually pay. It is the same file Import Statement takes for expenses, read the same way, and the columns are kept on the account for both: a statement already brought in for its expenses goes straight to the review, and either side can go on to the other without uploading it again. Only the money in is brought in here.
+ - Each deposit is matched to what it is:
+ - an invoice number in its text or reference ("MOBILE DEPOSIT INV-1042")
+ - what the same payer was last time - a client's payment, other income in its category, or a transfer
+ - a client's name in it ("ACH CREDIT RAVENWOOD DENTAL GRP")
+ - the only invoice owing exactly that much, the oldest of one client's invoices owing it, or everything one client owes together
+ - a payout from the payment provider, which comes in as a transfer from the account its online payments go into, and a transfer from your savings or another of your accounts
+ - anything else is other income, for you to give a category and the client it came from
+ - A payment pays the client's invoices the oldest due first. One check for several invoices pays them all, and a deposit short of what they owe leaves the last one part paid. Pick the client and the invoices it pays are ticked for you - the one owing the amount, the ones that add up to it, or the oldest first - and each deposit says what it pays off, in full or part paid, or how much more than they owe it is. Two deposits on one invoice don't pay it twice.
+ - Deposits brought in before are locked, so importing the same statement again brings nothing in twice. A deposit with the amount of a payment, other income or transfer entered by hand on that account within 4 days - or of a day's payments together, one check entered as a payment on each invoice - is left out unless ticked, and is linked to what was entered so the next statement knows it. A payout into the account the payment provider's payments go into is recorded already, so it is left out.
+ - Import brings in the ticked deposits as payments (each invoice paid or part paid, with its history saying so), other income and transfers, and opens the Income list on that account and those dates. Email each client their receipt sends the usual payment receipt for each invoice paid. Every ticked deposit is checked first, so nothing comes in until they are all right.
+ - How it was paid is read from the text - ACH, a check, a wire - when one of your payment methods fits, or the one picked on upload.
+ - The payers are remembered for next time - see or forget them from the Import Deposits page.
+ - A payment or other income brought in this way says so on its quick look.
+ - Payments need write access to Sales, as adding one on an invoice does. Without it, deposits can still come in as other income and transfers.
### Bug Fixes
@@ -710,6 +727,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- 3.0.3: `trips.trip_end_odmeter` renamed `trip_end_odometer`, and `trip_miles` from `float(15,1)` to `decimal(10,1)` (0.0). New `trip_location_id`, `trip_ticket_id` and `trip_created_by` (0), keyed with `trip_user_id` (`trip_user_id`, `trip_date`). `trip_created_by` is backfilled from the audit log's Trip Create entries, else the driver, and `trip_location_id` where the destination matches one of the client's locations by name or by `formatAddress()` of its address, case and spacing aside.
- 3.0.4: `trips.trip_own_vehicle` (0), `trip_expense_id` (0, keyed), `trip_billable` (0), `trip_invoice_id` (0, keyed) and `trip_invoice_item_id` (0). `settings.config_mileage_unit` ('mi' or 'km'), `config_mileage_rate` (`decimal(10,4)`, 0), `config_mileage_category_id` (set to an Expense category named Mileage, else Travel), `config_mileage_vendor_id`, `config_trip_charge` (`decimal(15,2)`), `config_trip_bill_rate` (`decimal(10,4)`), `config_trip_included` (`decimal(10,1)`) and `config_trip_item_name` ('Travel').
- 3.0.5: `revenues.revenue_description` becomes `text`, with `revenue_created_by` (0, backfilled from the audit log's Revenue Create entries) and a `revenue_date` key. `payments` gets a `payment_date` key.
+ - 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`).
- 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`.
@@ -929,6 +947,13 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Seeds: `demoBuildClient()` sets `revenue_created_by`, and `demoBuildCompanyFinancials()` adds the company's rebates, interest and referral fees (references `RBT-`, `INT-` and `REF-`, removed with the demo data).
- CSS: `.itflow-income-from`.
- Removed: `agent/post/income_model.php`, and `agent/modals/income/income_bulk_edit_account.php`, `income_bulk_edit_category.php` and `income_bulk_edit_method.php` (`bulk_edit_income_account`, `bulk_edit_income_category` and `bulk_edit_income_method` are replaced by `bulk_edit_income`).
+- Import Deposits, in the new `functions/income_import.php` (loaded after `income.php`), on top of `functions/expense_import.php`'s reader:
+ - `incomeImportLines($rows, $map, &$charges)` keeps the money in from `expenseImportLines()`, made positive, counting the charges. `incomeImportOpenInvoices()` is every invoice still owed in the agent's client scope, oldest due first, with its balance. `incomeImportRules()`, `incomeImportMethod($text, $default)`, `incomeImportInvoiceNumbers($text, $prefixes)` (after an invoice prefix in use or the word invoice - never a bare number), `incomeImportPickInvoices($invoices, $amount)` (`exact`, `sum` - the fewest adding up to it, of up to 14 - `oldest` or `over`), `incomeImportNameWords()` and `incomeImportNameMatch()` (whole, or cut short), `incomeImportProviderAccounts()` and `incomeImportKind($text)` (`payout` or `transfer`).
+ - `incomeImportMatch($lines, $account_id, $method)` sets each deposit's `action` (payment, income or transfer), `client_id`, `invoice_ids`, `how`, `category_id`, `from_account_id`, `method`, `matched` (number, rule, name, amount, payout or transfer) and `match_note`. `expenseImportKeys()` keys them. `incomeImportDuplicates($account_id, $lines)` sets `imported` (from `payment_import_key` or `revenue_import_key`) or `entered_type`, `entered_ids` and `entered_label` (a payment, revenue or transfer leg on the account within `INCOME_IMPORT_DUPLICATE_DAYS`, or one day's payments summing to it). `incomeImportReview($import, &$charges)` runs them all and sets `state` (new, imported, entered, recorded or problem).
+ - `incomeImportSave($import, $picks, $opts, &$error)` checks every ticked line - `incomeImportCanPay()` (Sales and Financial at 2), the client in scope, its open invoices with running balances across the statement, an income category, another account - before inserting the payments (`updateInvoiceStatusFromPayments()`, history, `triggerCustomAction('invoice_pay')`, `billingPaymentSend()` with `$opts['receipts']`), revenues and transfers (`incomeImportTransfer()`), upserting `income_import_rules` and stamping the keys of entered lines left out.
+ - New page `agent/income_import.php` (`?step=columns` and `?step=review`, the statement in `$_SESSION['income_import']`) and `js/income_import.js` (`itflowIncomeImport()`, with each client's open invoices). Handlers in the new `agent/post/income_import.php`: `income_import_upload`, `income_import_columns`, `income_import_save` (POST `picks`, one JSON list of `n`, `take`, `action`, `client`, `invoices`, `category`, `account`, and `receipts`), GET `income_import_discard`, `income_import_rule_delete`, and `income_import_from_statement` and `expense_import_from_statement`, which copy the statement in the session from one side to the other. New window `agent/modals/income/income_import_rules.php`.
+ - The columns step is now `agent/includes/statement_columns.php` (`$columns_form_id`, `$columns_submit`, `$columns_side`), shared by `agent/expense_import.php` and `agent/income_import.php`. `expenseImportGuess()` takes the sign from the words on the lines when they are clear.
+ - CSS: `.itflow-import-details` and `.itflow-import-invoices`.
- 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.6.php b/admin/database_updates/3.0.6.php
new file mode 100644
index 000000000..46aea42c5
--- /dev/null
+++ b/admin/database_updates/3.0.6.php
@@ -0,0 +1,36 @@
+ 'Statement', 'columns' => 'Columns', 'review' => 'Review']
';
- $html .= '' . ($optional ? '- None -' : '- Pick the column -') . ' ';
- foreach ($header as $c => $label) {
- $html .= '' . escapeHtml($label) . ' ';
- }
- return $html . '';
- };
+ $columns_form_id = 'expenseImportColumns';
+ $columns_submit = 'expense_import_columns';
+ $columns_side = 'expense';
+ require __DIR__ . '/includes/statement_columns.php';
?>
-
-
-
-
'Statement', 'columns' => 'Columns', 'review' => 'Review']
Money in
= $count['money_in'] ?>
-
Payments and refunds - left out
+
diff --git a/agent/includes/statement_columns.php b/agent/includes/statement_columns.php
new file mode 100644
index 000000000..6cdbb6130
--- /dev/null
+++ b/agent/includes/statement_columns.php
@@ -0,0 +1,194 @@
+';
+ $html .= '
' . ($optional ? '- None -' : '- Pick the column -') . ' ';
+ foreach ($header as $c => $label) {
+ $html .= '
' . escapeHtml($label) . ' ';
+ }
+ return $html . '';
+};
+// The sign is kept as which way round a charge is; the income side asks it from the deposit's side
+$sign_options = $columns_side === 'income'
+ ? ['negative' => 'Positive - 25.00 came in', 'positive' => 'Negative - -25.00 came in']
+ : ['positive' => 'Positive - 25.00 is spent', 'negative' => 'Negative - -25.00 is spent'];
+?>
+
+
+
+
diff --git a/agent/income.php b/agent/income.php
index 9a7ea780b..5214a5ca7 100644
--- a/agent/income.php
+++ b/agent/income.php
@@ -154,6 +154,9 @@ $invoices_url = 'invoices.php?' . ($client_page ? "client_id=$client_id&" : '')
= $can_edit ? '' : ' ' ?>
diff --git a/agent/income_import.php b/agent/income_import.php
new file mode 100644
index 000000000..8287523cb
--- /dev/null
+++ b/agent/income_import.php
@@ -0,0 +1,409 @@
+ 'Statement', 'columns' => 'Columns', 'review' => 'Review'];
+
+?>
+
+
+ Income
+ Import Deposits
+
+
+
+
+ $label) { $i++;
+ $done = array_search($key, array_keys($steps)) < array_search($step, array_keys($steps)); ?>
+ 1) { ?>
+
+ = $done ? ' ' : $i . '. ' ?>= $label ?>
+
+
+
+
+ = escapeHtml($import['file_name']) ?> · = escapeHtml($account['account_name'] ?? 'an account since deleted') ?>
+ Start over
+
+
+
+
+
+
+
+
+
+
= escapeHtml($import['file_name']) ?> is part way through - nothing from it is imported yet.
+
Carry on with it
+
+
+
+
+
+
+
+
+
How it goes
+
+ The columns are worked out for you, and kept on the account - a statement already imported for expenses goes straight to the review.
+ Each deposit is matched to what it pays: an invoice number in its text, the client it came from last time or whose name is in it, or the only invoice owing that much. A client's invoices are paid oldest first, and a deposit short of them leaves the last one part paid.
+ Payouts from the payment provider and transfers from your other accounts come in as transfers, not income. Anything else is other income, with its category and client.
+ Deposits brought in before, and ones that match a payment or income entered by hand within = INCOME_IMPORT_DUPLICATE_DAYS ?> days, are left out unless you tick them.
+ Nothing is imported until you press Import on the review.
+
+
+
= $rules_count ?> payer= $rules_count === 1 ? '' : 's' ?> remembered
+
+
See them
+
+
+
+
+
+
+
+
+
+ $invoice['invoice_id'], 'ref' => $invoice['ref'], 'balance' => $invoice['balance'], 'due' => $invoice['due'],
+ 'scope' => mb_strimwidth($invoice['scope'], 0, 60, '...'), 'currency' => $invoice['currency']];
+ }
+ $payer_options = '';
+ foreach ($clients as $client_id => $client_name) {
+ if (isset($owing[$client_id])) {
+ $payer_options .= '
' . escapeHtml($client_name . ' - owes ' . billingMoney(array_sum(array_column($owing[$client_id], 'balance')))) . ' ';
+ }
+ }
+ $client_options = '';
+ foreach ($clients as $client_id => $client_name) {
+ $client_options .= '
' . escapeHtml($client_name) . ' ';
+ }
+ $category_options = '';
+ foreach ($categories as $category_id => $category) {
+ $category_options .= '
' . escapeHtml($category['category_name']) . ' ';
+ }
+ $account_options = '';
+ foreach ($accounts as $account_id => $row) {
+ if ($account_id !== intval($import['account_id'])) {
+ $account_options .= '
' . escapeHtml($row['account_name']) . ' ';
+ }
+ }
+
+ $count = ['new' => 0, 'imported' => 0, 'entered' => 0, 'recorded' => 0, 'problem' => 0, 'payment' => 0];
+ $total_new = 0;
+ $total_paying = 0;
+ foreach ($lines as $line) {
+ $count[$line['state']]++;
+ if ($line['state'] === 'new') {
+ $total_new += $line['amount'];
+ if ($line['action'] === 'payment' && $line['invoice_ids'] && $line['how'] !== 'over') {
+ $count['payment']++;
+ $total_paying += $line['amount'];
+ }
+ }
+ }
+ $states = [
+ 'new' => ['label' => 'New', 'tone' => 'primary'],
+ 'imported' => ['label' => 'Imported before', 'tone' => 'secondary'],
+ 'entered' => ['label' => 'Entered already?', 'tone' => 'warning'],
+ 'recorded' => ['label' => 'Recorded already', 'tone' => 'secondary'],
+ 'problem' => ['label' => "Can't read", 'tone' => 'danger'],
+ ];
+ $matched_icons = ['number' => 'fa-hashtag', 'rule' => 'fa-magic', 'name' => 'fa-user', 'amount' => 'fa-equals', 'payout' => 'fa-globe', 'transfer' => 'fa-exchange-alt'];
+ ?>
+
+
+
+
+
+
New deposits
+
= $count['new'] ?>
+
= $money($total_new) ?> came in
+
+
+
+
+
Paying invoices
+
= $count['payment'] ?>
+
= $can_pay ? $money($total_paying) . ' matched to what clients owe' : 'Recording payments takes Sales access' ?>
+
+
+
+
+
Already in
+
= $count['imported'] + $count['entered'] + $count['recorded'] ?>
+
= $count['imported'] ?> imported before · = $count['entered'] ?> look entered= $count['recorded'] ? ' · ' . $count['recorded'] . ' payout' . ($count['recorded'] === 1 ? '' : 's') : '' ?>
+
+
+
+
+
Columns
+
= $import['remembered'] ? 'As last time' : 'As you set them' ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
A deposit whose words start like these is matched to what was picked for it last time. Each import updates them.
+
+
+
+
+
+ Deposit starts
+ It is
+ From
+ Used
+
+
+
+
+
+
+ = escapeHtml($rule['import_rule_match']) ?>
+ = escapeHtml($actions[$action] ?? $action) ?>= $action === 'income' && $rule['category_name'] ? ' · ' . escapeHtml($rule['category_name']) . ' ' : '' ?>
+ = escapeHtml($from) ?>
+ = intval($rule['import_rule_used_count']) ?>
+
+
+
+
+
+
+
+
+
+
+
+
Nothing remembered yet - each statement you import teaches it.
+
+
+
+
+
- = timeAgo($row['payment_created_at']) ?>
+ = timeAgo($row['payment_created_at']) ?> from a bank statement
diff --git a/agent/modals/revenue/revenue.php b/agent/modals/revenue/revenue.php
index eb3f46d95..5611519fb 100644
--- a/agent/modals/revenue/revenue.php
+++ b/agent/modals/revenue/revenue.php
@@ -75,7 +75,7 @@ ob_start();
- = timeAgo($row['revenue_created_at']) ?> by = escapeHtml($row['created_by_name']) ?>
+ = timeAgo($row['revenue_created_at']) ?> by = escapeHtml($row['created_by_name']) ?> from a bank statement
diff --git a/agent/post/income_import.php b/agent/post/income_import.php
new file mode 100644
index 000000000..207108f2a
--- /dev/null
+++ b/agent/post/income_import.php
@@ -0,0 +1,219 @@
+ $account_id,
+ 'method' => $method,
+ 'file_name' => mb_substr(basename((string) $file['name']), 0, 120),
+ 'header' => $read['header'],
+ 'rows' => $read['rows'],
+ 'map' => $map,
+ 'guess' => $map ?: expenseImportGuess($read['header'], $read['rows']),
+ 'remembered' => $map !== null,
+ ];
+
+ redirect('income_import.php?step=' . ($map ? 'review' : 'columns'));
+
+}
+
+if (isset($_POST['income_import_columns'])) {
+
+ validateCSRFToken();
+
+ enforceUserPermission('module_financial', 2);
+
+ $import = $_SESSION['income_import'] ?? null;
+ if (!$import) {
+ flashAlert('Upload the statement again - the one you started is gone', 'error');
+ redirect('income_import.php');
+ }
+ $map = expenseImportMapClean($_POST, count($import['header']));
+ if (!$map) {
+ flashAlert('Pick the columns with the date, the description and the amount', 'error');
+ redirect('income_import.php?step=columns');
+ }
+ if (!array_filter(expenseImportLines($import['rows'], $map), function ($line) { return $line['problem'] === ''; })) {
+ $_SESSION['income_import']['guess'] = $map;
+ flashAlert("None of the lines read with those columns - check the date format and the amount", 'error');
+ redirect('income_import.php?step=columns');
+ }
+
+ $_SESSION['income_import']['map'] = $map;
+ $_SESSION['income_import']['guess'] = $map;
+ $_SESSION['income_import']['remembered'] = false;
+ expenseImportSaveMap($import['account_id'], $import['header'], $map);
+
+ redirect('income_import.php?step=review');
+
+}
+
+if (isset($_POST['income_import_save'])) {
+
+ validateCSRFToken();
+
+ enforceUserPermission('module_financial', 2);
+
+ $import = $_SESSION['income_import'] ?? null;
+ if (!$import || !$import['map']) {
+ flashAlert('Upload the statement again - the one you started is gone', 'error');
+ redirect('income_import.php');
+ }
+ $picks = [];
+ foreach ((array) json_decode((string) ($_POST['picks'] ?? ''), true) as $pick) {
+ if (is_array($pick) && isset($pick['n'])) {
+ $picks[intval($pick['n'])] = [
+ 'take' => !empty($pick['take']),
+ 'action' => (string) ($pick['action'] ?? ''),
+ 'client' => intval($pick['client'] ?? 0),
+ 'invoices' => array_map('intval', (array) ($pick['invoices'] ?? [])),
+ 'category' => intval($pick['category'] ?? 0),
+ 'account' => intval($pick['account'] ?? 0),
+ ];
+ }
+ }
+ $result = incomeImportSave($import, $picks, ['receipts' => !empty($_POST['receipts'])], $error);
+ if (!$result) {
+ flashAlert(escapeHtml($error), 'error');
+ redirect('income_import.php?step=review');
+ }
+ unset($_SESSION['income_import']);
+
+ $account_name = (string) getFieldById('accounts', intval($import['account_id']), 'account_name');
+ $currency = (string) getFieldById('accounts', intval($import['account_id']), 'account_currency_code') ?: $session_company_currency;
+ $count = $result['payments'] + $result['income'] + $result['transfers'];
+ logAudit("Income", "Import", "$session_name imported deposits from " . escapeSql($import['file_name'] . " for $account_name") . ": " . $result['payments'] . " payment(s), "
+ . $result['income'] . " other income, " . $result['transfers'] . " transfer(s)");
+
+ $parts = [];
+ if ($result['payments']) {
+ $parts[] = '' . escapeHtml(billingMoney($result['paid'], $currency)) . ' paid on ' . ($result['invoices_paid'] + $result['invoices_part']) . ' invoice' . (($result['invoices_paid'] + $result['invoices_part']) === 1 ? '' : 's')
+ . ($result['invoices_part'] ? ' (' . $result['invoices_part'] . ' part paid)' : '');
+ }
+ if ($result['income']) {
+ $parts[] = '' . escapeHtml(billingMoney($result['income_total'], $currency)) . ' other income';
+ }
+ if ($result['transfers']) {
+ $parts[] = $result['transfers'] . ' transfer' . ($result['transfers'] === 1 ? '' : 's') . ' in';
+ }
+ $notes = [];
+ if ($result['receipts']) {
+ $notes[] = $result['receipts'] . ' receipt' . ($result['receipts'] === 1 ? '' : 's') . ' emailed';
+ }
+ if ($result['linked']) {
+ $notes[] = $result['linked'] . ' matched to what was entered already';
+ }
+ if ($result['skipped']) {
+ $notes[] = $result['skipped'] . ' imported before';
+ }
+ flashAlert(($count ? implode(', ', $parts) . ' brought in' : 'Nothing brought in') . ($notes ? ' · ' . escapeHtml(implode(', ', $notes)) : ''));
+
+ if (!$count) {
+ redirect('income.php');
+ }
+ redirect('income.php?' . http_build_query(['account' => intval($import['account_id']), 'canned_date' => 'custom', 'dtf' => $result['from'], 'dtt' => $result['to']]));
+
+}
+
+/* Start over - the statement in progress is dropped. */
+if (isset($_GET['income_import_discard'])) {
+
+ validateCSRFToken();
+
+ unset($_SESSION['income_import']);
+
+ redirect('income_import.php');
+
+}
+
+/* The statement read for expenses, on to its deposits - and back - without uploading it again. */
+if (isset($_GET['income_import_from_statement']) || isset($_GET['expense_import_from_statement'])) {
+
+ validateCSRFToken();
+
+ enforceUserPermission('module_financial', 2);
+
+ $to_income = isset($_GET['income_import_from_statement']);
+ $from = $_SESSION[$to_income ? 'expense_import' : 'income_import'] ?? null;
+ if (!$from) {
+ flashAlert('Upload the statement again - the one you started is gone', 'error');
+ redirect($to_income ? 'income_import.php' : 'expense_import.php');
+ }
+ $_SESSION[$to_income ? 'income_import' : 'expense_import'] = [
+ 'account_id' => $from['account_id'],
+ 'method' => $to_income ? (string) $config_default_payment_method : (string) $config_default_expense_payment_method,
+ 'file_name' => $from['file_name'],
+ 'header' => $from['header'],
+ 'rows' => $from['rows'],
+ 'map' => $from['map'],
+ 'guess' => $from['guess'],
+ 'remembered' => $from['remembered'],
+ ];
+
+ redirect(($to_income ? 'income_import.php' : 'expense_import.php') . '?step=' . ($from['map'] ? 'review' : 'columns'));
+
+}
+
+/* Forget what a payer was matched to. */
+if (isset($_GET['income_import_rule_delete'])) {
+
+ validateCSRFToken();
+
+ enforceUserPermission('module_financial', 2);
+
+ $rule_id = intval($_GET['income_import_rule_delete']);
+ $match = getFieldById('income_import_rules', $rule_id, 'import_rule_match');
+ mysqli_query($mysqli, "DELETE FROM income_import_rules WHERE import_rule_id = $rule_id");
+ if ($match !== null) {
+ logAudit("Income", "Import Rule Delete", "$session_name removed the deposit match for " . escapeSql($match));
+ }
+
+ flashAlert($match !== null ? 'Forgotten - ' . escapeHtml($match) . ' will be matched afresh next time' : 'That match was already gone', $match !== null ? 'success' : 'error');
+
+ redirect();
+
+}
diff --git a/css/itflow_custom.css b/css/itflow_custom.css
index f0835c5f3..b5edf8057 100644
--- a/css/itflow_custom.css
+++ b/css/itflow_custom.css
@@ -6374,3 +6374,19 @@ a.itflow-billing-stat:hover {
max-width: 0;
min-width: 14rem;
}
+/* Import Deposits' review - what a deposit pays, with the client's invoices to tick (agent/income_import.php) */
+.itflow-import-table .itflow-import-details {
+ min-width: 16rem;
+ max-width: 24rem;
+}
+.itflow-import-invoices {
+ max-height: 7.5rem;
+ overflow-y: auto;
+ padding: 0.25rem 0.5rem;
+ border: 1px solid var(--bs-border-color);
+ border-radius: var(--bs-border-radius-sm);
+ background-color: var(--bs-body-bg);
+}
+.itflow-import-invoices.is-invalid {
+ border-color: var(--bs-form-invalid-border-color);
+}
diff --git a/db.sql b/db.sql
index 78a3bdc22..5347021aa 100644
--- a/db.sql
+++ b/db.sql
@@ -1459,6 +1459,28 @@ CREATE TABLE `history` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `income_import_rules`
+--
+
+DROP TABLE IF EXISTS `income_import_rules`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8mb4 */;
+CREATE TABLE `income_import_rules` (
+ `import_rule_id` int(11) NOT NULL AUTO_INCREMENT,
+ `import_rule_match` varchar(200) NOT NULL,
+ `import_rule_action` varchar(10) NOT NULL DEFAULT 'income',
+ `import_rule_client_id` int(11) NOT NULL DEFAULT 0,
+ `import_rule_category_id` int(11) NOT NULL DEFAULT 0,
+ `import_rule_account_id` int(11) NOT NULL DEFAULT 0,
+ `import_rule_used_count` int(11) NOT NULL DEFAULT 0,
+ `import_rule_created_at` datetime NOT NULL DEFAULT current_timestamp(),
+ `import_rule_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
+ PRIMARY KEY (`import_rule_id`),
+ UNIQUE KEY `import_rule_match` (`import_rule_match`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `invoice_items`
--
@@ -1788,9 +1810,11 @@ CREATE TABLE `payments` (
`payment_archived_at` datetime DEFAULT NULL,
`payment_account_id` int(11) NOT NULL,
`payment_invoice_id` int(11) NOT NULL DEFAULT 0,
+ `payment_import_key` varchar(64) DEFAULT NULL,
PRIMARY KEY (`payment_id`),
KEY `payment_invoice_id` (`payment_invoice_id`),
- KEY `payment_date` (`payment_date`)
+ KEY `payment_date` (`payment_date`),
+ KEY `payment_import_key` (`payment_import_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -2354,9 +2378,11 @@ CREATE TABLE `revenues` (
`revenue_account_id` int(11) NOT NULL,
`revenue_client_id` int(11) NOT NULL DEFAULT 0,
`revenue_created_by` int(11) NOT NULL DEFAULT 0,
+ `revenue_import_key` varchar(64) DEFAULT NULL,
PRIMARY KEY (`revenue_id`),
KEY `revenue_client_id` (`revenue_client_id`,`revenue_archived_at`),
- KEY `revenue_date` (`revenue_date`)
+ KEY `revenue_date` (`revenue_date`),
+ KEY `revenue_import_key` (`revenue_import_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
diff --git a/functions.php b/functions.php
index c73d88a46..2be3ce7c6 100644
--- a/functions.php
+++ b/functions.php
@@ -57,3 +57,4 @@ require_once __DIR__ . '/functions/expenses.php';
require_once __DIR__ . '/functions/expense_import.php';
require_once __DIR__ . '/functions/trips.php';
require_once __DIR__ . '/functions/income.php';
+require_once __DIR__ . '/functions/income_import.php';
diff --git a/functions/expense_import.php b/functions/expense_import.php
index e2a85f232..ba9e3e2fa 100644
--- a/functions/expense_import.php
+++ b/functions/expense_import.php
@@ -305,18 +305,36 @@ function expenseImportGuess(array $header, array $rows) {
}
}
- // Charges are what most lines are
+ // Charges are what most lines are - unless the words say which way round
+ // money in is ("DEPOSIT", "ACH CREDIT", "TRANSFER FROM", "INTEREST" against
+ // "PURCHASE", "WITHDRAWAL", "ACH DEBIT"), as on a deposits-only export
$map['sign'] = 'positive';
if ($map['amount'] !== null) {
$negative = 0;
$positive = 0;
+ $votes = ['positive' => 0, 'negative' => 0];
+ $in_words = '/\b(deposit|deposits|ach credit|direct dep|transfer from|interest|refund|payment received|thank you|incoming)\b/i';
+ $out_words = '/\b(purchase|pos|debit card|ach debit|withdrawal|atm|fee|payment to|bill pay|transfer to|check paid|autopay)\b/i';
foreach ($sample as $cells) {
$amount = expenseImportAmount($cells[$map['amount']] ?? '');
if ($amount !== null && $amount != 0) {
$amount < 0 ? $negative++ : $positive++;
+ $text = $map['description'] !== null ? (string) ($cells[$map['description']] ?? '') : '';
+ $in = preg_match($in_words, $text);
+ $out = preg_match($out_words, $text);
+ if ($in && !$out) {
+ $votes[$amount < 0 ? 'positive' : 'negative']++;
+ } elseif ($out && !$in) {
+ $votes[$amount < 0 ? 'negative' : 'positive']++;
+ }
}
}
$map['sign'] = $negative > $positive ? 'negative' : 'positive';
+ foreach (['positive' => 'negative', 'negative' => 'positive'] as $sign => $other) {
+ if ($votes[$sign] >= 2 && $votes[$sign] >= 3 * $votes[$other]) {
+ $map['sign'] = $sign;
+ }
+ }
}
return $map;
}
diff --git a/functions/income_import.php b/functions/income_import.php
new file mode 100644
index 000000000..29134484e
--- /dev/null
+++ b/functions/income_import.php
@@ -0,0 +1,821 @@
+= 2 && lookupUserPermission('module_financial') >= 2;
+}
+
+/** What a deposit can be brought in as. */
+function incomeImportActions() {
+ return [
+ 'payment' => 'Payment on invoices',
+ 'income' => 'Other income',
+ 'transfer' => 'Transfer from an account',
+ ];
+}
+
+/**
+ * The deposits on a statement by a mapping - the lines with money in, each
+ * [n, date, description, match_text, amount (what came in, positive),
+ * reference, problem]. $charges gets how many lines are money out.
+ */
+function incomeImportLines(array $rows, array $map, &$charges = 0) {
+ $charges = 0;
+ $deposits = [];
+ foreach (expenseImportLines($rows, $map) as $line) {
+ if ($line['amount'] !== null && $line['amount'] > 0) {
+ $charges++;
+ continue;
+ }
+ if ($line['amount'] === null && $line['problem'] === '') {
+ continue;
+ }
+ $line['amount'] = $line['amount'] === null ? null : round(-$line['amount'], 2);
+ if ($line['problem'] === 'The amount is zero') {
+ continue;
+ }
+ $line['n'] = count($deposits);
+ $deposits[] = $line;
+ }
+ return $deposits;
+}
+
+/**
+ * Every invoice still owed that the agent may see - id => [invoice_id,
+ * client_id, client_name, ref, scope, due, currency, balance], the oldest
+ * due first.
+ */
+function incomeImportOpenInvoices() {
+ global $mysqli;
+ $invoices = [];
+ $sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_due, invoice_currency_code, invoice_client_id, client_name,
+ invoice_amount - COALESCE((SELECT SUM(payment_amount) FROM payments WHERE payment_invoice_id = invoice_id), 0) AS balance
+ FROM invoices JOIN clients ON client_id = invoice_client_id
+ WHERE invoice_status IN ('Sent', 'Viewed', 'Partial') AND invoice_archived_at IS NULL " . clientScopeSql('invoices.invoice_client_id') . "
+ HAVING balance > 0.004
+ ORDER BY invoice_due ASC, invoice_id ASC");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $invoices[intval($row['invoice_id'])] = [
+ 'invoice_id' => intval($row['invoice_id']),
+ 'client_id' => intval($row['invoice_client_id']),
+ 'client_name' => (string) $row['client_name'],
+ 'prefix' => (string) $row['invoice_prefix'],
+ 'number' => intval($row['invoice_number']),
+ 'ref' => $row['invoice_prefix'] . $row['invoice_number'],
+ 'scope' => (string) $row['invoice_scope'],
+ 'due' => (string) $row['invoice_due'],
+ 'currency' => (string) $row['invoice_currency_code'],
+ 'balance' => round(floatval($row['balance']), 2),
+ ];
+ }
+ return $invoices;
+}
+
+/** The remembered payers - match => [id, action, client_id, category_id, account_id]. */
+function incomeImportRules() {
+ global $mysqli;
+ $rules = [];
+ $sql = mysqli_query($mysqli, "SELECT import_rule_id, import_rule_match, import_rule_action, import_rule_client_id, import_rule_category_id, import_rule_account_id FROM income_import_rules");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $rules[$row['import_rule_match']] = ['id' => intval($row['import_rule_id']), 'action' => (string) $row['import_rule_action'], 'client_id' => intval($row['import_rule_client_id']),
+ 'category_id' => intval($row['import_rule_category_id']), 'account_id' => intval($row['import_rule_account_id'])];
+ }
+ return $rules;
+}
+
+/** How a deposit was paid, from its text - one of the payment methods set up when it says, else $default. */
+function incomeImportMethod($text, $default = '') {
+ $methods = paymentMethods();
+ $text = mb_strtolower((string) $text);
+ $wants = [
+ '/\b(ach|direct dep|direct deposit|ccd|ppd|eft)\b/' => ['ACH', 'Bank Transfer', 'EFT'],
+ '/\b(wire|fedwire|swift)\b/' => ['Wire', 'Wire Transfer', 'Bank Transfer'],
+ '/\b(check|cheque|chk|mobile deposit|remote deposit|rdc|counter deposit)\b/' => ['Check', 'Cheque'],
+ '/\b(zelle|venmo|cash app)\b/' => ['Zelle', 'Bank Transfer'],
+ '/\b(cash)\b/' => ['Cash'],
+ ];
+ foreach ($wants as $pattern => $names) {
+ if (preg_match($pattern, $text)) {
+ foreach ($names as $name) {
+ foreach ($methods as $method) {
+ if (strcasecmp($method, $name) === 0) {
+ return $method;
+ }
+ }
+ }
+ }
+ }
+ return in_array((string) $default, $methods, true) ? (string) $default : '';
+}
+
+/**
+ * The invoice numbers a deposit's text names - after an invoice prefix in
+ * use ("INV-1042", "inv 1042") or the word invoice ("Invoice #1042"). A bare
+ * number is a check number as often as not, so it doesn't count.
+ */
+function incomeImportInvoiceNumbers($text, array $prefixes) {
+ $stems = ['invoices', 'invoice', 'inv'];
+ foreach ($prefixes as $prefix) {
+ $stem = trim(mb_strtolower((string) $prefix), " -#:_/.");
+ if ($stem !== '' && preg_match('/^[\p{L}\d]+$/u', $stem)) {
+ $stems[] = $stem;
+ }
+ }
+ $stems = array_unique($stems);
+ usort($stems, function ($a, $b) { return mb_strlen($b) <=> mb_strlen($a); });
+ $alternation = implode('|', array_map(function ($s) { return preg_quote($s, '/'); }, $stems));
+ $numbers = [];
+ if (preg_match_all('/\b(?:' . $alternation . ')\s*(?:no\.?|number)?\s*[-#:_\/.]?\s*(\d{1,9}(?:\s*(?:,|&|and)\s*\d{1,9})*)\b/iu', (string) $text, $matches)) {
+ foreach ($matches[1] as $list) {
+ foreach (preg_split('/\s*(?:,|&|and)\s*/i', $list) as $number) {
+ if (ctype_digit($number) && intval($number) > 0) {
+ $numbers[intval($number)] = intval($number);
+ }
+ }
+ }
+ }
+ return array_values($numbers);
+}
+
+/**
+ * Which of a client's open invoices (oldest due first) a deposit pays - [ids,
+ * how]: the one owing exactly the amount ('exact'), the fewest that add up
+ * to it ('sum'), the oldest first until it is used up, the last part paid
+ * ('oldest'), or all of them when it is more than they owe ('over').
+ */
+function incomeImportPickInvoices(array $invoices, $amount) {
+ $invoices = array_values($invoices);
+ if (!$invoices || $amount <= 0) {
+ return [[], ''];
+ }
+ $cents = (int) round($amount * 100);
+ foreach ($invoices as $invoice) {
+ if ((int) round($invoice['balance'] * 100) === $cents) {
+ return [[$invoice['invoice_id']], 'exact'];
+ }
+ }
+ // The fewest that add up to it exactly - a check paying several
+ $count = min(count($invoices), 14);
+ $best = null;
+ for ($mask = 1; $mask < (1 << $count); $mask++) {
+ $sum = 0;
+ $ids = [];
+ for ($i = 0; $i < $count; $i++) {
+ if ($mask & (1 << $i)) {
+ $sum += (int) round($invoices[$i]['balance'] * 100);
+ $ids[] = $invoices[$i]['invoice_id'];
+ }
+ }
+ if ($sum === $cents && ($best === null || count($ids) < count($best))) {
+ $best = $ids;
+ }
+ }
+ if ($best) {
+ return [$best, 'sum'];
+ }
+ $total = 0;
+ $ids = [];
+ foreach ($invoices as $invoice) {
+ $ids[] = $invoice['invoice_id'];
+ $total += (int) round($invoice['balance'] * 100);
+ if ($total >= $cents) {
+ return [$ids, 'oldest'];
+ }
+ }
+ return [$ids, 'over'];
+}
+
+/**
+ * The names to look for in a deposit's text - id => ' its words ', the
+ * longest first, from expenseImportWords() (so "Ravenwood Dental Group, LLC"
+ * is " ravenwood dental group ").
+ */
+function incomeImportNameWords(array $names) {
+ $out = [];
+ foreach ($names as $id => $name) {
+ $words = expenseImportWords($name);
+ if ($words && mb_strlen(implode(' ', $words)) >= 4) {
+ $out[$id] = ' ' . implode(' ', $words) . ' ';
+ }
+ }
+ uasort($out, function ($a, $b) { return mb_strlen($b) <=> mb_strlen($a); });
+ return $out;
+}
+
+/** The id of the name that appears in a line's words - whole, or its first words with the last cut short ("RAVENWOOD DENTAL GRP"). 0 for none. */
+function incomeImportNameMatch(array $line_words, array $name_words) {
+ $text = ' ' . implode(' ', $line_words) . ' ';
+ foreach ($name_words as $id => $words) {
+ if (strpos($text, $words) !== false) {
+ return $id;
+ }
+ }
+ foreach ($name_words as $id => $words) {
+ $want = explode(' ', trim($words));
+ if (count($want) < 2) {
+ continue;
+ }
+ for ($at = 0; $at < count($line_words); $at++) {
+ $ok = 0;
+ foreach ($want as $j => $word) {
+ $have = $line_words[$at + $j] ?? null;
+ if ($have === null || !($have === $word || (mb_strlen($have) >= 3 && strpos($word, $have) === 0))) {
+ break;
+ }
+ $ok++;
+ }
+ if ($ok >= 2 && ($ok === count($want) || !isset($line_words[$at + $ok]) || $ok >= 3)) {
+ return $id;
+ }
+ }
+ }
+ return 0;
+}
+
+/** The accounts payment providers record online payments in. */
+function incomeImportProviderAccounts() {
+ global $mysqli;
+ $accounts = [];
+ $sql = mysqli_query($mysqli, "SELECT payment_provider_account, payment_provider_name FROM payment_providers WHERE payment_provider_active = 1 AND payment_provider_account > 0");
+ while ($row = mysqli_fetch_row($sql)) {
+ $accounts[intval($row[0])] = (string) $row[1];
+ }
+ return $accounts;
+}
+
+/** Does a deposit look like a payout of card payments, or a transfer between accounts? 'payout', 'transfer' or ''. */
+function incomeImportKind($text) {
+ $text = mb_strtolower((string) $text);
+ if (preg_match('/\b(stripe|paypal|square ?inc|squareup|gocardless|intuit|qbms|quickbooks payments|authorize ?net|bankcard|merchant (deposit|settlement|services|bankcd)|payout)\b/u', $text)) {
+ return 'payout';
+ }
+ if (preg_match('/\b(transfer|xfer|xfr|trnsfr|tfr)\b|\bfrom (savings|checking|share|sav|chk)\b/u', $text)) {
+ return 'transfer';
+ }
+ return '';
+}
+
+/**
+ * Match each deposit - sets key (the match key), action, client_id,
+ * invoice_ids, how (exact, sum, oldest or over), category_id,
+ * from_account_id, method, matched ('number', 'rule', 'name', 'amount',
+ * 'payout', 'transfer' or '') and match_note to say why.
+ */
+function incomeImportMatch(array $lines, $account_id, $default_method = '') {
+ global $mysqli;
+ $account_id = intval($account_id);
+ $can_pay = incomeImportCanPay();
+ $open = $can_pay ? incomeImportOpenInvoices() : [];
+ $by_client = [];
+ $prefixes = [];
+ foreach ($open as $invoice) {
+ $by_client[$invoice['client_id']][] = $invoice;
+ $prefixes[$invoice['prefix']] = $invoice['prefix'];
+ }
+ $rules = incomeImportRules();
+ uksort($rules, function ($a, $b) { return mb_strlen($b) <=> mb_strlen($a); });
+ $clients = [];
+ $client_names = [];
+ $sql = mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id'));
+ while ($row = mysqli_fetch_row($sql)) {
+ $clients[intval($row[0])] = (string) $row[1];
+ }
+ $client_names = incomeImportNameWords($clients);
+ $accounts = paymentAccounts();
+ $account_names = [];
+ foreach ($accounts as $id => $account) {
+ if ($id === $account_id) {
+ continue;
+ }
+ // Words that tell one of our accounts from another - not "business" or "account"
+ $words = array_values(array_diff(expenseImportWords($account['account_name']), ['business', 'account', 'accounts', 'bank', 'main', 'company', 'our']));
+ if ($words) {
+ $account_names[$id] = $words;
+ }
+ }
+ $providers = incomeImportProviderAccounts();
+ $categories = incomeCategories();
+
+ // Clients whose open invoices together owe one amount - when no other client's owe the same
+ $client_totals = [];
+ foreach ($by_client as $client_id => $invoices) {
+ $cents = 0;
+ foreach ($invoices as $invoice) {
+ $cents += (int) round($invoice['balance'] * 100);
+ }
+ $client_totals[$cents][] = $client_id;
+ }
+ $balances = [];
+ foreach ($open as $invoice) {
+ $balances[(int) round($invoice['balance'] * 100)][] = $invoice['invoice_id'];
+ }
+ $money = function ($amount, $currency = '') {
+ return billingMoney($amount, $currency);
+ };
+
+ foreach ($lines as $i => $line) {
+ $text = trim($line['match_text'] . ' ' . $line['reference']);
+ $key = expenseImportMatchKey($line['match_text']);
+ $line += ['key' => $key, 'action' => 'income', 'client_id' => 0, 'invoice_ids' => [], 'how' => '', 'category_id' => 0, 'from_account_id' => 0, 'matched' => '', 'match_note' => ''];
+ $line['key'] = $key;
+ $line['method'] = incomeImportMethod($text, $default_method);
+ if ($line['problem'] !== '' || $line['amount'] === null) {
+ $lines[$i] = $line;
+ continue;
+ }
+ $amount = $line['amount'];
+ $cents = (int) round($amount * 100);
+ $pay = function ($client_id, $invoices, $matched, $note) use (&$line, $amount) {
+ [$ids, $how] = incomeImportPickInvoices($invoices, $amount);
+ $line['action'] = 'payment';
+ $line['client_id'] = $client_id;
+ $line['invoice_ids'] = $ids;
+ $line['how'] = $how;
+ $line['matched'] = $matched;
+ $line['match_note'] = $note;
+ };
+
+ // 1. An invoice number in it
+ $named = [];
+ foreach (incomeImportInvoiceNumbers($text, array_values($prefixes)) as $number) {
+ foreach ($open as $invoice) {
+ if ($invoice['number'] === $number) {
+ $named[] = $invoice;
+ }
+ }
+ }
+ if ($named) {
+ $client_id = $named[0]['client_id'];
+ $named = array_values(array_filter($named, function ($inv) use ($client_id) { return $inv['client_id'] === $client_id; }));
+ $refs = implode(', ', array_column($named, 'ref'));
+ $line['action'] = 'payment';
+ $line['client_id'] = $client_id;
+ $line['invoice_ids'] = array_column($named, 'invoice_id');
+ $owed = (int) round(array_sum(array_column($named, 'balance')) * 100);
+ $line['how'] = $owed === $cents ? (count($named) > 1 ? 'sum' : 'exact') : ($owed > $cents ? 'oldest' : 'over');
+ $line['matched'] = 'number';
+ $line['match_note'] = "$refs in the text";
+ $lines[$i] = $line;
+ continue;
+ }
+
+ // 2. What this payer was last time
+ $rule = null;
+ if ($key !== '') {
+ foreach ($rules as $match => $candidate) {
+ if ($key === $match || strpos($key, $match . ' ') === 0) {
+ $rule = $candidate;
+ break;
+ }
+ }
+ }
+ $kind = incomeImportKind($text);
+ if ($rule) {
+ $note = 'As last time';
+ if ($rule['action'] === 'transfer' && isset($accounts[$rule['account_id']]) && $rule['account_id'] !== $account_id) {
+ $line['action'] = 'transfer';
+ $line['from_account_id'] = $rule['account_id'];
+ $line['matched'] = 'rule';
+ $line['match_note'] = $note;
+ } elseif ($rule['action'] === 'payment' && isset($clients[$rule['client_id']]) && !empty($by_client[$rule['client_id']])) {
+ $pay($rule['client_id'], $by_client[$rule['client_id']], 'rule', $note);
+ } elseif (in_array($rule['action'], ['payment', 'income'], true) && ($rule['client_id'] === 0 || isset($clients[$rule['client_id']]))) {
+ $line['action'] = 'income';
+ $line['client_id'] = $rule['client_id'];
+ $line['category_id'] = isset($categories[$rule['category_id']]) ? $rule['category_id'] : 0;
+ $line['matched'] = 'rule';
+ $line['match_note'] = $rule['action'] === 'payment' ? 'From them before - nothing of theirs is owed now' : $note;
+ }
+ if ($line['matched'] !== '') {
+ $lines[$i] = $line;
+ continue;
+ }
+ }
+
+ // 3. A payout of card payments, or a transfer from another of our accounts
+ if ($kind === 'payout') {
+ $line['matched'] = 'payout';
+ $line['action'] = 'transfer';
+ if (isset($providers[$account_id])) {
+ $line['recorded'] = true;
+ $line['match_note'] = 'A payout of ' . $providers[$account_id] . ' payments, recorded in this account already';
+ } elseif ($providers) {
+ $line['from_account_id'] = array_key_first($providers);
+ $line['match_note'] = 'A payout from ' . reset($providers);
+ } else {
+ $line['match_note'] = 'Looks like a payout of card payments';
+ }
+ $lines[$i] = $line;
+ continue;
+ }
+ if ($kind === 'transfer') {
+ $line['matched'] = 'transfer';
+ $line['action'] = 'transfer';
+ $line_words = expenseImportWords($text);
+ foreach ($account_names as $id => $words) {
+ if (array_intersect($words, $line_words)) {
+ $line['from_account_id'] = $id;
+ break;
+ }
+ }
+ $line['match_note'] = $line['from_account_id'] ? 'Looks like a transfer from ' . $accounts[$line['from_account_id']]['account_name'] : 'Looks like a transfer';
+ $lines[$i] = $line;
+ continue;
+ }
+
+ // 4. A client's name in it
+ $client_id = incomeImportNameMatch(expenseImportWords($text), $client_names);
+ if ($client_id) {
+ if (!empty($by_client[$client_id])) {
+ $pay($client_id, $by_client[$client_id], 'name', $clients[$client_id] . ' is named in it');
+ } else {
+ $line['client_id'] = $client_id;
+ $line['matched'] = 'name';
+ $line['match_note'] = $clients[$client_id] . ' is named in it - nothing of theirs is owed';
+ }
+ $lines[$i] = $line;
+ continue;
+ }
+
+ // 5. The only invoice owing exactly that, or the one client whose open invoices add up to it
+ if (count($balances[$cents] ?? []) === 1) {
+ $invoice = $open[$balances[$cents][0]];
+ $line['action'] = 'payment';
+ $line['client_id'] = $invoice['client_id'];
+ $line['invoice_ids'] = [$invoice['invoice_id']];
+ $line['how'] = 'exact';
+ $line['matched'] = 'amount';
+ $line['match_note'] = 'The only invoice owing ' . $money($amount, $invoice['currency']);
+ } elseif (count($client_totals[$cents] ?? []) === 1 && count($by_client[$client_totals[$cents][0]]) > 1) {
+ $client_id = $client_totals[$cents][0];
+ $line['action'] = 'payment';
+ $line['client_id'] = $client_id;
+ $line['invoice_ids'] = array_column($by_client[$client_id], 'invoice_id');
+ $line['how'] = 'sum';
+ $line['matched'] = 'amount';
+ $line['match_note'] = 'All ' . $clients[$client_id] . ' owes';
+ } elseif (count($balances[$cents] ?? []) > 1 && count(array_unique(array_map(function ($id) use ($open) { return $open[$id]['client_id']; }, $balances[$cents]))) === 1) {
+ // Several of one client's invoices owe it - the oldest due
+ $invoice = $open[$balances[$cents][0]];
+ $line['action'] = 'payment';
+ $line['client_id'] = $invoice['client_id'];
+ $line['invoice_ids'] = [$invoice['invoice_id']];
+ $line['how'] = 'exact';
+ $line['matched'] = 'amount';
+ $line['match_note'] = 'The oldest of ' . count($balances[$cents]) . ' ' . $clients[$invoice['client_id']] . ' invoices owing ' . $money($amount, $invoice['currency']);
+ } elseif (count($balances[$cents] ?? []) > 1) {
+ $line['match_note'] = count($balances[$cents]) . ' invoices owe ' . $money($amount) . ' - pick the one';
+ }
+ $lines[$i] = $line;
+ }
+ return $lines;
+}
+
+/**
+ * Deposits already in - sets imported ('payment' or 'revenue' with
+ * imported_id, the first thing it came in as) or entered (entered_type and
+ * entered_ids: a payment, other income or transfer entered by hand on the
+ * account for the amount within INCOME_IMPORT_DUPLICATE_DAYS days, the
+ * closest, or a day's payments that add up to it), with entered_label.
+ */
+function incomeImportDuplicates($account_id, array $lines) {
+ global $mysqli;
+ $account_id = intval($account_id);
+ $hashes = array_filter(array_column($lines, 'key_hash'));
+ $imported = [];
+ if ($hashes) {
+ $in = "('" . implode("','", array_map('escapeSql', $hashes)) . "')";
+ $sql = mysqli_query($mysqli, "SELECT 'payment', payment_id, payment_import_key FROM payments WHERE payment_import_key IN $in
+ UNION ALL SELECT 'revenue', revenue_id, revenue_import_key FROM revenues WHERE revenue_import_key IN $in");
+ while ($row = mysqli_fetch_row($sql)) {
+ if (!isset($imported[$row[2]])) {
+ $imported[$row[2]] = [$row[0], intval($row[1])];
+ }
+ }
+ }
+
+ // What was entered by hand on the account around the statement's dates
+ $dates = array_filter(array_column($lines, 'date'));
+ $singles = [];
+ $days = [];
+ if ($dates) {
+ $from = date('Y-m-d', strtotime(min($dates) . ' -' . INCOME_IMPORT_DUPLICATE_DAYS . ' days'));
+ $to = date('Y-m-d', strtotime(max($dates) . ' +' . INCOME_IMPORT_DUPLICATE_DAYS . ' days'));
+ $sql = mysqli_query($mysqli, "SELECT payment_id, payment_date, payment_amount, CONCAT(COALESCE(invoice_prefix, ''), COALESCE(invoice_number, '')) AS what FROM payments
+ LEFT JOIN invoices ON invoice_id = payment_invoice_id
+ WHERE payment_account_id = $account_id AND payment_import_key IS NULL AND payment_archived_at IS NULL AND payment_date BETWEEN '$from' AND '$to'
+ ORDER BY payment_date, payment_id");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $singles[] = ['type' => 'payment', 'ids' => [intval($row['payment_id'])], 'date' => $row['payment_date'], 'cents' => (int) round($row['payment_amount'] * 100),
+ 'label' => 'Payment on ' . ($row['what'] !== '' ? $row['what'] : 'an invoice') . ' on ' . $row['payment_date']];
+ $days[$row['payment_date']][] = ['id' => intval($row['payment_id']), 'cents' => (int) round($row['payment_amount'] * 100), 'what' => $row['what']];
+ }
+ $sql = mysqli_query($mysqli, "SELECT revenue_id, revenue_date, revenue_amount, revenue_description, category_name, transfer_id FROM revenues
+ LEFT JOIN categories ON category_id = revenue_category_id
+ LEFT JOIN transfers ON transfer_revenue_id = revenue_id
+ WHERE revenue_account_id = $account_id AND revenue_import_key IS NULL AND revenue_archived_at IS NULL AND revenue_date BETWEEN '$from' AND '$to'
+ ORDER BY revenue_date, revenue_id");
+ while ($row = mysqli_fetch_assoc($sql)) {
+ $what = $row['transfer_id'] !== null ? 'A transfer in' : (trim(strtok((string) $row['revenue_description'], "\n")) ?: ($row['category_name'] ?: 'Other income'));
+ $singles[] = ['type' => 'revenue', 'ids' => [intval($row['revenue_id'])], 'date' => $row['revenue_date'], 'cents' => (int) round($row['revenue_amount'] * 100),
+ 'label' => $what . ' on ' . $row['revenue_date'], 'transfer' => $row['transfer_id'] !== null];
+ }
+ }
+ // A day's payments together - one check for several invoices
+ $groups = [];
+ foreach ($days as $date => $payments) {
+ if (count($payments) > 1) {
+ $groups[] = ['type' => 'payment', 'ids' => array_column($payments, 'id'), 'date' => $date, 'cents' => array_sum(array_column($payments, 'cents')),
+ 'label' => 'Payments on ' . implode(', ', array_filter(array_column($payments, 'what'))) . ' on ' . $date];
+ }
+ }
+
+ $used = [];
+ foreach ($lines as $i => $line) {
+ $lines[$i]['imported'] = $imported[$line['key_hash']][0] ?? '';
+ $lines[$i]['imported_id'] = $imported[$line['key_hash']][1] ?? 0;
+ $lines[$i]['entered_type'] = '';
+ $lines[$i]['entered_ids'] = [];
+ $lines[$i]['entered_label'] = '';
+ if ($lines[$i]['imported'] !== '' || $line['problem'] !== '') {
+ continue;
+ }
+ $cents = (int) round($line['amount'] * 100);
+ foreach ([$singles, $groups] as $pool) {
+ $best = null;
+ foreach ($pool as $j => $candidate) {
+ if ($candidate['cents'] !== $cents || array_intersect_key(array_flip(array_map(function ($id) use ($candidate) { return $candidate['type'] . $id; }, $candidate['ids'])), $used)) {
+ continue;
+ }
+ $gap = abs((strtotime($candidate['date']) - strtotime($line['date'])) / 86400);
+ if ($gap <= INCOME_IMPORT_DUPLICATE_DAYS && ($best === null || $gap < $best[1])) {
+ $best = [$j, $gap];
+ }
+ }
+ if ($best) {
+ $candidate = $pool[$best[0]];
+ foreach ($candidate['ids'] as $id) {
+ $used[$candidate['type'] . $id] = true;
+ }
+ $lines[$i]['entered_type'] = $candidate['type'];
+ $lines[$i]['entered_ids'] = $candidate['ids'];
+ $lines[$i]['entered_label'] = $candidate['label'];
+ break;
+ }
+ }
+ }
+ return $lines;
+}
+
+/**
+ * Everything about a statement's deposits for the review - read, matched,
+ * keyed and checked for what is in already, each with a state: new,
+ * imported, entered, recorded (a payout into the payment provider's own
+ * account) or problem. $charges gets how many lines are money out.
+ */
+function incomeImportReview(array $import, &$charges = 0) {
+ $lines = incomeImportLines($import['rows'], $import['map'], $charges);
+ $lines = incomeImportMatch($lines, $import['account_id'], (string) ($import['method'] ?? ''));
+ $lines = expenseImportKeys($import['account_id'], $lines);
+ $lines = incomeImportDuplicates($import['account_id'], $lines);
+ foreach ($lines as $i => $line) {
+ $lines[$i]['state'] = $line['problem'] !== '' ? 'problem' : ($line['imported'] !== '' ? 'imported' : ($line['entered_type'] !== '' ? 'entered' : (!empty($line['recorded']) ? 'recorded' : 'new')));
+ }
+ return $lines;
+}
+
+/** Bring a transfer in from another of our accounts - the money out of one, the money into the other, and the transfer joining them. The revenue's id. */
+function incomeImportTransfer($from_account_id, $to_account_id, $date, $amount, $currency, $method, $notes, $key) {
+ global $mysqli, $session_user_id;
+ $amount = number_format($amount, 2, '.', '');
+ $currency = escapeSql($currency);
+ mysqli_query($mysqli, "INSERT INTO expenses SET expense_date = '$date', expense_amount = $amount, expense_currency_code = '$currency', expense_vendor_id = 0,
+ expense_category_id = 0, expense_account_id = " . intval($from_account_id) . ", expense_created_by = " . intval($session_user_id));
+ $expense_id = mysqli_insert_id($mysqli);
+ mysqli_query($mysqli, "INSERT INTO revenues SET revenue_date = '$date', revenue_amount = $amount, revenue_currency_code = '$currency', revenue_category_id = 0,
+ revenue_account_id = " . intval($to_account_id) . ", revenue_created_by = " . intval($session_user_id) . ", revenue_import_key = '" . escapeSql($key) . "'");
+ $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 = '" . escapeSql($method) . "',
+ transfer_notes = '" . escapeSql(mb_substr($notes, 0, 1000)) . "'");
+ return $revenue_id;
+}
+
+/**
+ * Bring in the ticked deposits. $picks is line n => [take, action, client,
+ * invoices (ids), category, account]; $opts receipts (email each client
+ * their receipt). Every ticked line is checked before any comes in: a
+ * payment needs Sales access, the client's open invoices and no more than
+ * they owe (the oldest due paid first, the last part paid); other income a
+ * category; a transfer another of our accounts. Each payer is remembered,
+ * and a deposit left out that looked entered already gives its key to what
+ * was entered. Returns [payments, invoices_paid, invoices_part, paid,
+ * income, income_total, transfers, transfer_total, receipts, linked,
+ * skipped, from, to] or null with $error.
+ */
+function incomeImportSave(array $import, array $picks, array $opts, &$error = '') {
+ global $mysqli, $session_user_id, $session_company_currency, $session_name;
+ $error = '';
+ $account_id = intval($import['account_id']);
+ $accounts = paymentAccounts();
+ if (!isset($accounts[$account_id])) {
+ $error = 'The account the statement is for no longer exists';
+ return null;
+ }
+ $currency = (string) ($accounts[$account_id]['account_currency_code'] ?: $session_company_currency);
+ $lines = incomeImportReview($import);
+ $can_pay = incomeImportCanPay();
+ $open = $can_pay ? incomeImportOpenInvoices() : [];
+ $categories = incomeCategories();
+ $clients = [];
+ $sql = mysqli_query($mysqli, "SELECT client_id FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id'));
+ while ($row = mysqli_fetch_row($sql)) {
+ $clients[intval($row[0])] = true;
+ }
+ $who = escapeSql(stripslashes((string) $session_name));
+
+ // Check every ticked deposit first, working out what each payment leaves owing
+ $bring = [];
+ $balances = array_map(function ($invoice) { return (int) round($invoice['balance'] * 100); }, $open);
+ foreach ($lines as $line) {
+ $pick = $picks[$line['n']] ?? null;
+ if (!$pick || empty($pick['take']) || !in_array($line['state'], ['new', 'entered', 'recorded'], true)) {
+ continue;
+ }
+ $what = date('M j', strtotime($line['date'])) . ' ' . billingMoney($line['amount'], $currency);
+ $action = (string) ($pick['action'] ?? '');
+ $client = intval($pick['client'] ?? 0);
+ if ($client && !isset($clients[$client])) {
+ $error = "The client picked for $what isn't one you can open";
+ return null;
+ }
+ $item = ['line' => $line, 'action' => $action, 'client' => $client, 'category' => 0, 'account' => 0, 'payments' => []];
+ if ($action === 'payment') {
+ if (!$can_pay) {
+ $error = 'Recording payments on invoices takes write access to Sales - ' . $what . ' can come in as other income';
+ return null;
+ }
+ $ids = array_values(array_unique(array_filter(array_map('intval', (array) ($pick['invoices'] ?? [])))));
+ if (!$client || !$ids) {
+ $error = "Pick the client and the invoices $what pays";
+ return null;
+ }
+ $invoices = [];
+ foreach ($ids as $id) {
+ if (!isset($open[$id]) || $open[$id]['client_id'] !== $client) {
+ $error = "An invoice picked for $what isn't one of the client's still owed";
+ return null;
+ }
+ $invoices[] = $open[$id];
+ }
+ usort($invoices, function ($a, $b) { return [$a['due'], $a['invoice_id']] <=> [$b['due'], $b['invoice_id']]; });
+ $left = (int) round($line['amount'] * 100);
+ foreach ($invoices as $invoice) {
+ $owed = $balances[$invoice['invoice_id']];
+ if ($left <= 0 || $owed <= 0) {
+ continue;
+ }
+ $take = min($left, $owed);
+ $item['payments'][] = ['invoice' => $invoice, 'cents' => $take];
+ $balances[$invoice['invoice_id']] -= $take;
+ $left -= $take;
+ }
+ if ($left > 0) {
+ $error = "$what is " . billingMoney($left / 100, $currency) . ' more than the invoices picked owe - pick another, or bring it in as other income';
+ return null;
+ }
+ } elseif ($action === 'income') {
+ $category = intval($pick['category'] ?? 0);
+ if (!isset($categories[$category])) {
+ $error = "Pick the category for $what";
+ return null;
+ }
+ $item['category'] = $category;
+ } elseif ($action === 'transfer') {
+ $from = intval($pick['account'] ?? 0);
+ if (!isset($accounts[$from]) || $from === $account_id) {
+ $error = "Pick the account $what came from";
+ return null;
+ }
+ $item['account'] = $from;
+ } else {
+ $error = "Pick what $what is";
+ return null;
+ }
+ $bring[] = $item;
+ }
+
+ $statuses = [];
+ $result = ['payments' => 0, 'invoices_paid' => 0, 'invoices_part' => 0, 'paid' => 0.0, 'income' => 0, 'income_total' => 0.0, 'transfers' => 0, 'transfer_total' => 0.0,
+ 'receipts' => 0, 'linked' => 0, 'from' => null, 'to' => null, 'skipped' => count(array_filter($lines, function ($l) { return $l['state'] === 'imported'; }))];
+ foreach ($bring as $item) {
+ $line = $item['line'];
+ $date = $line['date'];
+ $key = escapeSql($line['key_hash']);
+ $method = (string) $line['method'];
+ // The bank's text says who paid when it is more than "DEPOSIT" - it is the payment's reference when the statement has none
+ $words = array_diff(expenseImportWords($line['description']), ['deposit', 'deposits', 'mobile', 'remote', 'branch', 'counter', 'teller', 'incoming', 'item', 'items']);
+ $reference = mb_substr($line['reference'] !== '' ? $line['reference'] : ($words ? $line['description'] : ''), 0, 200);
+ if ($item['action'] === 'payment') {
+ foreach ($item['payments'] as $part) {
+ $invoice = $part['invoice'];
+ $invoice_id = $invoice['invoice_id'];
+ $amount = number_format($part['cents'] / 100, 2, '.', '');
+ mysqli_query($mysqli, "INSERT INTO payments SET payment_date = '$date', payment_amount = $amount, payment_currency_code = '" . escapeSql($invoice['currency'] ?: $currency) . "',
+ payment_account_id = $account_id, payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ", payment_reference = '" . escapeSql($reference) . "',
+ payment_invoice_id = $invoice_id, payment_import_key = '$key'");
+ $status = updateInvoiceStatusFromPayments($invoice_id);
+ mysqli_query($mysqli, "INSERT INTO history SET history_status = '" . escapeSql((string) $status) . "', history_description = 'Payment added from a bank statement', history_invoice_id = $invoice_id");
+ logAudit("Invoice", "Payment", "$who added a payment of " . escapeSql(billingMoney($amount, $invoice['currency'])) . " to invoice " . escapeSql($invoice['ref']) . " from a bank statement", $invoice['client_id'], $invoice_id);
+ if (!empty($opts['receipts'])) {
+ $sent = billingPaymentSend($invoice_id, floatval($amount), ['date' => $date, 'method' => $method, 'reference' => $reference]);
+ if ($sent) {
+ $result['receipts']++;
+ logAudit("Invoice", "Payment", "Payment receipt for invoice " . escapeSql($invoice['ref']) . " queued to " . escapeSql(implode(', ', $sent)), $invoice['client_id'], $invoice_id);
+ }
+ }
+ triggerCustomAction('invoice_pay', $invoice_id);
+ $result['payments']++;
+ $statuses[$invoice_id] = $status;
+ }
+ $result['paid'] += $line['amount'];
+ } elseif ($item['action'] === 'income') {
+ mysqli_query($mysqli, "INSERT INTO revenues SET revenue_date = '$date', revenue_amount = " . number_format($line['amount'], 2, '.', '') . ", revenue_currency_code = '" . escapeSql($currency) . "',
+ revenue_account_id = $account_id, revenue_category_id = {$item['category']}, revenue_client_id = {$item['client']},
+ revenue_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ", revenue_reference = '" . escapeSql(mb_substr($line['reference'], 0, 200)) . "',
+ revenue_description = '" . escapeSql($line['description']) . "', revenue_created_by = " . intval($session_user_id) . ", revenue_import_key = '$key'");
+ $revenue_id = mysqli_insert_id($mysqli);
+ logAudit("Revenue", "Create", "$who added other income " . escapeSql(mb_substr($line['description'], 0, 80) . ' - ' . billingMoney($line['amount'], $currency)) . " from a bank statement", $item['client'], $revenue_id);
+ $result['income']++;
+ $result['income_total'] += $line['amount'];
+ } else {
+ incomeImportTransfer($item['account'], $account_id, $date, $line['amount'], $currency, $method !== '' ? $method : 'Bank Transfer', $line['description'], $line['key_hash']);
+ logAudit("Account Transfer", "Create", "$who brought in a transfer of " . escapeSql(billingMoney($line['amount'], $currency)) . " from " . escapeSql($accounts[$item['account']]['account_name'])
+ . " to " . escapeSql($accounts[$account_id]['account_name']) . " from a bank statement");
+ $result['transfers']++;
+ $result['transfer_total'] += $line['amount'];
+ }
+ $result['from'] = $result['from'] === null || $date < $result['from'] ? $date : $result['from'];
+ $result['to'] = $result['to'] === null || $date > $result['to'] ? $date : $result['to'];
+ if ($line['key'] !== '') {
+ mysqli_query($mysqli, "INSERT INTO income_import_rules SET import_rule_match = '" . escapeSql($line['key']) . "', import_rule_action = '{$item['action']}',
+ import_rule_client_id = {$item['client']}, import_rule_category_id = {$item['category']}, import_rule_account_id = {$item['account']}, import_rule_used_count = 1
+ ON DUPLICATE KEY UPDATE import_rule_action = VALUES(import_rule_action), import_rule_client_id = VALUES(import_rule_client_id),
+ import_rule_category_id = VALUES(import_rule_category_id), import_rule_account_id = VALUES(import_rule_account_id), import_rule_used_count = import_rule_used_count + 1");
+ }
+ }
+
+ // Deposits left out that were entered by hand already - those take their keys
+ foreach ($lines as $line) {
+ $pick = $picks[$line['n']] ?? null;
+ if ($line['state'] === 'entered' && (!$pick || empty($pick['take']))) {
+ $table = $line['entered_type'] === 'payment' ? 'payments' : 'revenues';
+ $column = $line['entered_type'] === 'payment' ? 'payment' : 'revenue';
+ mysqli_query($mysqli, "UPDATE $table SET {$column}_import_key = '" . escapeSql($line['key_hash']) . "' WHERE {$column}_id IN (" . implode(',', array_map('intval', $line['entered_ids'])) . ") AND {$column}_import_key IS NULL");
+ $result['linked'] += mysqli_affected_rows($mysqli) ? 1 : 0;
+ }
+ }
+ // Each invoice once, as it was left
+ $result['invoices_paid'] = count(array_filter($statuses, function ($status) { return $status === 'Paid'; }));
+ $result['invoices_part'] = count($statuses) - $result['invoices_paid'];
+ foreach (['paid', 'income_total', 'transfer_total'] as $total) {
+ $result[$total] = round($result[$total], 2);
+ }
+ return $result;
+}
diff --git a/js/income_import.js b/js/income_import.js
new file mode 100644
index 000000000..216293604
--- /dev/null
+++ b/js/income_import.js
@@ -0,0 +1,379 @@
+/*
+ * Import Deposits' review (agent/income_import.php?step=review).
+ *
+ * Each deposit starts as it was matched: a payment on a client's invoices,
+ * other income, or a transfer from another account - the details for what
+ * it is show beside it. A payment lists the client's invoices still owed;
+ * picking the client ticks the one owing the amount, the ones that add up
+ * to it, or the oldest first, and the line says what it pays off - in full,
+ * part paid, or how much more than they owe. The deposits are applied in
+ * order, so two deposits on one invoice don't pay it twice. A client or
+ * category picked for one deposit fills in the same payer's others not
+ * touched yet. Deposits already in are hidden until asked for. On Import
+ * every line's choices go as one JSON field.
+ *
+ * itflowIncomeImport({ currency: 'USD', locale: 'en-US', invoices: { client_id: [{ id, ref, balance, due, scope, currency }] } });
+ */
+function itflowIncomeImport(options) {
+ var opts = options || {};
+ var form = document.getElementById('incomeImportReview');
+ if (!form || form.dataset.wired) {
+ return;
+ }
+ form.dataset.wired = '1';
+ var rows = Array.prototype.slice.call(form.querySelectorAll('[data-import-row]'));
+ var all = form.querySelector('[data-import-all]');
+ var showAll = form.querySelector('[data-import-show-all]');
+ var summary = form.querySelector('[data-import-summary]');
+ var submit = form.querySelector('[data-import-submit]');
+ var submitLabel = form.querySelector('[data-import-submit-label]');
+ var picks = form.querySelector('[data-import-picks]');
+ var bulkCategory = form.querySelector('[data-income-bulk-category]');
+ var invoices = opts.invoices || {};
+ var byId = {};
+ Object.keys(invoices).forEach(function (client) {
+ invoices[client].forEach(function (invoice) {
+ byId[invoice.id] = invoice;
+ });
+ });
+
+ function money(amount, currency) {
+ try {
+ return new Intl.NumberFormat(opts.locale || undefined, { style: 'currency', currency: currency || opts.currency || 'USD' }).format(amount);
+ } catch (e) {
+ return amount.toFixed(2);
+ }
+ }
+
+ function cents(value) {
+ return Math.round(Number(value) * 100);
+ }
+
+ function part(row, name) {
+ return row.querySelector('[data-income-' + name + ']');
+ }
+
+ function take(row) {
+ return row.querySelector('[data-import-take]');
+ }
+
+ function action(row) {
+ var select = part(row, 'action');
+ return select ? select.value : '';
+ }
+
+ // The invoices ticked on a line, the oldest due first
+ function picked(row) {
+ var box = part(row, 'invoices');
+ if (!box) {
+ return [];
+ }
+ return Array.prototype.slice.call(box.querySelectorAll('input:checked')).map(function (input) {
+ return byId[input.value];
+ }).filter(Boolean).sort(function (a, b) {
+ return a.due === b.due ? a.id - b.id : (a.due < b.due ? -1 : 1);
+ });
+ }
+
+ // Which of a client's invoices a deposit pays: the one owing it, the fewest adding up to it, or the oldest first
+ function suggest(list, amount) {
+ var want = cents(amount);
+ var i;
+ for (i = 0; i < list.length; i++) {
+ if (cents(list[i].balance) === want) {
+ return [list[i].id];
+ }
+ }
+ var count = Math.min(list.length, 14);
+ var best = null;
+ for (var mask = 1; mask < (1 << count); mask++) {
+ var sum = 0;
+ var ids = [];
+ for (i = 0; i < count; i++) {
+ if (mask & (1 << i)) {
+ sum += cents(list[i].balance);
+ ids.push(list[i].id);
+ }
+ }
+ if (sum === want && (best === null || ids.length < best.length)) {
+ best = ids;
+ }
+ }
+ if (best) {
+ return best;
+ }
+ var total = 0;
+ var oldest = [];
+ for (i = 0; i < list.length; i++) {
+ oldest.push(list[i].id);
+ total += cents(list[i].balance);
+ if (total >= want) {
+ break;
+ }
+ }
+ return oldest;
+ }
+
+ // The client's invoices as ticks, with those given ticked
+ function drawInvoices(row, ticked) {
+ var box = part(row, 'invoices');
+ var client = part(row, 'payer').value;
+ var list = invoices[client] || [];
+ var n = row.getAttribute('data-n');
+ box.innerHTML = '';
+ list.forEach(function (invoice) {
+ var wrap = document.createElement('div');
+ wrap.className = 'form-check small mb-0';
+ var input = document.createElement('input');
+ input.type = 'checkbox';
+ input.className = 'form-check-input';
+ input.value = invoice.id;
+ input.id = 'incomeImport' + n + 'Invoice' + invoice.id;
+ input.checked = ticked.indexOf(invoice.id) !== -1;
+ var label = document.createElement('label');
+ label.className = 'form-check-label text-truncate d-block';
+ label.htmlFor = input.id;
+ label.title = invoice.scope || '';
+ label.textContent = invoice.ref + ' · owes ' + money(invoice.balance, invoice.currency) + ' · due ' + invoice.due;
+ wrap.appendChild(input);
+ wrap.appendChild(label);
+ box.appendChild(wrap);
+ });
+ box.hidden = list.length === 0;
+ }
+
+ // One line: the details for what it is, what is required when it is ticked
+ function tidy(row) {
+ var kind = action(row);
+ if (!kind) {
+ return;
+ }
+ var on = take(row).checked && !take(row).disabled;
+ row.querySelectorAll('[data-income-for]').forEach(function (block) {
+ block.hidden = block.getAttribute('data-income-for') !== kind;
+ });
+ part(row, 'payer').required = on && kind === 'payment';
+ part(row, 'category').required = on && kind === 'income';
+ part(row, 'account').required = on && kind === 'transfer';
+ row.classList.toggle('itflow-unbilled-off', !on);
+ }
+
+ function update() {
+ var count = 0;
+ var total = 0;
+ var kinds = { payment: 0, income: 0, transfer: 0 };
+ var left = {};
+ Object.keys(byId).forEach(function (id) {
+ left[id] = cents(byId[id].balance);
+ });
+ rows.forEach(function (row) {
+ tidy(row);
+ var on = take(row).checked && !take(row).disabled;
+ if (on) {
+ count++;
+ total += Number(row.getAttribute('data-amount'));
+ if (kinds[action(row)] !== undefined) {
+ kinds[action(row)]++;
+ }
+ }
+ if (action(row) !== 'payment') {
+ return;
+ }
+ // What this deposit pays off, after the deposits above it
+ var applies = part(row, 'applies');
+ var remaining = cents(row.getAttribute('data-amount'));
+ var parts = [];
+ picked(row).forEach(function (invoice) {
+ if (remaining <= 0 || left[invoice.id] <= 0) {
+ return;
+ }
+ var paying = Math.min(remaining, left[invoice.id]);
+ parts.push(paying === left[invoice.id] ? invoice.ref + ' in full' : invoice.ref + ' ' + money(paying / 100, invoice.currency) + ' of ' + money(left[invoice.id] / 100, invoice.currency));
+ if (on) {
+ left[invoice.id] -= paying;
+ }
+ remaining -= paying;
+ });
+ row.dataset.over = remaining > 0 ? '1' : '';
+ applies.className = 'small mt-1 ' + (remaining > 0 ? 'text-danger-emphasis' : 'text-body-secondary');
+ if (!part(row, 'payer').value) {
+ applies.textContent = '';
+ } else if (!parts.length && !picked(row).length) {
+ applies.textContent = (invoices[part(row, 'payer').value] || []).length ? 'Tick the invoices it pays' : 'Nothing of theirs is owed - bring it in as other income';
+ } else {
+ applies.textContent = (parts.length ? 'Pays ' + parts.join(', ') : '') + (remaining > 0 ? (parts.length ? ' - ' : '') + money(remaining / 100) + ' more than they owe' : '');
+ }
+ });
+ var said = [];
+ if (kinds.payment) {
+ said.push(kinds.payment + ' payment' + (kinds.payment === 1 ? '' : 's'));
+ }
+ if (kinds.income) {
+ said.push(kinds.income + ' other income');
+ }
+ if (kinds.transfer) {
+ said.push(kinds.transfer + ' transfer' + (kinds.transfer === 1 ? '' : 's'));
+ }
+ summary.textContent = count ? count + ' deposit' + (count === 1 ? '' : 's') + ' · ' + money(Math.round(total * 100) / 100) + ' - ' + said.join(', ') : 'Tick the deposits to import';
+ submitLabel.textContent = count ? 'Import ' + count : 'Import';
+ submit.disabled = count === 0;
+ if (all) {
+ var shown = rows.filter(function (row) { return !row.hidden && !take(row).disabled; });
+ var on = shown.filter(function (row) { return take(row).checked; }).length;
+ all.checked = on > 0 && on === shown.length;
+ all.indeterminate = on > 0 && on < shown.length;
+ }
+ }
+
+ // Start each pick where it was matched
+ rows.forEach(function (row) {
+ ['action', 'payer', 'category', 'client', 'account'].forEach(function (name) {
+ var select = part(row, name);
+ if (select && select.getAttribute('data-value') !== null) {
+ var value = select.getAttribute('data-value');
+ if (value !== '' && select.querySelector('option[value="' + CSS.escape(value) + '"]:not([disabled])')) {
+ select.value = value;
+ }
+ }
+ });
+ if (part(row, 'invoices')) {
+ var given = (part(row, 'invoices').getAttribute('data-value') || '').split(',').filter(Boolean).map(Number);
+ drawInvoices(row, given);
+ }
+ if (row.hasAttribute('data-import-extra')) {
+ row.hidden = true;
+ }
+ });
+
+ // The same payer's other deposits not touched yet take what was picked for this one
+ function follow(row, name, value) {
+ var key = row.getAttribute('data-key');
+ if (!key) {
+ return;
+ }
+ rows.forEach(function (other) {
+ if (other === row || other.getAttribute('data-key') !== key || other.dataset.touched || !part(other, name) || part(other, name).value !== '' && part(other, name).value !== '0') {
+ return;
+ }
+ if (name === 'payer' && action(other) !== 'payment') {
+ return;
+ }
+ part(other, name).value = value;
+ if (name === 'payer') {
+ drawInvoices(other, suggest(invoices[value] || [], other.getAttribute('data-amount')));
+ }
+ });
+ }
+
+ form.addEventListener('change', function (e) {
+ var row = e.target.closest('[data-import-row]');
+ if (row && e.target.matches('[data-income-payer]')) {
+ row.dataset.touched = '1';
+ drawInvoices(row, suggest(invoices[e.target.value] || [], row.getAttribute('data-amount')));
+ follow(row, 'payer', e.target.value);
+ } else if (row && e.target.matches('[data-income-category]')) {
+ row.dataset.touched = '1';
+ follow(row, 'category', e.target.value);
+ } else if (row && e.target.matches('[data-income-action], [data-income-client], [data-income-account], [data-income-invoices] input')) {
+ row.dataset.touched = '1';
+ if (e.target.matches('[data-income-action]') && e.target.value !== 'payment' && part(row, 'invoices')) {
+ part(row, 'invoices').querySelectorAll('input').forEach(function (input) { input.checked = false; });
+ }
+ if (e.target.matches('[data-income-action]') && e.target.value === 'payment' && part(row, 'payer').value && !picked(row).length) {
+ drawInvoices(row, suggest(invoices[part(row, 'payer').value] || [], row.getAttribute('data-amount')));
+ }
+ }
+ if (e.target === bulkCategory) {
+ if (e.target.value !== '') {
+ rows.forEach(function (r) {
+ if (take(r).checked && action(r) === 'income') {
+ part(r, 'category').value = e.target.value;
+ }
+ });
+ }
+ e.target.value = '';
+ }
+ if (row && !e.target.matches('[data-import-take]') && !take(row).disabled && !take(row).checked && e.isTrusted) {
+ take(row).checked = true;
+ }
+ update();
+ });
+
+ if (all) {
+ all.addEventListener('change', function () {
+ rows.forEach(function (row) {
+ if (!row.hidden && !take(row).disabled) {
+ take(row).checked = all.checked;
+ }
+ });
+ update();
+ });
+ }
+ if (showAll) {
+ showAll.addEventListener('change', function () {
+ rows.forEach(function (row) {
+ if (row.hasAttribute('data-import-extra')) {
+ row.hidden = !showAll.checked;
+ if (row.hidden) {
+ take(row).checked = false;
+ }
+ }
+ });
+ update();
+ });
+ }
+
+ // Clicking a line (not its picks) ticks it
+ rows.forEach(function (row) {
+ row.addEventListener('click', function (e) {
+ if (e.target.closest('a, input, button, select, label, textarea, [data-income-invoices]')) {
+ return;
+ }
+ if (!take(row).disabled) {
+ take(row).checked = !take(row).checked;
+ update();
+ }
+ });
+ });
+
+ form.addEventListener('submit', function (e) {
+ if (!form.reportValidity()) {
+ e.preventDefault();
+ return;
+ }
+ // A payment needs its invoices, and no more than they owe
+ var wrong = rows.filter(function (row) {
+ return take(row).checked && !take(row).disabled && action(row) === 'payment' && (!picked(row).length || row.dataset.over);
+ });
+ rows.forEach(function (row) {
+ var box = part(row, 'invoices');
+ if (box) {
+ box.classList.toggle('is-invalid', wrong.indexOf(row) !== -1);
+ }
+ });
+ if (wrong.length) {
+ e.preventDefault();
+ wrong[0].scrollIntoView({ block: 'center' });
+ var applies = part(wrong[0], 'applies');
+ if (!picked(wrong[0]).length) {
+ applies.className = 'small mt-1 text-danger-emphasis';
+ applies.textContent = 'Tick the invoices it pays';
+ }
+ return;
+ }
+ var list = rows.map(function (row) {
+ return {
+ n: Number(row.getAttribute('data-n')),
+ take: take(row).checked && !take(row).disabled,
+ action: action(row),
+ client: action(row) === 'payment' ? (part(row, 'payer') ? part(row, 'payer').value : '') : (part(row, 'client') ? part(row, 'client').value : '0'),
+ invoices: action(row) === 'payment' ? picked(row).map(function (invoice) { return invoice.id; }) : [],
+ category: part(row, 'category') ? part(row, 'category').value : '',
+ account: part(row, 'account') ? part(row, 'account').value : ''
+ };
+ });
+ picks.value = JSON.stringify(list);
+ });
+
+ update();
+}