mirror of
https://github.com/itflow-org/itflow
synced 2026-12-05 10:39:00 +00:00
Expenses stage 4: getting expenses in - Import Statement from the expenses menu brings a card or bank CSV in as expenses, reading lines before the header, commas, semicolons or tabs, Windows text and amounts like (12.00), 12.00 CR or 1.234,56, guessing the date and its format, description, memo, amount or money out and in columns, sign and reference and remembering them per account so the next statement goes straight to the review, matching each line to a vendor from what was picked for that merchant last time or a vendor name in the text (shortened names too) with its last category, suggesting a new vendor named from the line when nothing matches, locking lines imported before so a statement never comes in twice, leaving out lines that look entered by hand within 4 days and linking them, leaving out money in unless ticked, filling in the same merchant's other lines, bulk category and client and billing on, making new vendors once and opening the account's expenses for those dates, with remembered merchants to see or forget; paid personally expenses with who paid them that count as spent on their date but move no balance until paid back, a To reimburse pill with what each agent is owed, Reimburse paying back the ticked expenses from one account on one date as a Reimbursement in Transactions with undo for full financial access, quick look, list, vendor page, bulk, export and dashboard showing who paid and whether they were paid back, database 3.0.2 with expense_import_key, expense_paid_by, expense_reimbursement_id, expense_import_rules, reimbursements and account_import_map, CHANGELOG updated
This commit is contained in:
32
CHANGELOG.md
32
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.1) 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.2) in the same pass. Nothing else is required.
|
||||
|
||||
This is a big release, with twenty-two database steps in one go, so take a backup before you update.
|
||||
This is a big release, with twenty-three 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:
|
||||
|
||||
@@ -87,6 +87,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
|
||||
- A recurring expense the nightly run missed by up to 7 nights is recorded the next night, dated the day it was due. One further behind waits for you to Record Now or Move On. The notification every night for each recurring expense with a date in the past is replaced by one notification, on the day it falls too far behind.
|
||||
- Deleting a recurring expense needs full Financial access, the same as deleting an expense. It used to need write access.
|
||||
- Unbilled Time also lists expenses to bill for agents with Financial access, and its count in the menu adds them. For those agents it shows in the menu even with ticketing turned off.
|
||||
- Transactions has a Reimbursement type for money paid back to an agent. A Transactions export filtered to Expense leaves those out.
|
||||
- Notifications now follow access too. An agent only sees notifications for clients and areas they can open, so someone without sales access no longer sees invoice and quote notifications.
|
||||
- Drop-downs: Tom Select is gone, replaced by ITFlow's own picker. It works the way you are used to: type to search, tick several in a multi-select, and type a new value in fields that allow it, such as ticket watchers. See Developer Updates if you have custom pages that used Tom Select.
|
||||
- Several small windows are gone because the change is now made where the value is shown:
|
||||
@@ -360,6 +361,20 @@ If you are coming from 26.08 or earlier, the database update still has to be run
|
||||
- A client's **recurring expense** can be billed on each time it records one, with a markup, or be **covered by** one of the client's recurring invoices. A covered one isn't billed by itself: the recurring invoice's new **Costs** card lists what it covers, what it bills a month before tax against what they cost a month, and the margin left, with Add to set up another one it covers. The recurring expenses list and quick look show which it is.
|
||||
- Expenses to bill show on the dashboard and the client overview's attention list, and the client overview's Not yet invoiced includes them. The export has Billing and Billed On columns.
|
||||
- The demo data's latest client expenses are to bill, at 15%.
|
||||
- **Import Statement**, from the expenses menu, brings a card or bank statement in as expenses:
|
||||
- Upload the CSV your bank or card exports, and pick the account it is for and how it was paid. Lines before the header, semicolons or tabs, and amounts like (12.00), 12.00 CR or 1.234,56 are read as they come.
|
||||
- The columns are worked out for you: the date and its format, the description and a memo, the amount (charges positive or negative) or separate money out and money in columns, and a reference such as the check number. You check them once against the statement - the next statement from the same account goes straight to the review.
|
||||
- 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.
|
||||
- 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.
|
||||
- Reimburse pays an agent back for the ticked expenses from one account, on a date, with how and a reference. The account's balance goes down then, and the payment shows in Transactions as a Reimbursement. Spending totals and reports count the expenses once, on their own dates.
|
||||
- The expense's quick look says who paid it, To reimburse with a Reimburse button, or when it was paid back. The reimbursement opens with what it paid back, and Undo (full Financial access) takes the payment back off the account.
|
||||
- Bulk Reimburse pays back the ticked expenses of one agent. Bulk Set Account puts a paid personally expense on an account instead, unless it was paid back already.
|
||||
- Expenses to reimburse show on the dashboard. The export has a Paid Personally column, and the list can be cut to one agent's.
|
||||
- **Tickets**
|
||||
- The ticket list has views for Open, Mine, Unassigned, Needs reply, Waiting, Overdue, Scheduled, Closed and All.
|
||||
- Each row shows whose move it is (yours or the client's) along with SLA and due badges, and status, priority and agent change right in the row.
|
||||
@@ -617,6 +632,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
|
||||
- 2.9.9: `expenses.expense_created_by` (0 for cron and payment providers), backfilled from the audit log's Expense Create entries, and `expense_refund_of_id`.
|
||||
- 3.0.0 (after 2.9.9, the way 2.0.0 followed 1.9.9): `recurring_expenses.recurring_expense_frequency` becomes `varchar(10)` (`month`, `quarter` or `year`, from 1 and 2), with `recurring_expense_anchor_day` (backfilled from the next date) and `recurring_expense_end_date`. `recurring_expense_day` and `recurring_expense_month` are dropped. `expenses.expense_recurring_expense_id`, backfilled by vendor, category, client and description from the day each recurring expense was set up.
|
||||
- 3.0.1: `expenses.expense_billable` (0), `expense_markup` (`decimal(7,2)`, 0.00), `expense_invoice_id` (keyed) and `expense_invoice_item_id`. `recurring_expenses.recurring_expense_billable` (0), `recurring_expense_markup` and `recurring_expense_recurring_invoice_id`. `settings.config_expense_markup` (0.00).
|
||||
- 3.0.2: `expenses.expense_import_key` (keyed), `expense_paid_by` (0) and `expense_reimbursement_id` (keyed). `expense_import_rules` (`import_rule_match` unique, `import_rule_vendor_id`, `import_rule_category_id`, `import_rule_client_id`, `import_rule_billable`, `import_rule_used_count`). `reimbursements` (`reimbursement_user_id`, `reimbursement_date`, `reimbursement_amount`, `reimbursement_currency_code`, `reimbursement_account_id`, `reimbursement_payment_method`, `reimbursement_reference`, `reimbursement_expense_id`, `reimbursement_created_by`). `accounts.account_import_map`.
|
||||
- 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`.
|
||||
@@ -785,6 +801,18 @@ If you are coming from 26.08 or earlier, the database update still has to be run
|
||||
- Handlers: GET `expense_unbill` (Financial and Sales at 2) and POST `invoice_add_expenses` (`invoice_id`, `expense_ids[]`, `expense_price[id]`, `tax_id`). `unbilled_invoice` and `unbilled_write_off` take `expense_ids[]` and `expense_price[id]` too (Financial at 2 when they are posted), and `unbilled_invoice_clients` bills each client's expenses for agents with Financial at 2. `bulk_edit_expenses` takes `field=billable` (`value` yes with `markup`, or no). `edit_invoice_settings` saves `config_expense_markup`. The export adds `expense_billing_display` and `expense_billed_on`.
|
||||
- New window `agent/modals/invoice/invoice_add_expenses.php?invoice_id=`. `recurring_expense_add.php` takes `?recurring_invoice_id=`. `agent/invoice.php` has the Expenses card and `agent/recurring_invoice.php` the Costs card for agents with Financial access. `js/unbilled_time.js` counts `[data-unbilled-expense-row]` rows with their `[data-unbilled-expense-pick]` and `[data-unbilled-expense-price]`. CSS: `.itflow-unbilled-price`.
|
||||
- `dashboardAttention()` and `clientOverviewAttention()` add Expenses to bill, and `clientOverviewMoney()` adds `unbilled_expenses` and `unbilled_expense_value`. `get_side_nav_counts.php` and `inc_all_client.php` set `$num_unbilled_expenses`.
|
||||
- Statement import, in the new `functions/expense_import.php` (loaded by `functions.php`):
|
||||
- `expenseImportRead($path, &$error)` reads a CSV up to `EXPENSE_IMPORT_MAX_BYTES` (2 MB) and `EXPENSE_IMPORT_MAX_LINES` (2000): byte order mark, Windows-1252, the delimiter the first lines agree on, and the header as the line before the first with a date. `expenseImportDateFormats()`, `expenseImportDate($value, $format)`, `expenseImportLooksLikeDate()` and `expenseImportAmount()`.
|
||||
- `expenseImportGuess($header, $rows)` maps date, description, memo, amount or debit and credit, and reference by header name then by content, with `date_format` and `sign`. `expenseImportMapClean()` checks a posted or saved one. `expenseImportSavedMap()` and `expenseImportSaveMap()` keep it in `accounts.account_import_map`, keyed on the column names (`expenseImportColumnsKey()`).
|
||||
- `expenseImportLines($rows, $map)` gives each line `date`, `description` (with the memo), `match_text`, `amount` (charges positive), `reference` and `problem`. `expenseImportReview($import)` runs `expenseImportMatch()` (rules from `expenseImportRules()`, then vendor names through `expenseImportWords()`), `expenseImportKeys()` (SHA-256 of account, date, amount, text and repeat, as `key_hash`) and `expenseImportDuplicates()` (`imported`, and `entered` within `EXPENSE_IMPORT_DUPLICATE_DAYS`). `expenseImportMatchKey()` and `expenseImportVendorName()`.
|
||||
- `expenseImportSave($import, $picks, &$error)` checks every ticked line first, makes new vendors once (`vendorFormSet()`), inserts the expenses with `expense_import_key`, upserts `expense_import_rules` on `import_rule_match`, and stamps the key on hand-entered expenses a left-out line matched.
|
||||
- New page `agent/expense_import.php` (`?step=columns` and `?step=review`, the statement in `$_SESSION['expense_import']`) and `js/expense_import.js` (`itflowExpenseImport()`). Handlers in the new `agent/post/expense_import.php`: `expense_import_upload` (POST `account`, `payment_method`, `file`), `expense_import_columns`, `expense_import_save` (POST `picks`, one JSON list of `n`, `take`, `vendor` or `new` with `new_vendor`, `category`, `client`, `billable` - under `max_input_vars` for long statements), GET `expense_import_discard` and `expense_import_rule_delete`. New window `agent/modals/expense/expense_import_rules.php`. CSS: `.itflow-import-*`.
|
||||
- Paid personally, in `functions/expenses.php`:
|
||||
- `expenseSave()` takes `account=personal` with `paid_by` (one of `expensePayers()`), saving `expense_account_id = 0` and `expense_paid_by`, in the company currency. Money back can't be paid personally, and a paid back expense keeps who paid it. `expenseSave()` and `expenseDelete()` refuse the payment row of a reimbursement, as they do a transfer's.
|
||||
- `expenseToReimburseSql()`, `expenseToReimburse($user_id, $ids)` (by agent, scoped), `expenseToReimburseCount()` and `expenseReimburse($user_id, $ids, $opts, &$error)`, which claims the expenses with a conditional `UPDATE`, then inserts the payment as an expense with no vendor and category on the account and the `reimbursements` row pointing at it. `reimbursementRow()`, `reimbursementExpenses()` and `reimbursementDelete()`.
|
||||
- `expenseRow()` adds `paid_by_name`, `reimbursement_date`, `reimbursed_account_name`, `reimbursement_out_id` and `reimbursed_to_name` (its joins on `accounts` and `users` are aliased now). `expenseShows()` adds `to_reimburse`, and `expenseFiltersSql()` takes `paid_by`.
|
||||
- Handlers: POST `expense_reimburse` (`user_id`, `expense_ids[]`, `account`, `date`, `payment_method`, `reference`) and GET `expense_reimbursement_delete` (Financial at 3). `bulk_edit_expenses` with `field=account` clears `expense_paid_by` and skips paid back ones. The export adds `expense_paid_by_display`.
|
||||
- New windows `agent/modals/expense/expense_reimburse.php` (`?user_id=` or `?expense_ids[]=`) and `expense_reimbursement.php?id=`. `agent/transactions.php`, its export and `agent/post/transaction.php` give the payment the type Reimbursement, with the agent as the other side. `dashboardAttention()` adds Expenses to reimburse.
|
||||
- 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.
|
||||
|
||||
59
admin/database_updates/3.0.2.php
Normal file
59
admin/database_updates/3.0.2.php
Normal file
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - Database update to version 3.0.2 (from 3.0.1)
|
||||
* Included by admin/database_updates.php - do not access directly
|
||||
*/
|
||||
|
||||
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
|
||||
|
||||
// Expenses from a statement import keep the key of the line they came
|
||||
// from, so the same statement can't bring them in twice. One paid
|
||||
// personally by an agent (expense_paid_by) is on no account until it is
|
||||
// paid back, by a reimbursement
|
||||
mysqli_query($mysqli, "ALTER TABLE `expenses`
|
||||
ADD COLUMN `expense_import_key` varchar(64) DEFAULT NULL AFTER `expense_invoice_item_id`,
|
||||
ADD COLUMN `expense_paid_by` int(11) NOT NULL DEFAULT 0 AFTER `expense_import_key`,
|
||||
ADD COLUMN `expense_reimbursement_id` int(11) DEFAULT NULL AFTER `expense_paid_by`,
|
||||
ADD KEY `expense_import_key` (`expense_import_key`),
|
||||
ADD KEY `expense_reimbursement_id` (`expense_reimbursement_id`)");
|
||||
|
||||
// What a statement line's merchant is - the vendor, category and client
|
||||
// picked for it last time, matched on the start of its cleaned-up text
|
||||
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `expense_import_rules` (
|
||||
`import_rule_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`import_rule_match` varchar(200) NOT NULL,
|
||||
`import_rule_vendor_id` int(11) NOT NULL,
|
||||
`import_rule_category_id` int(11) NOT NULL DEFAULT 0,
|
||||
`import_rule_client_id` int(11) NOT NULL DEFAULT 0,
|
||||
`import_rule_billable` tinyint(1) 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");
|
||||
|
||||
// Paying an agent back for what they paid personally - the money out of
|
||||
// the account is an expense with no vendor (reimbursement_expense_id), the
|
||||
// way a transfer is
|
||||
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `reimbursements` (
|
||||
`reimbursement_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`reimbursement_user_id` int(11) NOT NULL,
|
||||
`reimbursement_date` date NOT NULL,
|
||||
`reimbursement_amount` decimal(15,2) NOT NULL,
|
||||
`reimbursement_currency_code` varchar(200) NOT NULL,
|
||||
`reimbursement_account_id` int(11) NOT NULL,
|
||||
`reimbursement_payment_method` varchar(200) DEFAULT NULL,
|
||||
`reimbursement_reference` varchar(200) DEFAULT NULL,
|
||||
`reimbursement_expense_id` int(11) NOT NULL,
|
||||
`reimbursement_created_by` int(11) NOT NULL DEFAULT 0,
|
||||
`reimbursement_created_at` datetime NOT NULL DEFAULT current_timestamp(),
|
||||
PRIMARY KEY (`reimbursement_id`),
|
||||
KEY `reimbursement_user_id` (`reimbursement_user_id`),
|
||||
KEY `reimbursement_expense_id` (`reimbursement_expense_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
|
||||
|
||||
// The columns, date format and sign an account's statements were last
|
||||
// imported with, to start the next one from
|
||||
mysqli_query($mysqli, "ALTER TABLE `accounts` ADD COLUMN `account_import_map` text DEFAULT NULL AFTER `account_notes`");
|
||||
530
agent/expense_import.php
Normal file
530
agent/expense_import.php
Normal file
@@ -0,0 +1,530 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Import Statement - bring a card or bank statement in as expenses.
|
||||
*
|
||||
* 1. Upload: the account it is for, how it was paid, and the CSV the bank
|
||||
* or card exports.
|
||||
* 2. Columns: which column is the date, the description, the amount (or
|
||||
* money out and money in), a reference, the date format, and whether
|
||||
* charges are positive. Guessed, and remembered on the account - the
|
||||
* next statement with the same columns goes straight to the review.
|
||||
* 3. Review: every line with the vendor, category and client it matched,
|
||||
* ready to change; new vendors named from the text; lines imported
|
||||
* before, or that look entered by hand already, and money in left
|
||||
* unticked. Picking a vendor fills in the other lines from the same
|
||||
* merchant. Import brings in the ticked ones.
|
||||
*
|
||||
* functions/expense_import.php reads, matches and saves; the handlers are
|
||||
* in agent/post/expense_import.php.
|
||||
*/
|
||||
|
||||
require_once "includes/inc_all.php";
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$import = $_SESSION['expense_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'];
|
||||
$rules_count = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM expense_import_rules"))[0]);
|
||||
$account = $import ? ($accounts[intval($import['account_id'])] ?? null) : null;
|
||||
$currency = $account ? (string) $account['account_currency_code'] : (string) $session_company_currency;
|
||||
$money = function ($amount) use ($currency) {
|
||||
return escapeHtml(billingMoney($amount, $currency));
|
||||
};
|
||||
|
||||
$steps = ['upload' => 'Statement', 'columns' => 'Columns', 'review' => 'Review'];
|
||||
|
||||
?>
|
||||
|
||||
<ol class="breadcrumb d-print-none">
|
||||
<li class="breadcrumb-item"><a href="expenses.php">Expenses</a></li>
|
||||
<li class="breadcrumb-item active">Import Statement</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?expense_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="expense_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 Statement</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">It is the statement of <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 or card -</option>
|
||||
<?php foreach ($accounts as $account_id => $row) { ?>
|
||||
<option value="<?= $account_id ?>" <?= $account_id === intval($config_default_expense_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">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 were paid -</option>
|
||||
<?php foreach ($methods as $method) { ?>
|
||||
<option value="<?= escapeHtml($method) ?>" <?= $method === (string) $config_default_expense_payment_method ? 'selected' : '' ?>><?= escapeHtml($method) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</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 or card's website exports - often under Download, Export or Activity. Up to <?= EXPENSE_IMPORT_MAX_LINES ?> lines.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<button type="submit" name="expense_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="expenses.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 - check them once, and the next statement from the same account goes straight to the review.</li>
|
||||
<li>Each line is matched to a vendor: what you picked for that merchant last time, or one of your vendors whose name is in it. A new vendor can be made from the line's text.</li>
|
||||
<li>Lines brought in before, and ones with the same amount as an expense entered by hand within <?= EXPENSE_IMPORT_DUPLICATE_DAYS ?> days, are left out unless you tick them.</li>
|
||||
<li>Payments to the card and other money in are left out unless you tick them - then they come in as money back.</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 ?> merchant<?= $rules_count === 1 ? '' : 's' ?> remembered</span>
|
||||
<?php if ($rules_count) { ?>
|
||||
<a href="#" class="ajax-modal" data-modal-size="lg" data-modal-url="modals/expense/expense_import_rules.php">See them</a>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</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>';
|
||||
};
|
||||
?>
|
||||
|
||||
<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);
|
||||
$vendors = expenseVendors();
|
||||
$categories = expenseCategories();
|
||||
$defaults = expenseVendorDefaults();
|
||||
$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'];
|
||||
}
|
||||
$count = ['new' => 0, 'imported' => 0, 'entered' => 0, 'money_in' => 0, 'problem' => 0, 'matched' => 0];
|
||||
foreach ($lines as $i => $line) {
|
||||
$state = $line['problem'] !== '' ? 'problem' : ($line['imported'] ? 'imported' : ($line['entered'] ? 'entered' : ($line['amount'] < 0 ? 'money_in' : 'new')));
|
||||
$lines[$i]['state'] = $state;
|
||||
$count[$state]++;
|
||||
$count['matched'] += $state === 'new' && $line['vendor_id'] ? 1 : 0;
|
||||
}
|
||||
$vendor_options = '';
|
||||
foreach ($vendors as $vendor_id => $vendor) {
|
||||
$vendor_options .= '<option value="' . $vendor_id . '">' . escapeHtml($vendor['vendor_name']) . '</option>';
|
||||
}
|
||||
$category_options = '';
|
||||
foreach ($categories as $category_id => $category) {
|
||||
$category_options .= '<option value="' . $category_id . '">' . escapeHtml($category['category_name']) . '</option>';
|
||||
}
|
||||
$client_options = '';
|
||||
foreach ($clients as $client_id => $client_name) {
|
||||
$client_options .= '<option value="' . $client_id . '">' . escapeHtml($client_name) . '</option>';
|
||||
}
|
||||
$states = [
|
||||
'new' => ['label' => 'New', 'tone' => 'primary'],
|
||||
'imported' => ['label' => 'Imported before', 'tone' => 'secondary'],
|
||||
'entered' => ['label' => 'Entered already?', 'tone' => 'warning'],
|
||||
'money_in' => ['label' => 'Money in', 'tone' => 'success'],
|
||||
'problem' => ['label' => "Can't read", 'tone' => 'danger'],
|
||||
];
|
||||
?>
|
||||
|
||||
<!-- 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-receipt me-1"></i>New charges</div>
|
||||
<div class="itflow-billing-stat-value"><?= $count['new'] ?></div>
|
||||
<div class="itflow-billing-stat-note"><?= $count['matched'] ?> matched to a vendor</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'] ?></div>
|
||||
<div class="itflow-billing-stat-note"><?= $count['imported'] ?> imported before · <?= $count['entered'] ?> look entered</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-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>
|
||||
</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="expense_import.php?step=columns">Change them</a><?= $count['problem'] ? ' · <span class="text-danger-emphasis">' . $count['problem'] . " can't be read</span>" : '' ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form action="post.php" method="post" autocomplete="off" id="expenseImportReview">
|
||||
<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 lines</h3>
|
||||
<div class="input-group input-group-sm" style="width: auto;">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
|
||||
<select class="form-select" data-import-bulk-category aria-label="Category for the ticked lines">
|
||||
<option value="">- Category for the ticked -</option>
|
||||
<?= $category_options ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="input-group input-group-sm" style="width: auto;">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
|
||||
<select class="form-select" data-import-bulk-client aria-label="Client for the ticked lines">
|
||||
<option value="">- Client for the ticked -</option>
|
||||
<option value="0">Not for a client</option>
|
||||
<?= $client_options ?>
|
||||
</select>
|
||||
</div>
|
||||
<?php if ($count['money_in'] || $count['imported'] || $count['entered']) { ?>
|
||||
<div class="form-check form-switch mb-0 ms-2">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="importShowAll" data-import-show-all>
|
||||
<label class="form-check-label small" for="importShowAll">Show money in and lines 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>Vendor</th>
|
||||
<th>Category</th>
|
||||
<th>Client</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($lines as $line) {
|
||||
$n = intval($line['n']);
|
||||
$state = $line['state'];
|
||||
$take = $state === 'new' && $line['amount'] > 0;
|
||||
$fixed = in_array($state, ['imported', 'problem'], true);
|
||||
$vendor_value = $line['vendor_id'] ? (string) $line['vendor_id'] : 'new'; ?>
|
||||
<tr data-import-row data-n="<?= $n ?>" data-key="<?= escapeHtml($line['key']) ?>" data-amount="<?= $line['amount'] === null ? 0 : $line['amount'] ?>" data-state="<?= $state ?>"
|
||||
<?= in_array($state, ['new'], true) ? '' : '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 line">
|
||||
</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/expense/expense.php?id=<?= intval($line['imported']) ?>">Open it</a>
|
||||
<?php } elseif ($state === 'entered') { ?>
|
||||
<a class="ajax-modal small" href="#" data-modal-size="lg" data-modal-url="modals/expense/expense.php?id=<?= intval($line['entered']) ?>"><?= escapeHtml($line['entered_label']) ?></a>
|
||||
<?php } elseif ($state === 'problem') { ?>
|
||||
<span class="small text-danger-emphasis"><?= escapeHtml($line['problem']) ?></span>
|
||||
<?php } elseif ($line['matched'] === 'rule') { ?>
|
||||
<span class="small text-body-secondary" title="Picked for this merchant before"><i class="fas fa-magic me-1"></i>as last time</span>
|
||||
<?php } elseif ($line['matched'] === 'name') { ?>
|
||||
<span class="small text-body-secondary" title="The vendor's name is in the line"><i class="fas fa-link me-1"></i>by name</span>
|
||||
<?php } ?>
|
||||
<?php if ($line['reference'] !== '') { ?><span class="small text-body-secondary ms-1">#<?= escapeHtml($line['reference']) ?></span><?php } ?>
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-end text-nowrap itflow-money fw-semibold <?= $line['amount'] !== null && $line['amount'] < 0 ? 'text-success-emphasis' : '' ?>"><?= $line['amount'] === null ? '-' : $money($line['amount']) ?></td>
|
||||
<?php if ($fixed) { ?>
|
||||
<td colspan="3" 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-import-vendor data-value="<?= escapeHtml($vendor_value) ?>" aria-label="Vendor">
|
||||
<option value="">- Vendor -</option>
|
||||
<option value="new">+ New vendor</option>
|
||||
<?= $vendor_options ?>
|
||||
</select>
|
||||
<input type="text" class="form-control form-control-sm mt-1" maxlength="200" value="<?= escapeHtml($line['new_vendor']) ?>" data-import-new-vendor aria-label="New vendor name" placeholder="New vendor's name">
|
||||
</td>
|
||||
<td class="itflow-import-pick">
|
||||
<select class="form-select form-select-sm" data-import-category data-value="<?= intval($line['category_id']) ?: '' ?>" aria-label="Category">
|
||||
<option value="">- Category -</option>
|
||||
<?= $category_options ?>
|
||||
</select>
|
||||
</td>
|
||||
<td class="itflow-import-pick">
|
||||
<select class="form-select form-select-sm" data-import-client data-value="<?= intval($line['client_id']) ?>" aria-label="Client">
|
||||
<option value="0">-</option>
|
||||
<?= $client_options ?>
|
||||
</select>
|
||||
<div class="form-check form-switch small mt-1 mb-0" data-import-billable-box>
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="importBillable<?= $n ?>" data-import-billable <?= $line['billable'] ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="importBillable<?= $n ?>">Bill on</label>
|
||||
</div>
|
||||
</td>
|
||||
<?php } ?>
|
||||
</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>
|
||||
<a class="btn btn-light" href="expense_import.php?step=columns"><i class="fas fa-arrow-left me-2"></i>Columns</a>
|
||||
<button type="submit" name="expense_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/expense_import.js"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
itflowExpenseImport({
|
||||
currency: <?= json_encode($currency) ?>,
|
||||
locale: <?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>,
|
||||
defaults: <?= json_encode((object) array_map(function ($d) { return $d['category']; }, $defaults)) ?>
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php } ?>
|
||||
|
||||
<?php require_once "../includes/footer.php";
|
||||
@@ -36,6 +36,7 @@ $client_filter = intval($_GET['client'] ?? 0);
|
||||
$method_filter = trim((string) ($_GET['method'] ?? ''));
|
||||
$recurring_filter = intval($_GET['recurring_expense_id'] ?? 0);
|
||||
$recurring_filter_row = $recurring_filter ? recurringExpenseRow($recurring_filter) : null;
|
||||
$paid_by_filter = intval($_GET['paid_by'] ?? 0);
|
||||
$shows = expenseShows();
|
||||
$show = isset($shows[$_GET['show'] ?? '']) ? (string) ($_GET['show'] ?? '') : '';
|
||||
|
||||
@@ -53,7 +54,7 @@ $show_query = $shows[$show]['where'] ? "AND {$shows[$show]['where']}" : '';
|
||||
$joins = expenseJoinsSql();
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS expenses.*, vendor_name, vendor_archived_at, category_name, category_color, account_name, client_name, user_name,
|
||||
invoice_prefix, invoice_number
|
||||
invoice_prefix, invoice_number, (SELECT payer.user_name FROM users AS payer WHERE payer.user_id = expense_paid_by) AS paid_by_name
|
||||
FROM expenses $joins
|
||||
LEFT JOIN invoices ON invoice_id = expense_invoice_id
|
||||
WHERE $where $show_query
|
||||
@@ -96,7 +97,10 @@ $stat_money = function ($amount) use ($session_company_currency) {
|
||||
|
||||
// More filters open when one of them is set
|
||||
$more_filters = $account_filter || $method_filter !== '';
|
||||
$any_filter = $q || $vendor_filter || $category_filter || $account_filter || $client_filter || $method_filter !== '' || $recurring_filter || $show !== '' || $dtf !== '1970-01-01';
|
||||
$any_filter = $q || $vendor_filter || $category_filter || $account_filter || $client_filter || $method_filter !== '' || $recurring_filter || $paid_by_filter || $show !== '' || $dtf !== '1970-01-01';
|
||||
|
||||
// Who is owed for what they paid personally - above the list on To reimburse
|
||||
$owed = $show === 'to_reimburse' ? expenseToReimburse($paid_by_filter) : [];
|
||||
|
||||
// This month against the same days of last month
|
||||
$month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['last_to_date']) / $stats['last_to_date'] * 100) : null;
|
||||
@@ -152,8 +156,12 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
|
||||
<?php } ?>
|
||||
<button type="button" class="btn btn-primary dropdown-toggle <?= $can_edit ? 'dropdown-toggle-split' : '' ?>" data-bs-toggle="dropdown"><?= $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="expense_import.php"><i class="fa fa-fw fa-file-import text-secondary me-2"></i>Import Statement</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<?php } ?>
|
||||
<a class="dropdown-item ajax-modal" href="#"
|
||||
data-modal-url="<?= buildExportModalUrl('modals/expense/expense_export.php', ['account', 'vendor', 'category', 'client', 'method', 'recurring_expense_id', 'show', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
|
||||
data-modal-url="<?= buildExportModalUrl('modals/expense/expense_export.php', ['account', 'vendor', 'category', 'client', 'method', 'paid_by', 'recurring_expense_id', 'show', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
|
||||
<i class="fa fa-fw fa-download text-secondary me-2"></i>Export
|
||||
</a>
|
||||
<a class="dropdown-item" href="recurring_expenses.php"><i class="fa fa-fw fa-redo-alt text-secondary me-2"></i>Recurring Expenses</a>
|
||||
@@ -169,6 +177,9 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
|
||||
<?php if ($recurring_filter) { ?>
|
||||
<input type="hidden" name="recurring_expense_id" value="<?= $recurring_filter ?>">
|
||||
<?php } ?>
|
||||
<?php if ($paid_by_filter) { ?>
|
||||
<input type="hidden" name="paid_by" value="<?= $paid_by_filter ?>">
|
||||
<?php } ?>
|
||||
<div class="row g-2 align-items-center">
|
||||
<div class="col-lg-3 col-md-6">
|
||||
<div class="input-group">
|
||||
@@ -232,6 +243,7 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/expense/expense_bulk_edit.php?field=method" data-bulk="true"><i class="fas fa-fw fa-credit-card text-secondary me-2"></i>Set Payment Method</a>
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/expense/expense_bulk_edit.php?field=client" data-bulk="true"><i class="fas fa-fw fa-user text-secondary me-2"></i>Set Client</a>
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/expense/expense_bulk_edit.php?field=billable" data-bulk="true"><i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Set Billable</a>
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/expense/expense_reimburse.php" data-bulk="true"><i class="fas fa-fw fa-hand-holding-usd text-secondary me-2"></i>Reimburse</a>
|
||||
<?php if ($can_delete) { ?>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item text-danger text-bold ajax-modal" href="#" data-modal-url="modals/expense/expense_bulk_delete.php" data-bulk="true"><i class="fas fa-fw fa-trash me-2"></i>Delete</a>
|
||||
@@ -277,7 +289,7 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
|
||||
<!-- Cut the list - counted over what the filters above leave -->
|
||||
<nav class="nav nav-pills itflow-asset-tabs mt-2 flex-nowrap overflow-auto">
|
||||
<?php foreach ($shows as $key => $s) {
|
||||
$alarm = $key === 'no_receipt' && $counts[$key]; ?>
|
||||
$alarm = in_array($key, ['no_receipt', 'to_reimburse'], true) && $counts[$key]; ?>
|
||||
<a class="nav-link text-nowrap <?= $show === $key ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['show' => $key])) ?>"<?= !empty($s['title']) ? ' title="' . escapeHtml($s['title']) . '"' : '' ?>>
|
||||
<?php if (!empty($s['icon'])) { ?><i class="fas fa-fw <?= $s['icon'] ?> me-1"></i><?php } ?><?= $s['label'] ?>
|
||||
<span class="badge rounded-pill ms-1 <?= $alarm ? 'text-bg-warning' : '' ?>"><?= $counts[$key] ?></span>
|
||||
@@ -290,8 +302,30 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
|
||||
<a class="ms-2" href="<?= escapeHtml($filter_url(['recurring_expense_id' => ''])) ?>">Clear</a>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<?php if ($paid_by_filter) { ?>
|
||||
<div class="small text-body-secondary mt-2">
|
||||
<i class="fas fa-filter me-1"></i>Paid personally by <?= escapeHtml((string) getFieldById('users', $paid_by_filter, 'user_name')) ?>
|
||||
<a class="ms-2" href="<?= escapeHtml($filter_url(['paid_by' => ''])) ?>">Clear</a>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<?php if ($owed) { ?>
|
||||
<!-- Who is owed, to pay back -->
|
||||
<div class="list-group list-group-flush border-bottom">
|
||||
<?php foreach ($owed as $owed_id => $agent) { ?>
|
||||
<div class="list-group-item d-flex flex-wrap align-items-center gap-2 bg-warning-subtle">
|
||||
<i class="fas fa-hand-holding-usd text-warning-emphasis"></i>
|
||||
<span class="flex-grow-1"><strong><?= escapeHtml($agent['user_name']) ?></strong> is owed <strong class="itflow-money"><?= $stat_money($agent['total']) ?></strong>
|
||||
<span class="text-body-secondary">for <?= $agent['count'] ?> expense<?= $agent['count'] === 1 ? '' : 's' ?><?= $agent['oldest'] > 1 ? ', the oldest ' . $agent['oldest'] . ' days ago' : ($agent['oldest'] === 1 ? ', the oldest yesterday' : ' from today') ?></span></span>
|
||||
<?php if ($can_edit) { ?>
|
||||
<button type="button" class="btn btn-sm btn-success ajax-modal" data-modal-size="lg" data-modal-url="modals/expense/expense_reimburse.php?user_id=<?= $owed_id ?>"><i class="fas fa-hand-holding-usd me-1"></i>Reimburse</button>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle mb-0 itflow-billing-table">
|
||||
<thead class="<?= $num_rows[0] ? '' : 'd-none' ?> text-nowrap table-light">
|
||||
@@ -357,8 +391,17 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="text-nowrap">
|
||||
<?= escapeHtml($row['account_name'] ?: '-') ?>
|
||||
<?php if ($row['expense_payment_method']) { ?><div class="small text-body-secondary"><?= escapeHtml($row['expense_payment_method']) ?></div><?php } ?>
|
||||
<?php if (intval($row['expense_paid_by'])) { ?>
|
||||
<a class="text-reset" href="<?= escapeHtml($filter_url(['paid_by' => intval($row['expense_paid_by'])])) ?>" title="Paid personally - their expenses"><i class="fas fa-hand-holding-usd text-body-secondary me-1"></i><?= escapeHtml($row['paid_by_name'] ?: 'An agent') ?></a>
|
||||
<?php if ($row['expense_reimbursement_id']) { ?>
|
||||
<div class="small"><a class="text-success-emphasis ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/expense/expense_reimbursement.php?id=<?= intval($row['expense_reimbursement_id']) ?>"><i class="fas fa-check-circle me-1"></i>Paid back</a></div>
|
||||
<?php } elseif ($row_amount > 0) { ?>
|
||||
<div class="small text-warning-emphasis">To reimburse</div>
|
||||
<?php } ?>
|
||||
<?php } else { ?>
|
||||
<?= escapeHtml($row['account_name'] ?: '-') ?>
|
||||
<?php if ($row['expense_payment_method']) { ?><div class="small text-body-secondary"><?= escapeHtml($row['expense_payment_method']) ?></div><?php } ?>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="text-end itflow-money text-nowrap">
|
||||
<span class="fw-semibold <?= $row_amount < 0 ? 'text-success-emphasis' : '' ?>"><?= escapeHtml(billingMoney($row_amount, $row_currency)) ?></span>
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
/*
|
||||
* An expense's quick look - the receipt (shown right in the window when it
|
||||
* is a photo or a PDF, or attached here when there isn't one), who it was
|
||||
* paid to and for what, the account and how it was paid, the client, who
|
||||
* paid to and for what, the account and how it was paid (or the agent who
|
||||
* paid it personally, and whether they are paid back), the client, who
|
||||
* entered it, the refund it is or the refunds against it, billing it on to
|
||||
* the client (the invoice it is on, with the margin, or what it will bill
|
||||
* at), and the stock deliveries it paid for. Opened from the expenses list, the vendor's page,
|
||||
@@ -24,7 +25,10 @@ $expense_id = intval($row['expense_id']);
|
||||
$client_id = intval($row['expense_client_id']);
|
||||
$can_edit = lookupUserPermission('module_financial') >= 2;
|
||||
$can_delete = lookupUserPermission('module_financial') >= 3;
|
||||
$is_transfer = !empty($row['transfer_id']);
|
||||
$is_transfer = !empty($row['transfer_id']) || !empty($row['reimbursement_out_id']);
|
||||
$is_payback = !empty($row['reimbursement_out_id']);
|
||||
$paid_by = intval($row['expense_paid_by']);
|
||||
$to_reimburse = $paid_by && !$row['expense_reimbursement_id'] && floatval($row['expense_amount']) > 0;
|
||||
$amount = floatval($row['expense_amount']);
|
||||
$currency = (string) $row['expense_currency_code'];
|
||||
$receipt_kind = $row['expense_receipt'] && expenseReceiptPath($row['expense_receipt']) !== '' ? expenseReceiptKind($row['expense_receipt']) : '';
|
||||
@@ -62,7 +66,7 @@ ob_start();
|
||||
<?= vendorTile($row['vendor_name'] ?: 'Transfer', 'lg') ?>
|
||||
<div class="min-w-0 flex-grow-1">
|
||||
<h5 class="modal-title d-flex flex-wrap align-items-center column-gap-2">
|
||||
<span class="fw-semibold text-break"><?= escapeHtml($is_transfer ? 'Transfer out' : ($row['vendor_name'] ?: 'No vendor')) ?></span>
|
||||
<span class="fw-semibold text-break"><?= escapeHtml($is_payback ? 'Paid back to ' . ($row['reimbursed_to_name'] ?: 'an agent') : ($is_transfer ? 'Transfer out' : ($row['vendor_name'] ?: 'No vendor'))) ?></span>
|
||||
<?php if ($amount < 0) { ?><span class="badge rounded-pill text-bg-success fw-normal fs-6">Refund</span><?php } ?>
|
||||
</h5>
|
||||
<div class="small text-body-secondary mt-1"><?= escapeHtml(implode(' · ', array_filter([date('M j, Y', strtotime($row['expense_date'])), $row['category_name']]))) ?></div>
|
||||
@@ -76,7 +80,10 @@ ob_start();
|
||||
|
||||
<div class="modal-body">
|
||||
|
||||
<?php if ($is_transfer) { ?>
|
||||
<?php if ($is_payback) { ?>
|
||||
<div class="alert alert-info small mb-3"><i class="fas fa-hand-holding-usd me-2"></i>This is money paid back to <?= escapeHtml($row['reimbursed_to_name'] ?: 'an agent') ?> for what they paid personally -
|
||||
<a href="#" class="ajax-modal" data-modal-size="lg" data-modal-url="modals/expense/expense_reimbursement.php?id=<?= intval($row['reimbursement_out_id']) ?>">open the reimbursement</a> to see or undo it.</div>
|
||||
<?php } elseif ($is_transfer) { ?>
|
||||
<div class="alert alert-info small mb-3"><i class="fas fa-exchange-alt me-2"></i>This is the out side of a transfer between accounts - it is changed or deleted from <a href="transfers.php">Transfers</a>.</div>
|
||||
<?php } ?>
|
||||
|
||||
@@ -120,10 +127,24 @@ ob_start();
|
||||
<i class="fas fa-fw fa-list"></i>
|
||||
<span><?= expenseCategoryDot($row['category_color']) ?><?= escapeHtml($row['category_name'] ?: 'No category') ?></span>
|
||||
</div>
|
||||
<div class="itflow-glance-item" title="Paid from">
|
||||
<i class="fas fa-fw fa-piggy-bank"></i>
|
||||
<span><?= escapeHtml($row['account_name'] ?: 'No account') ?><?= $row['expense_payment_method'] ? ' <span class="text-body-secondary">· ' . escapeHtml($row['expense_payment_method']) . '</span>' : '' ?></span>
|
||||
</div>
|
||||
<?php if ($paid_by) { ?>
|
||||
<div class="itflow-glance-item" title="Paid personally">
|
||||
<i class="fas fa-fw fa-hand-holding-usd"></i>
|
||||
<span>
|
||||
Paid personally by <?= escapeHtml($row['paid_by_name'] ?: 'an agent since deleted') ?><?= $row['expense_payment_method'] ? ' <span class="text-body-secondary">· ' . escapeHtml($row['expense_payment_method']) . '</span>' : '' ?>
|
||||
<?php if ($row['expense_reimbursement_id']) { ?>
|
||||
<span class="d-block small"><a href="#" class="ajax-modal text-success-emphasis" data-modal-size="lg" data-modal-url="modals/expense/expense_reimbursement.php?id=<?= intval($row['expense_reimbursement_id']) ?>"><i class="fas fa-check-circle me-1"></i>Paid back <?= escapeHtml(date('M j, Y', strtotime($row['reimbursement_date']))) ?><?= $row['reimbursed_account_name'] ? ' from ' . escapeHtml($row['reimbursed_account_name']) : '' ?></a></span>
|
||||
<?php } elseif ($to_reimburse) { ?>
|
||||
<span class="d-block small text-warning-emphasis fw-semibold">To reimburse</span>
|
||||
<?php } ?>
|
||||
</span>
|
||||
</div>
|
||||
<?php } else { ?>
|
||||
<div class="itflow-glance-item" title="Paid from">
|
||||
<i class="fas fa-fw fa-piggy-bank"></i>
|
||||
<span><?= escapeHtml($row['account_name'] ?: 'No account') ?><?= $row['expense_payment_method'] ? ' <span class="text-body-secondary">· ' . escapeHtml($row['expense_payment_method']) . '</span>' : '' ?></span>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<?php if ($row['expense_reference']) { ?>
|
||||
<div class="itflow-glance-item" title="Reference">
|
||||
<i class="fas fa-fw fa-hashtag"></i>
|
||||
@@ -237,6 +258,9 @@ ob_start();
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<?php if ($to_reimburse && $can_edit) { ?>
|
||||
<button type="button" class="btn btn-outline-success ajax-modal" data-modal-size="lg" data-modal-url="modals/expense/expense_reimburse.php?expense_ids[]=<?= $expense_id ?>"><i class="fas fa-hand-holding-usd"></i><span class="d-none d-sm-inline ms-2">Reimburse</span></button>
|
||||
<?php } ?>
|
||||
<?php if ($can_unbill) { ?>
|
||||
<a class="btn btn-outline-secondary confirm-link" href="post.php?expense_unbill=<?= $expense_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
|
||||
data-confirm-text="<?= $row['invoice_status'] === 'Cancelled' ? escapeHtml($row['invoice_prefix'] . $row['invoice_number']) . ' is cancelled, so its line stays on it' : 'Its line comes off ' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?> and it waits to be billed again."><i class="fas fa-unlink"></i><span class="d-none d-sm-inline ms-2">Take off Invoice</span></a>
|
||||
|
||||
@@ -14,6 +14,8 @@ $client_filter = intval($_GET['client'] ?? 0);
|
||||
$method_filter = (string) ($_GET['method'] ?? '');
|
||||
$recurring_filter = intval($_GET['recurring_expense_id'] ?? 0);
|
||||
$recurring_filter_row = $recurring_filter ? recurringExpenseRow($recurring_filter) : null;
|
||||
$paid_by_filter = intval($_GET['paid_by'] ?? 0);
|
||||
$paid_by_name = $paid_by_filter ? getFieldById('users', $paid_by_filter, 'user_name') : null;
|
||||
$shows = expenseShows();
|
||||
$show_filter = isset($shows[$_GET['show'] ?? '']) ? (string) ($_GET['show'] ?? '') : '';
|
||||
|
||||
@@ -43,6 +45,10 @@ ob_start();
|
||||
<input type="hidden" name="recurring_expense_id" value="<?= $recurring_filter ?>">
|
||||
<div class="small text-body-secondary mb-3"><i class="fas fa-redo-alt me-1"></i>Only what <?= escapeHtml(recurringExpenseLabel($recurring_filter_row)) ?> recorded</div>
|
||||
<?php } ?>
|
||||
<?php if ($paid_by_name !== null) { ?>
|
||||
<input type="hidden" name="paid_by" value="<?= $paid_by_filter ?>">
|
||||
<div class="small text-body-secondary mb-3"><i class="fas fa-hand-holding-usd me-1"></i>Only what <?= escapeHtml($paid_by_name) ?> paid personally</div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Search</label>
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
* $form_vendor_id the vendor a new one starts with (0 to pick)
|
||||
* $form_client_id the client a new one starts with (0 for none)
|
||||
*
|
||||
* Posts date, amount, vendor, category, account, payment_method, client_id,
|
||||
* reference, description, the receipt as `file`, and refund_of (refund) or
|
||||
* receipt_remove (edit). Picking a vendor on a new expense fills in the
|
||||
* Posts date, amount, vendor, category, account ('personal' with paid_by
|
||||
* when an agent paid it themselves), payment_method, client_id, reference,
|
||||
* description, billable and markup, the receipt as `file`, and refund_of
|
||||
* (refund) or receipt_remove (edit). Picking a vendor on a new expense fills in the
|
||||
* category, account and payment method of the last expense with them,
|
||||
* unless those were changed by hand.
|
||||
*
|
||||
@@ -68,6 +69,14 @@ while ($row = mysqli_fetch_assoc($sql)) {
|
||||
}
|
||||
$form_receipt = $form_edit ? $form_value('expense_receipt') : '';
|
||||
|
||||
// Paid personally by an agent, to be paid back - not a refund. Once paid back, who paid stays.
|
||||
$form_paid_by = $form_row && !$form_refund ? intval($form_row['expense_paid_by']) : 0;
|
||||
$form_reimbursed = $form_edit && !empty($form_row['expense_reimbursement_id']);
|
||||
$form_payers = $form_refund ? [] : expensePayers($form_paid_by);
|
||||
if ($form_refund && !$form_account) {
|
||||
$form_account = intval($config_default_expense_account);
|
||||
}
|
||||
|
||||
// Billed on to the client - not for a refund. One already on an invoice stays billed to that client.
|
||||
$form_billed = $form_edit && !empty($form_row['expense_invoice_id']);
|
||||
$form_billable = $form_row && !$form_refund ? intval($form_row['expense_billable']) === 1 : false;
|
||||
@@ -157,13 +166,19 @@ $form_markup = $form_row && !$form_refund ? floatval($form_row['expense_markup']
|
||||
<label class="form-label">Paid from <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 data-expense-account>
|
||||
<select class="form-select select2" name="account" required data-expense-account <?= $form_reimbursed ? 'disabled' : '' ?>>
|
||||
<option value="">- Which account -</option>
|
||||
<?php foreach ($form_accounts as $account_id => $account) { ?>
|
||||
<option value="<?= $account_id ?>" <?= $form_account === $account_id ? 'selected' : '' ?> data-icon="fas fa-piggy-bank"
|
||||
<option value="<?= $account_id ?>" <?= !$form_paid_by && $form_account === $account_id ? 'selected' : '' ?> data-icon="fas fa-piggy-bank"
|
||||
data-description="<?= escapeHtml(billingMoney($account['balance'], $account['account_currency_code'])) ?><?= $account['account_archived_at'] ? ' - archived' : '' ?>"><?= escapeHtml($account['account_name']) ?></option>
|
||||
<?php } ?>
|
||||
<?php if (!$form_refund) { ?>
|
||||
<option value="personal" <?= $form_paid_by ? 'selected' : '' ?> data-icon="fas fa-hand-holding-usd" data-description="An agent paid it - to pay them back">Paid personally</option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
<?php if ($form_reimbursed) { ?>
|
||||
<input type="hidden" name="account" value="personal">
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -180,6 +195,32 @@ $form_markup = $form_row && !$form_refund ? floatval($form_row['expense_markup']
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!$form_refund) { ?>
|
||||
<div class="col-md-7" data-expense-payer <?= $form_paid_by ? '' : 'hidden' ?>>
|
||||
<label class="form-label">Paid personally by <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-hand-holding-usd"></i></span>
|
||||
<select class="form-select select2" name="paid_by" data-expense-paid-by <?= $form_reimbursed ? 'disabled' : '' ?>>
|
||||
<option value="">- Who paid it -</option>
|
||||
<?php foreach ($form_payers as $payer_id => $payer_name) { ?>
|
||||
<option value="<?= $payer_id ?>" <?= ($form_paid_by ?: intval($session_user_id)) === $payer_id ? 'selected' : '' ?>><?= escapeHtml($payer_name) ?><?= $payer_id === intval($session_user_id) ? ' (me)' : '' ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
<?php if ($form_reimbursed) { ?>
|
||||
<input type="hidden" name="paid_by" value="<?= $form_paid_by ?>">
|
||||
<?php } ?>
|
||||
</div>
|
||||
<div class="form-text">
|
||||
<?php if ($form_reimbursed) { ?>
|
||||
Paid back on <?= escapeHtml(date('M j, Y', strtotime($form_row['reimbursement_date']))) ?> from <?= escapeHtml($form_row['reimbursed_account_name'] ?: 'an account') ?> - undo that reimbursement to change who paid it.
|
||||
<?php } else { ?>
|
||||
It counts as spent on its date, and comes out of an account when they are paid back - from To reimburse on the expenses list.
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-5 d-none d-md-block" data-expense-payer <?= $form_paid_by ? '' : 'hidden' ?>></div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="col-md-7">
|
||||
<label class="form-label">Client</label>
|
||||
<div class="input-group">
|
||||
@@ -263,6 +304,27 @@ $form_markup = $form_row && !$form_refund ? floatval($form_row['expense_markup']
|
||||
|
||||
<?php if (!$form_refund) { ?>
|
||||
<script>
|
||||
(function () {
|
||||
// Paid personally: who paid it, instead of an account
|
||||
var root = document.getElementById(<?= json_encode($form_id) ?>);
|
||||
if (!root || root.dataset.payerWired) {
|
||||
return;
|
||||
}
|
||||
root.dataset.payerWired = '1';
|
||||
var account = root.querySelector('[data-expense-account]');
|
||||
var paidBy = root.querySelector('[data-expense-paid-by]');
|
||||
function update() {
|
||||
var personal = account.value === 'personal';
|
||||
root.querySelectorAll('[data-expense-payer]').forEach(function (el) {
|
||||
el.hidden = !personal;
|
||||
});
|
||||
paidBy.required = personal;
|
||||
}
|
||||
account.addEventListener('change', update);
|
||||
update();
|
||||
})();
|
||||
</script>
|
||||
<script>
|
||||
(function () {
|
||||
// Billing shows once there is a client; what it bills follows the amount and markup
|
||||
var root = document.getElementById(<?= json_encode($form_id) ?>);
|
||||
|
||||
74
agent/modals/expense/expense_import_rules.php
Normal file
74
agent/modals/expense/expense_import_rules.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* The merchants Import Statement remembers - what a line starting with
|
||||
* these words was matched to last time: the vendor, category and client,
|
||||
* 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_used_count, import_rule_billable, vendor_name, category_name, client_name
|
||||
FROM expense_import_rules
|
||||
LEFT JOIN vendors ON vendor_id = import_rule_vendor_id
|
||||
LEFT JOIN categories ON category_id = import_rule_category_id
|
||||
LEFT JOIN clients ON client_id = import_rule_client_id
|
||||
ORDER BY import_rule_used_count DESC, import_rule_match ASC LIMIT 500");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$rules[] = $row;
|
||||
}
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title"><i class="fas fa-fw fa-magic me-2"></i>Remembered Merchants <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 statement line 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">Line starts</th>
|
||||
<th>Vendor</th>
|
||||
<th>Category</th>
|
||||
<th>Client</th>
|
||||
<th class="text-end">Used</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($rules as $rule) { ?>
|
||||
<tr>
|
||||
<td class="ps-3 font-monospace"><?= escapeHtml($rule['import_rule_match']) ?></td>
|
||||
<td><?= escapeHtml($rule['vendor_name'] ?: 'A vendor since deleted') ?></td>
|
||||
<td><?= escapeHtml($rule['category_name'] ?: '-') ?></td>
|
||||
<td><?= escapeHtml($rule['client_name'] ?: '-') ?><?= intval($rule['import_rule_billable']) ? ' <span class="badge bg-warning-subtle text-warning-emphasis fw-normal">bill on</span>' : '' ?></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?expense_import_rule_delete=<?= intval($rule['import_rule_id']) ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
|
||||
data-confirm-text="Lines 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';
|
||||
147
agent/modals/expense/expense_reimburse.php
Normal file
147
agent/modals/expense/expense_reimburse.php
Normal file
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Reimburse - pay an agent back for what they paid personally. Their
|
||||
* expenses not paid back yet, ticked, with the account the money comes
|
||||
* from, the date, how and a reference; the total follows the ticks.
|
||||
* ?user_id= for one agent's, or ?expense_ids[]= from the list's bulk menu
|
||||
* (one agent's at a time). Posts expense_reimburse.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$user_id = intval($_GET['user_id'] ?? 0);
|
||||
$picked = array_values(array_unique(array_filter(array_map('intval', (array) ($_GET['expense_ids'] ?? [])))));
|
||||
if (!$user_id && $picked) {
|
||||
$agents = expenseToReimburse(0, $picked);
|
||||
if (count($agents) > 1) {
|
||||
exit(json_encode(['error' => 'Those were paid by ' . count($agents) . ' different agents - tick one agent\'s expenses at a time.']));
|
||||
}
|
||||
$user_id = $agents ? intval(array_key_first($agents)) : 0;
|
||||
}
|
||||
$agent = $user_id ? (expenseToReimburse($user_id)[$user_id] ?? null) : null;
|
||||
if (!$agent) {
|
||||
exit(json_encode(['error' => $picked ? 'None of those are waiting to be paid back - they were paid from an account, or paid back already.' : 'Nothing is waiting to be paid back to them.']));
|
||||
}
|
||||
|
||||
$accounts = paymentAccounts();
|
||||
$methods = paymentMethods();
|
||||
$default_account = intval($config_default_expense_account);
|
||||
$currency = (string) $session_company_currency;
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title text-truncate"><i class="fas fa-fw fa-hand-holding-usd me-2"></i>Reimburse <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($agent['user_name']) ?></span></h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<form action="post.php" method="post" autocomplete="off" id="expenseReimburse">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<input type="hidden" name="user_id" value="<?= $user_id ?>">
|
||||
|
||||
<div class="modal-body p-0">
|
||||
<div class="px-3 py-2 small text-body-secondary border-bottom">
|
||||
What <?= escapeHtml($agent['user_name']) ?> paid for personally and hasn't been paid back for. They count as spent on their own dates; the money comes out of the account on the date it is paid back.
|
||||
</div>
|
||||
<div class="list-group list-group-flush" style="max-height: 20rem; overflow-y: auto;">
|
||||
<?php foreach ($agent['expenses'] as $expense_id => $expense) { ?>
|
||||
<label class="list-group-item d-flex align-items-center gap-3 mb-0" for="reimburse<?= $expense_id ?>">
|
||||
<input class="form-check-input flex-shrink-0 mt-0" type="checkbox" name="expense_ids[]" value="<?= $expense_id ?>" id="reimburse<?= $expense_id ?>"
|
||||
<?= !$picked || in_array($expense_id, $picked, true) ? 'checked' : '' ?> data-reimburse data-amount="<?= floatval($expense['expense_amount']) ?>">
|
||||
<span class="flex-grow-1 min-w-0">
|
||||
<span class="d-block text-truncate"><?= escapeHtml($expense['vendor_name']) ?><?= trim((string) $expense['expense_description']) !== '' ? ' <span class="text-body-secondary">- ' . escapeHtml(truncate(strtok((string) $expense['expense_description'], "\n"), 60)) . '</span>' : '' ?></span>
|
||||
<span class="small text-body-secondary"><?= escapeHtml(implode(' · ', array_filter([$expense['expense_date'], $expense['category_name'], $expense['client_name']]))) ?></span>
|
||||
</span>
|
||||
<span class="itflow-money text-nowrap fw-semibold"><?= escapeHtml(billingMoney($expense['expense_amount'], $expense['expense_currency_code'])) ?></span>
|
||||
</label>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<div class="p-3 border-top">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-7">
|
||||
<label class="form-label">Paid back from <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 => $account) { ?>
|
||||
<option value="<?= $account_id ?>" <?= $account_id === $default_account ? 'selected' : '' ?> data-icon="fas fa-piggy-bank"
|
||||
data-description="<?= escapeHtml(billingMoney($account['balance'], $account['account_currency_code'])) ?>"><?= escapeHtml($account['account_name']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<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>
|
||||
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date('Y-m-d') ?>" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-7">
|
||||
<label class="form-label">How</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 were paid -</option>
|
||||
<?php foreach ($methods as $method) { ?>
|
||||
<option value="<?= escapeHtml($method) ?>"><?= escapeHtml($method) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Reference</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-hashtag"></i></span>
|
||||
<input type="text" class="form-control" name="reference" maxlength="200" placeholder="Check or transfer number">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<span class="me-auto small text-body-secondary" data-reimburse-summary></span>
|
||||
<button type="submit" name="expense_reimburse" class="btn btn-primary text-bold" data-reimburse-submit><i class="fas fa-check me-2"></i>Pay Back</button>
|
||||
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var form = document.getElementById('expenseReimburse');
|
||||
if (!form || form.dataset.wired) {
|
||||
return;
|
||||
}
|
||||
form.dataset.wired = '1';
|
||||
var summary = form.querySelector('[data-reimburse-summary]');
|
||||
var submit = form.querySelector('[data-reimburse-submit]');
|
||||
function money(amount) {
|
||||
try {
|
||||
return new Intl.NumberFormat(<?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>, { style: 'currency', currency: <?= json_encode($currency) ?> }).format(amount);
|
||||
} catch (e) {
|
||||
return amount.toFixed(2);
|
||||
}
|
||||
}
|
||||
function update() {
|
||||
var count = 0;
|
||||
var total = 0;
|
||||
form.querySelectorAll('[data-reimburse]').forEach(function (box) {
|
||||
if (box.checked) {
|
||||
count++;
|
||||
total += Number(box.getAttribute('data-amount'));
|
||||
}
|
||||
});
|
||||
summary.textContent = count ? count + ' expense' + (count === 1 ? '' : 's') + ' · ' + money(Math.round(total * 100) / 100) : 'Tick what to pay back';
|
||||
submit.disabled = count === 0;
|
||||
}
|
||||
form.addEventListener('change', update);
|
||||
update();
|
||||
})();
|
||||
</script>
|
||||
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
89
agent/modals/expense/expense_reimbursement.php
Normal file
89
agent/modals/expense/expense_reimbursement.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* A reimbursement's quick look - who was paid back, how much, when, from
|
||||
* which account and how, who entered it, and the expenses it paid back.
|
||||
* Undo takes the money out of the account away and makes the expenses to
|
||||
* reimburse again. Opened from an expense it paid back and Transactions.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_financial');
|
||||
|
||||
$row = reimbursementRow(intval($_GET['id'] ?? 0));
|
||||
if (!$row) {
|
||||
exit(json_encode(['error' => 'That reimbursement no longer exists - it was undone.']));
|
||||
}
|
||||
|
||||
$reimbursement_id = intval($row['reimbursement_id']);
|
||||
$currency = (string) $row['reimbursement_currency_code'];
|
||||
$expenses = reimbursementExpenses($reimbursement_id);
|
||||
$can_undo = lookupUserPermission('module_financial') >= 3;
|
||||
$expenses_total = array_sum(array_map(function ($e) { return floatval($e['expense_amount']); }, $expenses));
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
<div class="modal-header bg-dark" data-bs-theme="dark">
|
||||
<div class="d-flex align-items-center gap-3 min-w-0 flex-grow-1">
|
||||
<span class="itflow-asset-icon itflow-asset-icon-lg bg-success-subtle text-success-emphasis" aria-hidden="true"><i class="fas fa-hand-holding-usd"></i></span>
|
||||
<div class="min-w-0 flex-grow-1">
|
||||
<h5 class="modal-title fw-semibold text-break">Paid back to <?= escapeHtml($row['user_name'] ?: 'an agent since deleted') ?></h5>
|
||||
<div class="small text-body-secondary mt-1"><?= escapeHtml(date('M j, Y', strtotime($row['reimbursement_date']))) ?> · <?= count($expenses) ?> expense<?= count($expenses) === 1 ? '' : 's' ?></div>
|
||||
</div>
|
||||
<div class="fs-4 fw-semibold itflow-money text-white"><?= escapeHtml(billingMoney($row['reimbursement_amount'], $currency)) ?></div>
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white ms-3" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<div class="row g-2 itflow-asset-glance">
|
||||
<div class="col-sm-6">
|
||||
<div class="itflow-glance-item" title="Paid from">
|
||||
<i class="fas fa-fw fa-piggy-bank"></i>
|
||||
<span><?= escapeHtml($row['account_name'] ?: 'An account since deleted') ?><?= $row['reimbursement_payment_method'] ? ' <span class="text-body-secondary">· ' . escapeHtml($row['reimbursement_payment_method']) . '</span>' : '' ?></span>
|
||||
</div>
|
||||
<?php if ($row['reimbursement_reference']) { ?>
|
||||
<div class="itflow-glance-item" title="Reference">
|
||||
<i class="fas fa-fw fa-hashtag"></i>
|
||||
<span class="font-monospace text-break"><?= escapeHtml($row['reimbursement_reference']) ?></span>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<div class="itflow-glance-item" title="Entered">
|
||||
<i class="fas fa-fw fa-clock"></i>
|
||||
<span><span title="<?= escapeHtml($row['reimbursement_created_at']) ?>"><?= timeAgo($row['reimbursement_created_at']) ?></span><?php if ($row['created_by_name']) { ?> <span class="text-body-secondary">by <?= escapeHtml($row['created_by_name']) ?></span><?php } ?></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<div class="small fw-semibold text-uppercase text-body-secondary mb-1">What it paid back</div>
|
||||
<?php foreach ($expenses as $expense) { ?>
|
||||
<div class="d-flex justify-content-between gap-2 small py-1 border-bottom">
|
||||
<a class="text-truncate ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/expense/expense.php?id=<?= intval($expense['expense_id']) ?>">
|
||||
<span class="text-body-secondary me-1"><?= escapeHtml($expense['expense_date']) ?></span><?= escapeHtml($expense['vendor_name'] ?: 'Expense') ?><?= trim((string) $expense['expense_description']) !== '' ? ' - ' . escapeHtml(truncate(strtok((string) $expense['expense_description'], "\n"), 50)) : '' ?>
|
||||
</a>
|
||||
<span class="itflow-money text-nowrap"><?= escapeHtml(billingMoney($expense['expense_amount'], $expense['expense_currency_code'])) ?></span>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<?php if (!$expenses) { ?>
|
||||
<div class="small text-body-secondary">The expenses it paid back have since been deleted.</div>
|
||||
<?php } elseif (abs($expenses_total - floatval($row['reimbursement_amount'])) >= 0.005) { ?>
|
||||
<div class="small text-warning-emphasis mt-2"><i class="fas fa-exclamation-triangle me-1"></i>They come to <?= escapeHtml(billingMoney($expenses_total, $currency)) ?> now - one was changed or deleted after it was paid back.</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<?php if ($can_undo) { ?>
|
||||
<a class="btn btn-outline-danger confirm-link me-auto" href="post.php?expense_reimbursement_delete=<?= $reimbursement_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
|
||||
data-confirm-text="The <?= escapeHtml(billingMoney($row['reimbursement_amount'], $currency)) ?> comes back off <?= escapeHtml($row['account_name'] ?: 'the account') ?>, and its expenses are to reimburse again."><i class="fas fa-undo-alt me-2"></i>Undo</a>
|
||||
<?php } ?>
|
||||
<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';
|
||||
@@ -12,7 +12,7 @@ if (isset($_GET['account']) & !empty($_GET['account'])) {
|
||||
}
|
||||
|
||||
// Type Filter
|
||||
$transaction_types_array = ['Revenue', 'Payment', 'Expense', 'Transfer In', 'Transfer Out'];
|
||||
$transaction_types_array = ['Revenue', 'Payment', 'Expense', 'Transfer In', 'Transfer Out', 'Reimbursement'];
|
||||
if (isset($_GET['type']) & !empty($_GET['type']) && in_array($_GET['type'], $transaction_types_array)) {
|
||||
$type_filter = $_GET['type'];
|
||||
} else {
|
||||
|
||||
@@ -153,7 +153,7 @@ if (isset($_POST['bulk_edit_expenses'])) {
|
||||
} elseif ($field === 'account') {
|
||||
$accounts = paymentAccounts();
|
||||
if (isset($accounts[intval($value)])) {
|
||||
$set = "expense_account_id = " . intval($value);
|
||||
$set = "expense_account_id = " . intval($value) . ", expense_paid_by = 0";
|
||||
$label = "the account to " . $accounts[intval($value)]['account_name'];
|
||||
}
|
||||
} elseif ($field === 'client') {
|
||||
@@ -203,6 +203,7 @@ if (isset($_POST['bulk_edit_expenses'])) {
|
||||
}
|
||||
// Billed ones keep their client and stay billed; only a client's expenses can be billed on
|
||||
if (($row['expense_invoice_id'] && in_array($field, ['client', 'billable'], true))
|
||||
|| ($row['expense_reimbursement_id'] && $field === 'account')
|
||||
|| ($field === 'billable' && $value === 'yes' && (!intval($row['expense_client_id']) || floatval($row['expense_amount']) <= 0))) {
|
||||
$skipped++;
|
||||
continue;
|
||||
@@ -215,7 +216,7 @@ if (isset($_POST['bulk_edit_expenses'])) {
|
||||
logAudit("Expense", "Bulk Edit", "$session_name set " . escapeSql($label) . " on $count expense" . ($count === 1 ? '' : 's'));
|
||||
|
||||
flashAlert("Set " . escapeHtml($label) . " on <strong>$count</strong> expense" . ($count === 1 ? '' : 's')
|
||||
. ($skipped ? " - $skipped left as " . ($skipped === 1 ? 'it was' : 'they were') . ($field === 'billable' && $value === 'yes' ? ' (on an invoice already, or not for a client)' : ' (on an invoice already)') : ''),
|
||||
. ($skipped ? " - $skipped left as " . ($skipped === 1 ? 'it was' : 'they were') . ($field === 'billable' && $value === 'yes' ? ' (on an invoice already, or not for a client)' : ($field === 'account' ? ' (paid back to an agent already)' : ' (on an invoice already)')) : ''),
|
||||
$count ? 'success' : 'warning');
|
||||
|
||||
redirect();
|
||||
@@ -276,6 +277,58 @@ if (isset($_POST['bulk_delete_expenses'])) {
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* Pay an agent back for what they paid personally - the ticked expenses
|
||||
* (expense_ids[]) of one agent (user_id), from an account, on a date.
|
||||
*/
|
||||
if (isset($_POST['expense_reimburse'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$user_id = intval($_POST['user_id'] ?? 0);
|
||||
$result = expenseReimburse($user_id, array_unique(array_filter(array_map('intval', (array) ($_POST['expense_ids'] ?? [])))), [
|
||||
'account_id' => intval($_POST['account'] ?? 0),
|
||||
'date' => (string) ($_POST['date'] ?? ''),
|
||||
'payment_method' => (string) ($_POST['payment_method'] ?? ''),
|
||||
'reference' => (string) ($_POST['reference'] ?? ''),
|
||||
'by' => stripslashes($session_name),
|
||||
], $error);
|
||||
if (!$result) {
|
||||
flashAlert(escapeHtml($error), 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
flashAlert('<strong>' . escapeHtml($result['user_name']) . '</strong> paid back ' . escapeHtml(billingMoney($result['amount'], $result['currency']))
|
||||
. ' for ' . ($result['count'] === 1 ? '1 expense' : $result['count'] . ' expenses'));
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
/* Undo a reimbursement - its money out of the account goes, and the expenses are to reimburse again. */
|
||||
if (isset($_GET['expense_reimbursement_delete'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_financial', 3);
|
||||
|
||||
$row = reimbursementDelete(intval($_GET['expense_reimbursement_delete']));
|
||||
if (!$row) {
|
||||
flashAlert('That reimbursement no longer exists', 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
$what = billingMoney($row['reimbursement_amount'], $row['reimbursement_currency_code']) . ' paid back to ' . $row['user_name'] . ' on ' . $row['reimbursement_date'];
|
||||
logAudit("Expense", "Reimbursement Undo", "$session_name undid the " . escapeSql($what), 0, intval($row['reimbursement_id']));
|
||||
|
||||
flashAlert('Undone: <strong>' . escapeHtml($what) . '</strong> - its expenses are to reimburse again', 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isExportRequest('export_expenses')) {
|
||||
|
||||
validateCSRFToken();
|
||||
@@ -288,7 +341,9 @@ if (isExportRequest('export_expenses')) {
|
||||
// The same filters as the expenses list (functions/expenses.php)
|
||||
$where = expenseFiltersSql($_POST, $filter_summary);
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, account_name, client_name, user_name, invoice_prefix, invoice_number
|
||||
$sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, account_name, client_name, user_name, invoice_prefix, invoice_number,
|
||||
(SELECT payer.user_name FROM users AS payer WHERE payer.user_id = expense_paid_by) AS paid_by_name,
|
||||
(SELECT reimbursement_date FROM reimbursements WHERE reimbursement_id = expense_reimbursement_id) AS reimbursement_date
|
||||
FROM expenses " . expenseJoinsSql() . "
|
||||
LEFT JOIN invoices ON invoice_id = expense_invoice_id
|
||||
WHERE $where
|
||||
@@ -307,6 +362,7 @@ if (isExportRequest('export_expenses')) {
|
||||
$markup = rtrim(rtrim(number_format(floatval($row['expense_markup']), 2, '.', ''), '0'), '.') . '%';
|
||||
$row['expense_billing_display'] = $row['expense_invoice_id'] ? "Billed, $markup markup" : (intval($row['expense_billable']) ? "To bill, $markup markup" : '');
|
||||
$row['expense_billed_on'] = $row['expense_invoice_id'] && $row['invoice_number'] !== null ? $row['invoice_prefix'] . $row['invoice_number'] : '';
|
||||
$row['expense_paid_by_display'] = intval($row['expense_paid_by']) ? ($row['paid_by_name'] ?: 'An agent') . ($row['reimbursement_date'] ? ', paid back ' . $row['reimbursement_date'] : ', to reimburse') : '';
|
||||
addExportRow($export, $row);
|
||||
}
|
||||
|
||||
|
||||
181
agent/post/expense_import.php
Normal file
181
agent/post/expense_import.php
Normal file
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - importing a card or bank statement as expenses
|
||||
* (agent/expense_import.php; functions/expense_import.php does the work).
|
||||
*
|
||||
* Upload reads the CSV into the session with a first guess at its columns -
|
||||
* or the columns the account's last statement used, going straight to the
|
||||
* review. Columns sets them; Import brings in the ticked lines, sent from the
|
||||
* review as one JSON field (picks) so a long statement stays under PHP's
|
||||
* max_input_vars.
|
||||
*/
|
||||
|
||||
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
|
||||
|
||||
if (isset($_POST['expense_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 statement is for', 'error');
|
||||
redirect('expense_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('expense_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('expense_import.php');
|
||||
}
|
||||
$read = expenseImportRead($file['tmp_name'], $error);
|
||||
if (!$read) {
|
||||
flashAlert(escapeHtml($error), 'error');
|
||||
redirect('expense_import.php');
|
||||
}
|
||||
|
||||
// The columns the account's last statement used, if it looks the same
|
||||
$map = expenseImportSavedMap($account_id, $read['header']);
|
||||
$_SESSION['expense_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('expense_import.php?step=' . ($map ? 'review' : 'columns'));
|
||||
|
||||
}
|
||||
|
||||
if (isset($_POST['expense_import_columns'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$import = $_SESSION['expense_import'] ?? null;
|
||||
if (!$import) {
|
||||
flashAlert('Upload the statement again - the one you started is gone', 'error');
|
||||
redirect('expense_import.php');
|
||||
}
|
||||
$map = expenseImportMapClean($_POST, count($import['header']));
|
||||
if (!$map) {
|
||||
flashAlert('Pick the columns with the date, the description and the amount', 'error');
|
||||
redirect('expense_import.php?step=columns');
|
||||
}
|
||||
$lines = expenseImportLines($import['rows'], $map);
|
||||
if (!array_filter($lines, function ($line) { return $line['problem'] === ''; })) {
|
||||
$_SESSION['expense_import']['guess'] = $map;
|
||||
flashAlert("None of the lines read with those columns - check the date format and the amount", 'error');
|
||||
redirect('expense_import.php?step=columns');
|
||||
}
|
||||
|
||||
$_SESSION['expense_import']['map'] = $map;
|
||||
$_SESSION['expense_import']['guess'] = $map;
|
||||
$_SESSION['expense_import']['remembered'] = false;
|
||||
expenseImportSaveMap($import['account_id'], $import['header'], $map);
|
||||
|
||||
redirect('expense_import.php?step=review');
|
||||
|
||||
}
|
||||
|
||||
if (isset($_POST['expense_import_save'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$import = $_SESSION['expense_import'] ?? null;
|
||||
if (!$import || !$import['map']) {
|
||||
flashAlert('Upload the statement again - the one you started is gone', 'error');
|
||||
redirect('expense_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']),
|
||||
'vendor' => (string) ($pick['vendor'] ?? ''),
|
||||
'new_vendor' => (string) ($pick['new_vendor'] ?? ''),
|
||||
'category' => intval($pick['category'] ?? 0),
|
||||
'client' => intval($pick['client'] ?? 0),
|
||||
'billable' => !empty($pick['billable']),
|
||||
];
|
||||
}
|
||||
}
|
||||
$result = expenseImportSave($import, $picks, $error);
|
||||
if (!$result) {
|
||||
flashAlert(escapeHtml($error), 'error');
|
||||
redirect('expense_import.php?step=review');
|
||||
}
|
||||
unset($_SESSION['expense_import']);
|
||||
|
||||
$account_name = (string) getFieldById('accounts', intval($import['account_id']), 'account_name');
|
||||
$currency = (string) getFieldById('accounts', intval($import['account_id']), 'account_currency_code');
|
||||
logAudit("Expense", "Import", "$session_name imported " . $result['imported'] . " expense" . ($result['imported'] === 1 ? '' : 's') . " from " . escapeSql($import['file_name'] . " for $account_name")
|
||||
. ($result['vendors'] ? ", adding " . $result['vendors'] . " vendor" . ($result['vendors'] === 1 ? '' : 's') : ''));
|
||||
|
||||
$notes = [];
|
||||
if ($result['vendors']) {
|
||||
$notes[] = $result['vendors'] . ' new vendor' . ($result['vendors'] === 1 ? '' : 's');
|
||||
}
|
||||
if ($result['linked']) {
|
||||
$notes[] = $result['linked'] . ' matched to ' . ($result['linked'] === 1 ? 'an expense' : 'expenses') . ' entered already';
|
||||
}
|
||||
if ($result['skipped']) {
|
||||
$notes[] = $result['skipped'] . ' imported before';
|
||||
}
|
||||
flashAlert('<strong>' . $result['imported'] . ' expense' . ($result['imported'] === 1 ? '' : 's') . '</strong> imported - ' . escapeHtml(billingMoney($result['total'], $currency ?: $session_company_currency))
|
||||
. ($notes ? ' · ' . escapeHtml(implode(', ', $notes)) : ''));
|
||||
|
||||
if (!$result['imported']) {
|
||||
redirect('expenses.php');
|
||||
}
|
||||
redirect('expenses.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['expense_import_discard'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
unset($_SESSION['expense_import']);
|
||||
|
||||
redirect('expense_import.php');
|
||||
|
||||
}
|
||||
|
||||
/* Forget what a merchant was matched to. */
|
||||
if (isset($_GET['expense_import_rule_delete'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_financial', 2);
|
||||
|
||||
$rule_id = intval($_GET['expense_import_rule_delete']);
|
||||
$match = getFieldById('expense_import_rules', $rule_id, 'import_rule_match');
|
||||
mysqli_query($mysqli, "DELETE FROM expense_import_rules WHERE import_rule_id = $rule_id");
|
||||
if ($match !== null) {
|
||||
logAudit("Expense", "Import Rule Delete", "$session_name removed the statement 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();
|
||||
|
||||
}
|
||||
@@ -26,7 +26,7 @@ if (isExportRequest('export_transactions')) {
|
||||
$category = intval($_POST['category']);
|
||||
|
||||
// Type Filter
|
||||
$transaction_types_array = ['Revenue', 'Payment', 'Expense', 'Transfer In', 'Transfer Out'];
|
||||
$transaction_types_array = ['Revenue', 'Payment', 'Expense', 'Transfer In', 'Transfer Out', 'Reimbursement'];
|
||||
if (!empty($_POST['type']) && in_array($_POST['type'], $transaction_types_array)) {
|
||||
$type_query = "AND (transaction_type = '" . escapeSql($_POST['type']) . "')";
|
||||
$filter_summary['Type'] = $_POST['type'];
|
||||
@@ -138,12 +138,12 @@ if (isExportRequest('export_transactions')) {
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
CASE WHEN transfer_id IS NOT NULL THEN 'Transfer Out' ELSE 'Expense' END,
|
||||
CASE WHEN transfer_id IS NOT NULL THEN 'Transfer Out' WHEN reimbursement_id IS NOT NULL THEN 'Reimbursement' ELSE 'Expense' END,
|
||||
expense_id,
|
||||
expense_date,
|
||||
expense_created_at,
|
||||
CASE WHEN transfer_id IS NOT NULL THEN transfer_notes ELSE expense_description END,
|
||||
to_account.account_name,
|
||||
CASE WHEN reimbursement_id IS NOT NULL THEN payee.user_name ELSE to_account.account_name END,
|
||||
expense_reference,
|
||||
expense_client_id,
|
||||
CASE WHEN transfer_id IS NOT NULL THEN transfer_method ELSE expense_payment_method END,
|
||||
@@ -155,6 +155,8 @@ if (isExportRequest('export_transactions')) {
|
||||
LEFT JOIN transfers ON transfer_expense_id = expense_id
|
||||
LEFT JOIN revenues AS transfer_revenue ON transfer_revenue_id = transfer_revenue.revenue_id
|
||||
LEFT JOIN accounts AS to_account ON transfer_revenue.revenue_account_id = to_account.account_id
|
||||
LEFT JOIN reimbursements ON reimbursement_expense_id = expense_id
|
||||
LEFT JOIN users AS payee ON payee.user_id = reimbursement_user_id
|
||||
WHERE expense_account_id = $account
|
||||
AND expense_archived_at IS NULL
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ if (isset($_GET['account']) & !empty($_GET['account'])) {
|
||||
}
|
||||
|
||||
// Type Filter
|
||||
$transaction_types_array = ['Revenue', 'Payment', 'Expense', 'Transfer In', 'Transfer Out'];
|
||||
$transaction_types_array = ['Revenue', 'Payment', 'Expense', 'Transfer In', 'Transfer Out', 'Reimbursement'];
|
||||
if (isset($_GET['type']) & !empty($_GET['type']) && in_array($_GET['type'], $transaction_types_array)) {
|
||||
$type_query = "AND (transaction_type = '" . escapeSql($_GET['type']) . "')";
|
||||
$type_filter = escapeSql($_GET['type']);
|
||||
@@ -126,14 +126,14 @@ if ($account_filter) {
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
CASE WHEN transfer_id IS NOT NULL THEN 'Transfer Out' ELSE 'Expense' END,
|
||||
expense_id,
|
||||
CASE WHEN transfer_id IS NOT NULL THEN 'Transfer Out' WHEN reimbursement_id IS NOT NULL THEN 'Reimbursement' ELSE 'Expense' END,
|
||||
CASE WHEN reimbursement_id IS NOT NULL THEN reimbursement_id ELSE expense_id END,
|
||||
transfer_id,
|
||||
0,
|
||||
expense_date,
|
||||
expense_created_at,
|
||||
CASE WHEN transfer_id IS NOT NULL THEN transfer_notes ELSE expense_description END,
|
||||
to_account.account_name,
|
||||
CASE WHEN reimbursement_id IS NOT NULL THEN payee.user_name ELSE to_account.account_name END,
|
||||
expense_reference,
|
||||
expense_client_id,
|
||||
CASE WHEN transfer_id IS NOT NULL THEN transfer_method ELSE expense_payment_method END,
|
||||
@@ -146,6 +146,8 @@ if ($account_filter) {
|
||||
LEFT JOIN transfers ON transfer_expense_id = expense_id
|
||||
LEFT JOIN revenues AS transfer_revenue ON transfer_revenue_id = transfer_revenue.revenue_id
|
||||
LEFT JOIN accounts AS to_account ON transfer_revenue.revenue_account_id = to_account.account_id
|
||||
LEFT JOIN reimbursements ON reimbursement_expense_id = expense_id
|
||||
LEFT JOIN users AS payee ON payee.user_id = reimbursement_user_id
|
||||
WHERE expense_account_id = $account_filter
|
||||
AND expense_archived_at IS NULL
|
||||
|
||||
@@ -465,6 +467,8 @@ if ($account_filter) {
|
||||
$transaction_category_display = "<i class='fas fa-fw fa-arrow-left text-secondary me-1'></i>From $transaction_other_account";
|
||||
} elseif ($transaction_type == 'Transfer Out') {
|
||||
$transaction_category_display = "<i class='fas fa-fw fa-arrow-right text-secondary me-1'></i>To $transaction_other_account";
|
||||
} elseif ($transaction_type == 'Reimbursement') {
|
||||
$transaction_category_display = "<i class='fas fa-fw fa-hand-holding-usd text-secondary me-1'></i>To $transaction_other_account";
|
||||
} else {
|
||||
$transaction_category_display = $transaction_category;
|
||||
}
|
||||
@@ -497,6 +501,8 @@ if ($account_filter) {
|
||||
$transaction_modal_url = "modals/transfer/transfer_edit.php?id=$transaction_transfer_id";
|
||||
} elseif ($transaction_type == 'Expense') {
|
||||
$transaction_modal_url = "modals/expense/expense.php?id=$transaction_id";
|
||||
} elseif ($transaction_type == 'Reimbursement') {
|
||||
$transaction_modal_url = "modals/expense/expense_reimbursement.php?id=$transaction_id";
|
||||
} elseif ($transaction_type == 'Revenue') {
|
||||
$transaction_modal_url = "modals/revenue/revenue_edit.php?id=$transaction_id";
|
||||
} else {
|
||||
|
||||
@@ -129,7 +129,8 @@ if (!$vendor || (isset($_GET['client_id']) && $vendor_client_id !== intval($clie
|
||||
$spend = null;
|
||||
if ($is_ours && $can_financial) {
|
||||
$spend = vendorSpend($vendor_id);
|
||||
$sql = mysqli_query($mysqli, "SELECT expense_id, expense_date, expense_amount, expense_currency_code, expense_description, expense_reference, expense_receipt, category_name, account_name
|
||||
$sql = mysqli_query($mysqli, "SELECT expense_id, expense_date, expense_amount, expense_currency_code, expense_description, expense_reference, expense_receipt, category_name, account_name,
|
||||
expense_paid_by, (SELECT payer.user_name FROM users AS payer WHERE payer.user_id = expense_paid_by) AS paid_by_name
|
||||
FROM expenses
|
||||
LEFT JOIN categories ON category_id = expense_category_id
|
||||
LEFT JOIN accounts ON account_id = expense_account_id
|
||||
@@ -698,7 +699,7 @@ if (!$vendor || (isset($_GET['client_id']) && $vendor_client_id !== intval($clie
|
||||
<div><?= escapeHtml(truncate((string) $expense['expense_description'], 90)) ?: '<span class="text-body-secondary">-</span>' ?></div>
|
||||
<div class="small text-body-secondary"><?= escapeHtml(implode(' · ', array_filter([$expense['category_name'], $expense['expense_reference']]))) ?></div>
|
||||
</td>
|
||||
<td class="text-nowrap small"><?= escapeHtml($expense['account_name']) ?></td>
|
||||
<td class="text-nowrap small"><?= intval($expense['expense_paid_by']) ? '<i class="fas fa-hand-holding-usd text-body-secondary me-1" title="Paid personally"></i>' . escapeHtml($expense['paid_by_name'] ?: 'An agent') : escapeHtml($expense['account_name']) ?></td>
|
||||
<td class="text-end text-nowrap font-monospace"><?= numfmt_format_currency($currency_format, floatval($expense['expense_amount']), $expense['expense_currency_code']) ?></td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
|
||||
@@ -6345,3 +6345,20 @@ a.itflow-billing-stat:hover {
|
||||
min-width: 4.5rem;
|
||||
}
|
||||
}
|
||||
/* Import Statement's review - the statement text keeps to a width, the picks stay usable, the Import bar stays in view */
|
||||
.itflow-import-table tbody tr[data-import-row] {
|
||||
cursor: pointer;
|
||||
}
|
||||
.itflow-import-table .itflow-import-text {
|
||||
max-width: 22rem;
|
||||
min-width: 12rem;
|
||||
}
|
||||
.itflow-import-table .itflow-import-pick {
|
||||
min-width: 10.5rem;
|
||||
}
|
||||
.itflow-import-footer {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 3;
|
||||
background-color: var(--bs-tertiary-bg);
|
||||
}
|
||||
|
||||
55
db.sql
55
db.sql
@@ -30,6 +30,7 @@ CREATE TABLE `accounts` (
|
||||
`opening_balance` decimal(15,2) NOT NULL DEFAULT 0.00,
|
||||
`account_currency_code` varchar(200) NOT NULL,
|
||||
`account_notes` text DEFAULT NULL,
|
||||
`account_import_map` text DEFAULT NULL,
|
||||
`account_type` int(6) DEFAULT NULL,
|
||||
`account_created_at` datetime NOT NULL DEFAULT current_timestamp(),
|
||||
`account_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
|
||||
@@ -1330,6 +1331,28 @@ CREATE TABLE `email_queue` (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
|
||||
--
|
||||
-- Table structure for table `expense_import_rules`
|
||||
--
|
||||
|
||||
DROP TABLE IF EXISTS `expense_import_rules`;
|
||||
/*!40101 SET @saved_cs_client = @@character_set_client */;
|
||||
/*!40101 SET character_set_client = utf8mb4 */;
|
||||
CREATE TABLE `expense_import_rules` (
|
||||
`import_rule_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`import_rule_match` varchar(200) NOT NULL,
|
||||
`import_rule_vendor_id` int(11) NOT NULL,
|
||||
`import_rule_category_id` int(11) NOT NULL DEFAULT 0,
|
||||
`import_rule_client_id` int(11) NOT NULL DEFAULT 0,
|
||||
`import_rule_billable` tinyint(1) 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 `expenses`
|
||||
--
|
||||
@@ -1360,8 +1383,13 @@ CREATE TABLE `expenses` (
|
||||
`expense_markup` decimal(7,2) NOT NULL DEFAULT 0.00,
|
||||
`expense_invoice_id` int(11) DEFAULT NULL,
|
||||
`expense_invoice_item_id` int(11) DEFAULT NULL,
|
||||
`expense_import_key` varchar(64) DEFAULT NULL,
|
||||
`expense_paid_by` int(11) NOT NULL DEFAULT 0,
|
||||
`expense_reimbursement_id` int(11) DEFAULT NULL,
|
||||
PRIMARY KEY (`expense_id`),
|
||||
KEY `expense_invoice_id` (`expense_invoice_id`)
|
||||
KEY `expense_invoice_id` (`expense_invoice_id`),
|
||||
KEY `expense_import_key` (`expense_import_key`),
|
||||
KEY `expense_reimbursement_id` (`expense_reimbursement_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
|
||||
@@ -2262,6 +2290,31 @@ CREATE TABLE `recurring_tickets` (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
|
||||
--
|
||||
-- Table structure for table `reimbursements`
|
||||
--
|
||||
|
||||
DROP TABLE IF EXISTS `reimbursements`;
|
||||
/*!40101 SET @saved_cs_client = @@character_set_client */;
|
||||
/*!40101 SET character_set_client = utf8mb4 */;
|
||||
CREATE TABLE `reimbursements` (
|
||||
`reimbursement_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`reimbursement_user_id` int(11) NOT NULL,
|
||||
`reimbursement_date` date NOT NULL,
|
||||
`reimbursement_amount` decimal(15,2) NOT NULL,
|
||||
`reimbursement_currency_code` varchar(200) NOT NULL,
|
||||
`reimbursement_account_id` int(11) NOT NULL,
|
||||
`reimbursement_payment_method` varchar(200) DEFAULT NULL,
|
||||
`reimbursement_reference` varchar(200) DEFAULT NULL,
|
||||
`reimbursement_expense_id` int(11) NOT NULL,
|
||||
`reimbursement_created_by` int(11) NOT NULL DEFAULT 0,
|
||||
`reimbursement_created_at` datetime NOT NULL DEFAULT current_timestamp(),
|
||||
PRIMARY KEY (`reimbursement_id`),
|
||||
KEY `reimbursement_user_id` (`reimbursement_user_id`),
|
||||
KEY `reimbursement_expense_id` (`reimbursement_expense_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
|
||||
--
|
||||
-- Table structure for table `remember_tokens`
|
||||
--
|
||||
|
||||
@@ -54,3 +54,4 @@ require_once __DIR__ . '/functions/billing.php';
|
||||
require_once __DIR__ . '/functions/products.php';
|
||||
require_once __DIR__ . '/functions/billing_email.php';
|
||||
require_once __DIR__ . '/functions/expenses.php';
|
||||
require_once __DIR__ . '/functions/expense_import.php';
|
||||
|
||||
@@ -303,6 +303,14 @@ function dashboardAttention($access) {
|
||||
'detail' => $to_bill['count'] ? dashboardMoney($to_bill['value']) . ' to bill on' : null,
|
||||
'url' => '/agent/expenses.php?show=to_bill',
|
||||
];
|
||||
// What agents paid personally and haven't been paid back for
|
||||
$owed = expenseToReimburseCount();
|
||||
$items[] = [
|
||||
'count' => $owed['count'],
|
||||
'label' => 'Expenses to reimburse', 'icon' => 'hand-holding-usd', 'tone' => 'warning',
|
||||
'detail' => $owed['count'] ? dashboardMoney($owed['total']) . ' owed to ' . ($owed['agents'] === 1 ? '1 agent' : $owed['agents'] . ' agents') : null,
|
||||
'url' => '/agent/expenses.php?show=to_reimburse',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
770
functions/expense_import.php
Normal file
770
functions/expense_import.php
Normal file
@@ -0,0 +1,770 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - importing a card or bank statement as expenses.
|
||||
*
|
||||
* A statement exported as CSV is read (any delimiter, a header row found
|
||||
* among the first lines or none), its columns are guessed - the date, the
|
||||
* description, the amount or separate money out and money in, a reference -
|
||||
* along with the date format and whether charges are positive or negative,
|
||||
* and the guess is remembered on the account for its next statement.
|
||||
*
|
||||
* Each line is matched to a vendor: first by what was picked for the same
|
||||
* merchant last time (expense_import_rules, keyed on the start of the
|
||||
* cleaned-up description), then by one of our vendors' names appearing in
|
||||
* it, with the category and client that came with it, or the vendor's last
|
||||
* category. Lines with no match suggest a new vendor named from the text.
|
||||
*
|
||||
* Every line has a key (expense_import_key) from the account, date, amount,
|
||||
* text and which repeat of those it is in the file, so the same statement
|
||||
* can't bring a line in twice. A line not imported before but with the same
|
||||
* amount on the same account within a few days of an expense entered by
|
||||
* hand looks entered already - left out unless ticked, and if left out the
|
||||
* hand-entered one takes its key, so the next statement knows it too.
|
||||
*/
|
||||
|
||||
const EXPENSE_IMPORT_MAX_BYTES = 2097152;
|
||||
const EXPENSE_IMPORT_MAX_LINES = 2000;
|
||||
const EXPENSE_IMPORT_DUPLICATE_DAYS = 4;
|
||||
|
||||
/** The date formats a statement can use - format => an example. */
|
||||
function expenseImportDateFormats() {
|
||||
return [
|
||||
'm/d/Y' => '10/14/2026', 'm/d/y' => '10/14/26', 'Y-m-d' => '2026-10-14', 'd/m/Y' => '14/10/2026', 'd/m/y' => '14/10/26',
|
||||
'd.m.Y' => '14.10.2026', 'Y/m/d' => '2026/10/14', 'm-d-Y' => '10-14-2026', 'd-M-Y' => '14-Oct-2026', 'd-M-y' => '14-Oct-26',
|
||||
'd M Y' => '14 Oct 2026', 'M d, Y' => 'Oct 14, 2026', 'Ymd' => '20261014',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a statement CSV - [header (a name for each column), rows (lists of
|
||||
* cells)], or null with $error. Handles a byte order mark, Windows text,
|
||||
* commas, semicolons, tabs or pipes, lines before the header, and a file
|
||||
* with no header at all.
|
||||
*/
|
||||
function expenseImportRead($path, &$error = '') {
|
||||
$error = '';
|
||||
$text = @file_get_contents($path);
|
||||
if ($text === false || trim($text) === '') {
|
||||
$error = 'That file is empty';
|
||||
return null;
|
||||
}
|
||||
if (strlen($text) > EXPENSE_IMPORT_MAX_BYTES) {
|
||||
$error = 'That file is too big - export a month or two at a time';
|
||||
return null;
|
||||
}
|
||||
$text = preg_replace('/^\xEF\xBB\xBF/', '', $text);
|
||||
if (!mb_check_encoding($text, 'UTF-8')) {
|
||||
$text = mb_convert_encoding($text, 'UTF-8', 'Windows-1252');
|
||||
}
|
||||
$text = str_replace(["\r\n", "\r"], "\n", $text);
|
||||
if (strpos($text, "\0") !== false) {
|
||||
$error = "That doesn't look like a CSV file - export the statement as CSV";
|
||||
return null;
|
||||
}
|
||||
|
||||
// The delimiter the first lines agree on most
|
||||
$sample = array_slice(array_filter(explode("\n", $text), 'strlen'), 0, 20);
|
||||
$delimiter = ',';
|
||||
$best = 0;
|
||||
foreach ([',', ';', "\t", '|'] as $candidate) {
|
||||
$counts = array_map(function ($line) use ($candidate) { return count(str_getcsv($line, $candidate, '"', '')); }, $sample);
|
||||
$common = array_count_values($counts);
|
||||
arsort($common);
|
||||
$width = intval(array_key_first($common));
|
||||
if ($width > 1 && $common[$width] * $width > $best) {
|
||||
$best = $common[$width] * $width;
|
||||
$delimiter = $candidate;
|
||||
}
|
||||
}
|
||||
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
fwrite($handle, $text);
|
||||
rewind($handle);
|
||||
$rows = [];
|
||||
while (($cells = fgetcsv($handle, 0, $delimiter, '"', '')) !== false) {
|
||||
$cells = array_map(function ($cell) { return trim((string) $cell); }, $cells);
|
||||
if (implode('', $cells) === '') {
|
||||
continue;
|
||||
}
|
||||
$rows[] = $cells;
|
||||
if (count($rows) > EXPENSE_IMPORT_MAX_LINES + 20) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose($handle);
|
||||
if (count($rows) < 1) {
|
||||
$error = 'There are no lines in that file';
|
||||
return null;
|
||||
}
|
||||
|
||||
// The header is the last line before the first that has a date in it
|
||||
$first_data = null;
|
||||
foreach (array_slice($rows, 0, 20, true) as $i => $cells) {
|
||||
foreach ($cells as $cell) {
|
||||
if (expenseImportLooksLikeDate($cell)) {
|
||||
$first_data = $i;
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($first_data === null) {
|
||||
$error = "There are no dates in that file - export the statement's transactions as CSV";
|
||||
return null;
|
||||
}
|
||||
$width = max(array_map('count', array_slice($rows, $first_data, 50)));
|
||||
if ($first_data > 0) {
|
||||
$header = $rows[$first_data - 1];
|
||||
} else {
|
||||
$header = [];
|
||||
}
|
||||
$names = [];
|
||||
for ($c = 0; $c < $width; $c++) {
|
||||
$name = trim((string) ($header[$c] ?? ''));
|
||||
$names[] = $name !== '' ? mb_substr($name, 0, 60) : 'Column ' . ($c + 1);
|
||||
}
|
||||
$data = [];
|
||||
foreach (array_slice($rows, $first_data) as $cells) {
|
||||
$data[] = array_pad(array_slice($cells, 0, $width), $width, '');
|
||||
}
|
||||
if (count($data) > EXPENSE_IMPORT_MAX_LINES) {
|
||||
$error = 'That file has more than ' . EXPENSE_IMPORT_MAX_LINES . ' lines - export a shorter period';
|
||||
return null;
|
||||
}
|
||||
return ['header' => $names, 'rows' => $data];
|
||||
}
|
||||
|
||||
/** Does a cell look like a date in any of the formats? */
|
||||
function expenseImportLooksLikeDate($value) {
|
||||
$value = trim((string) $value);
|
||||
if ($value === '' || strlen($value) > 30 || !preg_match('/\d/', $value)) {
|
||||
return false;
|
||||
}
|
||||
foreach (array_keys(expenseImportDateFormats()) as $format) {
|
||||
if (expenseImportDate($value, $format) !== null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A date in a format, as Y-m-d - or null. A time after it is ignored. */
|
||||
function expenseImportDate($value, $format) {
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
if (strpos($format, ' ') === false) {
|
||||
$value = preg_split('/[\sT]/', $value)[0];
|
||||
} else {
|
||||
$value = preg_replace('/\s+\d{1,2}:\d{2}(:\d{2})?(\s*[AP]M)?$/i', '', $value);
|
||||
}
|
||||
if ($format === 'Ymd' && !preg_match('/^\d{8}$/', $value)) {
|
||||
return null;
|
||||
}
|
||||
$date = DateTime::createFromFormat('!' . $format, $value);
|
||||
$errors = DateTime::getLastErrors();
|
||||
if (!$date || ($errors && ($errors['warning_count'] || $errors['error_count']))) {
|
||||
return null;
|
||||
}
|
||||
$year = intval($date->format('Y'));
|
||||
if ($year < 1990 || $year > 2100) {
|
||||
return null;
|
||||
}
|
||||
return $date->format('Y-m-d');
|
||||
}
|
||||
|
||||
/**
|
||||
* An amount from a statement - "$1,234.56", "-12", "(12.00)", "12.00 CR",
|
||||
* "1.234,56", "USD 9.99" - as a number, or null. CR and brackets are money
|
||||
* in, written negative; DR is money out.
|
||||
*/
|
||||
function expenseImportAmount($value) {
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
$negative = false;
|
||||
if (preg_match('/^\((.*)\)$/', $value, $m)) {
|
||||
$value = $m[1];
|
||||
$negative = true;
|
||||
}
|
||||
if (preg_match('/\s*\b(CR|DR)\.?$/i', $value, $m)) {
|
||||
$negative = strtoupper($m[1]) === 'CR';
|
||||
$value = trim(substr($value, 0, -strlen($m[0])));
|
||||
}
|
||||
$value = preg_replace('/[^\d.,\-+]/u', '', $value);
|
||||
if ($value === '' || !preg_match('/\d/', $value)) {
|
||||
return null;
|
||||
}
|
||||
if (substr_count($value, '-') + substr_count($value, '+') > 1) {
|
||||
return null;
|
||||
}
|
||||
if (preg_match('/^[+-]?\d{1,3}(\.\d{3})*,\d{1,2}$/', $value) || preg_match('/^[+-]?\d+,\d{1,2}$/', $value)) {
|
||||
$value = str_replace(['.', ','], ['', '.'], $value);
|
||||
} else {
|
||||
$value = str_replace(',', '', $value);
|
||||
}
|
||||
if (!is_numeric($value)) {
|
||||
return null;
|
||||
}
|
||||
$amount = round(floatval($value), 2);
|
||||
return $negative ? -abs($amount) : $amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* A first guess at what each column is - [date, description, memo, amount,
|
||||
* debit, credit, reference] as column numbers (null where there is none),
|
||||
* with date_format and sign ('positive' when charges are positive). From
|
||||
* the header names first, then from what the cells hold.
|
||||
*/
|
||||
function expenseImportGuess(array $header, array $rows) {
|
||||
$map = ['date' => null, 'description' => null, 'memo' => null, 'amount' => null, 'debit' => null, 'credit' => null, 'reference' => null];
|
||||
$patterns = [
|
||||
'date' => '/^(transaction |trans\.? |posted |post |posting )?date$|^date posted$|^posted$|^date$/i',
|
||||
'description' => '/^(description|payee|merchant|name|details|transaction description|narrative|particulars|merchant name|transaction)$/i',
|
||||
'memo' => '/^(memo|notes?|extended description|additional info)$/i',
|
||||
'amount' => '/^(amount|transaction amount|amt|value|amount \(\w+\))$/i',
|
||||
'debit' => '/^(debit|debits|withdrawal|withdrawals|money out|charge|charges|paid out|debit amount|outflow)$/i',
|
||||
'credit' => '/^(credit|credits|deposit|deposits|money in|payment|payments|paid in|credit amount|inflow)$/i',
|
||||
'reference' => '/^(reference|ref|ref\.|reference number|check|check number|check #|chk|transaction id|id|confirmation)$/i',
|
||||
];
|
||||
foreach ($header as $c => $name) {
|
||||
foreach ($patterns as $field => $pattern) {
|
||||
if ($map[$field] === null && preg_match($pattern, trim($name))) {
|
||||
$map[$field] = $c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Prefer the transaction date over a posted date when both are there
|
||||
foreach ($header as $c => $name) {
|
||||
if (preg_match('/^trans(action)?\.? date$/i', trim($name))) {
|
||||
$map['date'] = $c;
|
||||
}
|
||||
}
|
||||
|
||||
// What the cells hold, for the columns the names didn't settle
|
||||
$sample = array_slice($rows, 0, 60);
|
||||
$share = function ($c, $test) use ($sample) {
|
||||
$hits = 0;
|
||||
$filled = 0;
|
||||
foreach ($sample as $cells) {
|
||||
$value = trim((string) ($cells[$c] ?? ''));
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
$filled++;
|
||||
$hits += $test($value) ? 1 : 0;
|
||||
}
|
||||
return $filled ? $hits / $filled : 0;
|
||||
};
|
||||
$width = count($header);
|
||||
if ($map['date'] === null) {
|
||||
for ($c = 0; $c < $width; $c++) {
|
||||
if ($share($c, 'expenseImportLooksLikeDate') >= 0.8) {
|
||||
$map['date'] = $c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($map['amount'] === null && $map['debit'] === null) {
|
||||
for ($c = $width - 1; $c >= 0; $c--) {
|
||||
if ($c !== $map['date'] && $c !== $map['reference'] && $share($c, function ($v) { return expenseImportAmount($v) !== null && !expenseImportLooksLikeDate($v) && preg_match('/[.,]\d{2}\)?$|^-?\d+$/', $v); }) >= 0.8) {
|
||||
$map['amount'] = $c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($map['description'] === null) {
|
||||
$longest = 0;
|
||||
for ($c = 0; $c < $width; $c++) {
|
||||
if (in_array($c, [$map['date'], $map['amount'], $map['debit'], $map['credit'], $map['reference']], true)) {
|
||||
continue;
|
||||
}
|
||||
$length = 0;
|
||||
foreach ($sample as $cells) {
|
||||
$value = (string) ($cells[$c] ?? '');
|
||||
$length += preg_match('/[a-z]/i', $value) ? mb_strlen($value) : 0;
|
||||
}
|
||||
if ($length > $longest) {
|
||||
$longest = $length;
|
||||
$map['description'] = $c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The date format every date parses in - the US one first when both fit
|
||||
$map['date_format'] = 'm/d/Y';
|
||||
if ($map['date'] !== null) {
|
||||
foreach (array_keys(expenseImportDateFormats()) as $format) {
|
||||
if ($share($map['date'], function ($v) use ($format) { return expenseImportDate($v, $format) !== null; }) === 1) {
|
||||
$map['date_format'] = $format;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Charges are what most lines are
|
||||
$map['sign'] = 'positive';
|
||||
if ($map['amount'] !== null) {
|
||||
$negative = 0;
|
||||
$positive = 0;
|
||||
foreach ($sample as $cells) {
|
||||
$amount = expenseImportAmount($cells[$map['amount']] ?? '');
|
||||
if ($amount !== null && $amount != 0) {
|
||||
$amount < 0 ? $negative++ : $positive++;
|
||||
}
|
||||
}
|
||||
$map['sign'] = $negative > $positive ? 'negative' : 'positive';
|
||||
}
|
||||
return $map;
|
||||
}
|
||||
|
||||
/** A mapping from a form or a saved one, checked against the columns there are - or null when it misses the date, description or an amount. */
|
||||
function expenseImportMapClean(array $in, $width) {
|
||||
$map = [];
|
||||
foreach (['date', 'description', 'memo', 'amount', 'debit', 'credit', 'reference'] as $field) {
|
||||
$value = $in[$field] ?? null;
|
||||
$map[$field] = $value === null || $value === '' || intval($value) < 0 || intval($value) >= $width ? null : intval($value);
|
||||
}
|
||||
$map['date_format'] = isset(expenseImportDateFormats()[$in['date_format'] ?? '']) ? $in['date_format'] : 'm/d/Y';
|
||||
$map['sign'] = ($in['sign'] ?? '') === 'negative' ? 'negative' : 'positive';
|
||||
if (($in['amounts'] ?? ($map['amount'] !== null ? 'one' : 'two')) === 'two') {
|
||||
$map['amount'] = null;
|
||||
} else {
|
||||
$map['debit'] = $map['credit'] = null;
|
||||
}
|
||||
if ($map['date'] === null || $map['description'] === null || ($map['amount'] === null && $map['debit'] === null && $map['credit'] === null)) {
|
||||
return null;
|
||||
}
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement's lines by a mapping - each [n, date, description (with
|
||||
* the memo), match_text (without), amount (a charge positive, money in
|
||||
* negative), reference, problem]. Lines with nothing like a date, such as
|
||||
* totals, are left out.
|
||||
*/
|
||||
function expenseImportLines(array $rows, array $map) {
|
||||
$lines = [];
|
||||
foreach ($rows as $n => $cells) {
|
||||
$date = expenseImportDate($cells[$map['date']] ?? '', $map['date_format']);
|
||||
if ($map['amount'] !== null) {
|
||||
$value = expenseImportAmount($cells[$map['amount']] ?? '');
|
||||
$amount = $value === null ? null : ($map['sign'] === 'negative' ? -$value : $value);
|
||||
} else {
|
||||
$debit = $map['debit'] !== null ? expenseImportAmount($cells[$map['debit']] ?? '') : null;
|
||||
$credit = $map['credit'] !== null ? expenseImportAmount($cells[$map['credit']] ?? '') : null;
|
||||
$amount = $debit === null && $credit === null ? null : round(abs((float) $debit) - abs((float) $credit), 2);
|
||||
}
|
||||
// Totals and notes - nothing like a date where the date goes
|
||||
if (($date === null && $amount === null) || ($date === null && !preg_match('/\d/', (string) ($cells[$map['date']] ?? '')))) {
|
||||
continue;
|
||||
}
|
||||
$description = trim(preg_replace('/\s+/u', ' ', (string) ($cells[$map['description']] ?? '')));
|
||||
$match_text = $description;
|
||||
$memo = $map['memo'] !== null ? trim(preg_replace('/\s+/u', ' ', (string) ($cells[$map['memo']] ?? ''))) : '';
|
||||
if ($memo !== '' && $memo !== $description) {
|
||||
$description = trim("$description - $memo", ' -');
|
||||
}
|
||||
$problem = $date === null ? "The date isn't in the format picked" : ($amount === null ? 'There is no amount' : ($amount == 0 ? 'The amount is zero' : ''));
|
||||
$lines[] = [
|
||||
'n' => count($lines),
|
||||
'date' => $date,
|
||||
'description' => mb_substr($description, 0, 500),
|
||||
'match_text' => $match_text,
|
||||
'amount' => $amount === null ? null : round($amount, 2),
|
||||
'reference' => $map['reference'] !== null ? mb_substr(trim((string) ($cells[$map['reference']] ?? '')), 0, 200) : '',
|
||||
'problem' => $problem,
|
||||
];
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/** Words that say how a line was paid, not who to - left out of matching. */
|
||||
function expenseImportNoiseWords() {
|
||||
return ['pos', 'purchase', 'purchases', 'debit', 'credit', 'card', 'checkcard', 'check', 'recurring', 'authorized', 'preauthorized', 'auth', 'ach', 'web', 'online',
|
||||
'pmt', 'pymt', 'payment', 'bill', 'billpay', 'visa', 'mastercard', 'mc', 'amex', 'withdrawal', 'transaction', 'trans', 'ppd', 'ccd', 'ref', 'id', 'on', 'at',
|
||||
'inc', 'llc', 'ltd', 'co', 'corp', 'the', 'www', 'com', 'net', 'org', 'us', 'usa', 'intl', 'sq', 'tst', 'sp', 'pp', 'ext'];
|
||||
}
|
||||
|
||||
/** A description's words for matching - lowercase letters only, the card, store and payment noise taken out. */
|
||||
function expenseImportWords($description) {
|
||||
$text = mb_strtolower((string) $description);
|
||||
$text = preg_replace('/\b(sq|tst|sp|pp|paypal|dd|ckc|cke|fsp|py)\s?\*\s?/u', ' ', $text);
|
||||
$text = preg_replace('/\*\S*/u', ' ', $text);
|
||||
$text = preg_replace('/\b\d{1,2}\/\d{1,2}(\/\d{2,4})?\b/u', ' ', $text);
|
||||
$text = preg_replace('/\.(com|net|org|io|co|us)\b/u', ' ', $text);
|
||||
$text = preg_replace('/[^\p{L}\s]+/u', ' ', $text);
|
||||
$noise = array_flip(expenseImportNoiseWords());
|
||||
$words = [];
|
||||
foreach (preg_split('/\s+/u', trim($text)) as $word) {
|
||||
if (mb_strlen($word) > 1 && !isset($noise[$word])) {
|
||||
$words[] = $word;
|
||||
}
|
||||
}
|
||||
return $words;
|
||||
}
|
||||
|
||||
/** What a line is matched on - the first three of its words. '' when there are none. */
|
||||
function expenseImportMatchKey($description) {
|
||||
return mb_substr(implode(' ', array_slice(expenseImportWords($description), 0, 3)), 0, 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A tidy vendor name from a description - "SQ *JOES COFFEE #123 PITTSBURGH
|
||||
* PA" is "Joes Coffee": processor prefixes, numbers and card noise out, and
|
||||
* a town and state on the end too.
|
||||
*/
|
||||
function expenseImportVendorName($description) {
|
||||
$text = preg_replace('/\b(sq|tst|sp|pp|paypal|dd|py)\s?\*\s?/iu', ' ', (string) $description);
|
||||
$text = preg_replace('/\*\S*|#\S*|\b\S*\d\S*\b/u', ' ', $text);
|
||||
$text = preg_replace('/[^\p{L}&\'\s.-]+/u', ' ', $text);
|
||||
$noise = array_flip(['pos', 'purchase', 'debit', 'card', 'checkcard', 'recurring', 'ach', 'pmt', 'payment', 'authorized', 'preauthorized', 'withdrawal', 'on']);
|
||||
// Statements in capitals get title case; mixed case is kept as it is written
|
||||
$shouting = mb_strtoupper($text) === $text;
|
||||
$words = [];
|
||||
foreach (preg_split('/\s+/u', trim($text)) as $word) {
|
||||
$word = trim($word, '.-,');
|
||||
if ($word !== '' && !isset($noise[mb_strtolower($word)])) {
|
||||
$words[] = $word;
|
||||
}
|
||||
}
|
||||
// A state on the end, and the town before it when that leaves a name
|
||||
$states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO',
|
||||
'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'];
|
||||
if (count($words) > 1 && in_array(end($words), $states, true)) {
|
||||
array_pop($words);
|
||||
if (count($words) >= 3) {
|
||||
array_pop($words);
|
||||
}
|
||||
}
|
||||
$words = array_slice($words, 0, 3);
|
||||
if ($shouting) {
|
||||
$words = array_map(function ($word) { return mb_convert_case(mb_strtolower($word), MB_CASE_TITLE); }, $words);
|
||||
}
|
||||
return mb_substr(implode(' ', $words), 0, 200) ?: 'New vendor';
|
||||
}
|
||||
|
||||
/** The remembered merchants - match => [vendor_id, category_id, client_id, billable, id]. */
|
||||
function expenseImportRules() {
|
||||
global $mysqli;
|
||||
$rules = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT import_rule_id, import_rule_match, import_rule_vendor_id, import_rule_category_id, import_rule_client_id, import_rule_billable
|
||||
FROM expense_import_rules JOIN vendors ON vendor_id = import_rule_vendor_id AND vendor_archived_at IS NULL AND vendor_client_id = 0");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$rules[$row['import_rule_match']] = ['id' => intval($row['import_rule_id']), 'vendor_id' => intval($row['import_rule_vendor_id']),
|
||||
'category_id' => intval($row['import_rule_category_id']), 'client_id' => intval($row['import_rule_client_id']), 'billable' => intval($row['import_rule_billable'])];
|
||||
}
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Match each line to a vendor - sets key (the match key), vendor_id,
|
||||
* category_id, client_id, billable, matched ('rule', 'name' or '') and
|
||||
* new_vendor (a name to make one with when nothing matched).
|
||||
*/
|
||||
function expenseImportMatch(array $lines) {
|
||||
$rules = expenseImportRules();
|
||||
uksort($rules, function ($a, $b) { return mb_strlen($b) <=> mb_strlen($a); });
|
||||
$defaults = expenseVendorDefaults();
|
||||
$vendor_words = [];
|
||||
foreach (expenseVendors() as $vendor_id => $vendor) {
|
||||
$words = expenseImportWords($vendor['vendor_name']);
|
||||
if ($words && mb_strlen(implode(' ', $words)) >= 3) {
|
||||
$vendor_words[$vendor_id] = ' ' . implode(' ', $words) . ' ';
|
||||
}
|
||||
}
|
||||
uasort($vendor_words, function ($a, $b) { return mb_strlen($b) <=> mb_strlen($a); });
|
||||
|
||||
foreach ($lines as $i => $line) {
|
||||
$key = expenseImportMatchKey($line['match_text'] ?? $line['description']);
|
||||
$line += ['key' => $key, 'vendor_id' => 0, 'category_id' => 0, 'client_id' => 0, 'billable' => 0, 'matched' => '', 'new_vendor' => ''];
|
||||
$line['key'] = $key;
|
||||
$rule = null;
|
||||
if ($key !== '') {
|
||||
foreach ($rules as $match => $candidate) {
|
||||
if ($key === $match || strpos($key, $match . ' ') === 0) {
|
||||
$rule = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($rule) {
|
||||
$line['vendor_id'] = $rule['vendor_id'];
|
||||
$line['category_id'] = $rule['category_id'];
|
||||
$line['client_id'] = $rule['client_id'];
|
||||
$line['billable'] = $rule['billable'];
|
||||
$line['matched'] = 'rule';
|
||||
} else {
|
||||
$line_words = expenseImportWords($line['match_text'] ?? $line['description']);
|
||||
$text = ' ' . implode(' ', $line_words) . ' ';
|
||||
foreach ($vendor_words as $vendor_id => $words) {
|
||||
if (strpos($text, $words) !== false) {
|
||||
$line['vendor_id'] = $vendor_id;
|
||||
$line['matched'] = 'name';
|
||||
break;
|
||||
}
|
||||
}
|
||||
// "THREE RIVERS COLO" for Three Rivers Colocation - the words in order, the last one cut short
|
||||
if (!$line['vendor_id']) {
|
||||
foreach ($vendor_words as $vendor_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)) {
|
||||
$line['vendor_id'] = $vendor_id;
|
||||
$line['matched'] = 'name';
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($line['vendor_id'] && !$line['category_id'] && isset($defaults[$line['vendor_id']])) {
|
||||
$line['category_id'] = $defaults[$line['vendor_id']]['category'];
|
||||
}
|
||||
if (!$line['vendor_id']) {
|
||||
$line['new_vendor'] = expenseImportVendorName($line['match_text'] ?? $line['description']);
|
||||
}
|
||||
$lines[$i] = $line;
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key of each line - the account, date, amount and cleaned text, and
|
||||
* which repeat of those it is in the file (two coffees on one day are two
|
||||
* lines). Sets key_hash on each.
|
||||
*/
|
||||
function expenseImportKeys($account_id, array $lines) {
|
||||
$seen = [];
|
||||
foreach ($lines as $i => $line) {
|
||||
$base = intval($account_id) . '|' . $line['date'] . '|' . number_format((float) $line['amount'], 2, '.', '') . '|' . mb_strtolower(preg_replace('/\s+/u', ' ', $line['description']));
|
||||
$seen[$base] = ($seen[$base] ?? 0) + 1;
|
||||
$lines[$i]['key_hash'] = hash('sha256', $base . '|' . $seen[$base]);
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lines already in - sets imported (the expense id a line came in as
|
||||
* before) or entered (an expense entered by hand on the account with the
|
||||
* same amount within EXPENSE_IMPORT_DUPLICATE_DAYS days, the closest one,
|
||||
* each matched once), with entered_label to show for it.
|
||||
*/
|
||||
function expenseImportDuplicates($account_id, array $lines) {
|
||||
global $mysqli;
|
||||
$account_id = intval($account_id);
|
||||
$hashes = array_filter(array_column($lines, 'key_hash'));
|
||||
$imported = [];
|
||||
if ($hashes) {
|
||||
$sql = mysqli_query($mysqli, "SELECT expense_id, expense_import_key FROM expenses WHERE expense_import_key IN ('" . implode("','", array_map('escapeSql', $hashes)) . "')");
|
||||
while ($row = mysqli_fetch_row($sql)) {
|
||||
$imported[$row[1]] = intval($row[0]);
|
||||
}
|
||||
}
|
||||
$dates = array_filter(array_column($lines, 'date'));
|
||||
$existing = [];
|
||||
if ($dates) {
|
||||
$from = date('Y-m-d', strtotime(min($dates) . ' -' . EXPENSE_IMPORT_DUPLICATE_DAYS . ' days'));
|
||||
$to = date('Y-m-d', strtotime(max($dates) . ' +' . EXPENSE_IMPORT_DUPLICATE_DAYS . ' days'));
|
||||
$sql = mysqli_query($mysqli, "SELECT expense_id, expense_date, expense_amount, vendor_name FROM expenses LEFT JOIN vendors ON vendor_id = expense_vendor_id
|
||||
WHERE expense_account_id = $account_id AND expense_vendor_id > 0 AND expense_import_key IS NULL AND expense_archived_at IS NULL
|
||||
AND expense_date BETWEEN '$from' AND '$to'");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$existing[intval($row['expense_id'])] = $row;
|
||||
}
|
||||
}
|
||||
$used = [];
|
||||
foreach ($lines as $i => $line) {
|
||||
$lines[$i]['imported'] = $imported[$line['key_hash']] ?? 0;
|
||||
$lines[$i]['entered'] = 0;
|
||||
$lines[$i]['entered_label'] = '';
|
||||
if ($lines[$i]['imported'] || $line['problem'] !== '') {
|
||||
continue;
|
||||
}
|
||||
$best = null;
|
||||
foreach ($existing as $expense_id => $row) {
|
||||
if (isset($used[$expense_id]) || abs(floatval($row['expense_amount']) - $line['amount']) >= 0.005) {
|
||||
continue;
|
||||
}
|
||||
$days = abs((strtotime($row['expense_date']) - strtotime($line['date'])) / 86400);
|
||||
if ($days <= EXPENSE_IMPORT_DUPLICATE_DAYS && ($best === null || $days < $best[1])) {
|
||||
$best = [$expense_id, $days];
|
||||
}
|
||||
}
|
||||
if ($best) {
|
||||
$used[$best[0]] = true;
|
||||
$lines[$i]['entered'] = $best[0];
|
||||
$lines[$i]['entered_label'] = trim($existing[$best[0]]['vendor_name'] . ' on ' . $existing[$best[0]]['expense_date']);
|
||||
}
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/** Everything about a statement's lines for the review - read, matched, keyed and checked for duplicates. */
|
||||
function expenseImportReview(array $import) {
|
||||
$lines = expenseImportLines($import['rows'], $import['map']);
|
||||
$lines = expenseImportMatch($lines);
|
||||
$lines = expenseImportKeys($import['account_id'], $lines);
|
||||
return expenseImportDuplicates($import['account_id'], $lines);
|
||||
}
|
||||
|
||||
/** The mapping an account's last statement used, if its columns are the same as these. */
|
||||
function expenseImportSavedMap($account_id, array $header) {
|
||||
$saved = json_decode((string) getFieldById('accounts', intval($account_id), 'account_import_map'), true);
|
||||
if (!is_array($saved) || ($saved['columns'] ?? '') !== expenseImportColumnsKey($header) || !is_array($saved['map'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
return expenseImportMapClean($saved['map'] + ['amounts' => ($saved['map']['amount'] ?? null) !== null ? 'one' : 'two'], count($header));
|
||||
}
|
||||
|
||||
/** What identifies a statement's layout - its column names. */
|
||||
function expenseImportColumnsKey(array $header) {
|
||||
return md5(mb_strtolower(implode('|', $header)));
|
||||
}
|
||||
|
||||
/** Remember the mapping for the account's next statement. */
|
||||
function expenseImportSaveMap($account_id, array $header, array $map) {
|
||||
global $mysqli;
|
||||
$json = json_encode(['columns' => expenseImportColumnsKey($header), 'map' => $map]);
|
||||
mysqli_query($mysqli, "UPDATE accounts SET account_import_map = '" . escapeSql($json) . "' WHERE account_id = " . intval($account_id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring in the ticked lines as expenses. $picks is line n => [vendor (an id,
|
||||
* or 'new' with new_vendor), category, client, billable]; $import the
|
||||
* statement in the session. New vendors are made once per name (or an
|
||||
* existing one by that name is used), each line's merchant is remembered for
|
||||
* next time, and a line left out that looked entered already gives its key to
|
||||
* that expense. Returns [imported, total, vendors (made), linked, skipped] or
|
||||
* null with $error.
|
||||
*/
|
||||
function expenseImportSave(array $import, array $picks, &$error = '') {
|
||||
global $mysqli, $session_user_id, $session_company_currency;
|
||||
$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;
|
||||
}
|
||||
$method = (string) $import['method'];
|
||||
if ($method !== '' && !in_array($method, paymentMethods(), true)) {
|
||||
$method = '';
|
||||
}
|
||||
$currency = escapeSql((string) ($accounts[$account_id]['account_currency_code'] ?: $session_company_currency));
|
||||
$lines = expenseImportReview($import);
|
||||
$vendors = expenseVendors();
|
||||
$categories = expenseCategories();
|
||||
$markup = expenseMarkupDefault();
|
||||
$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;
|
||||
}
|
||||
|
||||
// Check every ticked line before bringing any in
|
||||
$bring = [];
|
||||
foreach ($lines as $line) {
|
||||
$pick = $picks[$line['n']] ?? null;
|
||||
if (!$pick || empty($pick['take']) || $line['imported'] || $line['problem'] !== '') {
|
||||
continue;
|
||||
}
|
||||
$vendor = (string) ($pick['vendor'] ?? '');
|
||||
$new_name = trim((string) ($pick['new_vendor'] ?? ''));
|
||||
$category = intval($pick['category'] ?? 0);
|
||||
$client = intval($pick['client'] ?? 0);
|
||||
$what = date('M j', strtotime($line['date'])) . ' ' . billingMoney(abs($line['amount']), $accounts[$account_id]['account_currency_code']);
|
||||
if ($vendor === 'new' ? $new_name === '' : !isset($vendors[intval($vendor)])) {
|
||||
$error = "Pick the vendor for $what";
|
||||
return null;
|
||||
}
|
||||
if (!isset($categories[$category])) {
|
||||
$error = "Pick the category for $what";
|
||||
return null;
|
||||
}
|
||||
if ($client && !isset($clients[$client])) {
|
||||
$error = "The client picked for $what isn't one you can file expenses against";
|
||||
return null;
|
||||
}
|
||||
$bring[] = ['line' => $line, 'vendor' => $vendor === 'new' ? 0 : intval($vendor), 'new_vendor' => mb_substr($new_name, 0, 200), 'category' => $category, 'client' => $client,
|
||||
'billable' => intval(!empty($pick['billable']) && $client > 0 && $line['amount'] > 0)];
|
||||
}
|
||||
|
||||
// New vendors - one per name, or the one of ours already called that
|
||||
$made = 0;
|
||||
$by_name = [];
|
||||
foreach ($vendors as $vendor_id => $vendor) {
|
||||
$by_name[mb_strtolower(trim($vendor['vendor_name']))] = $vendor_id;
|
||||
}
|
||||
foreach ($bring as $i => $item) {
|
||||
if ($item['vendor']) {
|
||||
continue;
|
||||
}
|
||||
$name_key = mb_strtolower($item['new_vendor']);
|
||||
if (!isset($by_name[$name_key])) {
|
||||
$existing = mysqli_fetch_row(mysqli_query($mysqli, "SELECT vendor_id FROM vendors WHERE vendor_client_id = 0 AND vendor_archived_at IS NULL AND vendor_name = '" . escapeSql($item['new_vendor']) . "' LIMIT 1"));
|
||||
if ($existing) {
|
||||
$by_name[$name_key] = intval($existing[0]);
|
||||
} else {
|
||||
mysqli_query($mysqli, "INSERT INTO vendors SET " . vendorFormSet(['name' => $item['new_vendor'], 'description' => 'Added from a statement import']) . ", vendor_client_id = 0");
|
||||
$by_name[$name_key] = mysqli_insert_id($mysqli);
|
||||
logAudit('Vendor', 'Create', escapeSql(stripslashes((string) ($GLOBALS['session_name'] ?? 'ITFlow')) . " created vendor {$item['new_vendor']} from a statement import"), 0, $by_name[$name_key]);
|
||||
$made++;
|
||||
}
|
||||
}
|
||||
$bring[$i]['vendor'] = $by_name[$name_key];
|
||||
}
|
||||
|
||||
// The expenses, and what each merchant is next time
|
||||
$imported = 0;
|
||||
$total = 0.0;
|
||||
$min_date = null;
|
||||
$max_date = null;
|
||||
foreach ($bring as $item) {
|
||||
$line = $item['line'];
|
||||
mysqli_query($mysqli, "INSERT INTO expenses SET expense_date = '{$line['date']}', expense_amount = " . number_format($line['amount'], 2, '.', '') . ",
|
||||
expense_currency_code = '$currency', expense_vendor_id = {$item['vendor']}, expense_category_id = {$item['category']}, expense_account_id = $account_id,
|
||||
expense_client_id = {$item['client']}, expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
|
||||
expense_reference = '" . escapeSql($line['reference']) . "', expense_description = '" . escapeSql($line['description']) . "',
|
||||
expense_billable = {$item['billable']}, expense_markup = $markup, expense_import_key = '" . escapeSql($line['key_hash']) . "',
|
||||
expense_created_by = " . intval($session_user_id));
|
||||
$imported++;
|
||||
$total += $line['amount'];
|
||||
$min_date = $min_date === null || $line['date'] < $min_date ? $line['date'] : $min_date;
|
||||
$max_date = $max_date === null || $line['date'] > $max_date ? $line['date'] : $max_date;
|
||||
if ($line['key'] !== '') {
|
||||
mysqli_query($mysqli, "INSERT INTO expense_import_rules SET import_rule_match = '" . escapeSql($line['key']) . "', import_rule_vendor_id = {$item['vendor']},
|
||||
import_rule_category_id = {$item['category']}, import_rule_client_id = {$item['client']}, import_rule_billable = {$item['billable']}, import_rule_used_count = 1
|
||||
ON DUPLICATE KEY UPDATE import_rule_vendor_id = VALUES(import_rule_vendor_id), import_rule_category_id = VALUES(import_rule_category_id),
|
||||
import_rule_client_id = VALUES(import_rule_client_id), import_rule_billable = VALUES(import_rule_billable), import_rule_used_count = import_rule_used_count + 1");
|
||||
}
|
||||
}
|
||||
|
||||
// Lines left out that were entered by hand already - those expenses take their keys
|
||||
$linked = 0;
|
||||
foreach ($lines as $line) {
|
||||
$pick = $picks[$line['n']] ?? null;
|
||||
if ($line['entered'] && !$line['imported'] && (!$pick || empty($pick['take']))) {
|
||||
mysqli_query($mysqli, "UPDATE expenses SET expense_import_key = '" . escapeSql($line['key_hash']) . "' WHERE expense_id = {$line['entered']} AND expense_import_key IS NULL");
|
||||
$linked += mysqli_affected_rows($mysqli);
|
||||
}
|
||||
}
|
||||
|
||||
return ['imported' => $imported, 'total' => round($total, 2), 'vendors' => $made, 'linked' => $linked, 'from' => $min_date, 'to' => $max_date,
|
||||
'skipped' => count(array_filter($lines, function ($l) { return $l['imported']; }))];
|
||||
}
|
||||
@@ -35,24 +35,30 @@ function expenseRow($expense_id, $scoped = true) {
|
||||
}
|
||||
$scope = $scoped ? clientScopeSql('expenses.expense_client_id') : '';
|
||||
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT expenses.*, vendor_name, vendor_description, vendor_archived_at,
|
||||
category_name, category_color, category_icon, category_archived_at, account_name, account_archived_at, account_currency_code,
|
||||
client_name, client_abbreviation, user_name AS created_by_name, transfer_id,
|
||||
category_name, category_color, category_icon, category_archived_at, accounts.account_name, accounts.account_archived_at, accounts.account_currency_code,
|
||||
client_name, client_abbreviation, creator.user_name AS created_by_name, transfer_id,
|
||||
recurring_expense_frequency, recurring_expense_amount, recurring_expense_currency_code,
|
||||
invoice_prefix, invoice_number, invoice_status, item_subtotal AS billed_subtotal,
|
||||
refunded.expense_date AS refund_of_date, refunded.expense_amount AS refund_of_amount, refunded.expense_description AS refund_of_description,
|
||||
payer.user_name AS paid_by_name, paid_back.reimbursement_date, paid_back_account.account_name AS reimbursed_account_name,
|
||||
paying_out.reimbursement_id AS reimbursement_out_id, (SELECT u.user_name FROM users AS u WHERE u.user_id = paying_out.reimbursement_user_id) AS reimbursed_to_name,
|
||||
(SELECT COALESCE(SUM(-r.expense_amount), 0) FROM expenses AS r WHERE r.expense_refund_of_id = expenses.expense_id) AS refunded_amount,
|
||||
(SELECT COUNT(*) FROM expenses AS r WHERE r.expense_refund_of_id = expenses.expense_id) AS refund_count
|
||||
FROM expenses
|
||||
LEFT JOIN vendors ON vendor_id = expenses.expense_vendor_id
|
||||
LEFT JOIN categories ON category_id = expenses.expense_category_id
|
||||
LEFT JOIN accounts ON account_id = expenses.expense_account_id
|
||||
LEFT JOIN accounts ON accounts.account_id = expenses.expense_account_id
|
||||
LEFT JOIN clients ON client_id = expenses.expense_client_id
|
||||
LEFT JOIN users ON user_id = expenses.expense_created_by
|
||||
LEFT JOIN users AS creator ON creator.user_id = expenses.expense_created_by
|
||||
LEFT JOIN users AS payer ON payer.user_id = expenses.expense_paid_by
|
||||
LEFT JOIN transfers ON transfer_expense_id = expenses.expense_id
|
||||
LEFT JOIN expenses AS refunded ON refunded.expense_id = expenses.expense_refund_of_id
|
||||
LEFT JOIN recurring_expenses ON recurring_expense_id = expenses.expense_recurring_expense_id
|
||||
LEFT JOIN invoices ON invoice_id = expenses.expense_invoice_id
|
||||
LEFT JOIN invoice_items ON item_id = expenses.expense_invoice_item_id
|
||||
LEFT JOIN reimbursements AS paid_back ON paid_back.reimbursement_id = expenses.expense_reimbursement_id
|
||||
LEFT JOIN accounts AS paid_back_account ON paid_back_account.account_id = paid_back.reimbursement_account_id
|
||||
LEFT JOIN reimbursements AS paying_out ON paying_out.reimbursement_expense_id = expenses.expense_id
|
||||
WHERE expenses.expense_id = $expense_id $scope
|
||||
LIMIT 1"));
|
||||
return $row ?: null;
|
||||
@@ -75,6 +81,7 @@ function expenseShows() {
|
||||
'no_receipt' => ['label' => 'No receipt', 'icon' => 'fa-paperclip', 'where' => "COALESCE(expense_receipt, '') = '' AND expense_amount > 0", 'title' => 'No receipt attached yet'],
|
||||
'to_bill' => ['label' => 'To bill', 'icon' => 'fa-file-invoice-dollar', 'where' => expenseUnbilledSql(), 'title' => 'Billable to a client, and on no invoice yet'],
|
||||
'billed' => ['label' => 'Billed', 'icon' => 'fa-check-circle', 'where' => 'expense_invoice_id IS NOT NULL', 'title' => 'Billed on to a client on an invoice'],
|
||||
'to_reimburse' => ['label' => 'To reimburse', 'icon' => 'fa-hand-holding-usd', 'where' => expenseToReimburseSql(), 'title' => 'Paid personally by an agent, not paid back yet'],
|
||||
'refunds' => ['label' => 'Refunds', 'icon' => 'fa-undo-alt', 'where' => 'expense_amount < 0', 'title' => 'Money that came back - refunds and credits'],
|
||||
];
|
||||
}
|
||||
@@ -82,7 +89,7 @@ function expenseShows() {
|
||||
/**
|
||||
* The WHERE for a set of filters, as the list and the export take them
|
||||
* from the query string or the form: q, vendor, category, account, client,
|
||||
* method, recurring_expense_id, show, dtf and dtt. Starts with the vendor-expenses-only rule and
|
||||
* method, paid_by, recurring_expense_id, show, dtf and dtt. Starts with the vendor-expenses-only rule and
|
||||
* the agent's client scope. $summary is filled with what each filter is,
|
||||
* by name, for the export's heading.
|
||||
*/
|
||||
@@ -111,6 +118,11 @@ function expenseFiltersSql(array $src, &$summary = []) {
|
||||
$sql .= " AND expense_payment_method = '" . escapeSql($method) . "'";
|
||||
$summary['Paid by'] = $method;
|
||||
}
|
||||
$paid_by = intval($src['paid_by'] ?? 0);
|
||||
if ($paid_by) {
|
||||
$sql .= " AND expense_paid_by = $paid_by";
|
||||
$summary['Paid personally by'] = (string) getFieldById('users', $paid_by, 'user_name');
|
||||
}
|
||||
$recurring_id = intval($src['recurring_expense_id'] ?? 0);
|
||||
if ($recurring_id) {
|
||||
$sql .= " AND expense_recurring_expense_id = $recurring_id";
|
||||
@@ -261,6 +273,10 @@ function expenseSave(array $in, $expense_id = 0, &$error = '') {
|
||||
$error = 'That is the out side of a transfer between accounts - change it from Transfers';
|
||||
return 0;
|
||||
}
|
||||
if ($existing && $existing['reimbursement_out_id']) {
|
||||
$error = 'That is money paid back to ' . $existing['reimbursed_to_name'] . ' - undo the reimbursement to change it';
|
||||
return 0;
|
||||
}
|
||||
|
||||
$date = trim((string) ($in['date'] ?? ''));
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) || !checkdate(intval(substr($date, 5, 2)), intval(substr($date, 8, 2)), intval(substr($date, 0, 4)))) {
|
||||
@@ -300,9 +316,26 @@ function expenseSave(array $in, $expense_id = 0, &$error = '') {
|
||||
$error = 'Pick an expense category';
|
||||
return 0;
|
||||
}
|
||||
$account = intval($in['account'] ?? 0);
|
||||
// From one of our accounts, or paid personally by an agent - on no account
|
||||
// until they are paid back. Once paid back, who paid stays as it was.
|
||||
$personal = (string) ($in['account'] ?? '') === 'personal';
|
||||
$account = $personal ? 0 : intval($in['account'] ?? 0);
|
||||
$accounts = paymentAccounts($existing ? $existing['expense_account_id'] : 0);
|
||||
if (!isset($accounts[$account])) {
|
||||
$paid_by = $personal ? intval($in['paid_by'] ?? 0) : 0;
|
||||
if ($existing && $existing['expense_reimbursement_id'] && $paid_by !== intval($existing['expense_paid_by'])) {
|
||||
$error = 'It was paid back to ' . $existing['paid_by_name'] . ' - undo that reimbursement before changing who paid it';
|
||||
return 0;
|
||||
}
|
||||
if ($personal) {
|
||||
if ($amount < 0) {
|
||||
$error = 'Money back goes to one of your accounts - pick which';
|
||||
return 0;
|
||||
}
|
||||
if (!isset(expensePayers($existing ? $existing['expense_paid_by'] : 0)[$paid_by])) {
|
||||
$error = 'Pick who paid it';
|
||||
return 0;
|
||||
}
|
||||
} elseif (!isset($accounts[$account])) {
|
||||
$error = 'Pick the account it was paid from';
|
||||
return 0;
|
||||
}
|
||||
@@ -336,7 +369,7 @@ function expenseSave(array $in, $expense_id = 0, &$error = '') {
|
||||
$markup = round(max(0, min(1000, $markup)), 2);
|
||||
|
||||
$set = "expense_date = '$date', expense_amount = $amount, expense_vendor_id = $vendor, expense_category_id = $category,
|
||||
expense_account_id = $account, expense_client_id = $client_id, expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
|
||||
expense_account_id = $account, expense_paid_by = $paid_by, expense_client_id = $client_id, expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
|
||||
expense_reference = '" . escapeSql($reference) . "', expense_description = '" . escapeSql($description) . "',
|
||||
expense_billable = $billable, expense_markup = $markup";
|
||||
|
||||
@@ -344,7 +377,7 @@ function expenseSave(array $in, $expense_id = 0, &$error = '') {
|
||||
mysqli_query($mysqli, "UPDATE expenses SET $set WHERE expense_id = $expense_id");
|
||||
return $expense_id;
|
||||
}
|
||||
$currency = escapeSql((string) ($accounts[$account]['account_currency_code'] ?: $session_company_currency));
|
||||
$currency = escapeSql((string) ($personal ? $session_company_currency : ($accounts[$account]['account_currency_code'] ?: $session_company_currency)));
|
||||
mysqli_query($mysqli, "INSERT INTO expenses SET $set, expense_currency_code = '$currency', expense_created_by = " . intval($session_user_id)
|
||||
. ($refund_of ? ", expense_refund_of_id = $refund_of" : ''));
|
||||
return mysqli_insert_id($mysqli);
|
||||
@@ -367,6 +400,10 @@ function expenseDelete($expense_id, &$error = '') {
|
||||
$error = 'That is the out side of a transfer between accounts - delete the transfer instead';
|
||||
return null;
|
||||
}
|
||||
if ($row['reimbursement_out_id']) {
|
||||
$error = 'That is money paid back to ' . $row['reimbursed_to_name'] . ' - undo the reimbursement instead';
|
||||
return null;
|
||||
}
|
||||
$expense_id = intval($row['expense_id']);
|
||||
expenseReceiptDeleteFile($row['expense_receipt']);
|
||||
mysqli_query($mysqli, "UPDATE product_stock SET stock_expense_id = NULL WHERE stock_expense_id = $expense_id");
|
||||
@@ -1334,3 +1371,183 @@ function expenseWriteOff($client_id, array $expense_ids, $by) {
|
||||
}
|
||||
return $done;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- Paid personally */
|
||||
|
||||
/*
|
||||
* An agent can pay for something themselves - a cable run to the store, a
|
||||
* hotel - and be paid back. Such an expense (expense_paid_by) counts as
|
||||
* spending on its date like any other, but is on none of our accounts, so
|
||||
* no balance moves, until a reimbursement pays the agent back: one payment
|
||||
* from an account, on its own date, for one or more of their expenses. That
|
||||
* payment is an expense with no vendor (reimbursement_expense_id), the way
|
||||
* the out side of a transfer is, so it moves the balance and stays out of
|
||||
* the spending totals.
|
||||
*/
|
||||
|
||||
/** The SQL that makes an expense to reimburse: paid personally, not paid back yet. */
|
||||
function expenseToReimburseSql() {
|
||||
return "expense_paid_by > 0 AND expense_reimbursement_id IS NULL AND expense_vendor_id > 0 AND expense_archived_at IS NULL";
|
||||
}
|
||||
|
||||
/** Who can have paid for an expense personally - active agents, and $keep_id - id => name. */
|
||||
function expensePayers($keep_id = 0) {
|
||||
global $mysqli;
|
||||
$keep_id = intval($keep_id);
|
||||
$payers = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT user_id, user_name FROM users WHERE (user_type = 1 AND user_archived_at IS NULL) OR user_id = $keep_id ORDER BY user_name ASC");
|
||||
while ($row = mysqli_fetch_row($sql)) {
|
||||
$payers[intval($row[0])] = $row[1];
|
||||
}
|
||||
return $payers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expenses waiting to be paid back - one agent's ($user_id) or everyone's,
|
||||
* optionally only $ids, in the agent's client scope - by agent: user_id =>
|
||||
* [user_id, user_name, expenses (id => row), total, count, oldest (days)].
|
||||
*/
|
||||
function expenseToReimburse($user_id = 0, array $ids = []) {
|
||||
global $mysqli;
|
||||
$user_id = intval($user_id);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
$sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, client_name, user_name, DATEDIFF(CURDATE(), expense_date) AS waiting
|
||||
FROM expenses
|
||||
JOIN users ON user_id = expense_paid_by
|
||||
LEFT JOIN vendors ON vendor_id = expense_vendor_id
|
||||
LEFT JOIN categories ON category_id = expense_category_id
|
||||
LEFT JOIN clients ON client_id = expense_client_id
|
||||
WHERE " . expenseToReimburseSql() . ($user_id ? " AND expense_paid_by = $user_id" : '') . ($ids ? ' AND expense_id IN (' . implode(',', $ids) . ')' : '')
|
||||
. ' ' . clientScopeSql('expense_client_id') . "
|
||||
ORDER BY user_name ASC, expense_date ASC, expense_id ASC");
|
||||
$agents = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$uid = intval($row['expense_paid_by']);
|
||||
if (!isset($agents[$uid])) {
|
||||
$agents[$uid] = ['user_id' => $uid, 'user_name' => $row['user_name'], 'expenses' => [], 'total' => 0.0, 'count' => 0, 'oldest' => 0];
|
||||
}
|
||||
$agents[$uid]['expenses'][intval($row['expense_id'])] = $row;
|
||||
$agents[$uid]['total'] = round($agents[$uid]['total'] + floatval($row['expense_amount']), 2);
|
||||
$agents[$uid]['count']++;
|
||||
$agents[$uid]['oldest'] = max($agents[$uid]['oldest'], intval($row['waiting']));
|
||||
}
|
||||
return $agents;
|
||||
}
|
||||
|
||||
/** How many expenses are waiting to be paid back, and what they come to - for the list and the dashboard. */
|
||||
function expenseToReimburseCount() {
|
||||
global $mysqli;
|
||||
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*), COALESCE(SUM(expense_amount), 0), COUNT(DISTINCT expense_paid_by) FROM expenses
|
||||
WHERE " . expenseToReimburseSql() . ' ' . clientScopeSql('expense_client_id')));
|
||||
return ['count' => intval($row[0]), 'total' => round(floatval($row[1]), 2), 'agents' => intval($row[2])];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pay an agent back for their ticked expenses, from one of our accounts.
|
||||
* $opts: account_id, date, payment_method, reference, by (who, for the log).
|
||||
* The expenses are claimed first, so two agents can't pay one back twice.
|
||||
* Returns [reimbursement_id, amount, count, user_name, currency], or null
|
||||
* with $error.
|
||||
*/
|
||||
function expenseReimburse($user_id, array $expense_ids, array $opts, &$error = '') {
|
||||
global $mysqli, $session_user_id, $session_company_currency;
|
||||
$error = '';
|
||||
$user_id = intval($user_id);
|
||||
$waiting = expenseToReimburse($user_id, $expense_ids)[$user_id] ?? null;
|
||||
if (!$user_id || !$expense_ids || !$waiting) {
|
||||
$error = 'Nothing to pay back - those expenses are already paid back, or not paid personally.';
|
||||
return null;
|
||||
}
|
||||
$account = intval($opts['account_id'] ?? 0);
|
||||
$accounts = paymentAccounts();
|
||||
if (!isset($accounts[$account])) {
|
||||
$error = 'Pick the account the money comes from';
|
||||
return null;
|
||||
}
|
||||
$date = (string) ($opts['date'] ?? '');
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) || !checkdate(intval(substr($date, 5, 2)), intval(substr($date, 8, 2)), intval(substr($date, 0, 4)))) {
|
||||
$error = 'Enter the date they were paid back';
|
||||
return null;
|
||||
}
|
||||
$method = trim((string) ($opts['payment_method'] ?? ''));
|
||||
if ($method !== '' && !in_array($method, paymentMethods(), true)) {
|
||||
$error = 'Pick how they were paid back';
|
||||
return null;
|
||||
}
|
||||
$reference = mb_substr(trim((string) ($opts['reference'] ?? '')), 0, 200);
|
||||
$by = (string) ($opts['by'] ?? 'ITFlow');
|
||||
$currency = (string) ($accounts[$account]['account_currency_code'] ?: $session_company_currency);
|
||||
|
||||
// Claim them, then pay back what was claimed
|
||||
mysqli_query($mysqli, "INSERT INTO reimbursements SET reimbursement_user_id = $user_id, reimbursement_date = '$date', reimbursement_amount = 0,
|
||||
reimbursement_currency_code = '" . escapeSql($currency) . "', reimbursement_account_id = $account,
|
||||
reimbursement_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ", reimbursement_reference = '" . escapeSql($reference) . "',
|
||||
reimbursement_expense_id = 0, reimbursement_created_by = " . intval($session_user_id));
|
||||
$reimbursement_id = mysqli_insert_id($mysqli);
|
||||
mysqli_query($mysqli, "UPDATE expenses SET expense_reimbursement_id = $reimbursement_id
|
||||
WHERE expense_id IN (" . implode(',', array_keys($waiting['expenses'])) . ") AND expense_paid_by = $user_id AND " . expenseToReimburseSql());
|
||||
$claimed = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*), COALESCE(SUM(expense_amount), 0) FROM expenses WHERE expense_reimbursement_id = $reimbursement_id"));
|
||||
$count = intval($claimed[0]);
|
||||
$amount = round(floatval($claimed[1]), 2);
|
||||
if (!$count) {
|
||||
mysqli_query($mysqli, "DELETE FROM reimbursements WHERE reimbursement_id = $reimbursement_id");
|
||||
$error = 'Nothing to pay back - someone else paid those back just now.';
|
||||
return null;
|
||||
}
|
||||
|
||||
// The money out of the account - an expense with no vendor, like a transfer's
|
||||
$description = "Reimbursement to {$waiting['user_name']} - " . ($count === 1 ? '1 expense' : "$count expenses");
|
||||
mysqli_query($mysqli, "INSERT INTO expenses SET expense_date = '$date', expense_amount = $amount, expense_currency_code = '" . escapeSql($currency) . "',
|
||||
expense_vendor_id = 0, expense_category_id = 0, expense_account_id = $account, expense_client_id = 0,
|
||||
expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ", expense_reference = '" . escapeSql($reference) . "',
|
||||
expense_description = '" . escapeSql($description) . "', expense_created_by = " . intval($session_user_id));
|
||||
$cash_id = mysqli_insert_id($mysqli);
|
||||
mysqli_query($mysqli, "UPDATE reimbursements SET reimbursement_amount = $amount, reimbursement_expense_id = $cash_id WHERE reimbursement_id = $reimbursement_id");
|
||||
|
||||
logAudit('Expense', 'Reimburse', escapeSql("$by paid {$waiting['user_name']} back " . billingMoney($amount, $currency) . ' for ' . ($count === 1 ? '1 expense' : "$count expenses")
|
||||
. " from {$accounts[$account]['account_name']}"), 0, $reimbursement_id);
|
||||
|
||||
return ['reimbursement_id' => $reimbursement_id, 'amount' => $amount, 'count' => $count, 'user_name' => $waiting['user_name'], 'currency' => $currency];
|
||||
}
|
||||
|
||||
/** A reimbursement with who was paid back, the account and who entered it - or null. */
|
||||
function reimbursementRow($reimbursement_id) {
|
||||
global $mysqli;
|
||||
$id = intval($reimbursement_id);
|
||||
return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT reimbursements.*, payee.user_name, account_name, creator.user_name AS created_by_name
|
||||
FROM reimbursements
|
||||
LEFT JOIN users AS payee ON payee.user_id = reimbursement_user_id
|
||||
LEFT JOIN users AS creator ON creator.user_id = reimbursement_created_by
|
||||
LEFT JOIN accounts ON account_id = reimbursement_account_id
|
||||
WHERE reimbursement_id = $id")) ?: null;
|
||||
}
|
||||
|
||||
/** The expenses a reimbursement paid back, oldest first. */
|
||||
function reimbursementExpenses($reimbursement_id) {
|
||||
global $mysqli;
|
||||
$id = intval($reimbursement_id);
|
||||
$rows = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, client_name FROM expenses
|
||||
LEFT JOIN vendors ON vendor_id = expense_vendor_id
|
||||
LEFT JOIN categories ON category_id = expense_category_id
|
||||
LEFT JOIN clients ON client_id = expense_client_id
|
||||
WHERE expense_reimbursement_id = $id ORDER BY expense_date ASC, expense_id ASC");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** Undo a reimbursement - the money out of the account goes, and its expenses are to reimburse again. The row it undid, or null. */
|
||||
function reimbursementDelete($reimbursement_id) {
|
||||
global $mysqli;
|
||||
$row = reimbursementRow($reimbursement_id);
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
$id = intval($row['reimbursement_id']);
|
||||
mysqli_query($mysqli, "UPDATE expenses SET expense_reimbursement_id = NULL WHERE expense_reimbursement_id = $id");
|
||||
mysqli_query($mysqli, "DELETE FROM expenses WHERE expense_id = " . intval($row['reimbursement_expense_id']) . " AND expense_vendor_id = 0");
|
||||
mysqli_query($mysqli, "DELETE FROM reimbursements WHERE reimbursement_id = $id");
|
||||
return $row;
|
||||
}
|
||||
|
||||
@@ -387,6 +387,7 @@ function getExportColumns($export_type) {
|
||||
'expense_payment_method' => ['label' => 'Paid By', 'default' => false],
|
||||
'expense_reference' => ['label' => 'Reference', 'default' => false],
|
||||
'expense_receipt_display' => ['label' => 'Receipt', 'default' => false],
|
||||
'expense_paid_by_display' => ['label' => 'Paid Personally', 'default' => false],
|
||||
'expense_billing_display' => ['label' => 'Billing', 'default' => false],
|
||||
'expense_billed_on' => ['label' => 'Billed On', 'default' => false],
|
||||
'user_name' => ['label' => 'Entered By', 'default' => false],
|
||||
|
||||
218
js/expense_import.js
Normal file
218
js/expense_import.js
Normal file
@@ -0,0 +1,218 @@
|
||||
/*
|
||||
* Import Statement's review (agent/expense_import.php?step=review).
|
||||
*
|
||||
* Each line's vendor, category and client start as they were matched. A
|
||||
* vendor picked for a line fills in its category (the vendor's last one)
|
||||
* and the same vendor on the other lines from that merchant that nothing
|
||||
* matched yet; + New vendor shows a name to make it with. Bill on shows
|
||||
* once there is a client. Lines not new (money in, lines already in) are
|
||||
* hidden until asked for. The ticked lines need a vendor and category;
|
||||
* the summary and button follow the ticks. On Import every line's choices
|
||||
* go as one JSON field, so a long statement stays under max_input_vars.
|
||||
*
|
||||
* Needs js/billing_items.js for itflowBillingMoney when it is loaded, and
|
||||
* falls back to Intl otherwise.
|
||||
*
|
||||
* itflowExpenseImport({ currency: 'USD', locale: 'en-US', defaults: { vendor_id: category_id } });
|
||||
*/
|
||||
function itflowExpenseImport(options) {
|
||||
var opts = options || {};
|
||||
var form = document.getElementById('expenseImportReview');
|
||||
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-import-bulk-category]');
|
||||
var bulkClient = form.querySelector('[data-import-bulk-client]');
|
||||
var defaults = opts.defaults || {};
|
||||
|
||||
function money(amount) {
|
||||
try {
|
||||
return new Intl.NumberFormat(opts.locale || undefined, { style: 'currency', currency: opts.currency || 'USD' }).format(amount);
|
||||
} catch (e) {
|
||||
return amount.toFixed(2);
|
||||
}
|
||||
}
|
||||
|
||||
function part(row, name) {
|
||||
return row.querySelector('[data-import-' + name + ']');
|
||||
}
|
||||
|
||||
// One line: the new vendor's name only for + New vendor, Bill on only with a client
|
||||
function tidy(row) {
|
||||
var vendor = part(row, 'vendor');
|
||||
if (!vendor) {
|
||||
return;
|
||||
}
|
||||
var take = part(row, 'take');
|
||||
part(row, 'new-vendor').hidden = vendor.value !== 'new';
|
||||
part(row, 'billable-box').hidden = part(row, 'client').value === '0' || Number(row.getAttribute('data-amount')) <= 0;
|
||||
var on = take.checked;
|
||||
vendor.required = on;
|
||||
part(row, 'category').required = on;
|
||||
part(row, 'new-vendor').required = on && vendor.value === 'new';
|
||||
row.classList.toggle('itflow-unbilled-off', !on);
|
||||
}
|
||||
|
||||
function update() {
|
||||
var count = 0;
|
||||
var total = 0;
|
||||
rows.forEach(function (row) {
|
||||
var take = part(row, 'take');
|
||||
tidy(row);
|
||||
if (take.checked && !take.disabled) {
|
||||
count++;
|
||||
total += Number(row.getAttribute('data-amount'));
|
||||
}
|
||||
});
|
||||
summary.textContent = count ? count + ' line' + (count === 1 ? '' : 's') + ' · ' + money(Math.round(total * 100) / 100) : 'Tick the lines to import';
|
||||
submitLabel.textContent = count ? 'Import ' + count : 'Import';
|
||||
submit.disabled = count === 0;
|
||||
if (all) {
|
||||
var shown = rows.filter(function (row) { return !row.hidden && !part(row, 'take').disabled; });
|
||||
var on = shown.filter(function (row) { return part(row, 'take').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) {
|
||||
['vendor', 'category', 'client'].forEach(function (name) {
|
||||
var select = part(row, name);
|
||||
if (select && select.getAttribute('data-value') !== null) {
|
||||
var value = select.getAttribute('data-value');
|
||||
if (select.querySelector('option[value="' + CSS.escape(value) + '"]')) {
|
||||
select.value = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (row.hasAttribute('data-import-extra')) {
|
||||
row.hidden = true;
|
||||
}
|
||||
});
|
||||
|
||||
// A vendor picked fills in its category, and the same merchant's other unmatched lines
|
||||
form.addEventListener('change', function (e) {
|
||||
var row = e.target.closest('[data-import-row]');
|
||||
if (row && e.target.matches('[data-import-vendor]')) {
|
||||
row.dataset.touched = '1';
|
||||
var vendor = e.target.value;
|
||||
var category = part(row, 'category');
|
||||
if (vendor !== '' && vendor !== 'new' && defaults[vendor] && !category.dataset.touched) {
|
||||
category.value = String(defaults[vendor]);
|
||||
}
|
||||
var key = row.getAttribute('data-key');
|
||||
if (key && vendor !== '') {
|
||||
rows.forEach(function (other) {
|
||||
var otherVendor = part(other, 'vendor');
|
||||
if (other === row || other.getAttribute('data-key') !== key || other.dataset.touched || !otherVendor || (otherVendor.value !== '' && otherVendor.value !== 'new')) {
|
||||
return;
|
||||
}
|
||||
otherVendor.value = vendor;
|
||||
part(other, 'new-vendor').value = part(row, 'new-vendor').value;
|
||||
if (!part(other, 'category').dataset.touched) {
|
||||
part(other, 'category').value = category.value;
|
||||
}
|
||||
});
|
||||
}
|
||||
} else if (row && e.target.matches('[data-import-category], [data-import-client]')) {
|
||||
e.target.dataset.touched = '1';
|
||||
}
|
||||
if (e.target === bulkCategory || e.target === bulkClient) {
|
||||
var name = e.target === bulkCategory ? 'category' : 'client';
|
||||
if (e.target.value !== '') {
|
||||
rows.forEach(function (r) {
|
||||
if (part(r, 'take').checked && part(r, name)) {
|
||||
part(r, name).value = e.target.value;
|
||||
part(r, name).dataset.touched = '1';
|
||||
}
|
||||
});
|
||||
}
|
||||
e.target.value = '';
|
||||
}
|
||||
update();
|
||||
});
|
||||
|
||||
// A new vendor's name typed on one line follows to the same merchant's lines
|
||||
form.addEventListener('input', function (e) {
|
||||
if (!e.target.matches('[data-import-new-vendor]')) {
|
||||
return;
|
||||
}
|
||||
var row = e.target.closest('[data-import-row]');
|
||||
var key = row.getAttribute('data-key');
|
||||
rows.forEach(function (other) {
|
||||
if (other !== row && key && other.getAttribute('data-key') === key && part(other, 'vendor') && part(other, 'vendor').value === 'new' && !other.dataset.touched) {
|
||||
part(other, 'new-vendor').value = e.target.value;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (all) {
|
||||
all.addEventListener('change', function () {
|
||||
rows.forEach(function (row) {
|
||||
var take = part(row, 'take');
|
||||
if (!row.hidden && !take.disabled) {
|
||||
take.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) {
|
||||
part(row, 'take').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')) {
|
||||
return;
|
||||
}
|
||||
var take = part(row, 'take');
|
||||
if (!take.disabled) {
|
||||
take.checked = !take.checked;
|
||||
update();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
form.addEventListener('submit', function (e) {
|
||||
if (!form.reportValidity()) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
var list = rows.map(function (row) {
|
||||
var vendor = part(row, 'vendor');
|
||||
return {
|
||||
n: Number(row.getAttribute('data-n')),
|
||||
take: part(row, 'take').checked && !part(row, 'take').disabled,
|
||||
vendor: vendor ? vendor.value : '',
|
||||
new_vendor: vendor ? part(row, 'new-vendor').value : '',
|
||||
category: part(row, 'category') ? part(row, 'category').value : '',
|
||||
client: part(row, 'client') ? part(row, 'client').value : '0',
|
||||
billable: part(row, 'billable') ? part(row, 'billable').checked : false
|
||||
};
|
||||
});
|
||||
picks.value = JSON.stringify(list);
|
||||
});
|
||||
|
||||
update();
|
||||
}
|
||||
Reference in New Issue
Block a user