mirror of
https://github.com/itflow-org/itflow
synced 2026-11-30 08:09:00 +00:00
Income Import Deposits: bring the money in on a bank statement in as payments on invoices, other income or transfers from the Income list's menu, reading the same CSV as the expense statement import with the columns kept on the account for both sides and a link from each side's review to the other without uploading again; each deposit is matched by an invoice number in its text or reference, the payer remembered from last time, a client's name in it, the only invoice or the oldest of one client's invoices owing the amount or everything one client owes together, a payment provider payout or a transfer from another account, and anything else as other income for a category and client; payments pay the client's oldest invoices first with one deposit paying several and a short one leaving the last part paid, picking a client ticks the invoices it pays and each line says what it pays off, two deposits on one invoice don't pay it twice and more than they owe blocks the import; deposits imported before are locked, ones matching a payment, other income, transfer or a day's payments entered by hand within 4 days are left out and linked when left out, and a payout into the payment provider's own account counts as recorded; every ticked deposit is checked before any is saved, invoices get their status and history, receipts can be emailed, the payment method is read from the text, and payments and other income say they came from a bank statement on their quick look; payments need write Sales access and client scope applies; remembered payers window with forget; the statement columns step moved to a shared include and the sign guess now reads deposit and charge words on the lines; new functions/income_import.php, agent/income_import.php, js/income_import.js and agent/post/income_import.php; database 3.0.6 adds payment_import_key, revenue_import_key and the income_import_rules table; CHANGELOG updated
This commit is contained in:
31
CHANGELOG.md
31
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.
|
||||
|
||||
36
admin/database_updates/3.0.6.php
Normal file
36
admin/database_updates/3.0.6.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - Database update to version 3.0.6 (from 3.0.5)
|
||||
* Included by admin/database_updates.php - do not access directly
|
||||
*/
|
||||
|
||||
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
|
||||
|
||||
// Deposits brought in from a bank statement (functions/income_import.php)
|
||||
// keep the key of the line they came from, so the same statement can't
|
||||
// bring them in twice - as payments on invoices, or as other income and
|
||||
// the money coming in from a transfer
|
||||
mysqli_query($mysqli, "ALTER TABLE `payments`
|
||||
ADD COLUMN `payment_import_key` varchar(64) DEFAULT NULL AFTER `payment_invoice_id`,
|
||||
ADD KEY `payment_import_key` (`payment_import_key`)");
|
||||
mysqli_query($mysqli, "ALTER TABLE `revenues`
|
||||
ADD COLUMN `revenue_import_key` varchar(64) DEFAULT NULL AFTER `revenue_created_by`,
|
||||
ADD KEY `revenue_import_key` (`revenue_import_key`)");
|
||||
|
||||
// Who a deposit is from - what was picked for a payer last time (a
|
||||
// payment from a client, other income in a category, or a transfer from
|
||||
// one of our accounts), matched on the start of its cleaned-up text
|
||||
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `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");
|
||||
@@ -16,7 +16,9 @@
|
||||
* merchant. Import brings in the ticked ones.
|
||||
*
|
||||
* functions/expense_import.php reads, matches and saves; the handlers are
|
||||
* in agent/post/expense_import.php.
|
||||
* in agent/post/expense_import.php. The columns step is
|
||||
* agent/includes/statement_columns.php, shared with Import Deposits
|
||||
* (agent/income_import.php), which the money in can go on to.
|
||||
*/
|
||||
|
||||
require_once "includes/inc_all.php";
|
||||
@@ -151,179 +153,12 @@ $steps = ['upload' => 'Statement', 'columns' => 'Columns', 'review' => 'Review']
|
||||
</div>
|
||||
|
||||
<?php } elseif ($step === 'columns') {
|
||||
$guess = $import['guess'];
|
||||
$header = $import['header'];
|
||||
$two = $guess['amount'] === null && ($guess['debit'] !== null || $guess['credit'] !== null);
|
||||
$column_select = function ($name, $selected, $optional, $attrs = '') use ($header) {
|
||||
$html = '<select class="form-select" name="' . $name . '" ' . $attrs . '>';
|
||||
$html .= '<option value="">' . ($optional ? '- None -' : '- Pick the column -') . '</option>';
|
||||
foreach ($header as $c => $label) {
|
||||
$html .= '<option value="' . $c . '"' . ($selected !== null && intval($selected) === $c ? ' selected' : '') . '>' . escapeHtml($label) . '</option>';
|
||||
}
|
||||
return $html . '</select>';
|
||||
};
|
||||
$columns_form_id = 'expenseImportColumns';
|
||||
$columns_submit = 'expense_import_columns';
|
||||
$columns_side = 'expense';
|
||||
require __DIR__ . '/includes/statement_columns.php';
|
||||
?>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header bg-dark py-2">
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-columns me-2"></i>Which column is which <span class="fw-normal text-white-50 ms-1"><?= count($import['rows']) ?> lines</span></h3>
|
||||
</div>
|
||||
<form action="post.php" method="post" autocomplete="off" id="expenseImportColumns">
|
||||
<input type="hidden" name="csrf_token" value="<?= $csrf ?>">
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Date <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
|
||||
<?= $column_select('date', $guess['date'], false, 'required') ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Date format</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-calendar-alt"></i></span>
|
||||
<select class="form-select" name="date_format">
|
||||
<?php foreach (expenseImportDateFormats() as $format => $example) { ?>
|
||||
<option value="<?= escapeHtml($format) ?>" <?= $guess['date_format'] === $format ? 'selected' : '' ?>><?= escapeHtml($example) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Reference</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-hashtag"></i></span>
|
||||
<?= $column_select('reference', $guess['reference'], true) ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Description <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
|
||||
<?= $column_select('description', $guess['description'], false, 'required') ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">More description</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
|
||||
<?= $column_select('memo', $guess['memo'], true) ?>
|
||||
</div>
|
||||
<div class="form-text">A memo or notes column, added after the description.</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">The amounts are in</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-coins"></i></span>
|
||||
<select class="form-select" name="amounts" data-import-amounts>
|
||||
<option value="one" <?= $two ? '' : 'selected' ?>>One column</option>
|
||||
<option value="two" <?= $two ? 'selected' : '' ?>>Money out and money in columns</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="one">
|
||||
<label class="form-label">Amount <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
|
||||
<?= $column_select('amount', $guess['amount'], false) ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="one">
|
||||
<label class="form-label">A charge is</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-balance-scale"></i></span>
|
||||
<select class="form-select" name="sign">
|
||||
<option value="positive" <?= $guess['sign'] === 'positive' ? 'selected' : '' ?>>Positive - 25.00 is spent</option>
|
||||
<option value="negative" <?= $guess['sign'] === 'negative' ? 'selected' : '' ?>>Negative - -25.00 is spent</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="two">
|
||||
<label class="form-label">Money out</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-arrow-up"></i></span>
|
||||
<?= $column_select('debit', $guess['debit'], true) ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="two">
|
||||
<label class="form-label">Money in</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-arrow-down"></i></span>
|
||||
<?= $column_select('credit', $guess['credit'], true) ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- The statement as it reads -->
|
||||
<div class="table-responsive border-top">
|
||||
<table class="table table-sm table-striped small mb-0">
|
||||
<thead class="table-light text-nowrap">
|
||||
<tr>
|
||||
<?php foreach ($header as $c => $label) { ?>
|
||||
<th data-import-column="<?= $c ?>"><?= escapeHtml($label) ?></th>
|
||||
<?php } ?>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (array_slice($import['rows'], 0, 8) as $cells) { ?>
|
||||
<tr>
|
||||
<?php foreach ($cells as $c => $cell) { ?>
|
||||
<td class="text-nowrap" data-import-column="<?= $c ?>"><?= escapeHtml(truncate($cell, 60)) ?></td>
|
||||
<?php } ?>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="card-footer d-flex flex-wrap gap-2 align-items-center">
|
||||
<button type="submit" name="expense_import_columns" class="btn btn-primary text-bold"><i class="fas fa-arrow-right me-2"></i>Review the Lines</button>
|
||||
<span class="small text-body-secondary">The first <?= min(8, count($import['rows'])) ?> of <?= count($import['rows']) ?> lines. These columns are kept for the next statement of <?= escapeHtml($account['account_name'] ?? 'this account') ?>.</span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var form = document.getElementById('expenseImportColumns');
|
||||
var amounts = form.querySelector('[data-import-amounts]');
|
||||
var labels = { date: 'Date', description: 'Description', memo: 'More', amount: 'Amount', debit: 'Out', credit: 'In', reference: 'Reference' };
|
||||
function update() {
|
||||
form.querySelectorAll('[data-import-amounts-for]').forEach(function (el) {
|
||||
el.hidden = el.getAttribute('data-import-amounts-for') !== amounts.value;
|
||||
el.querySelectorAll('select').forEach(function (select) {
|
||||
select.disabled = el.hidden;
|
||||
});
|
||||
});
|
||||
// Shade the columns picked, and say what each is
|
||||
var picked = {};
|
||||
Object.keys(labels).forEach(function (field) {
|
||||
var select = form.querySelector('select[name="' + field + '"]');
|
||||
if (select && !select.disabled && select.value !== '') {
|
||||
picked[select.value] = labels[field];
|
||||
}
|
||||
});
|
||||
form.querySelectorAll('[data-import-column]').forEach(function (cell) {
|
||||
var name = picked[cell.getAttribute('data-import-column')];
|
||||
cell.classList.toggle('table-primary', !!name);
|
||||
if (cell.tagName === 'TH') {
|
||||
var tag = cell.querySelector('.badge');
|
||||
if (!tag) {
|
||||
tag = document.createElement('span');
|
||||
tag.className = 'badge text-bg-primary fw-normal ms-1';
|
||||
cell.appendChild(tag);
|
||||
}
|
||||
tag.textContent = name || '';
|
||||
tag.hidden = !name;
|
||||
}
|
||||
});
|
||||
}
|
||||
form.addEventListener('change', update);
|
||||
update();
|
||||
})();
|
||||
</script>
|
||||
|
||||
<?php } else {
|
||||
// The review
|
||||
$lines = expenseImportReview($import);
|
||||
@@ -383,7 +218,7 @@ $steps = ['upload' => 'Statement', 'columns' => 'Columns', 'review' => 'Review']
|
||||
<div class="itflow-billing-stat">
|
||||
<div class="itflow-billing-stat-label"><i class="fas fa-arrow-down me-1"></i>Money in</div>
|
||||
<div class="itflow-billing-stat-value"><?= $count['money_in'] ?></div>
|
||||
<div class="itflow-billing-stat-note">Payments and refunds - left out</div>
|
||||
<div class="itflow-billing-stat-note">Payments and refunds - left out<?php if ($count['money_in']) { ?> · <a href="post.php?income_import_from_statement&csrf_token=<?= $csrf ?>">Bring them in as income</a><?php } ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-xl-3">
|
||||
|
||||
194
agent/includes/statement_columns.php
Normal file
194
agent/includes/statement_columns.php
Normal file
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
/*
|
||||
* Which column of a bank or card statement is which - the date, its format,
|
||||
* a reference, the description and more of it, and the amount in one column
|
||||
* (with which way round it is) or in money out and money in columns. The
|
||||
* columns step of Import Statement (expenses) and Import Deposits (income),
|
||||
* which keep the same columns on the account, so a statement read on one
|
||||
* side reads the same on the other. Set before including:
|
||||
*
|
||||
* $import the statement in the session (header, rows, guess)
|
||||
* $account the account it is for (paymentAccounts() row), or null
|
||||
* $columns_form_id the form's id
|
||||
* $columns_submit the submit button's name, the handler that saves them
|
||||
* $columns_side expense or income, for how the sign is put
|
||||
*/
|
||||
isset($mysqli) || die("Direct file access is not allowed");
|
||||
|
||||
$guess = $import['guess'];
|
||||
$header = $import['header'];
|
||||
$two = $guess['amount'] === null && ($guess['debit'] !== null || $guess['credit'] !== null);
|
||||
$column_select = function ($name, $selected, $optional, $attrs = '') use ($header) {
|
||||
$html = '<select class="form-select" name="' . $name . '" ' . $attrs . '>';
|
||||
$html .= '<option value="">' . ($optional ? '- None -' : '- Pick the column -') . '</option>';
|
||||
foreach ($header as $c => $label) {
|
||||
$html .= '<option value="' . $c . '"' . ($selected !== null && intval($selected) === $c ? ' selected' : '') . '>' . escapeHtml($label) . '</option>';
|
||||
}
|
||||
return $html . '</select>';
|
||||
};
|
||||
// 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'];
|
||||
?>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header bg-dark py-2">
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-columns me-2"></i>Which column is which <span class="fw-normal text-white-50 ms-1"><?= count($import['rows']) ?> lines</span></h3>
|
||||
</div>
|
||||
<form action="post.php" method="post" autocomplete="off" id="<?= escapeHtml($columns_form_id) ?>">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Date <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
|
||||
<?= $column_select('date', $guess['date'], false, 'required') ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Date format</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-calendar-alt"></i></span>
|
||||
<select class="form-select" name="date_format">
|
||||
<?php foreach (expenseImportDateFormats() as $format => $example) { ?>
|
||||
<option value="<?= escapeHtml($format) ?>" <?= $guess['date_format'] === $format ? 'selected' : '' ?>><?= escapeHtml($example) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Reference</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-hashtag"></i></span>
|
||||
<?= $column_select('reference', $guess['reference'], true) ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Description <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
|
||||
<?= $column_select('description', $guess['description'], false, 'required') ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">More description</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
|
||||
<?= $column_select('memo', $guess['memo'], true) ?>
|
||||
</div>
|
||||
<div class="form-text">A memo or notes column, added after the description.</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">The amounts are in</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-coins"></i></span>
|
||||
<select class="form-select" name="amounts" data-import-amounts>
|
||||
<option value="one" <?= $two ? '' : 'selected' ?>>One column</option>
|
||||
<option value="two" <?= $two ? 'selected' : '' ?>>Money out and money in columns</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="one">
|
||||
<label class="form-label">Amount <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
|
||||
<?= $column_select('amount', $guess['amount'], false) ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="one">
|
||||
<label class="form-label"><?= $columns_side === 'income' ? 'Money in is' : 'A charge is' ?></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-balance-scale"></i></span>
|
||||
<select class="form-select" name="sign">
|
||||
<?php foreach ($sign_options as $value => $label) { ?>
|
||||
<option value="<?= $value ?>" <?= $guess['sign'] === $value ? 'selected' : '' ?>><?= $label ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="two">
|
||||
<label class="form-label">Money out</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-arrow-up"></i></span>
|
||||
<?= $column_select('debit', $guess['debit'], true) ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4" data-import-amounts-for="two">
|
||||
<label class="form-label">Money in</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-arrow-down"></i></span>
|
||||
<?= $column_select('credit', $guess['credit'], true) ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- The statement as it reads -->
|
||||
<div class="table-responsive border-top">
|
||||
<table class="table table-sm table-striped small mb-0">
|
||||
<thead class="table-light text-nowrap">
|
||||
<tr>
|
||||
<?php foreach ($header as $c => $label) { ?>
|
||||
<th data-import-column="<?= $c ?>"><?= escapeHtml($label) ?></th>
|
||||
<?php } ?>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (array_slice($import['rows'], 0, 8) as $cells) { ?>
|
||||
<tr>
|
||||
<?php foreach ($cells as $c => $cell) { ?>
|
||||
<td class="text-nowrap" data-import-column="<?= $c ?>"><?= escapeHtml(truncate($cell, 60)) ?></td>
|
||||
<?php } ?>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="card-footer d-flex flex-wrap gap-2 align-items-center">
|
||||
<button type="submit" name="<?= escapeHtml($columns_submit) ?>" class="btn btn-primary text-bold"><i class="fas fa-arrow-right me-2"></i>Review the Lines</button>
|
||||
<span class="small text-body-secondary">The first <?= min(8, count($import['rows'])) ?> of <?= count($import['rows']) ?> lines. These columns are kept for the next statement of <?= escapeHtml($account['account_name'] ?? 'this account') ?>, for expenses and deposits alike.</span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var form = document.getElementById(<?= json_encode($columns_form_id) ?>);
|
||||
var amounts = form.querySelector('[data-import-amounts]');
|
||||
var labels = { date: 'Date', description: 'Description', memo: 'More', amount: 'Amount', debit: 'Out', credit: 'In', reference: 'Reference' };
|
||||
function update() {
|
||||
form.querySelectorAll('[data-import-amounts-for]').forEach(function (el) {
|
||||
el.hidden = el.getAttribute('data-import-amounts-for') !== amounts.value;
|
||||
el.querySelectorAll('select').forEach(function (select) {
|
||||
select.disabled = el.hidden;
|
||||
});
|
||||
});
|
||||
// Shade the columns picked, and say what each is
|
||||
var picked = {};
|
||||
Object.keys(labels).forEach(function (field) {
|
||||
var select = form.querySelector('select[name="' + field + '"]');
|
||||
if (select && !select.disabled && select.value !== '') {
|
||||
picked[select.value] = labels[field];
|
||||
}
|
||||
});
|
||||
form.querySelectorAll('[data-import-column]').forEach(function (cell) {
|
||||
var name = picked[cell.getAttribute('data-import-column')];
|
||||
cell.classList.toggle('table-primary', !!name);
|
||||
if (cell.tagName === 'TH') {
|
||||
var tag = cell.querySelector('.badge');
|
||||
if (!tag) {
|
||||
tag = document.createElement('span');
|
||||
tag.className = 'badge text-bg-primary fw-normal ms-1';
|
||||
cell.appendChild(tag);
|
||||
}
|
||||
tag.textContent = name || '';
|
||||
tag.hidden = !name;
|
||||
}
|
||||
});
|
||||
}
|
||||
form.addEventListener('change', update);
|
||||
update();
|
||||
})();
|
||||
</script>
|
||||
@@ -154,6 +154,9 @@ $invoices_url = 'invoices.php?' . ($client_page ? "client_id=$client_id&" : '')
|
||||
<?php } ?>
|
||||
<button type="button" class="btn <?= $can_edit ? 'btn-primary dropdown-toggle-split' : 'btn-light' ?> dropdown-toggle" data-bs-toggle="dropdown" aria-label="More"><?= $can_edit ? '' : '<i class="fas fa-ellipsis-h"></i>' ?></button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<?php if ($can_edit) { ?>
|
||||
<a class="dropdown-item" href="income_import.php"><i class="fa fa-fw fa-file-import text-secondary me-2"></i>Import Deposits</a>
|
||||
<?php } ?>
|
||||
<a class="dropdown-item ajax-modal" href="#"
|
||||
data-modal-url="<?= buildExportModalUrl('modals/income/income_export.php', ['client_id', 'client', 'category', 'account', 'method', 'show', 'type', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
|
||||
<i class="fa fa-fw fa-download text-secondary me-2"></i>Export
|
||||
@@ -408,7 +411,7 @@ $invoices_url = 'invoices.php?' . ($client_page ? "client_id=$client_id&" : '')
|
||||
<i class="fas fa-hand-holding-usd fa-2x mb-2 opacity-50"></i>
|
||||
<div><?= $any_filter ? 'Nothing matches.' : 'Nothing has come in yet.' ?></div>
|
||||
<?php if (!$any_filter) { ?>
|
||||
<div class="small mt-1">A payment is added on its invoice. Money in that isn't for an invoice is New Income here.</div>
|
||||
<div class="small mt-1">A payment is added on its invoice. Money in that isn't for an invoice is New Income here<?= $can_edit ? ', and a bank statement\'s deposits come in with <a href="income_import.php">Import Deposits</a>' : '' ?>.</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
409
agent/income_import.php
Normal file
409
agent/income_import.php
Normal file
@@ -0,0 +1,409 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Import Deposits - bring the money in on a bank statement in as income.
|
||||
*
|
||||
* 1. Upload: the account the deposits went into, how they are usually paid,
|
||||
* and the CSV the bank exports - the same file Import Statement takes for
|
||||
* expenses.
|
||||
* 2. Columns: as Import Statement (agent/includes/statement_columns.php),
|
||||
* remembered on the account for both sides.
|
||||
* 3. Review: every deposit as a payment on a client's invoices, other income
|
||||
* or a transfer from another of our accounts, as it was matched, ready to
|
||||
* change. Payments show what they pay off; deposits imported before, ones
|
||||
* that look entered already and payouts recorded already are left out.
|
||||
* Import brings in the ticked ones, emailing receipts when asked.
|
||||
*
|
||||
* functions/income_import.php matches and saves; the handlers are in
|
||||
* agent/post/income_import.php.
|
||||
*/
|
||||
|
||||
require_once "includes/inc_all.php";
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$import = $_SESSION['income_import'] ?? null;
|
||||
$step = (string) ($_GET['step'] ?? '');
|
||||
if (!$import || !in_array($step, ['columns', 'review'], true)) {
|
||||
$step = 'upload';
|
||||
} elseif ($step === 'review' && empty($import['map'])) {
|
||||
$step = 'columns';
|
||||
}
|
||||
$accounts = paymentAccounts();
|
||||
$methods = paymentMethods();
|
||||
$csrf = $_SESSION['csrf_token'];
|
||||
$can_pay = incomeImportCanPay();
|
||||
$rules_count = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM income_import_rules"))[0]);
|
||||
$account = $import ? ($accounts[intval($import['account_id'])] ?? null) : null;
|
||||
$currency = $account ? (string) ($account['account_currency_code'] ?: $session_company_currency) : (string) $session_company_currency;
|
||||
$money = function ($amount, $code = null) use ($currency) {
|
||||
return escapeHtml(billingMoney($amount, $code ?? $currency));
|
||||
};
|
||||
|
||||
$steps = ['upload' => 'Statement', 'columns' => 'Columns', 'review' => 'Review'];
|
||||
|
||||
?>
|
||||
|
||||
<ol class="breadcrumb d-print-none">
|
||||
<li class="breadcrumb-item"><a href="income.php">Income</a></li>
|
||||
<li class="breadcrumb-item active">Import Deposits</li>
|
||||
</ol>
|
||||
|
||||
<!-- Where it is up to -->
|
||||
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<?php $i = 0; foreach ($steps as $key => $label) { $i++;
|
||||
$done = array_search($key, array_keys($steps)) < array_search($step, array_keys($steps)); ?>
|
||||
<?php if ($i > 1) { ?><i class="fas fa-chevron-right text-body-tertiary small"></i><?php } ?>
|
||||
<span class="badge rounded-pill fs-6 fw-normal <?= $key === $step ? 'text-bg-primary' : ($done ? 'bg-success-subtle text-success-emphasis' : 'bg-body-secondary text-body-secondary') ?>">
|
||||
<?= $done ? '<i class="fas fa-check me-1"></i>' : $i . '. ' ?><?= $label ?>
|
||||
</span>
|
||||
<?php } ?>
|
||||
<?php if ($import) { ?>
|
||||
<span class="ms-auto small text-body-secondary text-truncate">
|
||||
<i class="fas fa-file-csv me-1"></i><?= escapeHtml($import['file_name']) ?> · <?= escapeHtml($account['account_name'] ?? 'an account since deleted') ?>
|
||||
<a class="ms-2 confirm-link" href="post.php?income_import_discard&csrf_token=<?= $csrf ?>" data-confirm-text="The statement you started is dropped - nothing from it has been imported.">Start over</a>
|
||||
</span>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<?php if ($step === 'upload') { ?>
|
||||
|
||||
<?php if ($import) { ?>
|
||||
<div class="alert alert-info d-flex flex-wrap align-items-center gap-2">
|
||||
<i class="fas fa-file-csv"></i>
|
||||
<span class="me-auto"><?= escapeHtml($import['file_name']) ?> is part way through - nothing from it is imported yet.</span>
|
||||
<a class="btn btn-sm btn-primary" href="income_import.php?step=<?= $import['map'] ? 'review' : 'columns' ?>">Carry on with it</a>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-lg-7">
|
||||
<div class="card">
|
||||
<div class="card-header bg-dark py-2">
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-file-import me-2"></i>Import Deposits</h3>
|
||||
</div>
|
||||
<form action="post.php" method="post" enctype="multipart/form-data" autocomplete="off">
|
||||
<input type="hidden" name="csrf_token" value="<?= $csrf ?>">
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-7">
|
||||
<label class="form-label">The deposits went into <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
|
||||
<select class="form-select select2" name="account" required>
|
||||
<option value="">- Which account -</option>
|
||||
<?php foreach ($accounts as $account_id => $row) { ?>
|
||||
<option value="<?= $account_id ?>" <?= $account_id === intval($config_default_payment_account) ? 'selected' : '' ?> data-icon="fas fa-piggy-bank"
|
||||
data-description="<?= escapeHtml(billingMoney($row['balance'], $row['account_currency_code'])) ?>"><?= escapeHtml($row['account_name']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Usually paid by</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-credit-card"></i></span>
|
||||
<select class="form-select select2" name="payment_method">
|
||||
<option value="">- How they paid -</option>
|
||||
<?php foreach ($methods as $method) { ?>
|
||||
<option value="<?= escapeHtml($method) ?>" <?= $method === (string) $config_default_payment_method ? 'selected' : '' ?>><?= escapeHtml($method) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-text">When a deposit doesn't say - ACH, a check or a wire is read from its text.</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Statement <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-file-csv"></i></span>
|
||||
<input type="file" class="form-control" name="file" accept=".csv,.txt,.tsv,text/csv" required>
|
||||
</div>
|
||||
<div class="form-text">The CSV your bank's website exports - often under Download, Export or Activity. Up to <?= EXPENSE_IMPORT_MAX_LINES ?> lines. Only the money in is brought in here.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<button type="submit" name="income_import_upload" class="btn btn-primary text-bold"><i class="fas fa-upload me-2"></i>Read Statement</button>
|
||||
<a class="btn btn-light ms-1" href="income.php"><i class="fas fa-times me-2"></i>Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-5">
|
||||
<div class="card">
|
||||
<div class="card-body small">
|
||||
<h3 class="h6 fw-semibold"><i class="fas fa-fw fa-info-circle text-secondary me-1"></i>How it goes</h3>
|
||||
<ul class="ps-3 mb-3">
|
||||
<li>The columns are worked out for you, and kept on the account - a statement already imported for expenses goes straight to the review.</li>
|
||||
<li>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.</li>
|
||||
<li>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.</li>
|
||||
<li>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.</li>
|
||||
<li>Nothing is imported until you press Import on the review.</li>
|
||||
</ul>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span class="text-body-secondary"><i class="fas fa-magic me-1"></i><?= $rules_count ?> payer<?= $rules_count === 1 ? '' : 's' ?> remembered</span>
|
||||
<?php if ($rules_count) { ?>
|
||||
<a href="#" class="ajax-modal" data-modal-size="lg" data-modal-url="modals/income/income_import_rules.php">See them</a>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php } elseif ($step === 'columns') {
|
||||
$columns_form_id = 'incomeImportColumns';
|
||||
$columns_submit = 'income_import_columns';
|
||||
$columns_side = 'income';
|
||||
require __DIR__ . '/includes/statement_columns.php';
|
||||
?>
|
||||
|
||||
<?php } else {
|
||||
// The review
|
||||
$lines = incomeImportReview($import, $charges);
|
||||
$open = $can_pay ? incomeImportOpenInvoices() : [];
|
||||
$categories = incomeCategories();
|
||||
$clients = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$clients[intval($row['client_id'])] = $row['client_name'];
|
||||
}
|
||||
// Each client's open invoices, for the payment picks - and what each owes in all
|
||||
$owing = [];
|
||||
foreach ($open as $invoice) {
|
||||
$owing[$invoice['client_id']][] = ['id' => $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 .= '<option value="' . $client_id . '">' . escapeHtml($client_name . ' - owes ' . billingMoney(array_sum(array_column($owing[$client_id], 'balance')))) . '</option>';
|
||||
}
|
||||
}
|
||||
$client_options = '';
|
||||
foreach ($clients as $client_id => $client_name) {
|
||||
$client_options .= '<option value="' . $client_id . '">' . escapeHtml($client_name) . '</option>';
|
||||
}
|
||||
$category_options = '';
|
||||
foreach ($categories as $category_id => $category) {
|
||||
$category_options .= '<option value="' . $category_id . '">' . escapeHtml($category['category_name']) . '</option>';
|
||||
}
|
||||
$account_options = '';
|
||||
foreach ($accounts as $account_id => $row) {
|
||||
if ($account_id !== intval($import['account_id'])) {
|
||||
$account_options .= '<option value="' . $account_id . '">' . escapeHtml($row['account_name']) . '</option>';
|
||||
}
|
||||
}
|
||||
|
||||
$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'];
|
||||
?>
|
||||
|
||||
<!-- What is in it -->
|
||||
<div class="row g-3 mb-3">
|
||||
<div class="col-6 col-xl-3">
|
||||
<div class="itflow-billing-stat">
|
||||
<div class="itflow-billing-stat-label"><i class="fas fa-arrow-down me-1"></i>New deposits</div>
|
||||
<div class="itflow-billing-stat-value"><?= $count['new'] ?></div>
|
||||
<div class="itflow-billing-stat-note"><?= $money($total_new) ?> came in</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-xl-3">
|
||||
<div class="itflow-billing-stat">
|
||||
<div class="itflow-billing-stat-label"><i class="fas fa-file-invoice-dollar me-1"></i>Paying invoices</div>
|
||||
<div class="itflow-billing-stat-value"><?= $count['payment'] ?></div>
|
||||
<div class="itflow-billing-stat-note"><?= $can_pay ? $money($total_paying) . ' matched to what clients owe' : 'Recording payments takes Sales access' ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-xl-3">
|
||||
<div class="itflow-billing-stat">
|
||||
<div class="itflow-billing-stat-label"><i class="fas fa-check-double me-1"></i>Already in</div>
|
||||
<div class="itflow-billing-stat-value"><?= $count['imported'] + $count['entered'] + $count['recorded'] ?></div>
|
||||
<div class="itflow-billing-stat-note"><?= $count['imported'] ?> imported before · <?= $count['entered'] ?> look entered<?= $count['recorded'] ? ' · ' . $count['recorded'] . ' payout' . ($count['recorded'] === 1 ? '' : 's') : '' ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-xl-3">
|
||||
<div class="itflow-billing-stat">
|
||||
<div class="itflow-billing-stat-label"><i class="fas fa-columns me-1"></i>Columns</div>
|
||||
<div class="itflow-billing-stat-value fs-6 fw-normal mt-2"><?= $import['remembered'] ? 'As last time' : 'As you set them' ?></div>
|
||||
<div class="itflow-billing-stat-note">
|
||||
<a href="income_import.php?step=columns">Change them</a><?= $count['problem'] ? ' · <span class="text-danger-emphasis">' . $count['problem'] . " can't be read</span>" : '' ?>
|
||||
<?php if ($charges) { ?>
|
||||
· <?= $charges ?> charge<?= $charges === 1 ? '' : 's' ?> - <a href="post.php?expense_import_from_statement&csrf_token=<?= $csrf ?>">bring them in as expenses</a>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!$lines && $charges) { ?>
|
||||
<div class="alert alert-warning"><i class="fas fa-exclamation-triangle me-2"></i>Every line on this statement reads as money out. If it has deposits, <a href="income_import.php?step=columns">check which way round the amounts are</a>.</div>
|
||||
<?php } ?>
|
||||
|
||||
<form action="post.php" method="post" autocomplete="off" id="incomeImportReview">
|
||||
<input type="hidden" name="csrf_token" value="<?= $csrf ?>">
|
||||
<input type="hidden" name="picks" value="" data-import-picks>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header py-2 d-flex flex-wrap align-items-center gap-2">
|
||||
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-tasks text-secondary me-2"></i>The deposits</h3>
|
||||
<div class="input-group input-group-sm" style="width: auto;">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
|
||||
<select class="form-select" data-income-bulk-category aria-label="Category for the ticked other income">
|
||||
<option value="">- Category for the ticked other income -</option>
|
||||
<?= $category_options ?>
|
||||
</select>
|
||||
</div>
|
||||
<?php if ($count['imported'] || $count['entered'] || $count['recorded'] || $count['problem']) { ?>
|
||||
<div class="form-check form-switch mb-0 ms-2">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="incomeImportShowAll" data-import-show-all>
|
||||
<label class="form-check-label small" for="incomeImportShowAll">Show deposits already in</label>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle mb-0 itflow-billing-table itflow-import-table">
|
||||
<thead class="table-light text-nowrap">
|
||||
<tr>
|
||||
<th class="checkbox-column border-end">
|
||||
<div class="form-check"><input class="form-check-input" type="checkbox" data-import-all title="Tick or untick them all" aria-label="All"></div>
|
||||
</th>
|
||||
<th>Date</th>
|
||||
<th>On the statement</th>
|
||||
<th class="text-end">Amount</th>
|
||||
<th>It is</th>
|
||||
<th>What it pays, or where it goes</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($lines as $line) {
|
||||
$n = intval($line['n']);
|
||||
$state = $line['state'];
|
||||
$fixed = in_array($state, ['imported', 'problem'], true);
|
||||
$action = $line['action'] === 'payment' && !$can_pay ? 'income' : $line['action'];
|
||||
$ready = ($action === 'payment' && $line['invoice_ids'] && $line['how'] !== 'over') || $action === 'income' || ($action === 'transfer' && $line['from_account_id']);
|
||||
$take = $state === 'new' && $ready; ?>
|
||||
<tr data-import-row data-n="<?= $n ?>" data-key="<?= escapeHtml($line['key']) ?>" data-amount="<?= $line['amount'] === null ? 0 : $line['amount'] ?>" data-state="<?= $state ?>"
|
||||
<?= $state === 'new' ? '' : 'data-import-extra' ?> class="<?= $take ? '' : 'itflow-unbilled-off' ?>">
|
||||
<td class="checkbox-column border-end">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" data-import-take <?= $take ? 'checked' : '' ?> <?= $fixed ? 'disabled' : '' ?> aria-label="Import this deposit">
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-nowrap small"><?= $line['date'] ? escapeHtml($line['date']) : '<span class="text-danger-emphasis">?</span>' ?></td>
|
||||
<td class="itflow-import-text">
|
||||
<div class="text-truncate" title="<?= escapeHtml($line['description']) ?>"><?= escapeHtml($line['description']) ?: '<span class="text-body-secondary">-</span>' ?></div>
|
||||
<div class="small">
|
||||
<span class="badge rounded-pill bg-<?= $states[$state]['tone'] ?>-subtle text-<?= $states[$state]['tone'] ?>-emphasis fw-normal"><?= $states[$state]['label'] ?></span>
|
||||
<?php if ($state === 'imported') { ?>
|
||||
<a class="ajax-modal small" href="#" data-modal-size="lg" data-modal-url="modals/<?= $line['imported'] === 'payment' ? 'payment/payment' : 'revenue/revenue' ?>.php?id=<?= intval($line['imported_id']) ?>">Open it</a>
|
||||
<?php } elseif ($state === 'entered') { ?>
|
||||
<?php if ($line['entered_type'] === 'payment') { ?>
|
||||
<a class="ajax-modal small" href="#" data-modal-size="lg" data-modal-url="modals/payment/payment.php?id=<?= intval($line['entered_ids'][0]) ?>"><?= escapeHtml($line['entered_label']) ?></a>
|
||||
<?php } else { ?>
|
||||
<span class="small text-body-secondary"><?= escapeHtml($line['entered_label']) ?></span>
|
||||
<?php } ?>
|
||||
<?php } elseif ($state === 'problem') { ?>
|
||||
<span class="small text-danger-emphasis"><?= escapeHtml($line['problem']) ?></span>
|
||||
<?php } ?>
|
||||
<?php if ($state !== 'problem' && $line['match_note'] !== '' && $state !== 'imported') { ?>
|
||||
<span class="small text-body-secondary"><i class="fas <?= $matched_icons[$line['matched']] ?? 'fa-info-circle' ?> me-1"></i><?= escapeHtml($line['match_note']) ?></span>
|
||||
<?php } ?>
|
||||
<?php if ($line['reference'] !== '') { ?><span class="small text-body-secondary ms-1">#<?= escapeHtml($line['reference']) ?></span><?php } ?>
|
||||
<?php if ($line['method'] !== '' && !$fixed) { ?><span class="small text-body-secondary ms-1">· <?= escapeHtml($line['method']) ?></span><?php } ?>
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-end text-nowrap itflow-money fw-semibold text-success-emphasis"><?= $line['amount'] === null ? '-' : $money($line['amount']) ?></td>
|
||||
<?php if ($fixed) { ?>
|
||||
<td colspan="2" class="small text-body-secondary"><?= $state === 'imported' ? 'Brought in from a statement before - not imported again.' : 'Not imported - fix the columns if every line says this.' ?></td>
|
||||
<?php } else { ?>
|
||||
<td class="itflow-import-pick">
|
||||
<select class="form-select form-select-sm" data-income-action data-value="<?= escapeHtml($action) ?>" aria-label="What it is">
|
||||
<?php foreach (incomeImportActions() as $value => $label) { ?>
|
||||
<option value="<?= $value ?>" <?= $value === 'payment' && !$can_pay ? 'disabled' : '' ?>><?= $label ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</td>
|
||||
<td class="itflow-import-pick itflow-import-details">
|
||||
<div data-income-for="payment">
|
||||
<select class="form-select form-select-sm" data-income-payer data-value="<?= $action === 'payment' ? intval($line['client_id']) : '' ?>" aria-label="Paid by client">
|
||||
<option value="">- Which client paid -</option>
|
||||
<?= $payer_options ?>
|
||||
</select>
|
||||
<div class="itflow-import-invoices mt-1" data-income-invoices data-value="<?= escapeHtml(implode(',', $line['invoice_ids'])) ?>"></div>
|
||||
<div class="small mt-1" data-income-applies></div>
|
||||
</div>
|
||||
<div data-income-for="income">
|
||||
<select class="form-select form-select-sm" data-income-category data-value="<?= intval($line['category_id']) ?: '' ?>" aria-label="Category">
|
||||
<option value="">- Category -</option>
|
||||
<?= $category_options ?>
|
||||
</select>
|
||||
<select class="form-select form-select-sm mt-1" data-income-client data-value="<?= $action === 'income' ? intval($line['client_id']) : 0 ?>" aria-label="From client">
|
||||
<option value="0">- Not from a client -</option>
|
||||
<?= $client_options ?>
|
||||
</select>
|
||||
</div>
|
||||
<div data-income-for="transfer">
|
||||
<select class="form-select form-select-sm" data-income-account data-value="<?= intval($line['from_account_id']) ?: '' ?>" aria-label="From account">
|
||||
<option value="">- From which of your accounts -</option>
|
||||
<?= $account_options ?>
|
||||
</select>
|
||||
<div class="small text-body-secondary mt-1">Money moved between your accounts - not income.</div>
|
||||
</div>
|
||||
</td>
|
||||
<?php } ?>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
<?php if (!$lines) { ?>
|
||||
<tr><td colspan="6" class="text-center text-body-secondary py-4">No money in on this statement.</td></tr>
|
||||
<?php } ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="card-footer d-flex flex-wrap align-items-center gap-2 itflow-import-footer">
|
||||
<span class="me-auto small text-body-secondary" data-import-summary></span>
|
||||
<?php if ($can_pay) { ?>
|
||||
<div class="form-check form-switch mb-0 me-2">
|
||||
<input class="form-check-input" type="checkbox" role="switch" name="receipts" value="1" id="incomeImportReceipts">
|
||||
<label class="form-check-label small" for="incomeImportReceipts">Email each client their receipt</label>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<a class="btn btn-light" href="income_import.php?step=columns"><i class="fas fa-arrow-left me-2"></i>Columns</a>
|
||||
<button type="submit" name="income_import_save" value="1" class="btn btn-primary text-bold" data-import-submit><i class="fas fa-file-import me-2"></i><span data-import-submit-label>Import</span></button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<script src="/js/income_import.js"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
itflowIncomeImport({
|
||||
currency: <?= json_encode($currency) ?>,
|
||||
locale: <?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>,
|
||||
invoices: <?= json_encode((object) $owing) ?>
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php } ?>
|
||||
|
||||
<?php require_once "../includes/footer.php";
|
||||
76
agent/modals/income/income_import_rules.php
Normal file
76
agent/modals/income/income_import_rules.php
Normal file
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* The payers Import Deposits remembers - what a deposit starting with these
|
||||
* words was last time: a payment from a client, other income in a category
|
||||
* and from a client, or a transfer from one of our accounts, and how often.
|
||||
* Forgetting one has the next statement match it afresh.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$rules = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT import_rule_id, import_rule_match, import_rule_action, import_rule_used_count, client_name, category_name, account_name
|
||||
FROM income_import_rules
|
||||
LEFT JOIN clients ON client_id = import_rule_client_id
|
||||
LEFT JOIN categories ON category_id = import_rule_category_id
|
||||
LEFT JOIN accounts ON account_id = import_rule_account_id
|
||||
ORDER BY import_rule_used_count DESC, import_rule_match ASC LIMIT 500");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$rules[] = $row;
|
||||
}
|
||||
$actions = incomeImportActions();
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title"><i class="fas fa-fw fa-magic me-2"></i>Remembered Payers <span class="fw-normal text-white-50 ms-1"><?= count($rules) ?></span></h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body p-0">
|
||||
<div class="px-3 py-2 small text-body-secondary border-bottom">A deposit whose words start like these is matched to what was picked for it last time. Each import updates them.</div>
|
||||
<?php if ($rules) { ?>
|
||||
<div class="table-responsive" style="max-height: 28rem;">
|
||||
<table class="table table-sm table-hover align-middle mb-0 small">
|
||||
<thead class="table-light text-nowrap">
|
||||
<tr>
|
||||
<th class="ps-3">Deposit starts</th>
|
||||
<th>It is</th>
|
||||
<th>From</th>
|
||||
<th class="text-end">Used</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($rules as $rule) {
|
||||
$action = (string) $rule['import_rule_action'];
|
||||
$from = $action === 'transfer' ? ($rule['account_name'] ?: 'An account since deleted') : ($rule['client_name'] ?: ($action === 'payment' ? 'A client since deleted' : '-')); ?>
|
||||
<tr>
|
||||
<td class="ps-3 font-monospace"><?= escapeHtml($rule['import_rule_match']) ?></td>
|
||||
<td><?= escapeHtml($actions[$action] ?? $action) ?><?= $action === 'income' && $rule['category_name'] ? ' <span class="text-body-secondary">· ' . escapeHtml($rule['category_name']) . '</span>' : '' ?></td>
|
||||
<td><?= escapeHtml($from) ?></td>
|
||||
<td class="text-end"><?= intval($rule['import_rule_used_count']) ?></td>
|
||||
<td class="text-end pe-3">
|
||||
<a class="btn btn-sm btn-link text-danger p-0 confirm-link" title="Forget" href="post.php?income_import_rule_delete=<?= intval($rule['import_rule_id']) ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
|
||||
data-confirm-text="Deposits starting "<?= escapeHtml($rule['import_rule_match']) ?>" are matched afresh next time."><i class="fas fa-fw fa-times"></i></a>
|
||||
</td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php } else { ?>
|
||||
<div class="itflow-asset-empty">
|
||||
<i class="fas fa-magic fa-2x mb-2 opacity-50"></i>
|
||||
<div>Nothing remembered yet - each statement you import teaches it.</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Close</button>
|
||||
</div>
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
@@ -123,7 +123,7 @@ ob_start();
|
||||
</div>
|
||||
<div class="itflow-glance-item" title="Entered">
|
||||
<i class="fas fa-fw fa-clock"></i>
|
||||
<span title="<?= escapeHtml($row['payment_created_at']) ?>"><?= timeAgo($row['payment_created_at']) ?></span>
|
||||
<span><span title="<?= escapeHtml($row['payment_created_at']) ?>"><?= timeAgo($row['payment_created_at']) ?></span><?php if (!empty($row['payment_import_key'])) { ?> <span class="text-body-secondary">from a bank statement</span><?php } ?></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
|
||||
@@ -75,7 +75,7 @@ ob_start();
|
||||
</div>
|
||||
<div class="itflow-glance-item" title="Entered">
|
||||
<i class="fas fa-fw fa-clock"></i>
|
||||
<span><span title="<?= escapeHtml($row['revenue_created_at']) ?>"><?= timeAgo($row['revenue_created_at']) ?></span><?php if ($row['created_by_name']) { ?> <span class="text-body-secondary">by <?= escapeHtml($row['created_by_name']) ?></span><?php } ?></span>
|
||||
<span><span title="<?= escapeHtml($row['revenue_created_at']) ?>"><?= timeAgo($row['revenue_created_at']) ?></span><?php if ($row['created_by_name']) { ?> <span class="text-body-secondary">by <?= escapeHtml($row['created_by_name']) ?></span><?php } ?><?php if (!empty($row['revenue_import_key'])) { ?> <span class="text-body-secondary">from a bank statement</span><?php } ?></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
|
||||
219
agent/post/income_import.php
Normal file
219
agent/post/income_import.php
Normal file
@@ -0,0 +1,219 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - importing the deposits on a bank statement as income
|
||||
* (agent/income_import.php; functions/income_import.php does the work, and
|
||||
* functions/expense_import.php reads the file).
|
||||
*
|
||||
* Upload reads the CSV into the session with a first guess at its columns -
|
||||
* or the columns the account's last statement used, from either side, going
|
||||
* straight to the review. Columns sets them; Import brings in the ticked
|
||||
* deposits, sent from the review as one JSON field (picks). A statement read
|
||||
* on one side can go on to the other without uploading it again.
|
||||
*/
|
||||
|
||||
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
|
||||
|
||||
if (isset($_POST['income_import_upload'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$account_id = intval($_POST['account'] ?? 0);
|
||||
$accounts = paymentAccounts();
|
||||
if (!isset($accounts[$account_id])) {
|
||||
flashAlert('Pick the account the deposits went into', 'error');
|
||||
redirect('income_import.php');
|
||||
}
|
||||
$method = trim((string) ($_POST['payment_method'] ?? ''));
|
||||
if ($method !== '' && !in_array($method, paymentMethods(), true)) {
|
||||
$method = '';
|
||||
}
|
||||
$file = $_FILES['file'] ?? null;
|
||||
if (!$file || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK || !is_uploaded_file($file['tmp_name'])) {
|
||||
flashAlert(($file['error'] ?? 0) === UPLOAD_ERR_INI_SIZE ? 'That file is too big - export a month or two at a time' : 'Choose the statement file', 'error');
|
||||
redirect('income_import.php');
|
||||
}
|
||||
if (!in_array(strtolower(pathinfo((string) $file['name'], PATHINFO_EXTENSION)), ['csv', 'txt', 'tsv'], true)) {
|
||||
flashAlert('Export the statement as a CSV file - that is a ' . escapeHtml(strtoupper(pathinfo((string) $file['name'], PATHINFO_EXTENSION)) ?: 'different') . ' file', 'error');
|
||||
redirect('income_import.php');
|
||||
}
|
||||
$read = expenseImportRead($file['tmp_name'], $error);
|
||||
if (!$read) {
|
||||
flashAlert(escapeHtml($error), 'error');
|
||||
redirect('income_import.php');
|
||||
}
|
||||
|
||||
$map = expenseImportSavedMap($account_id, $read['header']);
|
||||
$_SESSION['income_import'] = [
|
||||
'account_id' => $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[] = '<strong>' . escapeHtml(billingMoney($result['paid'], $currency)) . '</strong> 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[] = '<strong>' . escapeHtml(billingMoney($result['income_total'], $currency)) . '</strong> 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 - <strong>' . escapeHtml($match) . '</strong> will be matched afresh next time' : 'That match was already gone', $match !== null ? 'success' : 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
30
db.sql
30
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 */;
|
||||
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
821
functions/income_import.php
Normal file
821
functions/income_import.php
Normal file
@@ -0,0 +1,821 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - importing the deposits on a bank statement as income.
|
||||
*
|
||||
* The statement is read, and its columns worked out and remembered on the
|
||||
* account, by functions/expense_import.php - the same file can be brought in
|
||||
* on both sides: its charges as expenses, its deposits here. Only the money
|
||||
* in is a deposit.
|
||||
*
|
||||
* Each deposit becomes one of three things:
|
||||
*
|
||||
* - payment on one or more of a client's open invoices, the oldest due
|
||||
* first, the last part paid when the deposit is short of them
|
||||
* - income other income, with a category and the client it came from
|
||||
* - transfer money moved in from another of our accounts - a payout of
|
||||
* card payments from the payment provider's account, or savings
|
||||
*
|
||||
* It is matched, in this order, by an invoice number in its text; by what
|
||||
* was picked for the same payer last time (income_import_rules, keyed on the
|
||||
* start of the cleaned-up text, like the expense side's merchants); by a
|
||||
* client's name in it; by being the only invoice, or the one client's open
|
||||
* invoices together, owing exactly that much; and by looking like a payout
|
||||
* or a transfer. A client's invoices are picked as the one owing the amount,
|
||||
* the ones that add up to it, or the oldest first.
|
||||
*
|
||||
* Every deposit has a key, as the expense side's lines do, kept on the
|
||||
* payments (payment_import_key) or the revenue (revenue_import_key) it came
|
||||
* in as, so the same statement can't bring it in twice. A deposit not
|
||||
* imported before but with the amount of a payment, other income or transfer
|
||||
* entered by hand on the account within a few days - or of a day's payments
|
||||
* together, one check paying several invoices - looks entered already: left
|
||||
* out unless ticked, and if left out those take its key. A payout into the
|
||||
* account the payment provider's payments are recorded in is recorded
|
||||
* already.
|
||||
*/
|
||||
|
||||
const INCOME_IMPORT_DUPLICATE_DAYS = 4;
|
||||
|
||||
/** May this agent record payments on invoices from a statement - the rule for adding a payment (Sales and Financial at 2). */
|
||||
function incomeImportCanPay() {
|
||||
return lookupUserPermission('module_sales') >= 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;
|
||||
}
|
||||
379
js/income_import.js
Normal file
379
js/income_import.js
Normal file
@@ -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();
|
||||
}
|
||||
Reference in New Issue
Block a user