Invoices, quotes and recurring invoices makeover stage 3: Unbilled Time page under Billing and in each client's menu with a count, listing every client's billable resolved or closed tickets not yet invoiced with time logged, hours to bill, rate, amount and oldest waiting, invoicing many clients at once onto a new draft each or each one's newest draft, and per client reviewing each ticket's hours before billing onto a new or existing draft with a line per ticket or one for all, live totals, and Not billable to write tickets off, Billing Time settings under Admin Settings Invoice for rounding to 6, 12, 15 or 30 minutes or the hour, nearest or always up, a per-ticket minimum and the line name, defaulting to the nearest 15 minutes, rebuilt ticket Invoice window showing time by agent, hours to bill and the client or default rate with add-to-draft and an open ticket warning, Add Tickets on an invoice now adds lines for the tickets' time with an option to attach without lines, client overview, dashboard and Unbilled Work report linking to it and counting unbilled time the same way, ticket billing written to ticket history instead of an internal note, invoices from tickets and copies due on the client's terms including On Receipt. Fixes ticket invoice line placed near the top of existing invoices, a ticket billable twice from two windows, no rate when the client had none set, and no hours filled in for tickets with 100 hours or more. Adds DB 2.9.2, billingTimeInvoice() as the one billing path with ticket claiming, billingUnbilledSql() and related helpers, unbilled_invoice, unbilled_invoice_clients and unbilled_write_off handlers, js/unbilled_time.js, and updates the 26.11 changelog

