Income modernized for MSP use: rebuilt Income list with cards for this month against the same days of last month, the year so far with a monthly average, recurring per month from running recurring invoices and still owed on invoices with the late part, pills for invoice payments, other income, paid online and no category, client/category/date filters with account and payment method under More filters, search by amount, reference and invoice number, footer total, sort whitelist and ?open=; new payment quick look with the invoice, paid in all and still owed, the other payments on it, online fee when recorded, Open Invoice, Email Receipt, Edit and Delete; new other income quick look with who entered it and what the client has paid in this year, with Edit, Copy and Delete; one New/Edit/Copy Other Income form with a client picker, an icon on every field, validation of every field and the currency taken from the account; other income now needs Financial write to add and change and Financial full to delete, payments keep their Sales and Financial rules; bulk Set Category (a payment's invoice takes it), Set Account, Set Payment Method, Set Client and Delete for other income, with payments left alone where they belong to their invoice; export with the list's filters plus Invoice and Paid Online columns; income counted the same everywhere through new functions/income.php, so uncategorised other income now counts on the dashboard, client overview, Income Summary, P&L, Income by Client and Client Profitability while transfers stay out; Income Summary and P&L No category rows and type links open the list, Transactions opens the quick looks, Accounts link to their transactions and income, search has an Income group; demo data adds quarterly rebates, interest and referral fees; income_model.php and the three old bulk modals removed; database 3.0.5 makes revenue_description text, adds revenue_created_by backfilled from the audit log and date keys on revenues and payments; CHANGELOG updated

This commit is contained in:
johnnyq
2026-10-16 21:17:50 -04:00
parent a2a0823163
commit 11dabf8a26
34 changed files with 2025 additions and 1726 deletions

View File

@@ -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.4) 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.5) in the same pass. Nothing else is required.
This is a big release, with twenty-five database steps in one go, so take a backup before you update.
This is a big release, with twenty-six 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:
@@ -27,6 +27,8 @@ Recurring expenses keep their next date and from then on run on that day of the
Trips already logged keep the miles they were entered with (see Breaking Changes, Trips). Each takes who logged it from the audit log, or its driver where the log has no record. A trip for a client whose destination is one of that client's locations, by name or by address, is linked to that location. Trips already logged count as driven in a company vehicle and not billable, so nothing is paid back or billed for them until you say so (see New Features, Trips). No mileage rate or trip charge is set, and mileage goes under an expense category called Mileage, or Travel, when there is one.
Other income already entered (money in that isn't for an invoice, which used to be called revenue) takes who entered it from the audit log, where it has a record of it. Income with no category now counts in the dashboard and reports, so their totals can go up by that much (see Breaking Changes, Income).
If you are coming from 26.08 or earlier, the database update still has to be run from the command line one time, exactly as described under Upgrading to 26.09 below.
### Breaking Changes and Notes
@@ -94,6 +96,13 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Every agent can open Trips when accounting is on, and log their own driving. An agent without Financial access sees only the trips they drove or logged, and can change or delete only those. Logging a trip for someone else, or changing theirs, needs write access to Financial, and deleting theirs needs full access. Before, any agent who opened the page saw every trip of their clients and could change any of them.
- A trip's miles are the whole trip. The form asks for the miles one way and doubles them for a round trip. The old form saved the number as typed, whether Round Trip was ticked or not, so an older round trip entered as the miles one way still counts once. Edit those to correct them.
- The database column `trips.trip_end_odmeter` is now `trip_end_odometer`. Anything of your own that reads it, such as a custom report, needs the new name.
- Income:
- Money in that isn't for an invoice is now called other income (it was revenue). Adding and changing it needs write access to Financial, and deleting it full access. It used to need Sales. Payments keep the invoice's rules, full access to Sales and Financial.
- Other income counts whether it has a category or not, on the Income list, the dashboard, the client overview and every report, as No category when it has none. The dashboard and reports used to leave it out until it had a category, so their income can go up after the update by what had none. Money coming in from a transfer between your own accounts is still not income.
- New other income takes the currency of the account it goes into. It used to take the company's currency whatever the account.
- The Income list's Bulk menu has Set Category, Set Account, Set Payment Method and the new Set Client, a window each, and Delete. A payment's category is its invoice's, so Set Category on a payment sets its invoice's category, as before. A payment's client is its invoice's, so Set Client leaves payments alone, and payments are deleted from their invoice, not here.
- The export's Type column says Invoice payment or Other income (it was Payment or Revenue), and Source is now What for, with new Invoice and Paid Online columns.
- In Transactions, a payment's date opens its quick look instead of the invoice. The quick look has Open Invoice.
- 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:
@@ -575,6 +584,24 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Once billed, a trip keeps its distance, client and billable, and can't be deleted.
- The dashboard shows Trips to bill and Mileage to pay back, the client overview Trips to bill, and the Unbilled Time count in the menu counts trips.
- The demo data logs a trip to the site for each onsite ticket fixed in the last six months. The last six weeks of driving are in the agent's own vehicle, and a billable ticket's trip in the last month is billable when trips have a charge or rate.
- **Income** (rebuilt)
- Income is counted the same way everywhere - the Income list, the dashboard, the client overview, Income Summary, Profit & Loss, Income by Client and Client Profitability: invoice payments, and other income (money in that isn't for an invoice) whether it has a category or not. Money moved between your own accounts is left out.
- Along the top of the list: what came in this month against the same days of last month, the year so far with its monthly average, what the running recurring invoices bill a month, and what is still owed on invoices with how much of it is late. Each one opens what is behind it.
- Pills cut the list to invoice payments, other income, what was paid online and what has no category, each with a count. Filter by client, category and date, and under More filters by the account it went into and how it was paid. Search finds what it was for, an invoice number, a reference such as a check number, an amount, the client, category or account. The total of everything the filters leave sits under the list.
- Each row shows the invoice and what it was for (or what the other income was), how it was paid and its reference, the category with its colour, the client, the account, and the amount with a mark when it was paid online.
- Clicking a payment opens its quick look:
- the invoice it paid, its status and due date, what it came to, what has been paid on it in all and what is still owed
- the other payments on the same invoice, each opening its own
- the client, the invoice's category, the account, how it was paid and the reference
- for a payment made online, the payment provider's fee and what came in after it, when the fee is in the expenses
- Open Invoice, Email Receipt (to the client's billing contacts again), Edit and Delete
- Clicking other income opens its quick look: what it was with the rest of the description as notes, the client, category, account, how it was paid, the reference, who entered it and when, and what has come in from that client this year. Edit, Copy and Delete.
- New Income, Edit and Copy are one form with an icon on every field. Pick the client it came from - a rebate passed on to a client, a deposit held for them - and it counts for them in Income by Client and Client Profitability. The amount shows the account's currency, and can be negative for money that went back out. Every field is checked when it is saved: a real date, an amount, an account and an income category. Copy dates the copy today and leaves off the reference.
- A client's Income page has the same cards and pills for that client, with New Income starting with them.
- Bulk actions set the category, account, payment method or client on the ticked rows, or delete the other income among them. Each window says what it will leave alone.
- Export takes the same filters as the list, including the pills, with Invoice and Paid Online columns.
- Income Summary and Profit & Loss list No category as a line, opening those on the list, and their Invoice payments and Other income figures open those pills. Accounts link to Transactions and the income into each account. Search finds other income by what it was, its reference or its amount, and payments by their reference, opening the quick look.
- The demo data adds the money an MSP takes in besides invoices: a distributor's partner rebate each quarter, interest on the savings account and the odd referral fee.
### Bug Fixes
@@ -630,6 +657,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Users: Your account > Activity showed other agents' sign-ins. A password with a space at the start or end was saved inconsistently, so the agent either could not sign in or could sign in but not open credentials. Passwords are now saved exactly as typed.
- Users: disabling a user left a blank name in the audit log.
- Income on the dashboard and in the reports counted money moved between your own accounts as income when the transfer had been given a category.
- Income: the Invoice payments and Other revenue figures on the Income Summary report opened the whole Income list, as the list didn't understand their links. Sorting the Income list by a column it doesn't have gave a database error.
- Income: the revenue form saved whatever was typed, such as no account, no category or an amount of nothing. A revenue's client couldn't be set, so it never counted for the client.
- Client Portal: a ticket rating could be saved as any value. Only Good and Bad, the two buttons the portal shows, are accepted now. The demo data rated tickets Great and Ok, which the portal never offers, and now uses Good and Bad.
- Notifications that linked to a page did not open correctly from Admin pages.
- Messages showed a backslash before apostrophes and quotes in names, or showed `&` instead of `&`.
@@ -642,7 +671,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
### Developer Updates
- Database 2.8.0 to 3.0.4, one file per step under `admin/database_updates/`, with `db.sql` matching 3.0.4:
- Database 2.8.0 to 3.0.5, one file per step under `admin/database_updates/`, with `db.sql` matching 3.0.5:
- 2.8.0: `racks.rack_units_descending`, `rack_power_capacity` and `rack_photo_rear`. On `rack_units`: `unit_face`, `unit_full_depth`, `unit_type`, `unit_power_watts`, `unit_notes` and a `unit_asset_id` key. Unlinked items move from asset id 0 to NULL.
- 2.8.1: `location_documents` and `location_files`.
- 2.8.2: `vendor_tags` (tag type 6), and `vendor_contact_phone_country_code`, `vendor_contact_phone` and `vendor_contact_email`.
@@ -680,6 +709,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- 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`.
- 3.0.3: `trips.trip_end_odmeter` renamed `trip_end_odometer`, and `trip_miles` from `float(15,1)` to `decimal(10,1)` (0.0). New `trip_location_id`, `trip_ticket_id` and `trip_created_by` (0), keyed with `trip_user_id` (`trip_user_id`, `trip_date`). `trip_created_by` is backfilled from the audit log's Trip Create entries, else the driver, and `trip_location_id` where the destination matches one of the client's locations by name or by `formatAddress()` of its address, case and spacing aside.
- 3.0.4: `trips.trip_own_vehicle` (0), `trip_expense_id` (0, keyed), `trip_billable` (0), `trip_invoice_id` (0, keyed) and `trip_invoice_item_id` (0). `settings.config_mileage_unit` ('mi' or 'km'), `config_mileage_rate` (`decimal(10,4)`, 0), `config_mileage_category_id` (set to an Expense category named Mileage, else Travel), `config_mileage_vendor_id`, `config_trip_charge` (`decimal(15,2)`), `config_trip_bill_rate` (`decimal(10,4)`), `config_trip_included` (`decimal(10,1)`) and `config_trip_item_name` ('Travel').
- 3.0.5: `revenues.revenue_description` becomes `text`, with `revenue_created_by` (0, backfilled from the audit log's Revenue Create entries) and a `revenue_date` key. `payments` gets a `payment_date` key.
- 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`.
@@ -732,7 +762,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- `agent/reports/includes/inc_all_reports.php` is kept for custom report pages and now loads the two new includes.
- Tax Collected works out every tax for the period in one query (`taxCollected()` in the page), with the same figures as `getMonthlyTax()`.
- Budgets: `agent/post/budget.php` handles `save_budget` and `copy_budget`, needing Financial at level 2 and a CSRF token. A blank or zero amount removes that month's budget rather than storing 0.
- `dashboardRevenueSql()` in `functions/dashboard.php` is the one rule for which revenues count as income, used by the dashboard and the reports. It leaves out the incoming side of transfers.
- `dashboardRevenueSql()` in `functions/dashboard.php` is the one rule for which revenues count as income, used by the dashboard and the reports. It leaves out the incoming side of transfers. It now returns `incomeRevenueSql('revenues.revenue_id')` (see Income below), so uncategorised revenues count.
- CSS: the `.itflow-report-*` classes in `css/itflow_custom.css`, with print rules that keep side-by-side cards together.
- Client portal: `add_ticket_feedback` stores only `Good` or `Bad`. Demo data rates some closed tickets and leaves a few older Windows machines on Windows 10, so the satisfaction and lifecycle reports have something to show.
- The client actions menu links to the Client Review for that client, and the credentials list's rotation report link keeps the client.
@@ -884,6 +914,21 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Settings: the Trips and Mileage section of `admin/settings_invoice.php` (`#mileage`), saved by `edit_invoice_settings`.
- `get_side_nav_counts.php` and `inc_all_client.php` set `$num_unbilled_trips` for the Unbilled Time badge. `dashboardAttention()` adds Trips to bill and Mileage to pay back, and `clientOverviewAttention()` Trips to bill. `dashboardTrips()` returns `unit` for the chart, and the Mileage report's `rate` defaults to the mileage rate.
- Seeds: `demoBuildClient()` and `demoBuildCompanyFinancials()` set `trip_own_vehicle` for the last 45 days, and `trip_billable` for a billable ticket's trip in the last 30 when `tripBillingOn()`.
- Income, in the new `functions/income.php` (loaded by `functions.php` after `trips.php`):
- `incomeRevenueSql($column)` is the one rule for which revenues are income - those that aren't the in side of a transfer (`NOT EXISTS` on `transfers.transfer_revenue_id`), categorised or not. `dashboardRevenueSql()` returns it, and `clientOverviewMoney()`, `clientOverviewMonthly()` and `dashboardTopClients()` use that in place of `revenue_category_id > 0`.
- Access: `incomeCanEdit()` (Financial at 2), `incomeCanDelete()` (Financial at 3) and `incomeCanEditPayments()` (Sales and Financial at 3, as `edit_payment` and `delete_payment`).
- `incomeUnionSql()` is every payment and non-transfer revenue as one row set, in the agent's client scope (`clientScopeSql('COALESCE(invoice_client_id, 0)')` for payments), with `income_type` (`payment` or `revenue`), `income_id`, `income_date`, `income_created_at`, `income_invoice_id`, `invoice_prefix`, `invoice_number`, `invoice_status`, `income_description` (the invoice's scope for a payment), `income_category_id`, `category_name`, `category_color`, `income_client_id`, `client_name`, `income_amount`, `income_currency_code`, `income_method`, `income_reference`, `income_account_id`, `account_name`, `account_archived_at` and `income_online` (`incomeOnlineSql()`: a reference of `Stripe - pi_...`). Select from it as a derived table `AS income`.
- The list and export share `incomeFiltersSql($src, &$summary, $with_show = true)` (q, client, category, account, method, show or type, dtf and dtt; q also matches an amount) and `incomeShows()`, the pills (`payments`, `other`, `online`, `uncategorised`). `incomeShowFrom($src)` maps the older `?type=payment` and `revenue`, either case. Also `incomeTotal($from, $to, $client_id)`, `incomeStats($client_id)` (`month`, `last_to_date`, `change`, `year`, `year_average`, `recurring`, `recurring_count`, `owed`, `owed_count`, `overdue`, `overdue_count`) and `incomeCategories($keep_id)`, which leaves out Account Transfer.
- Other income: `incomeRevenueRow($id, $scoped = true)` (with `client_name`, `category_name`, `account_name`, `account_currency_code` and `created_by_name`; null for a transfer's leg), `incomeRevenueLabel($row)`, `incomeRevenueSave($in, $id, &$error)` - the one path that writes it, taking `date`, `amount`, `account`, `category`, `client_id`, `payment_method`, `reference` and `description`, checking each, taking the account's currency and setting `revenue_created_by` on insert - and `incomeRevenueDelete($id, &$error)`.
- Payments: `incomePaymentRow($id)` (the invoice's number, status, amount, dates, scope, client and category, `invoice_paid`, `others` - the other payments on the invoice - and `fee`, an expense whose reference starts with an online payment's reference) and `incomePaymentLabel($row)`.
- `incomeBulkIds($refs)` turns the list's `payment-12` and `revenue-7` (either case, so the old `Payment-12` too) into `['payment' => ids, 'revenue' => ids]`.
- `agent/income.php` is rebuilt on these, taking `?client=` (or the client pages' `?client_id=`), `?category=`, `?account=`, `?method=`, `?show=`, `?type=`, the date filter, `?open=payment-12` or `revenue-7`, and sorting on a whitelist only.
- Handlers: `agent/post/revenue.php` - `add_revenue` (New and Copy) and `edit_revenue` (with `revenue_id`) through `incomeRevenueSave()` at Financial 2, GET `delete_revenue` through `incomeRevenueDelete()` at Financial 3, logged with the client. `agent/post/income.php` - `bulk_edit_income` (`field` = category, account, method or client, `value`, `income_ids[]`; Financial at 2, payments only with `incomeCanEditPayments()`), `bulk_delete_income` (Financial at 3, other income only) and `export_income` through `incomeFiltersSql()`, with `income_invoice` and `income_online` added to the `income` export columns. `agent/post/payment.php` adds GET `payment_send_receipt` (Sales at 2), resending the receipt through `billingPaymentSend()`.
- New windows: `agent/modals/payment/payment.php?id=` and `agent/modals/revenue/revenue.php?id=` (quick looks), `revenue_form.php` (the fields of `revenue_add.php`, which takes `?client_id=`, `revenue_edit.php` and the new `revenue_copy.php`), `agent/modals/income/income_bulk_edit.php?field=` and `income_bulk_delete.php`, with the menu in `agent/includes/income_bulk_menu.php`. `income_export.php` posts `show`, `client`, `dtf` and `dtt` in place of `type`, `date_from` and `date_to`.
- `globalSearchGroups()` has an Income group over `incomeUnionSql()`. `reportCategoryYearTable()` takes a sixth argument, the query that opens the No category row (`show=uncategorised` on the Income Summary). `agent/transactions.php` opens `payment.php` and `revenue.php`, and `agent/accounts.php` links each account's Transactions and Income.
- Seeds: `demoBuildClient()` sets `revenue_created_by`, and `demoBuildCompanyFinancials()` adds the company's rebates, interest and referral fees (references `RBT-`, `INT-` and `REF-`, removed with the demo data).
- CSS: `.itflow-income-from`.
- Removed: `agent/post/income_model.php`, and `agent/modals/income/income_bulk_edit_account.php`, `income_bulk_edit_category.php` and `income_bulk_edit_method.php` (`bulk_edit_income_account`, `bulk_edit_income_category` and `bulk_edit_income_method` are replaced by `bulk_edit_income`).
- 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.

View File

@@ -0,0 +1,20 @@
<?php
/*
* ITFlow - Database update to version 3.0.5 (from 3.0.4)
* Included by admin/database_updates.php - do not access directly
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
// Other income (functions/income.php): who entered it, what it was for in
// more than a line, and the dates the Income list and its totals run on
mysqli_query($mysqli, "ALTER TABLE `revenues`
MODIFY `revenue_description` text DEFAULT NULL,
ADD COLUMN `revenue_created_by` int(11) NOT NULL DEFAULT 0 AFTER `revenue_client_id`,
ADD KEY `revenue_date` (`revenue_date`)");
mysqli_query($mysqli, "ALTER TABLE `payments` ADD KEY `payment_date` (`payment_date`)");
// Who entered each, from the audit log where it says
mysqli_query($mysqli, "UPDATE revenues JOIN logs ON log_type = 'Revenue' AND log_action = 'Create' AND log_entity_id = revenue_id
SET revenue_created_by = log_user_id WHERE revenue_created_by = 0 AND log_user_id > 0");

View File

@@ -980,6 +980,11 @@ function demoDataRemove($mysqli) {
mysqli_query($mysqli, "DELETE FROM transfers WHERE transfer_id = $transfer_id");
}
// The company's other income - rebates, interest and referral fees on our accounts
mysqli_query($mysqli, "DELETE FROM revenues WHERE revenue_client_id = 0 AND revenue_account_id IN ($owned_ids)
AND (revenue_reference LIKE 'RBT-%' OR revenue_reference LIKE 'INT-%' OR revenue_reference LIKE 'REF-%')
AND NOT EXISTS (SELECT 1 FROM transfers WHERE transfer_revenue_id = revenue_id)");
}
// The transfer categories are ours - the Categories pack has no equivalent.
@@ -3267,6 +3272,7 @@ function demoBuildBilling($mysqli, $profile, $index, $client_id, $vendor_id, $mo
'revenue_category_id' => $support_category_id,
'revenue_account_id' => $bank_account_id,
'revenue_client_id' => $client_id,
'revenue_created_by' => intval($context['user_id']),
'revenue_created_at' => demoMonthDateTime($month, 22, 10, 15),
]);
$counts['billing']++;
@@ -3521,6 +3527,41 @@ function demoBuildCompanyFinancials($mysqli, $context, &$counts) {
}
// Money in that never went through an invoice - the distributor's partner
// rebate each quarter, interest on the savings, and the odd referral fee.
// The RBT-, INT- and REF- references are how removal finds them again.
$other_income = [];
for ($month = 24; $month >= 0; $month--) {
if ($month % 3 === 1) {
$other_income[] = [$month, 12, 380.00 + (($month % 5) * 45), 'Rebates', 'ACH', 'RBT-', "Distributor partner rebate for last quarter's licensing", $operating_id];
}
if ($savings_id) {
$other_income[] = [$month, 28, 18.40 + ((24 - $month) * 0.65), 'Interest', 'ACH', 'INT-', 'Interest on the tax reserve', $savings_id];
}
if ($month === 9 || $month === 2) {
$other_income[] = [$month, 17, 250.00, 'Referral Fees', 'Check', 'REF-', "Referral fee - passed a website rebuild to a design partner", $operating_id];
}
}
foreach ($other_income as [$month, $day, $amount, $category, $method, $prefix, $description, $account_id]) {
if (demoIsFuture(demoMonthDate($month, $day))) {
continue;
}
starterInsert($mysqli, 'revenues', [
'revenue_date' => demoMonthDate($month, $day),
'revenue_amount' => number_format($amount, 2, '.', ''),
'revenue_currency_code' => $currency,
'revenue_payment_method' => $method,
'revenue_reference' => $prefix . demoSerial($category . $month . $day, 8),
'revenue_description' => $description,
'revenue_category_id' => demoCategoryId($mysqli, $category, 'Income'),
'revenue_account_id' => $account_id,
'revenue_client_id' => 0,
'revenue_created_by' => intval($context['user_id']),
'revenue_created_at' => demoMonthDateTime($month, $day, 11, 5),
]);
$counts['company']++;
}
}
// ------------------------------

View File

@@ -98,6 +98,12 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
data-modal-url="modals/account/account_edit.php?id=<?= $account_id ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
</a>
<a class="dropdown-item" href="transactions.php?account=<?= $account_id ?>">
<i class="fas fa-fw fa-exchange-alt me-2"></i>Transactions
</a>
<a class="dropdown-item" href="income.php?account=<?= $account_id ?>">
<i class="fas fa-fw fa-hand-holding-usd me-2"></i>Income into it
</a>
<?php if ($balance == 0 && $account_id != $config_stripe_account) { //Cannot Archive an Account until it reaches 0 Balance and cant be selected as an online account ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger" href="post.php?archive_account=<?= $account_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">

View File

@@ -0,0 +1,24 @@
<?php
/*
* The Income list's Bulk menu - shown once rows are ticked (js/bulk_actions.js).
* Set the category, account, payment method or client of the ticked rows, or
* delete the other income among them. A payment's category is its invoice's,
* its client is the invoice's, and it is deleted from the invoice.
*/
isset($mysqli) || die("Direct file access is not allowed");
?>
<div class="dropdown" id="bulkActionButton" hidden>
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-layer-group"></i><span class="d-none d-xxl-inline ms-1">Bulk</span> (<span id="selectedCount">0</span>)
</button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/income/income_bulk_edit.php?field=category" data-bulk="true"><i class="fas fa-fw fa-tag text-secondary me-2"></i>Set Category</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/income/income_bulk_edit.php?field=account" data-bulk="true"><i class="fas fa-fw fa-piggy-bank text-secondary me-2"></i>Set Account</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/income/income_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/income/income_bulk_edit.php?field=client" data-bulk="true"><i class="fas fa-fw fa-building text-secondary me-2"></i>Set Client</a>
<?php if (incomeCanDelete()) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold ajax-modal" href="#" data-modal-url="modals/income/income_bulk_delete.php" data-bulk="true"><i class="fas fa-fw fa-trash me-2"></i>Delete</a>
<?php } ?>
</div>
</div>

View File

@@ -1,5 +1,24 @@
<?php
/*
* Income - the money that comes in: payments against invoices, and other
* income that isn't for an invoice (a deposit, a rebate, interest, a
* referral fee). functions/income.php has what counts and how.
*
* Along the top: this month against the same days of last month, the year
* so far with its monthly average, what the running recurring invoices bill
* a month, and what is still owed on invoices. Pills cut the list to
* invoice payments, other income, what was paid online and what has no
* category; filters by client, category, account, payment method and date.
* A row opens its quick look - a payment's with its invoice, other income's
* with Edit and Copy.
*
* Takes ?client= (or the client pages' ?client_id=), ?category=,
* ?account=, ?method=, ?show= (payments, other, online, uncategorised; the
* older ?type=payment and revenue too), the date filter and ?open=
* (payment-12 or revenue-7) to open one.
*/
// Default Column Sortby/Order Filter
$sort = "income_date";
$order = "DESC";
@@ -7,545 +26,411 @@ $order = "DESC";
// If client_id is in URI then show client Side Bar and client header
if (isset($_GET['client_id'])) {
require_once "includes/inc_all_client.php";
$payment_client_query = "AND invoice_client_id = $client_id";
$revenue_client_query = "AND revenue_client_id = $client_id";
$client_url = "client_id=$client_id&";
$client_page = true;
} else {
require_once "includes/inc_all.php";
$payment_client_query = '';
$revenue_client_query = '';
$client_url = '';
$client_page = false;
$client_id = 0;
}
// Perms
enforceUserPermission('module_financial');
// Type Filter
$income_types_array = ['Payment', 'Revenue'];
if (isset($_GET['type']) && !empty($_GET['type']) && in_array($_GET['type'], $income_types_array)) {
$type_query = "AND (income_type = '" . escapeSql($_GET['type']) . "')";
$type_filter = escapeSql($_GET['type']);
} else {
// Default - any
$type_query = '';
$type_filter = '';
$can_edit = incomeCanEdit();
$can_delete = incomeCanDelete();
$can_bulk = $can_edit;
$can_sales = lookupUserPermission('module_sales') >= 1;
$client_filter = $client_page ? intval($client_id) : intval($_GET['client'] ?? 0);
$category_filter = intval($_GET['category'] ?? 0);
$account_filter = intval($_GET['account'] ?? 0);
$method_filter = (string) ($_GET['method'] ?? '');
$shows = incomeShows();
$show = incomeShowFrom($_GET);
$more_filters = $account_filter || $method_filter !== '';
// Only these sort - filter_header.php hands through any lowercase word
$sortable_columns = ['income_date' => 'income.income_date', 'income_amount' => 'income.income_amount', 'client_name' => 'income.client_name',
'category_name' => 'income.category_name', 'account_name' => 'income.account_name', 'income_type' => 'income.income_type'];
if (!isset($sortable_columns[$sort])) {
$sort = 'income_date';
}
// Account Filter
if (isset($_GET['account']) && !empty($_GET['account'])) {
$account_query = 'AND (income_account_id = ' . intval($_GET['account']) . ')';
$account_filter = intval($_GET['account']);
} else {
// Default - any
$account_query = '';
$account_filter = '';
}
// Category Filter - a revenue carries its own category, a payment inherits the one on the
// invoice it was paid against. Both come from the same 'Income' category pool.
if (isset($_GET['category']) && !empty($_GET['category'])) {
$category_query = 'AND (income_category_id = ' . intval($_GET['category']) . ')';
$category_filter = intval($_GET['category']);
} else {
// Default - any
$category_query = '';
$category_filter = '';
}
// Payment Method Filter
if (isset($_GET['method']) && !empty($_GET['method'])) {
$method_query = "AND (income_method = '" . escapeSql($_GET['method']) . "')";
$method_filter = escapeHtml($_GET['method']);
} else {
// Default - any
$method_query = '';
$method_filter = '';
}
// Money in comes from two places - payments applied to an invoice, and standalone revenues.
// Transfers between accounts are stored as a linked expense + revenue pair, so the revenue leg
// is excluded here (transfer_id IS NULL) - moving your own money is not income.
$income_query =
"SELECT
'Payment' AS income_type,
payment_id AS income_id,
payment_date AS income_date,
payment_created_at AS income_created_at,
payment_invoice_id AS income_invoice_id,
CONCAT(invoice_prefix, invoice_number) AS income_source,
category_name AS income_category,
IFNULL(invoice_category_id, 0) AS income_category_id,
invoice_client_id AS income_client_id,
client_name AS income_client,
payment_amount AS income_amount,
payment_currency_code AS income_currency_code,
payment_method AS income_method,
payment_reference AS income_reference,
payment_account_id AS income_account_id,
account_name AS income_account,
account_archived_at AS income_account_archived
FROM payments
LEFT JOIN invoices ON payment_invoice_id = invoice_id
LEFT JOIN clients ON invoice_client_id = client_id
LEFT JOIN accounts ON payment_account_id = account_id
LEFT JOIN categories ON invoice_category_id = category_id
WHERE payment_archived_at IS NULL
$payment_client_query
" . clientScopeSql('invoice_client_id') . "
UNION ALL
SELECT
'Revenue',
revenue_id,
revenue_date,
revenue_created_at,
0,
revenue_description,
category_name,
revenue_category_id,
revenue_client_id,
client_name,
revenue_amount,
revenue_currency_code,
revenue_payment_method,
revenue_reference,
revenue_account_id,
account_name,
account_archived_at
FROM revenues
LEFT JOIN categories ON revenue_category_id = category_id
LEFT JOIN clients ON revenue_client_id = client_id
LEFT JOIN accounts ON revenue_account_id = account_id
LEFT JOIN transfers ON transfer_revenue_id = revenue_id
WHERE revenue_archived_at IS NULL
AND transfer_id IS NULL
$revenue_client_query
" . clientScopeSql('revenue_client_id') . "";
$income_filter_query =
"WHERE DATE(income_date) BETWEEN '$dtf' AND '$dtt'
AND (income_source LIKE '%$q%' OR income_category LIKE '%$q%' OR income_client LIKE '%$q%' OR income_account LIKE '%$q%' OR income_method LIKE '%$q%' OR income_reference LIKE '%$q%' OR income_amount LIKE '%$q%')
$type_query
$category_query
$account_query
$method_query";
$sql = mysqli_query(
$mysqli,
"SELECT SQL_CALC_FOUND_ROWS * FROM (
$income_query
) AS income
$income_filter_query
ORDER BY $sort $order LIMIT $record_from, $record_to"
);
// Everything but the pill, then the pill - the pill counts are over what the rest leave
$filter_src = array_merge($_GET, ['dtf' => $dtf, 'dtt' => $dtt, 'client' => $client_filter, 'show' => $show, 'type' => '']);
$where = incomeFiltersSql($filter_src, $summary, false);
$show_query = $show !== '' ? 'AND ' . $shows[$show]['where'] : '';
$union = incomeUnionSql();
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS income.* FROM ($union) AS income
WHERE $where $show_query
ORDER BY {$sortable_columns[$sort]} $order, income.income_created_at DESC, income.income_id DESC LIMIT $record_from, $record_to");
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$rows = [];
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
// Summary - totals for the current filtered view, split by where the money came from
$sql_summary = mysqli_query(
$mysqli,
"SELECT
SUM(CASE WHEN income_type = 'Payment' THEN income_amount ELSE 0 END) AS total_payments,
SUM(CASE WHEN income_type = 'Revenue' THEN income_amount ELSE 0 END) AS total_revenues,
SUM(income_amount) AS total_income
FROM (
$income_query
) AS income
$income_filter_query"
);
$row = mysqli_fetch_assoc($sql_summary);
$summary_total_payments = floatval($row['total_payments']);
$summary_total_revenues = floatval($row['total_revenues']);
$summary_total_income = floatval($row['total_income']);
// The pills, and the total of what is listed
$count_sql = [];
foreach ($shows as $key => $s) {
$count_sql[] = $key === '' ? 'COUNT(*)' : "COALESCE(SUM({$s['where']}), 0)";
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', $count_sql) . ", COALESCE(SUM(CASE WHEN 1 $show_query THEN income.income_amount END), 0)
FROM ($union) AS income WHERE $where"));
$counts = [];
foreach (array_keys($shows) as $i => $key) {
$counts[$key] = intval($row[$i]);
}
$listed_total = floatval($row[count($shows)]);
$stats = incomeStats($client_page ? $client_id : 0);
$money = function ($amount, $currency = '') {
return escapeHtml(billingMoney($amount, $currency));
};
$filter_url = function ($changes) use ($client_page, $client_id) {
$params = array_merge($_GET, $changes);
unset($params['page'], $params['type']);
if ($client_page) {
$params['client_id'] = $client_id;
}
return '?' . http_build_query(array_filter($params, function ($v) { return $v !== '' && $v !== null; }));
};
$date_url = function ($from, $to, $changes = []) use ($filter_url) {
return $filter_url(array_merge(['canned_date' => 'custom', 'dtf' => $from, 'dtt' => $to], $changes));
};
$any_filter = $q || ($client_filter && !$client_page) || $category_filter || $account_filter || $method_filter !== '' || $show !== '' || $dtf !== '1970-01-01';
$add_url = 'modals/revenue/revenue_add.php' . ($client_page ? "?client_id=$client_id" : '');
$invoices_url = 'invoices.php?' . ($client_page ? "client_id=$client_id&" : '') . 'status=Unpaid';
?>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-hand-holding-usd me-2"></i>Income</h3>
<div class="card-tools">
<?php if (lookupUserPermission("module_sales") >= 2) { ?>
<div class="btn-group">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/revenue/revenue_add.php" data-modal-size="lg">
<i class="fas fa-plus me-2"></i>New Revenue
</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown"></button>
<div class="dropdown-menu">
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="modals/income/income_export.php?<?= $client_url ?>type=<?= urlencode($type_filter) ?>&category=<?= $category_filter ?>&account=<?= $account_filter ?>&method=<?= urlencode($_GET['method'] ?? '') ?>&dtf=<?= $dtf ?>&dtt=<?= $dtt ?>&q=<?= urlencode($q ?? '') ?>">
<i class="fa fa-fw fa-download me-2"></i>Export
</a>
</div>
</div>
<!-- The money in -->
<div class="row g-3 mb-3">
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $dtf === $stats['month_start'] && $show === '' ? 'active' : '' ?>" href="<?= escapeHtml($date_url($stats['month_start'], date('Y-m-t'), ['show' => ''])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-calendar-alt me-1"></i>This month</div>
<div class="itflow-billing-stat-value text-success-emphasis"><?= $money($stats['month']) ?></div>
<div class="itflow-billing-stat-note">
<?php if ($stats['change'] !== null) { ?>
<span class="<?= $stats['change'] >= 0 ? 'text-success-emphasis' : 'text-warning-emphasis' ?>"><i class="fas fa-arrow-<?= $stats['change'] >= 0 ? 'up' : 'down' ?> me-1"></i><?= abs($stats['change']) ?>%</span> on the same days of <?= date('F', strtotime($stats['last_start'])) ?>
<?php } else { ?>
<button type="button" class="btn btn-default ajax-modal"
data-modal-url="modals/income/income_export.php?<?= $client_url ?>type=<?= urlencode($type_filter) ?>&category=<?= $category_filter ?>&account=<?= $account_filter ?>&method=<?= urlencode($_GET['method'] ?? '') ?>&dtf=<?= $dtf ?>&dtt=<?= $dtt ?>&q=<?= urlencode($q ?? '') ?>">
<i class="fa fa-fw fa-download me-2"></i>Export
</button>
Nothing in by now last month
<?php } ?>
</div>
</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat <?= $dtf === $stats['year_start'] && $show === '' ? 'active' : '' ?>" href="<?= escapeHtml($date_url($stats['year_start'], date('Y-12-31'), ['show' => ''])) ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-chart-line me-1"></i><?= date('Y') ?> so far</div>
<div class="itflow-billing-stat-value"><?= $money($stats['year']) ?></div>
<div class="itflow-billing-stat-note"><?= $money($stats['year_average']) ?> a month on average</div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat" href="<?= $can_sales ? 'recurring_invoices.php' . ($client_page ? "?client_id=$client_id" : '') : '#' ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-redo-alt me-1"></i>Recurring</div>
<div class="itflow-billing-stat-value"><?= $money($stats['recurring']) ?><span class="fs-6 fw-normal text-body-secondary"> a month</span></div>
<div class="itflow-billing-stat-note"><?= $stats['recurring_count'] ? 'From ' . $stats['recurring_count'] . ' recurring invoice' . ($stats['recurring_count'] === 1 ? '' : 's') : 'No recurring invoices running' ?></div>
</a>
</div>
<div class="col-sm-6 col-xl-3">
<a class="itflow-billing-stat" href="<?= $can_sales ? escapeHtml($invoices_url) : '#' ?>">
<div class="itflow-billing-stat-label"><i class="fas fa-hourglass-half me-1"></i>Still owed</div>
<div class="itflow-billing-stat-value <?= $stats['overdue'] > 0 ? 'text-danger-emphasis' : '' ?>"><?= $money($stats['owed']) ?></div>
<div class="itflow-billing-stat-note">
<?= $stats['owed_count'] ? 'On ' . $stats['owed_count'] . ' invoice' . ($stats['owed_count'] === 1 ? '' : 's') : 'Every invoice is paid' ?><?= $stats['overdue'] > 0 ? ' &middot; <span class="text-danger-emphasis">' . $money($stats['overdue']) . ' late</span>' : '' ?>
</div>
</a>
</div>
</div>
<div class="card-header py-3">
<form autocomplete="off">
<?php if ($client_url) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-hand-holding-usd me-2"></i>Income</h3>
<div class="card-tools">
<div class="btn-group">
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="<?= $add_url ?>"><i class="fas fa-plus me-2"></i>New Income</button>
<?php } ?>
<div class="row g-2 align-items-end">
<div class="col-sm-4">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search Income">
<button class="btn btn-secondary" title="More filters" type="button" data-bs-toggle="collapse" data-bs-target="#advancedFilter"><i class="fas fa-filter"></i></button>
<button class="btn btn-primary" title="Search"><i class="fa fa-search"></i></button>
<button type="button" class="btn <?= $can_edit ? 'btn-primary dropdown-toggle-split' : 'btn-light' ?> dropdown-toggle" data-bs-toggle="dropdown" aria-label="More"><?= $can_edit ? '' : '<i class="fas fa-ellipsis-h"></i>' ?></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="<?= buildExportModalUrl('modals/income/income_export.php', ['client_id', 'client', 'category', 'account', 'method', 'show', 'type', 'q'], ['dtf' => $dtf, 'dtt' => $dtt]) ?>">
<i class="fa fa-fw fa-download text-secondary me-2"></i>Export
</a>
<?php if (lookupUserPermission('module_reporting') >= 1) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="reports/income_summary.php"><i class="fa fa-fw fa-chart-bar text-secondary me-2"></i>Income Summary</a>
<a class="dropdown-item" href="reports/income_by_client.php<?= $client_page ? "?client_id=$client_id" : '' ?>"><i class="fa fa-fw fa-users text-secondary me-2"></i>Income by Client</a>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="card-header py-3">
<form autocomplete="off">
<input type="hidden" name="show" value="<?= escapeHtml($show) ?>">
<?php if ($client_page) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<div class="row g-2 align-items-center">
<div class="col-lg-4 col-md-6">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search income" title="What for, invoice number, reference, amount, client, category, account">
<button class="btn btn-outline-secondary <?= $more_filters ? 'active' : '' ?>" title="More filters" type="button" data-bs-toggle="collapse" data-bs-target="#incomeMoreFilters"><i class="fas fa-filter"></i></button>
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="col-lg-2 col-md-6">
<input type="text" id="dateFilter" class="form-control" autocomplete="off" title="Date it came in" aria-label="Date it came in">
<input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date'] ?? '') ?>">
<input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
<input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
</div>
<div class="col-lg-<?= $client_page ? 6 : 3 ?> col-md-6">
<div class="d-flex gap-2">
<div class="flex-grow-1 min-w-0">
<select class="form-select select2" name="category" onchange="this.form.submit()" aria-label="Category">
<option value="">- Any category -</option>
<?php foreach (incomeCategories($category_filter) as $option_id => $category) { ?>
<option <?= $category_filter === $option_id ? 'selected' : '' ?> value="<?= $option_id ?>"<?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?></option>
<?php } ?>
</select>
</div>
<?php if ($client_page && $can_bulk) { ?>
<?php require __DIR__ . '/includes/income_bulk_menu.php'; ?>
<?php } ?>
</div>
</div>
<?php if (!$client_page) { ?>
<div class="col-lg-3 col-md-6">
<div class="d-flex gap-2">
<div class="flex-grow-1 min-w-0">
<select class="form-select select2" name="client" onchange="this.form.submit()" aria-label="Client">
<option value="">- Any client -</option>
<?php
$sql_filter = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients
WHERE (EXISTS (SELECT 1 FROM invoices JOIN payments ON payment_invoice_id = invoice_id WHERE invoice_client_id = client_id)
OR EXISTS (SELECT 1 FROM revenues WHERE revenue_client_id = client_id)) " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql_filter)) {
$option_id = intval($row['client_id']); ?>
<option <?= $client_filter === $option_id ? 'selected' : '' ?> value="<?= $option_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
<?php if ($can_bulk) { ?>
<?php require __DIR__ . '/includes/income_bulk_menu.php'; ?>
<?php } ?>
</div>
</div>
<div class="col-md-2">
<?php } ?>
</div>
<div class="collapse <?= $more_filters ? 'show' : '' ?>" id="incomeMoreFilters">
<div class="row g-2 mt-0">
<div class="col-lg-3 col-md-6">
<div class="input-group">
<select class="form-select select2" name="type" onchange="this.form.submit()">
<option value="">- All Types -</option>
<?php foreach ($income_types_array as $income_type_option) { ?>
<option <?php if ($type_filter == $income_type_option) { echo "selected"; } ?>><?= $income_type_option ?></option>
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" onchange="this.form.submit()" aria-label="Paid into">
<option value="">- Any account -</option>
<?php foreach (paymentAccounts($account_filter) as $option_id => $account) { ?>
<option <?= $account_filter === $option_id ? 'selected' : '' ?> value="<?= $option_id ?>"><?= escapeHtml($account['account_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-2">
<div class="col-lg-3 col-md-6">
<div class="input-group">
<select class="form-select select2" name="category" onchange="this.form.submit()">
<option value="">- All Categories -</option>
<span class="input-group-text"><i class="fa fa-fw fa-credit-card"></i></span>
<select class="form-select select2" name="method" onchange="this.form.submit()" aria-label="Paid by">
<option value="">- Any payment method -</option>
<?php
$sql_categories_filter = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories
WHERE category_type = 'Income'
AND (EXISTS (SELECT 1 FROM revenues WHERE revenue_category_id = category_id)
OR EXISTS (SELECT 1 FROM payments JOIN invoices ON payment_invoice_id = invoice_id WHERE invoice_category_id = category_id))
ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql_categories_filter)) {
$filter_category_id = intval($row['category_id']);
$filter_category_name = escapeHtml($row['category_name']);
?>
<option <?php if ($category_filter == $filter_category_id) { echo "selected"; } ?> value="<?= $filter_category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $filter_category_name ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-2">
<div class="input-group">
<select class="form-select select2" name="account" onchange="this.form.submit()">
<option value="">- All Accounts -</option>
<?php
$sql_accounts_filter = mysqli_query($mysqli, "SELECT account_id, account_name FROM accounts
WHERE EXISTS (SELECT 1 FROM payments WHERE payment_account_id = account_id)
OR EXISTS (SELECT 1 FROM revenues WHERE revenue_account_id = account_id)
ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql_accounts_filter)) {
$filter_account_id = intval($row['account_id']);
$filter_account_name = escapeHtml($row['account_name']);
?>
<option <?php if ($account_filter == $filter_account_id) { echo "selected"; } ?> value="<?= $filter_account_id ?>"><?= $filter_account_name ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-2">
<div class="input-group">
<select class="form-select select2" name="method" onchange="this.form.submit()">
<option value="">- All Payment Methods -</option>
<?php
$sql_payment_methods_filter = mysqli_query($mysqli, "SELECT DISTINCT payment_method AS method FROM payments WHERE payment_method != ''
UNION SELECT DISTINCT revenue_payment_method FROM revenues WHERE revenue_payment_method != ''
ORDER BY method ASC");
while ($row = mysqli_fetch_assoc($sql_payment_methods_filter)) {
$filter_method = escapeHtml($row['method']);
?>
<option <?php if ($method_filter == $filter_method) { echo "selected"; } ?>><?= $filter_method ?></option>
<?php
}
?>
$sql_filter = mysqli_query($mysqli, "SELECT DISTINCT payment_method AS method FROM payments WHERE COALESCE(payment_method, '') <> ''
UNION SELECT DISTINCT revenue_payment_method FROM revenues WHERE COALESCE(revenue_payment_method, '') <> '' ORDER BY method ASC");
while ($row = mysqli_fetch_row($sql_filter)) { ?>
<option <?= $method_filter === $row[0] ? 'selected' : '' ?> value="<?= escapeHtml($row[0]) ?>"><?= escapeHtml($row[0]) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<?php if (lookupUserPermission("module_sales") >= 3 && lookupUserPermission("module_financial") >= 3) { ?>
<div class="row g-3">
<div class="col-12">
<div class="btn-group float-end">
<div class="dropdown mt-3" id="bulkActionButton" hidden>
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-layer-group me-2"></i>Bulk Action (<span id="selectedCount">0</span>)
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/income/income_bulk_edit_category.php"
data-bulk="true">
<i class="fas fa-fw fa-list me-2"></i>Set Category
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/income/income_bulk_edit_account.php"
data-bulk="true">
<i class="fas fa-fw fa-piggy-bank me-2"></i>Set Account
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/income/income_bulk_edit_method.php"
data-bulk="true">
<i class="fas fa-fw fa-money-check-alt me-2"></i>Set Payment Method
</a>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<div class="collapse mt-3 <?php if (isset($_GET['dtf']) && $_GET['dtf'] !== '1970-01-01') { echo"show"; } ?>" id="advancedFilter">
<div class="row g-3">
<div class="col-md-3">
<div>
<label class="form-label">Date range</label>
<input type="text" id="dateFilter" class="form-control" autocomplete="off">
<input type="hidden" name="canned_date" id="canned_date" value="<?= escapeHtml($_GET['canned_date'] ?? '') ?>">
<input type="hidden" name="dtf" id="dtf" value="<?= escapeHtml($dtf ?? '') ?>">
<input type="hidden" name="dtt" id="dtt" value="<?= escapeHtml($dtt ?? '') ?>">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="row px-3 pt-3">
<div class="col-lg-4 col-md-6 col-sm-12">
<!-- small box -->
<div class="small-box bg-blue text-white">
<div class="inner">
<h3><?= numfmt_format_currency($currency_format, $summary_total_payments, $session_company_currency) ?></h3>
<p>Invoice Payments</p>
</div>
<div class="icon">
<i class="fa fa-credit-card"></i>
</div>
</div>
</div>
<!-- ./col -->
<div class="col-lg-4 col-md-6 col-sm-12">
<!-- small box -->
<div class="small-box bg-info text-white">
<div class="inner">
<h3><?= numfmt_format_currency($currency_format, $summary_total_revenues, $session_company_currency) ?></h3>
<p>Other Revenue</p>
</div>
<div class="icon">
<i class="fa fa-hand-holding-usd"></i>
</div>
</div>
</div>
<!-- ./col -->
<div class="col-lg-4 col-md-6 col-sm-12">
<!-- small box -->
<div class="small-box bg-success">
<div class="inner">
<h3><?= numfmt_format_currency($currency_format, $summary_total_income, $session_company_currency) ?></h3>
<p>Total Income</p>
</div>
<div class="icon">
<i class="fa fa-balance-scale"></i>
</div>
</div>
</div>
<!-- ./col -->
</div>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?> text-nowrap table-light border-top">
<tr>
<?php if (lookupUserPermission("module_sales") >= 3 && lookupUserPermission("module_financial") >= 3) { ?>
<td class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" onclick="checkAll(this)">
</div>
</td>
<?php } ?>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_date&order=<?= $disp ?>">
Date <?php if ($sort == 'income_date') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_type&order=<?= $disp ?>">
Type <?php if ($sort == 'income_type') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_source&order=<?= $disp ?>">
Source <?php if ($sort == 'income_source') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_category&order=<?= $disp ?>">
Category <?php if ($sort == 'income_category') { echo $order_icon; } ?>
</a>
</th>
<?php if (!$client_url) { ?>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_client&order=<?= $disp ?>">
Client <?php if ($sort == 'income_client') { echo $order_icon; } ?>
</a>
</th>
<?php } ?>
<th class="text-end">
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_amount&order=<?= $disp ?>">
Amount <?php if ($sort == 'income_amount') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_method&order=<?= $disp ?>">
Method <?php if ($sort == 'income_method') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_reference&order=<?= $disp ?>">
Reference <?php if ($sort == 'income_reference') { echo $order_icon; } ?>
</a>
</th>
<th>
<a class="text-dark" href="?<?= $url_query_strings_sort ?>&sort=income_account&order=<?= $disp ?>">
Account <?php if ($sort == 'income_account') { echo $order_icon; } ?>
</a>
</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
$income_type = escapeHtml($row['income_type']);
$income_id = intval($row['income_id']);
$income_date = escapeHtml($row['income_date']);
$income_invoice_id = intval($row['income_invoice_id']);
$income_source = escapeHtml($row['income_source']);
$income_category = escapeHtml($row['income_category']);
$income_client_id = intval($row['income_client_id']);
$income_client = escapeHtml($row['income_client']);
$income_amount = floatval($row['income_amount']);
$income_currency_code = escapeHtml($row['income_currency_code']);
$income_method = escapeHtml($row['income_method']);
$income_reference = escapeHtml($row['income_reference']);
if (empty($income_reference)) {
$income_reference_display = "-";
} else {
$income_reference_display = $income_reference;
}
$income_account = escapeHtml($row['income_account']);
$income_account_archived = escapeHtml($row['income_account_archived']);
if (empty($income_account_archived)) {
$income_account_archived_display = "";
} else {
$income_account_archived_display = "Archived - ";
}
// Each type keeps its own edit modal and delete handler
if ($income_type == 'Payment') {
$income_edit_modal = "modals/payment/payment_edit.php?id=$income_id";
$income_delete_action = "delete_payment=$income_id";
$income_type_badge = "bg-blue";
} else {
$income_edit_modal = "modals/revenue/revenue_edit.php?id=$income_id";
$income_delete_action = "delete_revenue=$income_id";
$income_type_badge = "bg-info";
}
?>
<tr>
<?php if (lookupUserPermission("module_sales") >= 3 && lookupUserPermission("module_financial") >= 3) { ?>
<td class="checkbox-column bg-light border-end">
<div class="form-check">
<input class="form-check-input bulk-select" type="checkbox" name="income_ids[]" value="<?= $income_type ?>-<?= $income_id ?>">
</div>
</td>
<?php } ?>
<td>
<a class="ajax-modal" href="#"
data-modal-size = "lg"
data-modal-url = "<?= $income_edit_modal ?>">
<?= $income_date ?>
</a>
</td>
<td><span class="badge <?= $income_type_badge ?>"><?= $income_type ?></span></td>
<td>
<?php if ($income_type == 'Payment' && $income_invoice_id) { ?>
<a href="invoice.php?<?= $client_url ?>invoice_id=<?= $income_invoice_id ?>">
<?= $income_source ?>
</a>
<?php } else { ?>
<?= $income_source === '' ? '-' : $income_source ?>
<?php } ?>
</td>
<td><?= $income_category === '' ? '-' : $income_category ?></td>
<?php if (!$client_url) { ?>
<td>
<?php if ($income_client_id) { ?>
<a href="income.php?client_id=<?= $income_client_id ?>"><?= $income_client ?></a>
<?php } else { ?>
-
<?php } ?>
</td>
<?php } ?>
<td class="text-end font-monospace"><?= numfmt_format_currency($currency_format, $income_amount, $income_currency_code) ?></td>
<td><?= $income_method ?></td>
<td><?= $income_reference_display ?></td>
<td><?= "$income_account_archived_display$income_account" ?></td>
<td>
<?php if (lookupUserPermission("module_sales") >= 3) { ?>
<div class="dropdown dropstart text-center">
<button class="btn btn-secondary btn-sm" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-h"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-size = "lg"
data-modal-url = "<?= $income_edit_modal ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?<?= $income_delete_action ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
</div>
</div>
<?php } ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php require_once "../includes/filter_footer.php"; ?>
</form>
<!-- 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 === 'uncategorised' && $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>
</a>
<?php } ?>
</nav>
</div>
<script src="/js/bulk_actions.js"></script>
<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">
<tr>
<?php if ($can_bulk) { ?>
<th class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" onclick="checkAll(this)" title="Select all on this page">
</div>
</th>
<?php } ?>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=income_date&order=<?= $disp ?>">Date <?php if ($sort == 'income_date') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=income_type&order=<?= $disp ?>">From <?php if ($sort == 'income_type') { echo $order_icon; } ?></a></th>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=category_name&order=<?= $disp ?>">Category <?php if ($sort == 'category_name') { echo $order_icon; } ?></a></th>
<?php if (!$client_page) { ?>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">Client <?php if ($sort == 'client_name') { echo $order_icon; } ?></a></th>
<?php } ?>
<th><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=account_name&order=<?= $disp ?>">Paid into <?php if ($sort == 'account_name') { echo $order_icon; } ?></a></th>
<th class="text-end"><a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=income_amount&order=<?= $disp ?>">Amount <?php if ($sort == 'income_amount') { echo $order_icon; } ?></a></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row) {
$is_payment = $row['income_type'] === 'payment';
$income_id = intval($row['income_id']);
$ref = $row['income_type'] . '-' . $income_id;
$row_open = 'data-modal-size="lg" data-modal-url="modals/' . ($is_payment ? 'payment/payment' : 'revenue/revenue') . '.php?id=' . $income_id . '"';
$row_amount = floatval($row['income_amount']);
$row_currency = (string) $row['income_currency_code'];
$row_client_id = intval($row['income_client_id']);
$first_line = trim(strtok((string) $row['income_description'], "\n"));
?>
<tr>
<?php if ($can_bulk) { ?>
<td class="checkbox-column bg-light border-end">
<div class="form-check">
<input class="form-check-input bulk-select" type="checkbox" name="income_ids[]" value="<?= $ref ?>" aria-label="Select this">
</div>
</td>
<?php } ?>
<td class="text-nowrap"><a class="fw-semibold ajax-modal" href="#" <?= $row_open ?>><?= escapeHtml($row['income_date']) ?></a></td>
<td class="itflow-income-from">
<?php if ($is_payment) { ?>
<div class="text-truncate">
<i class="fas fa-file-invoice-dollar text-body-secondary me-1" title="Invoice payment"></i>
<?php if ($row['invoice_number'] !== null) { ?>
<?php if ($can_sales) { ?><a href="invoice.php?invoice_id=<?= intval($row['income_invoice_id']) ?>"><?= escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?></a><?php } else { ?><?= escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?><?php } ?>
<?php if ($first_line !== '') { ?><span class="text-body-secondary"> - <?= escapeHtml($first_line) ?></span><?php } ?>
<?php } else { ?>
<span class="text-body-secondary">An invoice since deleted</span>
<?php } ?>
</div>
<?php } else { ?>
<div class="text-truncate"><i class="fas fa-hand-holding-usd text-body-secondary me-1" title="Other income"></i><?= escapeHtml($first_line !== '' ? $first_line : ($row['category_name'] ?: 'Other income')) ?></div>
<?php } ?>
<div class="small text-body-secondary text-truncate">
<?= escapeHtml(implode(' · ', array_filter([(string) $row['income_method'], $row['income_reference'] ? '#' . $row['income_reference'] : '']))) ?: '&nbsp;' ?>
<?php if (intval($row['income_online'])) { ?><span class="badge rounded-pill bg-info-subtle text-info-emphasis fw-normal ms-1"><i class="fas fa-globe me-1"></i>Online</span><?php } ?>
</div>
</td>
<td>
<?php if (intval($row['income_category_id']) && $row['category_name'] !== null) { ?>
<div class="text-truncate" style="max-width: 10rem;" title="<?= escapeHtml($row['category_name']) ?>"><?= expenseCategoryDot($row['category_color']) ?><?= escapeHtml($row['category_name']) ?></div>
<?php } else { ?>
<span class="text-warning-emphasis small" title="Not in a category - the reports show it as No category">No category</span>
<?php } ?>
</td>
<?php if (!$client_page) { ?>
<td>
<?php if ($row_client_id && $row['client_name'] !== null) { ?>
<div class="text-truncate" style="max-width: 12rem;"><a class="text-reset" href="<?= escapeHtml($filter_url(['client' => $row_client_id])) ?>" title="<?= escapeHtml($row['client_name']) ?> - what came in from them"><?= escapeHtml($row['client_name']) ?></a></div>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<?php } ?>
<td>
<div class="text-truncate" style="max-width: 10rem;"><?= escapeHtml($row['account_name'] ?: '-') ?></div>
<?php if ($row['account_archived_at']) { ?><div class="small text-body-secondary">Archived</div><?php } ?>
</td>
<td class="text-end itflow-money text-nowrap">
<span class="fw-semibold <?= $row_amount < 0 ? 'text-danger-emphasis' : '' ?>"><?= $money($row_amount, $row_currency) ?></span>
</td>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#" <?= $row_open ?>><i class="fas fa-fw fa-eye text-secondary me-2"></i>Open</a>
<?php if ($is_payment) { ?>
<?php if ($can_sales && $row['invoice_number'] !== null) { ?>
<a class="dropdown-item" href="invoice.php?invoice_id=<?= intval($row['income_invoice_id']) ?>"><i class="fas fa-fw fa-file-invoice text-secondary me-2"></i>Open Invoice</a>
<?php } ?>
<?php if (incomeCanEditPayments() && $row['invoice_number'] !== null) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/payment/payment_edit.php?id=<?= $income_id ?>"><i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit</a>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_payment=<?= $income_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="The payment of <?= $money($row_amount, $row_currency) ?> comes off <?= escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?>, which is owed again.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
<?php } else { ?>
<?php if ($can_edit) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/revenue/revenue_edit.php?id=<?= $income_id ?>"><i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/revenue/revenue_copy.php?id=<?= $income_id ?>"><i class="fas fa-fw fa-copy text-secondary me-2"></i>Copy</a>
<?php } ?>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_revenue=<?= $income_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= escapeHtml(($first_line !== '' ? $first_line : 'This income') . ' - ' . billingMoney($row_amount, $row_currency)) ?> goes for good.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
<?php if ($num_rows[0]) { ?>
<tfoot>
<tr class="table-light">
<td colspan="<?= ($can_bulk ? 5 : 4) + ($client_page ? 0 : 1) ?>" class="text-body-secondary small">
<?php $listed = intval($num_rows[0]); ?>
<?= $listed ?> <?= $show === 'payments' || $show === 'online' ? ($listed === 1 ? 'payment' : 'payments') : ($show === 'other' ? 'other income' : ($listed === 1 ? 'payment or other income' : 'payments and other income')) ?><?= $listed > count($rows) ? ' - the total is for all of them, not just this page' : '' ?>
</td>
<td class="text-end fw-semibold text-nowrap itflow-money"><?= $money($listed_total) ?></td>
<td></td>
</tr>
</tfoot>
<?php } ?>
</table>
</div>
<?php if (!$num_rows[0]) { ?>
<div class="itflow-asset-empty">
<i class="fas fa-hand-holding-usd fa-2x mb-2 opacity-50"></i>
<div><?= $any_filter ? 'Nothing matches.' : 'Nothing has come in yet.' ?></div>
<?php if (!$any_filter) { ?>
<div class="small mt-1">A payment is added on its invoice. Money in that isn't for an invoice is New Income here.</div>
<?php } ?>
</div>
<?php } ?>
<?php require_once "../includes/filter_footer.php"; ?>
</div>
<?php
require_once "../includes/footer.php";
<?php if (preg_match('/^(payment|revenue)-(\d+)$/i', (string) ($_GET['open'] ?? ''), $open)) { ?>
<script>
// Opened from elsewhere - straight to its quick look
document.addEventListener('DOMContentLoaded', function () {
var open = document.createElement('a');
open.className = 'ajax-modal';
open.href = '#';
open.dataset.modalSize = 'lg';
open.dataset.modalUrl = 'modals/<?= strtolower($open[1]) === 'payment' ? 'payment/payment' : 'revenue/revenue' ?>.php?id=<?= intval($open[2]) ?>';
document.body.appendChild(open);
open.click();
open.remove();
});
</script>
<?php } ?>
<script src="../js/bulk_actions.js"></script>
<?php require_once "../includes/footer.php";

View File

@@ -0,0 +1,59 @@
<?php
/*
* Delete the other income among the ticked Income rows. A payment is taken
* off from its invoice, so ticked payments are left alone. Posts
* bulk_delete_income with income_ids[].
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_financial', 3);
$ids = incomeBulkIds($_GET['income_ids'] ?? []);
$count = count($ids['revenue']);
$payments = count($ids['payment']);
if (!$count) {
echo json_encode(['error' => $payments ? "A payment is deleted from its invoice - tick other income to delete it here." : 'Tick the income to delete first.']);
exit;
}
$total = [];
$sql = mysqli_query($mysqli, "SELECT revenue_currency_code, SUM(revenue_amount) FROM revenues WHERE revenue_id IN (" . implode(',', $ids['revenue']) . ") AND revenue_archived_at IS NULL
AND " . incomeRevenueSql('revenue_id') . ' ' . clientScopeSql('revenue_client_id') . " GROUP BY revenue_currency_code");
while ($row = mysqli_fetch_row($sql)) {
$total[] = billingMoney($row[1], $row[0]);
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-trash me-2"></i>Delete <?= $count ?> Other Income</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php foreach ($ids['revenue'] as $id) { ?>
<input type="hidden" name="income_ids[]" value="revenue-<?= $id ?>">
<?php } ?>
<div class="modal-body">
<div class="d-flex gap-3 align-items-start">
<i class="fas fa-exclamation-triangle fa-2x text-danger"></i>
<div>
<div class="fw-semibold"><?= $count === 1 ? 'This income goes' : "These $count go" ?> for good<?= $total ? ' - ' . escapeHtml(implode(' and ', $total)) : '' ?>.</div>
<div class="text-body-secondary small mt-1">It comes out of the account balances and the reports. This can't be undone.</div>
<?php if ($payments) { ?>
<div class="text-body-secondary small mt-1">The <?= $payments === 1 ? 'payment' : "$payments payments" ?> ticked with <?= $count === 1 ? 'it' : 'them' ?> <?= $payments === 1 ? 'stays' : 'stay' ?> - a payment is deleted from its invoice.</div>
<?php } ?>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="bulk_delete_income" class="btn btn-danger text-bold"><i class="fas fa-trash me-2"></i>Delete <?= $count ?></button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,119 @@
<?php
/*
* Set the category, account, payment method or client of the ticked Income
* rows - ?field= category, account, method or client, with income_ids[] as
* payment-12 / revenue-7. A payment's category is its invoice's, so the
* invoice takes it; its client is the invoice's, so Set Client changes only
* the other income. Changing a payment takes the invoice's own rights.
* Posts bulk_edit_income with field, value and income_ids[].
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_financial', 2);
$ids = incomeBulkIds($_GET['income_ids'] ?? []);
$payments = count($ids['payment']);
$others = count($ids['revenue']);
$count = $payments + $others;
$field = (string) ($_GET['field'] ?? '');
$can_payments = incomeCanEditPayments();
$fields = [
'category' => ['label' => 'Category', 'icon' => 'fa-tag'],
'account' => ['label' => 'Account', 'icon' => 'fa-piggy-bank'],
'method' => ['label' => 'Payment Method', 'icon' => 'fa-credit-card'],
'client' => ['label' => 'Client', 'icon' => 'fa-building'],
];
if (!isset($fields[$field])) {
echo json_encode(['error' => 'Pick what to set from the Bulk Action menu.']);
exit;
}
if (!$count) {
echo json_encode(['error' => 'Tick the income to change first.']);
exit;
}
// What the ticked rows are, in words - and what of it this leaves alone
$ticked = implode(' and ', array_filter([
$payments ? $payments . ' invoice payment' . ($payments === 1 ? '' : 's') : '',
$others ? $others . ' other income' : '',
]));
$notes = [];
if ($payments && $field === 'client') {
$notes[] = "A payment's client is its invoice's - the " . ($payments === 1 ? 'payment stays' : "$payments payments stay") . ' as ' . ($payments === 1 ? 'it is' : 'they are') . '.';
} elseif ($payments && !$can_payments) {
$notes[] = 'Changing a payment takes full access to Sales and Financial - the ' . ($payments === 1 ? 'payment stays' : "$payments payments stay") . ' as ' . ($payments === 1 ? 'it is' : 'they are') . '.';
} elseif ($payments && $field === 'category') {
$notes[] = "A payment's category is its invoice's - the invoice" . ($payments === 1 ? '' : 's') . ' behind the ' . ($payments === 1 ? 'payment takes' : 'payments take') . ' it, and with it every payment on ' . ($payments === 1 ? 'it' : 'them') . '.';
}
if ($field === 'account') {
$notes[] = 'The currency stays as it was entered.';
}
$changes = $field === 'client' || !$can_payments ? $others : $count;
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw <?= $fields[$field]['icon'] ?> me-2"></i>Set <?= $fields[$field]['label'] ?> <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($ticked) ?></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">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="field" value="<?= $field ?>">
<?php foreach (['payment', 'revenue'] as $type) {
foreach ($ids[$type] as $id) { ?>
<input type="hidden" name="income_ids[]" value="<?= "$type-$id" ?>">
<?php }
} ?>
<div class="modal-body">
<label class="form-label"><?= $fields[$field]['label'] ?><?= $field !== 'client' ? ' <strong class="text-danger">*</strong>' : '' ?></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw <?= $fields[$field]['icon'] ?>"></i></span>
<?php if ($field === 'category') { ?>
<select class="form-select select2" name="value" required>
<option value="">- Pick a category -</option>
<?php foreach (incomeCategories() as $option_id => $category) { ?>
<option value="<?= $option_id ?>"<?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?></option>
<?php } ?>
</select>
<?php } elseif ($field === 'account') { ?>
<select class="form-select select2" name="value" required>
<option value="">- Pick the account it went into -</option>
<?php foreach (paymentAccounts() as $option_id => $account) { ?>
<option value="<?= $option_id ?>"><?= escapeHtml($account['account_name']) ?><?= $account['account_currency_code'] ? ' (' . escapeHtml($account['account_currency_code']) . ')' : '' ?></option>
<?php } ?>
</select>
<?php } elseif ($field === 'method') { ?>
<select class="form-select select2" name="value" required>
<option value="">- Pick how it was paid -</option>
<?php foreach (paymentMethods() as $method) { ?>
<option><?= escapeHtml($method) ?></option>
<?php } ?>
</select>
<?php } else { ?>
<select class="form-select select2" name="value">
<option value="0">- Not from a client -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) { ?>
<option value="<?= intval($row['client_id']) ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
<?php } ?>
</div>
<?php foreach ($notes as $note) { ?>
<div class="form-text"><?= escapeHtml($note) ?></div>
<?php } ?>
</div>
<div class="modal-footer">
<button type="submit" name="bulk_edit_income" class="btn btn-primary text-bold" <?= $changes ? '' : 'disabled' ?>><i class="fas fa-check me-2"></i>Set on <?= $changes ?></button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,71 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
// Income rows are a UNION of payments and revenues, so each checkbox carries a composite
// reference ("Payment-12" / "Revenue-7"). Whitelist the shape before echoing it back.
$income_ids = preg_grep('/^(Payment|Revenue)-[1-9][0-9]*$/', array_filter((array) ($_GET['income_ids'] ?? []), 'is_string'));
$count = count($income_ids);
// Generate the HTML form content using output buffering.
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-piggy-bank me-2"></i>Set Account for <strong><?= $count ?></strong> Income Record<?= $count == 1 ? '' : 's' ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php foreach ($income_ids as $income_id) { ?> <input type="hidden" name="income_ids[]" value="<?= $income_id ?>"><?php } ?>
<div class="modal-body">
<div class="mb-3">
<label>Account <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="bulk_account_id" data-placeholder="- Select an Account -" required>
<option></option>
<?php
$sql = mysqli_query($mysqli, "SELECT account_id, account_name, opening_balance FROM accounts WHERE account_archived_at IS NULL ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$account_id = intval($row['account_id']);
$account_name = escapeHtml($row['account_name']);
$opening_balance = floatval($row['opening_balance']);
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_payments FROM payments WHERE payment_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_payments);
$total_payments = floatval($row['total_payments']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS total_revenues FROM revenues WHERE revenue_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_revenues);
$total_revenues = floatval($row['total_revenues']);
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS total_expenses FROM expenses WHERE expense_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_expenses);
$total_expenses = floatval($row['total_expenses']);
$balance = $opening_balance + $total_payments + $total_revenues - $total_expenses;
?>
<option value="<?= $account_id ?>"><div class="float-start"><?= $account_name ?></div><div class="float-end"> [$<?= number_format($balance, 2) ?>]</div></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="bulk_edit_income_account" class="btn btn-primary text-bold"><i class="fa fa-fw fa-check me-2"></i>Set</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,115 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
// Income rows are a UNION of payments and revenues, so each checkbox carries a composite
// reference ("Payment-12" / "Revenue-7"). Whitelist the shape before echoing it back.
$income_ids = preg_grep('/^(Payment|Revenue)-[1-9][0-9]*$/', array_filter((array) ($_GET['income_ids'] ?? []), 'is_string'));
$count = count($income_ids);
// A revenue carries its own category, but a payment does not - it inherits the category from the
// invoice it was paid against, so categorising a payment really means categorising that invoice.
// Work out up front what that will drag along, and say so.
$selected_payment_ids = [];
foreach ($income_ids as $income_ref) {
if (str_starts_with($income_ref, 'Payment-')) {
$selected_payment_ids[] = intval(substr($income_ref, strlen('Payment-')));
}
}
$affected_invoice_count = 0;
$orphan_payment_count = 0;
$sibling_payment_count = 0;
if ($selected_payment_ids) {
$selected_payment_ids_sql = implode(',', $selected_payment_ids);
$sql = mysqli_query($mysqli, "SELECT
SUM(CASE WHEN payment_invoice_id = 0 THEN 1 ELSE 0 END) AS orphan_count,
COUNT(DISTINCT CASE WHEN payment_invoice_id != 0 THEN payment_invoice_id END) AS invoice_count
FROM payments
WHERE payment_id IN ($selected_payment_ids_sql)");
$row = mysqli_fetch_assoc($sql);
$orphan_payment_count = intval($row['orphan_count']);
$affected_invoice_count = intval($row['invoice_count']);
// Other payments sitting on those same invoices - not selected, but they will show the new
// category too, because they read it from the invoice as well
$sql = mysqli_query($mysqli, "SELECT COUNT(*) AS sibling_count FROM payments
WHERE payment_archived_at IS NULL
AND payment_id NOT IN ($selected_payment_ids_sql)
AND payment_invoice_id != 0
AND payment_invoice_id IN (SELECT payment_invoice_id FROM payments WHERE payment_id IN ($selected_payment_ids_sql) AND payment_invoice_id != 0)");
$row = mysqli_fetch_assoc($sql);
$sibling_payment_count = intval($row['sibling_count']);
}
// Generate the HTML form content using output buffering.
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-list me-2"></i>Set Category for <strong><?= $count ?></strong> Income Record<?= $count == 1 ? '' : 's' ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php foreach ($income_ids as $income_id) { ?> <input type="hidden" name="income_ids[]" value="<?= $income_id ?>"><?php } ?>
<div class="modal-body">
<?php if ($affected_invoice_count || $orphan_payment_count) { ?>
<div class="alert alert-warning">
<?php if ($affected_invoice_count) { ?>
A payment has no category of its own - it takes the one on the invoice it was paid against.
This will set the category on <strong><?= $affected_invoice_count ?></strong> invoice<?= $affected_invoice_count == 1 ? '' : 's' ?>,
which changes how <?= $affected_invoice_count == 1 ? 'that invoice' : 'those invoices' ?> categorise<?= $affected_invoice_count == 1 ? 's' : '' ?> everywhere else too.
<?php if ($sibling_payment_count) { ?>
<br><br><strong><?= $sibling_payment_count ?></strong> further payment<?= $sibling_payment_count == 1 ? '' : 's' ?> against
<?= $affected_invoice_count == 1 ? 'that invoice' : 'those invoices' ?> <?= $sibling_payment_count == 1 ? 'is' : 'are' ?> not selected,
but will show the new category as well.
<?php } ?>
<?php } ?>
<?php if ($orphan_payment_count) { ?>
<?php if ($affected_invoice_count) { ?><br><br><?php } ?>
<strong><?= $orphan_payment_count ?></strong> selected payment<?= $orphan_payment_count == 1 ? '' : 's' ?>
<?= $orphan_payment_count == 1 ? 'has' : 'have' ?> no linked invoice and will be skipped.
<?php } ?>
</div>
<?php } ?>
<div class="mb-3">
<label>Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select select2" name="bulk_category_id" data-placeholder="- Select a Category -" required>
<option></option>
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND category_archived_at IS NULL ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="bulk_edit_income_category" class="btn btn-primary text-bold"><i class="fa fa-fw fa-check me-2"></i>Set</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,54 +0,0 @@
<?php
require_once '../../../includes/modal_header.php';
// Income rows are a UNION of payments and revenues, so each checkbox carries a composite
// reference ("Payment-12" / "Revenue-7"). Whitelist the shape before echoing it back.
$income_ids = preg_grep('/^(Payment|Revenue)-[1-9][0-9]*$/', array_filter((array) ($_GET['income_ids'] ?? []), 'is_string'));
$count = count($income_ids);
// Generate the HTML form content using output buffering.
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-money-check-alt me-2"></i>Set Payment Method for <strong><?= $count ?></strong> Income Record<?= $count == 1 ? '' : 's' ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php foreach ($income_ids as $income_id) { ?> <input type="hidden" name="income_ids[]" value="<?= $income_id ?>"><?php } ?>
<div class="modal-body">
<div class="mb-3">
<label>Payment Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="bulk_payment_method" data-placeholder="- Select a Method of Payment -" required>
<option></option>
<?php
$sql = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods ORDER BY payment_method_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$payment_method_name = escapeHtml($row['payment_method_name']);
?>
<option><?= $payment_method_name ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="bulk_edit_income_method" class="btn btn-primary text-bold"><i class="fa fa-fw fa-check me-2"></i>Set</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,68 +1,40 @@
<?php
/*
* Export the income - pre-filled from the Income list's filters, and
* editable: the export runs whatever this form posts.
*/
require_once '../../../includes/modal_header.php';
// Pre-fill from the income page's current filters
enforceUserPermission('module_financial');
// Client - carried through from the client-scoped Income page
$client_id = intval($_GET['client_id'] ?? 0);
// Type Filter
$income_types_array = ['Payment', 'Revenue'];
if (isset($_GET['type']) && !empty($_GET['type']) && in_array($_GET['type'], $income_types_array)) {
$type_filter = $_GET['type'];
} else {
$type_filter = '';
if ($client_id) {
enforceClientAccess();
}
// Category Filter
if (isset($_GET['category']) && !empty($_GET['category'])) {
$category_filter = intval($_GET['category']);
} else {
$category_filter = '';
}
$q_filter = $_GET['q'] ?? '';
$client_filter = intval($_GET['client'] ?? 0);
$category_filter = intval($_GET['category'] ?? 0);
$account_filter = intval($_GET['account'] ?? 0);
$method_filter = (string) ($_GET['method'] ?? '');
$shows = incomeShows();
$show_filter = incomeShowFrom($_GET);
// Account Filter
if (isset($_GET['account']) && !empty($_GET['account'])) {
$account_filter = intval($_GET['account']);
} else {
$account_filter = '';
}
// Payment Method Filter
if (isset($_GET['method']) && !empty($_GET['method'])) {
$method_filter = escapeHtml($_GET['method']);
} else {
$method_filter = '';
}
// Search Filter
if (isset($_GET['q']) && !empty($_GET['q'])) {
$q_filter = $_GET['q'];
} else {
$q_filter = '';
}
// Date Filter - ignore the all-time defaults so the date fields stay clean
if (isset($_GET['dtf']) && !empty($_GET['dtf']) && $_GET['dtf'] !== '1970-01-01') {
$date_from_filter = escapeHtml($_GET['dtf']);
} else {
$date_from_filter = '';
}
if (isset($_GET['dtt']) && !empty($_GET['dtt']) && $_GET['dtt'] !== '2099-12-31') {
$date_to_filter = escapeHtml($_GET['dtt']);
} else {
$date_to_filter = '';
}
// The all-time sentinels from filter_header.php leave the dates blank
$date_from_filter = (!empty($_GET['dtf']) && $_GET['dtf'] !== '1970-01-01') ? escapeHtml($_GET['dtf']) : '';
$date_to_filter = (!empty($_GET['dtt']) && $_GET['dtt'] !== '2099-12-31') ? escapeHtml($_GET['dtt']) : '';
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-download me-2"></i>Export Income</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-download me-2"></i>Export Income</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<?php exportTabsNav(); ?>
<form action="post.php" method="post" autocomplete="off">
@@ -74,119 +46,99 @@ ob_start();
<?php exportTabsFiltersOpen(); ?>
<div class="mb-3">
<label>Search</label>
<label class="form-label">Search</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-search"></i></span>
<input type="text" class="form-control" name="q" value="<?= stripslashes(escapeHtml($q_filter)) ?>" placeholder="Source, category, client, account, method, reference or amount">
<span class="input-group-text"><i class="fa fa-fw fa-search"></i></span>
<input type="text" class="form-control" name="q" value="<?= stripslashes(escapeHtml($q_filter)) ?>" placeholder="What for, invoice number, reference, amount, client, category, account">
</div>
</div>
<div class="mb-3">
<label>Type</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="type">
<option value="">- All Types -</option>
<?php foreach ($income_types_array as $income_type_option) { ?>
<option <?php if ($type_filter == $income_type_option) { echo "selected"; } ?> value="<?= $income_type_option ?>"><?= $income_type_option ?></option>
<?php } ?>
</select>
<div class="row g-3 mb-3">
<div class="col-md-6">
<label class="form-label">Showing</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-filter"></i></span>
<select class="form-select select2" name="show">
<?php foreach ($shows as $key => $s) { ?>
<option <?= $show_filter === $key ? 'selected' : '' ?> value="<?= escapeHtml($key) ?>"><?= escapeHtml($key === '' ? 'All income' : $s['label']) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="mb-3">
<label>Category</label>
<div class="input-group">
<?php if (!$client_id) { ?>
<div class="col-md-6">
<label class="form-label">Client</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
<select class="form-select select2" name="client">
<option value="">- Any client -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients
WHERE (EXISTS (SELECT 1 FROM invoices JOIN payments ON payment_invoice_id = invoice_id WHERE invoice_client_id = client_id)
OR EXISTS (SELECT 1 FROM revenues WHERE revenue_client_id = client_id)) " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$option_id = intval($row['client_id']); ?>
<option <?= $client_filter === $option_id ? 'selected' : '' ?> value="<?= $option_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } ?>
<div class="col-md-6">
<label class="form-label">Category</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category">
<option value="">- All Categories -</option>
<?php
$sql_categories_filter = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories
WHERE category_type = 'Income'
AND (EXISTS (SELECT 1 FROM revenues WHERE revenue_category_id = category_id)
OR EXISTS (SELECT 1 FROM payments JOIN invoices ON payment_invoice_id = invoice_id WHERE invoice_category_id = category_id))
ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql_categories_filter)) {
$filter_category_id = intval($row['category_id']);
$filter_category_name = escapeHtml($row['category_name']);
?>
<option <?php if ($category_filter == $filter_category_id) { echo "selected"; } ?> value="<?= $filter_category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $filter_category_name ?></option>
<?php
}
?>
</select>
<select class="form-select select2" name="category">
<option value="">- Any category -</option>
<?php foreach (incomeCategories($category_filter) as $option_id => $category) { ?>
<option <?= $category_filter === $option_id ? 'selected' : '' ?> value="<?= $option_id ?>"<?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="mb-3">
<label>Account</label>
<div class="input-group">
<div class="col-md-6">
<label class="form-label">Paid into</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">
<option value="">- All Accounts -</option>
<?php
$sql_accounts_filter = mysqli_query($mysqli, "SELECT account_id, account_name FROM accounts
WHERE EXISTS (SELECT 1 FROM payments WHERE payment_account_id = account_id)
OR EXISTS (SELECT 1 FROM revenues WHERE revenue_account_id = account_id)
ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql_accounts_filter)) {
$filter_account_id = intval($row['account_id']);
$filter_account_name = escapeHtml($row['account_name']);
?>
<option <?php if ($account_filter == $filter_account_id) { echo "selected"; } ?> value="<?= $filter_account_id ?>"><?= $filter_account_name ?></option>
<?php
}
?>
</select>
<select class="form-select select2" name="account">
<option value="">- Any account -</option>
<?php foreach (paymentAccounts($account_filter) as $option_id => $account) { ?>
<option <?= $account_filter === $option_id ? 'selected' : '' ?> value="<?= $option_id ?>"><?= escapeHtml($account['account_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="mb-3">
<label>Payment Method</label>
<div class="input-group">
<div class="col-md-6">
<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="method">
<option value="">- All Payment Methods -</option>
<?php
$sql_payment_methods_filter = mysqli_query($mysqli, "SELECT DISTINCT payment_method AS method FROM payments WHERE payment_method != ''
UNION SELECT DISTINCT revenue_payment_method FROM revenues WHERE revenue_payment_method != ''
ORDER BY method ASC");
while ($row = mysqli_fetch_assoc($sql_payment_methods_filter)) {
$filter_method = escapeHtml($row['method']);
?>
<option <?php if ($method_filter == $filter_method) { echo "selected"; } ?> value="<?= $filter_method ?>"><?= $filter_method ?></option>
<?php
}
?>
</select>
<select class="form-select select2" name="method">
<option value="">- Any payment method -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT DISTINCT payment_method AS method FROM payments WHERE COALESCE(payment_method, '') <> ''
UNION SELECT DISTINCT revenue_payment_method FROM revenues WHERE COALESCE(revenue_payment_method, '') <> '' ORDER BY method ASC");
while ($row = mysqli_fetch_row($sql)) { ?>
<option <?= $method_filter === $row[0] ? 'selected' : '' ?> value="<?= escapeHtml($row[0]) ?>"><?= escapeHtml($row[0]) ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="mb-3">
<label>Date From</label>
<div class="input-group">
<div class="col-md-6">
<label class="form-label">Dated from</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_from" value="<?= $date_from_filter ?>" max="2999-12-31">
<input type="date" class="form-control" name="dtf" value="<?= $date_from_filter ?>" max="2999-12-31">
</div>
</div>
</div>
<div class="mb-3">
<label>Date To</label>
<div class="input-group">
<div class="col-md-6">
<label class="form-label">Dated to</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_to" value="<?= $date_to_filter ?>" max="2999-12-31">
<input type="date" class="form-control" name="dtt" value="<?= $date_to_filter ?>" max="2999-12-31">
</div>
</div>
</div>
<?php exportTabsColumns('income'); ?>
</div>

View File

@@ -0,0 +1,179 @@
<?php
/*
* A payment's quick look - the invoice it paid (status, what it was for, what
* it came to, what has been paid on it in all and what is left), the other
* payments on it, where the money went and how it was paid. One paid online
* shows the payment provider's fee and what came in after it, when the fee
* is in the expenses with the payment's reference. Open the
* invoice, email the receipt again, Edit and Delete. Opened from the Income
* list, Transactions and the reports. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_financial');
$row = incomePaymentRow(intval($_GET['id'] ?? 0));
if (!$row) {
echo json_encode(['error' => 'That payment no longer exists, or is not one you can see.']);
exit;
}
$payment_id = intval($row['payment_id']);
$client_id = intval($row['invoice_client_id']);
$amount = floatval($row['payment_amount']);
$currency = (string) ($row['payment_currency_code'] ?: $row['invoice_currency_code']);
$has_invoice = $row['invoice_number'] !== null;
$can_sales = lookupUserPermission('module_sales') >= 1;
$can_edit = incomeCanEditPayments() && $has_invoice;
$online = preg_match('/^Stripe - pi_/', (string) $row['payment_reference']) === 1;
$state = $has_invoice ? invoiceState($row, $row['invoice_paid']) : null;
$can_receipt = $has_invoice && lookupUserPermission('module_sales') >= 2 && $client_id;
$receipt_to = $can_receipt ? array_column(billingEmailRecipients($client_id), 'email') : [];
$money = function ($value, $code = null) use ($currency) {
return escapeHtml(billingMoney($value, $code ?? $currency));
};
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-file-invoice-dollar"></i></span>
<div class="min-w-0 flex-grow-1">
<h5 class="modal-title fw-semibold text-break"><?= $has_invoice ? 'Payment on ' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) : 'Payment' ?></h5>
<div class="small text-body-secondary mt-1 text-truncate"><?= escapeHtml(date('D, M j, Y', strtotime($row['payment_date']))) ?><?= $row['client_name'] !== null ? ' &middot; ' . escapeHtml($row['client_name']) : '' ?></div>
</div>
<div class="text-end">
<div class="fs-4 fw-semibold text-white text-nowrap"><?= $money($amount) ?></div>
<?php if ($online) { ?>
<div class="small text-body-secondary"><i class="fas fa-globe me-1"></i>Paid online</div>
<?php } ?>
</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">
<!-- The invoice it paid -->
<?php if ($has_invoice) { ?>
<div class="p-3 rounded border bg-body-tertiary mb-3">
<div class="d-flex flex-wrap align-items-start gap-3">
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold">
<?php if ($can_sales) { ?>
<a href="invoice.php?invoice_id=<?= intval($row['invoice_id']) ?>"><?= escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?></a>
<?php } else { ?>
<?= escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?>
<?php } ?>
<span class="ms-1"><?= invoiceStatusBadge($row['invoice_status']) ?></span>
<?= invoiceDuePill($state) ?>
</div>
<?php if (trim((string) $row['invoice_scope']) !== '') { ?>
<div class="small text-body-secondary text-truncate mt-1"><?= escapeHtml($row['invoice_scope']) ?></div>
<?php } ?>
<div class="small text-body-secondary mt-1">Dated <?= escapeHtml($row['invoice_date']) ?>, due <?= escapeHtml($row['invoice_due']) ?></div>
</div>
<div class="text-end small">
<div><span class="text-body-secondary">Invoice</span> <span class="itflow-money fw-semibold ms-2"><?= $money($row['invoice_amount'], $row['invoice_currency_code']) ?></span></div>
<div><span class="text-body-secondary">Paid in all</span> <span class="itflow-money ms-2"><?= $money($row['invoice_paid'], $row['invoice_currency_code']) ?></span></div>
<div class="<?= $state['balance'] > 0 ? 'text-danger-emphasis' : 'text-success-emphasis' ?>">
<span><?= $state['balance'] > 0 ? 'Still owed' : 'Nothing owed' ?></span>
<?php if ($state['balance'] > 0) { ?><span class="itflow-money fw-semibold ms-2"><?= $money($state['balance'], $row['invoice_currency_code']) ?></span><?php } ?>
</div>
</div>
</div>
<?php if ($row['others']) { ?>
<div class="border-top mt-3 pt-2">
<div class="small fw-semibold text-uppercase text-body-secondary mb-1">The other payment<?= count($row['others']) === 1 ? '' : 's' ?> on it</div>
<?php foreach ($row['others'] as $other) { ?>
<div class="d-flex justify-content-between small">
<a href="#" class="ajax-modal" data-modal-size="lg" data-modal-url="modals/payment/payment.php?id=<?= intval($other['payment_id']) ?>"><?= escapeHtml($other['payment_date']) ?><?= $other['payment_method'] ? ' - ' . escapeHtml($other['payment_method']) : '' ?></a>
<span class="itflow-money"><?= $money($other['payment_amount'], $other['payment_currency_code'] ?: $row['invoice_currency_code']) ?></span>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<?php } else { ?>
<div class="alert alert-warning small">The invoice this was paid on has since been deleted.</div>
<?php } ?>
<!-- At a glance -->
<div class="row g-2 itflow-asset-glance">
<div class="col-sm-6">
<div class="itflow-glance-item" title="Client">
<i class="fas fa-fw fa-building"></i>
<?php if ($client_id && $row['client_name'] !== null) { ?>
<a class="text-truncate" href="income.php?client_id=<?= $client_id ?>" title="What came in from them"><?= escapeHtml($row['client_name']) ?></a>
<?php } else { ?>
<span class="text-body-secondary">No client</span>
<?php } ?>
</div>
<div class="itflow-glance-item" title="Category - the invoice's">
<i class="fas fa-fw fa-tag"></i>
<?php if (intval($row['invoice_category_id']) && $row['category_name'] !== null) { ?>
<span class="text-truncate"><?= expenseCategoryDot($row['category_color']) ?><?= escapeHtml($row['category_name']) ?></span>
<?php } else { ?>
<span class="text-warning-emphasis">No category<?= $has_invoice ? ' - set one on the invoice' : '' ?></span>
<?php } ?>
</div>
<div class="itflow-glance-item" title="Entered">
<i class="fas fa-fw fa-clock"></i>
<span title="<?= escapeHtml($row['payment_created_at']) ?>"><?= timeAgo($row['payment_created_at']) ?></span>
</div>
</div>
<div class="col-sm-6">
<div class="itflow-glance-item" title="Paid into">
<i class="fas fa-fw fa-piggy-bank"></i>
<span class="text-truncate"><?= escapeHtml($row['account_name'] ?: 'No account') ?><?= $row['account_archived_at'] ? ' <span class="text-body-secondary">(archived)</span>' : '' ?></span>
</div>
<div class="itflow-glance-item" title="Paid by">
<i class="fas fa-fw fa-credit-card"></i>
<span><?= escapeHtml($row['payment_method'] ?: '-') ?></span>
</div>
<?php if (trim((string) $row['payment_reference']) !== '') { ?>
<div class="itflow-glance-item" title="Reference">
<i class="fas fa-fw fa-hashtag"></i>
<span class="font-monospace text-truncate"><?= escapeHtml($row['payment_reference']) ?></span>
</div>
<?php } ?>
</div>
</div>
<!-- Paid online: what the payment provider kept, when its fee is in the expenses -->
<?php if ($online && $row['fee']) {
$fee = floatval($row['fee']['expense_amount']); ?>
<div class="d-flex flex-wrap align-items-center gap-3 mt-3 p-2 px-3 rounded border">
<i class="fas fa-globe text-info"></i>
<div class="flex-grow-1 small">
The payment provider's fee was <a href="#" class="ajax-modal" data-modal-size="lg" data-modal-url="modals/expense/expense.php?id=<?= intval($row['fee']['expense_id']) ?>"><?= $money($fee, $row['fee']['expense_currency_code'] ?: $currency) ?></a>
- <strong><?= $money($amount - $fee) ?></strong> came in after it
</div>
</div>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($has_invoice && $can_sales) { ?>
<a class="btn btn-primary text-bold" href="invoice.php?invoice_id=<?= intval($row['invoice_id']) ?>"><i class="fas fa-file-invoice me-2"></i>Open Invoice</a>
<?php } ?>
<?php if ($can_receipt) { ?>
<a class="btn btn-outline-secondary confirm-link <?= $receipt_to ? '' : 'disabled' ?>" href="post.php?payment_send_receipt=<?= $payment_id ?>&amp;csrf_token=<?= $_SESSION['csrf_token'] ?>"
title="<?= $receipt_to ? 'To ' . escapeHtml(implode(', ', $receipt_to)) : 'No billing contact with an email' ?>"
data-confirm-text="The receipt for <?= $money($amount) ?> goes to <?= escapeHtml(implode(', ', $receipt_to)) ?>."><i class="fas fa-paper-plane"></i><span class="d-none d-sm-inline ms-2">Email Receipt</span></a>
<?php } ?>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-url="modals/payment/payment_edit.php?id=<?= $payment_id ?>"><i class="fas fa-edit"></i><span class="d-none d-sm-inline ms-2">Edit</span></button>
<a class="btn btn-outline-danger confirm-link" href="post.php?delete_payment=<?= $payment_id ?>&amp;csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="The payment of <?= $money($amount) ?> comes off <?= escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?>, which is owed again."><i class="fas fa-trash"></i><span class="d-none d-sm-inline ms-2">Delete</span></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';

View File

@@ -0,0 +1,129 @@
<?php
/*
* Other income's quick look - what it was, the client it came from (and what
* else came in from them this year), its category, the account it went into,
* how it was paid, its reference and who entered it. Edit, Copy and Delete.
* Opened from the Income list, Transactions and the reports. ?id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_financial');
$row = incomeRevenueRow(intval($_GET['id'] ?? 0));
if (!$row) {
echo json_encode(['error' => 'That income no longer exists, or is not one you can see.']);
exit;
}
$revenue_id = intval($row['revenue_id']);
$client_id = intval($row['revenue_client_id']);
$amount = floatval($row['revenue_amount']);
$currency = (string) $row['revenue_currency_code'];
$description = trim((string) $row['revenue_description']);
$title = trim(strtok($description, "\n"));
if ($title === '') {
$title = $row['category_name'] ?: 'Other income';
}
$rest = trim(substr($description, strlen(strtok($description, "\n"))));
$can_edit = incomeCanEdit();
$can_delete = incomeCanDelete();
$client_year = $client_id && $row['client_name'] !== null ? incomeTotal(date('Y-01-01'), date('Y-m-d'), $client_id) : null;
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"><?= escapeHtml($title) ?></h5>
<div class="small text-body-secondary mt-1 text-truncate"><?= escapeHtml(date('D, M j, Y', strtotime($row['revenue_date']))) ?> &middot; Other income</div>
</div>
<div class="text-end">
<div class="fs-4 fw-semibold text-nowrap <?= $amount < 0 ? 'text-danger' : 'text-white' ?>"><?= escapeHtml(billingMoney($amount, $currency)) ?></div>
<?php if ($amount < 0) { ?>
<div class="small text-body-secondary">went back out</div>
<?php } ?>
</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">
<!-- At a glance -->
<div class="row g-2 itflow-asset-glance">
<div class="col-sm-6">
<div class="itflow-glance-item" title="From client">
<i class="fas fa-fw fa-building"></i>
<?php if ($client_id && $row['client_name'] !== null) { ?>
<a class="text-truncate" href="income.php?client_id=<?= $client_id ?>" title="What came in from them"><?= escapeHtml($row['client_name']) ?></a>
<?php } else { ?>
<span class="text-body-secondary">Not from a client</span>
<?php } ?>
</div>
<div class="itflow-glance-item" title="Category">
<i class="fas fa-fw fa-tag"></i>
<?php if (intval($row['revenue_category_id']) && $row['category_name'] !== null) { ?>
<a class="text-reset text-truncate" href="income.php?category=<?= intval($row['revenue_category_id']) ?>"><?= expenseCategoryDot($row['category_color']) ?><?= escapeHtml($row['category_name']) ?></a>
<?php } else { ?>
<span class="text-warning-emphasis">No category - the reports show it as No category</span>
<?php } ?>
</div>
<div class="itflow-glance-item" title="Entered">
<i class="fas fa-fw fa-clock"></i>
<span><span title="<?= escapeHtml($row['revenue_created_at']) ?>"><?= timeAgo($row['revenue_created_at']) ?></span><?php if ($row['created_by_name']) { ?> <span class="text-body-secondary">by <?= escapeHtml($row['created_by_name']) ?></span><?php } ?></span>
</div>
</div>
<div class="col-sm-6">
<div class="itflow-glance-item" title="Paid into">
<i class="fas fa-fw fa-piggy-bank"></i>
<span class="text-truncate"><?= escapeHtml($row['account_name'] ?: 'No account') ?><?= $row['account_archived_at'] ? ' <span class="text-body-secondary">(archived)</span>' : '' ?></span>
</div>
<div class="itflow-glance-item" title="Paid by">
<i class="fas fa-fw fa-credit-card"></i>
<span><?= escapeHtml($row['revenue_payment_method'] ?: '-') ?></span>
</div>
<?php if (trim((string) $row['revenue_reference']) !== '') { ?>
<div class="itflow-glance-item" title="Reference">
<i class="fas fa-fw fa-hashtag"></i>
<span class="font-monospace text-truncate"><?= escapeHtml($row['revenue_reference']) ?></span>
</div>
<?php } ?>
</div>
</div>
<?php if ($rest !== '') { ?>
<div class="mt-3">
<div class="small fw-semibold text-uppercase text-body-secondary mb-1">Notes</div>
<div class="text-break" style="white-space: pre-line;"><?= escapeHtml($rest) ?></div>
</div>
<?php } ?>
<?php if ($client_year !== null) { ?>
<div class="d-flex align-items-center gap-3 mt-3 p-2 px-3 rounded border bg-body-tertiary small">
<i class="fas fa-chart-line text-body-secondary"></i>
<div class="flex-grow-1"><strong><?= escapeHtml(billingMoney($client_year)) ?></strong> in from <?= escapeHtml($row['client_name']) ?> so far this year, invoice payments included</div>
<a href="income.php?client_id=<?= $client_id ?>">See it all</a>
</div>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-primary text-bold ajax-modal" data-modal-size="lg" data-modal-url="modals/revenue/revenue_edit.php?id=<?= $revenue_id ?>"><i class="fas fa-edit me-2"></i>Edit</button>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-size="lg" data-modal-url="modals/revenue/revenue_copy.php?id=<?= $revenue_id ?>"><i class="fas fa-copy me-2"></i>Copy</button>
<?php } ?>
<?php if ($can_delete) { ?>
<a class="btn btn-outline-danger confirm-link" href="post.php?delete_revenue=<?= $revenue_id ?>&amp;csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= escapeHtml(incomeRevenueLabel($row)) ?> goes for good."><i class="fas fa-trash"></i><span class="d-none d-sm-inline ms-2">Delete</span></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';

View File

@@ -1,148 +1,38 @@
<?php
/*
* New Income - money in that isn't for an invoice: a deposit, a rebate,
* interest, a referral fee. ?client_id= starts it with a client (from their
* Income page). A payment against an invoice is added on the invoice.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_financial', 2);
$form_row = null;
$form_mode = 'new';
$form_client_id = intval($_GET['client_id'] ?? 0);
if ($form_client_id) {
$client_id = $form_client_id;
enforceClientAccess();
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-hand-holding-usd me-2"></i>New Revenue</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-hand-holding-usd me-2"></i>New Income</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<div class="row g-2">
<div class="mb-3 col-md">
<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="mb-3 col-md">
<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>
<input type="text" class="form-control" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="amount" placeholder="0.00" required>
</div>
</div>
</div>
<div class="row g-2">
<div class="mb-3 col-md">
<label>Account <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="">- Account -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT account_currency_code, account_id, account_name, opening_balance FROM accounts WHERE account_archived_at IS NULL ORDER BY account_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$account_id = intval($row['account_id']);
$account_name = escapeHtml($row['account_name']);
$account_currency_code = escapeHtml($row['account_currency_code']);
$opening_balance = floatval($row['opening_balance']);
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_payments FROM payments WHERE payment_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_payments);
$total_payments = floatval($row['total_payments']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS total_revenues FROM revenues WHERE revenue_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_revenues);
$total_revenues = floatval($row['total_revenues']);
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS total_expenses FROM expenses WHERE expense_account_id = $account_id");
$row = mysqli_fetch_assoc($sql_expenses);
$total_expenses = floatval($row['total_expenses']);
$balance = $opening_balance + $total_payments + $total_revenues - $total_expenses;
?>
<option <?php if ($config_default_payment_account == $account_id) { echo "selected"; } ?> value="<?= $account_id ?>"><?= $account_name ?> [ <?= numfmt_format_currency($currency_format, $balance, $account_currency_code) ?> ]</option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3 col-md">
<label>Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Category -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND category_archived_at IS NULL ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
</div>
<div class="mb-3">
<label>Description</label>
<textarea class="form-control" rows="5" name="description" placeholder="Enter a description" maxlength="200"></textarea>
</div>
<div class="row g-2">
<div class="mb-3 col-md">
<label>Payment Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="payment_method" required>
<option value="">- Method of Payment -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods ORDER BY payment_method_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$payment_method_name = escapeHtml($row['payment_method_name']);
?>
<option><?= $payment_method_name ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3 col-md">
<label>Reference</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-alt"></i></span>
<input type="text" class="form-control" name="reference" placeholder="Check #, trans #, etc" maxlength="200">
</div>
</div>
</div>
<div class="small text-body-secondary mb-3"><i class="fas fa-info-circle me-1"></i>For money in that isn't for an invoice. A payment on an invoice is added from the invoice, so it is marked paid.</div>
<?php require __DIR__ . '/revenue_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_revenue" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Add Revenue</button>
<button type="submit" name="add_revenue" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Add Income</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -0,0 +1,34 @@
<?php
/* Copy other income - the same category, client, account and amount, dated today. ?id= */
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_financial', 2);
$form_row = incomeRevenueRow(intval($_GET['id'] ?? 0));
if (!$form_row) {
exit(json_encode(['error' => 'That income no longer exists, or is not one you can see.']));
}
$form_mode = 'copy';
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fas fa-fw fa-copy me-2"></i>Copy Income</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="modal-body">
<?php require __DIR__ . '/revenue_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_revenue" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Add Income</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,171 +1,29 @@
<?php
/* Edit other income - with write access to Financial. ?id= */
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_financial', 2);
$revenue_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT revenue_account_id, revenue_amount, revenue_category_id, revenue_created_at,
revenue_currency_code, revenue_date, revenue_description, revenue_payment_method,
revenue_reference FROM revenues WHERE revenue_id = $revenue_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$revenue_description = escapeHtml($row['revenue_description']);
$revenue_reference = escapeHtml($row['revenue_reference']);
$revenue_date = escapeHtml($row['revenue_date']);
$revenue_payment_method = escapeHtml($row['revenue_payment_method']);
$revenue_amount = floatval($row['revenue_amount']);
$revenue_currency_code = escapeHtml($row['revenue_currency_code']);
$revenue_created_at = escapeHtml($row['revenue_created_at']);
$account_id = intval($row['revenue_account_id']);
$category_id = intval($row['revenue_category_id']);
$form_row = incomeRevenueRow(intval($_GET['id'] ?? 0));
if (!$form_row) {
exit(json_encode(['error' => 'That income no longer exists, or is not one you can see.']));
}
$form_mode = 'edit';
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-hand-holding-usd me-2"></i>Edit Revenue</h5>
<h5 class="modal-title text-truncate"><i class="fas fa-fw fa-hand-holding-usd me-2"></i>Edit Income <span class="fw-normal text-white-50 ms-1"><?= escapeHtml($form_row['revenue_date']) ?></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">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="revenue_id" value="<?= $revenue_id ?>">
<input type="hidden" name="revenue_id" value="<?= intval($form_row['revenue_id']) ?>">
<div class="modal-body">
<div class="row g-2">
<div class="mb-3 col-md">
<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="<?= $revenue_date ?>" required>
</div>
</div>
<div class="mb-3 col-md">
<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>
<input type="text" class="form-control" inputmode="decimal" pattern="[0-9]*\.?[0-9]{0,2}" name="amount" value="<?= number_format($revenue_amount, 2, '.', '') ?>" placeholder="0.00" required>
</div>
</div>
</div>
<div class="row g-2">
<div class="mb-3 col-md">
<label>Account <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="">- Select Account -</option>
<?php
$sql_accounts = mysqli_query($mysqli, "SELECT account_archived_at, account_currency_code, account_id, account_name, opening_balance FROM accounts WHERE (account_archived_at > '$revenue_created_at' OR account_archived_at IS NULL) ORDER BY account_archived_at ASC, account_name ASC");
while ($row = mysqli_fetch_assoc($sql_accounts)) {
$account_id_select = intval($row['account_id']);
$account_name_select = escapeHtml($row['account_name']);
$account_currency_code_select = escapeHtml($row['account_currency_code']);
$opening_balance = floatval($row['opening_balance']);
$account_archived_at = escapeHtml($row['account_archived_at']);
if (empty($account_archived_at)) {
$account_archived_display = "";
} else {
$account_archived_display = "Archived - ";
}
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS total_payments FROM payments WHERE payment_account_id = $account_id_select");
$row = mysqli_fetch_assoc($sql_payments);
$total_payments = floatval($row['total_payments']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS total_revenues FROM revenues WHERE revenue_account_id = $account_id_select");
$row = mysqli_fetch_assoc($sql_revenues);
$total_revenues = floatval($row['total_revenues']);
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS total_expenses FROM expenses WHERE expense_account_id = $account_id_select");
$row = mysqli_fetch_assoc($sql_expenses);
$total_expenses = floatval($row['total_expenses']);
$balance = $opening_balance + $total_payments + $total_revenues - $total_expenses;
?>
<option <?php if ($account_id == $account_id_select) { echo "selected"; } ?> value="<?= $account_id_select ?>"><?= $account_archived_display ?> <?= $account_name_select ?> [ <?= numfmt_format_currency($currency_format, $balance, $account_currency_code_select) ?> ]</option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3 col-md">
<label>Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- Select Category -</option>
<?php
$sql_category = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND (category_archived_at > '$revenue_created_at' OR category_archived_at IS NULL) ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql_category)) {
$category_id_select = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option <?php if ($category_id_select == $category_id) { echo "selected"; } ?> value="<?= $category_id_select ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
</select>
<button class="btn btn-secondary ajax-modal" title="New category" type="button"
data-modal-url="../admin/modals/category/category_add.php?category=Income">
<i class="fas fa-fw fa-plus"></i>
</button>
</div>
</div>
</div>
<div class="mb-3">
<label>Description</label>
<textarea class="form-control" rows="8" name="description" maxlength="200"><?= $revenue_description ?></textarea>
</div>
<div class="row g-2">
<div class="mb-3 col-md">
<label>Payment Method <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-money-check-alt"></i></span>
<select class="form-select select2" name="payment_method" required>
<option value="">- Select Method of Payment -</option>
<?php
$sql_categories = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods ORDER BY payment_method_name ASC");
while ($row = mysqli_fetch_assoc($sql_categories)) {
$payment_method_name_select = escapeHtml($row['payment_method_name']);
?>
<option <?php if ($revenue_payment_method == $payment_method_name_select) { echo "selected"; } ?>><?= "$payment_method_name_select" ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3 col-md">
<label>Reference</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-alt"></i></span>
<input type="text" class="form-control" name="reference" placeholder="Check #, trans #, etc" maxlength="200" value="<?= $revenue_reference ?>">
</div>
</div>
</div>
<?php require __DIR__ . '/revenue_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_revenue" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
@@ -174,5 +32,4 @@ ob_start();
</form>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,175 @@
<?php
/*
* The fields of other income - money in that isn't for an invoice - shared
* by New Income, Edit and Copy. Set before including:
*
* $form_mode new | edit | copy
* $form_row incomeRevenueRow() for edit and copy; null for new
* $form_client_id the client a new one starts with (0 for none)
*
* Posts date, amount, account, category, client_id, payment_method,
* reference and description (agent/post/revenue.php). The currency is the
* account's and follows the account picked; a copy is dated today.
*
* Should not be accessed directly.
*/
isset($mysqli) || die("Direct file access is not allowed");
$form_edit = $form_mode === 'edit';
$form_id = 'revenueForm' . ucfirst($form_mode) . ($form_row ? intval($form_row['revenue_id']) : '');
$form_value = function ($column, $default = '') use ($form_row) {
return $form_row ? (string) ($form_row[$column] ?? $default) : $default;
};
$form_date = $form_edit ? $form_value('revenue_date') : date('Y-m-d');
$form_amount = $form_row ? floatval($form_row['revenue_amount']) : null;
$form_account = $form_row ? intval($form_row['revenue_account_id']) : intval($config_default_payment_account);
$form_category = intval($form_value('revenue_category_id', '0'));
$form_client = $form_row ? intval($form_row['revenue_client_id']) : intval($form_client_id ?? 0);
$form_method = $form_row ? $form_value('revenue_payment_method') : (string) ($config_default_payment_method ?? '');
$form_reference = $form_edit ? $form_value('revenue_reference') : '';
$form_description = $form_value('revenue_description');
$form_accounts = paymentAccounts($form_edit ? $form_account : 0);
if (!isset($form_accounts[$form_account])) {
$form_account = 0;
}
$form_categories = incomeCategories($form_edit ? $form_category : 0);
$form_methods = paymentMethods();
if ($form_method !== '' && !in_array($form_method, $form_methods, true)) {
if ($form_edit) {
$form_methods[] = $form_method;
} else {
$form_method = '';
}
}
$form_clients = [];
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients
WHERE (client_archived_at IS NULL OR client_id = $form_client) " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$form_clients[] = $row;
}
$form_currency = $form_account ? ($form_accounts[$form_account]['account_currency_code'] ?: $session_company_currency) : $session_company_currency;
?>
<div class="row g-3" id="<?= $form_id ?>">
<div class="col-md-7">
<label class="form-label">Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="category" required>
<option value="">- What it was -</option>
<?php foreach ($form_categories as $category_id => $category) { ?>
<option value="<?= $category_id ?>" <?= $form_category === $category_id ? 'selected' : '' ?><?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?><?= $category['category_archived_at'] ? ' (archived)' : '' ?></option>
<?php } ?>
</select>
<?php if ($session_is_admin) { ?>
<button class="btn btn-outline-secondary ajax-modal" title="New category" type="button" data-modal-url="../admin/modals/category/category_add.php?category=Income"><i class="fas fa-fw fa-plus"></i></button>
<?php } ?>
</div>
</div>
<div class="col-md-5">
<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>
<input type="text" class="form-control text-end fw-semibold" inputmode="decimal" pattern="-?[0-9,]*\.?[0-9]{0,2}" name="amount" placeholder="0.00" required
value="<?= $form_amount === null ? '' : number_format($form_amount, 2, '.', '') ?>" <?= $form_mode === 'new' ? 'autofocus' : '' ?>>
<span class="input-group-text" data-revenue-currency><?= escapeHtml($form_currency) ?></span>
</div>
<?php if ($form_edit && $form_amount < 0) { ?>
<div class="form-text">Negative - money that went back out.</div>
<?php } ?>
</div>
<div class="col-md-7">
<label class="form-label">Paid into <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="account" required data-revenue-account>
<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" data-currency="<?= escapeHtml($account['account_currency_code'] ?: $session_company_currency) ?>"
data-description="<?= escapeHtml(billingMoney($account['balance'], $account['account_currency_code'])) ?><?= $account['account_archived_at'] ? ' - archived' : '' ?>"><?= 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="<?= escapeHtml($form_date) ?>" required>
</div>
</div>
<div class="col-12">
<label class="form-label">From client</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="client_id">
<option value="0">- Not from a client -</option>
<?php foreach ($form_clients as $client) { ?>
<option value="<?= intval($client['client_id']) ?>" <?= $form_client === intval($client['client_id']) ? 'selected' : '' ?><?= selectOptionClient($client['client_id'], $client['client_name'], $client['client_abbreviation'] ?? '') ?>><?= escapeHtml($client['client_name']) ?></option>
<?php } ?>
</select>
</div>
<div class="form-text">Money of theirs that isn't for an invoice - it counts for them in Income by Client and Client Profitability.</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 it was paid -</option>
<?php foreach ($form_methods as $method) { ?>
<option value="<?= escapeHtml($method) ?>" <?= $form_method === $method ? 'selected' : '' ?>><?= escapeHtml($method) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-7">
<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 number, deposit or transaction number" value="<?= escapeHtml($form_reference) ?>">
</div>
</div>
<div class="col-12">
<label class="form-label">Description</label>
<div class="input-group">
<span class="input-group-text align-items-start pt-2"><i class="fa fa-fw fa-align-left"></i></span>
<textarea class="form-control" rows="3" name="description" placeholder="What it was - Pax8 partner rebate for Q3, referral fee from Ravenwood, interest"><?= escapeHtml($form_description) ?></textarea>
</div>
<div class="form-text">The first line shows in the list.</div>
</div>
</div>
<script>
(function () {
// The currency is the account's
var root = document.getElementById(<?= json_encode($form_id) ?>);
if (!root || root.dataset.revenueWired) {
return;
}
root.dataset.revenueWired = '1';
var account = root.querySelector('[data-revenue-account]');
var currency = root.querySelector('[data-revenue-currency]');
var update = function () {
var option = account.options[account.selectedIndex];
currency.textContent = option && option.dataset.currency ? option.dataset.currency : <?= json_encode((string) $session_company_currency) ?>;
};
account.addEventListener('change', update);
if (window.jQuery) {
window.jQuery(account).on('change select2:select', update);
}
})();
</script>

View File

@@ -1,7 +1,15 @@
<?php
/*
* ITFlow - Income POST request handler
* ITFlow - the Income list's bulk actions and export. The list holds
* payments and other income together, so the ticked rows come as
* payment-12 / revenue-7 (incomeBulkIds()).
*
* Other income is changed with write access to Financial. A payment keeps
* the invoice's own rules - full access to Sales and Financial - and its
* category and client are its invoice's: Set Category sets the invoice's,
* Set Client leaves payments alone, and payments are deleted from their
* invoice, not here.
*/
if (!defined('FROM_POST_HANDLER')) {
@@ -9,299 +17,132 @@ if (!defined('FROM_POST_HANDLER')) {
exit;
}
// The Income page merges payments and revenues, so its bulk actions have to fan out across both
// tables. Selection parsing is shared - see income_model.php.
// Gating: these are the multi-row form of the row Edit action on the Income page, so they gate the
// same way the payment edit handler does (the strictest of the two row types).
if (isset($_POST['bulk_edit_income_account'])) {
if (isset($_POST['bulk_edit_income'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 3);
enforceUserPermission('module_financial', 3);
enforceUserPermission('module_financial', 2);
require_once 'income_model.php';
$account_id = intval($_POST['bulk_account_id']);
// Get Account name for logging and Notification - and confirm it is a real, un-archived account
$sql_account = mysqli_query($mysqli, "SELECT account_name FROM accounts WHERE account_id = $account_id AND account_archived_at IS NULL LIMIT 1");
$row = mysqli_fetch_assoc($sql_account);
if (!$row || !$income_count) {
flashAlert("Nothing to update", 'error');
$ids = incomeBulkIds($_POST['income_ids'] ?? []);
$field = (string) ($_POST['field'] ?? '');
$raw = (string) ($_POST['value'] ?? '');
$value = intval($raw);
$can_payments = incomeCanEditPayments();
$label = '';
if ($field === 'category') {
$categories = incomeCategories();
if (isset($categories[$value])) {
$label = 'the category to ' . $categories[$value]['category_name'];
$revenue_set = "revenue_category_id = $value";
}
} elseif ($field === 'account') {
$accounts = paymentAccounts();
if (isset($accounts[$value]) && !$accounts[$value]['account_archived_at']) {
$label = 'the account to ' . $accounts[$value]['account_name'];
$revenue_set = "revenue_account_id = $value";
$payment_set = "payment_account_id = $value";
}
} elseif ($field === 'method') {
if (in_array($raw, paymentMethods(), true)) {
$label = 'the payment method to ' . $raw;
$revenue_set = "revenue_payment_method = '" . escapeSql($raw) . "'";
$payment_set = "payment_method = '" . escapeSql($raw) . "'";
}
} elseif ($field === 'client') {
if (!$value) {
$label = 'no client';
$revenue_set = 'revenue_client_id = 0';
} elseif (mysqli_num_rows(mysqli_query($mysqli, "SELECT client_id FROM clients WHERE client_id = $value " . clientScopeSql('client_id')))) {
$label = 'the client to ' . getFieldById('clients', $value, 'client_name');
$revenue_set = "revenue_client_id = $value";
}
}
if ($label === '' || (!$ids['payment'] && !$ids['revenue'])) {
flashAlert($ids['payment'] || $ids['revenue'] ? 'Pick what to set them to' : 'Tick the income to change first', 'error');
redirect();
}
$label_sql = escapeSql($label);
$account_name = escapeSql($row['account_name']);
$updated_count = 0;
// Payments - client comes from the invoice the payment was made against
foreach ($payment_ids as $payment_id) {
$sql = mysqli_query($mysqli, "SELECT payment_reference, invoice_client_id FROM payments LEFT JOIN invoices ON payment_invoice_id = invoice_id WHERE payment_id = $payment_id AND payment_archived_at IS NULL");
$row = mysqli_fetch_assoc($sql);
// Other income
$count = 0;
foreach ($ids['revenue'] as $revenue_id) {
$row = incomeRevenueRow($revenue_id);
if (!$row) {
continue;
}
$payment_reference = escapeSql($row['payment_reference']);
$client_id = intval($row['invoice_client_id']);
if ($client_id) {
enforceClientAccess($client_id);
}
mysqli_query($mysqli, "UPDATE payments SET payment_account_id = $account_id WHERE payment_id = $payment_id");
logAudit("Payment", "Edit", "$session_name assigned payment $payment_reference to account $account_name", $client_id, $payment_id);
$updated_count++;
mysqli_query($mysqli, "UPDATE revenues SET $revenue_set WHERE revenue_id = $revenue_id");
logAudit("Revenue", "Edit", "$session_name set $label_sql on other income " . escapeSql(incomeRevenueLabel($row)), intval($row['revenue_client_id']), $revenue_id);
$count++;
}
// Revenues
foreach ($revenue_ids as $revenue_id) {
$sql = mysqli_query($mysqli, "SELECT revenue_description, revenue_client_id FROM revenues WHERE revenue_id = $revenue_id AND revenue_archived_at IS NULL");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
continue;
// Payments - their own account and method; their invoice's category; never their client
$kept = 0;
$invoices = 0;
if ($field === 'client' || !$can_payments) {
$kept = count($ids['payment']);
} elseif ($field === 'category') {
$invoice_rows = [];
foreach ($ids['payment'] as $payment_id) {
$row = incomePaymentRow($payment_id);
if ($row && $row['invoice_id']) {
$invoice_rows[intval($row['invoice_id'])] = $row;
$count++;
} elseif ($row) {
$kept++;
}
}
$revenue_description = escapeSql($row['revenue_description']);
$client_id = intval($row['revenue_client_id']);
if ($client_id) {
enforceClientAccess($client_id);
foreach ($invoice_rows as $invoice_id => $row) {
mysqli_query($mysqli, "UPDATE invoices SET invoice_category_id = $value WHERE invoice_id = $invoice_id");
logAudit("Invoice", "Edit", "$session_name set $label_sql on invoice " . escapeSql($row['invoice_prefix'] . $row['invoice_number']) . " from the Income list", intval($row['invoice_client_id']), $invoice_id);
$invoices++;
}
mysqli_query($mysqli, "UPDATE revenues SET revenue_account_id = $account_id WHERE revenue_id = $revenue_id");
logAudit("Revenue", "Edit", "$session_name assigned revenue $revenue_description to account $account_name", $client_id, $revenue_id);
$updated_count++;
}
if ($updated_count) {
logAudit("Income", "Bulk Edit", "$session_name assigned $updated_count income record(s) to account $account_name");
flashAlert("You assigned account <strong>$account_name</strong> to <strong>$updated_count</strong> income record(s)");
} else {
flashAlert("No income records were updated", 'error');
foreach ($ids['payment'] as $payment_id) {
$row = incomePaymentRow($payment_id);
if (!$row) {
continue;
}
mysqli_query($mysqli, "UPDATE payments SET $payment_set WHERE payment_id = $payment_id");
logAudit("Payment", "Edit", "$session_name set $label_sql on the payment " . escapeSql(incomePaymentLabel($row)), intval($row['invoice_client_id']), $payment_id);
$count++;
}
}
logAudit("Income", "Bulk Edit", "$session_name set $label_sql on $count income record" . ($count === 1 ? '' : 's'));
$notes = [];
if ($invoices) {
$notes[] = "on the $invoices invoice" . ($invoices === 1 ? '' : 's') . ' behind the payments';
}
if ($kept) {
$notes[] = "$kept payment" . ($kept === 1 ? '' : 's') . ' left as ' . ($kept === 1 ? 'it was' : 'they were')
. ($field === 'client' ? " - a payment's client is its invoice's" : ($can_payments ? ' - not on an invoice' : ' - changing a payment takes full access to Sales and Financial'));
}
flashAlert("Set " . escapeHtml($label) . " on <strong>$count</strong>" . ($notes ? ' - ' . escapeHtml(implode('; ', $notes)) : ''), $kept ? 'warning' : 'success');
redirect();
}
if (isset($_POST['bulk_edit_income_category'])) {
if (isset($_POST['bulk_delete_income'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 3);
enforceUserPermission('module_financial', 3);
require_once 'income_model.php';
$category_id = intval($_POST['bulk_category_id']);
// Get Category name for logging and Notification - and confirm it is a live Income category
$sql_category = mysqli_query($mysqli, "SELECT category_name FROM categories WHERE category_id = $category_id AND category_type = 'Income' AND category_archived_at IS NULL LIMIT 1");
$row = mysqli_fetch_assoc($sql_category);
if (!$row || !$income_count) {
flashAlert("Nothing to update", 'error');
redirect();
}
$category_name = escapeSql($row['category_name']);
$revenue_updated_count = 0;
$invoice_updated_count = 0;
$skipped_count = 0;
// Revenues carry their own category
foreach ($revenue_ids as $revenue_id) {
$sql = mysqli_query($mysqli, "SELECT revenue_description, revenue_client_id FROM revenues WHERE revenue_id = $revenue_id AND revenue_archived_at IS NULL");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
$skipped_count++;
continue;
}
$revenue_description = escapeSql($row['revenue_description']);
$client_id = intval($row['revenue_client_id']);
if ($client_id) {
enforceClientAccess($client_id);
}
mysqli_query($mysqli, "UPDATE revenues SET revenue_category_id = $category_id WHERE revenue_id = $revenue_id");
logAudit("Revenue", "Edit", "$session_name assigned revenue $revenue_description to category $category_name", $client_id, $revenue_id);
$revenue_updated_count++;
}
// A payment has no category of its own - it inherits the one on the invoice it was paid
// against, so this writes to the INVOICE. Two selected payments against the same invoice
// therefore collapse into a single invoice update, and a payment with no invoice is skipped.
$invoice_ids = [];
foreach ($payment_ids as $payment_id) {
$sql = mysqli_query($mysqli, "SELECT payment_invoice_id FROM payments WHERE payment_id = $payment_id AND payment_archived_at IS NULL");
$row = mysqli_fetch_assoc($sql);
$payment_invoice_id = intval($row['payment_invoice_id'] ?? 0);
if ($payment_invoice_id) {
$invoice_ids[$payment_invoice_id] = $payment_invoice_id;
} else {
$skipped_count++;
}
}
foreach ($invoice_ids as $invoice_id) {
$sql = mysqli_query($mysqli, "SELECT invoice_prefix, invoice_number, invoice_client_id FROM invoices WHERE invoice_id = $invoice_id");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
$skipped_count++;
continue;
}
$invoice_prefix = escapeSql($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$client_id = intval($row['invoice_client_id']);
enforceClientAccess($client_id);
mysqli_query($mysqli, "UPDATE invoices SET invoice_category_id = $category_id WHERE invoice_id = $invoice_id");
logAudit("Invoice", "Edit", "$session_name assigned invoice $invoice_prefix$invoice_number to category $category_name", $client_id, $invoice_id);
$invoice_updated_count++;
}
// Spell out the invoice leg - the user selected payments, not invoices
$updated_summary = [];
if ($revenue_updated_count) {
$updated_summary[] = "<strong>$revenue_updated_count</strong> revenue(s)";
}
if ($invoice_updated_count) {
$updated_summary[] = "<strong>$invoice_updated_count</strong> invoice(s) behind the selected payment(s)";
}
if ($updated_summary) {
logAudit("Income", "Bulk Edit", "$session_name assigned category $category_name to $revenue_updated_count revenue(s) and $invoice_updated_count invoice(s)");
$skipped_note = '';
if ($skipped_count) {
$skipped_note = " - <strong>$skipped_count</strong> record(s) skipped";
}
flashAlert("You assigned category <strong>$category_name</strong> to " . implode(' and ', $updated_summary) . $skipped_note);
} else {
flashAlert("No income records were categorised - a payment can only take a category from the invoice it was paid against", 'error');
}
redirect();
}
if (isset($_POST['bulk_edit_income_method'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 3);
enforceUserPermission('module_financial', 3);
require_once 'income_model.php';
// The method is stored by name on both tables, so validate it against the lookup list
$payment_method = escapeSql($_POST['bulk_payment_method']);
$sql_payment_method = mysqli_query($mysqli, "SELECT payment_method_name FROM payment_methods WHERE payment_method_name = '$payment_method' LIMIT 1");
$row = mysqli_fetch_assoc($sql_payment_method);
if (!$row || !$income_count) {
flashAlert("Nothing to update", 'error');
redirect();
}
$payment_method = escapeSql($row['payment_method_name']);
$updated_count = 0;
// Payments - client comes from the invoice the payment was made against
foreach ($payment_ids as $payment_id) {
$sql = mysqli_query($mysqli, "SELECT payment_reference, invoice_client_id FROM payments LEFT JOIN invoices ON payment_invoice_id = invoice_id WHERE payment_id = $payment_id AND payment_archived_at IS NULL");
$row = mysqli_fetch_assoc($sql);
$ids = incomeBulkIds($_POST['income_ids'] ?? []);
$count = 0;
foreach ($ids['revenue'] as $revenue_id) {
$row = incomeRevenueDelete($revenue_id, $delete_error);
if (!$row) {
continue;
}
$payment_reference = escapeSql($row['payment_reference']);
$client_id = intval($row['invoice_client_id']);
if ($client_id) {
enforceClientAccess($client_id);
}
mysqli_query($mysqli, "UPDATE payments SET payment_method = '$payment_method' WHERE payment_id = $payment_id");
logAudit("Payment", "Edit", "$session_name set payment $payment_reference to payment method $payment_method", $client_id, $payment_id);
$updated_count++;
logAudit("Revenue", "Delete", "$session_name deleted other income " . escapeSql(incomeRevenueLabel($row)), intval($row['revenue_client_id']));
$count++;
}
logAudit("Income", "Bulk Delete", "$session_name deleted $count other income record" . ($count === 1 ? '' : 's'));
// Revenues
foreach ($revenue_ids as $revenue_id) {
$sql = mysqli_query($mysqli, "SELECT revenue_description, revenue_client_id FROM revenues WHERE revenue_id = $revenue_id AND revenue_archived_at IS NULL");
$row = mysqli_fetch_assoc($sql);
if (!$row) {
continue;
}
$revenue_description = escapeSql($row['revenue_description']);
$client_id = intval($row['revenue_client_id']);
if ($client_id) {
enforceClientAccess($client_id);
}
mysqli_query($mysqli, "UPDATE revenues SET revenue_payment_method = '$payment_method' WHERE revenue_id = $revenue_id");
logAudit("Revenue", "Edit", "$session_name set revenue $revenue_description to payment method $payment_method", $client_id, $revenue_id);
$updated_count++;
}
if ($updated_count) {
logAudit("Income", "Bulk Edit", "$session_name set $updated_count income record(s) to payment method $payment_method");
flashAlert("You set payment method <strong>$payment_method</strong> on <strong>$updated_count</strong> income record(s)");
} else {
flashAlert("No income records were updated", 'error');
}
$kept = count($ids['payment']);
flashAlert("<strong>$count</strong> other income deleted" . ($kept ? " - $kept payment" . ($kept === 1 ? ' was' : 's were') . ' kept; a payment is deleted from its invoice' : ''), 'error');
redirect();
@@ -315,183 +156,45 @@ if (isExportRequest('export_income')) {
$format = resolveExportFormat($_POST['export_income']);
$date_from = escapeSql($_POST['date_from']);
$date_to = escapeSql($_POST['date_to']);
$account = intval($_POST['account']);
// Client Filter - carried over from the client-scoped Income page
$client_id = intval($_POST['client_id'] ?? 0);
// The same filters as the Income list, over the income this agent may see
$src = $_POST;
if (!empty($_POST['client_id'])) {
$src['client'] = intval($_POST['client_id']);
}
$where = incomeFiltersSql($src, $filter_summary);
$client_id = intval($src['client'] ?? 0);
if ($client_id) {
enforceClientAccess();
$payment_client_query = "AND invoice_client_id = $client_id";
$revenue_client_query = "AND revenue_client_id = $client_id";
$client_name = getFieldById('clients', $client_id, 'client_name');
$file_name_prepend = "$client_name-";
} else {
// Default - any
$payment_client_query = '';
$revenue_client_query = '';
$file_name_prepend = "$session_company_name-";
}
// Type Filter
$income_types_array = ['Payment', 'Revenue'];
if (!empty($_POST['type']) && in_array($_POST['type'], $income_types_array)) {
$type_query = "AND (income_type = '" . escapeSql($_POST['type']) . "')";
} else {
// Default - any
$type_query = '';
}
// Account Filter
if ($account) {
$account_query = "AND (income_account_id = $account)";
} else {
// Default - any
$account_query = '';
}
// Category Filter - a revenue carries its own category, a payment inherits the one on the
// invoice it was paid against. Both come from the same 'Income' category pool.
$category = intval($_POST['category'] ?? 0);
if ($category) {
$category_query = "AND (income_category_id = $category)";
} else {
// Default - any
$category_query = '';
}
// Payment Method Filter
if (!empty($_POST['method'])) {
$method_query = "AND (income_method = '" . escapeSql($_POST['method']) . "')";
} else {
// Default - any
$method_query = '';
}
// Search Filter - mirrors the income page search box
$q = escapeSql($_POST['q']);
if (!empty($q)) {
$search_query = "AND (income_source LIKE '%$q%' OR income_category LIKE '%$q%' OR income_client LIKE '%$q%' OR income_account LIKE '%$q%' OR income_method LIKE '%$q%' OR income_reference LIKE '%$q%' OR income_amount LIKE '%$q%')";
} else {
// Default - any
$search_query = '';
}
// Date Filter
if (!empty($date_from) && !empty($date_to)) {
$date_query = "AND DATE(income_date) BETWEEN '$date_from' AND '$date_to'";
} else {
$date_query = '';
}
// Filter summary for the export header. This handler was the only one not building it,
// so a filtered PDF came out looking like a full export.
$filter_summary = [];
if ($client_id) {
$filter_summary['Client'] = $client_name;
}
if (!empty($_POST['type']) && in_array($_POST['type'], $income_types_array)) {
$filter_summary['Type'] = $_POST['type'];
}
if ($category) {
$filter_summary['Category'] = getFieldById('categories', $category, 'category_name');
}
if ($account) {
$filter_summary['Account'] = getFieldById('accounts', $account, 'account_name');
}
if (!empty($_POST['method'])) {
$filter_summary['Payment Method'] = $_POST['method'];
}
if (!empty($date_from) && !empty($date_to)) {
$filter_summary['Date'] = "$date_from to $date_to";
}
if (!empty($_POST['q'])) {
$filter_summary['Search'] = $_POST['q'];
}
// Same union as income.php - payments applied to an invoice, and standalone revenues.
// Transfers between accounts are stored as a linked expense + revenue pair, so the revenue leg
// is excluded here (transfer_id IS NULL) - moving your own money is not income.
$sql = mysqli_query(
$mysqli,
"SELECT * FROM (
SELECT
'Payment' AS income_type,
payment_id AS income_id,
payment_date AS income_date,
payment_created_at AS income_created_at,
CONCAT(invoice_prefix, invoice_number) AS income_source,
category_name AS income_category,
IFNULL(invoice_category_id, 0) AS income_category_id,
client_name AS income_client,
payment_amount AS income_amount,
payment_currency_code AS income_currency_code,
payment_method AS income_method,
payment_reference AS income_reference,
payment_account_id AS income_account_id,
account_name AS income_account
FROM payments
LEFT JOIN invoices ON payment_invoice_id = invoice_id
LEFT JOIN clients ON invoice_client_id = client_id
LEFT JOIN accounts ON payment_account_id = account_id
LEFT JOIN categories ON invoice_category_id = category_id
WHERE payment_archived_at IS NULL
$payment_client_query
" . clientScopeSql('invoice_client_id') . "
UNION ALL
SELECT
'Revenue',
revenue_id,
revenue_date,
revenue_created_at,
revenue_description,
category_name,
revenue_category_id,
client_name,
revenue_amount,
revenue_currency_code,
revenue_payment_method,
revenue_reference,
revenue_account_id,
account_name
FROM revenues
LEFT JOIN categories ON revenue_category_id = category_id
LEFT JOIN clients ON revenue_client_id = client_id
LEFT JOIN accounts ON revenue_account_id = account_id
LEFT JOIN transfers ON transfer_revenue_id = revenue_id
WHERE revenue_archived_at IS NULL
AND transfer_id IS NULL
$revenue_client_query
) AS income
WHERE 1 = 1
$date_query
$type_query
$category_query
$account_query
$method_query
$search_query
ORDER BY income_date ASC, income_created_at ASC, income_type ASC, income_id ASC"
);
$sql = mysqli_query($mysqli, "SELECT income.* FROM (" . incomeUnionSql() . ") AS income
WHERE $where
ORDER BY income.income_date ASC, income.income_created_at ASC, income.income_type ASC, income.income_id ASC");
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0) {
guardExportPdfRowCount($format, $num_rows);
$export = beginExport('income', $format, $file_name_prepend . 'Income', 'Income', summarizeExportFilters($filter_summary));
$export = beginExport('income', $format, ($client_id ? getFieldById('clients', $client_id, 'client_name') : $session_company_name) . '-Income', 'Income', summarizeExportFilters($filter_summary));
while ($row = mysqli_fetch_assoc($sql)) {
$is_payment = $row['income_type'] === 'payment';
$row['income_type'] = $is_payment ? 'Invoice payment' : 'Other income';
$row['income_invoice'] = $is_payment && $row['invoice_number'] !== null ? $row['invoice_prefix'] . $row['invoice_number'] : '';
$row['income_source'] = trim(strtok((string) $row['income_description'], "\n"));
$row['income_category'] = (string) $row['category_name'];
$row['income_client'] = (string) $row['client_name'];
$row['income_account'] = (string) $row['account_name'];
$row['income_online'] = intval($row['income_online']) ? 'Yes' : '';
addExportRow($export, $row);
}
finishExport($export);
}
logAudit("Income", "Export", "$session_name exported $num_rows income record(s) to a " . strtoupper($format) . " file");
logAudit("Income", "Export", "$session_name exported $num_rows income record(s) to a " . strtoupper($format) . " file", $client_id);
exit;

View File

@@ -1,36 +0,0 @@
<?php
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
// The Income page is a UNION of two tables, so its bulk checkboxes carry a composite reference
// ("Payment-12" / "Revenue-7") rather than a bare id. Split them back out into per-table id
// lists so each bulk handler can update the right table.
$payment_ids = [];
$revenue_ids = [];
foreach ((array) ($_POST['income_ids'] ?? []) as $income_ref) {
if (!is_string($income_ref)) {
continue;
}
$income_ref_parts = explode('-', $income_ref, 2);
if (count($income_ref_parts) != 2) {
continue;
}
$income_ref_id = intval($income_ref_parts[1]);
if ($income_ref_id < 1) {
continue;
}
if ($income_ref_parts[0] == 'Payment') {
$payment_ids[$income_ref_id] = $income_ref_id;
} elseif ($income_ref_parts[0] == 'Revenue') {
$revenue_ids[$income_ref_id] = $income_ref_id;
}
}
$income_count = count($payment_ids) + count($revenue_ids);

View File

@@ -636,3 +636,34 @@ if (isset($_GET['refund_payment_stripe'])) {
redirect();
}
/* Email a payment's receipt to the client's billing contacts again - from its quick look. */
if (isset($_GET['payment_send_receipt'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
enforceUserPermission('module_financial');
$row = incomePaymentRow(intval($_GET['payment_send_receipt']));
if (!$row || $row['invoice_number'] === null) {
flashAlert('That payment no longer exists, or is not one you can see', 'error');
redirect();
}
$receipt_to = billingPaymentSend($row['invoice_id'], floatval($row['payment_amount']), [
'date' => $row['payment_date'],
'method' => (string) $row['payment_method'],
'reference' => (string) $row['payment_reference'],
]);
if (!$receipt_to) {
flashAlert(escapeHtml($row['client_name']) . ' has no billing contact with an email to send the receipt to', 'error');
redirect();
}
logAudit("Invoice", "Payment", "Payment receipt for invoice " . escapeSql($row['invoice_prefix'] . $row['invoice_number']) . " queued to " . escapeSql(implode(', ', $receipt_to)), intval($row['invoice_client_id']), intval($row['invoice_id']));
flashAlert("Receipt for <strong>" . escapeHtml(incomePaymentLabel($row)) . "</strong> queued to " . escapeHtml(implode(', ', $receipt_to)));
redirect();
}

View File

@@ -1,32 +1,45 @@
<?php
/*
* ITFlow - GET/POST request handler for revenue
* ITFlow - other income: money in that isn't for an invoice (revenues).
* New and Copy post add_revenue, Edit posts edit_revenue - both through
* incomeRevenueSave(), which checks every field. Write access to Financial
* adds and changes it; full access deletes it.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
/** The form's fields as incomeRevenueSave() takes them. */
function revenuePostInput() {
return [
'date' => (string) ($_POST['date'] ?? ''),
'amount' => (string) ($_POST['amount'] ?? ''),
'account' => intval($_POST['account'] ?? 0),
'category' => intval($_POST['category'] ?? 0),
'client_id' => intval($_POST['client_id'] ?? 0),
'payment_method' => (string) ($_POST['payment_method'] ?? ''),
'reference' => (string) ($_POST['reference'] ?? ''),
'description' => (string) ($_POST['description'] ?? ''),
];
}
if (isset($_POST['add_revenue'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
enforceUserPermission('module_financial', 2);
$date = escapeSql($_POST['date']);
$amount = floatval($_POST['amount']);
$account = intval($_POST['account']);
$category = intval($_POST['category']);
$payment_method = escapeSql($_POST['payment_method']);
$description = escapeSql($_POST['description']);
$reference = escapeSql($_POST['reference']);
$revenue_id = incomeRevenueSave(revenuePostInput(), 0, $error);
if (!$revenue_id) {
flashAlert(escapeHtml($error), 'error');
redirect();
}
$row = incomeRevenueRow($revenue_id);
$label = incomeRevenueLabel($row);
mysqli_query($mysqli,"INSERT INTO revenues SET revenue_date = '$date', revenue_amount = $amount, revenue_currency_code = '$session_company_currency', revenue_payment_method = '$payment_method', revenue_reference = '$reference', revenue_description = '$description', revenue_category_id = $category, revenue_account_id = $account");
logAudit("Revenue", "Create", "$session_name added other income " . escapeSql($label), intval($row['revenue_client_id']), $revenue_id);
$revenue_id = mysqli_insert_id($mysqli);
logAudit("Revenue", "Create", "$session_name added revenue $description", 0, $revenue_id);
flashAlert("Revenue added");
flashAlert("Income <strong>" . escapeHtml($label) . "</strong> added");
redirect();
@@ -36,28 +49,23 @@ if (isset($_POST['edit_revenue'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
enforceUserPermission('module_financial', 2);
$revenue_id = intval($_POST['revenue_id']);
$revenue_id = intval($_POST['revenue_id'] ?? 0);
$before = incomeRevenueRow($revenue_id);
if (!incomeRevenueSave(revenuePostInput(), $revenue_id, $error)) {
flashAlert(escapeHtml($error), 'error');
redirect();
}
$row = incomeRevenueRow($revenue_id);
$label = incomeRevenueLabel($row);
$client_id = intval(getFieldById('revenues', $revenue_id, 'revenue_client_id'));
if ($client_id) {
enforceClientAccess();
logAudit("Revenue", "Edit", "$session_name edited other income " . escapeSql($label), intval($row['revenue_client_id']), $revenue_id);
if ($before && intval($before['revenue_client_id']) && intval($before['revenue_client_id']) !== intval($row['revenue_client_id'])) {
logAudit("Revenue", "Edit", "$session_name moved other income " . escapeSql($label) . " to " . escapeSql($row['client_name'] ?: 'no client'), intval($before['revenue_client_id']), $revenue_id);
}
$date = escapeSql($_POST['date']);
$amount = floatval($_POST['amount']);
$account = intval($_POST['account']);
$category = intval($_POST['category']);
$payment_method = escapeSql($_POST['payment_method']);
$description = escapeSql($_POST['description']);
$reference = escapeSql($_POST['reference']);
mysqli_query($mysqli,"UPDATE revenues SET revenue_date = '$date', revenue_amount = $amount, revenue_payment_method = '$payment_method', revenue_reference = '$reference', revenue_description = '$description', revenue_category_id = $category, revenue_account_id = $account WHERE revenue_id = $revenue_id");
logAudit("Revenue", "Edit", "$session_name edited revenue $description", 0, $revenue_id);
flashAlert("Revenue edited");
flashAlert("Income <strong>" . escapeHtml($label) . "</strong> saved");
redirect();
@@ -67,23 +75,18 @@ if (isset($_GET['delete_revenue'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 3);
enforceUserPermission('module_financial', 3);
$revenue_id = intval($_GET['delete_revenue']);
$client_id = intval(getFieldById('revenues', $revenue_id, 'revenue_client_id'));
if ($client_id) {
enforceClientAccess();
$row = incomeRevenueDelete(intval($_GET['delete_revenue']), $error);
if (!$row) {
flashAlert(escapeHtml($error), 'error');
redirect();
}
$label = incomeRevenueLabel($row);
// Get Revenue Details
$revenue_description = escapeSql(getFieldById('revenues', $revenue_id, 'revenue_description'));
logAudit("Revenue", "Delete", "$session_name deleted other income " . escapeSql($label), intval($row['revenue_client_id']));
mysqli_query($mysqli,"DELETE FROM revenues WHERE revenue_id = $revenue_id");
logAudit("Revenue", "Delete", "$session_name deleted revenue $revenue_description");
flashAlert("Revenue removed", 'error');
flashAlert("Income <strong>" . escapeHtml($label) . "</strong> deleted", 'error');
redirect();

View File

@@ -2,10 +2,12 @@
/*
* Income - a year of money received, by income category and month. Invoice
* payments are filed under the category of the invoice they paid; revenues
* entered on their own count when they have a category and are not one side
* of a transfer between accounts - the same income the dashboard and the
* Profit & Loss count. Compared with last year to the same date.
* payments are filed under the category of the invoice they paid; other
* income (money in that isn't for an invoice) under its own, and under No
* category without one. The money coming in from a transfer between our
* accounts isn't income. The same income the Income list, the dashboard and
* the Profit & Loss count (functions/income.php). Compared with last year to
* the same date.
*/
require_once "includes/inc_report.php";
@@ -31,7 +33,7 @@ if (reportExporting()) {
reportCategoryYearCsv($categories, $grid, $year, "Income $year", 'Total income');
}
// Where it came from: invoices paid, or revenue entered on its own
// Where it came from: invoices paid, or other income
$from_invoices = dashboardSum("SELECT SUM(payment_amount) FROM payments WHERE " . reportRangeSql('payment_date', ['start' => $from, 'end' => $to]));
$from_other = $totals['total'] - $from_invoices;
@@ -62,9 +64,9 @@ require_once "includes/inc_report_layout.php";
['label' => 'Income', 'value' => reportMoney($totals['total']), 'sub' => reportChangeHtml($totals['total'], $prev_total, 'up', $compare),
'url' => "/agent/income.php?canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Invoice payments', 'value' => reportMoney($from_invoices), 'sub' => escapeHtml(reportPercent(reportShare($from_invoices, $totals['total']))) . ' <span class="text-body-tertiary">of income</span>',
'url' => "/agent/income.php?type=payment&canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Other revenue', 'value' => reportMoney($from_other), 'sub' => escapeHtml(reportPercent(reportShare($from_other, $totals['total']))) . ' <span class="text-body-tertiary">of income</span>',
'url' => "/agent/income.php?type=revenue&canned_date=custom&dtf=$from&dtt=$to"],
'url' => "/agent/income.php?show=payments&canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Other income', 'value' => reportMoney($from_other), 'sub' => escapeHtml(reportPercent(reportShare($from_other, $totals['total']))) . ' <span class="text-body-tertiary">of income</span>',
'url' => "/agent/income.php?show=other&canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Monthly average', 'value' => reportMoney($average), 'sub' => $best_month ? 'Best month <span class="text-body">' . date('F', mktime(0, 0, 0, $best_month, 1)) . '</span>' : ''],
]) ?>
@@ -84,10 +86,10 @@ require_once "includes/inc_report_layout.php";
</div>
</div>
<?= reportSectionOpen('By category', 'Click an amount to see the payments and revenue behind it', 'itflow-report-long') ?>
<?= reportCategoryYearTable($categories, $grid, $year, 'income.php', 'Total income') ?>
<?= reportSectionOpen('By category', 'Click an amount to see the payments and other income behind it', 'itflow-report-long') ?>
<?= reportCategoryYearTable($categories, $grid, $year, 'income.php', 'Total income', 'show=uncategorised') ?>
<div class="card-footer small text-body-secondary">
Payments are filed under the category of the invoice they paid. Revenue counts when it has a category; transfers between your own accounts are left out.
Payments are filed under the category of the invoice they paid, other income under its own - No category when it has none. Transfers between your own accounts are left out.
</div>
</div>

View File

@@ -5,8 +5,8 @@
* quarter, with the net profit and margin under it and last year beside it.
*
* Cash basis, as the dashboard: income is invoice payments (filed under the
* invoice's category) and revenues with a category; spending is vendor
* expenses. Transfers between accounts are neither. In the current year it
* invoice's category) and other income, categorised or not (No category);
* spending is vendor expenses. Transfers between accounts are neither. In the current year it
* runs to today and is compared with the same stretch of last year.
*/
@@ -124,9 +124,9 @@ $render = function ($line, $class = '') use ($columns, $year) {
. escapeHtml($line['name']) . (!empty($line['archived']) ? ' <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Archived</span>' : '') . '</td>';
foreach ($columns as $i => [$label, $first, $last]) {
$url = '';
if ($list && $cat) {
if ($list && ($cat || $kind === 'income')) {
[$dtf, $dtt] = reportColumnDates($year, $first, $last);
$url = "/agent/$list?category=$cat&canned_date=custom&dtf=$dtf&dtt=$dtt";
$url = "/agent/$list?" . ($cat ? "category=$cat" : 'show=uncategorised') . "&canned_date=custom&dtf=$dtf&dtt=$dtt";
}
$amount = $line['cells'][$i];
$html .= '<td class="text-end' . ($kind === 'profit' && $amount < 0 ? ' text-danger' : '') . '">' . reportGridAmount($amount, $url) . '</td>';

View File

@@ -504,7 +504,9 @@ if ($account_filter) {
} 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";
$transaction_modal_url = "modals/revenue/revenue.php?id=$transaction_id";
} elseif ($transaction_type == 'Payment') {
$transaction_modal_url = "modals/payment/payment.php?id=$transaction_id";
} else {
$transaction_modal_url = "";
}
@@ -513,17 +515,11 @@ if ($account_filter) {
<tr>
<td class="ps-3">
<?php if ($transaction_type == 'Payment') { ?>
<a class="text-bold" href="invoice.php?invoice_id=<?= $transaction_invoice_id ?>">
<?= $transaction_date ?>
</a>
<?php } else { ?>
<a class="text-bold ajax-modal" href="#"
data-modal-size="lg"
data-modal-url="<?= $transaction_modal_url ?>">
<?= $transaction_date ?>
</a>
<?php } ?>
<a class="text-bold ajax-modal" href="#"
data-modal-size="lg"
data-modal-url="<?= $transaction_modal_url ?>">
<?= $transaction_date ?>
</a>
</td>
<td><span class="badge text-bg-<?= $transaction_badge_color ?>"><?= $transaction_type ?></span></td>
<td>

View File

@@ -6368,3 +6368,9 @@ a.itflow-billing-stat:hover {
max-width: 0;
min-width: 14rem;
}
/* Income - what it was takes the room left and cuts short, rather than push the amount off the side (agent/income.php) */
.itflow-income-from {
width: 100%;
max-width: 0;
min-width: 14rem;
}

9
db.sql
View File

@@ -1789,7 +1789,8 @@ CREATE TABLE `payments` (
`payment_account_id` int(11) NOT NULL,
`payment_invoice_id` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`payment_id`),
KEY `payment_invoice_id` (`payment_invoice_id`)
KEY `payment_invoice_id` (`payment_invoice_id`),
KEY `payment_date` (`payment_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -2345,15 +2346,17 @@ CREATE TABLE `revenues` (
`revenue_currency_code` varchar(200) NOT NULL,
`revenue_payment_method` varchar(200) DEFAULT NULL,
`revenue_reference` varchar(200) DEFAULT NULL,
`revenue_description` varchar(200) DEFAULT NULL,
`revenue_description` text DEFAULT NULL,
`revenue_created_at` datetime NOT NULL DEFAULT current_timestamp(),
`revenue_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
`revenue_archived_at` datetime DEFAULT NULL,
`revenue_category_id` int(11) NOT NULL DEFAULT 0,
`revenue_account_id` int(11) NOT NULL,
`revenue_client_id` int(11) NOT NULL DEFAULT 0,
`revenue_created_by` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`revenue_id`),
KEY `revenue_client_id` (`revenue_client_id`,`revenue_archived_at`)
KEY `revenue_client_id` (`revenue_client_id`,`revenue_archived_at`),
KEY `revenue_date` (`revenue_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

View File

@@ -56,3 +56,4 @@ require_once __DIR__ . '/functions/billing_email.php';
require_once __DIR__ . '/functions/expenses.php';
require_once __DIR__ . '/functions/expense_import.php';
require_once __DIR__ . '/functions/trips.php';
require_once __DIR__ . '/functions/income.php';

View File

@@ -544,7 +544,7 @@ function clientOverviewMoney($client_id, $balance, $recurring_monthly) {
return dashboardSum("SELECT SUM(payment_amount) FROM payments JOIN invoices ON payment_invoice_id = invoice_id
WHERE invoice_client_id = $client_id AND payment_date BETWEEN '$from' AND '$to'")
+ dashboardSum("SELECT SUM(revenue_amount) FROM revenues WHERE revenue_client_id = $client_id
AND revenue_category_id > 0 AND revenue_date BETWEEN '$from' AND '$to'");
AND " . dashboardRevenueSql() . " AND revenue_date BETWEEN '$from' AND '$to'");
};
$paid_ytd = $paid($year_start, $today);
$paid_last_ytd = $paid($last_year_start, $last_year_today);
@@ -625,7 +625,7 @@ function clientOverviewMonthly($client_id) {
JOIN invoices ON payment_invoice_id = invoice_id
WHERE invoice_client_id = $client_id AND payment_date BETWEEN '$from' AND '$to' GROUP BY m", $months),
dashboardMonthly("SELECT DATE_FORMAT(revenue_date, '%Y-%m') AS m, SUM(revenue_amount) AS v FROM revenues
WHERE revenue_client_id = $client_id AND revenue_category_id > 0 AND revenue_date BETWEEN '$from' AND '$to' GROUP BY m", $months)
WHERE revenue_client_id = $client_id AND " . dashboardRevenueSql() . " AND revenue_date BETWEEN '$from' AND '$to' GROUP BY m", $months)
);
return [

View File

@@ -642,17 +642,16 @@ function dashboardMoney($amount) {
}
/**
* SQL: a revenue that is income - it has a category, and it is not the in
* side of a transfer between accounts. The transfer handler leaves both
* halves without a category; one that has been given one since (the demo data
* files them as "Account Transfer") is still only money moving between
* accounts. The out side is never spending: it has no vendor.
* SQL: a revenue that is income - any that is not the in side of a transfer
* between accounts, categorised or not, as the Income list counts it
* (incomeRevenueSql()). The out side of a transfer is never spending: it has
* no vendor.
*/
function dashboardRevenueSql() {
return "revenue_category_id > 0 AND revenue_id NOT IN (SELECT transfer_revenue_id FROM transfers)";
return incomeRevenueSql('revenues.revenue_id');
}
/** Cash basis, as the Income reports: invoice payments plus categorised revenues. */
/** Cash basis, as the Income list and reports: invoice payments plus other income. */
function dashboardIncome($start, $end) {
return dashboardSum("SELECT SUM(payment_amount) FROM payments WHERE payment_date BETWEEN '$start' AND '$end'")
+ dashboardSum("SELECT SUM(revenue_amount) FROM revenues WHERE " . dashboardRevenueSql() . " AND revenue_date BETWEEN '$start' AND '$end'");
@@ -932,7 +931,7 @@ function dashboardTopClients($period, $limit = 8) {
WHERE payment_date BETWEEN '$start' AND '$end' " . clientScopeSql('invoice_client_id') . "
UNION ALL
SELECT revenue_client_id, revenue_amount FROM revenues
WHERE revenue_category_id > 0 AND revenue_client_id > 0 AND revenue_date BETWEEN '$start' AND '$end' " . clientScopeSql('revenue_client_id') . "
WHERE " . dashboardRevenueSql() . " AND revenue_client_id > 0 AND revenue_date BETWEEN '$start' AND '$end' " . clientScopeSql('revenue_client_id') . "
) AS income
JOIN clients USING (client_id)
GROUP BY client_id, client_name

View File

@@ -396,7 +396,8 @@ function getExportColumns($export_type) {
'income' => [
'income_date' => ['label' => 'Date'],
'income_type' => ['label' => 'Type'],
'income_source' => ['label' => 'Source', 'weight' => 3],
'income_invoice' => ['label' => 'Invoice'],
'income_source' => ['label' => 'What for', 'weight' => 3],
'income_category' => ['label' => 'Category'],
'income_client' => ['label' => 'Client', 'weight' => 2],
'income_amount' => ['label' => 'Amount', 'format' => 'money'],
@@ -404,6 +405,7 @@ function getExportColumns($export_type) {
'income_method' => ['label' => 'Payment Method'],
'income_reference' => ['label' => 'Reference'],
'income_account' => ['label' => 'Account'],
'income_online' => ['label' => 'Paid Online'],
],
'transactions' => [

388
functions/income.php Normal file
View File

@@ -0,0 +1,388 @@
<?php
/*
* ITFlow - income: the money that comes in.
*
* Two kinds. A payment is money against an invoice (payments) - its client
* and category are the invoice's, and it is made and changed from the
* invoice. Other income is money in that isn't for an invoice (revenues) - a
* deposit, a rebate, interest, a referral fee - with its own client and
* category, made here. The money coming into one account from another in a
* transfer is a revenue too, but isn't income (incomeRevenueSql()).
*
* Every list, total, report and dashboard counts income the same way: the
* payments, and the other income that isn't a transfer, categorised or not.
*
* Who sees what: Financial access, in the agent's client scope. Other income
* is added and changed with write access to Financial and deleted with full
* access; a payment keeps the invoice's own rules (Sales and Financial).
*/
/** The SQL that makes a revenue income - not the money coming in from a transfer between our accounts. $column is the revenue id. */
function incomeRevenueSql($column = 'revenues.revenue_id') {
return "NOT EXISTS (SELECT 1 FROM transfers WHERE transfer_revenue_id = $column)";
}
/** May this agent add and change other income? */
function incomeCanEdit() {
return lookupUserPermission('module_financial') >= 2;
}
/** May this agent delete other income? */
function incomeCanDelete() {
return lookupUserPermission('module_financial') >= 3;
}
/** May this agent change and delete payments - the invoice's own rule. */
function incomeCanEditPayments() {
return lookupUserPermission('module_sales') >= 3 && lookupUserPermission('module_financial') >= 3;
}
/** Was a payment made online - through a payment provider? */
function incomeOnlineSql($reference = 'payment_reference') {
return "$reference LIKE 'Stripe - pi\\_%'";
}
/**
* Every payment and every piece of other income as one list, in the agent's
* client scope - a row each with income_type (payment or revenue),
* income_id, income_date, income_created_at, income_invoice_id,
* invoice_prefix, invoice_number, invoice_status, income_description,
* income_category_id, category_name, category_color, income_client_id,
* client_name, income_amount, income_currency_code, income_method,
* income_reference, income_account_id, account_name, account_archived_at
* and income_online. Select from it as a derived table.
*/
function incomeUnionSql() {
return "SELECT 'payment' AS income_type, payment_id AS income_id, payment_date AS income_date, payment_created_at AS income_created_at,
payment_invoice_id AS income_invoice_id, invoice_prefix, invoice_number, invoice_status, invoice_scope AS income_description,
COALESCE(invoice_category_id, 0) AS income_category_id, category_name, category_color,
COALESCE(invoice_client_id, 0) AS income_client_id, client_name, payment_amount AS income_amount, payment_currency_code AS income_currency_code,
payment_method AS income_method, payment_reference AS income_reference, payment_account_id AS income_account_id, account_name, account_archived_at,
IF(" . incomeOnlineSql() . ", 1, 0) AS income_online
FROM payments
LEFT JOIN invoices ON invoice_id = payment_invoice_id
LEFT JOIN clients ON client_id = invoice_client_id
LEFT JOIN accounts ON account_id = payment_account_id
LEFT JOIN categories ON category_id = invoice_category_id
WHERE payment_archived_at IS NULL " . clientScopeSql('COALESCE(invoice_client_id, 0)') . "
UNION ALL
SELECT 'revenue', revenue_id, revenue_date, revenue_created_at,
0, NULL, NULL, NULL, revenue_description,
revenue_category_id, category_name, category_color,
revenue_client_id, client_name, revenue_amount, revenue_currency_code,
revenue_payment_method, revenue_reference, revenue_account_id, account_name, account_archived_at,
0
FROM revenues
LEFT JOIN clients ON client_id = revenue_client_id
LEFT JOIN accounts ON account_id = revenue_account_id
LEFT JOIN categories ON category_id = revenue_category_id
WHERE revenue_archived_at IS NULL AND " . incomeRevenueSql() . ' ' . clientScopeSql('revenue_client_id');
}
/** The ways the list can be cut - ?show= (and the old ?type=Payment / Revenue). */
function incomeShows() {
return [
'' => ['label' => 'All', 'where' => ''],
'payments' => ['label' => 'Invoice payments', 'icon' => 'fa-file-invoice-dollar', 'where' => "income.income_type = 'payment'", 'title' => 'Paid against an invoice'],
'other' => ['label' => 'Other income', 'icon' => 'fa-hand-holding-usd', 'where' => "income.income_type = 'revenue'", 'title' => "Money in that isn't for an invoice"],
'online' => ['label' => 'Paid online', 'icon' => 'fa-globe', 'where' => 'income.income_online = 1', 'title' => 'Paid by card through the payment provider'],
'uncategorised' => ['label' => 'No category', 'icon' => 'fa-question-circle', 'where' => 'income.income_category_id = 0', 'title' => 'Not in a category - the reports show it as No category'],
];
}
/** The ?show= a request asks for - ?show=, or the ?type=payment / revenue older links use. */
function incomeShowFrom(array $src) {
$show = (string) ($src['show'] ?? '');
$type = strtolower((string) ($src['type'] ?? ''));
if ($show === '' && $type !== '') {
$show = $type === 'payment' ? 'payments' : ($type === 'revenue' ? 'other' : '');
}
return isset(incomeShows()[$show]) ? $show : '';
}
/**
* The WHERE over incomeUnionSql() AS income for a set of filters, as the list
* and the export take them: q, client, category, account, method, show (or
* type), dtf and dtt. $summary gets what each is, by name, for the export.
* $with_show false leaves the pill out, for the pills' own counts.
*/
function incomeFiltersSql(array $src, &$summary = [], $with_show = true) {
$summary = [];
$sql = '1 = 1';
$q = trim((string) ($src['q'] ?? ''));
if ($q !== '') {
$like = escapeSql($q);
$amount_text = str_replace([',', '$'], '', $q);
$amount = preg_match('/^-?\d+(\.\d{1,2})?$/', $amount_text) ? round(floatval($amount_text), 2) : null;
$sql .= " AND (income.income_description LIKE '%$like%' OR income.income_reference LIKE '%$like%' OR income.client_name LIKE '%$like%'
OR income.category_name LIKE '%$like%' OR income.account_name LIKE '%$like%' OR income.income_method LIKE '%$like%'
OR CONCAT(COALESCE(income.invoice_prefix, ''), COALESCE(income.invoice_number, '')) LIKE '%$like%'" . ($amount !== null ? " OR income.income_amount = $amount" : '') . ")";
$summary['Search'] = $q;
}
foreach (['client' => ['income.income_client_id', 'clients', 'client_name', 'Client'], 'category' => ['income.income_category_id', 'categories', 'category_name', 'Category'],
'account' => ['income.income_account_id', 'accounts', 'account_name', 'Account']] as $key => $f) {
$id = intval($src[$key] ?? 0);
if ($id) {
$sql .= " AND {$f[0]} = $id";
$summary[$f[3]] = (string) getFieldById($f[1], $id, $f[2]);
}
}
$method = trim((string) ($src['method'] ?? ''));
if ($method !== '') {
$sql .= " AND income.income_method = '" . escapeSql($method) . "'";
$summary['Paid by'] = $method;
}
$show = incomeShowFrom($src);
if ($with_show && $show !== '') {
$sql .= ' AND ' . incomeShows()[$show]['where'];
$summary['Showing'] = incomeShows()[$show]['label'];
}
$dtf = (string) ($src['dtf'] ?? '');
$dtt = (string) ($src['dtt'] ?? '');
$dtf = preg_match('/^\d{4}-\d{2}-\d{2}$/', $dtf) ? $dtf : '1970-01-01';
$dtt = preg_match('/^\d{4}-\d{2}-\d{2}$/', $dtt) ? $dtt : '2099-12-31';
if ($dtf !== '1970-01-01' || $dtt !== '2099-12-31') {
$sql .= " AND income.income_date BETWEEN '$dtf' AND '$dtt'";
$range = formatExportDateRange($dtf, $dtt);
if ($range) {
$summary['Dated'] = $range;
}
}
return $sql;
}
/** What came in between two dates, in the agent's client scope - optionally one client's. */
function incomeTotal($from, $to, $client_id = 0) {
global $mysqli;
$client_id = intval($client_id);
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(income_amount), 0) FROM (" . incomeUnionSql() . ") AS income
WHERE income.income_date BETWEEN '" . escapeSql($from) . "' AND '" . escapeSql($to) . "'" . ($client_id ? " AND income.income_client_id = $client_id" : '')));
return round(floatval($row[0]), 2);
}
/**
* The money along the top of the list, in the agent's client scope (one
* client's on their page): this month against the same days of last month,
* the year so far with its monthly average, what the running recurring
* invoices bill a month, and what is still owed on invoices (and how much
* of it is late).
*/
function incomeStats($client_id = 0) {
global $mysqli;
$client_id = intval($client_id);
$month_start = date('Y-m-01');
$today = date('Y-m-d');
$last_start = date('Y-m-01', strtotime('first day of last month'));
$last_to_date = date('Y-m-d', min(strtotime(date('Y-m-t', strtotime($last_start))), strtotime($last_start . ' +' . (intval(date('j')) - 1) . ' days')));
$year_start = date('Y-01-01');
$stats = [
'month_start' => $month_start, 'last_start' => $last_start, 'year_start' => $year_start,
'month' => incomeTotal($month_start, $today, $client_id),
'last_to_date' => incomeTotal($last_start, $last_to_date, $client_id),
'year' => incomeTotal($year_start, $today, $client_id),
];
$stats['change'] = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['last_to_date']) / $stats['last_to_date'] * 100) : null;
$stats['year_average'] = round($stats['year'] / max(1, intval(date('n')) - 1 + intval(date('j')) / intval(date('t'))), 2);
$client_sql = $client_id ? " AND recurring_invoice_client_id = $client_id" : '';
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(" . recurringInvoiceMonthlySql() . "), 0), COUNT(*) FROM recurring_invoices
WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL $client_sql " . clientScopeSql('recurring_invoice_client_id')));
$stats['recurring'] = round(floatval($row[0]), 2);
$stats['recurring_count'] = intval($row[1]);
$open = dashboardOpenInvoicesSql(($client_id ? " AND invoice_client_id = $client_id" : '') . ' ' . clientScopeSql('invoice_client_id'));
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(balance), 0), COUNT(*), COALESCE(SUM(CASE WHEN invoice_due < CURDATE() THEN balance END), 0),
COALESCE(SUM(invoice_due < CURDATE()), 0)
FROM ($open) AS open_invoices WHERE balance > 0"));
$stats['owed'] = round(floatval($row[0]), 2);
$stats['owed_count'] = intval($row[1]);
$stats['overdue'] = round(floatval($row[2]), 2);
$stats['overdue_count'] = intval($row[3]);
return $stats;
}
/** The income categories - id => row, archived ones left out but $keep_id. */
function incomeCategories($keep_id = 0) {
global $mysqli;
$keep_id = intval($keep_id);
$categories = [];
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon, category_archived_at FROM categories
WHERE category_type = 'Income' AND category_name <> 'Account Transfer' AND (category_archived_at IS NULL OR category_id = $keep_id)
ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$categories[intval($row['category_id'])] = $row;
}
return $categories;
}
/* ---------------------------------------------------------- Other income */
/** One piece of other income with its client, category, account and who entered it - raw, or null. Scoped; a transfer's leg isn't income. */
function incomeRevenueRow($revenue_id, $scoped = true) {
global $mysqli;
$revenue_id = intval($revenue_id);
if (!$revenue_id) {
return null;
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT revenues.*, client_name, client_abbreviation, category_name, category_color, account_name,
account_archived_at, account_currency_code, creator.user_name AS created_by_name
FROM revenues
LEFT JOIN clients ON client_id = revenue_client_id
LEFT JOIN categories ON category_id = revenue_category_id
LEFT JOIN accounts ON account_id = revenue_account_id
LEFT JOIN users AS creator ON creator.user_id = revenue_created_by
WHERE revenue_id = $revenue_id AND revenue_archived_at IS NULL AND " . incomeRevenueSql('revenue_id') . ' ' . ($scoped ? clientScopeSql('revenue_client_id') : '') . "
LIMIT 1"));
return $row ?: null;
}
/** Other income in a phrase - "Referral fee - $250.00 on 2026-10-05". Raw. */
function incomeRevenueLabel(array $row) {
$what = trim(strtok((string) ($row['revenue_description'] ?? ''), "\n"));
if ($what === '') {
$what = trim((string) ($row['category_name'] ?? '')) ?: 'Other income';
}
return $what . ' - ' . billingMoney($row['revenue_amount'], $row['revenue_currency_code']) . ' on ' . $row['revenue_date'];
}
/**
* The one path that writes other income from a form - New, Edit and Copy.
* $in: date, amount, account, category, client_id, payment_method,
* reference and description. The amount can't be nothing; the currency is
* the account's. Returns the revenue id, or 0 with $error.
*/
function incomeRevenueSave(array $in, $revenue_id = 0, &$error = '') {
global $mysqli, $session_user_id, $session_company_currency;
$error = '';
$revenue_id = intval($revenue_id);
$existing = $revenue_id ? incomeRevenueRow($revenue_id) : null;
if ($revenue_id && !$existing) {
$error = 'That income no longer exists, or is not one you can see';
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)))) {
$error = 'Enter the date it came in';
return 0;
}
$amount = billingNumberInput($in['amount'] ?? '');
if ($amount === null || $amount == 0 || abs($amount) >= 1e12) {
$error = 'Enter the amount';
return 0;
}
$accounts = paymentAccounts($existing ? $existing['revenue_account_id'] : 0);
$account_id = intval($in['account'] ?? 0);
if (!isset($accounts[$account_id])) {
$error = 'Pick the account it went into';
return 0;
}
$categories = incomeCategories($existing ? $existing['revenue_category_id'] : 0);
$category_id = intval($in['category'] ?? 0);
if (!isset($categories[$category_id])) {
$error = 'Pick a category';
return 0;
}
$client_id = intval($in['client_id'] ?? 0);
if ($client_id && !mysqli_num_rows(mysqli_query($mysqli, "SELECT client_id FROM clients WHERE client_id = $client_id " . clientScopeSql('client_id')))) {
$error = "That client isn't one you can open";
return 0;
}
$method = trim((string) ($in['payment_method'] ?? ''));
if ($method !== '' && !in_array($method, paymentMethods(), true) && !($existing && $method === (string) $existing['revenue_payment_method'])) {
$error = 'Pick how it was paid';
return 0;
}
$reference = mb_substr(trim((string) ($in['reference'] ?? '')), 0, 200);
$description = trim(str_replace("\r\n", "\n", (string) ($in['description'] ?? '')));
$currency = (string) ($accounts[$account_id]['account_currency_code'] ?: $session_company_currency);
$set = "revenue_date = '$date', revenue_amount = $amount, revenue_currency_code = '" . escapeSql($currency) . "', revenue_account_id = $account_id,
revenue_category_id = $category_id, revenue_client_id = $client_id, revenue_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
revenue_reference = '" . escapeSql($reference) . "', revenue_description = " . ($description === '' ? 'NULL' : "'" . escapeSql($description) . "'");
if ($existing) {
mysqli_query($mysqli, "UPDATE revenues SET $set WHERE revenue_id = $revenue_id");
return $revenue_id;
}
mysqli_query($mysqli, "INSERT INTO revenues SET $set, revenue_created_by = " . intval($session_user_id));
return mysqli_insert_id($mysqli);
}
/** Delete other income this agent may see - the row it deleted, or null with $error. */
function incomeRevenueDelete($revenue_id, &$error = '') {
global $mysqli;
$error = '';
$row = incomeRevenueRow($revenue_id);
if (!$row) {
$error = 'That income no longer exists, or is not one you can see';
return null;
}
mysqli_query($mysqli, "DELETE FROM revenues WHERE revenue_id = " . intval($row['revenue_id']));
return $row;
}
/* -------------------------------------------------------------- Payments */
/**
* A payment with its invoice (number, status, amount, client, category),
* account, what the invoice has been paid in all, the other payments on it
* and, for one made online, the payment provider's fee expense - raw, or
* null. Scoped to the invoice's client.
*/
function incomePaymentRow($payment_id) {
global $mysqli;
$payment_id = intval($payment_id);
if (!$payment_id) {
return null;
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT payments.*, invoice_id, invoice_prefix, invoice_number, invoice_status, invoice_amount, invoice_currency_code,
invoice_date, invoice_due, invoice_scope, invoice_client_id, client_name, category_name, category_color, invoice_category_id, account_name, account_archived_at
FROM payments
LEFT JOIN invoices ON invoice_id = payment_invoice_id
LEFT JOIN clients ON client_id = invoice_client_id
LEFT JOIN categories ON category_id = invoice_category_id
LEFT JOIN accounts ON account_id = payment_account_id
WHERE payment_id = $payment_id AND payment_archived_at IS NULL " . clientScopeSql('COALESCE(invoice_client_id, 0)') . "
LIMIT 1"));
if (!$row) {
return null;
}
$row['invoice_paid'] = $row['invoice_id'] ? invoicePaid($row['invoice_id']) : 0.0;
$row['others'] = [];
if ($row['invoice_id']) {
$sql = mysqli_query($mysqli, "SELECT payment_id, payment_date, payment_amount, payment_currency_code, payment_method FROM payments
WHERE payment_invoice_id = " . intval($row['invoice_id']) . " AND payment_id <> $payment_id AND payment_archived_at IS NULL ORDER BY payment_date ASC, payment_id ASC");
while ($other = mysqli_fetch_assoc($sql)) {
$row['others'][] = $other;
}
}
$row['fee'] = null;
if (preg_match('/^Stripe - pi_/', (string) $row['payment_reference'])) {
$row['fee'] = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT expense_id, expense_amount, expense_currency_code FROM expenses
WHERE LOCATE('" . escapeSql($row['payment_reference']) . "', expense_reference) = 1 ORDER BY expense_id ASC LIMIT 1")) ?: null;
}
return $row;
}
/** A payment in a phrase - "INV-12 - $500.00 on 2026-10-05". Raw. */
function incomePaymentLabel(array $row) {
return ($row['invoice_number'] !== null ? $row['invoice_prefix'] . $row['invoice_number'] : 'A payment') . ' - ' . billingMoney($row['payment_amount'], $row['payment_currency_code'])
. ' on ' . $row['payment_date'];
}
/* ---------------------------------------------------------------- Bulk */
/**
* The ticked rows of the Income list - "payment-12" / "revenue-7" - as
* ['payment' => ids, 'revenue' => ids]. Anything else is left out.
*/
function incomeBulkIds($refs) {
$ids = ['payment' => [], 'revenue' => []];
foreach ((array) $refs as $ref) {
if (is_string($ref) && preg_match('/^(payment|revenue)-([1-9]\d*)$/i', $ref, $m)) {
$ids[strtolower($m[1])][intval($m[2])] = intval($m[2]);
}
}
return $ids;
}

View File

@@ -23,7 +23,8 @@
* require_once "../../includes/footer.php";
*
* Money is counted the way the dashboard counts it: income is what came in -
* invoice payments, and revenues with a category; spending is expenses with a
* invoice payments, and other income that isn't a transfer, categorised or
* not (functions/income.php); spending is expenses with a
* vendor, as an expense with no vendor is the out side of a transfer between
* accounts. Anything tied to a client goes through clientScopeSql(), so an
* agent restricted to some clients only ever sees those clients' rows; the
@@ -1469,7 +1470,7 @@ function reportCategoryChartSeries(array $categories, array $grid, $months_shown
* the year and its share, a totals row, and each amount opening the list it
* came from ($list: income.php or expenses.php).
*/
function reportCategoryYearTable(array $categories, array $grid, $year, $list, $total_label) {
function reportCategoryYearTable(array $categories, array $grid, $year, $list, $total_label, $uncategorised = '') {
$columns = reportYearColumns('month');
$totals = reportGridTotals($grid);
$html = '<div class="table-responsive"><table class="table table-sm table-hover align-middle mb-0 itflow-report-table itflow-report-grid" data-report-sort>'
@@ -1487,10 +1488,10 @@ function reportCategoryYearTable(array $categories, array $grid, $year, $list, $
. (!empty($category['category_archived_at']) ? ' <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Archived</span>' : '') . '</td>';
foreach ($columns as $i => [$label, $first, $last]) {
[$dtf, $dtt] = reportColumnDates($year, $first, $last);
$url = $cat ? "/agent/$list?category=$cat&canned_date=custom&dtf=$dtf&dtt=$dtt" : '';
$url = $cat || $uncategorised !== '' ? "/agent/$list?" . ($cat ? "category=$cat" : $uncategorised) . "&canned_date=custom&dtf=$dtf&dtt=$dtt" : '';
$html .= '<td class="text-end" data-value="' . round($row['months'][$i], 2) . '">' . reportGridAmount($row['months'][$i], $url) . '</td>';
}
$url = $cat ? "/agent/$list?category=$cat&canned_date=custom&dtf=$year-01-01&dtt=$year-12-31" : '';
$url = $cat || $uncategorised !== '' ? "/agent/$list?" . ($cat ? "category=$cat" : $uncategorised) . "&canned_date=custom&dtf=$year-01-01&dtt=$year-12-31" : '';
$share = reportShare($row['total'], $totals['total'], 1);
$html .= '<td class="text-end fw-semibold" data-value="' . round($row['total'], 2) . '">' . reportGridAmount($row['total'], $url) . '</td>'
. '<td class="text-end text-body-secondary" data-value="' . ($share ?? 0) . '">' . reportPercent($share) . '</td></tr>';

View File

@@ -558,6 +558,31 @@ function globalSearchGroups($terms, $deep) {
},
];
// Income - other income by what it was or its reference, a payment by its reference (check or
// transaction number), either by the amount. The union is already in the agent's client scope.
$income_amount_match = $expense_amount > 0 ? "OR ABS(income.income_amount) = $expense_amount" : '';
$groups[] = [
'key' => 'income', 'label' => 'Income', 'icon' => 'hand-holding-usd', 'module' => 'module_financial', 'enabled' => $accounting,
'select' => 'income.*',
'from' => '(' . incomeUnionSql() . ') AS income',
'where' => "((income.income_type = 'revenue' AND income.income_description LIKE '%$like%') OR income.income_reference LIKE '%$like%' $income_amount_match)",
'scope' => null,
'order' => ($expense_amount > 0 ? "(ABS(income.income_amount) = $expense_amount) DESC, " : '') . 'income.income_date DESC, income.income_id DESC',
'list_url' => '/agent/income.php?' . http_build_query(['q' => $q]),
'item' => function ($row) {
$payment = $row['income_type'] === 'payment';
$what = trim(strtok((string) $row['income_description'], "\n"));
return [
'title' => $payment ? 'Payment on ' . ($row['invoice_number'] !== null ? $row['invoice_prefix'] . $row['invoice_number'] : 'an invoice since deleted')
: ($what !== '' ? mb_strimwidth($what, 0, 80, '...') : ($row['category_name'] ?: 'Other income')),
'subtitle' => globalSearchMoney($row['income_amount'], $row['income_currency_code']) . ' · ' . $row['income_date']
. ($row['income_reference'] ? ' · #' . $row['income_reference'] : ''),
'context' => implode(' · ', array_filter([$row['client_name'], $payment ? '' : (string) $row['category_name']])),
'url' => '/agent/income.php?open=' . $row['income_type'] . '-' . intval($row['income_id']),
];
},
];
$vendor_phone_match = $phone ? "OR REGEXP_REPLACE(vendor_phone, '[^0-9]', '') LIKE '%$phone%'" : '';
$groups[] = [
'key' => 'vendors', 'label' => 'Vendors', 'icon' => 'building', 'module' => 'module_client',