From 8d5e5091ad4f0d6ec1c63585755acef4dbd6ae67 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Fri, 16 Oct 2026 18:36:43 -0400 Subject: [PATCH] Expenses stage 3: billable expenses and pass-through costs - mark an expense for a client billable with a markup (default in Admin > Settings > Invoice), expenses to bill sit beside the time in Unbilled Time and go on a new or draft invoice with the tickets as a line each at a price that can be changed, the invoice gets an Expenses card with cost against billed and the margin plus an Add Expenses window, taking one off or deleting its line or invoice makes it to bill again (paid invoices keep it, cancelled ones keep the line), the quick look and list link billed expenses to their invoice with To bill and Billed pills and Bulk Set Billable, recurring expenses can be billed on each time or covered by one of the client's recurring invoices with a Costs card showing the monthly margin, expenses to bill counted in the menu, dashboard and client overview, export Billing and Billed On columns, demo data with recent client expenses to bill, database 3.0.1 --- CHANGELOG.md | 27 +- admin/database_updates/3.0.1.php | 28 + admin/post/demo_data_model.php | 3 + admin/post/settings_invoice.php | 9 +- admin/settings_invoice.php | 16 + agent/client_overview.php | 9 +- agent/expenses.php | 12 +- agent/includes/client_side_nav.php | 6 +- agent/includes/get_side_nav_counts.php | 3 + agent/includes/inc_all_client.php | 2 + agent/includes/side_nav.php | 6 +- agent/invoice.php | 58 +- agent/modals/expense/expense.php | 50 +- agent/modals/expense/expense_bulk_edit.php | 35 +- agent/modals/expense/expense_form.php | 83 ++- agent/modals/invoice/invoice_add_expenses.php | 157 ++++++ .../recurring_expense/recurring_expense.php | 24 +- .../recurring_expense_add.php | 8 +- .../recurring_expense_form.php | 86 ++- agent/post/billing.php | 93 +++- agent/post/expense.php | 66 ++- agent/post/invoice.php | 46 ++ agent/post/recurring_invoice.php | 3 + agent/recurring_expenses.php | 8 +- agent/recurring_invoice.php | 51 +- agent/unbilled_time.php | 223 ++++++-- css/itflow_custom.css | 18 + db.sql | 11 +- functions/billing.php | 3 +- functions/client_overview.php | 16 +- functions/dashboard.php | 10 + functions/expenses.php | 512 +++++++++++++++++- functions/export.php | 2 + js/unbilled_time.js | 84 ++- 34 files changed, 1649 insertions(+), 119 deletions(-) create mode 100644 admin/database_updates/3.0.1.php create mode 100644 agent/modals/invoice/invoice_add_expenses.php diff --git a/CHANGELOG.md b/CHANGELOG.md index aafc921b6..58ca610d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.11 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 3.0.0) 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.1) in the same pass. Nothing else is required. -This is a big release, with twenty-one database steps in one go, so take a backup before you update. +This is a big release, with twenty-two 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: @@ -23,7 +23,7 @@ Payment reminders keep the schedule they had: 1 and 30 days late, then every 30 Expenses already entered take who entered them from the audit log, where it has a record of it. Expense receipts are no longer opened straight from the uploads folder - see Breaking Changes, Expenses. -Recurring expenses keep their next date and from then on run on that day of the month - monthly ones stay monthly and yearly ones yearly. Look over their next dates once after the update (see Breaking Changes, Expenses). The expenses they recorded before are linked to them, matched on the vendor, category, client and description. +Recurring expenses keep their next date and from then on run on that day of the month - monthly ones stay monthly and yearly ones yearly. Look over their next dates once after the update (see Breaking Changes, Expenses). The expenses they recorded before are linked to them, matched on the vendor, category, client and description. No expense or recurring expense becomes billable to a client by itself - they stay your cost until you mark them (see New Features, Expenses). 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. @@ -86,6 +86,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Recurring expenses run on the day of the month of their next date, the way recurring invoices do. The nightly run used to move a monthly one a month on from the day it happened to run, and a new one started in the month picked in the form even when it was monthly. Check the next dates on the Recurring Expenses page after the update. - A recurring expense the nightly run missed by up to 7 nights is recorded the next night, dated the day it was due. One further behind waits for you to Record Now or Move On. The notification every night for each recurring expense with a date in the past is replaced by one notification, on the day it falls too far behind. - Deleting a recurring expense needs full Financial access, the same as deleting an expense. It used to need write access. + - Unbilled Time also lists expenses to bill for agents with Financial access, and its count in the menu adds them. For those agents it shows in the menu even with ticketing turned off. - 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: @@ -254,6 +255,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - One client's tickets, each with its hours to bill filled in and ready to change before it goes on. Tick the ones to bill and make an invoice or add them to one of the client's drafts, with a line for each ticket or one for all of them. The total follows as you change the hours, rate or tax. - Not billable writes off ticked tickets so they leave the list. Each one's history says so. - Two agents billing the same tickets at once can't both bill them. + - Expenses to bill on to clients sit beside the time and go on the same invoice - see Expenses, Billing expenses on. - Billing Time in Admin > Settings > Invoice: round a ticket's time to 6, 12, 15 or 30 minutes or the hour, to the nearest step or always up, with a minimum a ticket bills, and the name of the invoice line. It starts as before: the nearest 15 minutes, no minimum. - The ticket's Invoice window is redone. It shows the time logged by each agent and the hours that bills, with the client's rate (or the default rate) filled in, and it can add to one of the client's drafts. An open ticket can still be billed from here, with a warning that later time won't be. - Add Tickets on an invoice bills their time: tick the tickets, change their hours, and they go on as lines at the rate. @@ -349,6 +351,15 @@ If you are coming from 26.08 or earlier, the database update still has to be run - The nightly run tells the team about each expense it records, opening it. - The dashboard's recurring expenses, its cash flow forecast and the Expenses, Recurring Revenue and Spend by Vendor reports count quarterly ones and stop at end dates. The vendor page's Recurring tab opens the quick look. - The demo data's standing costs are recurring expenses on their own days, with the insurance quarterly, linked to the history they recorded. + - **Billing expenses on** to clients - pass-through costs such as hardware, licenses or a courier: + - Mark an expense for a client billable in New Expense or Edit, with a markup. The window shows what it will bill as you type. The default markup is set in Admin > Settings > Invoice, under Billable Expenses. + - It waits in **Unbilled Time** beside the time. One client's page lists their expenses to bill with the cost, markup, the price to change and the margin, and Make Invoice puts the ticked tickets and expenses on one new draft, or one of their drafts. Not billable takes the ticked ones off the list. The all-clients page has an Expenses column, includes clients with only expenses waiting, and bills each client's time and expenses together. + - Each goes on the invoice as a line of its own, named from the first line of its description, with the vendor, date and reference under it. A refund against it comes off the price first. + - The invoice has an **Expenses** card: each expense's cost against what it billed, the margin, and the totals. Add opens Add Expenses with the client's waiting expenses and their prices. Taking one off removes its line, and so does deleting the line or the invoice - the expense is then to bill again. Once the invoice is paid it stays. A cancelled invoice keeps its line, and the expense can still be taken off to bill on a new one. + - The expense's quick look says it is to bill, at what price and markup, or which invoice it is billed on with the margin, with Take off Invoice. The list has To bill and Billed pills, a mark on each row linking to Unbilled Time or the invoice, and Bulk Set Billable. A billed expense can't be moved to another client until it is taken off. + - A client's **recurring expense** can be billed on each time it records one, with a markup, or be **covered by** one of the client's recurring invoices. A covered one isn't billed by itself: the recurring invoice's new **Costs** card lists what it covers, what it bills a month before tax against what they cost a month, and the margin left, with Add to set up another one it covers. The recurring expenses list and quick look show which it is. + - Expenses to bill show on the dashboard and the client overview's attention list, and the client overview's Not yet invoiced includes them. The export has Billing and Billed On columns. + - The demo data's latest client expenses are to bill, at 15%. - **Tickets** - The ticket list has views for Open, Mine, Unassigned, Needs reply, Waiting, Overdue, Scheduled, Closed and All. - Each row shows whose move it is (yours or the client's) along with SLA and due badges, and status, priority and agent change right in the row. @@ -605,6 +616,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - 2.9.8: `settings.config_invoice_reminder_days` ('1,30' - days from the due date, negative before it), `config_invoice_reminder_repeat` (30), `config_statement_monthly` (0), `config_statement_day` (1) and `config_billing_email_attach_pdf` (1), and `clients.client_reminders` (1). - 2.9.9: `expenses.expense_created_by` (0 for cron and payment providers), backfilled from the audit log's Expense Create entries, and `expense_refund_of_id`. - 3.0.0 (after 2.9.9, the way 2.0.0 followed 1.9.9): `recurring_expenses.recurring_expense_frequency` becomes `varchar(10)` (`month`, `quarter` or `year`, from 1 and 2), with `recurring_expense_anchor_day` (backfilled from the next date) and `recurring_expense_end_date`. `recurring_expense_day` and `recurring_expense_month` are dropped. `expenses.expense_recurring_expense_id`, backfilled by vendor, category, client and description from the day each recurring expense was set up. + - 3.0.1: `expenses.expense_billable` (0), `expense_markup` (`decimal(7,2)`, 0.00), `expense_invoice_id` (keyed) and `expense_invoice_item_id`. `recurring_expenses.recurring_expense_billable` (0), `recurring_expense_markup` and `recurring_expense_recurring_invoice_id`. `settings.config_expense_markup` (0.00). - 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`. @@ -764,6 +776,15 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Cron: the recurring expense block in `cron/nightly_tasks.php` records active ones due from `RECURRING_EXPENSE_GRACE_DAYS` ago up to today, passing each next date as `$run`. It sends an `Expense Created` notification per expense, linking `expenses.php?open=`, and an `Expense` notification the day one falls one day past the grace. The nightly notification for every past next date is gone. - `dashboardExpectedExpenses()` walks each one's runs with `recurringExpenseRunsUntil()`. - Seeds: `demoBuildCompanyFinancials()` gives its recurring expenses `recurring_expense_anchor_day` and a next date one period after the last of their history, and links that history. + - Billing expenses on, in the same file: + - `expenseUnbilledSql()` is the one definition of an expense to bill: billable, on no invoice, for a client, with a vendor and a positive amount, not archived. `expenseUnbilled($client_id, $ids)` reads them in the agent's client scope with `cost` (less refunds - fully refunded ones are left out), `price` (`expenseBillPrice($cost, $markup)`) and `waiting`. Also `expenseUnbilledByClient()`, `expenseUnbilledCount($client_id)` (count and value, in SQL, for the menus, dashboard and client overview), `expenseMarkupDefault()` and `expenseMarginText()`. + - `expenseBillInvoice($client_id, $prices, $opts, &$error)` is the one path that bills expenses. It validates the prices and tax, uses one of the client's invoices whose lines can change or makes a draft with `billingInvoiceCreate()`, claims the expenses with a conditional `UPDATE`, adds a line each through `billingItemSave()` (`expenseBillLine()` names it), sets `expense_invoice_item_id`, and writes invoice history and the audit log. `expenseBillWithTime($client_id, $hours, $prices, $opts, &$error)` bills tickets with `billingTimeInvoice()` then expenses on the same invoice, for Unbilled Time. + - `expenseUnbill($id, &$error)` takes one off - its line through `billingItemDelete()`, or only the link on a cancelled invoice - refusing on a paid or non-billable one (`expenseCanUnbill($status)`). `billingItemDelete()` frees the expense billed on a line it deletes, and `delete_invoice` frees the invoice's expenses. `expenseWriteOff()` sets `expense_billable = 0`. `expenseOnInvoice($invoice_id)` lists an invoice's with `cost` and `billed`. `expenseUnbilledMerge($clients, $client_id)` adds expenses to `billingUnbilledByClient()`'s clients. + - `expenseSave()` takes `billable` and `markup` (0 to 1000, the default when blank) and refuses a new client while billed. `expenseRow()` adds the invoice's number and status and `billed_subtotal`. `expenseShows()` adds `to_bill` and `billed`. + - Recurring: `recurringExpenseSave()` takes `billing` (`bill`, `covered` or empty, with a client), `markup` and `recurring_invoice_id`, which must be one of the client's from `recurringExpenseCoverOptions()`. `recurringExpenseRecord()` makes the expense billable with the markup when the recurring one is billed on. `recurringExpenseRow()` adds the covering recurring invoice. `recurringExpensesCovering($recurring_invoice_id)` and `recurringInvoiceCosts($recurring_invoice_id)` (revenue a month before tax, the running costs, margin and percent). `delete_recurring_invoice` clears `recurring_expense_recurring_invoice_id`. + - Handlers: GET `expense_unbill` (Financial and Sales at 2) and POST `invoice_add_expenses` (`invoice_id`, `expense_ids[]`, `expense_price[id]`, `tax_id`). `unbilled_invoice` and `unbilled_write_off` take `expense_ids[]` and `expense_price[id]` too (Financial at 2 when they are posted), and `unbilled_invoice_clients` bills each client's expenses for agents with Financial at 2. `bulk_edit_expenses` takes `field=billable` (`value` yes with `markup`, or no). `edit_invoice_settings` saves `config_expense_markup`. The export adds `expense_billing_display` and `expense_billed_on`. + - New window `agent/modals/invoice/invoice_add_expenses.php?invoice_id=`. `recurring_expense_add.php` takes `?recurring_invoice_id=`. `agent/invoice.php` has the Expenses card and `agent/recurring_invoice.php` the Costs card for agents with Financial access. `js/unbilled_time.js` counts `[data-unbilled-expense-row]` rows with their `[data-unbilled-expense-pick]` and `[data-unbilled-expense-price]`. CSS: `.itflow-unbilled-price`. + - `dashboardAttention()` and `clientOverviewAttention()` add Expenses to bill, and `clientOverviewMoney()` adds `unbilled_expenses` and `unbilled_expense_value`. `get_side_nav_counts.php` and `inc_all_client.php` set `$num_unbilled_expenses`. - The billing helpers (`billingTimeInvoice()`, `quoteConvert()`, `recurringInvoiceGenerate()` and the rest) take the agent's name as plain text. Their handlers now pass `stripslashes($session_name)`, so a name with an apostrophe no longer shows a backslash in history and the audit log. - Sidebar brand: `agent/css/sidebar_brand_fix.css` and `agent/js/sidebar_brand_fix.js` from 26.10 are replaced by CSS in `css/itflow_custom.css`. `includes/load_company_settings.php` now sets `$session_company_logo`. - `alertMessageHtml()` no longer double-encodes, and save messages built from `escapeSql()` values use `stripslashes()` at the flash. diff --git a/admin/database_updates/3.0.1.php b/admin/database_updates/3.0.1.php new file mode 100644 index 000000000..87c2d3f8f --- /dev/null +++ b/admin/database_updates/3.0.1.php @@ -0,0 +1,28 @@ + $client_id, 'expense_category_id' => demoCategoryId($mysqli, $expense[2], 'Expense'), 'expense_account_id' => $bank_account_id, + // The latest ones are still to bill on to the client, with a markup + 'expense_billable' => $month <= 2 ? 1 : 0, + 'expense_markup' => $month <= 2 ? '15.00' : '0.00', 'expense_created_at' => demoMonthDateTime($month, 14, 16, 45), ]); $counts['billing']++; diff --git a/admin/post/settings_invoice.php b/admin/post/settings_invoice.php index b0edd6516..1f5515481 100644 --- a/admin/post/settings_invoice.php +++ b/admin/post/settings_invoice.php @@ -27,6 +27,13 @@ if (isset($_POST['edit_invoice_settings'])) { $config_time_item_name = trim((string) ($_POST['config_time_item_name'] ?? '')); $config_time_item_name = escapeSql(mb_substr($config_time_item_name !== '' ? $config_time_item_name : 'Support [Hourly]', 0, 200)); + // Billable expenses - the markup they start with, a percent + $config_expense_markup = billingNumberInput(str_replace('%', '', (string) ($_POST['config_expense_markup'] ?? '0'))); + if ($config_expense_markup === null || $config_expense_markup < 0 || $config_expense_markup > 1000) { + flashAlert('The default markup is a percent, from 0 to 1000', 'error'); + redirect(); + } + // Reminders and statements - see billingReminderRules(). Days before the due date // are stored negative, the due date itself as 0, days late positive. $config_send_invoice_reminders = intval(!empty($_POST['config_send_invoice_reminders'])); @@ -45,7 +52,7 @@ if (isset($_POST['edit_invoice_settings'])) { config_invoice_reminder_repeat = $config_invoice_reminder_repeat, config_statement_monthly = $config_statement_monthly, config_statement_day = $config_statement_day, config_billing_email_attach_pdf = $config_billing_email_attach_pdf WHERE company_id = 1"); - mysqli_query($mysqli,"UPDATE settings SET config_time_increment = $config_time_increment, config_time_rounding = '$config_time_rounding', config_time_minimum = $config_time_minimum, config_time_item_name = '$config_time_item_name' WHERE company_id = 1"); + mysqli_query($mysqli,"UPDATE settings SET config_time_increment = $config_time_increment, config_time_rounding = '$config_time_rounding', config_time_minimum = $config_time_minimum, config_time_item_name = '$config_time_item_name', config_expense_markup = $config_expense_markup WHERE company_id = 1"); mysqli_query($mysqli,"UPDATE settings SET config_invoice_prefix = '$config_invoice_prefix', config_invoice_next_number = $config_invoice_next_number, config_invoice_footer = '$config_invoice_footer', config_invoice_show_tax_id = $config_invoice_show_tax_id, config_invoice_late_fee_enable = $config_invoice_late_fee_enable, config_invoice_late_fee_percent = $config_invoice_late_fee_percent, config_invoice_paid_notification_email = '$config_invoice_paid_notification_email', config_recurring_invoice_prefix = '$config_recurring_invoice_prefix', config_recurring_invoice_next_number = $config_recurring_invoice_next_number WHERE company_id = 1"); diff --git a/admin/settings_invoice.php b/admin/settings_invoice.php index fcb33d765..d525886d5 100644 --- a/admin/settings_invoice.php +++ b/admin/settings_invoice.php @@ -264,6 +264,22 @@ require_once "includes/inc_all_admin.php";
+

Billable Expenses

+

An expense for a client can be billed on to them - it waits in Unbilled Time and goes on their invoice at what it cost, less any refund, plus a markup. A recurring expense can be billed on each time it records one.

+ +
+
+ +
+ + +
+ What a billable expense starts with - 0 bills it at cost. Each expense can have its own. +
+
+ +
+ diff --git a/agent/client_overview.php b/agent/client_overview.php index a39f40ad2..7e9daa7d7 100644 --- a/agent/client_overview.php +++ b/agent/client_overview.php @@ -504,11 +504,14 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code, /mo recurring invoice - + Not yet invoiced - - ticket + + + ticket +
diff --git a/agent/expenses.php b/agent/expenses.php index 2d823b611..e6c423a78 100644 --- a/agent/expenses.php +++ b/agent/expenses.php @@ -27,6 +27,7 @@ enforceUserPermission('module_financial'); $can_edit = lookupUserPermission('module_financial') >= 2; $can_delete = lookupUserPermission('module_financial') >= 3; +$can_sales = lookupUserPermission('module_sales') >= 1; $vendor_filter = intval($_GET['vendor'] ?? 0); $category_filter = intval($_GET['category'] ?? 0); @@ -51,8 +52,10 @@ $where = expenseFiltersSql($filter_src); $show_query = $shows[$show]['where'] ? "AND {$shows[$show]['where']}" : ''; $joins = expenseJoinsSql(); -$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS expenses.*, vendor_name, vendor_archived_at, category_name, category_color, account_name, client_name, user_name +$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS expenses.*, vendor_name, vendor_archived_at, category_name, category_color, account_name, client_name, user_name, + invoice_prefix, invoice_number FROM expenses $joins + LEFT JOIN invoices ON invoice_id = expense_invoice_id WHERE $where $show_query ORDER BY {$sortable_columns[$sort]} $order, expense_id DESC LIMIT $record_from, $record_to"); @@ -228,6 +231,7 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la Set Account Set Payment Method Set Client + Set Billable Delete @@ -342,6 +346,12 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
+ +
Billed Billed
+ 0) { ?> +
To billTo bill
+ - diff --git a/agent/includes/client_side_nav.php b/agent/includes/client_side_nav.php index c5d3010a8..be6ceafeb 100644 --- a/agent/includes/client_side_nav.php +++ b/agent/includes/client_side_nav.php @@ -344,14 +344,14 @@ - + = 1) { ?> - + = 1) { ?>
+ +
+
+

Expenses

+ + + +
+ +
+ +
+
+
+ +
+
+ + + + + +
+
+ Cost → line gone' ?> + +
+
+ +
+ + +
expense to bill to could go on this invoice.
+ +
+ +

History

diff --git a/agent/modals/expense/expense.php b/agent/modals/expense/expense.php index 1be97b42c..e510bb488 100644 --- a/agent/modals/expense/expense.php +++ b/agent/modals/expense/expense.php @@ -4,8 +4,9 @@ * An expense's quick look - the receipt (shown right in the window when it * is a photo or a PDF, or attached here when there isn't one), who it was * paid to and for what, the account and how it was paid, the client, who - * entered it, the refund it is or the refunds against it, and the stock - * deliveries it paid for. Opened from the expenses list, the vendor's page, + * entered it, the refund it is or the refunds against it, billing it on to + * the client (the invoice it is on, with the margin, or what it will bill + * at), and the stock deliveries it paid for. Opened from the expenses list, the vendor's page, * Transactions and search (expenses.php?open=). */ @@ -30,6 +31,14 @@ $receipt_kind = $row['expense_receipt'] && expenseReceiptPath($row['expense_rece $receipt_missing = $row['expense_receipt'] && $receipt_kind === '' && expenseReceiptPath($row['expense_receipt']) === ''; $receipt_url = "expense_receipt.php?expense_id=$expense_id"; +// Billing it on to the client +$can_sales = lookupUserPermission('module_sales'); +$billed_on = intval($row['expense_invoice_id']); +$cost = round($amount - floatval($row['refunded_amount']), 2); +$billable = !$billed_on && intval($row['expense_billable']) && $client_id && $amount > 0 && !$is_transfer; +$bill_price = expenseBillPrice($cost, $row['expense_markup']); +$can_unbill = $billed_on && $can_edit && expenseCanUnbill($row['invoice_status']); + // Refunds against it, and the stock it paid for $refunds = []; $sql = mysqli_query($mysqli, "SELECT expense_id, expense_date, expense_amount, expense_description FROM expenses WHERE expense_refund_of_id = $expense_id ORDER BY expense_date ASC, expense_id ASC"); @@ -143,6 +152,37 @@ ob_start(); : 'a recurring expense since deleted' ?>
+ +
+ + + + Billed on an invoice since deleted + + Billed on ' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) . '' : escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?>(cancelled)' : '' ?> + + at + · + + + +
+ +
+ + + + Billable, but refunded in full + + To bill at + · % markup + + · Unbilled Time + + + +
+
@@ -197,9 +237,13 @@ ob_start();
+ + Take off Invoice + Delete + data-confirm-text=" goes for good.">Delete
diff --git a/agent/modals/expense/expense_bulk_edit.php b/agent/modals/expense/expense_bulk_edit.php index 60d37aec5..6449af198 100644 --- a/agent/modals/expense/expense_bulk_edit.php +++ b/agent/modals/expense/expense_bulk_edit.php @@ -1,8 +1,10 @@ ['label' => 'Account', 'icon' => 'fa-piggy-bank'], 'client' => ['label' => 'Client', 'icon' => 'fa-user'], 'method' => ['label' => 'Payment Method', 'icon' => 'fa-credit-card'], + 'billable' => ['label' => 'Billable', 'icon' => 'fa-file-invoice-dollar'], ]; if (!isset($fields[$field])) { echo json_encode(['error' => 'Pick what to set from the Bulk Action menu.']); @@ -69,6 +72,11 @@ ob_start(); + + + +
+ +
+ + +
+
+
Only those for a client are billed on, and not ones already on an invoice - those stay as they are.
+ + + +
> +
+ + +
+ Billed on . + Changing the amount here doesn't change the invoice - take it off the invoice to bill it again. +
+ + + +
+ data-expense-billable> + +
+
+ + + markup +
+
Bills - it waits in Unbilled Time and on their invoices until it goes on one.
+ +
+
+ +
@@ -226,6 +261,52 @@ $form_receipt = $form_edit ? $form_value('expense_receipt') : '';
+ + + + + += 1; +$covered_by = intval($row['recurring_expense_recurring_invoice_id']); +$cover = $covered_by && $row['recurring_invoice_number'] !== null ? recurringInvoiceCosts($covered_by) : null; +$markup = floatval($row['recurring_expense_markup']); $post_url = function ($action, $extra = '') use ($id) { return "post.php?$action=$id$extra&csrf_token=" . $_SESSION['csrf_token']; }; @@ -114,6 +120,22 @@ ob_start(); Not for a client
+ +
+ + + Covered by ' . escapeHtml($cover_number) . '' : escapeHtml($cover_number) ?> + · a month before tax + + Covered by a recurring invoice since deleted + + Billed on each time at · % markup + + Our cost - not billed on + +
+
recorded this year · a year at this amount diff --git a/agent/modals/recurring_expense/recurring_expense_add.php b/agent/modals/recurring_expense/recurring_expense_add.php index 9b48b1355..ddb95d662 100644 --- a/agent/modals/recurring_expense/recurring_expense_add.php +++ b/agent/modals/recurring_expense/recurring_expense_add.php @@ -4,7 +4,8 @@ * New Recurring Expense - who it is paid to, how much, how often and from * when (and until when, for a lease or financing), what for, from which * account and how. ?vendor_id= starts it with one of our vendors (from the - * vendor's page), ?client_id= with a client. + * vendor's page), ?client_id= with a client, ?recurring_invoice_id= with + * a client and covered by that recurring invoice (from its Costs card). */ require_once '../../../includes/modal_header.php'; @@ -14,6 +15,11 @@ enforceUserPermission('module_financial', 2); $form_row = null; $form_vendor_id = intval($_GET['vendor_id'] ?? 0); $form_client_id = intval($_GET['client_id'] ?? 0); +$form_recurring_invoice_id = intval($_GET['recurring_invoice_id'] ?? 0); +if ($form_recurring_invoice_id) { + // From a recurring invoice's Costs card: for its client, covered by it + $form_client_id = intval(getFieldById('recurring_invoices', $form_recurring_invoice_id, 'recurring_invoice_client_id')); +} if ($form_client_id) { $client_id = $form_client_id; enforceClientAccess(); diff --git a/agent/modals/recurring_expense/recurring_expense_form.php b/agent/modals/recurring_expense/recurring_expense_form.php index 274766a44..0ffbe15be 100644 --- a/agent/modals/recurring_expense/recurring_expense_form.php +++ b/agent/modals/recurring_expense/recurring_expense_form.php @@ -54,6 +54,22 @@ while ($row = mysqli_fetch_assoc($sql)) { $form_clients[] = $row; } +// Billed on to the client each time, or covered by one of their recurring invoices +$form_covered_by = $form_edit ? intval($form_row['recurring_expense_recurring_invoice_id']) : intval($form_recurring_invoice_id ?? 0); +$form_billing = $form_covered_by ? 'covered' : ($form_edit && intval($form_row['recurring_expense_billable']) ? 'bill' : ''); +$form_markup = $form_edit ? floatval($form_row['recurring_expense_markup']) : expenseMarkupDefault(); +$form_covers = []; +$sql = mysqli_query($mysqli, "SELECT recurring_invoice_id, recurring_invoice_prefix, recurring_invoice_number, recurring_invoice_scope, recurring_invoice_amount, + recurring_invoice_frequency, recurring_invoice_currency_code, recurring_invoice_client_id + FROM recurring_invoices + WHERE (recurring_invoice_archived_at IS NULL OR recurring_invoice_id = $form_covered_by) " . clientScopeSql('recurring_invoice_client_id') . " + ORDER BY recurring_invoice_status DESC, recurring_invoice_number ASC"); +while ($row = mysqli_fetch_assoc($sql)) { + $form_covers[intval($row['recurring_invoice_client_id'])][] = [intval($row['recurring_invoice_id']), + billingNumber('recurring', $row) . (trim((string) $row['recurring_invoice_scope']) !== '' ? ' - ' . $row['recurring_invoice_scope'] : '') + . ' (' . billingMoney(recurringInvoiceMonthly($row['recurring_invoice_amount'], $row['recurring_invoice_frequency']), $row['recurring_invoice_currency_code']) . ' a month)']; +} + ?>
@@ -134,7 +150,7 @@ while ($row = mysqli_fetch_assoc($sql)) {
- @@ -143,6 +159,37 @@ while ($row = mysqli_fetch_assoc($sql)) {
+
> +
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+
+
+
@@ -231,6 +278,43 @@ while ($row = mysqli_fetch_assoc($sql)) { }); update(); + // For a client: billed on each time, or covered by one of their recurring invoices + var covers = ; + var client = root.querySelector('[data-recurring-client]'); + var billingBox = root.querySelector('[data-recurring-billing]'); + var mode = root.querySelector('[data-recurring-billing-mode]'); + var cover = root.querySelector('[data-recurring-cover]'); + var billingNote = root.querySelector('[data-recurring-billing-note]'); + function billing() { + var options = covers[client.value] || []; + billingBox.hidden = !client.value || client.value === '0'; + var selected = cover.value || cover.getAttribute('data-selected'); + cover.innerHTML = ''; + options.forEach(function (o) { + var option = document.createElement('option'); + option.value = o[0]; + option.textContent = o[1]; + option.selected = String(o[0]) === String(selected); + cover.appendChild(option); + }); + mode.querySelector('option[value="covered"]').disabled = !options.length; + if (mode.value === 'covered' && !options.length) { + mode.value = ''; + } + root.querySelectorAll('[data-recurring-billing-for]').forEach(function (el) { + el.hidden = el.getAttribute('data-recurring-billing-for') !== mode.value; + el.querySelectorAll('input, select').forEach(function (input) { + input.disabled = el.hidden; + }); + }); + billingNote.textContent = mode.value === 'bill' ? 'Each one it records waits in Unbilled Time to go on their next invoice, with the markup.' + : mode.value === 'covered' ? 'Not billed on by itself - the recurring invoice shows it as a cost against what it bills, with the margin.' + : (options.length ? 'Filed against them as a cost. It can also be shown against one of their recurring invoices.' : 'Filed against them as a cost - they have no recurring invoice to cover it.'); + } + client.addEventListener('change', billing); + mode.addEventListener('change', billing); + billing(); + // Picking a vendor fills in what the last expense with them used, unless changed by hand var defaults = ; diff --git a/agent/post/billing.php b/agent/post/billing.php index 0c8151853..d851c400d 100644 --- a/agent/post/billing.php +++ b/agent/post/billing.php @@ -56,6 +56,36 @@ function unbilledResultText(array $result) { return $text; } +/** What billing tickets and expenses together did, for the flash - the time's text, then the expenses'. */ +function unbilledBothText(array $result, $currency) { + $parts = []; + if ($result['time']) { + $parts[] = unbilledResultText($result['time']); + } + if ($result['expenses']) { + $e = $result['expenses']; + $parts[] = ($result['time'] ? '' : '' . escapeHtml($e['number']) . ': ') . '' . $e['expenses'] . ' expense' . ($e['expenses'] === 1 ? '' : 's') . ' billed - ' + . escapeHtml(billingMoney($e['amount'], $currency)) . ' on ' . escapeHtml(billingMoney($e['cost'], $currency)) . ' of cost'; + } + $text = implode('. ', $parts); + if ($result['error'] !== '') { + $text .= '. Not billed: ' . escapeHtml($result['error']); + } + return $text; +} + +/** The ticked expenses and their prices from Unbilled Time - expense id => price; empty unless the agent can bill them. */ +function unbilledPostPrices() { + $prices = []; + foreach (array_unique(array_filter(array_map('intval', (array) ($_POST['expense_ids'] ?? [])))) as $expense_id) { + $prices[$expense_id] = $_POST['expense_price'][$expense_id] ?? null; + } + if ($prices) { + enforceUserPermission('module_financial', 2); + } + return $prices; +} + /** The audit log's name for each kind. */ function billingAuditType($type) { return ['invoice' => 'Invoice', 'quote' => 'Quote', 'recurring' => 'Recurring Invoice'][$type] ?? 'Invoice'; @@ -216,8 +246,9 @@ if (isset($_GET['recurring_invoice_sync'])) { } /* - * Unbilled Time, one client: bill the ticked tickets at the hours typed, on - * a new draft or one of the client's drafts. + * Unbilled Time, one client: bill the ticked tickets at the hours typed, and + * the ticked expenses at the prices typed, on a new draft or one of the + * client's drafts. */ if (isset($_POST['unbilled_invoice'])) { @@ -229,10 +260,11 @@ if (isset($_POST['unbilled_invoice'])) { enforceClientAccess(); $hours = []; - foreach (array_unique(array_map('intval', (array) ($_POST['ticket_ids'] ?? []))) as $ticket_id) { + foreach (array_unique(array_filter(array_map('intval', (array) ($_POST['ticket_ids'] ?? [])))) as $ticket_id) { $hours[$ticket_id] = $_POST['hours'][$ticket_id] ?? null; } - $result = billingTimeInvoice($client_id, $hours, [ + $prices = unbilledPostPrices(); + $result = expenseBillWithTime($client_id, $hours, $prices, [ 'invoice_id' => intval($_POST['invoice_id'] ?? 0), 'date' => (string) ($_POST['date'] ?? ''), 'category_id' => intval($_POST['category'] ?? 0), @@ -248,15 +280,16 @@ if (isset($_POST['unbilled_invoice'])) { redirect(); } - flashAlert(unbilledResultText($result)); + flashAlert(unbilledBothText($result, $session_company_currency), $result['error'] !== '' ? 'warning' : 'success'); redirect("invoice.php?invoice_id={$result['invoice_id']}"); } /* * Unbilled Time, every client: bill each ticked client's unbilled tickets at - * the hours their time comes to - on a new draft each, or each one's newest - * draft when it has one. + * the hours their time comes to, and their expenses to bill at cost with + * the markup - on a new draft each, or each one's newest draft when it has + * one. Expenses only for agents who can bill them. */ if (isset($_POST['unbilled_invoice_clients'])) { @@ -265,7 +298,9 @@ if (isset($_POST['unbilled_invoice_clients'])) { enforceUserPermission('module_sales', 2); $use_draft = ($_POST['target'] ?? '') === 'draft'; - $by_client = billingUnbilledByClient(); + $with_expenses = lookupUserPermission('module_financial') >= 2; + $by_client = intval($config_module_enable_ticketing) === 1 ? billingUnbilledByClient() : []; + $by_client = $with_expenses ? expenseUnbilledMerge($by_client) : $by_client; $made = []; $failed = []; foreach (array_unique(array_map('intval', (array) ($_POST['client_ids'] ?? []))) as $bill_client_id) { @@ -273,7 +308,7 @@ if (isset($_POST['unbilled_invoice_clients'])) { continue; } $c = $by_client[$bill_client_id]; - $result = billingTimeInvoice($bill_client_id, array_fill_keys(array_keys($c['tickets']), null), [ + $result = expenseBillWithTime($bill_client_id, array_fill_keys(array_keys($c['tickets']), null), array_fill_keys(array_keys($c['expenses'] ?? []), null), [ 'invoice_id' => $use_draft && $c['drafts'] ? intval(array_key_first($c['drafts'])) : 0, 'date' => (string) ($_POST['date'] ?? ''), 'category_id' => intval($_POST['category'] ?? 0), @@ -285,6 +320,9 @@ if (isset($_POST['unbilled_invoice_clients'])) { ], $error); if ($result) { $made[] = $result; + if ($result['error'] !== '') { + $failed[] = $c['client_name'] . ': ' . $result['error']; + } } else { $failed[] = $c['client_name'] . ': ' . $error; } @@ -295,17 +333,25 @@ if (isset($_POST['unbilled_invoice_clients'])) { redirect('unbilled_time.php'); } - $tickets = array_sum(array_map(function ($r) { return count($r['tickets']); }, $made)); - $hours = array_sum(array_column($made, 'hours')); + $tickets = array_sum(array_map(function ($r) { return $r['time'] ? count($r['time']['tickets']) : 0; }, $made)); + $hours = array_sum(array_map(function ($r) { return $r['time'] ? $r['time']['hours'] : 0; }, $made)); + $expenses = array_sum(array_map(function ($r) { return $r['expenses'] ? $r['expenses']['expenses'] : 0; }, $made)); $numbers = array_column($made, 'number'); + $what = []; + if ($tickets) { + $what[] = $tickets . ' ticket' . ($tickets === 1 ? '' : 's') . ', ' . billingQuantity($hours) . ' h'; + } + if ($expenses) { + $what[] = $expenses . ' expense' . ($expenses === 1 ? '' : 's'); + } flashAlert('' . count($made) . ' invoice' . (count($made) === 1 ? '' : 's') . ' ' . (array_filter(array_column($made, 'new')) ? 'made or added to' : 'added to') . ' - ' - . $tickets . ' ticket' . ($tickets === 1 ? '' : 's') . ', ' . billingQuantity($hours) . ' h: ' . escapeHtml(implode(', ', array_slice($numbers, 0, 12)) . (count($numbers) > 12 ? ' and more' : '')) + . implode(' and ', $what) . ': ' . escapeHtml(implode(', ', array_slice($numbers, 0, 12)) . (count($numbers) > 12 ? ' and more' : '')) . ($failed ? '. Not billed: ' . escapeHtml(implode(' ', $failed)) : ''), $failed ? 'warning' : 'success'); redirect('invoices.php?status=Draft'); } -/* Unbilled Time: the ticked tickets aren't billable after all - written off. */ +/* Unbilled Time: the ticked tickets and expenses aren't billable after all - written off. */ if (isset($_POST['unbilled_write_off'])) { validateCSRFToken(); @@ -315,14 +361,25 @@ if (isset($_POST['unbilled_write_off'])) { $client_id = intval($_POST['client_id'] ?? 0); enforceClientAccess(); - $done = billingTimeWriteOff($client_id, array_map('intval', (array) ($_POST['ticket_ids'] ?? [])), stripslashes($session_name)); - if (!$done) { - flashAlert('Nothing changed - tick the tickets that are not billable.', 'error'); + $done = billingTimeWriteOff($client_id, array_filter(array_map('intval', (array) ($_POST['ticket_ids'] ?? []))), stripslashes($session_name)); + $expense_ids = array_keys(unbilledPostPrices()); + $done_expenses = $expense_ids ? expenseWriteOff($client_id, $expense_ids, stripslashes($session_name)) : []; + if (!$done && !$done_expenses) { + flashAlert('Nothing changed - tick the tickets or expenses that are not billable.', 'error'); redirect(); } - logAudit('Ticket', 'Edit', escapeSql("$session_name marked " . (count($done) === 1 ? 'ticket ' : count($done) . ' tickets ') . implode(', ', array_slice($done, 0, 20)) . ' not billable'), $client_id); + if ($done) { + logAudit('Ticket', 'Edit', escapeSql("$session_name marked " . (count($done) === 1 ? 'ticket ' : count($done) . ' tickets ') . implode(', ', array_slice($done, 0, 20)) . ' not billable'), $client_id); + } - flashAlert((count($done) === 1 ? '' . escapeHtml($done[0]) . ' is' : '' . count($done) . ' tickets are') . ' not billable now'); + $what = []; + if ($done) { + $what[] = count($done) === 1 ? '' . escapeHtml($done[0]) . '' : '' . count($done) . ' tickets'; + } + if ($done_expenses) { + $what[] = count($done_expenses) === 1 ? 'the expense ' . escapeHtml($done_expenses[0]) . '' : '' . count($done_expenses) . ' expenses'; + } + flashAlert(ucfirst(implode(' and ', $what)) . (count($done) + count($done_expenses) === 1 ? ' is' : ' are') . ' not billable now'); redirect(); } diff --git a/agent/post/expense.php b/agent/post/expense.php index 05c860a57..6070660df 100644 --- a/agent/post/expense.php +++ b/agent/post/expense.php @@ -127,7 +127,9 @@ if (isset($_GET['delete_expense'])) { /* * Set one thing on the ticked expenses: field = category, account, client - * (0 takes the client off) or method ('' clears it), to value. + * (0 takes the client off), method ('' clears it) or billable (yes, with + * markup, or no), to value. Expenses already billed on an invoice keep + * their client and stay billed. */ if (isset($_POST['bulk_edit_expenses'])) { @@ -163,6 +165,21 @@ if (isset($_POST['bulk_edit_expenses'])) { $set = "expense_client_id = " . intval($value); $label = "the client to $client_name"; } + if (!intval($value)) { + $set .= ", expense_billable = 0"; + } + } elseif ($field === 'billable') { + $markup = billingNumberInput($_POST['markup'] ?? ''); + if ($value === 'no') { + $set = "expense_billable = 0"; + $label = "them not to bill on"; + } elseif ($value === 'yes' && $markup !== null && $markup >= 0 && $markup <= 1000) { + $set = "expense_billable = 1, expense_markup = $markup"; + $label = "them to bill on at " . rtrim(rtrim(number_format($markup, 2, '.', ''), '0'), '.') . "% markup"; + } elseif ($value === 'yes') { + flashAlert('The markup is a percent, from 0 to 1000', 'error'); + redirect(); + } } elseif ($field === 'method') { if ($value === '') { $set = "expense_payment_method = NULL"; @@ -178,11 +195,18 @@ if (isset($_POST['bulk_edit_expenses'])) { } $count = 0; + $skipped = 0; foreach ($expense_ids as $expense_id) { $row = expenseRow($expense_id); if (!$row || $row['transfer_id'] || !intval($row['expense_vendor_id'])) { continue; } + // Billed ones keep their client and stay billed; only a client's expenses can be billed on + if (($row['expense_invoice_id'] && in_array($field, ['client', 'billable'], true)) + || ($field === 'billable' && $value === 'yes' && (!intval($row['expense_client_id']) || floatval($row['expense_amount']) <= 0))) { + $skipped++; + continue; + } mysqli_query($mysqli, "UPDATE expenses SET $set WHERE expense_id = $expense_id"); logAudit("Expense", "Edit", "$session_name set " . escapeSql($label) . " on the expense " . escapeSql(expenseLabel($row)), intval($row['expense_client_id']), $expense_id); $count++; @@ -190,7 +214,39 @@ if (isset($_POST['bulk_edit_expenses'])) { logAudit("Expense", "Bulk Edit", "$session_name set " . escapeSql($label) . " on $count expense" . ($count === 1 ? '' : 's')); - flashAlert("Set " . escapeHtml($label) . " on $count expense" . ($count === 1 ? '' : 's')); + flashAlert("Set " . escapeHtml($label) . " on $count expense" . ($count === 1 ? '' : 's') + . ($skipped ? " - $skipped left as " . ($skipped === 1 ? 'it was' : 'they were') . ($field === 'billable' && $value === 'yes' ? ' (on an invoice already, or not for a client)' : ' (on an invoice already)') : ''), + $count ? 'success' : 'warning'); + + redirect(); + +} + +/* + * Take a billed expense off its invoice - the line comes off and it waits + * to be billed again. Not once the invoice is paid or cancelled. + */ +if (isset($_GET['expense_unbill'])) { + + validateCSRFToken(); + + enforceUserPermission('module_financial', 2); + enforceUserPermission('module_sales', 2); + + $expense_id = intval($_GET['expense_unbill']); + $row = expenseRow($expense_id); + $number = $row ? expenseUnbill($expense_id, $error) : ''; + if (!$row || $number === '') { + flashAlert($row ? $error : 'That expense no longer exists', 'error'); + redirect(); + } + + logAudit("Expense", "Unbill", "$session_name took the expense " . escapeSql(expenseLabel($row)) . " off invoice " . escapeSql($number), intval($row['expense_client_id']), $expense_id); + if ($row['invoice_status'] !== null) { + billingLog('invoice', intval($row['expense_invoice_id']), $row['invoice_status'], 'Expense taken off by ' . stripslashes($session_name) . ' - ' . expenseLabel($row)); + } + + flashAlert("Expense " . escapeHtml(expenseLabel($row)) . " taken off " . escapeHtml($number) . " - it is to bill again"); redirect(); @@ -232,8 +288,9 @@ if (isExportRequest('export_expenses')) { // The same filters as the expenses list (functions/expenses.php) $where = expenseFiltersSql($_POST, $filter_summary); - $sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, account_name, client_name, user_name + $sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, account_name, client_name, user_name, invoice_prefix, invoice_number FROM expenses " . expenseJoinsSql() . " + LEFT JOIN invoices ON invoice_id = expense_invoice_id WHERE $where ORDER BY expense_date ASC, expense_id ASC"); @@ -247,6 +304,9 @@ if (isExportRequest('export_expenses')) { while ($row = mysqli_fetch_assoc($sql)) { $row['expense_receipt_display'] = $row['expense_receipt'] ? 'Yes' : 'No'; + $markup = rtrim(rtrim(number_format(floatval($row['expense_markup']), 2, '.', ''), '0'), '.') . '%'; + $row['expense_billing_display'] = $row['expense_invoice_id'] ? "Billed, $markup markup" : (intval($row['expense_billable']) ? "To bill, $markup markup" : ''); + $row['expense_billed_on'] = $row['expense_invoice_id'] && $row['invoice_number'] !== null ? $row['invoice_prefix'] . $row['invoice_number'] : ''; addExportRow($export, $row); } diff --git a/agent/post/invoice.php b/agent/post/invoice.php index afa172c0c..00b20ebd1 100644 --- a/agent/post/invoice.php +++ b/agent/post/invoice.php @@ -308,6 +308,9 @@ if (isset($_GET['delete_invoice'])) { // Assets made from its hardware stay on the client's assets, unlinked mysqli_query($mysqli, "UPDATE assets SET asset_invoice_id = 0, asset_invoice_item_id = 0 WHERE asset_invoice_id = $invoice_id"); + // Expenses billed on it are to bill again + mysqli_query($mysqli, "UPDATE expenses SET expense_invoice_id = NULL, expense_invoice_item_id = NULL WHERE expense_invoice_id = $invoice_id"); + logAudit("Invoice", "Delete", "$session_name deleted invoice $invoice_prefix$invoice_number", $client_id); flashAlert("Invoice $invoice_prefix$invoice_number deleted", 'error'); @@ -624,6 +627,49 @@ if (isset($_POST['add_ticket_to_invoice'])) { } +/* + * Bill the client's ticked expenses on this invoice, a line each, at the + * price given for each (expense_price[id]; blank is its cost with its + * markup), with the tax picked. + */ +if (isset($_POST['invoice_add_expenses'])) { + + validateCSRFToken(); + + enforceUserPermission('module_sales', 2); + enforceUserPermission('module_financial', 2); + + $invoice_id = intval($_POST['invoice_id'] ?? 0); + $invoice = billingRow('invoice', $invoice_id); + if (!$invoice) { + flashAlert('That invoice no longer exists.', 'error'); + redirect(); + } + $client_id = intval($invoice['client_id']); + + enforceClientAccess(); + + $prices = []; + foreach (array_unique(array_filter(array_map('intval', (array) ($_POST['expense_ids'] ?? [])))) as $expense_id) { + $prices[$expense_id] = $_POST['expense_price'][$expense_id] ?? null; + } + $result = expenseBillInvoice($client_id, $prices, [ + 'invoice_id' => $invoice_id, + 'tax_id' => intval($_POST['tax_id'] ?? 0), + 'by' => stripslashes($session_name), + ], $error); + if (!$result) { + flashAlert(escapeHtml($error), 'error'); + redirect("invoice.php?invoice_id=$invoice_id"); + } + + flashAlert(($result['expenses'] === 1 ? '1 expense' : "{$result['expenses']} expenses") . ' billed - ' + . escapeHtml(billingMoney($result['amount'], $invoice['invoice_currency_code'])) . ' on ' . escapeHtml(billingMoney($result['cost'], $invoice['invoice_currency_code'])) . ' of cost'); + + redirect("invoice.php?invoice_id=$invoice_id#items"); + +} + if (isset($_GET['remove_ticket_from_invoice'])) { validateCSRFToken(); diff --git a/agent/post/recurring_invoice.php b/agent/post/recurring_invoice.php index 667db4e12..4564866a8 100644 --- a/agent/post/recurring_invoice.php +++ b/agent/post/recurring_invoice.php @@ -178,6 +178,9 @@ if (isset($_GET['delete_recurring_invoice'])) { // Its autopay goes with it - the nightly run would otherwise keep a card set up for nothing mysqli_query($mysqli,"DELETE FROM recurring_payments WHERE recurring_payment_recurring_invoice_id = $recurring_invoice_id"); + // The recurring expenses it covered are only our cost again + mysqli_query($mysqli,"UPDATE recurring_expenses SET recurring_expense_recurring_invoice_id = NULL WHERE recurring_expense_recurring_invoice_id = $recurring_invoice_id"); + //Delete Items Associated with the Recurring $sql = mysqli_query($mysqli,"SELECT item_id FROM recurring_invoice_items WHERE item_recurring_invoice_id = $recurring_invoice_id"); while($row = mysqli_fetch_assoc($sql)) { diff --git a/agent/recurring_expenses.php b/agent/recurring_expenses.php index fa6070218..4d84e2921 100644 --- a/agent/recurring_expenses.php +++ b/agent/recurring_expenses.php @@ -46,8 +46,9 @@ $where = recurringExpenseFiltersSql($_GET); $monthly_sql = expenseRecurringMonthlySql(); $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS recurring_expenses.*, vendor_name, vendor_archived_at, category_name, category_color, account_name, client_name, - $monthly_sql AS monthly + $monthly_sql AS monthly, recurring_invoice_prefix, recurring_invoice_number FROM recurring_expenses $joins + LEFT JOIN recurring_invoices ON recurring_invoice_id = recurring_expense_recurring_invoice_id WHERE $where $status_query ORDER BY {$sortable_columns[$sort]} $order, recurring_expense_id ASC LIMIT $record_from, $record_to"); @@ -244,6 +245,11 @@ $any_filter = $q || $vendor_filter || $category_filter || $client_filter;
+ +
Covered by
+ +
Billed on
+ - diff --git a/agent/recurring_invoice.php b/agent/recurring_invoice.php index 3929dfd25..dba5b5ead 100644 --- a/agent/recurring_invoice.php +++ b/agent/recurring_invoice.php @@ -10,8 +10,9 @@ * right: the schedule (what it brings in a month, the period the next * invoice covers and the dates after, whether invoices go out by * themselves), its per-user and per-device lines against what the client - * has now, the card it charges, the invoices it has made and whether they - * were paid, and its history. + * has now, what it costs us (the recurring expenses it covers, and the + * margin left), the card it charges, the invoices it has made and whether + * they were paid, and its history. */ // If client_id is in URI then show client Side Bar and client header @@ -68,6 +69,11 @@ $can_edit = lookupUserPermission('module_sales') >= 2; $can_delete = lookupUserPermission('module_sales') >= 3; $csrf = $_SESSION['csrf_token']; +// What it costs us - the recurring expenses it covers (functions/expenses.php) +$can_see_costs = lookupUserPermission('module_financial') >= 1; +$can_add_costs = lookupUserPermission('module_financial') >= 2; +$costs = $can_see_costs ? recurringInvoiceCosts($recurring_invoice_id) : null; + // Cards on file the client could be charged on $saved_methods = []; $sql = mysqli_query($mysqli, "SELECT saved_payment_id, saved_payment_description, payment_provider_name, payment_provider_active FROM client_saved_payment_methods @@ -292,6 +298,47 @@ $paper = [
+ + +
+
+

Costs

+ + + +
+ +
+ +
+ +
+ +
+
+
+
+
+
+
+ +
+ + +
+ No costs against it yet. Add the recurring expenses it pays for - the licenses, hosting or backup it resells - to see the margin it leaves each month. +
+ +
+ +

Autopay

diff --git a/agent/unbilled_time.php b/agent/unbilled_time.php index e465849d2..a3e2b079f 100644 --- a/agent/unbilled_time.php +++ b/agent/unbilled_time.php @@ -2,19 +2,24 @@ /* * Unbilled Time - billable tickets that are done (resolved or closed) and on - * no invoice yet: the time to bill. + * no invoice yet: the time to bill. And, for agents who can see expenses, + * what we paid for clients to bill on to them (billable expenses on no + * invoice yet), at cost with its markup. * * Every client: one row each with what is waiting - tickets, hours, what it - * comes to at their rate, how long the oldest has waited. Tick clients and - * invoice them all at once, one draft each (or onto each one's newest draft). + * comes to at their rate, the expenses, how long the oldest has waited. + * Tick clients and invoice them all at once, one draft each (or onto each + * one's newest draft). * * One client (?client_id=): every ticket, with its hours to bill filled in * from the time logged and the rounding in Admin > Settings > Invoice, ready - * to change before it goes on. Tick the ones to bill and make an invoice, or - * add them to one of the client's drafts - or mark them not billable. + * to change before it goes on, and every expense with its price. Tick the + * ones to bill and make an invoice, or add them to one of the client's + * drafts - or mark them not billable. * - * functions/billing.php (Billing time) counts and bills; the handlers are in - * agent/post/billing.php. + * functions/billing.php (Billing time) counts and bills the time, + * functions/expenses.php (Billing expenses on) the expenses; the handlers + * are in agent/post/billing.php. */ if (isset($_GET['client_id'])) { @@ -29,15 +34,20 @@ if (isset($_GET['client_id'])) { enforceUserPermission('module_sales'); $can_edit = lookupUserPermission('module_sales') >= 2; -$ready = intval($config_module_enable_accounting) === 1 && intval($config_module_enable_ticketing) === 1; +$with_time = intval($config_module_enable_ticketing) === 1; +$with_expenses = lookupUserPermission('module_financial') >= 1; +$ready = intval($config_module_enable_accounting) === 1 && ($with_time || $with_expenses); +$can_bill_expenses = $can_edit && lookupUserPermission('module_financial') >= 2; $rules = billingTimeRules(); -$clients = $ready ? billingUnbilledByClient($client_view ? $client_id : 0) : []; +$clients = $ready && $with_time ? billingUnbilledByClient($client_view ? $client_id : 0) : []; +$clients = $ready && $with_expenses ? expenseUnbilledMerge($clients, $client_view ? $client_id : 0) : $clients; $currency = (string) $session_company_currency; $money = function ($amount) use ($currency) { return escapeHtml(billingMoney($amount, $currency)); }; -$total = ['tickets' => 0, 'seconds' => 0, 'hours' => 0.0, 'value' => 0.0, 'oldest' => 0, 'no_time' => 0, 'no_rate' => 0]; +$total = ['tickets' => 0, 'seconds' => 0, 'hours' => 0.0, 'value' => 0.0, 'oldest' => 0, 'no_time' => 0, 'no_rate' => 0, + 'expenses' => 0, 'expense_value' => 0.0, 'expense_cost' => 0.0]; foreach ($clients as $c) { $total['tickets'] += count($c['tickets']); $total['seconds'] += $c['seconds']; @@ -45,9 +55,16 @@ foreach ($clients as $c) { $total['value'] += $c['value']; $total['oldest'] = max($total['oldest'], $c['oldest']); $total['no_time'] += $c['no_time']; - $total['no_rate'] += $c['rate'] <= 0 ? 1 : 0; + $total['no_rate'] += $c['tickets'] && $c['rate'] <= 0 ? 1 : 0; + $total['expenses'] += count($c['expenses'] ?? []); + $total['expense_value'] += $c['expense_value'] ?? 0; + $total['expense_cost'] += $c['expense_cost'] ?? 0; } $this_client = $client_view ? ($clients[$client_id] ?? null) : null; +$show_time = $with_time && (!$client_view || ($this_client && $this_client['tickets'])); +$markup_text = function ($markup) { + return rtrim(rtrim(number_format(floatval($markup), 2, '.', ''), '0'), '.') . '%'; +}; $categories = billingCategories(); $taxes = billingTaxes(); @@ -69,8 +86,14 @@ $hours_text = function ($hours) {
To bill
-
-
0 ? $money($this_client['rate']) . ' an hour' . ($this_client['default_rate'] ? ', the default rate' : '') : 'no rate set') : 'At each client\'s hourly rate' ?>
+
+
+ + of time · of expenses + + 0 ? $money($this_client['rate']) . ' an hour' . ($this_client['default_rate'] ? ', the default rate' : '') : 'no rate set') : 'At each client\'s hourly rate' ?> + +
@@ -82,10 +105,10 @@ $hours_text = function ($hours) {
-
Tickets
-
+
Tickets
+
+ ' . $total['expenses'] : '' ?>
- + ' . $total['no_time'] . ' with no time logged' : '' ?>
@@ -93,8 +116,8 @@ $hours_text = function ($hours) {
Waiting longest
-
-
Since the ticket was done
+
+
@@ -103,7 +126,7 @@ $hours_text = function ($hours) {
-
Unbilled Time needs both ticketing and accounting turned on, in Admin > Settings > Modules.
+
Unbilled Time needs accounting turned on, in Admin > Settings > Modules.
@@ -113,8 +136,8 @@ $hours_text = function ($hours) {
-
Nothing waiting to be billed - billable tickets that are done are all on an invoice.
-
A ticket shows here once it is billable and resolved or closed.
+
Nothing waiting to be billed - billable tickets that are done are all on an invoice.
+
A ticket shows here once it is billable and resolved or closed.
@@ -127,14 +150,86 @@ $hours_text = function ($hours) {
+ + +
+
+

Expenses to bill

+ Expenses +
+
+ + + + + + + + + + + + + + + $expense) { + [$line_name] = expenseBillLine($expense); ?> + + + + + + + + + + + + +
+
+ +
+
ExpensePaidCostBillMargin
+
+ +
+
+ +
+
+
+ +
+ +
+
+
+ + + + + +
+
+ +
+ +
+ +
No unbilled tickets for .
+
@@ -154,10 +249,15 @@ $hours_text = function ($hours) { - - - - + + + + + + + + + @@ -202,7 +302,7 @@ $hours_text = function ($hours) { } else { foreach ($clients as $id => $c) { $draft = $c['drafts'] ? reset($c['drafts']) : null; ?> - + - - - - - + + + + + + + + + +
Amount ClientTicketsLoggedBillRateTicketsLoggedBillRateExpenses Amount Oldest
@@ -218,22 +318,36 @@ $hours_text = function ($hours) {
- - -
with no time
- -
- 0) { ?> - default' : '' ?> - - No rate - - + -' ?> + +
with no time
+ +
-' ?>-' ?> + + - + 0) { ?> + default' : '' ?> + + No rate + + + + +
expense
+ + - + +
Review @@ -244,11 +358,15 @@ $hours_text = function ($hours) {
- + + + +
+
@@ -316,6 +434,7 @@ $hours_text = function ($hours) {
+
@@ -323,7 +442,8 @@ $hours_text = function ($hours) {
- + +
@@ -345,6 +465,7 @@ $hours_text = function ($hours) {
+
@@ -354,7 +475,11 @@ $hours_text = function ($hours) {
+ +
Expenses go on with a line each, at their price.
+
+