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

This commit is contained in:
johnnyq
2026-10-16 18:36:43 -04:00
parent 94413424e4
commit 8d5e5091ad
34 changed files with 1649 additions and 119 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.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.

View File

@@ -0,0 +1,28 @@
<?php
/*
* ITFlow - Database update to version 3.0.1 (from 3.0.0)
* Included by admin/database_updates.php - do not access directly
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
// Expenses billed on to the client (functions/expenses.php): billable with
// a markup, and the invoice and line they went on once billed
mysqli_query($mysqli, "ALTER TABLE `expenses`
ADD COLUMN `expense_billable` tinyint(1) NOT NULL DEFAULT 0 AFTER `expense_recurring_expense_id`,
ADD COLUMN `expense_markup` decimal(7,2) NOT NULL DEFAULT 0.00 AFTER `expense_billable`,
ADD COLUMN `expense_invoice_id` int(11) DEFAULT NULL AFTER `expense_markup`,
ADD COLUMN `expense_invoice_item_id` int(11) DEFAULT NULL AFTER `expense_invoice_id`,
ADD KEY `expense_invoice_id` (`expense_invoice_id`)");
// A client's recurring expense is either billed on as each one is
// recorded, or covered by one of their recurring invoices - its cost
// shown against what that bills
mysqli_query($mysqli, "ALTER TABLE `recurring_expenses`
ADD COLUMN `recurring_expense_billable` tinyint(1) NOT NULL DEFAULT 0 AFTER `recurring_expense_account_id`,
ADD COLUMN `recurring_expense_markup` decimal(7,2) NOT NULL DEFAULT 0.00 AFTER `recurring_expense_billable`,
ADD COLUMN `recurring_expense_recurring_invoice_id` int(11) DEFAULT NULL AFTER `recurring_expense_markup`");
// The markup a billable expense starts with
mysqli_query($mysqli, "ALTER TABLE `settings` ADD COLUMN `config_expense_markup` decimal(7,2) NOT NULL DEFAULT 0.00 AFTER `config_time_item_name`");

View File

@@ -3208,6 +3208,9 @@ function demoBuildBilling($mysqli, $profile, $index, $client_id, $vendor_id, $mo
'expense_client_id' => $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']++;

View File

@@ -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");

View File

@@ -264,6 +264,22 @@ require_once "includes/inc_all_admin.php";
<hr>
<h4 id="billable-expenses">Billable Expenses</h4>
<p class="text-secondary small">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.</p>
<div class="row">
<div class="col-md-6 mb-3">
<label>Default markup</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-percent"></i></span>
<input type="text" class="form-control" name="config_expense_markup" inputmode="decimal" value="<?= rtrim(rtrim(number_format(expenseMarkupDefault(), 2, '.', ''), '0'), '.') ?>" placeholder="0">
</div>
<small class="text-secondary">What a billable expense starts with - 0 bills it at cost. Each expense can have its own.</small>
</div>
</div>
<hr>
<button type="submit" name="edit_invoice_settings" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Save</button>
</form>

View File

@@ -504,11 +504,14 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code,
<span class="itflow-dash-money-value"><?= $money_format($money['recurring']) ?><span class="fs-6 fw-normal text-body-secondary">/mo</span></span>
<span class="small text-body-tertiary"><?= $num_recurring_invoices ?> recurring invoice<?= $num_recurring_invoices === 1 ? '' : 's' ?></span>
</a>
<?php if ($access['tickets']) { ?>
<?php if ($access['tickets'] || $money['unbilled_expenses']) {
$unbilled_total = $money['unbilled_value'] + $money['unbilled_expense_value']; ?>
<a href="unbilled_time.php?client_id=<?= $client_id ?>" class="itflow-dash-rail-item">
<span class="small text-body-secondary">Not yet invoiced</span>
<span class="itflow-dash-money-value <?= $money['unbilled_value'] > 0 ? 'text-info-emphasis' : '' ?>"><?= $money_format($money['unbilled_value']) ?></span>
<span class="small text-body-tertiary"><?= $money['unbilled_tickets'] ?> ticket<?= $money['unbilled_tickets'] === 1 ? '' : 's' ?><?= $money['unbilled_seconds'] ? ', ' . dashboardDuration($money['unbilled_seconds']) . ' logged' : '' ?></span>
<span class="itflow-dash-money-value <?= $unbilled_total > 0 ? 'text-info-emphasis' : '' ?>"><?= $money_format($unbilled_total) ?></span>
<span class="small text-body-tertiary">
<?php if ($access['tickets']) { ?><?= $money['unbilled_tickets'] ?> ticket<?= $money['unbilled_tickets'] === 1 ? '' : 's' ?><?= $money['unbilled_seconds'] && !$money['unbilled_expenses'] ? ', ' . dashboardDuration($money['unbilled_seconds']) . ' logged' : '' ?><?php } ?><?= $access['tickets'] && $money['unbilled_expenses'] ? ', ' : '' ?><?= $money['unbilled_expenses'] ? $money['unbilled_expenses'] . ' expense' . ($money['unbilled_expenses'] === 1 ? '' : 's') : '' ?>
</span>
</a>
<?php } ?>
<div class="itflow-dash-rail-item">

View File

@@ -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
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/expense/expense_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/expense/expense_bulk_edit.php?field=method" data-bulk="true"><i class="fas fa-fw fa-credit-card text-secondary me-2"></i>Set Payment Method</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/expense/expense_bulk_edit.php?field=client" data-bulk="true"><i class="fas fa-fw fa-user text-secondary me-2"></i>Set Client</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/expense/expense_bulk_edit.php?field=billable" data-bulk="true"><i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Set Billable</a>
<?php if ($can_delete) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold ajax-modal" href="#" data-modal-url="modals/expense/expense_bulk_delete.php" data-bulk="true"><i class="fas fa-fw fa-trash me-2"></i>Delete</a>
@@ -342,6 +346,12 @@ $month_change = $stats['last_to_date'] > 0 ? round(($stats['month'] - $stats['la
<td>
<?php if (intval($row['expense_client_id'])) { ?>
<div class="text-truncate" style="max-width: 10rem;"><a class="text-reset" href="<?= escapeHtml($filter_url(['client' => intval($row['expense_client_id'])])) ?>" title="<?= escapeHtml((string) $row['client_name']) ?> - their expenses"><?= escapeHtml($row['client_name']) ?></a></div>
<?php if ($row['expense_invoice_id']) {
$row_invoice = $row['invoice_number'] !== null ? $row['invoice_prefix'] . $row['invoice_number'] : 'an invoice'; ?>
<div class="small"><?php if ($can_sales && $row['invoice_number'] !== null) { ?><a class="text-success-emphasis" href="invoice.php?invoice_id=<?= intval($row['expense_invoice_id']) ?>" title="Billed on to them"><i class="fas fa-check-circle me-1"></i>Billed <?= escapeHtml($row_invoice) ?></a><?php } else { ?><span class="text-success-emphasis"><i class="fas fa-check-circle me-1"></i>Billed <?= escapeHtml($row_invoice) ?></span><?php } ?></div>
<?php } elseif (intval($row['expense_billable']) && $row_amount > 0) { ?>
<div class="small"><?php if ($can_sales) { ?><a class="text-warning-emphasis" href="unbilled_time.php?client_id=<?= intval($row['expense_client_id']) ?>" title="Billable at <?= escapeHtml(rtrim(rtrim(number_format(floatval($row['expense_markup']), 2, '.', ''), '0'), '.')) ?>% markup - bill it from Unbilled Time"><i class="fas fa-file-invoice-dollar me-1"></i>To bill</a><?php } else { ?><span class="text-warning-emphasis"><i class="fas fa-file-invoice-dollar me-1"></i>To bill</span><?php } ?></div>
<?php } ?>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>

View File

@@ -344,14 +344,14 @@
</a>
</li>
<?php if ($config_module_enable_ticketing == 1) { ?>
<?php if ($config_module_enable_ticketing == 1 || lookupUserPermission('module_financial') >= 1) { ?>
<li class="nav-item">
<a href="/agent/unbilled_time.php?client_id=<?= $client_id ?>" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "unbilled_time.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-user-clock"></i>
<p>
Unbilled Time
<?php if ($num_unbilled_tickets) { ?>
<span class="right badge text-light"><?= $num_unbilled_tickets ?></span>
<?php if ($num_unbilled_tickets || !empty($num_unbilled_expenses)) { ?>
<span class="right badge text-light"><?= $num_unbilled_tickets + intval($num_unbilled_expenses ?? 0) ?></span>
<?php } ?>
</p>
</a>

View File

@@ -28,6 +28,9 @@ $num_recurring_invoices = $row['num'];
// Unbilled tickets - billable, done and on no invoice (Billing > Unbilled Time)
$num_unbilled_tickets = $config_module_enable_accounting == 1 && $config_module_enable_ticketing == 1 && lookupUserPermission('module_sales') >= 1 ? billingUnbilledCount() : 0;
// Expenses to bill on to clients - billable, on no invoice (Unbilled Time too)
$num_unbilled_expenses = $config_module_enable_accounting == 1 && lookupUserPermission('module_sales') >= 1 && lookupUserPermission('module_financial') >= 1 ? expenseUnbilledCount()['count'] : 0;
// Products whose stock is at or under the reorder level, or out
$num_products_reorder = $config_module_enable_accounting == 1 && lookupUserPermission('module_sales') >= 1 ? productReorderCount() : 0;

View File

@@ -167,6 +167,8 @@ if (isset($_GET['client_id'])) {
// Billable tickets done and not invoiced yet, for Unbilled Time
$num_unbilled_tickets = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM tickets WHERE " . billingUnbilledSql() . " AND ticket_client_id = $client_id"))[0]);
// ...and their expenses to bill on, for those who can see expenses
$num_unbilled_expenses = lookupUserPermission('module_financial') >= 1 ? expenseUnbilledCount($client_id)['count'] : 0;
// Get Credit Balance
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COALESCE(SUM(credit_amount), 0) AS credit_balance

View File

@@ -150,14 +150,14 @@
</p>
</a>
</li>
<?php if ($config_module_enable_ticketing == 1) { ?>
<?php if ($config_module_enable_ticketing == 1 || lookupUserPermission('module_financial') >= 1) { ?>
<li class="nav-item">
<a href="/agent/unbilled_time.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "unbilled_time.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-user-clock"></i>
<p>
Unbilled Time
<?php if ($num_unbilled_tickets) { ?>
<span class="right badge text-light" data-bs-toggle="tooltip" title="Billable tickets done, not invoiced"><?= $num_unbilled_tickets ?></span>
<?php if ($num_unbilled_tickets || $num_unbilled_expenses) { ?>
<span class="right badge text-light" data-bs-toggle="tooltip" title="<?= $num_unbilled_expenses ? "$num_unbilled_tickets billable ticket" . ($num_unbilled_tickets == 1 ? '' : 's') . " done and $num_unbilled_expenses expense" . ($num_unbilled_expenses == 1 ? '' : 's') . ' to bill, not invoiced' : 'Billable tickets done, not invoiced' ?>"><?= $num_unbilled_tickets + $num_unbilled_expenses ?></span>
<?php } ?>
</p>
</a>

View File

@@ -9,7 +9,8 @@
* as the client sees it, with its lines edited in place while it is open.
* On the right: what has been paid and what is left, the payments, the
* hardware sold on it and whether it is on the client's assets yet, the
* tickets billed on it and its history.
* tickets and expenses billed on it (the expenses with what they cost us and
* the margin) and its history.
*/
// If client_id is in URI then show client Side Bar and client header
@@ -59,6 +60,12 @@ $can_edit_lines = billingCanEditItems('invoice', $invoice);
$mail_ready = !empty($config_smtp_provider) && billingEmailableContacts('invoice', $client_id) > 0;
$saved_card = $can_take_payment && in_array($status, ['Sent', 'Viewed'], true) && invoiceHasSavedCard($client_id);
$unbilled_tickets = $can_edit && $can_edit_lines && $config_module_enable_ticketing ? count(billingUnbilledTickets($client_id)) : 0;
// Expenses billed on it, against what they cost us (functions/expenses.php)
$can_see_expenses = lookupUserPermission('module_financial') >= 1;
$can_bill_expenses = $can_edit && $can_edit_lines && lookupUserPermission('module_financial') >= 2;
$can_unbill_expenses = $can_edit && lookupUserPermission('module_financial') >= 2 && expenseCanUnbill($status);
$billed_expenses = $can_see_expenses ? expenseOnInvoice($invoice_id) : [];
$unbilled_expenses = $can_bill_expenses ? count(expenseUnbilled($client_id)) : 0;
$guest_url = billingGuestUrl('invoice', $invoice);
// Hardware sold on it, and how much of it is on the client's assets (functions/products.php)
$can_see_assets = lookupUserPermission('module_support') >= 1;
@@ -246,7 +253,7 @@ $paper = [
<?php } ?>
<?php if ($can_delete) { ?>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_invoice=<?= $invoice_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-text="<?= escapeHtml($number) ?> goes for good, with its lines, payments and history. Its tickets become unbilled again.">
data-confirm-text="<?= escapeHtml($number) ?> goes for good, with its lines, payments and history. Its tickets become unbilled again, and its expenses are to bill again.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
@@ -459,6 +466,53 @@ $paper = [
</div>
<?php } ?>
<?php if ($billed_expenses || $unbilled_expenses) {
$expenses_cost = array_sum(array_column($billed_expenses, 'cost'));
$expenses_billed = array_sum(array_map(function ($e) { return floatval($e['billed']); }, $billed_expenses)); ?>
<div class="card mb-3">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-shopping-cart text-secondary me-2"></i>Expenses <span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal ms-1"><?= count($billed_expenses) ?></span></h3>
<?php if ($unbilled_expenses) { ?>
<button type="button" class="btn btn-sm btn-outline-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/invoice/invoice_add_expenses.php?invoice_id=<?= $invoice_id ?>">
<i class="fas fa-plus me-1"></i>Add <span class="badge rounded-pill text-bg-primary ms-1" title="To bill"><?= $unbilled_expenses ?></span>
</button>
<?php } ?>
</div>
<?php if ($billed_expenses) { ?>
<div class="list-group list-group-flush">
<?php foreach ($billed_expenses as $expense) {
$expense_id = intval($expense['expense_id']);
[$line_name] = expenseBillLine($expense); ?>
<div class="list-group-item">
<div class="d-flex align-items-start gap-2">
<div class="flex-grow-1 min-w-0">
<a class="text-truncate d-block" href="expenses.php?open=<?= $expense_id ?>" title="<?= escapeHtml($line_name) ?>"><?= escapeHtml($line_name) ?></a>
<div class="small text-body-secondary text-truncate"><?= escapeHtml(implode(' · ', array_filter([$expense['vendor_name'], $expense['expense_date']]))) ?></div>
</div>
<?php if ($can_unbill_expenses) { ?>
<a class="btn btn-sm btn-link text-body-secondary confirm-link p-0" title="Take off the invoice" href="post.php?expense_unbill=<?= $expense_id ?>&csrf_token=<?= $csrf ?>"
data-confirm-text="<?= $status === 'Cancelled' ? 'The invoice is cancelled, so its line stays on it' : 'Its line comes off the invoice' ?> and the expense waits to be billed again.">
<i class="fas fa-fw fa-unlink"></i>
</a>
<?php } ?>
</div>
<div class="d-flex justify-content-between gap-2 small mt-1">
<span class="itflow-money text-nowrap"><span class="text-body-secondary">Cost <?= $money($expense['cost']) ?> &rarr;</span> <?= $expense['billed'] !== null ? $money($expense['billed']) : '<span class="text-body-secondary">line gone</span>' ?></span>
<?php if ($expense['billed'] !== null) { ?><span class="text-nowrap <?= $expense['billed'] < $expense['cost'] ? 'text-danger-emphasis' : 'text-body-secondary' ?>"><?= escapeHtml(expenseMarginText($expense['billed'], $expense['cost'])) ?></span><?php } ?>
</div>
</div>
<?php } ?>
</div>
<div class="card-footer small d-flex justify-content-between gap-2">
<span class="text-body-secondary">Cost <?= $money($expenses_cost) ?> &middot; billed <?= $money($expenses_billed) ?></span>
<span class="fw-semibold <?= $expenses_billed < $expenses_cost ? 'text-danger-emphasis' : '' ?>"><?= escapeHtml(expenseMarginText($expenses_billed, $expenses_cost) ?: 'No charge') ?></span>
</div>
<?php } else { ?>
<div class="card-body small text-body-secondary"><?= $unbilled_expenses ?> expense<?= $unbilled_expenses === 1 ? '' : 's' ?> to bill to <?= escapeHtml($invoice['client_name']) ?> could go on this invoice.</div>
<?php } ?>
</div>
<?php } ?>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-history text-secondary me-2"></i>History</h3>

View File

@@ -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' ?></span>
</div>
<?php } ?>
<?php if ($billed_on) { ?>
<div class="itflow-glance-item" title="Billed">
<i class="fas fa-fw fa-file-invoice-dollar"></i>
<span>
<?php if ($row['invoice_status'] === null) { ?>
Billed on an invoice since deleted
<?php } else { ?>
Billed on <?= $can_sales ? '<a href="invoice.php?invoice_id=' . $billed_on . '">' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) . '</a>' : escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?><?= $row['invoice_status'] === 'Cancelled' ? ' <span class="text-danger-emphasis">(cancelled)</span>' : '' ?>
<?php if ($row['billed_subtotal'] !== null) { ?>
at <?= escapeHtml(billingMoney($row['billed_subtotal'], $currency)) ?>
<span class="text-body-secondary">&middot; <?= escapeHtml(expenseMarginText($row['billed_subtotal'], $cost)) ?></span>
<?php } ?>
<?php } ?>
</span>
</div>
<?php } elseif ($billable) { ?>
<div class="itflow-glance-item" title="To bill">
<i class="fas fa-fw fa-file-invoice-dollar"></i>
<span>
<?php if ($cost <= 0) { ?>
Billable, but refunded in full
<?php } else { ?>
<span class="text-warning-emphasis fw-semibold">To bill</span> at <?= escapeHtml(billingMoney($bill_price, $currency)) ?>
<span class="text-body-secondary">&middot; <?= escapeHtml(rtrim(rtrim(number_format(floatval($row['expense_markup']), 2, '.', ''), '0'), '.')) ?>% markup</span>
<?php if ($can_sales) { ?>
<span class="text-body-secondary">&middot;</span> <a href="unbilled_time.php?client_id=<?= $client_id ?>">Unbilled Time</a>
<?php } ?>
<?php } ?>
</span>
</div>
<?php } ?>
<?php if ($row['expense_refund_of_id']) { ?>
<div class="itflow-glance-item" title="Refund of">
<i class="fas fa-fw fa-undo-alt"></i>
@@ -197,9 +237,13 @@ ob_start();
<?php } ?>
</div>
<?php } ?>
<?php if ($can_unbill) { ?>
<a class="btn btn-outline-secondary confirm-link" href="post.php?expense_unbill=<?= $expense_id ?>&amp;csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= $row['invoice_status'] === 'Cancelled' ? escapeHtml($row['invoice_prefix'] . $row['invoice_number']) . ' is cancelled, so its line stays on it' : 'Its line comes off ' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) ?> and it waits to be billed again."><i class="fas fa-unlink"></i><span class="d-none d-sm-inline ms-2">Take off Invoice</span></a>
<?php } ?>
<?php if ($can_delete && !$is_transfer) { ?>
<a class="btn btn-outline-danger confirm-link" href="post.php?delete_expense=<?= $expense_id ?>&amp;csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= escapeHtml(expenseLabel($row)) ?> goes for good<?= $row['expense_receipt'] ? ', with its receipt' : '' ?>."><i class="fas fa-trash"></i><span class="d-none d-sm-inline ms-2">Delete</span></a>
data-confirm-text="<?= escapeHtml(expenseLabel($row)) ?> goes for good<?= $row['expense_receipt'] ? ', with its receipt' : '' ?>.<?= $billed_on && $row['invoice_status'] !== null ? ' Its line stays on ' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) . '.' : '' ?>"><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>

View File

@@ -1,8 +1,10 @@
<?php
/*
* Set one thing on the ticked expenses - ?field= category, account, client
* or method. Posts bulk_edit_expenses with field, value and expense_ids[].
* Set one thing on the ticked expenses - ?field= category, account, client,
* method or billable (bill them on to their clients, with a markup, or
* not). Posts bulk_edit_expenses with field, value (and markup) and
* expense_ids[].
*/
require_once '../../../includes/modal_header.php';
@@ -18,6 +20,7 @@ $fields = [
'account' => ['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();
<option value="<?= intval($row['client_id']) ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
<?php } elseif ($field === 'billable') { ?>
<select class="form-select" name="value" data-bulk-billable>
<option value="yes">Bill them on to their clients</option>
<option value="no">Our cost - not billed on</option>
</select>
<?php } else { ?>
<select class="form-select select2" name="value">
<option value="">- None -</option>
@@ -78,6 +86,29 @@ ob_start();
</select>
<?php } ?>
</div>
<?php if ($field === 'billable') { ?>
<div class="mt-3" data-bulk-markup>
<label class="form-label">Markup</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-percent"></i></span>
<input type="text" class="form-control" name="markup" inputmode="decimal" value="<?= rtrim(rtrim(number_format(expenseMarkupDefault(), 2, '.', ''), '0'), '.') ?>" aria-label="Markup">
</div>
</div>
<div class="form-text">Only those for a client are billed on, and not ones already on an invoice - those stay as they are.</div>
<script>
(function () {
var value = document.querySelector('.modal.show [data-bulk-billable], [data-bulk-billable]');
var markup = value && value.closest('form').querySelector('[data-bulk-markup]');
if (!value || !markup || value.dataset.wired) {
return;
}
value.dataset.wired = '1';
value.addEventListener('change', function () {
markup.hidden = value.value !== 'yes';
});
})();
</script>
<?php } ?>
</div>
<div class="modal-footer">
<button type="submit" name="bulk_edit_expenses" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Set on <?= $count ?></button>

View File

@@ -68,6 +68,11 @@ while ($row = mysqli_fetch_assoc($sql)) {
}
$form_receipt = $form_edit ? $form_value('expense_receipt') : '';
// Billed on to the client - not for a refund. One already on an invoice stays billed to that client.
$form_billed = $form_edit && !empty($form_row['expense_invoice_id']);
$form_billable = $form_row && !$form_refund ? intval($form_row['expense_billable']) === 1 : false;
$form_markup = $form_row && !$form_refund ? floatval($form_row['expense_markup']) : expenseMarkupDefault();
?>
<div class="row g-3" id="<?= $form_id ?>" data-expense-form="<?= $form_mode ?>">
@@ -179,12 +184,15 @@ $form_receipt = $form_edit ? $form_value('expense_receipt') : '';
<label class="form-label">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">
<select class="form-select select2" name="client_id" data-expense-client <?= $form_billed ? 'disabled' : '' ?>>
<option value="0">- Not for 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>
<?php if ($form_billed) { ?>
<input type="hidden" name="client_id" value="<?= $form_client ?>">
<?php } ?>
</div>
<div class="form-text">A direct cost of theirs - it counts against them in Client Profitability.</div>
</div>
@@ -197,6 +205,33 @@ $form_receipt = $form_edit ? $form_value('expense_receipt') : '';
</div>
</div>
<?php if (!$form_refund) { ?>
<div class="col-12" data-expense-billing <?= $form_client ? '' : 'hidden' ?>>
<div class="d-flex flex-wrap align-items-center gap-3 p-2 px-3 rounded border bg-body-tertiary">
<?php if ($form_billed) { ?>
<i class="fas fa-check-circle text-success"></i>
<div class="flex-grow-1 small">
Billed on <a href="invoice.php?invoice_id=<?= intval($form_row['expense_invoice_id']) ?>"><?= escapeHtml($form_row['invoice_prefix'] . $form_row['invoice_number']) ?></a><?= $form_row['billed_subtotal'] !== null ? ' at ' . escapeHtml(billingMoney($form_row['billed_subtotal'], $form_row['expense_currency_code'])) : '' ?>.
<span class="text-body-secondary">Changing the amount here doesn't change the invoice - take it off the invoice to bill it again.</span>
</div>
<input type="hidden" name="billable" value="1">
<input type="hidden" name="markup" value="<?= number_format($form_markup, 2, '.', '') ?>">
<?php } else { ?>
<div class="form-check form-switch mb-0">
<input class="form-check-input" type="checkbox" role="switch" name="billable" value="1" id="<?= $form_id ?>Billable" <?= $form_billable ? 'checked' : '' ?> data-expense-billable>
<label class="form-check-label" for="<?= $form_id ?>Billable">Bill it on to them</label>
</div>
<div class="input-group input-group-sm" style="max-width: 11rem;" data-expense-billable-only>
<span class="input-group-text"><i class="fa fa-fw fa-percent"></i></span>
<input type="text" class="form-control text-end" name="markup" inputmode="decimal" value="<?= rtrim(rtrim(number_format($form_markup, 2, '.', ''), '0'), '.') ?>" aria-label="Markup" data-expense-markup>
<span class="input-group-text">markup</span>
</div>
<div class="small text-body-secondary" data-expense-billable-only>Bills <strong data-expense-bills></strong> - it waits in Unbilled Time and on their invoices until it goes on one.</div>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="col-12">
<label class="form-label">Description</label>
<div class="input-group">
@@ -226,6 +261,52 @@ $form_receipt = $form_edit ? $form_value('expense_receipt') : '';
</div>
<?php if (!$form_refund) { ?>
<script>
(function () {
// Billing shows once there is a client; what it bills follows the amount and markup
var root = document.getElementById(<?= json_encode($form_id) ?>);
if (!root || root.dataset.billingWired) {
return;
}
root.dataset.billingWired = '1';
var client = root.querySelector('[data-expense-client]');
var block = root.querySelector('[data-expense-billing]');
var billable = root.querySelector('[data-expense-billable]');
var markup = root.querySelector('[data-expense-markup]');
var bills = root.querySelector('[data-expense-bills]');
var amount = root.querySelector('input[name="amount"]');
function number(value) {
var n = Number(String(value || '').replace(/[\s,$%]/g, ''));
return isNaN(n) ? 0 : n;
}
function update() {
block.hidden = !client.value || client.value === '0' || number(amount.value) < 0;
if (!billable) {
return;
}
root.querySelectorAll('[data-expense-billable-only]').forEach(function (el) {
el.classList.toggle('d-none', !billable.checked);
});
var price = Math.round(number(amount.value) * (1 + number(markup.value) / 100) * 100) / 100;
try {
bills.textContent = new Intl.NumberFormat(<?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>, { style: 'currency', currency: <?= json_encode($form_currency) ?> }).format(price);
} catch (e) {
bills.textContent = price.toFixed(2);
}
}
client.addEventListener('change', update);
[billable, markup, amount].forEach(function (el) {
if (el) {
el.addEventListener('input', update);
el.addEventListener('change', update);
}
});
update();
})();
</script>
<?php } ?>
<?php if (in_array($form_mode, ['new', 'copy'], true)) { ?>
<script>
(function () {

View File

@@ -0,0 +1,157 @@
<?php
/*
* Add Expenses to an invoice - the client's billable expenses that aren't
* on an invoice yet, each at its cost with its markup, the price ready to
* change, the margin following along. Each goes on as a line of its own.
* ?invoice_id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
enforceUserPermission('module_financial', 2);
$invoice_id = intval($_GET['invoice_id'] ?? 0);
$invoice = billingRow('invoice', $invoice_id);
if (!$invoice) {
exit(json_encode(['error' => 'That invoice no longer exists.']));
}
$client_id = intval($invoice['client_id']);
enforceClientAccess();
if (!billingCanEditItems('invoice', $invoice)) {
exit(json_encode(['error' => billingNumber('invoice', $invoice) . " can't take more lines - it is paid, cancelled or non-billable."]));
}
$expenses = expenseUnbilled($client_id);
$currency = (string) $invoice['invoice_currency_code'];
$taxes = billingTaxes();
$markup_text = function ($markup) {
return rtrim(rtrim(number_format(floatval($markup), 2, '.', ''), '0'), '.') . '%';
};
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fas fa-fw fa-shopping-cart me-2"></i>Add Expenses <span class="fw-normal text-white-50 ms-1"><?= escapeHtml(billingNumber('invoice', $invoice)) ?></span></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off" id="invoiceAddExpenses">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">
<div class="modal-body p-0">
<?php if ($expenses) { ?>
<div class="px-3 py-2 small text-body-secondary border-bottom">
What we paid for <?= escapeHtml($invoice['client_name']) ?> to bill on to them, at its cost (less any refund) with its markup. Change a price before adding - each goes on as a line of its own.
</div>
<div class="list-group list-group-flush" style="max-height: 22rem; overflow-y: auto;">
<?php foreach ($expenses as $expense_id => $expense) {
[$line_name] = expenseBillLine($expense); ?>
<div class="list-group-item d-flex align-items-center gap-3" data-add-expense-row data-cost="<?= $expense['cost'] ?>">
<input class="form-check-input flex-shrink-0 mt-0" type="checkbox" name="expense_ids[]" value="<?= $expense_id ?>" id="addExpense<?= $expense_id ?>" checked data-add-expense>
<label class="flex-grow-1 min-w-0 mb-0" for="addExpense<?= $expense_id ?>">
<span class="d-block text-truncate"><?= escapeHtml($line_name) ?></span>
<span class="small text-body-secondary d-block text-truncate">
<?= escapeHtml($expense['vendor_name']) ?> &middot; <?= escapeHtml($expense['expense_date']) ?>
&middot; cost <?= escapeHtml(billingMoney($expense['cost'], $currency)) ?> + <?= $markup_text($expense['expense_markup']) ?>
</span>
</label>
<div class="text-end flex-shrink-0" style="width: 8rem;">
<div class="input-group input-group-sm">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control text-end" name="expense_price[<?= $expense_id ?>]" value="<?= number_format($expense['price'], 2, '.', '') ?>" inputmode="decimal" aria-label="Price to bill" data-add-expense-price>
</div>
<div class="small text-body-secondary mt-1" data-add-expense-margin></div>
</div>
</div>
<?php } ?>
</div>
<div class="p-3 border-top">
<div class="row g-3">
<div class="col-sm-6">
<label class="form-label">Tax</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-percent"></i></span>
<select class="form-select" name="tax_id" data-add-expense-tax>
<option value="0" data-percent="0">No tax</option>
<?php foreach ($taxes as $tax_id => $tax) { ?>
<option value="<?= intval($tax_id) ?>" data-percent="<?= floatval($tax['tax_percent']) ?>"><?= escapeHtml($tax['tax_name'] . ' ' . billingQuantity($tax['tax_percent']) . '%') ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
</div>
<?php } else { ?>
<div class="itflow-asset-empty">
<i class="fas fa-shopping-cart fa-2x mb-2 opacity-50"></i>
<div>No expenses to bill - <?= escapeHtml($invoice['client_name']) ?>'s billable expenses are all on an invoice.</div>
<div class="small mt-1">Mark one billable from its Edit window, or several at once with Bulk Action &rsaquo; Set Billable on <a href="expenses.php?client=<?= $client_id ?>">their expenses</a>.</div>
</div>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($expenses) { ?>
<span class="me-auto small text-body-secondary" data-add-expense-summary></span>
<button type="submit" name="invoice_add_expenses" class="btn btn-primary text-bold" data-add-expense-submit><i class="fas fa-check me-2"></i>Add</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i><?= $expenses ? 'Cancel' : 'Close' ?></button>
</div>
</form>
<script>
(function () {
var form = document.getElementById('invoiceAddExpenses');
if (!form || form.dataset.wired || !form.querySelector('[data-add-expense]')) {
return;
}
form.dataset.wired = '1';
var currency = <?= json_encode($currency) ?>;
var tax = form.querySelector('[data-add-expense-tax]');
var summary = form.querySelector('[data-add-expense-summary]');
var submit = form.querySelector('[data-add-expense-submit]');
function number(value) {
var n = Number(String(value || '').replace(/[\s,$]/g, ''));
return isNaN(n) ? 0 : n;
}
function money(amount) {
try {
return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency || 'USD' }).format(amount);
} catch (e) {
return amount.toFixed(2);
}
}
function update() {
var count = 0;
var price = 0;
var cost = 0;
form.querySelectorAll('[data-add-expense-row]').forEach(function (row) {
var box = row.querySelector('[data-add-expense]');
var input = row.querySelector('[data-add-expense-price]');
var margin = row.querySelector('[data-add-expense-margin]');
var p = number(input.value);
var c = Number(row.getAttribute('data-cost'));
input.disabled = !box.checked;
margin.textContent = p > 0 ? Math.round((p - c) / p * 100) + '% margin' : 'no charge';
if (box.checked) {
count++;
price += p;
cost += c;
}
});
var option = tax.options[tax.selectedIndex];
price = Math.round(price * 100) / 100;
var total = price + Math.round(price * Number(option ? option.getAttribute('data-percent') || 0 : 0)) / 100;
summary.textContent = count ? count + ' expense' + (count === 1 ? '' : 's') + ' · ' + money(total) + (price > 0 ? ' · ' + Math.round((price - cost) / price * 100) + '% margin' : '') : 'Tick the expenses to add';
submit.disabled = count === 0;
}
form.addEventListener('change', update);
form.addEventListener('input', update);
update();
})();
</script>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -3,7 +3,9 @@
/*
* A recurring expense's quick look - what it costs and how often, the
* schedule with the next few dates and when it ends, the account, how it is
* paid, the client, and the expenses it has recorded. Record Now, Move On
* paid, the client and billing it on to them (each time, with a markup, or
* covered by one of their recurring invoices, with the margin left), and
* the expenses it has recorded. Record Now, Move On
* (when it has fallen behind), Pause or Resume, Edit and Delete. Opened from
* the recurring expenses list, the vendor page and an expense it recorded.
*/
@@ -30,6 +32,10 @@ $next = (string) $row['recurring_expense_next_date'];
$behind = $state === 'active' && $next < date('Y-m-d');
$upcoming = recurringExpenseUpcoming($row, 4);
$made = recurringExpenseMade($id, 8);
$can_sales = lookupUserPermission('module_sales') >= 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&amp;csrf_token=" . $_SESSION['csrf_token'];
};
@@ -114,6 +120,22 @@ ob_start();
<span class="text-body-secondary">Not for a client</span>
<?php } ?>
</div>
<?php if ($client_id) { ?>
<div class="itflow-glance-item" title="Billing it on">
<i class="fas fa-fw fa-file-invoice-dollar"></i>
<?php if ($cover) {
$cover_number = $row['recurring_invoice_prefix'] . $row['recurring_invoice_number']; ?>
<span>Covered by <?= $can_sales ? '<a href="recurring_invoice.php?recurring_invoice_id=' . $covered_by . '">' . escapeHtml($cover_number) . '</a>' : escapeHtml($cover_number) ?>
<span class="text-body-secondary">&middot; <?= escapeHtml(billingMoney($cover['revenue'], $currency)) ?> a month before tax<?= $cover['percent'] !== null ? ', ' . $cover['percent'] . '% margin after ' . (count(array_filter(array_column($cover['rows'], 'running'))) === 1 ? 'this cost' : 'its costs') : '' ?></span></span>
<?php } elseif ($covered_by) { ?>
<span class="text-body-secondary">Covered by a recurring invoice since deleted</span>
<?php } elseif (intval($row['recurring_expense_billable'])) { ?>
<span>Billed on each time at <?= escapeHtml(billingMoney(expenseBillPrice($amount, $markup), $currency)) ?> <span class="text-body-secondary">&middot; <?= escapeHtml(rtrim(rtrim(number_format($markup, 2, '.', ''), '0'), '.')) ?>% markup</span></span>
<?php } else { ?>
<span class="text-body-secondary">Our cost - not billed on</span>
<?php } ?>
</div>
<?php } ?>
<div class="itflow-glance-item" title="This year">
<i class="fas fa-fw fa-coins"></i>
<span><?= escapeHtml(billingMoney($row['made_year'], $currency)) ?> recorded this year <span class="text-body-secondary">&middot; <?= escapeHtml(billingMoney($amount * 12 / recurringInvoiceMonths($row['recurring_expense_frequency']), $currency)) ?> a year at this amount</span></span>

View File

@@ -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();

View File

@@ -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)'];
}
?>
<div class="row g-3" id="<?= $form_id ?>" data-recurring-expense-form>
@@ -134,7 +150,7 @@ while ($row = mysqli_fetch_assoc($sql)) {
<label class="form-label">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">
<select class="form-select select2" name="client_id" data-recurring-client>
<option value="0">- Not for 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>
@@ -143,6 +159,37 @@ while ($row = mysqli_fetch_assoc($sql)) {
</div>
</div>
<div class="col-12" data-recurring-billing <?= $form_client ? '' : 'hidden' ?>>
<div class="row g-2 align-items-start p-2 rounded border bg-body-tertiary mx-0">
<div class="col-md-5">
<label class="form-label small mb-1">For them</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-invoice-dollar"></i></span>
<select class="form-select" name="billing" data-recurring-billing-mode>
<option value="" <?= $form_billing === '' ? 'selected' : '' ?>>Our cost - not billed on</option>
<option value="bill" <?= $form_billing === 'bill' ? 'selected' : '' ?>>Billed on to them each time</option>
<option value="covered" <?= $form_billing === 'covered' ? 'selected' : '' ?>>Covered by their recurring invoice</option>
</select>
</div>
</div>
<div class="col-md-3" data-recurring-billing-for="bill">
<label class="form-label small mb-1">Markup</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-percent"></i></span>
<input type="text" class="form-control text-end" name="markup" inputmode="decimal" value="<?= rtrim(rtrim(number_format($form_markup, 2, '.', ''), '0'), '.') ?>" aria-label="Markup">
</div>
</div>
<div class="col-md-7" data-recurring-billing-for="covered">
<label class="form-label small mb-1">Recurring invoice</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-redo-alt"></i></span>
<select class="form-select" name="recurring_invoice_id" data-recurring-cover data-selected="<?= $form_covered_by ?>"></select>
</div>
</div>
<div class="col-12 small text-body-secondary" data-recurring-billing-note></div>
</div>
</div>
<div class="col-md-7">
<label class="form-label">Paid from <strong class="text-danger">*</strong></label>
<div class="input-group">
@@ -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 = <?= json_encode((object) $form_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();
<?php if (!$form_edit) { ?>
// Picking a vendor fills in what the last expense with them used, unless changed by hand
var defaults = <?= json_encode((object) $form_defaults) ?>;

View File

@@ -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'] ? '' : '<strong>' . escapeHtml($e['number']) . '</strong>: ') . '<strong>' . $e['expenses'] . ' expense' . ($e['expenses'] === 1 ? '' : 's') . '</strong> 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('<strong>' . count($made) . ' invoice' . (count($made) === 1 ? '' : 's') . '</strong> ' . (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 ? '<strong>' . escapeHtml($done[0]) . '</strong> is' : '<strong>' . count($done) . ' tickets</strong> are') . ' not billable now');
$what = [];
if ($done) {
$what[] = count($done) === 1 ? '<strong>' . escapeHtml($done[0]) . '</strong>' : '<strong>' . count($done) . ' tickets</strong>';
}
if ($done_expenses) {
$what[] = count($done_expenses) === 1 ? 'the expense <strong>' . escapeHtml($done_expenses[0]) . '</strong>' : '<strong>' . count($done_expenses) . ' expenses</strong>';
}
flashAlert(ucfirst(implode(' and ', $what)) . (count($done) + count($done_expenses) === 1 ? ' is' : ' are') . ' not billable now');
redirect();
}

View File

@@ -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 <strong>$count</strong> expense" . ($count === 1 ? '' : 's'));
flashAlert("Set " . escapeHtml($label) . " on <strong>$count</strong> expense" . ($count === 1 ? '' : 's')
. ($skipped ? " - $skipped left as " . ($skipped === 1 ? 'it was' : 'they were') . ($field === 'billable' && $value === 'yes' ? ' (on an invoice already, or not for a client)' : ' (on an invoice already)') : ''),
$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 <strong>" . escapeHtml(expenseLabel($row)) . "</strong> 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);
}

View File

@@ -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 <strong>$invoice_prefix$invoice_number</strong> 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 ? '<strong>1 expense</strong>' : "<strong>{$result['expenses']} expenses</strong>") . ' 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();

View File

@@ -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)) {

View File

@@ -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;
<td>
<?php if (intval($row['recurring_expense_client_id'])) { ?>
<div class="text-truncate" style="max-width: 10rem;"><a class="text-reset" href="<?= escapeHtml($filter_url(['client' => intval($row['recurring_expense_client_id'])])) ?>"><?= escapeHtml($row['client_name']) ?></a></div>
<?php if ($row['recurring_invoice_number'] !== null) { ?>
<div class="small text-success-emphasis text-truncate" style="max-width: 10rem;" title="Covered by their recurring invoice"><i class="fas fa-shield-alt me-1"></i>Covered by <?= escapeHtml($row['recurring_invoice_prefix'] . $row['recurring_invoice_number']) ?></div>
<?php } elseif (intval($row['recurring_expense_billable'])) { ?>
<div class="small text-warning-emphasis" title="Each one it records is billed on to them at <?= escapeHtml(rtrim(rtrim(number_format(floatval($row['recurring_expense_markup']), 2, '.', ''), '0'), '.')) ?>% markup"><i class="fas fa-file-invoice-dollar me-1"></i>Billed on</div>
<?php } ?>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>

View File

@@ -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 = [
</div>
<?php } ?>
<?php if ($costs) { ?>
<!-- What it costs us: the recurring expenses it covers, and the margin left -->
<div class="card mb-3">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-shopping-cart text-secondary me-2"></i>Costs <span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal ms-1"><?= count($costs['rows']) ?></span></h3>
<?php if ($can_add_costs) { ?>
<button type="button" class="btn btn-sm btn-outline-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/recurring_expense/recurring_expense_add.php?recurring_invoice_id=<?= $recurring_invoice_id ?>" title="A recurring expense this covers">
<i class="fas fa-plus me-1"></i>Add
</button>
<?php } ?>
</div>
<?php if ($costs['rows']) { ?>
<div class="list-group list-group-flush">
<?php foreach ($costs['rows'] as $cost) { ?>
<div class="list-group-item d-flex align-items-center gap-2">
<?= vendorTile($cost['vendor_name'] ?: 'Recurring', 'sm') ?>
<div class="flex-grow-1 min-w-0">
<a class="text-truncate d-block ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/recurring_expense/recurring_expense.php?id=<?= intval($cost['recurring_expense_id']) ?>"><?= escapeHtml($cost['vendor_name'] ?: 'No vendor') ?></a>
<div class="small text-body-secondary text-truncate"><?= escapeHtml(implode(' · ', array_filter([$cost['recurring_expense_description'], $cost['category_name']]))) ?: '&nbsp;' ?></div>
</div>
<div class="text-end text-nowrap small">
<div class="itflow-money <?= $cost['running'] ? '' : 'text-body-secondary text-decoration-line-through' ?>"><?= $money($cost['monthly']) ?></div>
<div class="text-body-secondary"><?= $cost['running'] ? 'a month' : ucfirst(recurringExpenseState($cost)) ?></div>
</div>
</div>
<?php } ?>
</div>
<div class="card-footer small">
<div class="d-flex justify-content-between gap-2">
<span class="text-body-secondary">Bills <?= $money($costs['revenue']) ?> a month before tax &middot; costs <?= $money($costs['cost']) ?></span>
<span class="fw-semibold text-nowrap <?= $costs['margin'] < 0 ? 'text-danger-emphasis' : 'text-success-emphasis' ?>"><?= $money($costs['margin']) ?><?= $costs['percent'] !== null ? ' &middot; ' . $costs['percent'] . '%' : '' ?></span>
</div>
</div>
<?php } else { ?>
<div class="card-body small text-body-secondary">
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.
</div>
<?php } ?>
</div>
<?php } ?>
<div class="card mb-3">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-wallet text-secondary me-2"></i>Autopay</h3>

View File

@@ -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) {
<div class="col-sm-6 col-xl-3">
<div class="itflow-billing-stat">
<div class="itflow-billing-stat-label"><i class="fas fa-file-invoice-dollar me-1"></i>To bill</div>
<div class="itflow-billing-stat-value <?= $total['value'] > 0 ? 'text-info-emphasis' : '' ?>"><?= $money($total['value']) ?></div>
<div class="itflow-billing-stat-note"><?= $client_view ? 'At ' . ($this_client && $this_client['rate'] > 0 ? $money($this_client['rate']) . ' an hour' . ($this_client['default_rate'] ? ', the default rate' : '') : 'no rate set') : 'At each client\'s hourly rate' ?></div>
<div class="itflow-billing-stat-value <?= $total['value'] + $total['expense_value'] > 0 ? 'text-info-emphasis' : '' ?>"><?= $money($total['value'] + $total['expense_value']) ?></div>
<div class="itflow-billing-stat-note">
<?php if ($total['expenses']) { ?>
<?= $money($total['value']) ?> of time &middot; <?= $money($total['expense_value']) ?> of expenses
<?php } else { ?>
<?= $client_view ? 'At ' . ($this_client && $this_client['rate'] > 0 ? $money($this_client['rate']) . ' an hour' . ($this_client['default_rate'] ? ', the default rate' : '') : 'no rate set') : 'At each client\'s hourly rate' ?>
<?php } ?>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
@@ -82,10 +105,10 @@ $hours_text = function ($hours) {
</div>
<div class="col-sm-6 col-xl-3">
<div class="itflow-billing-stat">
<div class="itflow-billing-stat-label"><i class="fas fa-life-ring me-1"></i>Tickets</div>
<div class="itflow-billing-stat-value"><?= $total['tickets'] ?></div>
<div class="itflow-billing-stat-label"><i class="fas fa-life-ring me-1"></i>Tickets<?= $total['expenses'] ? ' &amp; expenses' : '' ?></div>
<div class="itflow-billing-stat-value"><?= $total['tickets'] ?><?= $total['expenses'] ? ' <span class="text-body-secondary fw-normal">+</span> ' . $total['expenses'] : '' ?></div>
<div class="itflow-billing-stat-note">
<?= $client_view ? 'Resolved or closed, not invoiced' : count($clients) . ' client' . (count($clients) === 1 ? '' : 's') ?>
<?= $client_view ? ($total['expenses'] ? $total['tickets'] . ' ticket' . ($total['tickets'] === 1 ? '' : 's') . ', ' . $total['expenses'] . ' expense' . ($total['expenses'] === 1 ? '' : 's') : 'Resolved or closed, not invoiced') : count($clients) . ' client' . (count($clients) === 1 ? '' : 's') ?>
<?= $total['no_time'] ? ' &middot; <span class="text-warning-emphasis">' . $total['no_time'] . ' with no time logged</span>' : '' ?>
</div>
</div>
@@ -93,8 +116,8 @@ $hours_text = function ($hours) {
<div class="col-sm-6 col-xl-3">
<div class="itflow-billing-stat">
<div class="itflow-billing-stat-label"><i class="fas fa-hourglass-half me-1"></i>Waiting longest</div>
<div class="itflow-billing-stat-value <?= $total['oldest'] > 30 ? 'text-danger-emphasis' : '' ?>"><?= $total['tickets'] ? $total['oldest'] . ' day' . ($total['oldest'] === 1 ? '' : 's') : '-' ?></div>
<div class="itflow-billing-stat-note">Since the ticket was done</div>
<div class="itflow-billing-stat-value <?= $total['oldest'] > 30 ? 'text-danger-emphasis' : '' ?>"><?= $total['tickets'] || $total['expenses'] ? $total['oldest'] . ' day' . ($total['oldest'] === 1 ? '' : 's') : '-' ?></div>
<div class="itflow-billing-stat-note"><?= $total['expenses'] ? 'Since the ticket was done or the expense paid' : 'Since the ticket was done' ?></div>
</div>
</div>
</div>
@@ -103,7 +126,7 @@ $hours_text = function ($hours) {
<div class="card">
<div class="itflow-asset-empty py-5">
<i class="fas fa-user-clock fa-2x mb-2 opacity-50"></i>
<div>Unbilled Time needs both ticketing and accounting turned on, in Admin &gt; Settings &gt; Modules.</div>
<div>Unbilled Time needs accounting turned on<?= $with_expenses ? '' : ', and ticketing' ?>, in Admin &gt; Settings &gt; Modules.</div>
</div>
</div>
<?php } elseif (!$clients) { ?>
@@ -113,8 +136,8 @@ $hours_text = function ($hours) {
</div>
<div class="itflow-asset-empty py-5">
<i class="fas fa-check-circle fa-2x mb-2 opacity-50"></i>
<div>Nothing waiting to be billed<?= $client_view ? ' for ' . escapeHtml($client_name) : '' ?> - billable tickets that are done are all on an invoice.</div>
<div class="small mt-1">A ticket shows here once it is billable and resolved or closed.</div>
<div>Nothing waiting to be billed<?= $client_view ? ' for ' . escapeHtml($client_name) : '' ?> - billable tickets that are done<?= $with_expenses ? ', and billable expenses,' : '' ?> are all on an invoice.</div>
<div class="small mt-1">A ticket shows here once it is billable and resolved or closed<?= $with_expenses ? ', an expense once it is marked billable to its client' : '' ?>.</div>
</div>
</div>
<?php } else { ?>
@@ -127,14 +150,86 @@ $hours_text = function ($hours) {
<div class="row g-3">
<div class="col-xl-8">
<?php if ($client_view && !empty($this_client['expenses'])) { ?>
<!-- What we paid for them, to bill on -->
<div class="card mb-3">
<div class="card-header d-flex align-items-center">
<h3 class="card-title mb-0 me-auto"><i class="fas fa-fw fa-shopping-cart text-secondary me-2"></i>Expenses to bill <span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal ms-1"><?= count($this_client['expenses']) ?></span></h3>
<a class="btn btn-sm btn-outline-secondary" href="expenses.php?client=<?= $client_id ?>&amp;show=to_bill" title="In the expenses list"><i class="fas fa-shopping-cart me-1"></i>Expenses</a>
</div>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0 itflow-billing-table itflow-unbilled-table">
<thead class="text-nowrap table-light">
<tr>
<?php if ($can_bill_expenses) { ?>
<th class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" type="checkbox" checked data-unbilled-expense-all title="Tick or untick them all" aria-label="All expenses">
</div>
</th>
<?php } ?>
<th>Expense</th>
<th class="d-none d-md-table-cell">Paid</th>
<th class="text-end">Cost</th>
<th class="text-end">Bill</th>
<th class="text-end d-none d-sm-table-cell">Margin</th>
</tr>
</thead>
<tbody>
<?php foreach ($this_client['expenses'] as $expense_id => $expense) {
[$line_name] = expenseBillLine($expense); ?>
<tr data-unbilled-expense-row data-cost="<?= $expense['cost'] ?>">
<?php if ($can_bill_expenses) { ?>
<td class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="expense_ids[]" value="<?= $expense_id ?>" checked data-unbilled-expense-pick aria-label="Bill <?= escapeHtml(expenseLabel($expense)) ?>">
</div>
</td>
<?php } ?>
<td class="min-w-0">
<a href="#" class="ajax-modal" data-modal-size="lg" data-modal-url="modals/expense/expense.php?id=<?= $expense_id ?>"><?= escapeHtml($line_name) ?></a>
<div class="small text-body-secondary"><?= escapeHtml(implode(' · ', array_filter([$expense['vendor_name'], $expense['category_name']]))) ?></div>
</td>
<td class="text-nowrap d-none d-md-table-cell">
<div class="small"><?= escapeHtml($expense['expense_date']) ?></div>
<?= $waiting_pill($expense['waiting']) ?>
</td>
<td class="text-end text-nowrap">
<?= $money($expense['cost']) ?>
<div class="small text-body-secondary">+ <?= $markup_text($expense['expense_markup']) ?></div>
</td>
<td class="text-end itflow-unbilled-price">
<?php if ($can_bill_expenses) { ?>
<input type="text" class="form-control form-control-sm text-end" name="expense_price[<?= $expense_id ?>]" value="<?= number_format($expense['price'], 2, '.', '') ?>" inputmode="decimal" aria-label="Price to bill" data-unbilled-expense-price>
<?php } else { ?>
<?= $money($expense['price']) ?>
<?php } ?>
</td>
<td class="text-end text-nowrap small text-body-secondary d-none d-sm-table-cell" data-unbilled-expense-margin><?= escapeHtml(expenseMarginText($expense['price'], $expense['cost'])) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="card-footer small text-body-secondary">
At what it cost (less any refund) with its markup<?= $session_is_admin ? ' - <a href="/admin/settings_invoice.php#billable-expenses">the default markup</a>' : '' ?>. Change a price before billing; each goes on as a line of its own.
</div>
</div>
<?php } ?>
<div class="card">
<div class="card-header bg-dark py-2 d-flex align-items-center">
<h3 class="card-title mt-2 me-auto"><i class="fas fa-fw fa-user-clock me-2"></i>Unbilled Time<?= $client_view ? '' : ' by client' ?></h3>
<?php if ($client_view) { ?>
<a class="btn btn-dark btn-sm me-1" href="unbilled_time.php" title="Every client's unbilled time"><i class="fas fa-users me-1"></i>All clients</a>
<?php } ?>
<a class="btn btn-dark btn-sm" href="reports/tickets_unbilled.php<?= $client_view ? "?client_id=$client_id" : '' ?>" title="The Unbilled Work report"><i class="fas fa-chart-bar me-1"></i>Report</a>
<?php if ($with_time) { ?>
<a class="btn btn-dark btn-sm" href="reports/tickets_unbilled.php<?= $client_view ? "?client_id=$client_id" : '' ?>" title="The Unbilled Work report"><i class="fas fa-chart-bar me-1"></i>Report</a>
<?php } ?>
</div>
<?php if ($client_view && !$show_time) { ?>
<div class="card-body small text-body-secondary"><i class="fas fa-check-circle me-1"></i>No unbilled tickets for <?= escapeHtml($client_name) ?><?= $with_time ? ' - their billable tickets that are done are all on an invoice' : '' ?>.</div>
<?php } else { ?>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0 itflow-billing-table itflow-unbilled-table">
<thead class="text-nowrap table-light">
@@ -154,10 +249,15 @@ $hours_text = function ($hours) {
<th class="text-end d-none d-sm-table-cell">Amount</th>
<?php } else { ?>
<th>Client</th>
<th class="text-end">Tickets</th>
<th class="text-end d-none d-lg-table-cell">Logged</th>
<th class="text-end d-none d-sm-table-cell">Bill</th>
<th class="text-end d-none d-lg-table-cell">Rate</th>
<?php if ($with_time) { ?>
<th class="text-end">Tickets</th>
<th class="text-end d-none d-lg-table-cell">Logged</th>
<th class="text-end d-none d-sm-table-cell">Bill</th>
<th class="text-end d-none d-lg-table-cell">Rate</th>
<?php } ?>
<?php if ($with_expenses) { ?>
<th class="text-end <?= $with_time ? 'd-none d-md-table-cell' : '' ?>">Expenses</th>
<?php } ?>
<th class="text-end">Amount</th>
<th class="d-none d-md-table-cell">Oldest</th>
<th class="d-none d-sm-table-cell"></th>
@@ -202,7 +302,7 @@ $hours_text = function ($hours) {
} else {
foreach ($clients as $id => $c) {
$draft = $c['drafts'] ? reset($c['drafts']) : null; ?>
<tr data-unbilled-row data-value="<?= round($c['value'], 2) ?>" data-hours="<?= round($c['hours'], 2) ?>" data-tickets="<?= count($c['tickets']) ?>">
<tr data-unbilled-row data-value="<?= round($c['value'] + ($c['expense_value'] ?? 0), 2) ?>" data-hours="<?= round($c['hours'], 2) ?>" data-tickets="<?= count($c['tickets']) ?>" data-expenses="<?= count($c['expenses'] ?? []) ?>">
<?php if ($can_edit) { ?>
<td class="checkbox-column border-end">
<div class="form-check">
@@ -218,22 +318,36 @@ $hours_text = function ($hours) {
</div>
<?php } ?>
</td>
<td class="text-end">
<?= count($c['tickets']) ?>
<?php if ($c['no_time']) { ?>
<div class="small text-warning-emphasis text-nowrap" title="No time logged - they go on the invoice with no charge unless you open the client and type the hours"><?= $c['no_time'] ?> with no time</div>
<?php } ?>
</td>
<td class="text-end text-nowrap d-none d-lg-table-cell"><?= billingDuration($c['seconds']) ?></td>
<td class="text-end text-nowrap d-none d-sm-table-cell"><?= $hours_text($c['hours']) ?></td>
<td class="text-end text-nowrap d-none d-lg-table-cell">
<?php if ($c['rate'] > 0) { ?>
<?= $money($c['rate']) ?><?= $c['default_rate'] ? '<div class="small text-body-tertiary" title="The client has no rate of its own">default</div>' : '' ?>
<?php } else { ?>
<span class="small text-warning-emphasis" title="Set an hourly rate on the client, or a default in Admin > Settings > Defaults">No rate</span>
<?php } ?>
</td>
<td class="text-end text-nowrap fw-semibold"><?= $money($c['value']) ?></td>
<?php if ($with_time) { ?>
<td class="text-end">
<?= count($c['tickets']) ?: '<span class="text-body-secondary">-</span>' ?>
<?php if ($c['no_time']) { ?>
<div class="small text-warning-emphasis text-nowrap" title="No time logged - they go on the invoice with no charge unless you open the client and type the hours"><?= $c['no_time'] ?> with no time</div>
<?php } ?>
</td>
<td class="text-end text-nowrap d-none d-lg-table-cell"><?= $c['tickets'] ? billingDuration($c['seconds']) : '<span class="text-body-secondary">-</span>' ?></td>
<td class="text-end text-nowrap d-none d-sm-table-cell"><?= $c['tickets'] ? $hours_text($c['hours']) : '<span class="text-body-secondary">-</span>' ?></td>
<td class="text-end text-nowrap d-none d-lg-table-cell">
<?php if (!$c['tickets']) { ?>
<span class="text-body-secondary">-</span>
<?php } elseif ($c['rate'] > 0) { ?>
<?= $money($c['rate']) ?><?= $c['default_rate'] ? '<div class="small text-body-tertiary" title="The client has no rate of its own">default</div>' : '' ?>
<?php } else { ?>
<span class="small text-warning-emphasis" title="Set an hourly rate on the client, or a default in Admin > Settings > Defaults">No rate</span>
<?php } ?>
</td>
<?php } ?>
<?php if ($with_expenses) { ?>
<td class="text-end text-nowrap <?= $with_time ? 'd-none d-md-table-cell' : '' ?>">
<?php if ($c['expenses']) { ?>
<?= $money($c['expense_value']) ?>
<div class="small text-body-secondary"><?= count($c['expenses']) ?> expense<?= count($c['expenses']) === 1 ? '' : 's' ?></div>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<?php } ?>
<td class="text-end text-nowrap fw-semibold"><?= $money($c['value'] + ($c['expense_value'] ?? 0)) ?></td>
<td class="text-nowrap d-none d-md-table-cell"><?= $waiting_pill($c['oldest']) ?></td>
<td class="text-end d-none d-sm-table-cell">
<a class="btn btn-sm btn-outline-secondary text-nowrap" href="unbilled_time.php?client_id=<?= $id ?>">Review</a>
@@ -244,11 +358,15 @@ $hours_text = function ($hours) {
</tbody>
</table>
</div>
<div class="card-footer small text-body-secondary">
Time is rounded <?= escapeHtml(billingTimeRulesText($rules)) ?>, per ticket<?= $session_is_admin ? ' - <a href="/admin/settings_invoice.php#billing-time">change how</a>' : '' ?>.
<?= $client_view ? 'Change the hours before billing - a ticket left at 0 goes on the invoice with no charge.' : 'Review a client to change the hours on its tickets first.' ?>
</div>
<?php if ($with_time) { ?>
<div class="card-footer small text-body-secondary">
Time is rounded <?= escapeHtml(billingTimeRulesText($rules)) ?>, per ticket<?= $session_is_admin ? ' - <a href="/admin/settings_invoice.php#billing-time">change how</a>' : '' ?>.
<?= $client_view ? 'Change the hours before billing - a ticket left at 0 goes on the invoice with no charge.' : 'Review a client to change the hours on its tickets' . ($with_expenses ? ' and the prices of its expenses' : '') . ' first.' ?>
</div>
<?php } ?>
<?php } ?>
</div>
</div>
<?php if ($can_edit) { ?>
@@ -316,6 +434,7 @@ $hours_text = function ($hours) {
</datalist>
</div>
</div>
<?php if ($show_time) { ?>
<div class="col-12">
<label class="form-label">Line</label>
<div class="input-group">
@@ -323,7 +442,8 @@ $hours_text = function ($hours) {
<input type="text" class="form-control" name="item_name" maxlength="200" value="<?= escapeHtml($rules['item_name']) ?>" required>
</div>
</div>
<?php if ($client_view) { ?>
<?php } ?>
<?php if ($client_view && $show_time) { ?>
<div class="col-sm-6 col-xl-12">
<label class="form-label">Rate <strong class="text-danger">*</strong></label>
<div class="input-group">
@@ -345,6 +465,7 @@ $hours_text = function ($hours) {
</select>
</div>
</div>
<?php if ($show_time) { ?>
<div class="col-12">
<label class="form-label">Lines</label>
<div class="input-group">
@@ -354,7 +475,11 @@ $hours_text = function ($hours) {
<option value="one">One line for all of them</option>
</select>
</div>
<?php if ($total['expenses']) { ?>
<div class="form-text">Expenses go on with a line each, at their price<?= $client_view ? '' : ' - cost with its markup' ?>.</div>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
<div class="card-footer">
@@ -368,7 +493,7 @@ $hours_text = function ($hours) {
</button>
<?php if ($client_view) { ?>
<button type="submit" name="unbilled_write_off" value="1" class="btn btn-outline-danger confirm-link" formnovalidate
data-confirm-title="Mark them not billable?" data-confirm-text="The ticked tickets stop being billable and leave this list. Their time stays logged on them, and each one's history says it." data-confirm-button="Not billable">
data-confirm-title="Mark them not billable?" data-confirm-text="The ticked tickets<?= $total['expenses'] ? ' and expenses' : '' ?> stop being billable and leave this list. <?= $total['tickets'] ? "Their time stays logged on them, and each one's history says it." : 'They stay in the expenses as our cost.' ?>" data-confirm-button="Not billable">
<i class="fas fa-ban me-2"></i>Not billable
</button>
<?php } ?>

View File

@@ -6327,3 +6327,21 @@ a.itflow-billing-stat:hover {
color: var(--bs-secondary-color);
text-align: center;
}
/* Unbilled Time - an expense's price box, and its row ticks like a ticket's */
.itflow-unbilled-table tbody tr[data-unbilled-expense-row] {
cursor: pointer;
}
.itflow-unbilled-price {
width: 7.5rem;
}
.itflow-unbilled-price .form-control {
min-width: 5.5rem;
}
@media (max-width: 575.98px) {
.itflow-unbilled-price {
width: 6rem;
}
.itflow-unbilled-price .form-control {
min-width: 4.5rem;
}
}

11
db.sql
View File

@@ -1356,7 +1356,12 @@ CREATE TABLE `expenses` (
`expense_account_id` int(11) DEFAULT NULL,
`expense_refund_of_id` int(11) DEFAULT NULL,
`expense_recurring_expense_id` int(11) DEFAULT NULL,
PRIMARY KEY (`expense_id`)
`expense_billable` tinyint(1) NOT NULL DEFAULT 0,
`expense_markup` decimal(7,2) NOT NULL DEFAULT 0.00,
`expense_invoice_id` int(11) DEFAULT NULL,
`expense_invoice_item_id` int(11) DEFAULT NULL,
PRIMARY KEY (`expense_id`),
KEY `expense_invoice_id` (`expense_invoice_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -2094,6 +2099,9 @@ CREATE TABLE `recurring_expenses` (
`recurring_expense_client_id` int(11) NOT NULL DEFAULT 0,
`recurring_expense_category_id` int(11) NOT NULL,
`recurring_expense_account_id` int(11) NOT NULL,
`recurring_expense_billable` tinyint(1) NOT NULL DEFAULT 0,
`recurring_expense_markup` decimal(7,2) NOT NULL DEFAULT 0.00,
`recurring_expense_recurring_invoice_id` int(11) DEFAULT NULL,
PRIMARY KEY (`recurring_expense_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@@ -2513,6 +2521,7 @@ CREATE TABLE `settings` (
`config_time_rounding` varchar(10) NOT NULL DEFAULT 'nearest',
`config_time_minimum` int(11) NOT NULL DEFAULT 0,
`config_time_item_name` varchar(200) NOT NULL DEFAULT 'Support [Hourly]',
`config_expense_markup` decimal(7,2) NOT NULL DEFAULT 0.00,
`config_project_prefix` varchar(200) NOT NULL DEFAULT 'PRJ-',
`config_project_next_number` int(11) NOT NULL DEFAULT 1,
`config_invoice_prefix` varchar(200) DEFAULT NULL,

View File

@@ -354,9 +354,10 @@ function billingItemDelete($type, $doc_id, $item_id) {
'invoice_id' => $doc_id, 'item_id' => $item_id, 'note' => billingNumber('invoice', billingRow('invoice', $doc_id, false)) . ' - line taken off',
]);
}
// Assets made from the line stay, still bought on the invoice
// Assets made from the line stay, still bought on the invoice; an expense billed on it is to bill again
if ($type === 'invoice') {
mysqli_query($mysqli, "UPDATE assets SET asset_invoice_item_id = 0 WHERE asset_invoice_id = $doc_id AND asset_invoice_item_id = $item_id");
mysqli_query($mysqli, "UPDATE expenses SET expense_invoice_id = NULL, expense_invoice_item_id = NULL WHERE expense_invoice_id = $doc_id AND expense_invoice_item_id = $item_id");
}
billingRecalc($type, $doc_id);
return $item;

View File

@@ -84,6 +84,15 @@ function clientOverviewAttention($client_id, $access, $renewals) {
'url' => "/agent/unbilled_time.php?client_id=$client_id",
];
}
if ($access['financial']) {
$to_bill = expenseUnbilledCount($client_id);
$items[] = [
'count' => $to_bill['count'],
'label' => 'Expenses to bill', 'icon' => 'shopping-cart', 'tone' => 'info',
'detail' => $to_bill['count'] ? dashboardMoney($to_bill['value']) . ' to bill on' : null,
'url' => "/agent/unbilled_time.php?client_id=$client_id",
];
}
}
if ($access['docs']) {
@@ -514,7 +523,9 @@ function clientOverviewActivity($client_id, $limit = 6) {
* the clients list and the old client header. Paid this year is cash in
* (invoice payments plus client revenues), compared with the same days last
* year. Unbilled is what Unbilled Time has for the client - billable tickets
* done and on no invoice, the time logged on them and what it comes to.
* done and on no invoice, the time logged on them and what it comes to - and,
* for agents who can see expenses, the expenses to bill on to them and what
* they come to with their markup.
*/
function clientOverviewMoney($client_id, $balance, $recurring_monthly) {
$year_start = date('Y-01-01');
@@ -536,6 +547,7 @@ function clientOverviewMoney($client_id, $balance, $recurring_monthly) {
- dashboardSum("SELECT SUM(payment_amount) FROM payments JOIN invoices ON payment_invoice_id = invoice_id WHERE $overdue_where");
$unbilled = billingUnbilledByClient($client_id)[intval($client_id)] ?? null;
$to_bill = lookupUserPermission('module_financial') >= 1 ? expenseUnbilledCount($client_id) : ['count' => 0, 'value' => 0.0];
return [
'balance' => $balance,
@@ -546,6 +558,8 @@ function clientOverviewMoney($client_id, $balance, $recurring_monthly) {
'unbilled_tickets' => $unbilled ? count($unbilled['tickets']) : 0,
'unbilled_seconds' => $unbilled ? intval($unbilled['seconds']) : 0,
'unbilled_value' => $unbilled ? floatval($unbilled['value']) : 0.0,
'unbilled_expenses' => $to_bill['count'],
'unbilled_expense_value' => $to_bill['value'],
];
}

View File

@@ -294,6 +294,16 @@ function dashboardAttention($access) {
'url' => '/agent/unbilled_time.php',
];
}
// What we paid for clients to bill on to them, on no invoice yet
if ($access['financial']) {
$to_bill = expenseUnbilledCount();
$items[] = [
'count' => $to_bill['count'],
'label' => 'Expenses to bill', 'icon' => 'shopping-cart', 'tone' => 'info',
'detail' => $to_bill['count'] ? dashboardMoney($to_bill['value']) . ' to bill on' : null,
'url' => '/agent/expenses.php?show=to_bill',
];
}
}
if ($access['support']) {

View File

@@ -38,6 +38,7 @@ function expenseRow($expense_id, $scoped = true) {
category_name, category_color, category_icon, category_archived_at, account_name, account_archived_at, account_currency_code,
client_name, client_abbreviation, user_name AS created_by_name, transfer_id,
recurring_expense_frequency, recurring_expense_amount, recurring_expense_currency_code,
invoice_prefix, invoice_number, invoice_status, item_subtotal AS billed_subtotal,
refunded.expense_date AS refund_of_date, refunded.expense_amount AS refund_of_amount, refunded.expense_description AS refund_of_description,
(SELECT COALESCE(SUM(-r.expense_amount), 0) FROM expenses AS r WHERE r.expense_refund_of_id = expenses.expense_id) AS refunded_amount,
(SELECT COUNT(*) FROM expenses AS r WHERE r.expense_refund_of_id = expenses.expense_id) AS refund_count
@@ -50,6 +51,8 @@ function expenseRow($expense_id, $scoped = true) {
LEFT JOIN transfers ON transfer_expense_id = expenses.expense_id
LEFT JOIN expenses AS refunded ON refunded.expense_id = expenses.expense_refund_of_id
LEFT JOIN recurring_expenses ON recurring_expense_id = expenses.expense_recurring_expense_id
LEFT JOIN invoices ON invoice_id = expenses.expense_invoice_id
LEFT JOIN invoice_items ON item_id = expenses.expense_invoice_item_id
WHERE expenses.expense_id = $expense_id $scope
LIMIT 1"));
return $row ?: null;
@@ -70,6 +73,8 @@ function expenseShows() {
'' => ['label' => 'All', 'where' => ''],
'client' => ['label' => 'For a client', 'icon' => 'fa-user', 'where' => 'expense_client_id > 0', 'title' => 'Filed against a client - their direct costs'],
'no_receipt' => ['label' => 'No receipt', 'icon' => 'fa-paperclip', 'where' => "COALESCE(expense_receipt, '') = '' AND expense_amount > 0", 'title' => 'No receipt attached yet'],
'to_bill' => ['label' => 'To bill', 'icon' => 'fa-file-invoice-dollar', 'where' => expenseUnbilledSql(), 'title' => 'Billable to a client, and on no invoice yet'],
'billed' => ['label' => 'Billed', 'icon' => 'fa-check-circle', 'where' => 'expense_invoice_id IS NOT NULL', 'title' => 'Billed on to a client on an invoice'],
'refunds' => ['label' => 'Refunds', 'icon' => 'fa-undo-alt', 'where' => 'expense_amount < 0', 'title' => 'Money that came back - refunds and credits'],
];
}
@@ -314,9 +319,26 @@ function expenseSave(array $in, $expense_id = 0, &$error = '') {
$reference = mb_substr(trim((string) ($in['reference'] ?? '')), 0, 200);
$description = trim((string) ($in['description'] ?? ''));
// Billed on to the client - only an expense for a client, not a refund. One
// already on an invoice stays billed, to that client, until it comes off it.
$billed = $existing && !empty($existing['expense_invoice_id']);
if ($billed && $client_id !== intval($existing['expense_client_id'])) {
$error = 'It is billed on an invoice for ' . $existing['client_name'] . ' - take it off that invoice before moving it to another client';
return 0;
}
$billable = $billed ? 1 : intval(!empty($in['billable']) && $client_id > 0 && $amount > 0);
$markup_text = str_replace(['%', ' '], '', trim((string) ($in['markup'] ?? '')));
$markup = $markup_text === '' ? ($existing ? floatval($existing['expense_markup']) : expenseMarkupDefault()) : floatval($markup_text);
if ($billable && ($markup_text !== '' && !is_numeric($markup_text) || $markup < 0 || $markup > 1000)) {
$error = 'The markup is a percent, from 0 to 1000';
return 0;
}
$markup = round(max(0, min(1000, $markup)), 2);
$set = "expense_date = '$date', expense_amount = $amount, expense_vendor_id = $vendor, expense_category_id = $category,
expense_account_id = $account, expense_client_id = $client_id, expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
expense_reference = '" . escapeSql($reference) . "', expense_description = '" . escapeSql($description) . "'";
expense_reference = '" . escapeSql($reference) . "', expense_description = '" . escapeSql($description) . "',
expense_billable = $billable, expense_markup = $markup";
if ($existing) {
mysqli_query($mysqli, "UPDATE expenses SET $set WHERE expense_id = $expense_id");
@@ -498,7 +520,8 @@ function recurringExpenseRow($recurring_expense_id, $scoped = true) {
$scope = $scoped ? clientScopeSql('recurring_expense_client_id') : '';
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT recurring_expenses.*, vendor_name, vendor_description, vendor_archived_at,
category_name, category_color, category_icon, category_archived_at, account_name, account_archived_at, account_currency_code,
client_name, client_abbreviation,
client_name, client_abbreviation, recurring_invoice_prefix, recurring_invoice_number, recurring_invoice_amount, recurring_invoice_frequency,
recurring_invoice_status, recurring_invoice_archived_at,
(SELECT COUNT(*) FROM expenses WHERE expense_recurring_expense_id = $id) AS made_count,
(SELECT COALESCE(SUM(expense_amount), 0) FROM expenses WHERE expense_recurring_expense_id = $id AND YEAR(expense_date) = YEAR(CURDATE())) AS made_year
FROM recurring_expenses
@@ -506,6 +529,7 @@ function recurringExpenseRow($recurring_expense_id, $scoped = true) {
LEFT JOIN categories ON category_id = recurring_expense_category_id
LEFT JOIN accounts ON account_id = recurring_expense_account_id
LEFT JOIN clients ON client_id = recurring_expense_client_id
LEFT JOIN recurring_invoices ON recurring_invoice_id = recurring_expense_recurring_invoice_id
WHERE recurring_expense_id = $id $scope
LIMIT 1"));
return $row ?: null;
@@ -712,6 +736,25 @@ function recurringExpenseSave(array $in, $recurring_expense_id = 0, &$error = ''
$reference = mb_substr(trim((string) ($in['reference'] ?? '')), 0, 255);
$description = trim((string) ($in['description'] ?? ''));
// For a client: billed on as each one is recorded, or covered by one of their recurring invoices
$billing = $client_id ? (string) ($in['billing'] ?? '') : '';
$billable = $billing === 'bill' ? 1 : 0;
$markup_text = str_replace(['%', ' '], '', trim((string) ($in['markup'] ?? '')));
$markup = $markup_text === '' ? ($existing ? floatval($existing['recurring_expense_markup']) : expenseMarkupDefault()) : floatval($markup_text);
if ($billable && ($markup_text !== '' && !is_numeric($markup_text) || $markup < 0 || $markup > 1000)) {
$error = 'The markup is a percent, from 0 to 1000';
return 0;
}
$markup = round(max(0, min(1000, $markup)), 2);
$covered_by = 0;
if ($billing === 'covered') {
$covered_by = intval($in['recurring_invoice_id'] ?? 0);
if (!isset(recurringExpenseCoverOptions($client_id, $existing ? intval($existing['recurring_expense_recurring_invoice_id']) : 0)[$covered_by])) {
$error = "Pick the client's recurring invoice that covers it";
return 0;
}
}
// The day it runs on follows the next date when that is set or moved
$anchor = (!$existing || $next !== (string) $existing['recurring_expense_next_date']) ? intval(substr($next, 8, 2)) : intval($existing['recurring_expense_anchor_day']);
$ended = $end !== '' && $next > $end;
@@ -729,7 +772,8 @@ function recurringExpenseSave(array $in, $recurring_expense_id = 0, &$error = ''
recurring_expense_next_date = '$next', recurring_expense_end_date = " . ($end === '' ? 'NULL' : "'$end'") . ", recurring_expense_status = $status,
recurring_expense_category_id = $category, recurring_expense_account_id = $account, recurring_expense_client_id = $client_id,
recurring_expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
recurring_expense_reference = '" . escapeSql($reference) . "', recurring_expense_description = '" . escapeSql($description) . "'";
recurring_expense_reference = '" . escapeSql($reference) . "', recurring_expense_description = '" . escapeSql($description) . "',
recurring_expense_billable = $billable, recurring_expense_markup = $markup, recurring_expense_recurring_invoice_id = " . ($covered_by ?: 'NULL');
if ($existing) {
mysqli_query($mysqli, "UPDATE recurring_expenses SET $set WHERE recurring_expense_id = $id");
@@ -780,7 +824,8 @@ function recurringExpenseRecord($recurring_expense_id, $by_user_id = 0, $run = n
expense_client_id = " . intval($row['recurring_expense_client_id']) . ", expense_category_id = " . intval($row['recurring_expense_category_id']) . ",
expense_account_id = " . intval($row['recurring_expense_account_id']) . ", expense_payment_method = " . ($method === '' ? 'NULL' : "'" . escapeSql($method) . "'") . ",
expense_reference = '" . escapeSql($row['recurring_expense_reference']) . "', expense_description = '" . escapeSql($row['recurring_expense_description']) . "',
expense_created_by = " . intval($by_user_id) . ", expense_recurring_expense_id = $id");
expense_created_by = " . intval($by_user_id) . ", expense_recurring_expense_id = $id,
expense_billable = " . (intval($row['recurring_expense_billable']) && intval($row['recurring_expense_client_id']) ? 1 : 0) . ", expense_markup = " . floatval($row['recurring_expense_markup']));
$expense_id = mysqli_insert_id($mysqli);
$label = recurringExpenseLabel($row);
@@ -830,3 +875,462 @@ function recurringExpenseLabel(array $row) {
. strtolower(recurringInvoiceFrequencies()[$row['recurring_expense_frequency']] ?? 'monthly')
. ($description !== '' ? ' - ' . mb_strimwidth($description, 0, 60, '...') : ''));
}
/* ------------------------------------------------- Billing expenses on */
/*
* An expense for a client can be billed on to them: billable, with a markup
* on its cost (what it came to, less anything refunded). Until it is on an
* invoice it waits in Unbilled Time and the invoice's Expenses card; once
* billed it points at the invoice and line (expense_invoice_id,
* expense_invoice_item_id). Taking the line off - or deleting the invoice -
* makes it to bill again. A client's recurring expense can be billed on as
* each one is recorded, or be covered by one of their recurring invoices,
* which then shows its cost against what it bills.
*/
/** The markup a billable expense starts with, as a percent - Admin > Settings > Invoice. */
function expenseMarkupDefault() {
global $mysqli;
static $markup = null;
if ($markup !== null) {
return $markup;
}
try {
$markup = floatval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_expense_markup FROM settings WHERE company_id = 1"))[0] ?? 0);
} catch (mysqli_sql_exception $e) {
$markup = 0.0;
}
return $markup;
}
/** What a cost bills at with its markup, to the cent. */
function expenseBillPrice($cost, $markup) {
return round(floatval($cost) * (1 + floatval($markup) / 100), 2);
}
/** The SQL that makes an expense to bill: billable, for a client, with a vendor and an amount, on no invoice yet. */
function expenseUnbilledSql() {
return "expense_billable = 1 AND expense_invoice_id IS NULL AND expense_client_id > 0 AND expense_vendor_id > 0 AND expense_amount > 0 AND expense_archived_at IS NULL";
}
/**
* Expenses to bill - one client's ($client_id) or every client the agent
* can open (0), optionally only $ids - oldest first. Each with its vendor,
* category and client, its cost (less refunds), the price its markup makes
* of that, and the days since it was paid. Fully refunded ones are left out.
*/
function expenseUnbilled($client_id = 0, array $ids = []) {
global $mysqli;
$client_id = intval($client_id);
$ids = array_filter(array_map('intval', $ids));
$where = expenseUnbilledSql() . ($client_id ? " AND expense_client_id = $client_id" : '') . ($ids ? ' AND expense_id IN (' . implode(',', $ids) . ')' : '')
. ' ' . clientScopeSql('expense_client_id');
$rows = [];
$sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, client_name, client_abbreviation,
(SELECT COALESCE(SUM(-r.expense_amount), 0) FROM expenses AS r WHERE r.expense_refund_of_id = expenses.expense_id) AS refunded,
DATEDIFF(CURDATE(), expense_date) AS waiting
FROM expenses
JOIN clients ON client_id = expense_client_id
LEFT JOIN vendors ON vendor_id = expense_vendor_id
LEFT JOIN categories ON category_id = expense_category_id
WHERE $where
ORDER BY client_name ASC, expense_date ASC, expense_id ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['cost'] = round(floatval($row['expense_amount']) - floatval($row['refunded']), 2);
if ($row['cost'] <= 0) {
continue;
}
$row['price'] = expenseBillPrice($row['cost'], $row['expense_markup']);
$row['waiting'] = max(0, intval($row['waiting']));
$rows[intval($row['expense_id'])] = $row;
}
return $rows;
}
/** The same, by client - each with its expenses, their cost and price, and how long the oldest has waited. */
function expenseUnbilledByClient($client_id = 0) {
$clients = [];
foreach (expenseUnbilled($client_id) as $id => $expense) {
$cid = intval($expense['expense_client_id']);
if (!isset($clients[$cid])) {
$clients[$cid] = ['client_id' => $cid, 'client_name' => $expense['client_name'], 'client_abbreviation' => $expense['client_abbreviation'],
'expenses' => [], 'cost' => 0.0, 'value' => 0.0, 'oldest' => 0];
}
$clients[$cid]['expenses'][$id] = $expense;
$clients[$cid]['cost'] += $expense['cost'];
$clients[$cid]['value'] += $expense['price'];
$clients[$cid]['oldest'] = max($clients[$cid]['oldest'], $expense['waiting']);
}
return $clients;
}
/** How many expenses are waiting to be billed, and what they come to - every client the agent can open, or one - for the menu, the dashboard and the client's overview. */
function expenseUnbilledCount($client_id = 0) {
global $mysqli;
$client_id = intval($client_id);
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*), COALESCE(SUM(ROUND((expense_amount - refunded) * (1 + expense_markup / 100), 2)), 0)
FROM (SELECT expense_amount, expense_markup,
(SELECT COALESCE(SUM(-r.expense_amount), 0) FROM expenses AS r WHERE r.expense_refund_of_id = expenses.expense_id) AS refunded
FROM expenses
WHERE " . expenseUnbilledSql() . ($client_id ? " AND expense_client_id = $client_id" : '') . ' ' . clientScopeSql('expense_client_id') . ") AS waiting
WHERE expense_amount - refunded > 0"));
return ['count' => intval($row[0]), 'value' => round(floatval($row[1]), 2)];
}
/** The invoice line an expense goes on as - [name, description]. Raw. */
function expenseBillLine(array $expense) {
$lines = preg_split('/\R/', trim((string) $expense['expense_description']));
$name = trim((string) array_shift($lines));
if ($name === '') {
$name = trim((string) ($expense['category_name'] ?? '')) ?: 'Expense';
}
$description = implode(' - ', array_filter([
$expense['vendor_name'] ?? '',
date('m/d/Y', strtotime((string) $expense['expense_date'])),
trim((string) $expense['expense_reference']) !== '' ? '#' . trim((string) $expense['expense_reference']) : '',
]));
$rest = trim(implode("\n", $lines));
return [mb_substr($name, 0, 200), $rest !== '' ? "$rest\n$description" : $description];
}
/**
* Bill expenses on an invoice, a line each. $prices is expense id => price
* (null: the cost with its markup). Only the client's expenses still to
* bill are taken, and each is claimed first, so two agents can't bill one
* twice. $opts:
* invoice_id one of the client's invoices whose lines can change, or 0 for a new draft
* date, category_id, scope for a new draft
* tax_id the tax on the lines
* by who, for the history and audit log
* Returns [invoice_id, number, new, expenses (count), amount, cost, lines], or null with $error.
*/
function expenseBillInvoice($client_id, array $prices, array $opts, &$error = '') {
global $mysqli;
$error = '';
$client_id = intval($client_id);
$by = (string) ($opts['by'] ?? 'ITFlow');
$expenses = $prices ? expenseUnbilled($client_id, array_keys($prices)) : [];
if (!$client_id || !$expenses) {
$error = 'Nothing to bill - those expenses are already on an invoice, or no longer billable.';
return null;
}
$bill = [];
foreach ($expenses as $id => $expense) {
$value = $prices[$id] ?? null;
$price = ($value === null || trim((string) $value) === '') ? $expense['price'] : billingNumberInput($value);
if ($price === null || $price < 0 || $price >= 1e9) {
$error = 'The price for ' . ($expense['vendor_name'] ?: 'an expense') . ' on ' . $expense['expense_date'] . ' has to be a number, zero or more.';
return null;
}
$bill[$id] = round($price, 2);
}
$tax_id = intval($opts['tax_id'] ?? 0);
if ($tax_id && !mysqli_num_rows(mysqli_query($mysqli, "SELECT tax_id FROM taxes WHERE tax_id = $tax_id"))) {
$error = 'That tax no longer exists.';
return null;
}
$invoice_id = intval($opts['invoice_id'] ?? 0);
$new = false;
if ($invoice_id) {
$invoice = billingRow('invoice', $invoice_id);
if (!$invoice || intval($invoice['client_id']) !== $client_id || !billingCanEditItems('invoice', $invoice)) {
$error = "That invoice isn't one of the client's you can still add to.";
return null;
}
} else {
$invoice_id = billingInvoiceCreate($client_id, $opts['date'] ?? '', $opts['category_id'] ?? 0, $opts['scope'] ?? '', $by);
if (!$invoice_id) {
$error = "The invoice couldn't be made.";
return null;
}
$new = true;
}
$number = billingNumber('invoice', billingRow('invoice', $invoice_id, false));
// Claim them - only those still to bill go on
$in = implode(',', array_keys($bill));
mysqli_query($mysqli, "UPDATE expenses SET expense_invoice_id = $invoice_id WHERE expense_id IN ($in) AND expense_client_id = $client_id AND " . expenseUnbilledSql());
$claimed = [];
$sql = mysqli_query($mysqli, "SELECT expense_id FROM expenses WHERE expense_invoice_id = $invoice_id AND expense_id IN ($in) AND expense_invoice_item_id IS NULL");
while ($row = mysqli_fetch_row($sql)) {
$claimed[intval($row[0])] = true;
}
if (!$claimed) {
if ($new) {
mysqli_query($mysqli, "DELETE FROM history WHERE history_invoice_id = $invoice_id");
mysqli_query($mysqli, "DELETE FROM invoices WHERE invoice_id = $invoice_id");
}
$error = 'Nothing to bill - someone else billed those expenses just now.';
return null;
}
$lines = 0;
$amount = 0.0;
$cost = 0.0;
foreach ($bill as $id => $price) {
if (!isset($claimed[$id])) {
continue;
}
$expense = $expenses[$id];
[$name, $description] = expenseBillLine($expense);
$item_id = billingItemSave('invoice', $invoice_id, ['name' => $name, 'description' => $description, 'qty' => 1, 'price' => $price, 'tax_id' => $tax_id], 0, $line_error);
if (!$item_id) {
mysqli_query($mysqli, "UPDATE expenses SET expense_invoice_id = NULL WHERE expense_id = $id AND expense_invoice_id = $invoice_id");
continue;
}
mysqli_query($mysqli, "UPDATE expenses SET expense_invoice_item_id = " . intval($item_id) . " WHERE expense_id = $id");
$lines++;
$amount += $price;
$cost += $expense['cost'];
logAudit('Expense', 'Bill', escapeSql("$by billed " . expenseLabel($expense) . " on invoice $number at " . billingMoney($price, $expense['expense_currency_code'])), $client_id, $id);
}
billingRecalc('invoice', $invoice_id);
$invoice = billingRow('invoice', $invoice_id, false);
$currency = (string) $invoice['invoice_currency_code'];
$what = $lines === 1 ? '1 expense' : "$lines expenses";
billingLog('invoice', $invoice_id, $invoice['invoice_status'], ucfirst($what) . " billed by $by - " . billingMoney($amount, $currency) . ' on ' . billingMoney($cost, $currency) . ' of cost');
logAudit('Invoice', $new ? 'Create' : 'Edit', escapeSql("$by billed $what on invoice $number - " . billingMoney($amount, $currency)), $client_id, $invoice_id);
if ($new) {
triggerCustomAction('invoice_create', $invoice_id);
}
return ['invoice_id' => $invoice_id, 'number' => $number, 'new' => $new, 'expenses' => $lines, 'amount' => round($amount, 2), 'cost' => round($cost, 2), 'lines' => $lines];
}
/**
* Can an expense come off an invoice in this status: while its lines can
* change, or once it is cancelled - not once it is paid or non-billable.
*/
function expenseCanUnbill($invoice_status) {
return $invoice_status !== null && lookupUserPermission('module_sales') >= 2 && !in_array($invoice_status, ['Paid', 'Non-Billable'], true);
}
/**
* Take an expense off the invoice it was billed on - its line comes off,
* and it is to bill again. On a cancelled invoice the line stays, as the
* invoice was, and only the link goes. Refused once the invoice is paid or
* non-billable. The invoice number it came off, or '' with $error.
*/
function expenseUnbill($expense_id, &$error = '') {
global $mysqli;
$error = '';
$row = expenseRow($expense_id);
if (!$row || !$row['expense_invoice_id']) {
$error = "That expense isn't on an invoice";
return '';
}
$invoice = billingRow('invoice', intval($row['expense_invoice_id']), false);
$id = intval($row['expense_id']);
if (!$invoice) {
mysqli_query($mysqli, "UPDATE expenses SET expense_invoice_id = NULL, expense_invoice_item_id = NULL WHERE expense_id = $id");
return 'an invoice since deleted';
}
$number = billingNumber('invoice', $invoice);
if (!expenseCanUnbill($invoice['invoice_status'])) {
$error = "$number is " . strtolower($invoice['invoice_status']) . " - its lines can't change any more";
return '';
}
if ($row['expense_invoice_item_id'] && $invoice['invoice_status'] !== 'Cancelled') {
billingItemDelete('invoice', intval($invoice['invoice_id']), intval($row['expense_invoice_item_id']));
}
mysqli_query($mysqli, "UPDATE expenses SET expense_invoice_id = NULL, expense_invoice_item_id = NULL WHERE expense_id = $id");
return $number;
}
/** The expenses billed on an invoice - each with its cost (less refunds) and what its line bills before tax. */
function expenseOnInvoice($invoice_id) {
global $mysqli;
$invoice_id = intval($invoice_id);
$rows = [];
$sql = mysqli_query($mysqli, "SELECT expenses.*, vendor_name, category_name, item_subtotal,
(SELECT COALESCE(SUM(-r.expense_amount), 0) FROM expenses AS r WHERE r.expense_refund_of_id = expenses.expense_id) AS refunded
FROM expenses
LEFT JOIN vendors ON vendor_id = expense_vendor_id
LEFT JOIN categories ON category_id = expense_category_id
LEFT JOIN invoice_items ON item_id = expense_invoice_item_id
WHERE expense_invoice_id = $invoice_id
ORDER BY expense_date ASC, expense_id ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['cost'] = round(floatval($row['expense_amount']) - floatval($row['refunded']), 2);
$row['billed'] = $row['item_subtotal'] !== null ? floatval($row['item_subtotal']) : null;
$rows[] = $row;
}
return $rows;
}
/** "18% margin" - what is left of a price after its cost, as a share of the price. */
function expenseMarginText($price, $cost) {
$price = floatval($price);
if ($price <= 0) {
return '';
}
return round(($price - floatval($cost)) / $price * 100) . '% margin';
}
/** A client's recurring invoices a recurring expense can be covered by - id => row. */
function recurringExpenseCoverOptions($client_id, $keep_id = 0) {
global $mysqli;
$client_id = intval($client_id);
$keep_id = intval($keep_id);
$rows = [];
if (!$client_id) {
return $rows;
}
$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_status
FROM recurring_invoices
WHERE recurring_invoice_client_id = $client_id AND (recurring_invoice_archived_at IS NULL OR recurring_invoice_id = $keep_id)
ORDER BY recurring_invoice_status DESC, recurring_invoice_number ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[intval($row['recurring_invoice_id'])] = $row;
}
return $rows;
}
/** The recurring expenses a recurring invoice covers - each with what it costs a month, and whether it is running (not paused or ended). */
function recurringExpensesCovering($recurring_invoice_id) {
global $mysqli;
$id = intval($recurring_invoice_id);
$rows = [];
$sql = mysqli_query($mysqli, "SELECT recurring_expenses.*, vendor_name, category_name, category_color, " . expenseRecurringMonthlySql() . " AS monthly
FROM recurring_expenses
LEFT JOIN vendors ON vendor_id = recurring_expense_vendor_id
LEFT JOIN categories ON category_id = recurring_expense_category_id
WHERE recurring_expense_recurring_invoice_id = $id AND recurring_expense_archived_at IS NULL
ORDER BY recurring_expense_status DESC, vendor_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['monthly'] = floatval($row['monthly']);
$row['running'] = recurringExpenseState($row) === 'active';
$rows[] = $row;
}
return $rows;
}
/**
* A recurring invoice against the recurring expenses it covers, a month:
* revenue (what it bills a month before tax), cost (the running ones), the
* margin left and as a percent of revenue, and the rows.
*/
function recurringInvoiceCosts($recurring_invoice_id) {
global $mysqli;
$id = intval($recurring_invoice_id);
$invoice = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT recurring_invoice_amount, recurring_invoice_frequency,
(SELECT COALESCE(SUM(item_tax), 0) FROM recurring_invoice_items WHERE item_recurring_invoice_id = $id) AS tax
FROM recurring_invoices WHERE recurring_invoice_id = $id"));
$rows = recurringExpensesCovering($id);
$revenue = $invoice ? round(recurringInvoiceMonthly(floatval($invoice['recurring_invoice_amount']) - floatval($invoice['tax']), $invoice['recurring_invoice_frequency']), 2) : 0.0;
$cost = 0.0;
foreach ($rows as $row) {
if ($row['running']) {
$cost += $row['monthly'];
}
}
$cost = round($cost, 2);
return ['rows' => $rows, 'revenue' => $revenue, 'cost' => $cost, 'margin' => round($revenue - $cost, 2),
'percent' => $revenue > 0 ? round(($revenue - $cost) / $revenue * 100) : null];
}
/* ------------------------------------------------- Unbilled Time, with expenses */
/**
* Unbilled Time's clients (billingUnbilledByClient()) with their expenses to
* bill as well: each gets expenses, expense_cost and expense_value, a client
* with only expenses waiting is added (no tickets, with their rate and
* drafts), and the oldest counts the expenses too. Sorted by what it all
* comes to. One client's ($client_id) or every client the agent can open.
*/
function expenseUnbilledMerge(array $clients, $client_id = 0) {
global $mysqli;
foreach ($clients as $id => $c) {
$clients[$id] += ['expenses' => [], 'expense_cost' => 0.0, 'expense_value' => 0.0];
}
$added = [];
foreach (expenseUnbilledByClient($client_id) as $id => $e) {
if (!isset($clients[$id])) {
$client_rate = getFieldById('clients', $id, 'client_rate');
$clients[$id] = ['client_id' => $id, 'client_name' => $e['client_name'], 'client_abbreviation' => $e['client_abbreviation'],
'rate' => billingTimeRate($client_rate), 'default_rate' => floatval($client_rate) <= 0, 'tickets' => [], 'seconds' => 0, 'hours' => 0.0,
'value' => 0.0, 'oldest' => 0, 'no_time' => 0, 'drafts' => []];
$added[] = intval($id);
}
$clients[$id]['expenses'] = $e['expenses'];
$clients[$id]['expense_cost'] = round($e['cost'], 2);
$clients[$id]['expense_value'] = round($e['value'], 2);
$clients[$id]['oldest'] = max($clients[$id]['oldest'], $e['oldest']);
}
if ($added) {
$sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_date, invoice_amount, invoice_client_id FROM invoices
WHERE invoice_status = 'Draft' AND invoice_archived_at IS NULL AND invoice_client_id IN (" . implode(',', $added) . ")
ORDER BY invoice_date DESC, invoice_id DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[intval($row['invoice_client_id'])]['drafts'][intval($row['invoice_id'])] = $row;
}
}
uasort($clients, function ($a, $b) {
return ($b['value'] + $b['expense_value']) <=> ($a['value'] + $a['expense_value'])
?: (count($b['tickets']) + count($b['expenses'])) <=> (count($a['tickets']) + count($a['expenses']));
});
return $clients;
}
/**
* Bill a client's tickets ($hours: ticket id => hours, null for what the
* time comes to) and expenses ($prices: expense id => price, null for the
* cost with its markup) on one invoice - the time first, then the expenses
* on the same invoice. Either can be empty. $opts as billingTimeInvoice()
* takes them (the tax goes on the expense lines too). Returns
* [invoice_id, number, new, time (billingTimeInvoice's result or null),
* expenses (expenseBillInvoice's or null), error (what didn't go on)], or
* null with $error when nothing went on.
*/
function expenseBillWithTime($client_id, array $hours, array $prices, array $opts, &$error = '') {
$error = '';
if (!$hours && !$prices) {
$error = 'Nothing to bill - tick the tickets or expenses to bill.';
return null;
}
$time = null;
$time_error = '';
if ($hours) {
$time = billingTimeInvoice($client_id, $hours, $opts, $time_error);
if (!$time && !$prices) {
$error = $time_error;
return null;
}
}
$expenses = null;
$expense_error = '';
if ($prices) {
$expense_opts = $opts;
if ($time) {
$expense_opts['invoice_id'] = $time['invoice_id'];
}
$expenses = expenseBillInvoice($client_id, $prices, $expense_opts, $expense_error);
}
if (!$time && !$expenses) {
$error = trim($time_error . ' ' . $expense_error);
return null;
}
$first = $time ?: $expenses;
return ['invoice_id' => $first['invoice_id'], 'number' => $first['number'], 'new' => !empty($first['new']), 'time' => $time, 'expenses' => $expenses,
'error' => trim(($hours && !$time ? $time_error : '') . ' ' . ($prices && !$expenses ? $expense_error : ''))];
}
/** The client's ticked expenses to bill aren't billable after all - their labels. */
function expenseWriteOff($client_id, array $expense_ids, $by) {
global $mysqli;
$expenses = $expense_ids ? expenseUnbilled($client_id, $expense_ids) : [];
$done = [];
foreach ($expenses as $expense_id => $expense) {
mysqli_query($mysqli, "UPDATE expenses SET expense_billable = 0 WHERE expense_id = $expense_id AND expense_invoice_id IS NULL AND expense_billable = 1");
if (mysqli_affected_rows($mysqli) === 1) {
logAudit('Expense', 'Edit', escapeSql("$by marked the expense " . expenseLabel($expense) . ' not billable'), intval($client_id), $expense_id);
$done[] = expenseLabel($expense);
}
}
return $done;
}

View File

@@ -387,6 +387,8 @@ function getExportColumns($export_type) {
'expense_payment_method' => ['label' => 'Paid By', 'default' => false],
'expense_reference' => ['label' => 'Reference', 'default' => false],
'expense_receipt_display' => ['label' => 'Receipt', 'default' => false],
'expense_billing_display' => ['label' => 'Billing', 'default' => false],
'expense_billed_on' => ['label' => 'Billed On', 'default' => false],
'user_name' => ['label' => 'Entered By', 'default' => false],
],

View File

@@ -2,10 +2,12 @@
* Unbilled Time (agent/unbilled_time.php).
*
* One client: tick the tickets to bill and change their hours - each row's
* amount, and the total at the rate and tax picked, follow as you type.
* amount, and the total at the rate and tax picked, follow as you type. The
* same for its expenses and their prices, each with its margin on its cost.
* Every client: tick the clients to bill - the total is what their tickets
* come to now. Either way the button says what it will make, and the new
* invoice's date, category and scope only show when there is a new one.
* and expenses come to now. Either way the button says what it will make,
* and the new invoice's date, category and scope only show when there is a
* new one.
*
* Needs js/billing_items.js (itflowBillingMoney, itflowBillingNumber).
*
@@ -19,7 +21,9 @@ function itflowUnbilledTime(options) {
}
var mode = form.getAttribute('data-unbilled');
var rows = Array.prototype.slice.call(form.querySelectorAll('[data-unbilled-row]'));
var expenseRows = Array.prototype.slice.call(form.querySelectorAll('[data-unbilled-expense-row]'));
var all = form.querySelector('[data-unbilled-all]');
var expenseAll = form.querySelector('[data-unbilled-expense-all]');
var rate = form.querySelector('[data-unbilled-rate]');
var tax = form.querySelector('[data-unbilled-tax]');
var target = form.querySelector('[data-unbilled-target]');
@@ -44,6 +48,7 @@ function itflowUnbilledTime(options) {
function update() {
var picked = 0;
var tickets = 0;
var expenses = 0;
var hours = 0;
var amount = 0;
var perHour = rate ? number(rate.value) : 0;
@@ -74,19 +79,58 @@ function itflowUnbilledTime(options) {
} else if (on) {
picked++;
tickets += Number(row.getAttribute('data-tickets') || 0);
expenses += Number(row.getAttribute('data-expenses') || 0);
hours += Number(row.getAttribute('data-hours') || 0);
amount += Number(row.getAttribute('data-value') || 0);
}
});
// A client's expenses - each at its price, with the margin on its cost
var expensePicked = 0;
expenseRows.forEach(function (row) {
var pick = row.querySelector('[data-unbilled-expense-pick]');
var on = !pick || pick.checked;
var input = row.querySelector('[data-unbilled-expense-price]');
var price = input ? number(input.value) : 0;
var cost = Number(row.getAttribute('data-cost') || 0);
var margin = row.querySelector('[data-unbilled-expense-margin]');
row.classList.toggle('itflow-unbilled-off', !on);
if (input) {
input.classList.toggle('is-invalid', input.value.trim() !== '' && (isNaN(itflowBillingNumber(input.value)) || price < 0));
if (margin) {
margin.textContent = price > 0 ? Math.round((price - cost) / price * 100) + '% margin' : 'No charge';
margin.classList.toggle('text-danger-emphasis', price < cost);
}
}
if (on && pick) {
expensePicked++;
expenses++;
amount += Math.round(price * 100) / 100;
}
});
if (expenseAll) {
expenseAll.checked = expensePicked > 0 && expensePicked === expenseRows.length;
expenseAll.indeterminate = expensePicked > 0 && expensePicked < expenseRows.length;
}
var taxed = amount + Math.round(amount * percent) / 100;
hours = Math.round(hours * 100) / 100;
if (summary) {
summary.textContent = (mode === 'client' ? '' : plural(picked, 'client') + ' · ') + plural(tickets, 'ticket') + ' · ' + hours + ' h' + (percent ? ' · with tax' : '');
var parts = mode === 'client' ? [] : [plural(picked, 'client')];
if (tickets || !expenses) {
parts.push(plural(tickets, 'ticket'), hours + ' h');
}
if (expenses) {
parts.push(plural(expenses, 'expense'));
}
summary.textContent = parts.join(' · ') + (percent ? ' · with tax' : '');
}
if (total) {
total.textContent = money(taxed);
}
if (mode === 'client') {
picked += expensePicked;
}
if (submit) {
submit.disabled = picked === 0;
}
@@ -98,8 +142,9 @@ function itflowUnbilledTime(options) {
}
}
if (all) {
all.checked = picked > 0 && picked === rows.length;
all.indeterminate = picked > 0 && picked < rows.length;
var rowsPicked = picked - (mode === 'client' ? expensePicked : 0);
all.checked = rowsPicked > 0 && rowsPicked === rows.length;
all.indeterminate = rowsPicked > 0 && rowsPicked < rows.length;
}
// Not billable needs something ticked too
form.querySelectorAll('button[name="unbilled_write_off"]').forEach(function (button) {
@@ -130,38 +175,49 @@ function itflowUnbilledTime(options) {
update();
});
}
if (expenseAll) {
expenseAll.addEventListener('change', function () {
expenseRows.forEach(function (row) {
var pick = row.querySelector('[data-unbilled-expense-pick]');
if (pick) {
pick.checked = expenseAll.checked;
}
});
update();
});
}
form.addEventListener('input', function (e) {
if (e.target.matches('[data-unbilled-hours], [data-unbilled-rate]')) {
if (e.target.matches('[data-unbilled-hours], [data-unbilled-rate], [data-unbilled-expense-price]')) {
update();
}
});
form.addEventListener('change', function (e) {
if (e.target.matches('[data-unbilled-pick], [data-unbilled-tax]')) {
if (e.target.matches('[data-unbilled-pick], [data-unbilled-expense-pick], [data-unbilled-tax]')) {
update();
} else if (e.target === target) {
targetChanged();
}
});
// Clicking a ticket's row (not its link or hours) ticks it
rows.forEach(function (row) {
// Clicking a ticket's or expense's row (not its link or box) ticks it
rows.concat(expenseRows).forEach(function (row) {
row.addEventListener('click', function (e) {
if (e.target.closest('a, input, button, select, label')) {
return;
}
var pick = row.querySelector('[data-unbilled-pick]');
var pick = row.querySelector('[data-unbilled-pick], [data-unbilled-expense-pick]');
if (pick) {
pick.checked = !pick.checked;
update();
}
});
});
// Enter in an hours box moves to the next one rather than billing
// Enter in an hours or price box moves to the next one rather than billing
form.addEventListener('keydown', function (e) {
if (e.key !== 'Enter' || !e.target.matches('[data-unbilled-hours]')) {
if (e.key !== 'Enter' || !e.target.matches('[data-unbilled-hours], [data-unbilled-expense-price]')) {
return;
}
e.preventDefault();
var inputs = Array.prototype.slice.call(form.querySelectorAll('[data-unbilled-hours]'));
var inputs = Array.prototype.slice.call(form.querySelectorAll('[data-unbilled-hours], [data-unbilled-expense-price]'));
var next = inputs[inputs.indexOf(e.target) + 1];
if (next) {
next.focus();