This commit is contained in:
johnnyq
2026-10-16 13:42:06 -04:00
parent 422088fb60
commit 1a51fc8dd6
26 changed files with 1648 additions and 431 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 2.9.1) in the same pass. Nothing else is required.
Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 2.9.2) in the same pass. Nothing else is required.
This is a big release, with twelve database steps in one go, so take a backup before you update.
This is a big release, with thirteen 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:
@@ -59,7 +59,12 @@ If you are coming from 26.08 or earlier, the database update still has to be run
Click the value and pick a new one, or use the + at the end of a record's tags. Each change saves straight away.
- Tickets: a closed ticket can no longer be changed, either from the ticket's windows or through the API. Merging is only offered between tickets of the same client.
- Invoicing a ticket: the invoice line now reads `Ticket TCK-123 - Subject - 10/14/2026`. It used to be a block of text with the agent, dates, contact, asset and time spent. You can still edit it before adding the line.
- Invoicing a ticket:
- The invoice line now reads `Ticket TCK-123 - Subject - 10/14/2026`. It used to be a block of text with the agent, dates, contact, asset and time spent. You can still edit it before adding the line.
- Billing a ticket goes in the ticket's history ("Billed on invoice INV-45"). It used to add an internal note to the conversation.
- An invoice made from a ticket is due on the client's terms, the same as New Invoice. A client set to On Receipt is due on receipt, where it used to get the default terms.
- Add Tickets on an invoice now adds a line for each ticket's time. To only put the tickets on the invoice, as before, switch off Bill their time.
- A ticket's time is counted the same way everywhere: Unbilled Time, the Invoice window, Add Tickets and the Unbilled Work report. A ticket counts once it is resolved or closed, and archived tickets and archived replies are left out.
- Calendars: only admins can add, edit or delete calendars now. Agents can still add and edit events.
- Licenses: archiving a license keeps its seats (the devices and users on it), so restoring it brings everything back. In 26.10, archiving took the seats off.
- Vendors: deleting a vendor that has expenses, recurring expenses or payment provider fees archives it instead, so your books keep it. Deleting any vendor now also clears it from the assets, licenses, tickets and domains that named it.
@@ -139,7 +144,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Receivables Aging: what each client owes, split into not due yet, 1 to 30, 31 to 60, 61 to 90 and over 90 days late, and the overdue invoices, longest overdue first.
- Recurring Revenue: monthly and yearly recurring revenue by client and category, and every recurring invoice with its next date. With Financial access, what is left after recurring expenses.
- Tax Collected: tax and the sales it was charged on, per tax, by quarter or by month.
- Unbilled Work: billable tickets that are done but not invoiced, with the hours to bill (to the nearest 15 minutes, as the Invoice window does) and what they are worth at the client's rate.
- Unbilled Work: billable tickets that are done but not invoiced, with the hours to bill (rounded the way Billing Time in Admin > Settings > Invoice says, as Unbilled Time does) and what they are worth at the client's rate.
- Time Detail by Client: per client, each ticket and the time on every reply, with the hours to bill.
- Ticket Overview: tickets opened against resolved, the typical first reply and time to resolve, sources, priorities, categories, top clients and contacts, and a weekday by hour chart of when tickets come in.
- Tickets by Client: volume and its change, urgent tickets, time logged, reply and resolution times, SLA and satisfaction for each client.
@@ -207,6 +212,15 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Quarterly recurring invoices, alongside monthly and yearly. They count as a third in monthly recurring revenue on the dashboard, the client pages, the client portal and the reports.
- Period words: `{month}`, `{quarter}`, `{year}` and `{period}` in a recurring invoice's scope, notes or lines are filled in with the period each invoice covers, such as "Managed services November 2026", "Q4 2026" or "Nov 1 - Nov 30, 2026".
- Invoice Now names the run it bills, whether it will be emailed and when the next one is, before you confirm. Pressing it twice, or in two tabs, bills that run only once.
- **Unbilled Time**, under Billing and in each client's menu, with a count of what is waiting:
- Every client with billable tickets that are done and not invoiced, with their tickets, the time logged, the hours to bill, their rate, what it comes to and how long the oldest has waited. Tick clients and make all their invoices at once - a new draft each, or onto each one's newest draft.
- 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.
- 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.
- The client overview's Not yet invoiced shows what the unbilled time comes to and opens Unbilled Time. The dashboard and the Unbilled Work report link to it too.
- **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.
@@ -381,6 +395,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Billing: the client's view of a quote offered Accept on a viewed quote that had run out, and the invoice and quote views put the browser's HTML into the history.
- Billing: copying an invoice logged its old number with the prefix twice.
- Recurring invoices: if cron missed a night, that recurring invoice stopped billing until someone moved its date. The missed run is now billed the next night, up to 7 days late.
- Invoicing a ticket: on an invoice that already had lines, its line went in near the top instead of at the end. A ticket already on an invoice could be billed again from a second window, and a ticket with 100 hours or more logged had no hours filled in.
- Invoicing a ticket for a client with no hourly rate filled in nothing. It now takes the default hourly rate, as the Unbilled Work report already did.
- Recurring invoices: the email went to contacts that had been archived, and could reach the same address twice.
- Client Portal: the recurring card on the home page didn't show for a client with only yearly recurring invoices, and counted archived ones.
- Copy buttons in many places, such as pages that already had a window open, showed Copied! but copied nothing. Copy guest URL on invoices and quotes jumped the page to the top, and copying an empty field wiped your clipboard.
@@ -413,7 +429,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
### Developer Updates
- Database 2.8.0 to 2.9.1, one file per step under `admin/database_updates/`, with `db.sql` matching 2.9.1:
- Database 2.8.0 to 2.9.2, one file per step under `admin/database_updates/`, with `db.sql` matching 2.9.2:
- 2.8.0: `racks.rack_units_descending`, `rack_power_capacity` and `rack_photo_rear`. On `rack_units`: `unit_face`, `unit_full_depth`, `unit_type`, `unit_power_watts`, `unit_notes` and a `unit_asset_id` key. Unlinked items move from asset id 0 to NULL.
- 2.8.1: `location_documents` and `location_files`.
- 2.8.2: `vendor_tags` (tag type 6), and `vendor_contact_phone_country_code`, `vendor_contact_phone` and `vendor_contact_email`.
@@ -438,6 +454,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- `item_note` widened to 1000, `item_view_limit` made `NOT NULL DEFAULT 0` (NULL was unlimited), existing `item_key` values replaced by their SHA-256, and `item_name` filled from the shared record
- `settings.config_share_max_hours` (720) and `config_share_require_protection` (0)
- 2.9.1: `recurring_invoice_items.item_seat_source`, `item_seat_filter` (JSON) and `item_seat_minimum`, and `recurring_invoices.recurring_invoice_anchor_day`, backfilled from the day of each next date.
- 2.9.2: `settings.config_time_increment` (15), `config_time_rounding` ('nearest'), `config_time_minimum` (0) and `config_time_item_name` ('Support [Hourly]').
- 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`.
@@ -536,6 +553,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Schedules: `recurringInvoiceFrequencies()` (month, quarter, year), `recurringInvoiceMonths()`, `recurringInvoicePeriodWord()`, `recurringInvoiceMonthly()` and `recurringInvoiceMonthlySql()` (use it in SQL sums), `recurringInvoiceAfter()`, `recurringInvoicePeriod()` and `recurringInvoiceTokens()`. `validateRecurringFrequency()` accepts `quarter`. The edit handler keeps `recurring_invoice_anchor_day` unless the next date changes, and the add and edit handlers run their dates through `validateDate()`.
- Seats: `recurringSeatSources()`, `recurringSeatFilter()`, `recurringSeatCount()` (null when a license is gone or isn't the client's), `recurringSeatDescribe()`, `recurringSeatOptions()`, `recurringSeatLines()` and `recurringInvoiceRefresh()`, which syncs the seat quantities and takes each line's tax at its current rate. `billing_item_save` takes `seat_source` (empty for typed), `seat_tag`, `seat_types[]`, `seat_software_id`, `seat_count` (`used` or `total`) and `seat_minimum` on recurring lines. A form without `seat_source` leaves the seat settings alone.
- New handlers: `recurring_invoice_sync` (GET, `agent/post/billing.php`) and `recurring_seat_count` in `agent/ajax.php`, which returns `{count, quantity, label}` or `{error}` and needs Sales and access to the client. `itflowBillingSeatForm()` in `js/billing_items.js` drives the Edit Line seat fields.
- Billing time (`functions/billing.php`): `billingTimeRules()` reads the settings once a request (falling back to the old rules before 2.9.2 is applied, so they are not in `load_global_settings.php`), `billingTimeIncrements()`, `billingTimeRulesText()`, `billingTimeHours()`, `billingTimeRate()`, `billingTimeDescription()`. `billingUnbilledSql()` is the one definition of unbilled (billable, status Resolved or Closed, not archived, `ticket_invoice_id = 0`); `billingUnbilledTickets()`, `billingUnbilledByClient()` and `billingUnbilledCount()` read it, scoped to the agent's clients. The dashboard, client overview, sidebars and the Unbilled Work report use them.
- `billingTimeInvoice($client_id, $hours, $opts, &$error)` is the one path that bills time - Unbilled Time, `add_invoice_from_ticket`, `add_ticket_to_invoice`. It validates first, makes the draft with `billingInvoiceCreate()` when needed, claims the tickets with a conditional `UPDATE` (deleting a new draft that ends up with none), adds the lines through `billingItemSave()`, and logs ticket history, invoice history and the audit log. `billingTimeWriteOff()` sets `ticket_billable = 0`. `invoiceUnbilledTickets()` is replaced by `billingUnbilledTickets()`, and `roundToNearest15Min()` is no longer used.
- New page `agent/unbilled_time.php` with `js/unbilled_time.js`, and handlers `unbilled_invoice`, `unbilled_invoice_clients` and `unbilled_write_off` in `agent/post/billing.php`. `add_ticket_to_invoice` takes `ticket_ids[]`, `hours[id]`, `bill_time`, `item_name`, `price`, `tax_id` and `lines` (`each` or `one`). `add_invoice_from_ticket` keeps its field names. `remove_ticket_from_invoice` writes to the ticket's history.
- Removed: `add_invoice_item`, `edit_invoice_item`, `delete_invoice_item`, `add_quote_item`, `edit_quote_item`, `delete_quote_item`, `add_recurring_invoice_item`, `edit_recurring_invoice_item`, `delete_recurring_invoice_item` and `link_invoice_to_ticket` (it wrote a column that does not exist), `update_invoice_items_order`, `update_quote_items_order` and `update_recurring_invoice_items_order` in `agent/ajax.php`, `agent/modals/invoice/invoice_item_edit.php`, `agent/modals/quote/quote_item_edit.php`, `agent/modals/recurring_invoice/recurring_invoice_item_edit.php`, `guest/guest_quote_upload_file_modal.php` and `js/product_autocomplete.js`.
- 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,18 @@
<?php
/*
* ITFlow - Database update to version 2.9.2 (from 2.9.1)
* Included by admin/database_updates.php - do not access directly
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
// How ticket time is billed (Admin > Settings > Invoice, billingTimeRules()):
// the step it rounds to in minutes, to the nearest step or always up, the
// least a ticket with time on it bills, and the invoice line's name. The
// defaults are how it has always been - the nearest 15 minutes, no minimum.
mysqli_query($mysqli, "ALTER TABLE `settings`
ADD COLUMN `config_time_increment` int(11) NOT NULL DEFAULT 15 AFTER `config_default_hourly_rate`,
ADD COLUMN `config_time_rounding` varchar(10) NOT NULL DEFAULT 'nearest' AFTER `config_time_increment`,
ADD COLUMN `config_time_minimum` int(11) NOT NULL DEFAULT 0 AFTER `config_time_rounding`,
ADD COLUMN `config_time_item_name` varchar(200) NOT NULL DEFAULT 'Support [Hourly]' AFTER `config_time_minimum`");

View File

@@ -19,6 +19,16 @@ if (isset($_POST['edit_invoice_settings'])) {
$config_invoice_paid_notification_email = escapeSql($_POST['config_invoice_paid_notification_email']);
}
// Billing time - see billingTimeRules()
$config_time_increment = intval($_POST['config_time_increment'] ?? 15);
$config_time_increment = isset(billingTimeIncrements()[$config_time_increment]) ? $config_time_increment : 15;
$config_time_rounding = ($_POST['config_time_rounding'] ?? '') === 'up' ? 'up' : 'nearest';
$config_time_minimum = max(0, min(1440, intval($_POST['config_time_minimum'] ?? 0)));
$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));
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_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");
logAudit("Settings", "Edit", "$session_name edited invoice settings");

View File

@@ -88,7 +88,55 @@ require_once "includes/inc_all_admin.php";
</div>
</div>
<hr>
<?php $time_rules = billingTimeRules(); ?>
<h4 id="billing-time">Billing Time</h4>
<p class="text-secondary small">How the time logged on a billable ticket becomes hours on an invoice - in Unbilled Time, a ticket's Invoice window and Add Tickets. Each ticket's time is rounded once, as a whole. It is billed at the client's hourly rate, or the default rate in Defaults when the client has none.</p>
<div class="row">
<div class="col-md-6 mb-3">
<label>Round to</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-stopwatch"></i></span>
<select class="form-select" name="config_time_increment">
<?php foreach (billingTimeIncrements() as $minutes => $label) { ?>
<option value="<?= $minutes ?>" <?= $time_rules['increment'] === $minutes ? 'selected' : '' ?>><?= escapeHtml($label) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-6 mb-3">
<label>Rounding</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-sort-amount-up"></i></span>
<select class="form-select" name="config_time_rounding">
<option value="nearest" <?= $time_rules['rounding'] === 'nearest' ? 'selected' : '' ?>>To the nearest - under half a step rounds down</option>
<option value="up" <?= $time_rules['rounding'] === 'up' ? 'selected' : '' ?>>Always up - any part of a step bills the whole step</option>
</select>
</div>
</div>
<div class="col-md-6 mb-3">
<label>Least a ticket bills</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-arrow-down"></i></span>
<select class="form-select" name="config_time_minimum">
<?php foreach ([0 => 'No minimum', 15 => '15 minutes', 30 => '30 minutes', 60 => '1 hour', 120 => '2 hours'] as $minutes => $label) { ?>
<option value="<?= $minutes ?>" <?= $time_rules['minimum'] === $minutes ? 'selected' : '' ?>><?= $label ?></option>
<?php } ?>
</select>
</div>
<small class="text-secondary">Once it has any time logged. A ticket with none bills nothing unless the hours are typed.</small>
</div>
<div class="col-md-6 mb-3">
<label>Invoice line</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-cube"></i></span>
<input type="text" class="form-control" name="config_time_item_name" maxlength="200" value="<?= escapeHtml($time_rules['item_name']) ?>" placeholder="Support [Hourly]" required>
</div>
<small class="text-secondary">The name of the line the time goes on. The ticket number, subject and date go in its description.</small>
</div>
</div>
<hr>

View File

@@ -246,7 +246,7 @@ if (isset($_GET['quick_pick_options'])) {
$options[] = ['value' => (string) $status_id, 'label' => $status['ticket_status_name'], 'color' => preg_match('/^(#[0-9a-f]{3,8}|[a-z]{3,24})$/i', (string) $status['ticket_status_color']) ? $status['ticket_status_color'] : ''];
}
} elseif ($field === 'billable') {
$options[] = ['value' => '1', 'label' => 'Billable', 'icon' => 'fas fa-dollar-sign', 'description' => 'Shows on the Unbilled Tickets report until invoiced'];
$options[] = ['value' => '1', 'label' => 'Billable', 'icon' => 'fas fa-dollar-sign', 'description' => 'Shows under Unbilled Time once done, until invoiced'];
$options[] = ['value' => '0', 'label' => 'Not billable', 'icon' => 'fas fa-minus'];
} elseif ($field === 'assignee' || $field === 'recurring_assignee') {
$options = quickPickAgents();

View File

@@ -505,10 +505,10 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code,
<span class="small text-body-tertiary"><?= $num_recurring_invoices ?> recurring invoice<?= $num_recurring_invoices === 1 ? '' : 's' ?></span>
</a>
<?php if ($access['tickets']) { ?>
<a href="tickets.php?client_id=<?= $client_id ?>&billing=unbilled&state=closed" class="itflow-dash-rail-item">
<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_tickets'] ? 'text-info-emphasis' : '' ?>"><?= $money['unbilled_tickets'] ?> <span class="fs-6 fw-normal text-body-secondary">ticket<?= $money['unbilled_tickets'] === 1 ? '' : 's' ?></span></span>
<span class="small text-body-tertiary"><?= $money['unbilled_seconds'] ? dashboardDuration($money['unbilled_seconds']) . ' logged' : 'Resolved and billable' ?></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>
</a>
<?php } ?>
<div class="itflow-dash-rail-item">

View File

@@ -344,6 +344,20 @@
</a>
</li>
<?php if ($config_module_enable_ticketing == 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 } ?>
</p>
</a>
</li>
<?php } ?>
<li class="nav-item">
<a href="/agent/recurring_invoices.php?client_id=<?= $client_id ?>" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "recurring_invoices.php" || basename($_SERVER["PHP_SELF"]) == "recurring_invoice.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-redo-alt"></i>

View File

@@ -25,6 +25,9 @@ $num_open_invoices = $row['num'];
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('recurring_invoice_id') AS num FROM recurring_invoices WHERE recurring_invoice_archived_at IS NULL " . clientScopeSql('recurring_invoice_client_id') . ""));
$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;
// Open Quotes Count
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('quote_id') AS num FROM quotes WHERE (quote_status = 'Sent' OR quote_status = 'Viewed') AND quote_archived_at IS NULL " . clientScopeSql('quote_client_id') . ""));
$num_open_quotes = $row['num'];

View File

@@ -165,6 +165,9 @@ if (isset($_GET['client_id'])) {
$recurring_monthly = floatval($row['recurring_monthly']);
$num_recurring_invoices = intval($row['num_recurring_invoices']);
// 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]);
// Get Credit Balance
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COALESCE(SUM(credit_amount), 0) AS credit_balance
FROM credits WHERE credit_client_id = $client_id"));

View File

@@ -150,6 +150,19 @@
</p>
</a>
</li>
<?php if ($config_module_enable_ticketing == 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 } ?>
</p>
</a>
</li>
<?php } ?>
<li class="nav-item">
<a href="/agent/recurring_invoices.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "recurring_invoices.php" || basename($_SERVER["PHP_SELF"]) == "recurring_invoice.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-redo-alt"></i>

View File

@@ -57,7 +57,7 @@ $can_manage_payments = lookupUserPermission('module_sales') >= 3 && lookupUserPe
$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 ? count(invoiceUnbilledTickets($client_id)) : 0;
$unbilled_tickets = $can_edit && $can_edit_lines && $config_module_enable_ticketing ? count(billingUnbilledTickets($client_id)) : 0;
$guest_url = billingGuestUrl('invoice', $invoice);
$csrf = $_SESSION['csrf_token'];

View File

@@ -30,10 +30,11 @@ $form_category_id = intval($form_value('category_id', '0'));
$form_categories = billingCategories($form_edit ? $form_value('created_at') : null);
$form_discount = floatval($form_value('discount_amount', '0'));
// Net terms - the client's, or the default - for a new invoice's due date
// Net terms for a new invoice's due date - the client's (0 is On Receipt), as
// the invoice is saved with; the default until a client is picked
$form_terms = intval($config_default_net_terms);
if ($form_client_id) {
$form_terms = intval(getFieldById('clients', $form_client_id, 'client_net_terms')) ?: $form_terms;
$form_terms = intval(getFieldById('clients', $form_client_id, 'client_net_terms'));
}
$form_clients = [];
@@ -61,7 +62,7 @@ $form_scope_placeholder = [
<select class="form-select select2" name="client_id" required data-billing-client>
<option value="">- Select a client -</option>
<?php foreach ($form_clients as $form_client) { ?>
<option value="<?= intval($form_client['client_id']) ?>" data-terms="<?= intval($form_client['client_net_terms']) ?: intval($config_default_net_terms) ?>"<?= selectOptionClient($form_client['client_id'], $form_client['client_name'], $form_client['client_abbreviation'] ?? '') ?>><?= escapeHtml($form_client['client_name']) ?></option>
<option value="<?= intval($form_client['client_id']) ?>" data-terms="<?= intval($form_client['client_net_terms']) ?>"<?= selectOptionClient($form_client['client_id'], $form_client['client_name'], $form_client['client_abbreviation'] ?? '') ?>><?= escapeHtml($form_client['client_name']) ?></option>
<?php } ?>
</select>
</div>
@@ -119,7 +120,7 @@ $form_scope_placeholder = [
<?php } ?>
</div>
<?php if (!$form_edit) { ?>
<div class="form-text" data-billing-terms-note><?= $form_terms ?> days from the invoice date - <?= $form_client_id ? "the client's" : 'the default' ?> terms.</div>
<div class="form-text" data-billing-terms-note><?= $form_terms ? "$form_terms days from the invoice date" : 'Due on receipt' ?> - <?= $form_client_id ? "the client's" : 'the default' ?> terms.</div>
<?php } ?>
</div>
<?php } elseif ($form_type === 'quote') { ?>
@@ -235,7 +236,7 @@ $form_scope_placeholder = [
if (due && date) {
due.value = plus(date.value, terms());
if (note) {
note.textContent = terms() + ' days from the invoice date - ' + (client && client.value ? "the client's" : 'the default') + ' terms.';
note.textContent = (terms() ? terms() + ' days from the invoice date' : 'Due on receipt') + ' - ' + (client && client.value ? "the client's" : 'the default') + ' terms.';
}
}
}

View File

@@ -1,9 +1,11 @@
<?php
/*
* Put tickets on an invoice - the client's billable tickets that are
* resolved or closed and not on an invoice yet, with the time worked on
* each. Tick any number. ?invoice_id=
* Add Tickets to an invoice - the client's billable tickets that are
* resolved or closed and not on an invoice yet. Each comes with the hours
* its time bills (rounded the way Admin > Settings > Invoice says), ready to
* change, and goes on as a line at the rate - or, with Bill their time off,
* goes on without a line, for work already on the invoice. ?invoice_id=
*/
require_once '../../../includes/modal_header.php';
@@ -17,8 +19,16 @@ if (!$invoice) {
}
$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."]));
}
$tickets = invoiceUnbilledTickets($client_id);
$tickets = billingUnbilledTickets($client_id);
$rules = billingTimeRules();
$first = $tickets ? reset($tickets) : null;
$rate = $first ? $first['rate'] : billingTimeRate(getFieldById('clients', $client_id, 'client_rate'));
$currency = (string) $invoice['invoice_currency_code'];
$taxes = billingTaxes();
ob_start();
@@ -27,28 +37,78 @@ ob_start();
<h5 class="modal-title"><i class="fas fa-fw fa-life-ring me-2"></i>Add Tickets <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">
<form action="post.php" method="post" autocomplete="off" id="invoiceAddTickets">
<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 ($tickets) { ?>
<div class="px-3 py-2 small text-body-secondary border-bottom">
<?= escapeHtml($invoice['client_name']) ?>'s billable tickets, resolved or closed, that aren't on an invoice. Adding one marks it billed - its time isn't added as a line.
<?= escapeHtml($invoice['client_name']) ?>'s billable tickets, resolved or closed, that aren't on an invoice. The hours are the time logged, rounded <?= escapeHtml(billingTimeRulesText($rules)) ?> - change them before adding.
</div>
<div class="list-group list-group-flush" style="max-height: 24rem; overflow-y: auto;">
<?php foreach ($tickets as $ticket) {
$ticket_id = intval($ticket['ticket_id']); ?>
<label class="list-group-item list-group-item-action d-flex align-items-center gap-3">
<input class="form-check-input flex-shrink-0 mt-0" type="checkbox" name="ticket_ids[]" value="<?= $ticket_id ?>">
<div class="flex-grow-1 min-w-0">
<div class="text-truncate"><span class="font-monospace small text-body-secondary me-2"><?= escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) ?></span><?= escapeHtml($ticket['ticket_subject']) ?></div>
<div class="small text-body-secondary">Opened <?= escapeHtml(date('Y-m-d', strtotime($ticket['ticket_created_at']))) ?></div>
<div class="list-group list-group-flush" style="max-height: 20rem; overflow-y: auto;">
<?php foreach ($tickets as $ticket_id => $ticket) { ?>
<div class="list-group-item d-flex align-items-center gap-3">
<input class="form-check-input flex-shrink-0 mt-0" type="checkbox" name="ticket_ids[]" value="<?= $ticket_id ?>" id="addTicket<?= $ticket_id ?>" data-add-ticket>
<label class="flex-grow-1 min-w-0 mb-0" for="addTicket<?= $ticket_id ?>">
<span class="d-block text-truncate"><span class="font-monospace small text-body-secondary me-2"><?= escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) ?></span><?= escapeHtml($ticket['ticket_subject']) ?></span>
<span class="small text-body-secondary">
<i class="far fa-clock me-1"></i><?= $ticket['seconds'] ? billingDuration($ticket['seconds']) . ' logged' : '<span class="text-warning-emphasis">No time logged</span>' ?>
&middot; done <?= escapeHtml(date('Y-m-d', strtotime((string) ($ticket['ticket_resolved_at'] ?: $ticket['ticket_closed_at'])))) ?>
</span>
</label>
<div class="input-group input-group-sm flex-shrink-0" style="width: 6.5rem;" data-add-ticket-hours>
<input type="text" class="form-control text-end" name="hours[<?= $ticket_id ?>]" value="<?= billingQuantity($ticket['hours']) ?>" inputmode="decimal" aria-label="Hours to bill">
<span class="input-group-text">h</span>
</div>
<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal" title="Time worked"><i class="far fa-clock me-1"></i><?= billingDuration($ticket['seconds']) ?></span>
</label>
</div>
<?php } ?>
</div>
<div class="p-3 border-top">
<div class="form-check form-switch mb-3">
<input class="form-check-input" type="checkbox" role="switch" name="bill_time" value="1" id="addTicketsBill" checked data-add-ticket-bill>
<label class="form-check-label" for="addTicketsBill">Bill their time - add lines at the hourly rate</label>
</div>
<div class="row g-3" data-add-ticket-lines>
<div class="col-12">
<label class="form-label">Line</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-cube"></i></span>
<input type="text" class="form-control" name="item_name" maxlength="200" value="<?= escapeHtml($rules['item_name']) ?>" required>
</div>
</div>
<div class="col-sm-4">
<label class="form-label">Rate <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control text-end" name="price" inputmode="decimal" value="<?= number_format($rate, 2, '.', '') ?>" required data-add-ticket-rate>
</div>
</div>
<div class="col-sm-4">
<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-ticket-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 class="col-sm-4">
<label class="form-label">Lines</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select" name="lines">
<option value="each">One each</option>
<option value="one">One for all</option>
</select>
</div>
</div>
</div>
<div class="form-text" data-add-ticket-nolines hidden>The tickets go on the invoice and stop being unbilled - nothing is added to its lines. For work already billed on it by hand.</div>
</div>
<?php } else { ?>
<div class="itflow-asset-empty">
<i class="fas fa-life-ring fa-2x mb-2 opacity-50"></i>
@@ -58,11 +118,71 @@ ob_start();
</div>
<div class="modal-footer">
<?php if ($tickets) { ?>
<button type="submit" name="add_ticket_to_invoice" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i>Add</button>
<span class="me-auto small text-body-secondary" data-add-ticket-summary></span>
<button type="submit" name="add_ticket_to_invoice" class="btn btn-primary text-bold" disabled data-add-ticket-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><?= $tickets ? 'Cancel' : 'Close' ?></button>
</div>
</form>
<script>
(function () {
var form = document.getElementById('invoiceAddTickets');
if (!form || form.dataset.wired) {
return;
}
form.dataset.wired = '1';
var currency = <?= json_encode($currency) ?>;
var bill = form.querySelector('[data-add-ticket-bill]');
var lines = form.querySelector('[data-add-ticket-lines]');
var noLines = form.querySelector('[data-add-ticket-nolines]');
var rate = form.querySelector('[data-add-ticket-rate]');
var tax = form.querySelector('[data-add-ticket-tax]');
var summary = form.querySelector('[data-add-ticket-summary]');
var submit = form.querySelector('[data-add-ticket-submit]');
if (!bill) {
return;
}
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 hours = 0;
form.querySelectorAll('[data-add-ticket]').forEach(function (box) {
var row = box.closest('.list-group-item');
var input = row.querySelector('[data-add-ticket-hours] input');
input.disabled = !bill.checked;
if (box.checked) {
count++;
hours += number(input.value);
}
});
lines.hidden = !bill.checked;
lines.querySelectorAll('input, select').forEach(function (input) {
input.disabled = !bill.checked;
});
noLines.hidden = bill.checked;
var option = tax.options[tax.selectedIndex];
var amount = Math.round(hours * number(rate.value) * 100) / 100;
amount += Math.round(amount * Number(option ? option.getAttribute('data-percent') || 0 : 0)) / 100;
hours = Math.round(hours * 100) / 100;
summary.textContent = count ? count + ' ticket' + (count === 1 ? '' : 's') + (bill.checked ? ' · ' + hours + ' h · ' + money(amount) : '') : 'Tick the tickets 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

@@ -19,7 +19,7 @@ $client_id = intval($doc['client_id']);
enforceClientAccess();
$doc_number = billingNumber($doc_type, $doc);
$lines = count(billingItems('invoice', intval($doc['invoice_id'])));
$terms = intval($doc['client_net_terms']) ?: intval($config_default_net_terms);
$terms = intval($doc['client_net_terms']); // 0 is On Receipt
ob_start();
@@ -39,7 +39,7 @@ ob_start();
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date('Y-m-d') ?>" required>
</div>
<div class="form-text">Due <?= $terms ?> days after it - the client's terms.</div>
<div class="form-text"><?= $terms ? "Due $terms days after it" : 'Due on receipt' ?> - the client's terms.</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_invoice_copy" class="btn btn-primary text-bold"><i class="fas fa-copy me-2"></i>Copy</button>

View File

@@ -1,307 +1,249 @@
<?php
/*
* Invoice a ticket - its time as a line on a new draft invoice or one of the
* client's drafts. The time logged on it (by agent), the hours that makes
* (rounded the way Admin > Settings > Invoice says) and the client's rate
* are filled in, ready to change. A ticket still open can be billed from
* here too - time logged after that isn't billed. ?ticket_id=
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_sales', 2);
// The ticket, after the module and client checks - or the modal's error
$ticket = ticketForModal($_GET['ticket_id'] ?? 0, 2);
$ticket_id = intval($ticket['ticket_id']);
if (!intval($ticket['ticket_client_id'])) {
echo json_encode(['error' => 'Move the ticket to a client before invoicing it.']);
exit;
$reference = ticketReference($ticket);
if (!$client_id) {
exit(json_encode(['error' => 'Move the ticket to a client before invoicing it.']));
}
if (intval($ticket['ticket_invoice_id'])) {
$on = billingRow('invoice', intval($ticket['ticket_invoice_id']));
exit(json_encode(['error' => "$reference is already billed" . ($on ? ' on ' . billingNumber('invoice', $on) : '') . '.']));
}
if (!intval($ticket['ticket_billable'])) {
exit(json_encode(['error' => "$reference isn't billable - mark it billable first."]));
}
$ticket_sql = mysqli_query(
$mysqli,
"SELECT asset_id, asset_name, asset_type, category_name, client_id, client_rate, contact_id,
contact_name, location_address, location_city, location_id, location_name, location_phone,
location_state, location_zip, ticket_assigned_to, ticket_billable, ticket_category,
ticket_created_at, ticket_created_by, ticket_first_response_at, ticket_number,
ticket_onsite, ticket_prefix, ticket_priority, ticket_quote_id, ticket_resolved_at,
ticket_subject, user_name FROM tickets
LEFT JOIN clients ON ticket_client_id = client_id
LEFT JOIN contacts ON ticket_contact_id = contact_id
LEFT JOIN users ON ticket_assigned_to = user_id
LEFT JOIN locations ON ticket_location_id = location_id
LEFT JOIN assets ON ticket_asset_id = asset_id
LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id
LEFT JOIN categories ON ticket_category = category_id
WHERE ticket_id = $ticket_id
" . clientScopeSql('ticket_client_id') . "
LIMIT 1"
);
$row = mysqli_fetch_assoc($ticket_sql);
$client_id = intval($row['client_id']);
$client_rate = floatval($row['client_rate']);
$ticket_prefix = escapeHtml($row['ticket_prefix']);
$ticket_number = intval($row['ticket_number']);
$ticket_category = intval($row['ticket_category']);
$ticket_category_display = escapeHtml($row['category_name']);
$ticket_subject = escapeHtml($row['ticket_subject']);
$ticket_priority = escapeHtml($row['ticket_priority']);
$ticket_billable = intval($row['ticket_billable']);
$ticket_onsite = intval($row['ticket_onsite']);
$ticket_created_at = escapeHtml($row['ticket_created_at']);
$ticket_created_by = intval($row['ticket_created_by']);
$ticket_date = date('Y-m-d g:i A', strtotime($ticket_created_at));
$ticket_date_description = date('m/d/Y', strtotime($ticket_created_at));
$ticket_first_response_at = escapeHtml($row['ticket_first_response_at']);
if ($ticket_first_response_at) {
$ticket_first_response_date_time = date('Y-m-d g:i A', strtotime($ticket_first_response_at));
} else {
$ticket_first_response_date_time = '';
$unbilled = billingUnbilledTickets($client_id, [$ticket_id], true);
$row = $unbilled[$ticket_id] ?? null;
if (!$row) {
exit(json_encode(['error' => "$reference can't be billed - it is archived."]));
}
$ticket_resolved_at = escapeHtml($row['ticket_resolved_at']);
if ($ticket_resolved_at) {
$ticket_resolved_date = date('Y-m-d g:i A', strtotime($ticket_resolved_at));
} else {
$ticket_resolved_date = '';
$rules = billingTimeRules();
$open = !in_array(intval($row['ticket_status']), [TICKET_STATUS_RESOLVED, TICKET_STATUS_CLOSED], true);
$currency = (string) $session_company_currency;
// The time on it, by who logged it
$agents = [];
$sql = mysqli_query($mysqli, "SELECT user_name, COUNT(*) AS entries, SUM(TIME_TO_SEC(ticket_reply_time_worked)) AS seconds FROM ticket_replies
LEFT JOIN users ON user_id = ticket_reply_by
WHERE ticket_reply_ticket_id = $ticket_id AND ticket_reply_archived_at IS NULL AND ticket_reply_time_worked > '00:00:00'
GROUP BY ticket_reply_by ORDER BY seconds DESC");
while ($agent = mysqli_fetch_assoc($sql)) {
$agents[] = $agent;
}
$ticket_assigned_to = intval($row['ticket_assigned_to']);
if ($ticket_assigned_to) {
$ticket_assigned_agent = escapeHtml($row['user_name']);
} else {
$ticket_assigned_agent = '';
$drafts = [];
$sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_amount FROM invoices
WHERE invoice_client_id = $client_id AND invoice_status = 'Draft' AND invoice_archived_at IS NULL ORDER BY invoice_date DESC, invoice_id DESC");
while ($draft = mysqli_fetch_assoc($sql)) {
$drafts[intval($draft['invoice_id'])] = $draft;
}
$ticket_quote_id = intval($row['ticket_quote_id']);
$contact_id = intval($row['contact_id']);
$contact_name = escapeHtml($row['contact_name']);
$asset_id = intval($row['asset_id']);
$asset_name = escapeHtml($row['asset_name']);
$asset_type = escapeHtml($row['asset_type']);
$location_id = intval($row['location_id']);
$location_name = escapeHtml($row['location_name']);
$location_address = escapeHtml($row['location_address']);
$location_city = escapeHtml($row['location_city']);
$location_state = escapeHtml($row['location_state']);
$location_zip = escapeHtml($row['location_zip']);
$location_phone = formatPhoneNumber($row['location_phone']);
if ($client_id) {
enforceClientAccess();
}
//Get Total Ticket Time
$ticket_total_reply_time = mysqli_query($mysqli, "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(ticket_reply_time_worked))) AS ticket_total_reply_time FROM ticket_replies WHERE ticket_reply_archived_at IS NULL AND ticket_reply_ticket_id = $ticket_id");
$row = mysqli_fetch_assoc($ticket_total_reply_time);
$ticket_total_reply_time = escapeHtml($row['ticket_total_reply_time']);
$ticket_total_reply_time_display = formatDuration($ticket_total_reply_time);
$sql_invoices = mysqli_query($mysqli, "SELECT invoice_amount, invoice_date, invoice_due, invoice_id, invoice_number, invoice_prefix,
invoice_scope, invoice_status FROM invoices WHERE invoice_status LIKE 'Draft' AND invoice_client_id = $client_id ORDER BY invoice_number ASC");
$categories = billingCategories();
$taxes = billingTaxes();
$scopes = ["Ticket $reference - " . $row['ticket_subject'], 'Support - ' . date('F Y')];
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-file-invoice-dollar me-2"></i>Invoice this ticket</h5>
<h5 class="modal-title"><i class="fas fa-fw fa-file-invoice-dollar me-2"></i>Invoice <?= escapeHtml($reference) ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<form action="post.php" method="post" autocomplete="off" id="ticketInvoiceForm">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
<div class="modal-body">
<?php if ($ticket_quote_id > 0) { ?>
<div class="alert alert-warning" role="alert">
<a href="quote.php?quote_id=<?=$ticket_quote_id?>">View quote?</a>
<?php if ($open) { ?>
<div class="alert alert-warning small py-2">
<i class="fas fa-exclamation-triangle me-1"></i><?= escapeHtml($reference) ?> is still open. It is billed once - time logged on it after this isn't billed.
</div>
<?php } ?>
<?php if (intval($ticket['ticket_quote_id'] ?? 0)) { ?>
<div class="alert alert-info small py-2">
<i class="fas fa-comment-dollar me-1"></i>It has a quote - <a href="quote.php?quote_id=<?= intval($ticket['ticket_quote_id']) ?>">check it</a> before billing the time as well.
</div>
<?php } ?>
<?php if (mysqli_num_rows($sql_invoices) > 0) { ?>
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#pills-add-to-invoice"><i class="fa fa-fw fa-plus me-2"></i>Add to Existing Invoice</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-create-invoice"><i class="fa fa-fw fa-check me-2"></i>Create New Invoice</a>
</li>
</ul>
<hr>
<?php } ?>
<div class="tab-content">
<?php
if (mysqli_num_rows($sql_invoices) > 0) { ?>
<div class="tab-pane fade <?php if (mysqli_num_rows($sql_invoices) > 0) { echo "active show"; } ?>" id="pills-add-to-invoice">
<div class="mb-3">
<label>Existing Invoice</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="invoice_id">
<option value="0">- Select an Existing Invoice -</option>
<?php
while ($row = mysqli_fetch_assoc($sql_invoices)) {
$invoice_id = intval($row['invoice_id']);
$invoice_prefix = escapeHtml($row['invoice_prefix']);
$invoice_number = intval($row['invoice_number']);
$invoice_scope = escapeHtml($row['invoice_scope']);
$invoice_status = escapeHtml($row['invoice_status']);
$invoice_date = escapeHtml($row['invoice_date']);
$invoice_due = escapeHtml($row['invoice_due']);
$invoice_amount = floatval($row['invoice_amount']);
?>
<option value="<?= $invoice_id ?>"><?= "$invoice_prefix$invoice_number | $invoice_scope" ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<!-- The time on it -->
<div class="d-flex flex-wrap align-items-center gap-3 p-3 mb-3 rounded bg-body-tertiary">
<div class="me-auto">
<div class="small text-body-secondary">Time logged</div>
<div class="fs-5 fw-semibold"><?= $row['seconds'] ? billingDuration($row['seconds']) : 'None' ?></div>
</div>
<div class="small text-body-secondary flex-grow-1">
<?php if ($agents) {
foreach ($agents as $agent) { ?>
<div><?= escapeHtml($agent['user_name'] ?: 'Someone removed') ?> - <?= billingDuration($agent['seconds']) ?> in <?= intval($agent['entries']) ?> <?= intval($agent['entries']) === 1 ? 'reply' : 'replies' ?></div>
<?php }
} else { ?>
<div class="text-warning-emphasis">No time logged on it - type the hours to bill.</div>
<?php } ?>
</div>
<div class="text-end">
<div class="small text-body-secondary">To bill</div>
<div class="fs-5 fw-semibold"><?= billingQuantity($row['hours']) ?> h</div>
</div>
</div>
<div class="tab-pane fade <?php if (mysqli_num_rows($sql_invoices) == 0) { echo "active show"; } ?>" id="pills-create-invoice">
<div class="row">
<div class="col-sm-6">
<div class="mb-3">
<label>Invoice Date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date("Y-m-d") ?>">
</div>
</div>
</div>
<div class="col-sm-6">
<div class="mb-3">
<label>Invoice Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select select2" name="category">
<option value="">- Select a Category -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories WHERE category_type = 'Income' AND category_archived_at IS NULL ORDER BY category_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<option value="<?= $category_id ?>"<?= selectOptionColor($row['category_color'] ?? '', $row['category_icon'] ?? '') ?>><?= $category_name ?></option>
<?php
}
?>
</select>
<button type="button" class="btn btn-secondary ajax-modal" title="New category" data-modal-url="/admin/modals/category/category_add.php?category=Expense"><i class="fas fa-fw fa-plus"></i></button>
</div>
</div>
</div>
<div class="row g-3">
<div class="col-12">
<label class="form-label">Invoice</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-invoice"></i></span>
<select class="form-select" name="invoice_id" data-ticket-invoice-target>
<option value="0">A new draft invoice</option>
<?php foreach ($drafts as $draft_id => $draft) { ?>
<option value="<?= $draft_id ?>">Add to <?= escapeHtml(billingNumber('invoice', $draft)) ?><?= trim((string) $draft['invoice_scope']) !== '' ? ' - ' . escapeHtml($draft['invoice_scope']) : '' ?> (<?= escapeHtml(billingMoney($draft['invoice_amount'], $currency)) ?>)</option>
<?php } ?>
</select>
</div>
<div class="mb-3">
<label>Invoice Title</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<select class="form-select select2" name="scope" data-tags="true" data-placeholder="- Enter or Select an Invoice Title -">
<option value=""></option>
<option><?= date('F Y'); ?> Tickets</option>
<option><?= "Ticket $ticket_prefix$ticket_number - $ticket_subject" ?></option>
</select>
</div>
</div>
<div class="col-sm-6" data-ticket-invoice-new>
<label class="form-label">Invoice date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date('Y-m-d') ?>" required>
</div>
</div>
</div>
<div class="mb-3">
<label>Item <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-box"></i></span>
<input type="text" class="form-control" name="item_name" placeholder="Item" maxlength="200" value="Support [Hourly]" required>
</div>
</div>
<div class="mb-3">
<label>Item Description</label>
<div class="input-group">
<textarea class="form-control" rows="10" name="item_description"><?php
// Build description text cleanly in PHP, not mixed with HTML
$description = "Ticket {$ticket_prefix}{$ticket_number} - $ticket_subject - $ticket_date_description";
echo trim($description); // Trim any leading/trailing spaces/newlines
?></textarea>
</div>
</div>
<div class="row g-2">
<div class="col">
<div class="mb-3">
<label>QTY <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-balance-scale"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name="qty" value="<?= roundToNearest15Min($ticket_total_reply_time) ?>" required>
</div>
<small class="form-text text-muted">
From the <strong><?= $ticket_total_reply_time ?></strong> worked on the ticket, rounded to the nearest 15 minutes.
</small>
<div class="col-sm-6" data-ticket-invoice-new>
<label class="form-label">Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select" name="category" required>
<option value="">- Category -</option>
<?php foreach ($categories as $category_id => $category) { ?>
<option value="<?= intval($category_id) ?>"<?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col">
<div class="mb-3">
<label>Price <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control" inputmode="decimal" pattern="-?[0-9]*\.?[0-9]{0,2}" name="price" value="<?= number_format($client_rate, 2, '.', '') ?>" required>
</div>
<small class="form-text text-muted">
The client's hourly rate is <strong><?= numfmt_format_currency($currency_format, $client_rate, $session_company_currency); ?></strong>
</small>
<div class="col-12" data-ticket-invoice-new>
<label class="form-label">Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" maxlength="255" value="<?= escapeHtml($scopes[0]) ?>" list="ticketInvoiceScopes">
<datalist id="ticketInvoiceScopes">
<?php foreach ($scopes as $scope) { ?>
<option value="<?= escapeHtml($scope) ?>"></option>
<?php } ?>
</datalist>
</div>
</div>
</div>
<div class="mb-3">
<label>Tax <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-piggy-bank"></i></span>
<select class="form-select select2" name="tax_id" required>
<option value="0">None</option>
<?php
$taxes_sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent FROM taxes WHERE tax_archived_at IS NULL ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($taxes_sql)) {
$tax_id_select = intval($row['tax_id']);
$tax_name = escapeHtml($row['tax_name']);
$tax_percent = floatval($row['tax_percent']);
?>
<option value="<?= $tax_id_select ?>"><?= "$tax_name $tax_percent%" ?></option>
<?php } ?>
</select>
<div class="col-12">
<label class="form-label">Line <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-cube"></i></span>
<input type="text" class="form-control" name="item_name" maxlength="200" value="<?= escapeHtml($rules['item_name']) ?>" required>
</div>
</div>
<div class="col-12">
<label class="form-label">Description</label>
<div class="input-group">
<span class="input-group-text align-items-start pt-2"><i class="fa fa-fw fa-align-left"></i></span>
<textarea class="form-control" name="item_description" rows="2"><?= escapeHtml(billingTimeDescription($row)) ?></textarea>
</div>
</div>
<div class="col-sm-4">
<label class="form-label">Hours <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<input type="text" class="form-control text-end" name="qty" inputmode="decimal" value="<?= billingQuantity($row['hours']) ?>" required data-ticket-invoice-hours>
</div>
<div class="form-text">Rounded <?= escapeHtml(billingTimeRulesText($rules)) ?>.</div>
</div>
<div class="col-sm-4">
<label class="form-label">Rate <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control text-end" name="price" inputmode="decimal" value="<?= number_format($row['rate'], 2, '.', '') ?>" required data-ticket-invoice-rate>
</div>
<div class="form-text"><?= $row['rate'] > 0 ? ($row['default_rate'] ? 'The default rate - the client has none.' : "The client's hourly rate.") : 'No rate is set for the client, or as a default.' ?></div>
</div>
<div class="col-sm-4">
<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-ticket-invoice-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 class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
<span class="text-body-secondary">The line comes to</span>
<span class="fs-5 fw-semibold itflow-money" data-ticket-invoice-total></span>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="add_invoice_from_ticket" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Invoice</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
<button type="submit" name="add_invoice_from_ticket" class="btn btn-primary text-bold"><i class="fas fa-check me-2"></i><span data-ticket-invoice-label>Make Invoice</span></button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
</div>
</form>
<script>
(function () {
var form = document.getElementById('ticketInvoiceForm');
if (!form || form.dataset.wired) {
return;
}
form.dataset.wired = '1';
var currency = <?= json_encode($currency) ?>;
var target = form.querySelector('[data-ticket-invoice-target]');
var hours = form.querySelector('[data-ticket-invoice-hours]');
var rate = form.querySelector('[data-ticket-invoice-rate]');
var tax = form.querySelector('[data-ticket-invoice-tax]');
var total = form.querySelector('[data-ticket-invoice-total]');
var label = form.querySelector('[data-ticket-invoice-label]');
function number(value) {
var text = String(value || '').replace(/[\s,$]/g, '');
return text === '' ? NaN : Number(text);
}
function update() {
var making = target.value === '0';
form.querySelectorAll('[data-ticket-invoice-new]').forEach(function (section) {
section.hidden = !making;
section.querySelectorAll('input, select').forEach(function (input) {
input.disabled = !making;
});
});
label.textContent = making ? 'Make Invoice' : 'Add to Invoice';
var h = number(hours.value);
var r = number(rate.value);
if (isNaN(h) || isNaN(r)) {
total.textContent = 'Not a number';
return;
}
var option = tax.options[tax.selectedIndex];
var amount = Math.round(h * r * 100) / 100;
amount += Math.round(amount * Number(option ? option.getAttribute('data-percent') || 0 : 0)) / 100;
try {
total.textContent = new Intl.NumberFormat(undefined, { style: 'currency', currency: currency || 'USD' }).format(amount);
} catch (e) {
total.textContent = amount.toFixed(2);
}
}
form.addEventListener('input', update);
form.addEventListener('change', update);
update();
})();
</script>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -44,6 +44,18 @@ function billingPostBack($type, $id, $hash = 'items') {
redirect($url . ($hash !== '' ? "#$hash" : ''));
}
/** What billing time did, for the flash - "TCK-12 and 3 more billed on INV-45 - 6.5 h on 4 lines". */
function unbilledResultText(array $result) {
$tickets = $result['tickets'];
$what = count($tickets) === 1 ? $tickets[0] : $tickets[0] . ' and ' . (count($tickets) - 1) . ' more';
$text = '<strong>' . escapeHtml($what) . '</strong> billed on <strong>' . escapeHtml($result['number']) . '</strong> - ' . billingQuantity($result['hours']) . ' h'
. ($result['lines'] > 1 ? ' on ' . $result['lines'] . ' lines' : '');
if ($result['no_charge']) {
$text .= '. ' . escapeHtml(implode(', ', $result['no_charge'])) . (count($result['no_charge']) === 1 ? ' had' : ' had') . ' no hours, so went on with no charge';
}
return $text;
}
/** The audit log's name for each kind. */
function billingAuditType($type) {
return ['invoice' => 'Invoice', 'quote' => 'Quote', 'recurring' => 'Recurring Invoice'][$type] ?? 'Invoice';
@@ -202,3 +214,115 @@ if (isset($_GET['recurring_invoice_sync'])) {
redirect();
}
/*
* Unbilled Time, one client: bill the ticked tickets at the hours typed, on
* a new draft or one of the client's drafts.
*/
if (isset($_POST['unbilled_invoice'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$client_id = intval($_POST['client_id'] ?? 0);
enforceClientAccess();
$hours = [];
foreach (array_unique(array_map('intval', (array) ($_POST['ticket_ids'] ?? []))) as $ticket_id) {
$hours[$ticket_id] = $_POST['hours'][$ticket_id] ?? null;
}
$result = billingTimeInvoice($client_id, $hours, [
'invoice_id' => intval($_POST['invoice_id'] ?? 0),
'date' => (string) ($_POST['date'] ?? ''),
'category_id' => intval($_POST['category'] ?? 0),
'scope' => (string) ($_POST['scope'] ?? ''),
'item_name' => (string) ($_POST['item_name'] ?? ''),
'price' => (string) ($_POST['price'] ?? ''),
'tax_id' => intval($_POST['tax_id'] ?? 0),
'combine' => ($_POST['lines'] ?? '') === 'one',
'by' => $session_name,
], $error);
if (!$result) {
flashAlert(escapeHtml($error), 'error');
redirect();
}
flashAlert(unbilledResultText($result));
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.
*/
if (isset($_POST['unbilled_invoice_clients'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$use_draft = ($_POST['target'] ?? '') === 'draft';
$by_client = billingUnbilledByClient();
$made = [];
$failed = [];
foreach (array_unique(array_map('intval', (array) ($_POST['client_ids'] ?? []))) as $bill_client_id) {
if (!isset($by_client[$bill_client_id]) || !hasClientAccess($bill_client_id)) {
continue;
}
$c = $by_client[$bill_client_id];
$result = billingTimeInvoice($bill_client_id, array_fill_keys(array_keys($c['tickets']), null), [
'invoice_id' => $use_draft && $c['drafts'] ? intval(array_key_first($c['drafts'])) : 0,
'date' => (string) ($_POST['date'] ?? ''),
'category_id' => intval($_POST['category'] ?? 0),
'scope' => (string) ($_POST['scope'] ?? ''),
'item_name' => (string) ($_POST['item_name'] ?? ''),
'tax_id' => intval($_POST['tax_id'] ?? 0),
'combine' => ($_POST['lines'] ?? '') === 'one',
'by' => $session_name,
], $error);
if ($result) {
$made[] = $result;
} else {
$failed[] = $c['client_name'] . ': ' . $error;
}
}
if (!$made) {
flashAlert($failed ? escapeHtml(implode(' ', $failed)) : 'Nothing billed - tick at least one client.', 'error');
redirect('unbilled_time.php');
}
$tickets = array_sum(array_map(function ($r) { return count($r['tickets']); }, $made));
$hours = array_sum(array_column($made, 'hours'));
$numbers = array_column($made, 'number');
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' : ''))
. ($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. */
if (isset($_POST['unbilled_write_off'])) {
validateCSRFToken();
enforceUserPermission('module_sales', 2);
$client_id = intval($_POST['client_id'] ?? 0);
enforceClientAccess();
$done = billingTimeWriteOff($client_id, array_map('intval', (array) ($_POST['ticket_ids'] ?? [])), $session_name);
if (!$done) {
flashAlert('Nothing changed - tick the tickets 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);
flashAlert((count($done) === 1 ? '<strong>' . escapeHtml($done[0]) . '</strong> is' : '<strong>' . count($done) . ' tickets</strong> are') . ' not billable now');
redirect();
}

View File

@@ -100,7 +100,7 @@ if (isset($_POST['add_invoice_copy'])) {
invoice_currency_code, invoice_discount_amount, invoice_note, invoice_number,
invoice_prefix, invoice_scope FROM clients, invoices WHERE client_id = invoice_client_id AND invoice_id = $invoice_id");
$row = mysqli_fetch_assoc($sql);
$client_net_terms = intval($row['client_net_terms']) ?: intval($config_default_net_terms);
$client_net_terms = intval($row['client_net_terms']); // 0 is On Receipt
$invoice_scope = escapeSql($row['invoice_scope']);
$invoice_discount_amount = floatval($row['invoice_discount_amount']);
$invoice_amount = floatval($row['invoice_amount']);
@@ -813,6 +813,11 @@ if (isExportRequest('export_invoices')) {
* Put tickets on an invoice - billable ones of the same client that are
* resolved or closed and not on an invoice yet. ticket_ids[] (or ticket_id).
*/
/*
* Add Tickets: put the client's unbilled tickets on this invoice - with a
* line for each one's time (or one for all), or, with bill_time off, without
* lines when the work is already on the invoice some other way.
*/
if (isset($_POST['add_ticket_to_invoice'])) {
validateCSRFToken();
@@ -829,27 +834,32 @@ if (isset($_POST['add_ticket_to_invoice'])) {
enforceClientAccess();
$ticket_ids = array_filter(array_map('intval', (array) ($_POST['ticket_ids'] ?? [$_POST['ticket_id'] ?? 0])));
$added = [];
foreach (invoiceUnbilledTickets($client_id) as $ticket) {
if (in_array(intval($ticket['ticket_id']), $ticket_ids, true)) {
mysqli_query($mysqli, "UPDATE tickets SET ticket_invoice_id = $invoice_id WHERE ticket_id = " . intval($ticket['ticket_id']) . " AND ticket_invoice_id = 0");
$added[] = $ticket['ticket_prefix'] . $ticket['ticket_number'];
}
$hours = [];
foreach (array_unique(array_filter(array_map('intval', (array) ($_POST['ticket_ids'] ?? [$_POST['ticket_id'] ?? 0])))) as $ticket_id) {
$hours[$ticket_id] = $_POST['hours'][$ticket_id] ?? null;
}
if (!$added) {
flashAlert('Nothing added - those tickets are already billed, or not billable.', 'error');
$bill_time = !empty($_POST['bill_time']);
$result = billingTimeInvoice($client_id, $hours, [
'invoice_id' => $invoice_id,
'item_name' => (string) ($_POST['item_name'] ?? ''),
'price' => (string) ($_POST['price'] ?? ''),
'tax_id' => intval($_POST['tax_id'] ?? 0),
'combine' => ($_POST['lines'] ?? '') === 'one',
'lines' => $bill_time,
'by' => $session_name,
], $error);
if (!$result) {
flashAlert(escapeHtml($error), 'error');
redirect("invoice.php?invoice_id=$invoice_id");
}
$number = billingNumber('invoice', $invoice);
billingLog('invoice', $invoice_id, $invoice['invoice_status'], 'Ticket' . (count($added) === 1 ? ' ' : 's ') . implode(', ', $added) . " added by $session_name");
logAudit("Invoice", "Edit", escapeSql("$session_name added ticket" . (count($added) === 1 ? ' ' : 's ') . implode(', ', $added) . " to invoice $number"), $client_id, $invoice_id);
$count = count($result['tickets']);
$what = $count === 1 ? 'Ticket <strong>' . escapeHtml($result['tickets'][0]) . '</strong>' : "<strong>$count tickets</strong>";
flashAlert($bill_time
? "$what billed - " . billingQuantity($result['hours']) . ' h' . ($result['lines'] ? ' on ' . $result['lines'] . ' line' . ($result['lines'] === 1 ? '' : 's') : ', with no charge')
: "$what added to the invoice, without lines");
flashAlert(count($added) === 1 ? "Ticket <strong>" . escapeHtml($added[0]) . "</strong> added to the invoice" : count($added) . " tickets added to the invoice");
redirect("invoice.php?invoice_id=$invoice_id");
redirect("invoice.php?invoice_id=$invoice_id" . ($bill_time && $result['lines'] ? '#items' : ''));
}
@@ -875,6 +885,7 @@ if (isset($_GET['remove_ticket_from_invoice'])) {
mysqli_query($mysqli,"UPDATE tickets SET ticket_invoice_id = 0 WHERE ticket_id = $ticket_id");
$ticket_number = $ticket['ticket_prefix'] . $ticket['ticket_number'];
logTicketHistory($ticket_id, escapeSql('Taken off invoice ' . billingNumber('invoice', $invoice) . " by $session_name - unbilled again"));
billingLog('invoice', $invoice_id, $invoice['invoice_status'], "Ticket $ticket_number taken off by $session_name");
logAudit("Invoice", "Edit", escapeSql("$session_name took ticket $ticket_number off invoice " . billingNumber('invoice', $invoice)), $client_id, $invoice_id);

View File

@@ -1429,6 +1429,11 @@ if (isset($_GET['reopen_ticket'])) {
}
/*
* Invoice a ticket - its time, at the hours and rate in the window, on a new
* draft or one of the client's drafts. billingTimeInvoice() does it, the same
* as Unbilled Time; a ticket that isn't done yet can be billed from here.
*/
if (isset($_POST['add_invoice_from_ticket'])) {
validateCSRFToken();
@@ -1437,75 +1442,33 @@ if (isset($_POST['add_invoice_from_ticket'])) {
$row = ticketForRequest($_POST['ticket_id'] ?? 0, 2);
$ticket_id = intval($row['ticket_id']);
$reference = escapeSql(ticketReference($row));
if (!$client_id) {
flashAlert('Move the ticket to a client before invoicing it.', 'error');
redirect();
}
$invoice_id = intval($_POST['invoice_id'] ?? 0);
$date_input = (string) ($_POST['date'] ?? '');
$date = ($parsed_date = DateTime::createFromFormat('!Y-m-d', $date_input)) && $parsed_date->format('Y-m-d') === $date_input ? $date_input : date('Y-m-d');
$category = intval($_POST['category'] ?? 0);
$scope = escapeSql($_POST['scope'] ?? '');
$client_net_terms = intval(getFieldById('clients', $client_id, 'client_net_terms')) ?: intval($config_default_net_terms);
if ($invoice_id === 0) {
$invoice_prefix = escapeSql($config_invoice_prefix);
// Atomically increment and get the new invoice number
mysqli_query($mysqli, "UPDATE settings SET config_invoice_next_number = LAST_INSERT_ID(config_invoice_next_number), config_invoice_next_number = config_invoice_next_number + 1 WHERE company_id = 1");
$invoice_number = mysqli_insert_id($mysqli);
// A key for the client's guest link to it
$url_key = randomString(32);
mysqli_query($mysqli, "INSERT INTO invoices SET invoice_prefix = '$invoice_prefix', invoice_number = $invoice_number, invoice_scope = '$scope', invoice_date = '$date', invoice_due = DATE_ADD('$date', INTERVAL $client_net_terms day), invoice_currency_code = '$session_company_currency', invoice_category_id = $category, invoice_status = 'Draft', invoice_url_key = '$url_key', invoice_client_id = $client_id");
$invoice_id = mysqli_insert_id($mysqli);
} else {
// Only one of the ticket's client's draft invoices
$invoice = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT invoice_prefix, invoice_number FROM invoices WHERE invoice_id = $invoice_id AND invoice_client_id = $client_id AND invoice_status = 'Draft'"));
if (!$invoice) {
flashAlert("That invoice isn't one of this client's drafts.", 'error');
redirect();
}
$invoice_prefix = escapeSql($invoice['invoice_prefix']);
$invoice_number = intval($invoice['invoice_number']);
$result = billingTimeInvoice($client_id, [$ticket_id => (string) ($_POST['qty'] ?? '')], [
'invoice_id' => intval($_POST['invoice_id'] ?? 0),
'date' => (string) ($_POST['date'] ?? ''),
'category_id' => intval($_POST['category'] ?? 0),
'scope' => (string) ($_POST['scope'] ?? ''),
'item_name' => (string) ($_POST['item_name'] ?? ''),
'description' => isset($_POST['item_description']) ? (string) $_POST['item_description'] : null,
'price' => (string) ($_POST['price'] ?? ''),
'tax_id' => intval($_POST['tax_id'] ?? 0),
'include_open' => true,
'by' => $session_name,
], $error);
if (!$result) {
flashAlert(escapeHtml($error), 'error');
redirect();
}
// The line for the work
$item_name = escapeSql($_POST['item_name'] ?? '');
$item_description = escapeSql($_POST['item_description'] ?? '');
$qty = floatval($_POST['qty'] ?? 0);
$price = floatval($_POST['price'] ?? 0);
$tax_id = intval($_POST['tax_id'] ?? 0);
$subtotal = $price * $qty;
$tax_amount = 0;
if ($tax_id > 0) {
$tax_percent = floatval(getFieldById('taxes', $tax_id, 'tax_percent'));
$tax_amount = $subtotal * $tax_percent / 100;
}
$total = $subtotal + $tax_amount;
flashAlert('<strong>' . escapeHtml(ticketReference($row)) . '</strong> billed on <strong>' . escapeHtml($result['number']) . '</strong> - ' . billingQuantity($result['hours']) . ' h'
. ($result['lines'] ? '' : ', with no charge'));
mysqli_query($mysqli, "INSERT INTO invoice_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_order = 1, item_tax_id = $tax_id, item_invoice_id = $invoice_id");
mysqli_query($mysqli, "UPDATE invoices SET invoice_amount = invoice_amount + $total WHERE invoice_id = $invoice_id");
mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Draft', history_description = 'Invoice created from Ticket $reference', history_invoice_id = $invoice_id");
// Add internal note to ticket, and link to invoice in database
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Created invoice <a href=\"invoice.php?invoice_id=$invoice_id\">$invoice_prefix$invoice_number</a> for this ticket.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id");
mysqli_query($mysqli, "UPDATE tickets SET ticket_invoice_id = $invoice_id WHERE ticket_id = $ticket_id");
logAudit("Invoice", "Create", "$session_name created invoice $invoice_prefix$invoice_number from Ticket $reference", $client_id, $invoice_id);
flashAlert("Invoice <strong>" . escapeHtml($invoice_prefix . $invoice_number) . "</strong> created from ticket");
redirect("invoice.php?invoice_id=$invoice_id");
redirect("invoice.php?invoice_id={$result['invoice_id']}");
}

View File

@@ -2,45 +2,28 @@
/*
* Unbilled Work - billable tickets that are resolved or closed but on no
* invoice yet: money left on the table. Each ticket's time is rounded to the
* nearest 15 minutes and priced at the client's hourly rate - the same
* quantity and price Invoice fills in on the ticket - so the value
* here is what invoicing them would come to. Per client, then every ticket,
* the longest waiting first.
* invoice yet: money left on the table. Each ticket's time is rounded the
* way Admin > Settings > Invoice says and priced at the client's hourly rate
* - the same hours and rate Unbilled Time and a ticket's Invoice window fill
* in - so the value here is what invoicing them would come to. Per client,
* then every ticket, the longest waiting first.
*/
require_once "includes/inc_report.php";
reportEnforce('tickets_unbilled');
$client_id = reportClientId();
$default_rate = floatval($config_default_hourly_rate);
// The same tickets, hours and rates Unbilled Time bills - functions/billing.php
$time_rules = billingTimeRules();
$tickets = [];
$sql = mysqli_query($mysqli, "
SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_client_id, ticket_resolved_at, ticket_closed_at, ticket_assigned_to,
user_name, user_avatar, client_name, client_abbreviation, client_rate,
COALESCE((SELECT SUM(TIME_TO_SEC(ticket_reply_time_worked)) FROM ticket_replies WHERE ticket_reply_ticket_id = ticket_id AND ticket_reply_archived_at IS NULL), 0) AS seconds,
DATEDIFF(CURDATE(), COALESCE(ticket_resolved_at, ticket_closed_at)) AS waiting
FROM tickets
JOIN clients ON ticket_client_id = client_id
LEFT JOIN users ON ticket_assigned_to = user_id
WHERE ticket_billable = 1 AND ticket_invoice_id = 0 AND ticket_archived_at IS NULL
AND (ticket_resolved_at IS NOT NULL OR ticket_closed_at IS NOT NULL)
" . reportClientSql('ticket_client_id', $client_id) . "
ORDER BY waiting DESC, ticket_number ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$seconds = intval($row['seconds']);
// To the nearest quarter hour, as roundToNearest15Min() does for the invoice line
$quarters = intdiv($seconds, 900) + ($seconds % 900 > 450 ? 1 : 0);
$row['billable_hours'] = $quarters * 0.25;
$rate = floatval($row['client_rate']) > 0 ? floatval($row['client_rate']) : $default_rate;
$row['rate'] = $rate;
$row['default_rate'] = floatval($row['client_rate']) <= 0;
$row['value'] = $row['billable_hours'] * $rate;
$row['seconds'] = $seconds;
$row['waiting'] = intval($row['waiting']);
foreach (billingUnbilledTickets($client_id) as $row) {
$row['billable_hours'] = $row['hours'];
$tickets[] = $row;
}
usort($tickets, function ($a, $b) {
return $b['waiting'] <=> $a['waiting'] ?: intval($a['ticket_number']) <=> intval($b['ticket_number']);
});
$clients = [];
foreach ($tickets as $ticket) {
@@ -74,11 +57,11 @@ $client_columns = [
return reportClientCell($row['client_id'], $row['client'], $row['abbr']);
}],
'tickets' => ['label' => 'Tickets', 'type' => 'count', 'html' => function ($row) {
return '<a class="itflow-report-amount" href="/agent/tickets.php?client_id=' . $row['client_id'] . '&billing=unbilled&state=closed">' . reportCount($row['tickets']) . '</a>'
. ($row['no_time'] ? ' <span class="small text-warning-emphasis" title="Tickets with under 8 minutes logged - nothing to bill unless you add time">(' . $row['no_time'] . ' with no time)</span>' : '');
return '<a class="itflow-report-amount" href="/agent/unbilled_time.php?client_id=' . $row['client_id'] . '">' . reportCount($row['tickets']) . '</a>'
. ($row['no_time'] ? ' <span class="small text-warning-emphasis" title="Tickets with too little time logged to bill">(' . $row['no_time'] . ' with no time)</span>' : '');
}],
'seconds' => ['label' => 'Time logged', 'type' => 'hours', 'decimals' => 2],
'billable_hours' => ['label' => 'To bill', 'type' => 'decimal', 'decimals' => 2, 'title' => 'Hours rounded to the nearest 15 minutes, ticket by ticket'],
'billable_hours' => ['label' => 'To bill', 'type' => 'decimal', 'decimals' => 2, 'title' => 'Hours rounded ' . billingTimeRulesText($time_rules) . ', ticket by ticket'],
'rate' => ['label' => 'Rate', 'type' => 'money', 'html' => $rate_html],
'value' => ['label' => 'Value', 'type' => 'money', 'class' => 'fw-semibold'],
'oldest' => ['label' => 'Oldest waiting', 'type' => 'count', 'csv_label' => 'Oldest days waiting', 'html' => function ($row) use ($waiting_html) {
@@ -143,9 +126,9 @@ $over_30 = array_filter($tickets, function ($t) { return $t['waiting'] > 30; });
<?= reportStats([
['label' => 'Not invoiced yet', 'value' => reportMoney($totals['value']), 'tone' => $totals['value'] > 0 ? 'warning' : '',
'sub' => '<span class="text-body-tertiary">At each client\'s rate</span>'],
['label' => 'Tickets', 'value' => reportCount(count($tickets)), 'url' => '/agent/tickets.php?billing=unbilled&state=closed',
['label' => 'Tickets', 'value' => reportCount(count($tickets)), 'url' => '/agent/unbilled_time.php' . ($client_id ? "?client_id=$client_id" : ''),
'sub' => reportCount(count($clients)) . ' <span class="text-body-tertiary">client' . (count($clients) === 1 ? '' : 's') . '</span>'],
['label' => 'Hours to bill', 'value' => number_format($totals['billable_hours'], 2), 'sub' => escapeHtml(reportHours($totals['seconds'], 2)) . ' <span class="text-body-tertiary">logged</span>', 'title' => 'Each ticket\'s time rounded to the nearest 15 minutes'],
['label' => 'Hours to bill', 'value' => number_format($totals['billable_hours'], 2), 'sub' => escapeHtml(reportHours($totals['seconds'], 2)) . ' <span class="text-body-tertiary">logged</span>', 'title' => 'Each ticket\'s time rounded ' . billingTimeRulesText($time_rules)],
['label' => 'Waiting over 30 days', 'value' => reportCount(count($over_30)), 'tone' => $over_30 ? 'danger' : 'success',
'sub' => $over_30 ? escapeHtml(reportMoney(array_sum(array_column($over_30, 'value')))) . ' <span class="text-body-tertiary">of it</span>' : '<span class="text-body-tertiary">Nothing left that long</span>'],
]) ?>
@@ -154,7 +137,7 @@ $over_30 = array_filter($tickets, function ($t) { return $t['waiting'] > 30; });
<div class="alert alert-warning d-flex gap-2 align-items-start">
<i class="fas fa-exclamation-triangle mt-1"></i>
<div>
<?php if ($no_time) { ?><div><?= $no_time ?> billable ticket<?= $no_time === 1 ? ' has' : 's have' ?> under 8 minutes logged, so <?= $no_time === 1 ? 'it adds' : 'they add' ?> nothing here - log the time, or mark <?= $no_time === 1 ? 'it' : 'them' ?> not billable.</div><?php } ?>
<?php if ($no_time) { ?><div><?= $no_time ?> billable ticket<?= $no_time === 1 ? ' has' : 's have' ?> too little time logged to bill, so <?= $no_time === 1 ? 'it adds' : 'they add' ?> nothing here - log the time, type the hours in <a href="/agent/unbilled_time.php">Unbilled Time</a>, or mark <?= $no_time === 1 ? 'it' : 'them' ?> not billable there.</div><?php } ?>
<?php if ($no_rate) { ?><div><?= $no_rate ?> ticket<?= $no_rate === 1 ? ' is' : 's are' ?> for a client with no hourly rate - set one on the client, or a default hourly rate in Admin > Settings.</div><?php } ?>
</div>
</div>
@@ -171,7 +154,7 @@ $over_30 = array_filter($tickets, function ($t) { return $t['waiting'] > 30; });
<?= reportSectionOpen('Every ticket', 'Longest waiting first', 'itflow-report-long') ?>
<?= reportTable($ticket_columns, $tickets, ['limit' => 300, 'export_table' => 'tickets', 'totals' => ['ticket' => 'Total'] + $totals]) ?>
<div class="card-footer small text-body-secondary">
Billable tickets that are resolved or closed and on no invoice. To bill one, open it and choose Invoice - the hours and rate here are what it fills in.
Billable tickets that are resolved or closed and on no invoice. Bill them in <a href="/agent/unbilled_time.php<?= $client_id ? "?client_id=$client_id" : '' ?>">Unbilled Time</a> - the hours and rates here are what it fills in.
</div>
</div>
<?php } ?>

396
agent/unbilled_time.php Normal file
View File

@@ -0,0 +1,396 @@
<?php
/*
* Unbilled Time - billable tickets that are done (resolved or closed) and on
* no invoice yet: the time to bill.
*
* 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).
*
* 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.
*
* functions/billing.php (Billing time) counts and bills; the handlers are in
* agent/post/billing.php.
*/
if (isset($_GET['client_id'])) {
require_once "includes/inc_all_client.php";
$client_view = true;
} else {
require_once "includes/inc_all.php";
$client_view = false;
$client_id = 0;
}
enforceUserPermission('module_sales');
$can_edit = lookupUserPermission('module_sales') >= 2;
$ready = intval($config_module_enable_accounting) === 1 && intval($config_module_enable_ticketing) === 1;
$rules = billingTimeRules();
$clients = $ready ? billingUnbilledByClient($client_view ? $client_id : 0) : [];
$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];
foreach ($clients as $c) {
$total['tickets'] += count($c['tickets']);
$total['seconds'] += $c['seconds'];
$total['hours'] += $c['hours'];
$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;
}
$this_client = $client_view ? ($clients[$client_id] ?? null) : null;
$categories = billingCategories();
$taxes = billingTaxes();
$scope_options = ['Support - ' . date('F Y'), 'Support - ' . date('F Y', strtotime('first day of last month'))];
$waiting_pill = function ($days) {
$tone = $days > 30 ? 'danger' : ($days > 7 ? 'warning' : 'secondary');
return '<span class="badge rounded-pill bg-' . $tone . '-subtle text-' . $tone . '-emphasis fw-normal">'
. ($days <= 0 ? 'Today' : $days . ' day' . ($days === 1 ? '' : 's')) . '</span>';
};
$hours_text = function ($hours) {
return billingQuantity($hours) . ' h';
};
?>
<!-- What is waiting to be billed -->
<div class="row g-3 mb-3">
<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>
</div>
<div class="col-sm-6 col-xl-3">
<div class="itflow-billing-stat">
<div class="itflow-billing-stat-label"><i class="fas fa-stopwatch me-1"></i>Hours</div>
<div class="itflow-billing-stat-value"><?= $hours_text($total['hours']) ?></div>
<div class="itflow-billing-stat-note"><?= billingDuration($total['seconds']) ?> logged, rounded <?= escapeHtml(billingTimeRulesText($rules)) ?></div>
</div>
</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-note">
<?= $client_view ? '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>
</div>
<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>
</div>
</div>
<?php if (!$ready) { ?>
<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>
</div>
<?php } elseif (!$clients) { ?>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-user-clock me-2"></i>Unbilled Time</h3>
</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>
</div>
<?php } else { ?>
<form action="post.php" method="post" autocomplete="off" data-unbilled="<?= $client_view ? 'client' : 'clients' ?>">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php if ($client_view) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<div class="row g-3">
<div class="col-xl-8">
<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>
</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_edit) { ?>
<th class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" type="checkbox" checked data-unbilled-all title="Tick or untick them all" aria-label="All">
</div>
</th>
<?php } ?>
<?php if ($client_view) { ?>
<th>Ticket</th>
<th class="d-none d-md-table-cell">Done</th>
<th class="text-end">Logged</th>
<th class="text-end">Bill</th>
<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>
<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>
<?php } ?>
</tr>
</thead>
<tbody>
<?php if ($client_view) {
foreach ($this_client['tickets'] as $ticket_id => $ticket) { ?>
<tr data-unbilled-row data-rate="<?= floatval($ticket['rate']) ?>">
<?php if ($can_edit) { ?>
<td class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="ticket_ids[]" value="<?= $ticket_id ?>" checked data-unbilled-pick aria-label="Bill <?= escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) ?>">
</div>
</td>
<?php } ?>
<td class="min-w-0">
<a href="ticket.php?client_id=<?= $client_id ?>&ticket_id=<?= $ticket_id ?>"><span class="font-monospace small me-1 text-nowrap"><?= escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) ?></span><?= escapeHtml($ticket['ticket_subject']) ?></a>
<div class="small text-body-secondary">
<?= $ticket['user_name'] ? escapeHtml($ticket['user_name']) : 'Unassigned' ?>
<?php if (intval($ticket['ticket_onsite'])) { ?>
<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal ms-1"><i class="fas fa-car-side me-1"></i>Onsite</span>
<?php } ?>
</div>
</td>
<td class="text-nowrap d-none d-md-table-cell">
<div class="small"><?= escapeHtml(date('Y-m-d', strtotime((string) ($ticket['ticket_resolved_at'] ?: $ticket['ticket_closed_at'])))) ?></div>
<?= $waiting_pill($ticket['waiting']) ?>
</td>
<td class="text-end text-nowrap <?= $ticket['seconds'] ? '' : 'text-warning-emphasis' ?>" <?= $ticket['seconds'] ? '' : 'title="No time logged - type the hours to bill, or leave it at 0 to put it on the invoice with no charge"' ?>><?= $ticket['seconds'] ? billingDuration($ticket['seconds']) : 'None' ?></td>
<td class="text-end itflow-unbilled-hours">
<?php if ($can_edit) { ?>
<input type="text" class="form-control form-control-sm text-end" name="hours[<?= $ticket_id ?>]" value="<?= billingQuantity($ticket['hours']) ?>" inputmode="decimal" aria-label="Hours to bill" data-unbilled-hours>
<?php } else { ?>
<?= $hours_text($ticket['hours']) ?>
<?php } ?>
</td>
<td class="text-end text-nowrap fw-semibold d-none d-sm-table-cell" data-unbilled-amount><?= $money($ticket['value']) ?></td>
</tr>
<?php }
} 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']) ?>">
<?php if ($can_edit) { ?>
<td class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="client_ids[]" value="<?= $id ?>" checked data-unbilled-pick aria-label="Bill <?= escapeHtml($c['client_name']) ?>">
</div>
</td>
<?php } ?>
<td>
<a class="fw-semibold" href="unbilled_time.php?client_id=<?= $id ?>"><?= escapeHtml($c['client_name']) ?></a>
<?php if ($c['drafts']) { ?>
<div class="small text-body-secondary" title="Newest draft">
<i class="fas fa-pencil-ruler me-1"></i><?= count($c['drafts']) ?> draft<?= count($c['drafts']) === 1 ? '' : 's' ?> &middot; <?= escapeHtml(billingNumber('invoice', $draft)) ?>
</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>
<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>
</td>
</tr>
<?php }
} ?>
</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>
</div>
</div>
<?php if ($can_edit) { ?>
<!-- How they go on -->
<div class="col-xl-4">
<div class="card itflow-unbilled-panel">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-fw fa-file-invoice-dollar text-secondary me-2"></i>Bill <?= $client_view ? 'them' : 'these clients' ?></h3>
</div>
<div class="card-body">
<div class="row g-3">
<?php if ($client_view) { ?>
<div class="col-12">
<label class="form-label">Invoice</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-invoice"></i></span>
<select class="form-select" name="invoice_id" data-unbilled-target>
<option value="0">A new draft invoice</option>
<?php foreach ($this_client['drafts'] as $draft_id => $draft) { ?>
<option value="<?= $draft_id ?>">Add to <?= escapeHtml(billingNumber('invoice', $draft)) ?><?= trim((string) $draft['invoice_scope']) !== '' ? ' - ' . escapeHtml($draft['invoice_scope']) : '' ?> (<?= $money($draft['invoice_amount']) ?>)</option>
<?php } ?>
</select>
</div>
</div>
<?php } else { ?>
<div class="col-12">
<label class="form-label">Invoices</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-file-invoice"></i></span>
<select class="form-select" name="target" data-unbilled-target>
<option value="new">A new draft for each client</option>
<option value="draft">Each client's newest draft, or a new one</option>
</select>
</div>
</div>
<?php } ?>
<div class="col-sm-6 col-xl-12" data-unbilled-new>
<label class="form-label">Invoice date <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-calendar"></i></span>
<input type="date" class="form-control" name="date" max="2999-12-31" value="<?= date('Y-m-d') ?>" required>
</div>
</div>
<div class="col-sm-6 col-xl-12" data-unbilled-new>
<label class="form-label">Category <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select" name="category" required>
<option value="">- Category -</option>
<?php foreach ($categories as $category_id => $category) { ?>
<option value="<?= intval($category_id) ?>"<?= selectOptionColor($category['category_color'] ?? '', $category['category_icon'] ?? '') ?>><?= escapeHtml($category['category_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-12" data-unbilled-new>
<label class="form-label">Scope</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-comment"></i></span>
<input type="text" class="form-control" name="scope" maxlength="255" value="<?= escapeHtml($scope_options[0]) ?>" list="unbilledScopes">
<datalist id="unbilledScopes">
<?php foreach ($scope_options as $scope_option) { ?>
<option value="<?= escapeHtml($scope_option) ?>"></option>
<?php } ?>
</datalist>
</div>
</div>
<div class="col-12">
<label class="form-label">Line</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-cube"></i></span>
<input type="text" class="form-control" name="item_name" maxlength="200" value="<?= escapeHtml($rules['item_name']) ?>" required>
</div>
</div>
<?php if ($client_view) { ?>
<div class="col-sm-6 col-xl-12">
<label class="form-label">Rate <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-dollar-sign"></i></span>
<input type="text" class="form-control text-end" name="price" inputmode="decimal" value="<?= number_format($this_client['rate'], 2, '.', '') ?>" required data-unbilled-rate>
</div>
<div class="form-text">An hour<?= $this_client['default_rate'] ? ' - the default, the client has no rate' : " - the client's rate" ?></div>
</div>
<?php } ?>
<div class="<?= $client_view ? 'col-sm-6 col-xl-12' : 'col-12' ?>">
<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-unbilled-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 class="col-12">
<label class="form-label">Lines</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-list"></i></span>
<select class="form-select" name="lines">
<option value="each">A line for each ticket</option>
<option value="one">One line for all of them</option>
</select>
</div>
</div>
</div>
</div>
<div class="card-footer">
<div class="d-flex justify-content-between align-items-end mb-3">
<div class="small text-body-secondary" data-unbilled-summary></div>
<div class="fs-4 fw-semibold itflow-money" data-unbilled-total></div>
</div>
<div class="d-flex flex-wrap gap-2">
<button type="submit" name="<?= $client_view ? 'unbilled_invoice' : 'unbilled_invoice_clients' ?>" value="1" class="btn btn-primary text-bold flex-grow-1" data-unbilled-submit>
<i class="fas fa-check me-2"></i><span data-unbilled-submit-label><?= $client_view ? 'Make Invoice' : 'Make Invoices' ?></span>
</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">
<i class="fas fa-ban me-2"></i>Not billable
</button>
<?php } ?>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
<?php } ?>
<script src="/js/billing_items.js"></script>
<script src="/js/unbilled_time.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
itflowUnbilledTime({
currency: <?= json_encode($currency) ?>,
locale: <?= json_encode(str_replace('_', '-', (string) $session_company_locale)) ?>
});
});
</script>
<?php require_once "../includes/footer.php";

View File

@@ -6016,6 +6016,33 @@ a.itflow-report-stat:focus-visible {
.itflow-paper-add-seat {
flex: 0 0 7.5rem;
}
/* Unbilled Time - an unticked row fades, the hours box is narrow, and the billing panel stays in view on wide screens */
.itflow-unbilled-table tr.itflow-unbilled-off > td:not(.checkbox-column) {
opacity: .45;
}
.itflow-unbilled-table tbody tr[data-unbilled-row] {
cursor: pointer;
}
.itflow-unbilled-hours {
width: 6.5rem;
}
.itflow-unbilled-hours .form-control {
min-width: 4.5rem;
}
@media (max-width: 575.98px) {
.itflow-unbilled-hours {
width: 4.75rem;
}
.itflow-unbilled-hours .form-control {
min-width: 3.5rem;
}
}
@media (min-width: 1200px) {
.itflow-unbilled-panel {
position: sticky;
top: 4.5rem;
}
}
/* A recurring invoice's add row has one more box - the item takes the top row, the numbers the one under it */
.itflow-paper-add-grid-seats .itflow-paper-add-item {
flex-basis: 100%;

4
db.sql
View File

@@ -2452,6 +2452,10 @@ CREATE TABLE `settings` (
`config_default_calendar` int(11) DEFAULT NULL,
`config_default_net_terms` int(11) DEFAULT NULL,
`config_default_hourly_rate` decimal(15,2) NOT NULL DEFAULT 0.00,
`config_time_increment` int(11) NOT NULL DEFAULT 15,
`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_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

@@ -562,7 +562,7 @@ function invoiceTickets($invoice_id) {
$rows = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_created_at, ticket_closed_at,
COALESCE(SUM(TIME_TO_SEC(ticket_reply_time_worked)), 0) AS seconds
FROM tickets LEFT JOIN ticket_replies ON ticket_reply_ticket_id = ticket_id
FROM tickets LEFT JOIN ticket_replies ON ticket_reply_ticket_id = ticket_id AND ticket_reply_archived_at IS NULL
WHERE ticket_invoice_id = $invoice_id
GROUP BY ticket_id ORDER BY ticket_id DESC");
while ($row = mysqli_fetch_assoc($sql)) {
@@ -571,22 +571,369 @@ function invoiceTickets($invoice_id) {
return $rows;
}
/** A client's billable tickets, resolved or closed, not on an invoice yet. */
function invoiceUnbilledTickets($client_id) {
/* ------------------------------------------------------------ Billing time */
/*
* Time is billed by the ticket: a billable ticket that is resolved or closed
* is billed once, with all the time worked on it, onto an invoice line at the
* client's hourly rate (or the default rate when the client has none). The
* time is rounded the way Admin > Settings > Invoice says - to a step of
* minutes, to the nearest step or always up, never under a minimum - and
* ticket_invoice_id marks it billed. Unbilled Time, the ticket's Invoice
* window, Add Tickets on an invoice and the Unbilled Work report all count
* and price it with the functions here.
*/
/**
* The steps time can be rounded to, in minutes => label - each a whole
* number of hundredths of an hour, so the hours on a line are exact.
*/
function billingTimeIncrements() {
return [6 => '6 minutes (a tenth of an hour)', 12 => '12 minutes', 15 => '15 minutes (a quarter hour)', 30 => '30 minutes', 60 => 'An hour'];
}
/**
* How time is billed: increment (minutes), rounding ('nearest' or 'up'),
* minimum (minutes a ticket bills at least, once it has any time) and
* item_name (the line's name). Read once a request; until the database has
* the settings (2.9.2) it is the old way - the nearest 15 minutes.
*/
function billingTimeRules($fresh = false) {
global $mysqli;
static $rules = null;
if ($rules !== null && !$fresh) {
return $rules;
}
$rules = ['increment' => 15, 'rounding' => 'nearest', 'minimum' => 0, 'item_name' => 'Support [Hourly]'];
try {
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_time_increment, config_time_rounding, config_time_minimum, config_time_item_name FROM settings WHERE company_id = 1"));
} catch (mysqli_sql_exception $e) {
$row = null;
}
if ($row) {
$increment = intval($row['config_time_increment']);
$rules['increment'] = isset(billingTimeIncrements()[$increment]) ? $increment : 15;
$rules['rounding'] = $row['config_time_rounding'] === 'up' ? 'up' : 'nearest';
$rules['minimum'] = max(0, min(1440, intval($row['config_time_minimum'])));
$rules['item_name'] = trim((string) $row['config_time_item_name']) !== '' ? (string) $row['config_time_item_name'] : 'Support [Hourly]';
}
return $rules;
}
/** The rules in words - "to the nearest 15 minutes", "up to the next 6 minutes, at least 1 hour". */
function billingTimeRulesText(?array $rules = null) {
$rules = $rules ?? billingTimeRules();
$step = $rules['increment'] === 60 ? 'hour' : $rules['increment'] . ' minutes';
$text = $rules['rounding'] === 'up' ? "up to the next $step" : "to the nearest $step";
if ($rules['minimum'] > 0) {
$text .= ', at least ' . billingDuration($rules['minimum'] * 60);
}
return $text;
}
/**
* The hours to bill for some seconds of work: rounded to the step, then
* never under the minimum. No time logged bills nothing.
*/
function billingTimeHours($seconds, ?array $rules = null) {
$rules = $rules ?? billingTimeRules();
$seconds = max(0, intval($seconds));
if ($seconds === 0) {
return 0.0;
}
$step = $rules['increment'] * 60;
$steps = $rules['rounding'] === 'up' ? intdiv($seconds + $step - 1, $step) : intdiv($seconds, $step) + ($seconds % $step > $step / 2 ? 1 : 0);
return round(max($steps * $step, $rules['minimum'] * 60) / 3600, 2);
}
/** The hourly rate a client's time is billed at - its own, or the default. */
function billingTimeRate($client_rate) {
global $config_default_hourly_rate;
return floatval($client_rate) > 0 ? floatval($client_rate) : floatval($config_default_hourly_rate);
}
/**
* The SQL that makes a ticket unbilled: billable, resolved or closed, not
* archived, on no invoice. $include_open takes open ones too - the ticket's
* own Invoice window can bill a ticket before it is done.
*/
function billingUnbilledSql($include_open = false) {
return "ticket_billable = 1 AND ticket_invoice_id = 0 AND ticket_archived_at IS NULL AND ticket_client_id > 0"
. ($include_open ? '' : " AND ticket_status IN (" . TICKET_STATUS_RESOLVED . ", " . TICKET_STATUS_CLOSED . ")");
}
/**
* Unbilled tickets - one client's ($client_id), or every client the agent
* can open (0), optionally only $ticket_ids - longest waiting first. Each
* with its client, its assignee, the seconds worked (archived replies left
* out), the hours that bills, the rate and what that comes to, and the days
* since it was done.
*/
function billingUnbilledTickets($client_id = 0, array $ticket_ids = [], $include_open = false) {
global $mysqli;
$client_id = intval($client_id);
$ids = array_filter(array_map('intval', $ticket_ids));
$where = billingUnbilledSql($include_open && $ids) . ($client_id ? " AND ticket_client_id = $client_id" : '') . ($ids ? ' AND ticket_id IN (' . implode(',', $ids) . ')' : '')
. ' ' . clientScopeSql('ticket_client_id');
$rules = billingTimeRules();
$rows = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_created_at,
COALESCE(SUM(TIME_TO_SEC(ticket_reply_time_worked)), 0) AS seconds
FROM tickets LEFT JOIN ticket_replies ON ticket_reply_ticket_id = ticket_id
WHERE ticket_client_id = $client_id AND ticket_billable = 1 AND ticket_invoice_id = 0 AND ticket_status IN (4, 5)
GROUP BY ticket_id ORDER BY ticket_id DESC");
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_onsite, ticket_created_at, ticket_resolved_at, ticket_closed_at,
ticket_client_id, ticket_assigned_to, client_name, client_abbreviation, client_rate, user_name, user_avatar,
COALESCE((SELECT SUM(TIME_TO_SEC(ticket_reply_time_worked)) FROM ticket_replies WHERE ticket_reply_ticket_id = ticket_id AND ticket_reply_archived_at IS NULL), 0) AS seconds,
DATEDIFF(CURDATE(), COALESCE(ticket_resolved_at, ticket_closed_at, ticket_created_at)) AS waiting
FROM tickets
JOIN clients ON client_id = ticket_client_id
LEFT JOIN users ON user_id = ticket_assigned_to
WHERE $where
ORDER BY client_name ASC, waiting DESC, ticket_number ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
$row['seconds'] = intval($row['seconds']);
$row['waiting'] = max(0, intval($row['waiting']));
$row['hours'] = billingTimeHours($row['seconds'], $rules);
$row['rate'] = billingTimeRate($row['client_rate']);
$row['default_rate'] = floatval($row['client_rate']) <= 0;
$row['value'] = round($row['hours'] * $row['rate'], 2);
$rows[intval($row['ticket_id'])] = $row;
}
return $rows;
}
/**
* The same, by client - each client with its tickets, time, hours, value,
* how long the oldest has waited, how many have no time logged, and its
* draft invoices. Biggest value first.
*/
function billingUnbilledByClient($client_id = 0) {
global $mysqli;
$clients = [];
foreach (billingUnbilledTickets($client_id) as $ticket) {
$id = intval($ticket['ticket_client_id']);
if (!isset($clients[$id])) {
$clients[$id] = ['client_id' => $id, 'client_name' => $ticket['client_name'], 'client_abbreviation' => $ticket['client_abbreviation'],
'rate' => $ticket['rate'], 'default_rate' => $ticket['default_rate'], 'tickets' => [], 'seconds' => 0, 'hours' => 0.0, 'value' => 0.0,
'oldest' => 0, 'no_time' => 0, 'drafts' => []];
}
$clients[$id]['tickets'][intval($ticket['ticket_id'])] = $ticket;
$clients[$id]['seconds'] += $ticket['seconds'];
$clients[$id]['hours'] += $ticket['hours'];
$clients[$id]['value'] += $ticket['value'];
$clients[$id]['oldest'] = max($clients[$id]['oldest'], $ticket['waiting']);
$clients[$id]['no_time'] += $ticket['seconds'] === 0 ? 1 : 0;
}
if ($clients) {
$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(',', array_keys($clients)) . ")
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'] <=> $a['value'] ?: count($b['tickets']) <=> count($a['tickets']);
});
return $clients;
}
/** How many unbilled tickets the agent can see - for the menu. */
function billingUnbilledCount() {
global $mysqli;
return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM tickets WHERE " . billingUnbilledSql() . ' ' . clientScopeSql('ticket_client_id')))[0]);
}
/** A ticket's invoice line description - "Ticket TCK-123 - Subject - 10/14/2026". */
function billingTimeDescription(array $ticket) {
return 'Ticket ' . $ticket['ticket_prefix'] . $ticket['ticket_number'] . ' - ' . $ticket['ticket_subject'] . ' - ' . date('m/d/Y', strtotime((string) $ticket['ticket_created_at']));
}
/**
* A new draft invoice for a client, as New Invoice makes one: the next
* number, due on the client's terms, in the company's currency. Its id.
*/
function billingInvoiceCreate($client_id, $date, $category_id, $scope, $by) {
global $mysqli, $config_invoice_prefix, $session_company_currency;
$client_id = intval($client_id);
$date = ($parsed = DateTime::createFromFormat('!Y-m-d', (string) $date)) && $parsed->format('Y-m-d') === (string) $date ? (string) $date : date('Y-m-d');
$terms = intval(getFieldById('clients', $client_id, 'client_net_terms'));
$number = billingNextNumber('invoice');
$prefix = escapeSql($config_invoice_prefix);
$scope = escapeSql(mb_substr(trim((string) $scope), 0, 255));
$currency = escapeSql($session_company_currency);
$category_id = intval($category_id);
$url_key = randomString(32);
mysqli_query($mysqli, "INSERT INTO invoices SET invoice_prefix = '$prefix', invoice_number = $number, invoice_scope = '$scope', invoice_date = '$date',
invoice_due = DATE_ADD('$date', INTERVAL $terms DAY), invoice_amount = 0, invoice_currency_code = '$currency', invoice_category_id = $category_id,
invoice_status = 'Draft', invoice_url_key = '$url_key', invoice_client_id = $client_id");
$invoice_id = intval(mysqli_insert_id($mysqli));
if ($invoice_id) {
billingLog('invoice', $invoice_id, 'Draft', "Invoice created by $by");
}
return $invoice_id;
}
/**
* Bill tickets' time on an invoice. $hours is ticket id => hours to bill
* (null: what the rules make of the time logged). Only the client's
* unbilled tickets are taken, and each is claimed on the way 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, item_name, price (null: the client's rate), description (one ticket only)
* combine one line for all of them instead of one each
* lines false to put the tickets on without adding lines (billed by hand)
* include_open take tickets that aren't done yet too
* by who, for the history
* A ticket with no hours goes on the invoice without a line. Returns
* [invoice_id, number, new, tickets (references), hours, lines, no_charge]
* or null with $error.
*/
function billingTimeInvoice($client_id, array $hours, array $opts, &$error = '') {
global $mysqli;
$error = '';
$client_id = intval($client_id);
$by = (string) ($opts['by'] ?? 'ITFlow');
$tickets = $hours ? billingUnbilledTickets($client_id, array_keys($hours), !empty($opts['include_open'])) : [];
$add_lines = !isset($opts['lines']) || $opts['lines'];
if (!$client_id || !$tickets) {
$error = 'Nothing to bill - those tickets are already on an invoice, or no longer billable.';
return null;
}
// What each one bills
$bill = [];
foreach ($tickets as $ticket_id => $ticket) {
$value = $hours[$ticket_id] ?? null;
$h = ($value === null || $value === '') ? $ticket['hours'] : billingNumberInput($value);
if ($h === null || $h < 0 || $h >= 10000) {
$error = 'The hours for ' . $ticket['ticket_prefix'] . $ticket['ticket_number'] . ' have to be a number, zero or more.';
return null;
}
$bill[$ticket_id] = round($h, 2);
}
$price = isset($opts['price']) && $opts['price'] !== '' && $opts['price'] !== null ? billingNumberInput($opts['price']) : billingTimeRate(reset($tickets)['client_rate']);
if ($price === null || abs($price) >= 1e9) {
$error = 'The rate has to be a number.';
return null;
}
$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;
}
$item_name = trim((string) ($opts['item_name'] ?? ''));
$item_name = $item_name !== '' ? $item_name : billingTimeRules()['item_name'];
if (mb_strlen($item_name) > 200) {
$error = 'That line name is too long - keep it under 200 characters.';
return null;
}
// The invoice
$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 unbilled go on
mysqli_query($mysqli, "UPDATE tickets SET ticket_invoice_id = $invoice_id WHERE ticket_id IN (" . implode(',', array_keys($bill)) . ") AND ticket_client_id = $client_id
AND ticket_invoice_id = 0 AND ticket_billable = 1");
$claimed = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id FROM tickets WHERE ticket_invoice_id = $invoice_id AND ticket_id IN (" . implode(',', array_keys($bill)) . ")");
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 tickets just now.';
return null;
}
// The lines
$lines = 0;
$no_charge = [];
$references = [];
$total_hours = 0.0;
$combined = [];
foreach ($bill as $ticket_id => $h) {
if (!isset($claimed[$ticket_id])) {
continue;
}
$ticket = $tickets[$ticket_id];
$reference = $ticket['ticket_prefix'] . $ticket['ticket_number'];
$references[] = $reference;
$total_hours += $h;
if (!$add_lines) {
logTicketHistory($ticket_id, escapeSql("Put on invoice $number by $by - no line added"));
continue;
}
if ($h <= 0) {
$no_charge[] = $reference;
} elseif (!empty($opts['combine'])) {
$combined[] = billingTimeDescription($ticket) . ' (' . billingQuantity($h) . ' h)';
} else {
$description = count($bill) === 1 && isset($opts['description']) ? (string) $opts['description'] : billingTimeDescription($ticket);
if (billingItemSave('invoice', $invoice_id, ['name' => $item_name, 'description' => $description, 'qty' => $h, 'price' => $price, 'tax_id' => $tax_id])) {
$lines++;
}
}
logTicketHistory($ticket_id, escapeSql("Billed on invoice $number by $by - " . ($h > 0 ? billingQuantity($h) . ' h' : 'no charge')));
}
if ($combined) {
$combined_hours = round(array_sum(array_intersect_key($bill, $claimed)), 2);
if (billingItemSave('invoice', $invoice_id, ['name' => $item_name, 'description' => implode("\n", $combined), 'qty' => $combined_hours, 'price' => $price, 'tax_id' => $tax_id])) {
$lines++;
}
}
billingRecalc('invoice', $invoice_id);
$invoice = billingRow('invoice', $invoice_id, false);
$what = (count($references) === 1 ? 'ticket ' : count($references) . ' tickets ') . implode(', ', array_slice($references, 0, 20)) . (count($references) > 20 ? ' and more' : '');
if ($add_lines) {
billingLog('invoice', $invoice_id, $invoice['invoice_status'], ucfirst($what) . " billed by $by - " . billingQuantity($total_hours) . ' h');
logAudit('Invoice', $new ? 'Create' : 'Edit', escapeSql("$by billed $what on invoice $number - " . billingQuantity($total_hours) . ' h'), $client_id, $invoice_id);
} else {
billingLog('invoice', $invoice_id, $invoice['invoice_status'], ucfirst($what) . " added by $by, without lines");
logAudit('Invoice', 'Edit', escapeSql("$by added $what to invoice $number, without lines"), $client_id, $invoice_id);
}
if ($new) {
triggerCustomAction('invoice_create', $invoice_id);
}
return ['invoice_id' => $invoice_id, 'number' => $number, 'new' => $new, 'tickets' => $references, 'hours' => round($total_hours, 2), 'lines' => $lines, 'no_charge' => $no_charge];
}
/**
* Mark unbilled tickets not billable - written off, so they leave Unbilled
* Time. Each gets it in its history. The references it changed.
*/
function billingTimeWriteOff($client_id, array $ticket_ids, $by) {
global $mysqli;
$tickets = $ticket_ids ? billingUnbilledTickets($client_id, $ticket_ids) : [];
$done = [];
foreach ($tickets as $ticket_id => $ticket) {
mysqli_query($mysqli, "UPDATE tickets SET ticket_billable = 0 WHERE ticket_id = $ticket_id AND ticket_invoice_id = 0 AND ticket_billable = 1");
if (mysqli_affected_rows($mysqli) === 1) {
logTicketHistory($ticket_id, escapeSql("Marked not billable by $by - " . billingDuration($ticket['seconds']) . ' logged was not billed'));
$done[] = $ticket['ticket_prefix'] . $ticket['ticket_number'];
}
}
return $done;
}
/** Seconds as "1h 30m". */
function billingDuration($seconds) {
$seconds = intval($seconds);

View File

@@ -79,10 +79,9 @@ function clientOverviewAttention($client_id, $access, $renewals) {
];
if ($access['tickets']) {
$items[] = [
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE ticket_client_id = $client_id
AND ticket_resolved_at IS NOT NULL AND ticket_billable = 1 AND ticket_invoice_id = 0"),
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE " . billingUnbilledSql() . " AND ticket_client_id = $client_id"),
'label' => 'Resolved, not invoiced', 'icon' => 'receipt', 'tone' => 'info',
'url' => "/agent/tickets.php?client_id=$client_id&billing=unbilled&state=closed",
'url' => "/agent/unbilled_time.php?client_id=$client_id",
];
}
}
@@ -514,8 +513,8 @@ function clientOverviewActivity($client_id, $limit = 6) {
* The money figures. Balance is invoiced minus paid, all time - the same as
* 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 resolved billable tickets with no invoice, and the time
* logged on them.
* 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.
*/
function clientOverviewMoney($client_id, $balance, $recurring_monthly) {
$year_start = date('Y-01-01');
@@ -536,7 +535,7 @@ function clientOverviewMoney($client_id, $balance, $recurring_monthly) {
$overdue = dashboardSum("SELECT SUM(invoice_amount) FROM invoices WHERE $overdue_where")
- dashboardSum("SELECT SUM(payment_amount) FROM payments JOIN invoices ON payment_invoice_id = invoice_id WHERE $overdue_where");
$unbilled_where = "ticket_client_id = $client_id AND ticket_resolved_at IS NOT NULL AND ticket_billable = 1 AND ticket_invoice_id = 0";
$unbilled = billingUnbilledByClient($client_id)[intval($client_id)] ?? null;
return [
'balance' => $balance,
@@ -544,10 +543,9 @@ function clientOverviewMoney($client_id, $balance, $recurring_monthly) {
'paid_ytd' => $paid_ytd,
'paid_change' => dashboardChange($paid_ytd, $paid_last_ytd),
'recurring' => $recurring_monthly,
'unbilled_tickets' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $unbilled_where"),
'unbilled_seconds' => intval(dashboardSum("SELECT SUM(TIME_TO_SEC(ticket_reply_time_worked)) FROM ticket_replies
JOIN tickets ON ticket_reply_ticket_id = ticket_id
WHERE ticket_reply_archived_at IS NULL AND $unbilled_where")),
'unbilled_tickets' => $unbilled ? count($unbilled['tickets']) : 0,
'unbilled_seconds' => $unbilled ? intval($unbilled['seconds']) : 0,
'unbilled_value' => $unbilled ? floatval($unbilled['value']) : 0.0,
];
}

View File

@@ -265,10 +265,9 @@ function dashboardAttention($access) {
];
if ($access['tickets']) {
$items[] = [
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE ticket_resolved_at IS NOT NULL
AND ticket_billable = 1 AND ticket_invoice_id = 0 $ticket_scope"),
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE " . billingUnbilledSql() . " $ticket_scope"),
'label' => 'Resolved, not invoiced', 'icon' => 'receipt', 'tone' => 'info',
'url' => '/agent/tickets.php?billing=unbilled&state=closed',
'url' => '/agent/unbilled_time.php',
];
}
}

173
js/unbilled_time.js Normal file
View File

@@ -0,0 +1,173 @@
/*
* 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.
* 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.
*
* Needs js/billing_items.js (itflowBillingMoney, itflowBillingNumber).
*
* itflowUnbilledTime({ currency: 'USD', locale: 'en-US' });
*/
function itflowUnbilledTime(options) {
var opts = options || {};
var form = document.querySelector('form[data-unbilled]');
if (!form) {
return;
}
var mode = form.getAttribute('data-unbilled');
var rows = Array.prototype.slice.call(form.querySelectorAll('[data-unbilled-row]'));
var all = form.querySelector('[data-unbilled-all]');
var rate = form.querySelector('[data-unbilled-rate]');
var tax = form.querySelector('[data-unbilled-tax]');
var target = form.querySelector('[data-unbilled-target]');
var summary = form.querySelector('[data-unbilled-summary]');
var total = form.querySelector('[data-unbilled-total]');
var submit = form.querySelector('[data-unbilled-submit]');
var submitLabel = form.querySelector('[data-unbilled-submit-label]');
function money(amount) {
return itflowBillingMoney(amount, opts.currency, opts.locale);
}
function number(value) {
var n = itflowBillingNumber(value);
return isNaN(n) ? 0 : n;
}
function plural(n, word) {
return n + ' ' + word + (n === 1 ? '' : 's');
}
function update() {
var picked = 0;
var tickets = 0;
var hours = 0;
var amount = 0;
var perHour = rate ? number(rate.value) : 0;
var option = tax && tax.options[tax.selectedIndex];
var percent = option ? Number(option.getAttribute('data-percent') || 0) : 0;
rows.forEach(function (row) {
var pick = row.querySelector('[data-unbilled-pick]');
var on = !pick || pick.checked;
row.classList.toggle('itflow-unbilled-off', !on);
if (mode === 'client') {
var input = row.querySelector('[data-unbilled-hours]');
var h = input ? number(input.value) : 0;
var line = Math.round(h * perHour * 100) / 100;
var cell = row.querySelector('[data-unbilled-amount]');
if (cell && input) {
cell.textContent = money(line);
}
if (input) {
input.classList.toggle('is-invalid', input.value.trim() !== '' && (isNaN(itflowBillingNumber(input.value)) || h < 0));
}
if (on) {
picked++;
tickets++;
hours += h;
amount += line;
}
} else if (on) {
picked++;
tickets += Number(row.getAttribute('data-tickets') || 0);
hours += Number(row.getAttribute('data-hours') || 0);
amount += Number(row.getAttribute('data-value') || 0);
}
});
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' : '');
}
if (total) {
total.textContent = money(taxed);
}
if (submit) {
submit.disabled = picked === 0;
}
if (submitLabel) {
if (mode === 'client') {
submitLabel.textContent = target && target.value !== '0' ? 'Add to Invoice' : 'Make Invoice';
} else {
submitLabel.textContent = picked === 1 ? 'Make 1 Invoice' : 'Make ' + picked + ' Invoices';
}
}
if (all) {
all.checked = picked > 0 && picked === rows.length;
all.indeterminate = picked > 0 && picked < rows.length;
}
// Not billable needs something ticked too
form.querySelectorAll('button[name="unbilled_write_off"]').forEach(function (button) {
button.disabled = picked === 0;
});
}
// A new invoice's own fields - only when one is made
function targetChanged() {
var making = !target || mode !== 'client' || target.value === '0';
form.querySelectorAll('[data-unbilled-new]').forEach(function (section) {
section.hidden = !making;
section.querySelectorAll('input, select').forEach(function (input) {
input.disabled = !making;
});
});
update();
}
if (all) {
all.addEventListener('change', function () {
rows.forEach(function (row) {
var pick = row.querySelector('[data-unbilled-pick]');
if (pick) {
pick.checked = all.checked;
}
});
update();
});
}
form.addEventListener('input', function (e) {
if (e.target.matches('[data-unbilled-hours], [data-unbilled-rate]')) {
update();
}
});
form.addEventListener('change', function (e) {
if (e.target.matches('[data-unbilled-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) {
row.addEventListener('click', function (e) {
if (e.target.closest('a, input, button, select, label')) {
return;
}
var pick = row.querySelector('[data-unbilled-pick]');
if (pick) {
pick.checked = !pick.checked;
update();
}
});
});
// Enter in an hours box moves to the next one rather than billing
form.addEventListener('keydown', function (e) {
if (e.key !== 'Enter' || !e.target.matches('[data-unbilled-hours]')) {
return;
}
e.preventDefault();
var inputs = Array.prototype.slice.call(form.querySelectorAll('[data-unbilled-hours]'));
var next = inputs[inputs.indexOf(e.target) + 1];
if (next) {
next.focus();
next.select();
}
});
targetChanged();
}