Rebuild all reports on a shared framework (functions/reports.php, inc_report.php, inc_report_layout.php, js/reports.js) with period, client and agent filters, sortable tables, CSV export of any table and clean print layouts, add Client Review (QBR), Renewals & Expirations, Asset Lifecycle, Documentation Coverage, Customer Satisfaction, Open Ticket Aging, Client Profitability, Quotes Pipeline and Mileage reports, make Budget vs Actual editable with save and copy-last-year, rename reports to say what they show, enforce module and feature access on every report page, exclude transfers from income via dashboardRevenueSql, limit portal ticket ratings to Good or Bad, seed ratings and Windows 10 holdouts in demo data, link Client Review from the client menu, and update the 26.11 changelog

This commit is contained in:
johnnyq
2026-10-16 00:04:40 -04:00
parent 076885fe3f
commit 15844faa9b
43 changed files with 8400 additions and 2945 deletions

View File

@@ -25,6 +25,10 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Client restrictions: if you limit agents to certain clients, that limit is now applied in places it used to slip through. This covers editing, archiving or deleting the client itself, the client list's bulk actions, credits, expenses, trips, recurring expenses, revenues, task approvals, the dashboard lists and the per-client reports. A restricted agent will lose access there. Company-wide report totals are unchanged.
- Dashboard: the Financial and Technical switches at the top of the dashboard are gone. Each part of the new dashboard shows to anyone whose role can open that part of ITFlow. If you used the switches to keep figures off someone's screen, take that module out of their role instead.
- Reports: each report now checks access on the page itself, not only in the menu, and is hidden when its part of ITFlow (accounting, ticketing or IT documentation) is turned off. Every report still needs the Reporting permission, plus:
- Sales for Receivables Aging and Recurring Revenue, which used to need Financial, as they show invoices. Unbilled Work also needs Sales now, in the menu as well as on the page.
- Financial for Mileage, which used to open with Reporting alone.
- Reports have new names that say what they show: Outstanding Balances is now Receivables Aging, Recurring Income by Client is Recurring Revenue, Expense by Vendor is Spend by Vendor, Tax Summary is Tax Collected, Unbilled Tickets is Unbilled Work, Time by Technician is Technician Performance, Tickets is Ticket Overview and SLA Summary is SLA Performance. The addresses are the same, so bookmarks still work, though the filters saved in an old bookmark may be ignored and the report opens on its default period.
- Notifications now follow access too. An agent only sees notifications for clients and areas they can open, so someone without sales access no longer sees invoice and quote notifications.
- Drop-downs: Tom Select is gone, replaced by ITFlow's own picker. It works the way you are used to: type to search, tick several in a multi-select, and type a new value in fields that allow it, such as ticket watchers. See Developer Updates if you have custom pages that used Tom Select.
- Several small windows are gone because the change is now made where the value is shown:
@@ -89,6 +93,38 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- receivables, and recurring revenue and expenses per month
- a cash flow chart that looks ahead using unpaid invoices, recurring invoices and recurring expenses
- receivables aging, top clients, account balances, the latest income and expenses, and trips
- **Reports** (rebuilt)
- Every report works the same way:
- pick a period (this or last month, this or last quarter, this or last year, the last 30 days, 90 days or 12 months, a past year, or your own dates), and narrow it to one client or one agent where that makes sense
- read the headline figures, compared with the period before, then the chart and the tables
- click a column heading to sort, and click a figure to open the tickets, invoices, income or expenses behind it
- Export downloads any table as a CSV with every row, and is recorded in the audit log. Print gives a clean page with your company name and the date.
- The Reports page lists every report you can open, grouped into Finance, Sales & Billing, Service Desk, and Clients & Documentation, with a search box. The menu on the left uses the same groups.
- New reports:
- Client Review: one client's quarter on a page, made to print for a business review (QBR). It covers their tickets and how fast they were handled, SLA and ratings, what the tickets were about, who raised them and which devices keep coming back, urgent tickets, projects, hardware to plan for, renewals, services needing a look, documentation gaps and billing. It opens with recommendations to talk through, and is also in the client's menu.
- Renewals & Expirations: domains, certificates, licenses and warranties due in the next 30 days to 12 months, or lapsed in the last 90 days, by month and by client. Ones that renew themselves show in blue and can be hidden.
- Asset Lifecycle: how old the hardware is, its warranty, and whether its operating system is still supported (Windows 10, Windows Server 2012 and older, macOS 13 and older and so on are flagged). It shows what reaches replacement age each quarter for the next two years, for budgeting, and lists the replacement candidates.
- Documentation Coverage: for each client, whether the basics are documented: primary and billing contacts, a primary location, assets with a location and an owner, networks, credentials, documents, domains, services and licenses. Each client gets a score, and what is missing links to the page to add it.
- Customer Satisfaction: the share of closed tickets rated good, how many get rated, by agent and by client, how ratings follow a late first reply or a slow fix, and every bad rating to follow up.
- Open Ticket Aging: the open tickets right now by how long they have been open, per agent and per client, with whose move it is, their SLA and when anything last happened.
- Client Profitability: income, direct costs and time per client, what you earn per hour against your target rate, and recurring revenue.
- Quotes Pipeline: quotes won, lost and open, the win rate by count and by value, and open quotes about to expire.
- Mileage: trips by agent and by client, valued at your rate per mile.
- Budget vs Actual: set a monthly budget for each expense category right on the report, or copy last year's, and see spending against it by month and category.
- Reworked reports:
- Profit & Loss: monthly or quarterly, with last year and the change beside each line, and the margin.
- Income and Expenses: by category across the year, with last year drawn as a dashed line.
- Spend by Vendor and Income by Client: the period against the one before, with a switch for those paid 600 or more for 1099s. Spend by Vendor adds each vendor's main category and recurring spend. Income by Client adds recurring revenue and the share of your top five clients.
- 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.
- 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.
- Technician Performance: hours logged and billable, utilization against the working days in the period, replies, tickets worked and resolved, SLA and satisfaction for each agent.
- SLA Performance and SLA by Client: targets met over time, by priority, by agent and by client, and the tickets past their SLA right now.
- Credential Rotation: how old every password is, the clients with the most due, which ones have 2FA, and every password due for a change.
- **Clients**
- The clients list has compact rows, filter chips you can remove one at a time, open ticket and balance columns, and tags under the industry with a + to add one. Clicking anywhere in the client's cell opens it.
- The client side menu shows the client's initials and name under an All clients link. Click it to switch to another client and stay on the same page.
@@ -276,6 +312,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- Records of one client can no longer be linked to another client's records: locations, contacts, vendors, assets, networks, domains, certificates, credentials, documents, files and projects.
- Users: Your account > Activity showed other agents' sign-ins. A password with a space at the start or end was saved inconsistently, so the agent either could not sign in or could sign in but not open credentials. Passwords are now saved exactly as typed.
- Users: disabling a user left a blank name in the audit log.
- Income on the dashboard and in the reports counted money moved between your own accounts as income when the transfer had been given a category.
- Client Portal: a ticket rating could be saved as any value. Only Good and Bad, the two buttons the portal shows, are accepted now. The demo data rated tickets Great and Ok, which the portal never offers, and now uses Good and Bad.
- Notifications that linked to a page did not open correctly from Admin pages.
- Messages showed a backslash before apostrophes and quotes in names, or showed `&` instead of `&`.
- The empty password strength meter showed on the credential form, and page numbers ran off the screen on phones.
@@ -346,6 +384,23 @@ If you are coming from 26.08 or earlier, the database update still has to be run
- `admin/modals/user/user_invite.php` is removed.
- Saving preferences no longer touches `users.user_extension_key`. The form had no extension field, so every save cleared it, and nothing else reads the key.
- Dashboard: `user_settings.user_config_dashboard_financial_enable` and `user_config_dashboard_technical_enable` are no longer read. The columns are left in place.
- Reports:
- `functions/reports.php` (loaded by `functions.php`) holds everything the report pages share:
- the catalogue, `reportCatalog()`, which drives the side menu and the Reports page, and access through `reportEnforce()`, `reportCan()` and `reportCatalogForUser()`
- periods (`reportPeriod()`, `reportRangeSql()`, `reportBuckets()`, `reportPeriodQuery()`) and request filters (`reportClientId()`, `reportAgentId()`, `reportClientSql()`)
- the page parts: `reportHeader()`, `reportStats()`, `reportChart()`, `reportTable()` and `reportSectionOpen()`
- CSV export with `reportExporting()` and `reportCsv()`, which guards against formulas and writes an audit log entry
- shared queries: `reportRenewals()`, `reportLifecycleAssets()`, `reportOsEndOfLife()` (the `REPORT_OS_END_OF_LIFE` list), `reportCoverage()` and `reportSlaCompliance()`
- A report page starts with `agent/reports/includes/inc_report.php` and `reportEnforce('key')`, works out its figures, sends a CSV if asked (`if (reportExporting()) reportCsv(...)`), and only then includes `inc_report_layout.php` to draw the page. To add a report, add it to `reportCatalog()` under the file name, and it shows in the menu and on the Reports page for whoever may open it.
- `reportTable()` columns take `label`, `type` (money, count, hours, duration, decimal, percent, date), `html`, `csv`, `csv_label`, `screen => false` (export only), `sort` and `title`. A row of `['_heading' => ...]` draws a heading row. Times export as decimal hours and the heading says so.
- Charts are drawn by `js/reports.js` from the JSON in `canvas[data-report-chart]`, with Chart.js. It also sorts `table[data-report-sort]`, submits `[data-report-autosubmit]` filters and runs the budget editor.
- `agent/reports/includes/inc_all_reports.php` is kept for custom report pages and now loads the two new includes.
- Tax Collected works out every tax for the period in one query (`taxCollected()` in the page), with the same figures as `getMonthlyTax()`.
- Budgets: `agent/post/budget.php` handles `save_budget` and `copy_budget`, needing Financial at level 2 and a CSRF token. A blank or zero amount removes that month's budget rather than storing 0.
- `dashboardRevenueSql()` in `functions/dashboard.php` is the one rule for which revenues count as income, used by the dashboard and the reports. It leaves out the incoming side of transfers.
- CSS: the `.itflow-report-*` classes in `css/itflow_custom.css`, with print rules that keep side-by-side cards together.
- Client portal: `add_ticket_feedback` stores only `Good` or `Bad`. Demo data rates some closed tickets and leaves a few older Windows machines on Windows 10, so the satisfaction and lifecycle reports have something to show.
- The client actions menu links to the Client Review for that client, and the credentials list's rotation report link keeps the client.
- 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.
- CSS: `[hidden] { display: none !important; }` at the top of `css/itflow_custom.css`, so the `hidden` attribute wins over `d-flex` and the other display utilities. `.pagination` wraps.

View File

@@ -1817,6 +1817,11 @@ function demoBuildAssets($mysqli, $profile, $index, $client_id, $location_id, $c
// fleet anyone recognises.
$batch = (int)floor(($number - 1) / 4);
$purchase_months = min(70, 3 + ($batch * 12) + (($seed + $index) % 7) + (int)floor($profile['age_days'] / 120));
// A few of the oldest Windows machines never made the move to Windows 11
$os = $model[2];
if (strpos($os, 'Windows 11') === 0 && $purchase_months >= 50 && ($seed + $index) % 3 === 0) {
$os = 'Windows 10 Pro 22H2';
}
$status = 'Deployed';
if ($number === $quantity && $quantity > 3) {
$status = 'Ready to Deploy';
@@ -1832,7 +1837,7 @@ function demoBuildAssets($mysqli, $profile, $index, $client_id, $location_id, $c
'asset_make' => $model[0],
'asset_model' => $model[1],
'asset_serial' => demoSerial($profile['abbreviation'] . $asset_type . $number),
'asset_os' => $model[2],
'asset_os' => $os,
'asset_uri' => $ip ? demoAssetUri($asset_type, $ip) : '',
'asset_status' => $status,
'asset_purchase_reference' => 'PO-' . demoSerial($profile['abbreviation'] . 'po' . $seed, 6),
@@ -2596,6 +2601,12 @@ function demoBuildTickets($mysqli, $profile, $index, $client_id, $contact_ids, $
'ticket_onsite' => !empty($ticket['onsite']) ? 1 : 0,
];
// Some contacts rate their closed tickets from the portal - a slow
// first reply is what earns most of the bad ratings
if (($sequence + $index) % 5 < 2) {
$fields['ticket_feedback'] = $slow || ($sequence + $index) % 23 === 0 ? 'Bad' : 'Good';
}
if (!empty($ticket['vendor']) && $vendor_ids) {
$fields['ticket_vendor_id'] = $vendor_ids[0];
$fields['ticket_vendor_ticket_number'] = 'V' . demoSerial($profile['abbreviation'] . 'vt' . $sequence, 7);
@@ -2675,7 +2686,7 @@ function demoBuildTickets($mysqli, $profile, $index, $client_id, $contact_ids, $
if ($stage['closed']) {
$fields['ticket_closed_at'] = demoDateTime($stage['closed'], 15, 30);
$fields['ticket_closed_by'] = $user_id;
$fields['ticket_feedback'] = $slot === 0 ? 'Great' : 'Ok';
$fields['ticket_feedback'] = 'Good';
}
if ($stage['status'] === $context['status_open'] && !empty($ticket['onsite'])) {
$fields['ticket_schedule'] = demoDateTime(-2, 10, 0);

View File

@@ -170,7 +170,7 @@ $filter_url = function ($changes) use ($client_url) {
<i class="fa fa-fw fa-download me-2"></i>Export
</a>
<?php } ?>
<a class="dropdown-item text-dark" href="reports/credential_rotation.php">
<a class="dropdown-item text-dark" href="reports/credential_rotation.php<?= $client_url ? '?client_id=' . intval($client_id) : '' ?>">
<i class="fa fa-fw fa-history me-2"></i>Rotation report
</a>
</div>

View File

@@ -1,6 +1,6 @@
<?php
/*
* The client actions menu - New Ticket, New Project, Edit, Export, Archive/Restore, Delete.
* The client actions menu - New Ticket, New Project, Edit, Export, Client Review, Archive/Restore, Delete.
* Shared by the client header (inc_client_top_head.php) and the client
* overview, so both offer exactly the same actions behind the same
* permissions. Include it inside a .dropdown, after its toggle button.
@@ -34,6 +34,11 @@
<i class="fas fa-fw fa-file-pdf me-2"></i>Export Data
</a>
<?php } ?>
<?php if (reportCan(reportFind('client_review'))) { ?>
<a class="dropdown-item" href="/agent/reports/client_review.php?client_id=<?= $client_id ?>">
<i class="fas fa-fw fa-clipboard-list me-2"></i>Client Review
</a>
<?php } ?>
<?php if (empty($client_archived_at)) { ?>
<div class="dropdown-divider"></div>

View File

@@ -252,7 +252,7 @@ ob_start();
<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 up to the next 15 minutes.
From the <strong><?= $ticket_total_reply_time ?></strong> worked on the ticket, rounded to the nearest 15 minutes.
</small>
</div>

114
agent/post/budget.php Normal file
View File

@@ -0,0 +1,114 @@
<?php
/*
* ITFlow - the budget behind Reports > Budget vs Actual: what is planned to
* be spent each month of a year, by expense category.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
/** A budget year that makes sense, or 0. */
function budgetYear($value) {
$year = intval($value);
return ($year >= 2000 && $year <= intval(date('Y')) + 5) ? $year : 0;
}
if (isset($_POST['save_budget'])) {
validateCSRFToken();
enforceUserPermission('module_financial', 2);
$year = budgetYear($_POST['year'] ?? 0);
if (!$year) {
flashAlert('That is not a year a budget can be set for.', 'error');
redirect('/agent/reports/budget.php');
}
// Only expense categories take a budget
$categories = [];
$sql = mysqli_query($mysqli, "SELECT category_id FROM categories WHERE category_type = 'Expense'");
while ($row = mysqli_fetch_assoc($sql)) {
$categories[intval($row['category_id'])] = true;
}
// What is there now, one row per category and month (an older duplicate is folded away below)
$existing = [];
$sql = mysqli_query($mysqli, "SELECT budget_id, budget_category_id, budget_month FROM budget WHERE budget_year = $year ORDER BY budget_id ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$existing[intval($row['budget_category_id'])][intval($row['budget_month'])][] = intval($row['budget_id']);
}
$changed = 0;
foreach ((array) ($_POST['budget'] ?? []) as $category_id => $months) {
$category_id = intval($category_id);
if (!isset($categories[$category_id]) || !is_array($months)) {
continue;
}
foreach ($months as $month => $value) {
$month = intval($month);
if ($month < 1 || $month > 12) {
continue;
}
$amount = round(max(0, floatval(str_replace([',', ' '], ['', ''], (string) $value))), 2);
$ids = $existing[$category_id][$month] ?? [];
if ($amount <= 0) {
if ($ids) {
mysqli_query($mysqli, "DELETE FROM budget WHERE budget_id IN (" . implode(',', $ids) . ")");
$changed++;
}
continue;
}
if ($ids) {
$keep = array_shift($ids);
mysqli_query($mysqli, "UPDATE budget SET budget_amount = $amount WHERE budget_id = $keep AND budget_amount <> $amount");
$changed += mysqli_affected_rows($mysqli) > 0 ? 1 : 0;
if ($ids) {
mysqli_query($mysqli, "DELETE FROM budget WHERE budget_id IN (" . implode(',', $ids) . ")");
}
} else {
mysqli_query($mysqli, "INSERT INTO budget SET budget_year = $year, budget_month = $month, budget_amount = $amount, budget_category_id = $category_id");
$changed++;
}
}
}
if ($changed) {
logAudit("Budget", "Edit", "$session_name updated the $year budget ($changed change" . ($changed === 1 ? '' : 's') . ")");
}
flashAlert($changed ? "The $year budget is saved" : "Nothing changed in the $year budget", $changed ? 'success' : 'info');
redirect("/agent/reports/budget.php?year=$year");
}
if (isset($_POST['copy_budget'])) {
validateCSRFToken();
enforceUserPermission('module_financial', 2);
$year = budgetYear($_POST['year'] ?? 0);
if (!$year) {
flashAlert('That is not a year a budget can be set for.', 'error');
redirect('/agent/reports/budget.php');
}
$from_year = $year - 1;
$count = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM budget WHERE budget_year = $from_year"))[0]);
if (!$count) {
flashAlert("There is no $from_year budget to copy.", 'error');
redirect("/agent/reports/budget.php?year=$year&view=edit");
}
mysqli_query($mysqli, "DELETE FROM budget WHERE budget_year = $year");
mysqli_query($mysqli, "INSERT INTO budget (budget_month, budget_year, budget_amount, budget_description, budget_category_id)
SELECT budget_month, $year, budget_amount, budget_description, budget_category_id FROM budget WHERE budget_year = $from_year");
logAudit("Budget", "Edit", "$session_name copied the $from_year budget into $year");
flashAlert("$from_year's budget is copied into $year - change any month and save");
redirect("/agent/reports/budget.php?year=$year&view=edit");
}

View File

@@ -0,0 +1,295 @@
<?php
/*
* Asset Lifecycle - the hardware still in use (not archived, lost, stolen or
* retired): how old it is, where its warranty stands and which operating
* systems are past their end of support. Then what comes due for
* replacement over the next two years, by type and by client, and the
* replacement candidates one by one - for planning budgets and refresh
* projects with clients. Age runs from the purchase date, else the install
* date.
*/
require_once "includes/inc_report.php";
reportEnforce('asset_lifecycle');
$year_choices = [3 => 'Replace after 3 years', 4 => 'Replace after 4 years', 5 => 'Replace after 5 years', 6 => 'Replace after 6 years', 7 => 'Replace after 7 years'];
$years = isset($year_choices[intval($_GET['years'] ?? 0)]) ? intval($_GET['years']) : 5;
$limit_days = $years * 365.25;
$client_id = reportClientId();
$type = trim((string) ($_GET['type'] ?? ''));
$assets = reportLifecycleAssets($client_id, $type);
$empty = ['assets' => 0, 'dated' => 0, 'age_total' => 0, 'old' => 0, 'undated' => 0, 'expired' => 0, 'ending' => 0, 'os' => 0];
$totals = $empty;
$by_type = [];
$by_client = [];
$candidates = [];
$os_names = [];
foreach ($assets as &$asset) {
$hardware = $asset['asset_type'] !== 'Virtual Machine';
$asset['old'] = $asset['age_days'] !== null && $asset['age_days'] >= $limit_days;
$asset['expired'] = $asset['warranty'] && $asset['warranty']['days'] < 0;
$asset['ending'] = $asset['warranty'] && $asset['warranty']['days'] >= 0 && $asset['warranty']['days'] <= 90;
$t = $asset['asset_type'] ?: 'Other';
$c = intval($asset['asset_client_id']);
$by_type[$t] = $by_type[$t] ?? ['type' => $t] + $empty;
$by_client[$c] = $by_client[$c] ?? ['client_id' => $c, 'client' => $asset['client_name'], 'abbr' => $asset['client_abbreviation']] + $empty;
foreach ([&$totals, &$by_type[$t], &$by_client[$c]] as &$group) {
$group['assets']++;
if ($asset['age_days'] !== null) {
$group['dated']++;
$group['age_total'] += $asset['age_days'];
} elseif ($hardware) {
$group['undated']++;
}
$group['old'] += $asset['old'] ? 1 : 0;
$group['expired'] += $asset['expired'] ? 1 : 0;
$group['ending'] += $asset['ending'] ? 1 : 0;
$group['os'] += $asset['os_eol'] !== '' ? 1 : 0;
}
unset($group);
if ($asset['os_eol'] !== '') {
$os_names[$asset['os_eol']] = ($os_names[$asset['os_eol']] ?? 0) + 1;
}
if ($asset['old'] || $asset['os_eol'] !== '') {
$candidates[] = $asset;
}
}
unset($asset);
$average = function ($group) {
return $group['dated'] ? $group['age_total'] / $group['dated'] : null;
};
foreach ([&$by_type, &$by_client] as &$groups) {
foreach ($groups as &$group) {
$group['average'] = $average($group);
}
unset($group);
}
unset($groups);
$totals['average'] = $average($totals);
uasort($by_type, function ($a, $b) { return $b['assets'] <=> $a['assets']; });
uasort($by_client, function ($a, $b) { return $b['old'] + $b['os'] <=> $a['old'] + $a['os'] ?: $b['assets'] <=> $a['assets']; });
usort($candidates, function ($a, $b) { return ($b['age_days'] ?? -1) <=> ($a['age_days'] ?? -1); });
arsort($os_names);
$count_cell = function ($key, $tone) {
return function ($row) use ($key, $tone) {
return $row[$key] ? '<span class="text-' . $tone . '-emphasis fw-semibold">' . reportCount($row[$key]) . '</span>' : '<span class="itflow-report-zero">–</span>';
};
};
$figure_columns = [
'assets' => ['label' => 'In use', 'type' => 'count'],
'average' => ['label' => 'Average age', 'type' => 'decimal', 'csv_label' => 'Average age (years)', 'csv' => function ($row) {
return $row['average'] === null ? '' : number_format($row['average'] / 365.25, 1, '.', '');
}, 'html' => function ($row) {
return $row['average'] === null ? '<span class="itflow-report-zero">–</span>' : reportYears($row['average']);
}],
'old' => ['label' => "Over $years years", 'type' => 'count', 'html' => $count_cell('old', 'danger')],
'expired' => ['label' => 'Out of warranty', 'type' => 'count', 'html' => $count_cell('expired', 'danger')],
'ending' => ['label' => 'Ends in 90 days', 'type' => 'count', 'title' => 'The warranty ends in the next 90 days', 'html' => $count_cell('ending', 'warning')],
'os' => ['label' => 'Unsupported OS', 'type' => 'count', 'html' => $count_cell('os', 'danger')],
'undated' => ['label' => 'No date', 'type' => 'count', 'title' => 'Hardware with neither a purchase nor an install date', 'html' => function ($row) {
return $row['undated'] ? '<span class="text-body-secondary">' . reportCount($row['undated']) . '</span>' : '<span class="itflow-report-zero">–</span>';
}],
];
$type_columns = ['type' => ['label' => 'Type', 'html' => function ($row) {
return '<span class="d-inline-flex align-items-center gap-2"><span class="itflow-asset-icon itflow-asset-icon-sm itflow-asset-tone-' . assetTypeTone($row['type']) . '" aria-hidden="true"><i class="fas fa-fw fa-' . getAssetIcon($row['type']) . '"></i></span>'
. '<a class="text-body fw-semibold text-nowrap" href="' . escapeHtml(reportUrl(['type' => $row['type'], 'export' => null, 'table' => null])) . '">' . escapeHtml($row['type']) . '</a></span>';
}]] + $figure_columns;
$client_columns = ['client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'assets.php');
}]] + $figure_columns;
$warranty_pill = function ($warranty) {
if (!$warranty) {
return '<span class="text-body-tertiary small">No date</span>';
}
$tone = $warranty['tone'];
return '<span class="badge rounded-pill bg-' . $tone . '-subtle text-' . $tone . '-emphasis border border-' . $tone . '-subtle fw-normal text-nowrap" title="' . escapeHtml($warranty['text']) . '">'
. escapeHtml($warranty['short']) . '</span>';
};
$candidate_columns = [
'asset_name' => ['label' => 'Asset', 'html' => function ($row) { return reportAssetCell($row); }],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['asset_client_id'], $row['client_name'], $row['client_abbreviation'], 'assets.php');
}],
'asset_type' => ['label' => 'Type'],
'model' => ['label' => 'Make and model', 'csv' => function ($row) { return trim($row['asset_make'] . ' ' . $row['asset_model']); }, 'html' => function ($row) {
return '<span class="text-nowrap">' . escapeHtml(trim($row['asset_make'] . ' ' . $row['asset_model'])) . '</span>';
}],
'asset_os' => ['label' => 'Operating system', 'html' => function ($row) {
if ($row['os_eol'] === '') {
return '<span class="text-nowrap">' . escapeHtml($row['asset_os']) . '</span>';
}
return '<span class="text-danger-emphasis fw-semibold text-nowrap" title="Past its end of support">' . escapeHtml($row['asset_os']) . ' <i class="fas fa-fw fa-exclamation-circle small"></i></span>';
}],
'age_days' => ['label' => 'Age', 'type' => 'decimal', 'csv_label' => 'Age (years)', 'csv' => function ($row) {
return $row['age_days'] === null ? '' : number_format($row['age_days'] / 365.25, 1, '.', '');
}, 'html' => function ($row) {
return $row['age_days'] === null ? '<span class="itflow-report-zero">–</span>'
: '<span class="' . ($row['old'] ? 'text-danger-emphasis fw-semibold' : '') . '" title="Since ' . escapeHtml($row['age_date']) . '">' . reportYears($row['age_days']) . '</span>';
}],
'warranty' => ['label' => 'Warranty', 'sort' => false, 'csv' => function ($row) { return $row['warranty'] ? $row['warranty']['date'] : ''; }, 'csv_label' => 'Warranty ends',
'html' => function ($row) use ($warranty_pill) { return $warranty_pill($row['warranty']); }],
'contact_name' => ['label' => 'Used by', 'html' => function ($row) {
return $row['contact_name'] ? '<span class="text-nowrap">' . escapeHtml($row['contact_name']) . '</span>' : '<span class="text-body-tertiary">-</span>';
}],
'location_name' => ['label' => 'Location', 'screen' => false],
'asset_status' => ['label' => 'Status', 'screen' => false],
];
if (reportExporting('types')) {
reportCsv('Assets by Type', $type_columns, array_values($by_type), ['type' => 'Total'] + $totals);
}
if (reportExporting('clients')) {
reportCsv('Assets by Client', $client_columns, array_values($by_client), ['client' => 'Total'] + $totals);
}
if (reportExporting()) {
reportCsv('Replacement Candidates', $candidate_columns, $candidates);
}
require_once "includes/inc_report_layout.php";
// The age profile - a bar a year, red from the replacement age
$age_labels = [];
$age_counts = [];
$age_tones = [];
$top = max($years + 2, 8);
for ($y = 0; $y < $top; $y++) {
$age_labels[] = $y === $top - 1 ? "$y+ yrs" : "$y-" . ($y + 1) . ' yrs';
$age_counts[$y] = 0;
$age_tones[] = $y >= $years ? 'danger' : ($y === $years - 1 ? 'warning' : 'accent');
}
foreach ($assets as $asset) {
if ($asset['age_days'] !== null) {
$age_counts[min($top - 1, intdiv($asset['age_days'], 365))]++;
}
}
if ($totals['undated']) {
$age_labels[] = 'No date';
$age_counts[] = $totals['undated'];
$age_tones[] = 'muted';
}
// Coming due - hardware reaching the replacement age, by quarter for the next two years
$quarters = [];
$cursor = new DateTime('first day of this month');
$cursor->setDate(intval($cursor->format('Y')), intval((ceil($cursor->format('n') / 3) - 1) * 3 + 1), 1);
for ($q = 0; $q < 8; $q++) {
$key = $cursor->format('Y') . '-Q' . ceil($cursor->format('n') / 3);
$quarters[$key] = ['label' => 'Q' . ceil($cursor->format('n') / 3) . ' ' . $cursor->format('y'), 'count' => 0];
$cursor->modify('+3 months');
}
foreach ($assets as $asset) {
if ($asset['age_date'] !== null && !$asset['old']) {
$due = new DateTime($asset['age_date']);
$due->modify("+$years years");
$key = $due->format('Y') . '-Q' . ceil($due->format('n') / 3);
if (isset($quarters[$key])) {
$quarters[$key]['count']++;
}
}
}
$coming = array_sum(array_column($quarters, 'count'));
$warranty_counts = ['Covered' => 0, 'Ends within 90 days' => 0, 'Expired' => 0, 'No date' => 0];
foreach ($assets as $asset) {
if ($asset['asset_type'] === 'Virtual Machine') {
continue;
}
$warranty_counts[!$asset['warranty'] ? 'No date' : ($asset['expired'] ? 'Expired' : ($asset['ending'] ? 'Ends within 90 days' : 'Covered'))]++;
}
$type_choices = ['' => 'Every type'];
$sql = mysqli_query($mysqli, "SELECT DISTINCT asset_type FROM assets WHERE asset_archived_at IS NULL AND asset_type != '' " . reportClientSql('asset_client_id', 0) . " ORDER BY asset_type");
while ($row = mysqli_fetch_assoc($sql)) {
$type_choices[$row['asset_type']] = $row['asset_type'];
}
if ($type !== '' && !isset($type_choices[$type])) {
$type_choices[$type] = $type;
}
$dated_share = $totals['dated'] ? reportShare($totals['old'], $totals['dated'], 0) : null;
?>
<div class="itflow-report">
<?php reportHeader('asset_lifecycle', [
'subtitle' => 'As of ' . date('M j, Y'),
'client' => $client_id,
'controls' => reportSelectControl('type', $type, $type_choices, 'fa-desktop') . reportSelectControl('years', $years, $year_choices, 'fa-recycle'),
'export' => ['candidates' => 'Replacement candidates', 'types' => 'By type', 'clients' => 'By client'],
]); ?>
<?= reportStats([
['label' => 'Assets in use', 'value' => reportCount($totals['assets']), 'url' => '/agent/assets.php' . ($client_id ? "?client_id=$client_id" : ''),
'sub' => $totals['average'] !== null ? 'Average age <span class="text-body">' . reportYears($totals['average']) . '</span>' : ''],
['label' => "Over $years years old", 'value' => reportCount($totals['old']), 'tone' => $totals['old'] ? 'danger' : 'success',
'sub' => $dated_share !== null ? reportPercent($dated_share) . ' <span class="text-body-tertiary">of dated hardware</span>' : ''],
['label' => 'Out of warranty', 'value' => reportCount($totals['expired']), 'tone' => $totals['expired'] ? 'warning' : '',
'sub' => reportCount($totals['ending']) . ' <span class="text-body-tertiary">more within 90 days</span>'],
['label' => 'Unsupported OS', 'value' => reportCount($totals['os']), 'tone' => $totals['os'] ? 'danger' : 'success',
'sub' => $os_names ? escapeHtml(array_key_first($os_names)) . ' <span class="text-body-tertiary">the most</span>' : '<span class="text-body-tertiary">All supported or unknown</span>'],
]) ?>
<?php if (!$assets) { ?>
<div class="card"><div class="card-body"><?= reportEmpty('No assets in use match these filters.', 'fa-desktop', 'secondary') ?></div></div>
<?php } else { ?>
<div class="row g-3">
<div class="col-lg-7">
<?= reportSectionOpen('Age', 'From purchase, else install date', 'h-100') ?>
<div class="card-body">
<?= reportChart(['type' => 'bar', 'labels' => $age_labels, 'series' => [['label' => 'Assets', 'data' => array_values($age_counts), 'tones' => $age_tones]],
'format' => 'count', 'legend' => false], '', 'Assets in use by age') ?>
</div>
</div>
</div>
<div class="col-lg-5">
<?= reportSectionOpen('Warranty', 'Hardware', 'h-100') ?>
<div class="card-body">
<?= reportChart(['type' => 'doughnut', 'labels' => array_keys($warranty_counts), 'series' => [['label' => 'Assets', 'data' => array_values($warranty_counts)]],
'colors' => ['success', 'warning', 'danger', 'muted'], 'format' => 'count'], 'donut', 'Hardware by warranty') ?>
<div class="mt-3"><?= reportLegendHtml(array_keys($warranty_counts), array_values($warranty_counts), ['success', 'warning', 'danger', 'muted'], 'count') ?></div>
</div>
</div>
</div>
</div>
<?= reportSectionOpen("Reaching $years years", reportCount($coming) . ' over the next two years - for budgeting') ?>
<div class="card-body">
<?= reportChart(['type' => 'bar', 'labels' => array_column($quarters, 'label'), 'series' => [['label' => 'Reaching ' . $years . ' years', 'data' => array_column($quarters, 'count'), 'tone' => 'warning']],
'format' => 'count', 'legend' => false], 'sm', "Hardware reaching $years years old, by quarter") ?>
</div>
</div>
<?php if (!$type) { ?>
<?= reportSectionOpen('By type', 'Pick one to see only that type') ?>
<?= reportTable($type_columns, array_values($by_type), ['totals' => ['type' => 'Total'] + $totals, 'totals_html' => ['average' => $totals['average'] === null ? '' : reportYears($totals['average'])]]) ?>
</div>
<?php } ?>
<?php if (!$client_id) { ?>
<?= reportSectionOpen('By client', 'The most to replace first') ?>
<?= reportTable($client_columns, array_values($by_client), ['limit' => 50, 'export_table' => 'clients', 'totals' => ['client' => 'Total'] + $totals,
'totals_html' => ['average' => $totals['average'] === null ? '' : reportYears($totals['average'])]]) ?>
</div>
<?php } ?>
<?= reportSectionOpen('Replacement candidates', "Over $years years old, or on an unsupported OS - oldest first", 'itflow-report-long') ?>
<?= reportTable($candidate_columns, $candidates, ['limit' => 300, 'export_table' => 'candidates',
'empty' => reportEmpty("Nothing is over $years years old or on an unsupported operating system.")]) ?>
<div class="card-footer small text-body-secondary">
Assets not archived and not lost, stolen or retired. Age runs from the purchase date, else the install date; virtual machines have no age or warranty.
Unsupported means the operating system is past its maker's end of support (such as Windows 10, Windows Server 2012 or older, macOS 13 or older).
</div>
</div>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,107 +1,393 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Budget vs Actual - what you planned to spend each month by expense
* category, against what you did spend (vendor expenses, as the Expenses
* report counts them).
*
* Summary shows the year per category: the budget, how much of it the months
* so far allow, what has been spent, and what is left. By month lays the year
* out as a grid. Edit (financial write access) sets the amounts - each
* month, or the same amount every month - or copies last year's in one go.
* Saving goes to agent/post/budget.php.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('budget');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
$next_year = intval(date('Y')) + 1;
[$year, $years] = reportYear("SELECT budget_year AS y FROM budget
UNION SELECT YEAR(expense_date) FROM expenses WHERE expense_vendor_id > 0
UNION SELECT $next_year");
$view = in_array($_GET['view'] ?? '', ['month', 'edit'], true) ? $_GET['view'] : 'summary';
$can_edit = lookupUserPermission('module_financial') >= 2;
if ($view === 'edit' && !$can_edit) {
$view = 'summary';
}
$sql_expense_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(expense_date) AS expense_year FROM expenses WHERE expense_category_id > 0 ORDER BY expense_year DESC");
$current_year = intval(date('Y'));
$months_elapsed = reportMonthsElapsed($year);
// How far through the year we are, to the day - what the budget should have covered by now
$year_elapsed = $year < $current_year ? 1.0 : ($year > $current_year ? 0.0 : (intval(date('z')) + 1) / (intval(date('L')) ? 366 : 365));
$categories = mysqli_query($mysqli, "SELECT * FROM categories WHERE category_type = 'Expense' ORDER BY category_name ASC");
$monthlyTotals = array_fill(1, 12, 0); // Initialize monthly totals for each month
// The plan: [category => [1..12 => amount]]
$budget = [];
$sql = mysqli_query($mysqli, "SELECT budget_category_id, budget_month, SUM(budget_amount) AS amount FROM budget WHERE budget_year = $year GROUP BY budget_category_id, budget_month");
while ($row = mysqli_fetch_assoc($sql)) {
$cat = intval($row['budget_category_id']);
$budget[$cat] = $budget[$cat] ?? array_fill(1, 12, 0.0);
$month = intval($row['budget_month']);
if ($month >= 1 && $month <= 12) {
$budget[$cat][$month] += floatval($row['amount']);
}
}
$has_prev_budget = intval(dashboardCount("SELECT COUNT(*) FROM budget WHERE budget_year = " . ($year - 1)));
// What was spent
$actual = reportExpensesByCategory("$year-01-01", "$year-12-31");
$categories = reportCategoryRows('Expense', $actual);
foreach ($budget as $cat => $months) {
if (!isset($categories[$cat])) {
// Budget against a category that is archived or gone - still show it so it can be cleared
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_archived_at FROM categories WHERE category_id = $cat"));
$categories[$cat] = $row ?: ['category_id' => $cat, 'category_name' => 'Deleted category', 'category_color' => '', 'category_archived_at' => date('Y-m-d')];
}
}
uasort($categories, function ($a, $b) {
return strcasecmp($a['category_name'], $b['category_name']);
});
unset($categories[0]);
// One line per category
$lines = [];
foreach ($categories as $cat => $category) {
$plan = $budget[$cat] ?? array_fill(1, 12, 0.0);
$spent = reportGridRow($actual, $cat);
$plan_total = array_sum($plan);
$plan_to_date = 0.0;
for ($m = 1; $m <= $months_elapsed; $m++) {
$plan_to_date += $plan[$m];
}
// The month we are in only counts as far as we are through it
if ($year === $current_year && $months_elapsed) {
$plan_to_date -= $plan[$months_elapsed] * (1 - intval(date('j')) / intval(date('t')));
}
$lines[$cat] = [
'name' => $category['category_name'], 'archived' => !empty($category['category_archived_at']),
'plan' => $plan, 'plan_total' => $plan_total, 'plan_to_date' => $plan_to_date,
'spent' => $spent['months'], 'spent_total' => $spent['total'],
];
}
$shown = array_filter($lines, function ($line) {
return $line['plan_total'] > 0 || $line['spent_total'] > 0;
});
$plan_total = array_sum(array_column($lines, 'plan_total'));
$plan_to_date = array_sum(array_column($lines, 'plan_to_date'));
$spent_total = array_sum(array_column($lines, 'spent_total'));
$over = array_filter($shown, function ($line) {
return $line['plan_total'] > 0 && $line['spent_total'] > $line['plan_to_date'] + 0.005;
});
$unbudgeted = array_filter($shown, function ($line) {
return $line['plan_total'] <= 0 && $line['spent_total'] > 0;
});
if (reportExporting()) {
$columns = ['name' => ['label' => 'Category']];
for ($m = 1; $m <= 12; $m++) {
$columns["b$m"] = ['label' => date('M', mktime(0, 0, 0, $m, 1)) . ' budget', 'type' => 'money'];
$columns["a$m"] = ['label' => date('M', mktime(0, 0, 0, $m, 1)) . ' actual', 'type' => 'money'];
}
$columns['plan_total'] = ['label' => "$year budget", 'type' => 'money'];
$columns['spent_total'] = ['label' => "$year actual", 'type' => 'money'];
$columns['left'] = ['label' => 'Remaining', 'type' => 'money'];
$rows = [];
foreach ($shown as $line) {
$row = ['name' => $line['name'], 'plan_total' => $line['plan_total'], 'spent_total' => $line['spent_total'], 'left' => $line['plan_total'] - $line['spent_total']];
for ($m = 1; $m <= 12; $m++) {
$row["b$m"] = $line['plan'][$m];
$row["a$m"] = $line['spent'][$m];
}
$rows[] = $row;
}
reportCsv("Budget vs Actual $year", $columns, $rows, ['name' => 'Total', 'plan_total' => $plan_total, 'spent_total' => $spent_total, 'left' => $plan_total - $spent_total]);
}
// Month by month, all categories together
$plan_months = array_fill(1, 12, 0.0);
$spent_months = array_fill(1, 12, 0.0);
foreach ($lines as $line) {
for ($m = 1; $m <= 12; $m++) {
$plan_months[$m] += $line['plan'][$m];
$spent_months[$m] += $line['spent'][$m];
}
}
require_once "includes/inc_report_layout.php";
$money_input = function ($value) {
return $value > 0 ? number_format($value, 2, '.', '') : '';
};
$used_meter = function ($spent, $plan) {
if ($plan <= 0) {
return $spent > 0 ? '<span class="badge rounded-pill bg-warning-subtle text-warning-emphasis border border-warning-subtle fw-normal">No budget</span>' : '';
}
$share = $spent / $plan * 100;
$tone = $share > 100 ? 'bg-danger' : ($share > 90 ? 'bg-warning' : '');
return '<div class="d-flex align-items-center gap-2"><div class="itflow-report-meter flex-grow-1"><span class="' . $tone . '" style="width: ' . min(100, round($share, 1)) . '%"></span></div>'
. '<span class="small text-nowrap ' . ($share > 100 ? 'text-danger-emphasis fw-semibold' : 'text-body-secondary') . '">' . reportPercent(round($share)) . '</span></div>';
};
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-balance-scale me-2"></i>Annual Budget</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
<div class="itflow-report">
while ($row = mysqli_fetch_assoc($sql_expense_years)) {
$expense_year = $row['expense_year'];
?>
<option <?php if ($year == $expense_year) { ?> selected <?php } ?> > <?= $expense_year ?></option>
<?php reportHeader('budget', [
'year' => [$year, $years],
'controls' => reportSegmentControl('view', $view, array_merge(['summary' => 'Summary', 'month' => 'By month'], $can_edit ? ['edit' => 'Edit budget'] : [])),
'export' => $view !== 'edit',
]); ?>
<?php } ?>
<?php if ($view === 'edit') { ?>
</select>
<form action="/agent/post.php" method="post" autocomplete="off" data-budget-form data-currency="<?= escapeHtml($session_company_currency) ?>">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="year" value="<?= $year ?>">
<div class="card itflow-report-section itflow-report-long">
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<h3 class="card-title mb-0 me-auto">Plan for <?= $year ?></h3>
<?php if ($has_prev_budget) { ?>
<button type="submit" name="copy_budget" value="1" class="btn btn-outline-secondary btn-sm confirm-link"
data-confirm-title="Copy <?= $year - 1 ?>'s budget?" data-confirm-text="Every amount in <?= $year ?> is replaced with <?= $year - 1 ?>'s, month for month." data-confirm-button="Copy it">
<i class="fas fa-fw fa-copy me-1"></i>Copy <?= $year - 1 ?>
</button>
<?php } ?>
</div>
<div class="table-responsive">
<table class="table table-sm align-middle mb-0 itflow-report-table itflow-report-grid itflow-report-budget-edit">
<thead class="table-light">
<tr>
<th>Category</th>
<th title="Type an amount and press Fill to put it in every month">Every month</th>
<?php for ($m = 1; $m <= 12; $m++) { ?>
<th class="text-end"><?= date('M', mktime(0, 0, 0, $m, 1)) ?></th>
<?php } ?>
<th class="text-end"><?= $year ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($lines as $cat => $line) {
if ($line['archived'] && $line['plan_total'] <= 0) {
continue;
} ?>
<tr data-budget-row>
<td><?= escapeHtml($line['name']) ?><?php if ($line['archived']) { ?> <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Archived</span><?php } ?></td>
<td>
<div class="input-group input-group-sm flex-nowrap">
<input type="text" inputmode="decimal" class="form-control" data-budget-fill-value aria-label="Amount for every month of <?= escapeHtml($line['name']) ?>" placeholder="0.00">
<button type="button" class="btn btn-outline-secondary" data-budget-fill title="Put this amount in every month">Fill</button>
</div>
</td>
<?php for ($m = 1; $m <= 12; $m++) { ?>
<td><input type="text" inputmode="decimal" pattern="[0-9]*[.,]?[0-9]{0,2}" class="form-control form-control-sm text-end" name="budget[<?= $cat ?>][<?= $m ?>]" value="<?= $money_input($line['plan'][$m]) ?>" placeholder="0" aria-label="<?= escapeHtml($line['name']) ?>, <?= date('F', mktime(0, 0, 0, $m, 1)) ?>" data-budget-cell></td>
<?php } ?>
<td class="text-end fw-semibold" data-budget-row-total><?= reportMoney($line['plan_total']) ?></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr class="fw-semibold">
<td>Total</td>
<td></td>
<?php for ($m = 1; $m <= 12; $m++) { ?>
<td class="text-end" data-budget-month-total="<?= $m ?>"><?= reportMoney($plan_months[$m]) ?></td>
<?php } ?>
<td class="text-end" data-budget-total><?= reportMoney($plan_total) ?></td>
</tr>
</tfoot>
</table>
</div>
<div class="card-footer d-flex flex-wrap align-items-center gap-2">
<button type="submit" name="save_budget" value="1" class="btn btn-primary"><i class="fas fa-check me-2"></i>Save budget</button>
<a class="btn btn-light" href="<?= escapeHtml(reportUrl(['view' => null])) ?>">Cancel</a>
<span class="small text-body-secondary ms-sm-2">Leave a month empty for no budget. Amounts are per month, before tax as you record expenses.</span>
</div>
</div>
</form>
<canvas id="cashFlow" width="100%" height="20"></canvas>
<?php } else { ?>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead class="text-dark">
<tr>
<th>Category</th>
<th class="text-end">January</th>
<th class="text-end">February</th>
<th class="text-end">March</th>
<th class="text-end">April</th>
<th class="text-end">May</th>
<th class="text-end">June</th>
<th class="text-end">July</th>
<th class="text-end">August</th>
<th class="text-end">September</th>
<th class="text-end">October</th>
<th class="text-end">November</th>
<th class="text-end">December</th>
<th class="text-end">Total</th>
</tr>
</thead>
<tbody>
<?php
$used = reportShare($spent_total, $plan_total);
echo reportStats([
['label' => $year === $current_year ? 'Budget this year' : "Budget $year", 'value' => reportMoney($plan_total),
'sub' => $plan_total > 0 ? escapeHtml(reportMoney($plan_total / 12)) . ' <span class="text-body-tertiary">a month on average</span>' : '<span class="text-body-tertiary">No budget set yet</span>'],
['label' => 'Spent', 'value' => reportMoney($spent_total), 'url' => "/agent/expenses.php?canned_date=custom&dtf=$year-01-01&dtt=$year-12-31",
'sub' => $used !== null ? escapeHtml(reportPercent($used)) . ' <span class="text-body-tertiary">of the budget' . ($year === $current_year ? ', ' . round($year_elapsed * 100) . '% of the year gone' : '') . '</span>' : ''],
['label' => $year === $current_year ? 'Against budget to date' : 'Against budget', 'value' => reportMoney(abs($plan_to_date - $spent_total)),
'tone' => $plan_total > 0 ? ($spent_total > $plan_to_date ? 'danger' : 'success') : '',
'sub' => $plan_total > 0 ? ($spent_total > $plan_to_date ? 'Over what the budget allows by now' : 'Under what the budget allows by now') : ''],
['label' => 'Remaining this year', 'value' => reportMoney($plan_total - $spent_total), 'tone' => $plan_total - $spent_total < 0 ? 'danger' : '',
'sub' => count($over) ? '<span class="text-danger-emphasis fw-semibold">' . count($over) . ' categor' . (count($over) === 1 ? 'y' : 'ies') . ' over budget</span>' : '<span class="text-body-tertiary">No category over budget</span>'],
]);
?>
<?php if ($plan_total <= 0) { ?>
<div class="card">
<div class="card-body text-center py-5">
<i class="fas fa-bullseye fa-2x text-body-tertiary d-block mb-2"></i>
<div class="fw-semibold">No budget for <?= $year ?> yet</div>
<div class="small text-body-secondary mb-3">Set what you plan to spend each month by category, and this report compares it with what you actually spend.</div>
<?php if ($can_edit) { ?>
<a class="btn btn-primary" href="<?= escapeHtml(reportUrl(['view' => 'edit'])) ?>"><i class="fas fa-pen me-2"></i>Set the <?= $year ?> budget</a>
<?php } ?>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('Budget and spending by month', escapeHtml((string) $year)) ?>
<div class="card-body">
<?php
if ($categories->num_rows > 0) {
while($category = $categories->fetch_assoc()) {
echo "<tr>";
echo "<td>" . escapeHtml($category['category_name']) . "</td>";
$categoryTotal = 0;
for ($month = 1; $month <= 12; $month++) {
// Fetch the monthly budget for this category for 2022
$sql = "SELECT budget_amount FROM budget WHERE budget_category_id = " . $category['category_id'] . " AND budget_month = $month AND budget_year = $year";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$budget = $result->fetch_assoc();
$amount = $budget['budget_amount'];
$categoryTotal += $amount;
$monthlyTotals[$month] += $amount;
echo "<td class='text-end'>" . $amount . "</td>";
} else {
echo "<td class='text-end'>0</td>";
}
}
echo "<td class='text-end'>" . $categoryTotal . "</td>";
echo "</tr>";
}
// Displaying the monthly totals row
echo "<tr><td><strong>Total</strong></td>";
$grandTotal = 0;
for ($month = 1; $month <= 12; $month++) {
$grandTotal += $monthlyTotals[$month];
echo "<td class='text-end'>" . $monthlyTotals[$month] . "</td>";
}
echo "<td class='text-end'>" . $grandTotal . "</td>";
echo "</tr>";
}
$months_shown = $year === $current_year ? intval(date('n')) : ($year > $current_year ? 0 : 12);
echo reportChart([
'type' => 'bar',
'labels' => array_map(function ($m) { return date('M', mktime(0, 0, 0, $m, 1)); }, range(1, 12)),
'series' => [
['label' => 'Spent', 'data' => array_map(function ($m) use ($spent_months, $months_shown) { return $m <= $months_shown ? round($spent_months[$m], 2) : null; }, range(1, 12)), 'tone' => 'accent'],
['label' => 'Budget', 'data' => array_map(function ($m) use ($plan_months) { return round($plan_months[$m], 2); }, range(1, 12)), 'tone' => 'muted', 'type' => 'line', 'dashed' => true],
],
'format' => 'money',
], '', 'Spending per month against the budget');
?>
</tbody>
</table>
</div>
</div>
</div>
<?php if ($view === 'month') { ?>
<?= reportSectionOpen('By month', 'Spent, with the budget under it - red where it went over', 'itflow-report-long') ?>
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0 itflow-report-table itflow-report-grid">
<thead class="table-light">
<tr>
<th>Category</th>
<?php for ($m = 1; $m <= 12; $m++) { ?>
<th class="text-end"><?= date('M', mktime(0, 0, 0, $m, 1)) ?></th>
<?php } ?>
<th class="text-end"><?= $year ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($shown as $cat => $line) { ?>
<tr>
<td><?= escapeHtml($line['name']) ?></td>
<?php for ($m = 1; $m <= 12; $m++) {
$spent = $line['spent'][$m];
$plan = $line['plan'][$m];
[$dtf, $dtt] = reportColumnDates($year, $m, $m); ?>
<td class="text-end">
<div class="<?= $plan > 0 && $spent > $plan + 0.005 ? 'text-danger fw-semibold' : '' ?>"><?= reportGridAmount($spent, "/agent/expenses.php?category=$cat&canned_date=custom&dtf=$dtf&dtt=$dtt") ?></div>
<div class="small text-body-tertiary"><?= $plan > 0 ? reportMoneyWhole($plan) : '&nbsp;' ?></div>
</td>
<?php } ?>
<td class="text-end">
<div class="fw-semibold <?= $line['plan_total'] > 0 && $line['spent_total'] > $line['plan_total'] ? 'text-danger' : '' ?>"><?= reportGridAmount($line['spent_total']) ?></div>
<div class="small text-body-tertiary"><?= $line['plan_total'] > 0 ? reportMoneyWhole($line['plan_total']) : '&nbsp;' ?></div>
</td>
</tr>
<?php } ?>
<?php if (!$shown) { ?>
<tr><td colspan="14" class="text-center text-body-secondary py-4">No budget and no spending in <?= $year ?>.</td></tr>
<?php } ?>
</tbody>
<tfoot>
<tr class="fw-semibold">
<td>Total</td>
<?php for ($m = 1; $m <= 12; $m++) { ?>
<td class="text-end">
<div class="<?= $plan_months[$m] > 0 && $spent_months[$m] > $plan_months[$m] + 0.005 ? 'text-danger' : '' ?>"><?= reportGridAmount($spent_months[$m]) ?></div>
<div class="small text-body-tertiary fw-normal"><?= $plan_months[$m] > 0 ? reportMoneyWhole($plan_months[$m]) : '&nbsp;' ?></div>
</td>
<?php } ?>
<td class="text-end">
<div><?= reportGridAmount($spent_total) ?></div>
<div class="small text-body-tertiary fw-normal"><?= reportMoneyWhole($plan_total) ?></div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
<?php } else { ?>
<?php
$columns = [
'name' => ['label' => 'Category', 'html' => function ($row) {
return escapeHtml($row['name']) . ($row['archived'] ? ' <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Archived</span>' : '');
}],
'plan_total' => ['label' => "Budget $year", 'type' => 'money', 'html' => function ($row) {
return $row['plan_total'] > 0 ? reportMoney($row['plan_total']) : '<span class="itflow-report-zero">–</span>';
}],
'plan_to_date' => ['label' => $year === $current_year ? 'Budget to date' : 'Budget', 'type' => 'money', 'title' => 'What the budget allows up to today', 'html' => function ($row) {
return $row['plan_total'] > 0 ? reportMoney($row['plan_to_date']) : '<span class="itflow-report-zero">–</span>';
}],
'spent_total' => ['label' => 'Spent', 'type' => 'money', 'html' => function ($row) use ($year) {
if (abs($row['spent_total']) < 0.005) {
return '<span class="itflow-report-zero">–</span>';
}
return '<a class="itflow-report-amount" href="/agent/expenses.php?category=' . intval($row['cat']) . "&canned_date=custom&dtf=$year-01-01&dtt=$year-12-31\">" . reportMoney($row['spent_total']) . '</a>';
}],
'difference' => ['label' => 'Under / over', 'type' => 'money', 'title' => 'Budget to date less what was spent - red is over', 'html' => function ($row) {
if ($row['plan_total'] <= 0) {
return '<span class="itflow-report-zero">–</span>';
}
return '<span class="' . ($row['difference'] < 0 ? 'text-danger fw-semibold' : 'text-success-emphasis') . '">' . reportMoney($row['difference']) . '</span>';
}],
'remaining' => ['label' => 'Left this year', 'type' => 'money', 'html' => function ($row) {
if ($row['plan_total'] <= 0) {
return '<span class="itflow-report-zero">–</span>';
}
return '<span class="' . ($row['remaining'] < 0 ? 'text-danger' : '') . '">' . reportMoney($row['remaining']) . '</span>';
}],
'used' => ['label' => 'Used', 'type' => 'percent', 'class' => 'itflow-report-used', 'html' => function ($row) use ($used_meter) {
return $used_meter($row['spent_total'], $row['plan_total']);
}],
];
if ($year !== $current_year) {
// A past year is all "to date", a future one has none yet
unset($columns['plan_to_date']);
$columns['difference']['title'] = 'The budget less what was spent - red is over';
}
$rows = [];
foreach ($shown as $cat => $line) {
$rows[] = [
'cat' => $cat, 'name' => $line['name'], 'archived' => $line['archived'],
'plan_total' => $line['plan_total'], 'plan_to_date' => $line['plan_to_date'], 'spent_total' => $line['spent_total'],
'difference' => $line['plan_to_date'] - $line['spent_total'], 'remaining' => $line['plan_total'] - $line['spent_total'],
'used' => reportShare($line['spent_total'], $line['plan_total']),
];
}
?>
<?= reportSectionOpen('By category', $unbudgeted ? '<span class="text-warning-emphasis">' . count($unbudgeted) . ' categor' . (count($unbudgeted) === 1 ? 'y has' : 'ies have') . ' spending but no budget</span>' : '') ?>
<?= reportTable($columns, $rows, [
'empty' => "No budget and no spending in $year.",
'totals' => ['name' => 'Total', 'plan_total' => $plan_total, 'plan_to_date' => $plan_to_date, 'spent_total' => $spent_total, 'difference' => $plan_to_date - $spent_total, 'remaining' => $plan_total - $spent_total],
'totals_html' => ['used' => $used_meter($spent_total, $plan_total), 'difference' => '<span class="' . ($plan_to_date - $spent_total < 0 ? 'text-danger' : 'text-success-emphasis') . '">' . reportMoney($plan_to_date - $spent_total) . '</span>'],
]) ?>
<div class="card-footer small text-body-secondary">
Spending is expenses with a vendor, by the date paid. <?= $year === $current_year ? 'Budget to date counts the months so far, and this month as far as today.' : '' ?>
<?php if ($can_edit) { ?><a href="<?= escapeHtml(reportUrl(['view' => 'edit'])) ?>">Edit the <?= $year ?> budget</a><?php } ?>
</div>
</div>
<?php } ?>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php";
?>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -0,0 +1,228 @@
<?php
/*
* Client Profitability - for each client, what they paid in the period
* against the time spent on them: income less the expenses filed against the
* client, divided by the hours logged on their tickets. That effective
* hourly rate is compared with a target (your default hourly rate unless
* another is entered), so a flat-fee client who takes more time than they
* pay for stands out.
*
* Income is cash in (invoice payments and the client's revenue); hours are
* time logged on ticket replies in the period, billable or not.
*/
require_once "includes/inc_report.php";
reportEnforce('client_profitability');
$period = reportPeriod('last_12');
$target = isset($_GET['target']) && $_GET['target'] !== '' ? round(max(0, floatval($_GET['target'])), 2) : round(floatval($config_default_hourly_rate), 2);
$with_tickets = reportFeatureOn('ticketing');
$clients = [];
$client = function ($row) use (&$clients) {
$id = intval($row['client_id']);
if (!isset($clients[$id])) {
$clients[$id] = ['client_id' => $id, 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation'] ?? '',
'income' => 0.0, 'costs' => 0.0, 'seconds' => 0, 'billable_seconds' => 0, 'tickets' => 0, 'mrr' => 0.0];
}
return $id;
};
$scope = clientScopeSql('client_id');
// Money in
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, SUM(amount) AS v FROM (
SELECT invoice_client_id AS client_id, payment_amount AS amount FROM payments
JOIN invoices ON invoice_id = payment_invoice_id
WHERE " . reportRangeSql('payment_date', $period) . "
UNION ALL
SELECT revenue_client_id, revenue_amount FROM revenues
WHERE revenue_client_id > 0 AND " . dashboardRevenueSql() . " AND " . reportRangeSql('revenue_date', $period) . "
) AS income
JOIN clients USING (client_id)
WHERE 1 = 1 $scope
GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[$client($row)]['income'] = floatval($row['v']);
}
// Money out on their behalf
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, SUM(expense_amount) AS v
FROM expenses JOIN clients ON expense_client_id = client_id
WHERE expense_vendor_id > 0 AND " . reportRangeSql('expense_date', $period) . " $scope
GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[$client($row)]['costs'] = floatval($row['v']);
}
// Time spent, and tickets raised
if ($with_tickets) {
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation,
SUM(TIME_TO_SEC(ticket_reply_time_worked)) AS s,
SUM(CASE WHEN ticket_billable = 1 THEN TIME_TO_SEC(ticket_reply_time_worked) ELSE 0 END) AS b
FROM ticket_replies
JOIN tickets ON ticket_reply_ticket_id = ticket_id
JOIN clients ON ticket_client_id = client_id
WHERE ticket_reply_archived_at IS NULL AND ticket_reply_time_worked IS NOT NULL
AND " . reportRangeSql('ticket_reply_created_at', $period) . " $scope
GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$id = $client($row);
$clients[$id]['seconds'] = intval($row['s']);
$clients[$id]['billable_seconds'] = intval($row['b']);
}
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, COUNT(ticket_id) AS n
FROM tickets JOIN clients ON ticket_client_id = client_id
WHERE " . reportRangeSql('ticket_created_at', $period) . " $scope
GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($clients[intval($row['client_id'])])) {
$clients[intval($row['client_id'])]['tickets'] = intval($row['n']);
}
}
}
// What they are on now, every month
$sql = mysqli_query($mysqli, "SELECT recurring_invoice_client_id AS client_id,
SUM(CASE WHEN recurring_invoice_frequency = 'year' THEN recurring_invoice_amount / 12 ELSE recurring_invoice_amount END) AS v
FROM recurring_invoices WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL GROUP BY recurring_invoice_client_id");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($clients[intval($row['client_id'])])) {
$clients[intval($row['client_id'])]['mrr'] = floatval($row['v']);
}
}
foreach ($clients as &$row) {
$row['net'] = $row['income'] - $row['costs'];
$row['hours'] = $row['seconds'] / 3600;
$row['rate'] = $row['seconds'] > 0 ? $row['net'] / ($row['seconds'] / 3600) : null;
$row['flag'] = '';
if ($row['seconds'] >= 1800 && $row['net'] <= 0) {
$row['flag'] = 'unpaid';
} elseif ($row['rate'] !== null && $target > 0 && $row['rate'] < $target && $row['seconds'] >= 1800) {
$row['flag'] = 'below';
}
}
unset($row);
// Lowest rate first - the ones to look at - then those with no time logged
usort($clients, function ($a, $b) {
if ($a['rate'] === null || $b['rate'] === null) {
return ($a['rate'] === null) <=> ($b['rate'] === null) ?: $b['net'] <=> $a['net'];
}
return $a['rate'] <=> $b['rate'];
});
$columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr']);
}],
'income' => ['label' => 'Income', 'type' => 'money'],
'costs' => ['label' => 'Direct costs', 'type' => 'money', 'title' => 'Expenses filed against the client', 'html' => function ($row) {
return $row['costs'] > 0 ? reportMoney($row['costs']) : '<span class="itflow-report-zero">–</span>';
}],
'net' => ['label' => 'Net', 'type' => 'money', 'class' => 'fw-semibold'],
];
if ($with_tickets) {
$columns['seconds'] = ['label' => 'Hours', 'type' => 'hours', 'title' => 'Time logged on their tickets in the period'];
$columns['billable_share'] = ['label' => 'Billable', 'type' => 'percent', 'title' => 'Share of the hours on billable tickets', 'class' => 'text-body-secondary'];
$columns['rate'] = ['label' => 'Per hour', 'type' => 'money', 'title' => 'Net divided by hours - your effective hourly rate', 'html' => function ($row) use ($target) {
if ($row['rate'] === null) {
return '<span class="itflow-report-zero">No time</span>';
}
$tone = $row['flag'] ? 'text-danger fw-semibold' : ($target > 0 && $row['rate'] >= $target ? 'text-success-emphasis fw-semibold' : 'fw-semibold');
return '<span class="' . $tone . '">' . reportMoney($row['rate']) . '</span>';
}];
$columns['tickets'] = ['label' => 'Tickets', 'type' => 'count'];
}
$columns['mrr'] = ['label' => 'Recurring / month', 'type' => 'money', 'html' => function ($row) {
return $row['mrr'] > 0 ? reportMoney($row['mrr']) : '<span class="itflow-report-zero">–</span>';
}];
$columns['flag'] = ['label' => '', 'sort' => false, 'csv_label' => 'Flag', 'csv' => function ($row) {
return ['unpaid' => 'Time but no income', 'below' => 'Below target'][$row['flag']] ?? '';
}, 'html' => function ($row) {
if ($row['flag'] === 'unpaid') {
return '<span class="badge rounded-pill bg-danger-subtle text-danger-emphasis border border-danger-subtle fw-normal">Time, no income</span>';
}
if ($row['flag'] === 'below') {
return '<span class="badge rounded-pill bg-warning-subtle text-warning-emphasis border border-warning-subtle fw-normal">Below target</span>';
}
return '';
}];
foreach ($clients as &$row) {
$row['billable_share'] = reportShare($row['billable_seconds'], $row['seconds']);
}
unset($row);
$income = array_sum(array_column($clients, 'income'));
$costs = array_sum(array_column($clients, 'costs'));
$seconds = array_sum(array_column($clients, 'seconds'));
$overall_rate = $seconds ? ($income - $costs) / ($seconds / 3600) : null;
$totals = ['client' => 'Total', 'income' => $income, 'costs' => $costs, 'net' => $income - $costs, 'seconds' => $seconds,
'rate' => $overall_rate, 'tickets' => array_sum(array_column($clients, 'tickets')), 'mrr' => array_sum(array_column($clients, 'mrr')),
'billable_share' => reportShare(array_sum(array_column($clients, 'billable_seconds')), $seconds)];
if (reportExporting()) {
reportCsv('Client Profitability ' . $period['start'] . ' to ' . $period['end'], $columns, $clients, $totals);
}
require_once "includes/inc_report_layout.php";
$flagged = array_filter($clients, function ($row) { return $row['flag'] !== ''; });
$chart_rows = array_values(array_filter($clients, function ($row) { return $row['rate'] !== null && $row['seconds'] >= 1800; }));
usort($chart_rows, function ($a, $b) { return $b['seconds'] <=> $a['seconds']; });
$chart_rows = array_slice($chart_rows, 0, 15);
usort($chart_rows, function ($a, $b) { return $a['rate'] <=> $b['rate']; });
$target_control = '<div class="col-sm-6 col-lg-2"><div class="input-group" title="The hourly rate you aim to earn - your default hourly rate unless you enter another">'
. '<span class="input-group-text"><i class="fas fa-fw fa-bullseye"></i></span>'
. '<input type="text" inputmode="decimal" class="form-control" name="target" value="' . ($target > 0 ? escapeHtml(number_format($target, 2, '.', '')) : '') . '" placeholder="Target per hour" aria-label="Target per hour" data-report-autosubmit>'
. '</div></div>';
?>
<div class="itflow-report">
<?php reportHeader('client_profitability', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(payment_date) AS y FROM payments"),
'controls' => $target_control,
]); ?>
<?= reportStats([
['label' => 'Income from clients', 'value' => reportMoney($income), 'sub' => $costs > 0 ? escapeHtml(reportMoney($costs)) . ' <span class="text-body-tertiary">in direct costs</span>' : '<span class="text-body-tertiary">No direct costs filed</span>'],
['label' => 'Hours worked', 'value' => $with_tickets ? reportHours($seconds) : '-', 'sub' => $with_tickets ? escapeHtml(reportPercent(reportShare(array_sum(array_column($clients, 'billable_seconds')), $seconds))) . ' <span class="text-body-tertiary">on billable tickets</span>' : '<span class="text-body-tertiary">Ticketing is off</span>'],
['label' => 'Earned per hour', 'value' => $overall_rate === null ? '-' : reportMoney($overall_rate), 'tone' => $overall_rate !== null && $target > 0 ? ($overall_rate >= $target ? 'success' : 'danger') : '',
'sub' => $target > 0 ? 'Target <span class="text-body">' . reportMoney($target) . '</span>' : '<span class="text-body-tertiary">Enter a target above</span>'],
['label' => 'Clients to look at', 'value' => reportCount(count($flagged)), 'tone' => $flagged ? 'danger' : 'success',
'sub' => '<span class="text-body-tertiary">Below target, or time with no income</span>'],
]) ?>
<?php if ($with_tickets && $chart_rows) { ?>
<?= reportSectionOpen('Earned per hour', 'The ' . count($chart_rows) . ' clients you spent the most time on - red is below target') ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_map(function ($r) { return $r['client']; }, $chart_rows),
'series' => [['label' => 'Per hour', 'data' => array_map(function ($r) { return round($r['rate'], 2); }, $chart_rows),
'tones' => array_map(function ($r) use ($target) { return $r['flag'] ? 'danger' : ($target > 0 ? 'success' : 'accent'); }, $chart_rows)]],
'format' => 'money',
'legend' => false,
], '', 'What each client earned per hour of work') ?>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By client', 'Lowest earning per hour first', 'itflow-report-long') ?>
<?= reportTable($columns, $clients, ['empty' => 'No income or time logged for any client in this period.', 'totals' => $totals]) ?>
<div class="card-footer small text-body-secondary">
Net is income (payments and revenue) less the expenses filed against the client. Per hour is net divided by the hours logged on their tickets in the same period -
a client who pays in one period for work done in another reads high or low; a longer period evens that out.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -0,0 +1,585 @@
<?php
/*
* Client Review - one client's period on a page, made to print for a
* quarterly business review (QBR): their tickets (how many, how fast, what
* about, who raised them, which devices keep coming back), SLA and ratings,
* projects, the hardware to plan for, renewals coming up, services that need
* a look, documentation gaps and - for agents who see billing - what was
* invoiced and paid. It closes the top with recommendations drawn from all
* of that, ready to talk through.
*
* Each part shows only when that side of ITFlow is on (ticketing, IT
* documentation, accounting) and the agent may see it.
*/
require_once "includes/inc_report.php";
reportEnforce('client_review');
$period = reportPeriod('last_quarter');
$client_id = reportClientId();
$ticketing = reportFeatureOn('ticketing');
$itdoc = reportFeatureOn('itdoc');
$billing = reportFeatureOn('accounting') && reportPermission('module_sales') >= 1;
$credentials_on = $itdoc && reportPermission('module_credential') >= 1;
const REVIEW_OLD_YEARS = 5;
$client = null;
if ($client_id) {
$client = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, client_type, client_website, client_created_at FROM clients WHERE client_id = $client_id"));
$primary = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name, contact_title, contact_email FROM contacts
WHERE contact_client_id = $client_id AND contact_archived_at IS NULL ORDER BY contact_primary DESC, contact_important DESC, contact_name ASC LIMIT 1"));
}
/*
* ---------- tickets ----------
*/
$t = null;
if ($client && $ticketing) {
$filter = reportTicketSql($client_id);
$opened_in = reportRangeSql('ticket_created_at', $period);
$t = [
'opened' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND $opened_in"),
'opened_prev' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND " . reportRangeSql('ticket_created_at', $period, true)),
'resolved' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND " . reportRangeSql('ticket_resolved_at', $period)),
'open_now' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND " . TICKET_OPEN_SQL),
'open_old' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND " . TICKET_OPEN_SQL . " AND ticket_created_at < NOW() - INTERVAL 30 DAY"),
'response' => reportMedian(reportColumn("SELECT TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) FROM tickets WHERE $filter AND $opened_in AND ticket_first_response_at IS NOT NULL")),
'resolve' => reportMedian(reportColumn("SELECT TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_resolved_at) FROM tickets WHERE $filter AND " . reportRangeSql('ticket_resolved_at', $period))),
'seconds' => dashboardSum("SELECT SUM(TIME_TO_SEC(ticket_reply_time_worked)) FROM ticket_replies JOIN tickets ON ticket_reply_ticket_id = ticket_id
WHERE $filter AND ticket_reply_archived_at IS NULL AND " . reportRangeSql('ticket_reply_created_at', $period)),
'sla' => reportSlaCompliance("$filter AND $opened_in"),
];
$rated = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT SUM(ticket_feedback = 'Good') AS good, SUM(ticket_feedback = 'Bad') AS bad FROM tickets
WHERE $filter AND " . reportRangeSql('ticket_closed_at', $period)));
$t['good'] = intval($rated['good']);
$t['bad'] = intval($rated['bad']);
$t['satisfaction'] = reportShare($t['good'], $t['good'] + $t['bad'], 1);
// Over the period
$buckets = reportBuckets($period);
$t['opened_series'] = reportSeries("SELECT " . reportBucketSql('ticket_created_at', $buckets['unit']) . " AS b, COUNT(ticket_id) AS v FROM tickets WHERE $filter AND $opened_in GROUP BY b", $buckets['keys']);
$t['resolved_series'] = reportSeries("SELECT " . reportBucketSql('ticket_resolved_at', $buckets['unit']) . " AS b, COUNT(ticket_id) AS v FROM tickets
WHERE $filter AND " . reportRangeSql('ticket_resolved_at', $period) . " GROUP BY b", $buckets['keys']);
// What about
$names = reportTicketCategories();
$t['categories'] = [];
$sql = mysqli_query($mysqli, "SELECT ticket_category AS cat, COUNT(ticket_id) AS n FROM tickets WHERE $filter AND $opened_in GROUP BY ticket_category ORDER BY n DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$t['categories'][] = ['label' => $names[intval($row['cat'])] ?? 'No category', 'value' => intval($row['n'])];
}
// Who raised them, and the devices that keep coming back
$t['contacts'] = [];
$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_title, COUNT(ticket_id) AS n FROM tickets JOIN contacts ON ticket_contact_id = contact_id
WHERE $filter AND $opened_in GROUP BY contact_id, contact_name, contact_title ORDER BY n DESC, contact_name ASC LIMIT 6");
while ($row = mysqli_fetch_assoc($sql)) {
$t['contacts'][] = $row;
}
$t['assets'] = [];
$sql = mysqli_query($mysqli, "SELECT assets.asset_id, asset_name, asset_type, asset_make, asset_model, asset_client_id, COUNT(DISTINCT tickets.ticket_id) AS n
FROM tickets JOIN ticket_assets ON ticket_assets.ticket_id = tickets.ticket_id JOIN assets ON assets.asset_id = ticket_assets.asset_id
WHERE $filter AND $opened_in GROUP BY assets.asset_id, asset_name, asset_type, asset_make, asset_model, asset_client_id ORDER BY n DESC, asset_name ASC LIMIT 6");
while ($row = mysqli_fetch_assoc($sql)) {
$t['assets'][] = $row;
}
// The urgent and high ones
$t['urgent'] = [];
$sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_client_id, ticket_created_at, ticket_resolved_at,
ticket_status_name, ticket_status_color, TIMESTAMPDIFF(SECOND, ticket_created_at, COALESCE(ticket_resolved_at, NOW())) AS took
FROM tickets LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id
WHERE $filter AND $opened_in AND ticket_priority IN ('Urgent', 'High')
ORDER BY FIELD(ticket_priority, 'Urgent', 'High'), ticket_created_at DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$t['urgent'][] = $row;
}
}
/*
* ---------- projects ----------
*/
$projects = [];
if ($client && $ticketing) {
$sql = mysqli_query($mysqli, "SELECT project_id, project_prefix, project_number, project_name, project_start, project_due, project_budget_hours, project_created_at,
project_completed_at, project_archived_at, project_client_id
FROM projects WHERE project_client_id = $client_id AND project_archived_at IS NULL
AND (project_completed_at IS NULL OR project_completed_at >= '" . $period['start'] . "')
ORDER BY project_completed_at IS NOT NULL, project_due IS NULL, project_due ASC, project_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$projects[intval($row['project_id'])] = $row;
}
$project_stats = projectStats(array_keys($projects));
}
/*
* ---------- hardware, renewals, services, documentation ----------
*/
$hw = null;
$renewals = [];
$services = [];
$coverage = null;
$credentials = null;
if ($client && $itdoc) {
$assets = reportLifecycleAssets($client_id);
$limit_days = REVIEW_OLD_YEARS * 365.25;
$hw = ['assets' => count($assets), 'old' => 0, 'expired' => 0, 'ending' => 0, 'os' => 0, 'age_total' => 0, 'dated' => 0, 'os_names' => [], 'types' => [], 'plan' => []];
foreach ($assets as $asset) {
$old = $asset['age_days'] !== null && $asset['age_days'] >= $limit_days;
$expired = $asset['warranty'] && $asset['warranty']['days'] < 0;
$ending = $asset['warranty'] && $asset['warranty']['days'] >= 0 && $asset['warranty']['days'] <= 90;
$hw['old'] += $old ? 1 : 0;
$hw['expired'] += $expired ? 1 : 0;
$hw['ending'] += $ending ? 1 : 0;
$hw['types'][$asset['asset_type'] ?: 'Other'] = ($hw['types'][$asset['asset_type'] ?: 'Other'] ?? 0) + 1;
if ($asset['age_days'] !== null) {
$hw['dated']++;
$hw['age_total'] += $asset['age_days'];
}
if ($asset['os_eol'] !== '') {
$hw['os']++;
$hw['os_names'][$asset['os_eol']] = ($hw['os_names'][$asset['os_eol']] ?? 0) + 1;
}
// What to plan for: unsupported, old, or a warranty about to end
$reasons = [];
if ($asset['os_eol'] !== '') {
$reasons[] = ['danger', $asset['os_eol'] . ' - no longer supported'];
}
if ($old) {
$reasons[] = ['danger', reportYears($asset['age_days']) . ' old'];
}
if ($ending) {
$reasons[] = ['warning', 'Warranty ends ' . ($asset['warranty']['days'] === 0 ? 'today' : 'in ' . $asset['warranty']['days'] . ' days')];
}
if ($reasons) {
$asset['reasons'] = $reasons;
$asset['rank'] = ($asset['os_eol'] !== '' ? 2 : 0) + ($old ? 1 : 0);
$hw['plan'][] = $asset;
}
}
arsort($hw['types']);
arsort($hw['os_names']);
usort($hw['plan'], function ($a, $b) { return $b['rank'] <=> $a['rank'] ?: ($b['age_days'] ?? 0) <=> ($a['age_days'] ?? 0); });
$hw['average'] = $hw['dated'] ? $hw['age_total'] / $hw['dated'] : null;
$renewals = reportRenewals($client_id, 90);
$sql = mysqli_query($mysqli, "SELECT service_id, service_name, service_category, service_importance, service_review_due, service_reviewed_at, service_client_id,
" . serviceAttentionSql() . " AS attention
FROM services WHERE service_client_id = $client_id AND service_archived_at IS NULL ORDER BY service_name");
$service_count = 0;
while ($row = mysqli_fetch_assoc($sql)) {
$service_count++;
$row['review'] = serviceReview($row);
if (intval($row['attention']) || in_array($row['review']['state'], ['overdue', 'soon'], true)) {
$services[] = $row;
}
}
$coverage = reportCoverage($client_id)[$client_id] ?? null;
if ($credentials_on) {
$credentials = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(*) AS total,
SUM(credential_password_changed_at IS NULL OR credential_password_changed_at < NOW() - INTERVAL " . CREDENTIAL_OVERDUE_DAYS . " DAY) AS stale
FROM credentials WHERE credential_client_id = $client_id AND credential_archived_at IS NULL"));
}
}
/*
* ---------- billing ----------
*/
$money = null;
if ($client && $billing) {
$paid_in = reportRangeSql('payment_date', $period);
$open = dashboardOpenInvoicesSql("AND invoice_client_id = $client_id");
$money = [
'invoiced' => dashboardSum("SELECT SUM(invoice_amount) FROM invoices WHERE invoice_client_id = $client_id AND invoice_status NOT IN ('Draft', 'Cancelled', 'Non-Billable')
AND " . reportRangeSql('invoice_date', $period)),
'paid' => dashboardSum("SELECT SUM(payment_amount) FROM payments JOIN invoices ON payment_invoice_id = invoice_id WHERE invoice_client_id = $client_id AND $paid_in"),
'balance' => dashboardSum("SELECT SUM(balance) FROM ($open) AS o WHERE balance > 0.004"),
'overdue' => dashboardSum("SELECT SUM(balance) FROM ($open) AS o WHERE balance > 0.004 AND invoice_due < CURDATE()"),
'mrr' => dashboardSum("SELECT SUM(IF(recurring_invoice_frequency = 'year', recurring_invoice_amount / 12, recurring_invoice_amount)) FROM recurring_invoices
WHERE recurring_invoice_client_id = $client_id AND recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL"),
'unbilled' => $ticketing ? dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE ticket_client_id = $client_id AND 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)") : 0,
];
}
/*
* ---------- recommendations ----------
*
* Each [tone, icon, text (HTML), link] - what stands out, worst first.
*/
$advice = [];
if ($client) {
$plural = function ($n, $one, $many = null) {
return reportCount($n) . ' ' . ($n === 1 ? $one : ($many ?? $one . 's'));
};
if ($hw && $hw['os']) {
$names = implode(', ', array_keys($hw['os_names']));
$advice[] = ['danger', 'fa-shield-alt', '<strong>' . $plural($hw['os'], 'device runs', 'devices run') . ' an operating system past its end of support</strong> (' . escapeHtml($names) . ').
They no longer get security fixes - plan the upgrades or replacements.', '/agent/reports/asset_lifecycle.php?client_id=' . $client_id];
}
if ($money && $money['overdue'] > 0.004) {
$advice[] = ['danger', 'fa-file-invoice-dollar', '<strong>' . reportMoney($money['overdue']) . ' is past due</strong> of a ' . reportMoney($money['balance']) . ' balance.', '/agent/reports/outstanding_balances.php?client_id=' . $client_id];
}
if ($t && $t['sla']['response_percent'] !== null && $t['sla']['response_percent'] < 90) {
$advice[] = ['warning', 'fa-stopwatch', '<strong>First replies met the SLA ' . reportPercent($t['sla']['response_percent']) . ' of the time.</strong> Look at when the late ones came in and who picked them up.',
'/agent/reports/sla_summary.php?client_id=' . $client_id . '&' . http_build_query(reportPeriodQuery($period))];
}
if ($t && $t['bad']) {
$advice[] = ['warning', 'fa-frown', '<strong>' . $plural($t['bad'], 'ticket was', 'tickets were') . ' rated bad.</strong> Go through ' . ($t['bad'] === 1 ? 'it' : 'them') . ' together and agree what changes.',
'/agent/reports/satisfaction.php?client_id=' . $client_id . '&' . http_build_query(reportPeriodQuery($period))];
}
if ($t && $t['opened'] >= 5 && $t['opened_prev'] && $t['opened'] > $t['opened_prev'] * 1.25) {
$advice[] = ['warning', 'fa-chart-line', '<strong>Tickets were up ' . reportChange($t['opened'], $t['opened_prev']) . '%</strong> on ' . escapeHtml($period['compare']) . ' (' . reportCount($t['opened']) . ' against ' . reportCount($t['opened_prev']) . ').', ''];
}
if ($t && $t['opened'] >= 5 && $t['categories'] && $t['categories'][0]['label'] !== 'No category' && $t['categories'][0]['value'] / $t['opened'] >= 0.3) {
$top = $t['categories'][0];
$advice[] = ['info', 'fa-tags', '<strong>' . escapeHtml($top['label']) . ' was ' . reportPercent(reportShare($top['value'], $t['opened'], 0)) . ' of tickets</strong> (' . reportCount($top['value']) . ').
Fixing the cause, or some training, could cut that down.', ''];
}
if ($t && $t['assets'] && intval($t['assets'][0]['n']) >= 3) {
$asset = $t['assets'][0];
$advice[] = ['info', 'fa-redo', '<strong>' . escapeHtml($asset['asset_name']) . ' was on ' . reportCount(intval($asset['n'])) . ' tickets.</strong> Worth repairing properly or replacing.',
'/agent/asset.php?client_id=' . $client_id . '&asset_id=' . intval($asset['asset_id'])];
}
if ($hw && $hw['old']) {
$advice[] = ['warning', 'fa-recycle', '<strong>' . $plural($hw['old'], 'device is', 'devices are') . ' over ' . REVIEW_OLD_YEARS . ' years old.</strong> Budget for replacing ' . ($hw['old'] === 1 ? 'it' : 'them') . ' over the coming year.',
'/agent/reports/asset_lifecycle.php?client_id=' . $client_id];
}
$manual_due = array_filter($renewals, function ($r) { return !$r['auto'] && $r['kind'] !== 'warranty'; });
if ($manual_due) {
$lapsed = count(array_filter($manual_due, function ($r) { return $r['days'] < 0; }));
$advice[] = [$lapsed ? 'danger' : 'warning', 'fa-calendar-alt', '<strong>' . $plural(count($manual_due), 'domain, certificate or license needs', 'domains, certificates or licenses need') . ' renewing</strong>'
. ($lapsed ? ', ' . reportCount($lapsed) . ' already lapsed' : ' in the next 90 days') . '.', '/agent/reports/renewals.php?client_id=' . $client_id . '&manual=1'];
}
if ($hw && $hw['ending']) {
$advice[] = ['info', 'fa-shield-alt', '<strong>' . $plural($hw['ending'], 'warranty ends', 'warranties end') . ' in the next 90 days.</strong> Extend the ones on kit that matters.',
'/agent/reports/renewals.php?client_id=' . $client_id . '&kind=warranty'];
}
if ($t && $t['open_old']) {
$advice[] = ['warning', 'fa-hourglass-half', '<strong>' . $plural($t['open_old'], 'ticket has', 'tickets have') . ' been open over 30 days.</strong> Close them out or agree a plan.',
'/agent/reports/ticket_aging.php?client_id=' . $client_id];
}
if ($services) {
$advice[] = ['info', 'fa-stream', '<strong>' . $plural(count($services), 'service needs', 'services need') . ' a look</strong> - a review due, or something it depends on expiring or out of action.',
'/agent/services.php?client_id=' . $client_id];
}
if ($credentials && intval($credentials['stale'])) {
$advice[] = ['info', 'fa-key', '<strong>' . $plural(intval($credentials['stale']), 'password has', 'passwords have') . ' not changed in over a year.</strong>',
'/agent/reports/credential_rotation.php?client_id=' . $client_id . '&days=365'];
}
if ($coverage && $coverage['missing']) {
$checks = reportCoverageChecks();
$advice[] = ['info', 'fa-tasks', '<strong>Documentation is missing:</strong> ' . escapeHtml(implode(', ', array_map(function ($k) use ($checks) { return strtolower($checks[$k]['label']); }, $coverage['missing']))) . '.',
'/agent/reports/documentation_coverage.php?gaps=1'];
}
if ($money && $money['unbilled']) {
$advice[] = ['info', 'fa-file-invoice', '<strong>' . $plural($money['unbilled'], 'billable ticket is', 'billable tickets are') . ' done but not invoiced yet.</strong>', '/agent/reports/tickets_unbilled.php?client_id=' . $client_id];
}
}
/*
* ---------- export: the tickets in the period ----------
*/
if ($t && reportExporting()) {
$rows = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_category, ticket_priority, ticket_status_name, ticket_created_at,
ticket_first_response_at, ticket_resolved_at, contact_name, user_name,
(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) AS seconds
FROM tickets LEFT JOIN contacts ON ticket_contact_id = contact_id LEFT JOIN users ON ticket_assigned_to = user_id LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id
WHERE " . reportTicketSql($client_id) . " AND " . reportRangeSql('ticket_created_at', $period) . " ORDER BY ticket_created_at ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['category'] = $names[intval($row['ticket_category'])] ?? '';
$row['response'] = $row['ticket_first_response_at'] ? strtotime($row['ticket_first_response_at']) - strtotime($row['ticket_created_at']) : null;
$rows[] = $row;
}
reportCsv($client['client_name'] . ' Tickets ' . $period['start'] . ' to ' . $period['end'], [
'ticket' => ['label' => 'Ticket', 'csv' => function ($row) { return ticketReference($row); }],
'ticket_subject' => ['label' => 'Subject'],
'category' => ['label' => 'Category'],
'ticket_priority' => ['label' => 'Priority'],
'ticket_status_name' => ['label' => 'Status'],
'contact_name' => ['label' => 'Contact'],
'user_name' => ['label' => 'Assigned to'],
'ticket_created_at' => ['label' => 'Opened'],
'response' => ['label' => 'Hours to first reply', 'type' => 'hours'],
'ticket_resolved_at' => ['label' => 'Resolved'],
'seconds' => ['label' => 'Hours logged', 'type' => 'hours'],
], $rows);
}
require_once "includes/inc_report_layout.php";
$header = [
'period' => $period,
'client' => $client_id,
'client_required' => true,
'export' => $t ? ['tickets' => 'Tickets in the period'] : false,
'print_meta' => $client ? $client['client_name'] : '',
];
?>
<div class="itflow-report itflow-report-review">
<?php reportHeader('client_review', $header); ?>
<?php if (!$client) { ?>
<div class="card"><div class="card-body">
<?= reportEmpty('Pick a client above to build their review.', 'fa-clipboard-list', 'secondary') ?>
</div></div>
<?php } else { ?>
<!-- Who it is for -->
<div class="card">
<div class="card-body d-flex flex-wrap align-items-center gap-3">
<?php $tone = clientInitialsTone($client_id); ?>
<span class="itflow-client-avatar bg-<?= $tone ?>-subtle text-<?= $tone ?>-emphasis"><?= escapeHtml(clientInitials((string) $client['client_abbreviation'], $client['client_name'])) ?></span>
<div class="me-auto">
<h2 class="h4 mb-0"><a class="text-body text-decoration-none" href="/agent/client_overview.php?client_id=<?= $client_id ?>"><?= escapeHtml($client['client_name']) ?></a></h2>
<div class="text-body-secondary">Business review · <?= escapeHtml($period['range']) ?></div>
</div>
<dl class="row small mb-0 g-2 text-body-secondary">
<?php if ($primary) { ?>
<dt class="col-auto fw-normal">Contact</dt>
<dd class="col-auto mb-0 text-body"><?= escapeHtml($primary['contact_name']) ?><?= $primary['contact_title'] ? ', ' . escapeHtml($primary['contact_title']) : '' ?></dd>
<?php } ?>
<dt class="col-auto fw-normal">Client since</dt>
<dd class="col-auto mb-0 text-body"><?= escapeHtml(date('M Y', strtotime($client['client_created_at']))) ?></dd>
</dl>
</div>
</div>
<?= reportSectionOpen('Recommendations', $advice ? reportCount(count($advice)) . ' to talk through' : '') ?>
<div class="card-body">
<?php if (!$advice) { ?>
<p class="mb-0 text-success-emphasis"><i class="fas fa-check-circle me-2"></i>Nothing stands out - a quiet, healthy period.</p>
<?php } else { ?>
<ul class="itflow-report-advice">
<?php foreach ($advice as [$tone, $icon, $text, $link]) { ?>
<li>
<i class="fas fa-fw <?= $icon ?> text-<?= $tone ?>"></i>
<div class="flex-grow-1"><?= $text ?></div>
<?php if ($link) { ?><a class="small text-nowrap d-print-none" href="<?= escapeHtml($link) ?>">Details<i class="fas fa-angle-right ms-1"></i></a><?php } ?>
</li>
<?php } ?>
</ul>
<?php } ?>
</div>
</div>
<?php if ($t) { ?>
<h2 class="itflow-report-group-title mt-4 mb-2">Service desk</h2>
<?= reportStats([
['label' => 'Tickets raised', 'value' => reportCount($t['opened']), 'url' => '/agent/tickets.php?client_id=' . $client_id . '&show=all',
'sub' => reportChangeHtml($t['opened'], $t['opened_prev'], 'down', $period['compare'])],
['label' => 'Resolved', 'value' => reportCount($t['resolved']), 'sub' => reportCount($t['open_now']) . ' <span class="text-body-tertiary">open now</span>'],
['label' => 'Typical first reply', 'value' => $t['response'] === null ? '-' : reportDuration($t['response']),
'sub' => $t['resolve'] === null ? '' : 'Resolved in <span class="text-body">' . reportDuration($t['resolve']) . '</span>'],
['label' => 'SLA met', 'value_html' => $t['sla']['response_percent'] === null ? '<span class="text-body-tertiary">-</span>' : reportRateHtml($t['sla']['response_percent']),
'sub' => $t['sla']['resolution_percent'] === null ? '<span class="text-body-tertiary">No SLA tickets</span>' : 'Resolution <span class="text-body">' . reportPercent($t['sla']['resolution_percent']) . '</span>'],
['label' => 'Satisfaction', 'value_html' => $t['satisfaction'] === null ? '<span class="text-body-tertiary">-</span>' : reportRateHtml($t['satisfaction']),
'sub' => ($t['good'] + $t['bad']) ? reportCount($t['good'] + $t['bad']) . ' <span class="text-body-tertiary">ratings</span>' : '<span class="text-body-tertiary">No ratings</span>'],
['label' => 'Time spent', 'value' => reportHours($t['seconds']) . ' h', 'sub' => '<span class="text-body-tertiary">Logged on their tickets</span>'],
]) ?>
<?php } ?>
<?php if ($t && $t['opened'] + $t['resolved'] > 0) { ?>
<div class="row g-3">
<div class="col-lg-7">
<?= reportSectionOpen('Tickets over the period', '', 'h-100') ?>
<div class="card-body">
<?= reportChart(['type' => 'bar', 'labels' => $buckets['labels'], 'series' => [
['label' => 'Raised', 'data' => $t['opened_series'], 'tone' => 'accent'],
['label' => 'Resolved', 'data' => $t['resolved_series'], 'tone' => 'success'],
], 'format' => 'count'], '', 'Tickets raised and resolved over the period') ?>
</div>
</div>
</div>
<div class="col-lg-5">
<?= reportSectionOpen('What they were about', '', 'h-100') ?>
<div class="card-body">
<?php $cats = reportTopN($t['categories'], 6); ?>
<?php if ($cats) { ?>
<?= reportChart(['type' => 'bar', 'horizontal' => true, 'labels' => array_column($cats, 'label'),
'series' => [['label' => 'Tickets', 'data' => array_column($cats, 'value'), 'tones' => array_map(function ($i, $c) { return $c['color'] ?? reportPalette($i); }, array_keys($cats), $cats)]],
'format' => 'count', 'legend' => false], '', 'Tickets raised by category') ?>
<?php } else { ?>
<?= reportEmpty('No tickets raised.', 'fa-tags', 'secondary') ?>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="row g-3">
<div class="col-lg-6">
<?= reportSectionOpen('Who raised the most', '', 'h-100') ?>
<?= reportTable([
'contact_name' => ['label' => 'Contact', 'html' => function ($row) use ($client_id) {
return '<a class="fw-semibold text-body" href="/agent/contact.php?client_id=' . $client_id . '&contact_id=' . intval($row['contact_id']) . '">' . escapeHtml($row['contact_name']) . '</a>'
. ($row['contact_title'] ? '<div class="small text-body-secondary">' . escapeHtml($row['contact_title']) . '</div>' : '');
}],
'n' => ['label' => 'Tickets', 'type' => 'count'],
], $t['contacts'], ['sortable' => false, 'empty' => 'No tickets had a contact.']) ?>
</div>
</div>
<div class="col-lg-6">
<?= reportSectionOpen('Devices with the most tickets', '', 'h-100') ?>
<?= reportTable([
'asset_name' => ['label' => 'Device', 'html' => function ($row) { return reportAssetCell($row); }],
'model' => ['label' => 'Make and model', 'html' => function ($row) {
return '<span class="small text-body-secondary">' . escapeHtml(trim($row['asset_make'] . ' ' . $row['asset_model'])) . '</span>';
}],
'n' => ['label' => 'Tickets', 'type' => 'count'],
], $t['assets'], ['sortable' => false, 'empty' => 'No tickets were linked to a device.']) ?>
</div>
</div>
</div>
<?php if ($t['urgent']) { ?>
<?= reportSectionOpen('Urgent and high priority', reportCount(count($t['urgent'])) . ' raised in the period') ?>
<?= reportTable([
'ticket' => ['label' => 'Ticket', 'class' => 'itflow-report-text', 'html' => function ($row) {
return reportPriorityDot($row['ticket_priority']) . reportTicketLink($row);
}],
'ticket_status_name' => ['label' => 'Status', 'html' => function ($row) {
$color = preg_match('/^#[0-9a-f]{3,8}$/i', (string) $row['ticket_status_color']) ? $row['ticket_status_color'] : '#6c757d';
return '<span class="badge rounded-pill text-white" style="background-color: ' . $color . '">' . escapeHtml($row['ticket_status_name']) . '</span>';
}],
'ticket_created_at' => ['label' => 'Raised', 'type' => 'date'],
'took' => ['label' => 'Resolved in', 'type' => 'duration', 'html' => function ($row) {
return $row['ticket_resolved_at'] ? reportDuration($row['took']) : '<span class="text-body-secondary small">Open ' . reportDuration($row['took']) . '</span>';
}],
], $t['urgent'], ['sortable' => false, 'limit' => 15]) ?>
</div>
<?php } ?>
<?php } ?>
<?php if ($projects) { ?>
<?= reportSectionOpen('Projects', 'Open, and completed since the period began') ?>
<?= reportTable([
'project_name' => ['label' => 'Project', 'class' => 'itflow-report-text', 'html' => function ($row) {
return '<a class="fw-semibold text-body" href="/agent/' . projectUrl($row['project_id'], $row['project_client_id']) . '">' . escapeHtml($row['project_name']) . '</a>'
. '<div class="small text-body-secondary">' . escapeHtml(projectReference($row)) . '</div>';
}],
'state' => ['label' => 'Status', 'html' => function ($row) {
return '<span class="d-inline-flex flex-wrap gap-1">' . projectStatePill($row) . (projectIsOpen($row) ? projectDuePill($row) : '') . '</span>';
}],
'progress' => ['label' => 'Progress', 'html' => function ($row) use ($project_stats) {
return projectProgressHtml($project_stats[intval($row['project_id'])], true);
}],
'time' => ['label' => 'Time', 'html' => function ($row) use ($project_stats) {
return projectTimeHtml($row, $project_stats[intval($row['project_id'])]);
}],
], array_values($projects), ['sortable' => false]) ?>
</div>
<?php } ?>
<?php if ($hw) { ?>
<h2 class="itflow-report-group-title mt-4 mb-2">Hardware and documentation</h2>
<?= reportStats([
['label' => 'Devices in use', 'value' => reportCount($hw['assets']), 'url' => '/agent/assets.php?client_id=' . $client_id,
'sub' => implode(' · ', array_map(function ($type, $n) { return escapeHtml($type) . ' <span class="text-body">' . reportCount($n) . '</span>'; },
array_slice(array_keys($hw['types']), 0, 3), array_slice(array_values($hw['types']), 0, 3)))],
['label' => 'Average age', 'value' => $hw['average'] === null ? '-' : reportYears($hw['average'])],
['label' => 'Over ' . REVIEW_OLD_YEARS . ' years old', 'value' => reportCount($hw['old']), 'tone' => $hw['old'] ? 'danger' : 'success'],
['label' => 'Out of warranty', 'value' => reportCount($hw['expired']), 'tone' => $hw['expired'] ? 'warning' : '',
'sub' => reportCount($hw['ending']) . ' <span class="text-body-tertiary">more within 90 days</span>'],
['label' => 'Unsupported OS', 'value' => reportCount($hw['os']), 'tone' => $hw['os'] ? 'danger' : 'success'],
]) ?>
<?php if ($hw['plan']) { ?>
<?= reportSectionOpen('Hardware to plan for', 'Unsupported, over ' . REVIEW_OLD_YEARS . ' years old, or the warranty ending soon') ?>
<?= reportTable([
'asset_name' => ['label' => 'Device', 'html' => function ($row) { return reportAssetCell($row); }],
'model' => ['label' => 'Make and model', 'html' => function ($row) {
return '<span class="text-nowrap">' . escapeHtml(trim($row['asset_make'] . ' ' . $row['asset_model'])) . '</span>';
}],
'contact_name' => ['label' => 'Used by', 'html' => function ($row) {
return $row['contact_name'] ? escapeHtml($row['contact_name']) : '<span class="text-body-tertiary">-</span>';
}],
'reasons' => ['label' => 'Why', 'html' => function ($row) {
$html = '<span class="d-inline-flex flex-wrap gap-1">';
foreach ($row['reasons'] as [$tone, $text]) {
$html .= '<span class="badge rounded-pill bg-' . $tone . '-subtle text-' . $tone . '-emphasis border border-' . $tone . '-subtle fw-normal">' . escapeHtml($text) . '</span>';
}
return $html . '</span>';
}],
], $hw['plan'], ['sortable' => false, 'limit' => 20]) ?>
</div>
<?php } ?>
<?php } ?>
<?php if ($itdoc && $renewals) { ?>
<?= reportSectionOpen('Renewals', 'Due in the next 90 days, or lapsed lately') ?>
<?= reportTable([
'days' => ['label' => 'Due', 'html' => function ($row) { return reportDuePill($row['days'], $row['auto']); }],
'name' => ['label' => 'What', 'class' => 'itflow-report-text', 'html' => function ($row) {
return '<div class="d-flex align-items-center gap-2">' . $row['tile'] . '<div class="min-w-0"><a class="fw-semibold text-body" href="' . escapeHtml($row['url']) . '">' . escapeHtml($row['name']) . '</a>'
. ($row['detail'] !== '' ? '<div class="small text-body-secondary">' . escapeHtml($row['detail']) . '</div>' : '') . '</div></div>';
}],
'kind' => ['label' => 'Type', 'html' => function ($row) { return REPORT_RENEWAL_KINDS[$row['kind']]['one']; }],
'date' => ['label' => 'Date', 'type' => 'date'],
], $renewals, ['sortable' => false, 'limit' => 20]) ?>
</div>
<?php } ?>
<?php if ($services) { ?>
<?= reportSectionOpen('Services needing a look', reportCount(count($services)) . ' of ' . reportCount($service_count)) ?>
<?= reportTable([
'service_name' => ['label' => 'Service', 'html' => function ($row) {
return '<span class="d-inline-flex align-items-center gap-2">' . serviceTile($row['service_category'], 'sm')
. '<a class="fw-semibold text-body" href="/agent/service.php?client_id=' . intval($row['service_client_id']) . '&service_id=' . intval($row['service_id']) . '">' . escapeHtml($row['service_name']) . '</a></span>';
}],
'service_importance' => ['label' => 'Importance'],
'review' => ['label' => 'Review', 'html' => function ($row) { return serviceReviewPill($row['review']); }],
'attention' => ['label' => 'Depends on', 'html' => function ($row) {
return intval($row['attention']) ? '<span class="text-danger-emphasis small"><i class="fas fa-exclamation-triangle me-1"></i>Something expiring or out of action</span>' : '<span class="text-body-tertiary small">All fine</span>';
}],
], $services, ['sortable' => false]) ?>
</div>
<?php } ?>
<?php if ($coverage) { ?>
<?= reportSectionOpen('Documentation', reportPercent($coverage['score']) . ' covered - ' . $coverage['passed'] . ' of ' . $coverage['applies'] . ' checks') ?>
<div class="card-body d-flex flex-wrap align-items-center gap-3">
<?php $tone = $coverage['score'] >= 90 ? 'success' : ($coverage['score'] >= 70 ? 'warning' : 'danger'); ?>
<div class="progress itflow-report-meter" style="width: 10rem" role="presentation"><div class="progress-bar bg-<?= $tone ?>" style="width: <?= round($coverage['score']) ?>%"></div></div>
<?php if ($coverage['missing']) { ?>
<span class="small text-body-secondary">Missing</span>
<?= reportCoverageMissingHtml($coverage) ?>
<?php } else { ?>
<span class="small text-success-emphasis"><i class="fas fa-check-circle me-1"></i>Everything we check is documented</span>
<?php } ?>
</div>
</div>
<?php } ?>
<?php if ($money) { ?>
<h2 class="itflow-report-group-title mt-4 mb-2">Billing</h2>
<?= reportStats([
['label' => 'Invoiced', 'value' => reportMoney($money['invoiced']), 'sub' => '<span class="text-body-tertiary">In the period</span>', 'url' => '/agent/invoices.php?client_id=' . $client_id],
['label' => 'Paid', 'value' => reportMoney($money['paid']), 'sub' => '<span class="text-body-tertiary">In the period</span>'],
['label' => 'Balance owing', 'value' => reportMoney($money['balance']), 'tone' => $money['overdue'] > 0.004 ? 'danger' : '',
'sub' => $money['overdue'] > 0.004 ? reportMoney($money['overdue']) . ' <span class="text-body-tertiary">past due</span>' : '<span class="text-body-tertiary">Nothing past due</span>'],
['label' => 'Monthly recurring', 'value' => reportMoney($money['mrr']), 'sub' => reportMoney($money['mrr'] * 12) . ' <span class="text-body-tertiary">a year</span>'],
]) ?>
<?php } ?>
<p class="small text-body-secondary">
Times run on the clock from when a ticket was raised; "typical" is the middle ticket, so a few long ones do not skew it. The SLA counts business hours.
Hardware age runs from the purchase date, else the install date.
</p>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,418 +1,200 @@
<?php
require_once "includes/inc_all_reports.php";
enforceUserPermission('module_sales');
/**
* Convert seconds to "HH:MM:SS" (supports totals > 24h by using hours > 24)
/*
* Time Detail by Client - every ticket reply with time on it in the period,
* grouped by client and ticket, with who logged it and what they wrote: the
* detail behind an invoice, for a client who asks what the hours were for.
*
* Each reply is rounded up to the billing increment picked (6, 15 or 30
* minutes) and those rounded figures are what add up to the ticket, client
* and grand totals, priced at the client's hourly rate.
*/
function secondsToHmsString($seconds) {
$seconds = (int) max(0, $seconds);
$hours = intdiv($seconds, 3600);
$minutes = intdiv($seconds % 3600, 60);
$secs = $seconds % 60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $secs);
require_once "includes/inc_report.php";
reportEnforce('client_ticket_time_detail');
$period = reportPeriod('last_month');
$client_id = reportClientId();
$agent_id = reportAgentId();
$billable_only = !empty($_GET['billable_only']);
$increments = ['0.1' => [360, '6 minutes'], '0.25' => [900, '15 minutes'], '0.5' => [1800, '30 minutes']];
$increment_key = isset($increments[$_GET['billing_increment'] ?? '']) ? $_GET['billing_increment'] : '0.25';
[$increment, $increment_label] = $increments[$increment_key];
$default_rate = floatval($config_default_hourly_rate);
$sql = mysqli_query($mysqli, "
SELECT ticket_reply_id, ticket_reply, ticket_reply_type, ticket_reply_created_at, TIME_TO_SEC(ticket_reply_time_worked) AS seconds,
ticket_reply_by, user_name, user_avatar,
ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_billable, ticket_client_id, ticket_resolved_at, ticket_closed_at, ticket_invoice_id,
client_name, client_abbreviation, client_rate
FROM ticket_replies
JOIN tickets ON ticket_reply_ticket_id = ticket_id
JOIN clients ON ticket_client_id = client_id
LEFT JOIN users ON ticket_reply_by = user_id
WHERE ticket_reply_archived_at IS NULL AND ticket_reply_time_worked IS NOT NULL AND TIME_TO_SEC(ticket_reply_time_worked) > 0
AND " . reportRangeSql('ticket_reply_created_at', $period) . "
" . reportClientSql('ticket_client_id', $client_id) . "
" . ($agent_id ? "AND ticket_reply_by = $agent_id" : '') . "
" . ($billable_only ? "AND ticket_billable = 1" : '') . "
ORDER BY client_name ASC, ticket_number ASC, ticket_reply_created_at ASC");
// Client > ticket > replies, with rounded totals at each level
$clients = [];
$replies = [];
while ($row = mysqli_fetch_assoc($sql)) {
$seconds = intval($row['seconds']);
$billed = intval(ceil($seconds / $increment) * $increment);
$rate = floatval($row['client_rate']) > 0 ? floatval($row['client_rate']) : $default_rate;
$row['seconds'] = $seconds;
$row['billed'] = $billed;
$row['rate'] = $rate;
// Only time on a billable ticket is worth anything on an invoice
$row['to_bill'] = intval($row['ticket_billable']) ? $billed : 0;
$row['value'] = $row['to_bill'] / 3600 * $rate;
$row['text'] = trim(preg_replace("/\n{3,}/", "\n\n", str_replace(["\r\n", "\r"], "\n", html_entity_decode(strip_tags(str_ireplace(['<br>', '<br/>', '<br />', '</p>', '</div>'], "\n", (string) $row['ticket_reply'])), ENT_QUOTES, 'UTF-8'))));
$replies[] = $row;
$c = intval($row['ticket_client_id']);
$t = intval($row['ticket_id']);
$clients[$c] = $clients[$c] ?? ['name' => $row['client_name'], 'abbr' => $row['client_abbreviation'], 'rate' => $rate, 'default_rate' => floatval($row['client_rate']) <= 0,
'tickets' => [], 'seconds' => 0, 'billed' => 0, 'to_bill' => 0, 'value' => 0.0];
$clients[$c]['tickets'][$t] = $clients[$c]['tickets'][$t] ?? ['row' => $row, 'replies' => [], 'seconds' => 0, 'billed' => 0, 'to_bill' => 0, 'value' => 0.0];
$clients[$c]['tickets'][$t]['replies'][] = $row;
foreach ([&$clients[$c], &$clients[$c]['tickets'][$t]] as &$level) {
$level['seconds'] += $seconds;
$level['billed'] += $billed;
$level['to_bill'] += $row['to_bill'];
$level['value'] += $row['value'];
}
unset($level);
}
/**
* Convert seconds to true decimal hours (rounded to 2 decimals).
*/
function secondsToDecimalHours($seconds) {
$seconds = (int) max(0, $seconds);
if ($seconds === 0) return 0.00;
return round($seconds / 3600, 2);
$total_seconds = array_sum(array_column($replies, 'seconds'));
$total_billed = array_sum(array_column($replies, 'billed'));
$total_to_bill = array_sum(array_column($replies, 'to_bill'));
$total_value = array_sum(array_column($replies, 'value'));
$ticket_count = array_sum(array_map(function ($c) { return count($c['tickets']); }, $clients));
if (reportExporting()) {
$columns = [
'client_name' => ['label' => 'Client'],
'ticket' => ['label' => 'Ticket', 'csv' => function ($row) { return ticketReference($row); }],
'ticket_subject' => ['label' => 'Subject'],
'date' => ['label' => 'Date', 'csv' => function ($row) { return date('Y-m-d H:i', strtotime($row['ticket_reply_created_at'])); }],
'user_name' => ['label' => 'Agent'],
'ticket_reply_type' => ['label' => 'Reply'],
'billable' => ['label' => 'Billable ticket', 'csv' => function ($row) { return intval($row['ticket_billable']) ? 'Yes' : 'No'; }],
'seconds' => ['label' => 'Hours', 'type' => 'hours'],
'billed' => ['label' => "Hours rounded up to {$increment_label}", 'type' => 'hours'],
'to_bill' => ['label' => 'Hours to bill', 'type' => 'hours'],
'rate' => ['label' => 'Rate', 'type' => 'money'],
'value' => ['label' => 'Value', 'type' => 'money'],
'text' => ['label' => 'Work done'],
];
reportCsv('Time Detail ' . $period['start'] . ' to ' . $period['end'], $columns, $replies, ['client_name' => 'Total', 'seconds' => $total_seconds, 'billed' => $total_billed, 'to_bill' => $total_to_bill, 'value' => $total_value]);
}
/**
* Round UP seconds to the nearest increment (in seconds).
*/
function secondsRoundUpToIncrement($seconds, $increment_seconds) {
$seconds = (int) max(0, $seconds);
$increment_seconds = (int) max(1, $increment_seconds);
require_once "includes/inc_report_layout.php";
if ($seconds === 0) return 0;
$controls = reportSelectControl('billing_increment', $increment_key, ['0.1' => 'Round up to 6 minutes', '0.25' => 'Round up to 15 minutes', '0.5' => 'Round up to 30 minutes'], 'fa-stopwatch', '', 'col-sm-6 col-lg-auto')
. reportSwitchControl('billable_only', $billable_only, 'Billable tickets only');
return (int) (ceil($seconds / $increment_seconds) * $increment_seconds);
}
/**
* Validate YYYY-MM-DD
*/
function isValidDateYmd($s) {
return is_string($s) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $s);
}
/**
* Billing increment options
* Key = hours (string), Value = increment seconds
*/
$billing_increment_options = [
'0.1' => 6 * 60, // 6 minutes
'0.25' => 15 * 60, // 15 minutes [DEFAULT]
'0.5' => 30 * 60, // 30 minutes
];
// Default range: current month
$from = isset($_GET['from']) ? $_GET['from'] : date('Y-m-01');
$to = isset($_GET['to']) ? $_GET['to'] : date('Y-m-t');
if (!isValidDateYmd($from)) $from = date('Y-m-01');
if (!isValidDateYmd($to)) $to = date('Y-m-t');
// Inclusive datetime bounds
$from_dt = $from . " 00:00:00";
$to_dt = $to . " 23:59:59";
$billable_only = (isset($_GET['billable_only']) && (int)$_GET['billable_only'] === 1) ? 1 : 0;
// Billing increment selection (default 0.25)
$billing_increment_key = isset($_GET['billing_increment']) ? (string)$_GET['billing_increment'] : '0.25';
if (!array_key_exists($billing_increment_key, $billing_increment_options)) {
$billing_increment_key = '0.25';
}
$billing_increment_seconds = $billing_increment_options[$billing_increment_key];
$billing_increment_minutes = (int) round($billing_increment_seconds / 60);
// Ticket-level billable flag (same as your original report)
$billable_sql = $billable_only ? " AND t.ticket_billable = 1 " : "";
$client_scope_sql = clientScopeSql('c.client_id');
/**
* Query returns ONLY replies that have time_worked and are within date range.
* Reply content column = tr.ticket_reply
*/
$stmt = $mysqli->prepare("
SELECT
c.client_id,
c.client_name,
t.ticket_id,
t.ticket_prefix,
t.ticket_number,
t.ticket_subject,
tr.ticket_reply_id,
tr.ticket_reply_created_at,
tr.ticket_reply_time_worked,
TIME_TO_SEC(tr.ticket_reply_time_worked) AS reply_time_seconds,
tr.ticket_reply AS reply_content
FROM tickets t
INNER JOIN clients c
ON c.client_id = t.ticket_client_id
INNER JOIN ticket_replies tr
ON tr.ticket_reply_ticket_id = t.ticket_id
AND tr.ticket_reply_time_worked IS NOT NULL
AND TIME_TO_SEC(tr.ticket_reply_time_worked) > 0
AND tr.ticket_reply_created_at BETWEEN ? AND ?
WHERE c.client_archived_at IS NULL
$billable_sql
$client_scope_sql
ORDER BY c.client_name ASC,
t.ticket_number ASC,
t.ticket_id ASC,
tr.ticket_reply_created_at ASC
");
$stmt->bind_param("ss", $from_dt, $to_dt);
$stmt->execute();
$result = $stmt->get_result();
$hours = function ($seconds) {
return number_format($seconds / 3600, 2);
};
?>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2">
<i class="fas fa-fw fa-life-ring me-2"></i>
Client Time Detail Audit Report (<?= escapeHtml($from) ?> to <?= escapeHtml($to) ?>)
<?php if ($billable_only) { ?>
<span class="badge bg-success ms-2">Billable Only</span>
<?php } ?>
</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();">
<i class="fas fa-fw fa-print me-2"></i>Print
</button>
</div>
</div>
<div class="card-header d-print-none">
<!-- Filters -->
<form class="mb-3">
<div class="row">
<div class="col-md-3 mb-2">
<label class="mb-1">From</label>
<input type="date" class="form-control" name="from" value="<?= escapeHtml($from) ?>">
</div>
<div class="itflow-report">
<div class="col-md-3 mb-2">
<label class="mb-1">To</label>
<input type="date" class="form-control" name="to" value="<?= escapeHtml($to) ?>">
</div>
<?php reportHeader('client_ticket_time_detail', [
'period' => $period,
'client' => $client_id,
'agent' => $agent_id,
'controls' => $controls,
]); ?>
<div class="col-md-3 mb-2">
<label class="mb-1">Billing time increment</label>
<select class="form-select" name="billing_increment">
<option value="0.1" <?= ($billing_increment_key === '0.1') ? 'selected' : '' ?>>0.1 hour (6 minutes)</option>
<option value="0.25" <?= ($billing_increment_key === '0.25') ? 'selected' : '' ?>>0.25 hour (15 minutes)</option>
<option value="0.5" <?= ($billing_increment_key === '0.5') ? 'selected' : '' ?>>0.5 hour (30 minutes)</option>
</select>
</div>
<div class="col-md-2 mb-2 d-flex align-items-end ms-auto">
<button type="submit" class="btn btn-success w-100">
<i class="fas fa-fw fa-filter me-1"></i>Apply
</button>
</div>
<div class="col-md-4 mb-2 d-flex align-items-end">
<div class="form-check">
<input
type="checkbox"
class="form-check-input"
id="billable_only"
name="billable_only"
value="1"
<?php if ($billable_only) echo 'checked'; ?>
>
<label class="form-check-label" for="billable_only">Billable tickets only</label>
</div>
</div>
<?= reportStats([
['label' => 'Time logged', 'value' => reportHours($total_seconds, 2) . ' h', 'sub' => reportCount(count($replies)) . ' <span class="text-body-tertiary">replies on</span> ' . reportCount($ticket_count) . ' <span class="text-body-tertiary">tickets</span>'],
['label' => 'To bill', 'value' => reportHours($total_to_bill, 2) . ' h', 'sub' => '<span class="text-body-tertiary">On billable tickets, each reply rounded up to ' . escapeHtml($increment_label) . '</span>'],
['label' => 'Value', 'value' => reportMoney($total_value), 'sub' => '<span class="text-body-tertiary">The hours to bill at each client\'s rate</span>'],
['label' => 'Clients', 'value' => reportCount(count($clients)), 'sub' => '<span class="text-body-tertiary">With time in the period</span>'],
]) ?>
<?php if (!$replies) { ?>
<div class="card"><div class="card-body"><?= reportEmpty('No time was logged on ticket replies in this period.', 'fa-stopwatch', 'secondary') ?></div></div>
<?php } ?>
<?php foreach ($clients as $cid => $client) { ?>
<div class="card itflow-report-section itflow-report-long">
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<h3 class="card-title mb-0 me-auto"><?= reportClientCell($cid, $client['name'], $client['abbr']) ?></h3>
<span class="small text-body-secondary">
<?= count($client['tickets']) ?> ticket<?= count($client['tickets']) === 1 ? '' : 's' ?> ·
<?= $hours($client['seconds']) ?> h logged ·
<span class="text-body fw-semibold"><?= $hours($client['to_bill']) ?> h to bill</span>
<?php if ($client['rate'] > 0) { ?>· <?= reportMoney($client['rate']) ?>/h<?= $client['default_rate'] ? ' (default)' : '' ?> · <span class="text-body fw-semibold"><?= reportMoney($client['value']) ?></span><?php } ?>
</span>
</div>
</form>
</div>
</div>
<div class="card">
<div class="table-responsive-sm">
<table class="table table-striped table-sm">
<thead class="bg-dark">
<tr>
<th>Ticket / Replies with Time</th>
<th class="text-end" style="width: 150px;">Time Worked</th>
<th class="text-end" style="width: 120px;">Billable (hrs)</th>
</tr>
</thead>
<tbody>
<?php
// Helper: print ticket subtotal row (billable hours = sum of rounded replies for that ticket)
$printTicketSubtotalRow = function($ticket_label_html, $ticket_seconds, $ticket_billable_seconds) {
$ticket_billed = secondsToDecimalHours($ticket_billable_seconds);
?>
<tr class="fw-bold">
<td class="text-end pe-3">Ticket Total for <?= $ticket_label_html ?></td>
<td class="text-end"><?= formatDuration(secondsToHmsString($ticket_seconds)) ?></td>
<td class="text-end"><?= number_format($ticket_billed, 2) ?></td>
</tr>
<?php
return $ticket_billed;
};
$current_client_id = null;
$current_client_name = null;
$current_ticket_id = null;
$current_ticket_label_html = null;
$client_ticket_count = 0;
$client_time_seconds = 0;
// Billable seconds are based on rounding each reply UP to the chosen increment
$client_billable_seconds = 0;
$ticket_time_seconds = 0;
$ticket_billable_seconds = 0;
$grand_ticket_count = 0;
$grand_time_seconds = 0;
$grand_billable_seconds = 0;
$had_rows = false;
while ($r = mysqli_fetch_assoc($result)) {
$had_rows = true;
$client_id = (int)$r['client_id'];
$client_name_html = escapeHtml($r['client_name']);
$ticket_id = (int)$r['ticket_id'];
$ticket_prefix = escapeHtml($r['ticket_prefix']);
$ticket_number = (int)$r['ticket_number'];
$ticket_subject_html = escapeHtml($r['ticket_subject']);
$reply_created_at = $r['ticket_reply_created_at'];
$reply_seconds = (int)$r['reply_time_seconds'];
$reply_hms = secondsToHmsString($reply_seconds);
// Rounded-up billable seconds for THIS reply
$reply_billable_seconds = secondsRoundUpToIncrement($reply_seconds, $billing_increment_seconds);
// Reply content: escape for safety, keep line breaks readable
$reply_content_raw = $r['reply_content'] ?? '';
$reply_content_clean = strip_tags($reply_content_raw);
$reply_content_clean = str_replace(["\r\n", "\r"], "\n", $reply_content_clean);
$reply_content_clean = preg_replace("/\n{3,}/", "\n\n", $reply_content_clean);
$reply_content_html = nl2br(escapeHtml(trim($reply_content_clean)));
// Close out previous client if client changed
if ($current_client_id !== null && $client_id !== $current_client_id) {
// Close out previous ticket (if any)
if ($current_ticket_id !== null) {
$printTicketSubtotalRow($current_ticket_label_html, $ticket_time_seconds, $ticket_billable_seconds);
$ticket_time_seconds = 0;
$ticket_billable_seconds = 0;
$current_ticket_id = null;
$current_ticket_label_html = null;
echo '<tr><td colspan="3"></td></tr>';
}
// Client subtotal (billable based on sum of rounded replies across all tickets)
?>
<tr class="fw-bold">
<td class="text-end">
Total for <?= $current_client_name ?> (<?= $client_ticket_count ?> tickets)
</td>
<td class="text-end"><?= formatDuration(secondsToHmsString($client_time_seconds)) ?></td>
<td class="text-end"><?= number_format(secondsToDecimalHours($client_billable_seconds), 2) ?></td>
</tr>
<tr><td colspan="3"></td></tr>
<?php
// Reset client totals
$client_ticket_count = 0;
$client_time_seconds = 0;
$client_billable_seconds = 0;
}
// Client header
if ($client_id !== $current_client_id) {
$current_client_id = $client_id;
$current_client_name = $client_name_html;
?>
<tr class="table-active">
<td colspan="3" class="fw-bold"><?= $client_name_html ?></td>
</tr>
<?php
}
// Ticket label
$display_ticket = trim($ticket_prefix . $ticket_number);
if ($display_ticket === '') $display_ticket = (string)$ticket_number;
$ticket_label_html = escapeHtml($display_ticket) . " - " . $ticket_subject_html;
// Ticket changed: close previous ticket subtotal
if ($current_ticket_id !== null && $ticket_id !== $current_ticket_id) {
$printTicketSubtotalRow($current_ticket_label_html, $ticket_time_seconds, $ticket_billable_seconds);
echo '<tr><td colspan="3"></td></tr>';
// Reset ticket accumulators
$ticket_time_seconds = 0;
$ticket_billable_seconds = 0;
$current_ticket_id = null;
$current_ticket_label_html = null;
}
// Ticket header (first row for this ticket)
if ($ticket_id !== $current_ticket_id) {
$current_ticket_id = $ticket_id;
$current_ticket_label_html = $ticket_label_html;
$client_ticket_count++;
$grand_ticket_count++;
?>
<div class="table-responsive">
<table class="table table-sm align-middle mb-0 itflow-report-table">
<thead class="table-light">
<tr>
<td class="fw-bold"><?= $ticket_label_html ?></td>
<td class="text-end text-muted"></td>
<td class="text-end text-muted"></td>
<th>Ticket and work done</th>
<th class="text-nowrap">Agent</th>
<th class="text-end text-nowrap">Logged</th>
<th class="text-end text-nowrap" title="Rounded up to <?= escapeHtml($increment_label) ?>">Rounded</th>
</tr>
<?php
}
</thead>
<tbody>
<?php foreach ($client['tickets'] as $ticket) {
$row = $ticket['row'];
$state = !empty($row['ticket_closed_at']) ? 'Closed' : (!empty($row['ticket_resolved_at']) ? 'Resolved' : 'Open'); ?>
<tr class="itflow-report-group-row">
<td colspan="2">
<?= reportTicketLink($row) ?>
<span class="small fw-normal text-body-secondary ms-2"><?= $state ?><?= intval($row['ticket_billable']) ? '' : ' · not billable' ?><?= intval($row['ticket_invoice_id']) ? ' · invoiced' : '' ?></span>
</td>
<td class="text-end"><?= $hours($ticket['seconds']) ?></td>
<td class="text-end"><?= $hours($ticket['billed']) ?></td>
</tr>
<?php foreach ($ticket['replies'] as $reply) { ?>
<tr>
<td class="itflow-report-sub">
<div class="small text-body-secondary">
<i class="far fa-clock me-1"></i><?= escapeHtml(date('D, M j, Y g:i A', strtotime($reply['ticket_reply_created_at']))) ?>
<?php if ($reply['ticket_reply_type'] === 'Internal') { ?><span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal ms-1">Internal note</span><?php } ?>
</div>
<?php if ($reply['text'] !== '') { ?>
<div class="mt-1" style="white-space: pre-line"><?= escapeHtml($reply['text']) ?></div>
<?php } ?>
</td>
<td class="text-nowrap align-top"><?= reportAgentCell($reply['ticket_reply_by'], $reply['user_name'] ?? '', $reply['user_avatar'] ?? '', 'Unknown') ?></td>
<td class="text-end align-top text-body-secondary"><?= $hours($reply['seconds']) ?></td>
<td class="text-end align-top"><?= $hours($reply['billed']) ?></td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
<?php } ?>
// Reply row (indented)
?>
<tr>
<td class="ps-4 text-muted">
<i class="far fa-clock me-1"></i>
<?= escapeHtml(date('Y-m-d g:i A', strtotime($reply_created_at))) ?>
<div class="mt-1 text-body" style="white-space: normal;">
<?= $reply_content_html ?>
</div>
</td>
<td class="text-end"><?= formatDuration($reply_hms) ?></td>
<td class="text-end"><?= number_format(secondsToDecimalHours($reply_billable_seconds), 2) ?></td>
</tr>
<?php
<?php if ($replies) { ?>
<div class="card">
<div class="card-body d-flex flex-wrap justify-content-between gap-2 fw-semibold">
<span>All clients - <?= reportCount($ticket_count) ?> tickets</span>
<span><?= $hours($total_seconds) ?> h logged · <?= $hours($total_to_bill) ?> h to bill · <?= reportMoney($total_value) ?></span>
</div>
<div class="card-footer small text-body-secondary">
Only replies with time on them, by the date they were written. Each reply is rounded up to <?= escapeHtml($increment_label) ?> on its own, and the rounded figures on billable tickets are what is to bill.
</div>
</div>
<?php } ?>
// Totals (raw time)
$ticket_time_seconds += $reply_seconds;
$client_time_seconds += $reply_seconds;
$grand_time_seconds += $reply_seconds;
// Totals (billable time = sum of rounded replies)
$ticket_billable_seconds += $reply_billable_seconds;
$client_billable_seconds += $reply_billable_seconds;
$grand_billable_seconds += $reply_billable_seconds;
}
if (!$had_rows) {
?>
<tr>
<td colspan="3" class="text-center text-muted">
No ticket replies with time worked found for this date range.
</td>
</tr>
<?php
} else {
// Close last ticket subtotal
if ($current_ticket_id !== null) {
$printTicketSubtotalRow($current_ticket_label_html, $ticket_time_seconds, $ticket_billable_seconds);
echo '<tr><td colspan="3"></td></tr>';
}
// Close last client subtotal
?>
<tr class="fw-bold">
<td class="text-end">
Total for <?= $current_client_name ?> (<?= $client_ticket_count ?> tickets)
</td>
<td class="text-end"><?= formatDuration(secondsToHmsString($client_time_seconds)) ?></td>
<td class="text-end"><?= number_format(secondsToDecimalHours($client_billable_seconds), 2) ?></td>
</tr>
<tr><td colspan="3"></td></tr>
<!-- Grand totals -->
<tr class="fw-bold">
<td class="text-end">
Grand Total (<?= $grand_ticket_count ?> tickets)
</td>
<td class="text-end"><?= formatDuration(secondsToHmsString($grand_time_seconds)) ?></td>
<td class="text-end"><?= number_format(secondsToDecimalHours($grand_billable_seconds), 2) ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<small class="text-muted p-2">
This report shows only ticket replies with time worked within the selected date range.
“Billable (hrs)” is calculated by rounding each reply up to the nearest <?= (int)$billing_increment_minutes ?> minutes (<?= escapeHtml($billing_increment_key) ?> hours),
then summing those rounded values for ticket/client/grand totals.
<br>
Reply content is displayed under each reply timestamp.
</small>
</div>
</div>
<?php
require_once "../../includes/footer.php";
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,130 +1,187 @@
<?php
/*
* Credential rotation - every client login whose password hasn't changed in
* a while (90 days unless another span is picked), oldest first, with how
* many each client has. Archived credentials are left out; ones with no
* change date recorded count as due. Each opens on its client's credentials
* page, where it can be changed (credentials.php?open=ID).
* Credential Rotation - client logins whose password has not changed in a
* while (90 days unless another span is picked), oldest first, with how old
* every password is and how many each client has due. Archived credentials
* and archived clients are left out; ones with no change date recorded count
* as due. Each opens on its client's credentials page, where it can be
* changed (credentials.php?open=ID). Nothing secret is shown or exported.
*/
require_once "includes/inc_all_reports.php";
require_once "includes/inc_report.php";
reportEnforce('credential_rotation');
enforceUserPermission('module_credential');
$day_options = [30 => '30 days', 60 => '60 days', 90 => '90 days', 180 => '6 months', 365 => 'A year'];
$day_options = [30 => 'Not changed in 30 days', 60 => 'Not changed in 60 days', 90 => 'Not changed in 90 days', 180 => 'Not changed in 6 months', 365 => 'Not changed in a year'];
$days = intval($_GET['days'] ?? CREDENTIAL_ROTATE_DAYS);
if (!isset($day_options[$days])) {
$days = CREDENTIAL_ROTATE_DAYS;
}
$sql = mysqli_query($mysqli,
"SELECT credential_id, credential_name, credential_description, credential_uri, credential_password_changed_at, credential_accessed_at,
credential_client_id, client_name
FROM credentials
JOIN clients ON credential_client_id = client_id
WHERE credential_archived_at IS NULL AND client_archived_at IS NULL
AND (credential_password_changed_at IS NULL OR credential_password_changed_at < NOW() - INTERVAL $days DAY)
" . clientScopeSql('credential_client_id') . "
ORDER BY client_name ASC, credential_password_changed_at IS NOT NULL, credential_password_changed_at ASC, credential_name ASC"
);
$client_id = reportClientId();
$credentials = [];
$by_client = [];
$sql = mysqli_query($mysqli, "SELECT credential_id, credential_name, credential_description, credential_uri, credential_category, credential_password_changed_at, credential_accessed_at,
(credential_otp_secret IS NOT NULL AND credential_otp_secret != '') AS has_otp, credential_client_id, client_name, client_abbreviation
FROM credentials
JOIN clients ON credential_client_id = client_id
WHERE credential_archived_at IS NULL AND client_archived_at IS NULL" . reportClientSql('credential_client_id', $client_id) . "
ORDER BY credential_password_changed_at IS NOT NULL, credential_password_changed_at ASC, client_name ASC, credential_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['has_otp'] = intval($row['has_otp']) === 1;
$row['age'] = credentialAge($row['credential_password_changed_at']);
$row['age_days'] = $row['age'] ? $row['age']['days'] : null;
$row['due'] = !$row['age'] || $row['age']['days'] >= $days;
$row['overdue'] = !$row['age'] || $row['age']['state'] === 'overdue';
$credentials[] = $row;
$client = intval($row['credential_client_id']);
$by_client[$client] = $by_client[$client] ?? ['name' => $row['client_name'], 'count' => 0, 'year' => 0];
$by_client[$client]['count']++;
$age = credentialAge($row['credential_password_changed_at']);
if (!$age || $age['state'] === 'overdue') {
$by_client[$client]['year']++;
}
$due = array_values(array_filter($credentials, function ($c) { return $c['due']; }));
// Every password by age
$age_buckets = ['Under 90 days' => [0, 90, 'success'], '90 days to 6 months' => [90, 182, 'warning'], '6 to 12 months' => [182, 365, 'orange'],
'1 to 2 years' => [365, 730, 'danger'], 'Over 2 years' => [730, PHP_INT_MAX, 'danger']];
$age_counts = array_fill_keys(array_keys($age_buckets), 0) + ['Never recorded' => 0];
$by_client = [];
foreach ($credentials as $row) {
$c = intval($row['credential_client_id']);
$by_client[$c] = $by_client[$c] ?? ['client_id' => $c, 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation'], 'total' => 0, 'due' => 0, 'overdue' => 0, 'otp' => 0, 'oldest' => null];
$by_client[$c]['total']++;
$by_client[$c]['due'] += $row['due'] ? 1 : 0;
$by_client[$c]['overdue'] += $row['overdue'] ? 1 : 0;
$by_client[$c]['otp'] += $row['has_otp'] ? 1 : 0;
if ($row['age']) {
$by_client[$c]['oldest'] = max($by_client[$c]['oldest'] ?? 0, $row['age']['days']);
foreach ($age_buckets as $label => [$from, $to]) {
if ($row['age']['days'] >= $from && $row['age']['days'] < $to) {
$age_counts[$label]++;
break;
}
}
} else {
$age_counts['Never recorded']++;
}
}
foreach ($by_client as &$client) {
$client['otp_share'] = reportShare($client['otp'], $client['total'], 0);
}
unset($client);
$by_client = array_values(array_filter($by_client, function ($c) { return $c['due'] > 0; }));
usort($by_client, function ($a, $b) { return $b['overdue'] <=> $a['overdue'] ?: $b['due'] <=> $a['due']; });
$client_columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'credentials.php');
}],
'total' => ['label' => 'Credentials', 'type' => 'count'],
'due' => ['label' => 'Due', 'type' => 'count', 'html' => function ($row) {
return '<a class="itflow-report-amount text-warning-emphasis fw-semibold" href="/agent/credentials.php?client_id=' . intval($row['client_id']) . '&show=due&sort=credential_password_changed_at&order=ASC">'
. reportCount($row['due']) . '</a>';
}],
'overdue' => ['label' => 'Over a year or never', 'type' => 'count', 'html' => function ($row) {
return $row['overdue'] ? '<span class="text-danger-emphasis fw-semibold">' . reportCount($row['overdue']) . '</span>' : '<span class="itflow-report-zero">–</span>';
}],
'oldest' => ['label' => 'Oldest change', 'type' => 'count', 'csv_label' => 'Oldest change (days ago)', 'html' => function ($row) {
return $row['oldest'] === null ? '<span class="itflow-report-zero">–</span>' : '<span class="text-nowrap">' . escapeHtml(timeAgo(date('Y-m-d', strtotime('-' . $row['oldest'] . ' days')))) . '</span>';
}],
'otp_share' => ['label' => 'With 2FA', 'type' => 'percent', 'title' => 'Credentials holding a 2FA (TOTP) code', 'class' => 'text-body-secondary'],
];
$credential_columns = [
'credential_name' => ['label' => 'Credential', 'class' => 'itflow-report-text', 'html' => function ($row) {
return '<div class="d-flex align-items-center gap-2">' . credentialTile($row, 'sm') . '<div class="min-w-0">'
. '<a class="fw-semibold text-body" href="/agent/credentials.php?client_id=' . intval($row['credential_client_id']) . '&open=' . intval($row['credential_id']) . '">' . escapeHtml($row['credential_name']) . '</a>'
. ($row['credential_description'] ? '<div class="small text-body-secondary">' . escapeHtml($row['credential_description']) . '</div>' : '') . '</div></div>';
}],
'credential_description' => ['label' => 'Description', 'screen' => false],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['credential_client_id'], $row['client_name'], $row['client_abbreviation'], 'credentials.php');
}],
'age_days' => ['label' => 'Password last changed', 'type' => 'count', 'csv_label' => 'Days since changed', 'html' => function ($row) {
if (!$row['age']) {
return '<span class="badge rounded-pill bg-danger-subtle text-danger-emphasis border border-danger-subtle fw-normal">Never recorded</span>';
}
return credentialAgePill($row['age']) . '<div class="small text-body-secondary mt-1">' . escapeHtml($row['age']['date']) . '</div>';
}],
'credential_password_changed_at' => ['label' => 'Changed on', 'type' => 'date', 'screen' => false],
'has_otp' => ['label' => '2FA', 'sort' => false, 'csv' => function ($row) { return $row['has_otp'] ? 'Yes' : 'No'; }, 'html' => function ($row) {
return $row['has_otp'] ? '<span class="text-success-emphasis small text-nowrap"><i class="fas fa-fw fa-shield-alt me-1"></i>Yes</span>' : '<span class="itflow-report-zero">–</span>';
}],
'credential_accessed_at' => ['label' => 'Last opened', 'type' => 'date', 'html' => function ($row) {
return $row['credential_accessed_at'] ? '<span class="small text-body-secondary text-nowrap" title="' . escapeHtml($row['credential_accessed_at']) . '">' . escapeHtml(timeAgo($row['credential_accessed_at'])) . '</span>'
: '<span class="itflow-report-zero">–</span>';
}],
];
if (reportExporting('clients')) {
reportCsv('Credential Rotation by Client', $client_columns, $by_client);
}
if (reportExporting()) {
reportCsv('Credentials Due for Rotation', $credential_columns, $due);
}
require_once "includes/inc_report_layout.php";
$overdue = count(array_filter($credentials, function ($c) { return $c['overdue']; }));
$otp = count(array_filter($credentials, function ($c) { return $c['has_otp']; }));
$clients_due = count($by_client);
$span = ['30' => '30 days', '60' => '60 days', '90' => '90 days', '180' => '6 months', '365' => 'year'][(string) $days];
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-history me-2"></i>Credentials not changed in <?= strtolower($day_options[$days]) ?></h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('credential_rotation', [
'subtitle' => $day_options[$days],
'controls' => reportSelectControl('days', $days, $day_options, 'fa-history') . reportClientControl($client_id),
'export' => ['credentials' => 'Credentials due', 'clients' => 'By client'],
]); ?>
<?= reportStats([
['label' => 'Credentials', 'value' => reportCount(count($credentials)), 'url' => '/agent/credentials.php' . ($client_id ? "?client_id=$client_id" : ''),
'sub' => reportCount($otp) . ' <span class="text-body-tertiary">with a 2FA code</span>'],
['label' => 'Due for rotation', 'value' => reportCount(count($due)), 'tone' => $due ? 'warning' : 'success',
'sub' => $credentials ? reportPercent(reportShare(count($due), count($credentials), 0)) . ' <span class="text-body-tertiary">of them</span>' : ''],
['label' => 'Over a year or never', 'value' => reportCount($overdue), 'tone' => $overdue ? 'danger' : 'success',
'sub' => reportCount($age_counts['Never recorded']) . ' <span class="text-body-tertiary">never recorded</span>'],
['label' => 'Clients with some due', 'value' => reportCount($clients_due), 'tone' => $clients_due ? 'warning' : ''],
]) ?>
<?php if ($credentials) { ?>
<?= reportSectionOpen('How old the passwords are', 'Every credential') ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'labels' => array_keys($age_counts),
'series' => [['label' => 'Credentials', 'data' => array_values($age_counts),
'tones' => array_merge(array_column(array_values($age_buckets), 2), ['muted'])]],
'format' => 'count',
'legend' => false,
], 'sm', 'Credentials by how long since the password changed') ?>
</div>
</div>
<div class="card-body">
<form class="d-flex flex-wrap align-items-center gap-2 mb-3 d-print-none">
<label class="form-label mb-0" for="rotationDays">Not changed in</label>
<select class="form-select w-auto" id="rotationDays" name="days" onchange="this.form.submit()">
<?php foreach ($day_options as $value => $label) { ?>
<option value="<?= $value ?>" <?= $value === $days ? 'selected' : '' ?>><?= $label ?></option>
<?php } ?>
</select>
<span class="text-body-secondary small ms-sm-2"><?= count($credentials) ?> credential<?= count($credentials) === 1 ? '' : 's' ?> across <?= count($by_client) ?> client<?= count($by_client) === 1 ? '' : 's' ?></span>
</form>
<?php } ?>
<?php if (!$credentials) { ?>
<div class="itflow-asset-empty"><i class="fas fa-check-circle fa-2x mb-2 text-success opacity-75"></i><div>Every password has changed in the last <?= strtolower($day_options[$days]) ?>.</div></div>
<?php } else { ?>
<?php if (!$due) { ?>
<div class="card"><div class="card-body"><?= reportEmpty("Every password has changed in the last $span.") ?></div></div>
<?php } else { ?>
<h6 class="text-body-secondary text-uppercase small fw-semibold">By client</h6>
<div class="table-responsive-sm mb-4">
<table class="table table-sm table-hover align-middle">
<thead class="table-light"><tr><th>Client</th><th class="text-end">Due</th><th class="text-end">Over a year or never</th></tr></thead>
<tbody>
<?php foreach ($by_client as $client_id => $client) { ?>
<tr>
<td><a href="../credentials.php?client_id=<?= $client_id ?>&show=due&sort=credential_password_changed_at&order=ASC"><?= escapeHtml($client['name']) ?></a></td>
<td class="text-end"><?= $client['count'] ?></td>
<td class="text-end"><?= $client['year'] ? '<span class="text-danger fw-semibold">' . $client['year'] . '</span>' : '<span class="text-body-secondary">0</span>' ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php if (!$client_id) { ?>
<?= reportSectionOpen('By client', 'The most overdue first') ?>
<?= reportTable($client_columns, $by_client, ['limit' => 50, 'export_table' => 'clients']) ?>
</div>
<?php } ?>
<h6 class="text-body-secondary text-uppercase small fw-semibold">Credentials, oldest first</h6>
<div class="table-responsive-sm">
<table class="table table-hover align-middle">
<thead class="table-light text-nowrap">
<tr>
<th>Client</th>
<th>Credential</th>
<th>Password last changed</th>
<th>Last used</th>
</tr>
</thead>
<tbody>
<?php foreach ($credentials as $row) {
$client_id = intval($row['credential_client_id']);
$age = credentialAge($row['credential_password_changed_at']); ?>
<tr>
<td class="text-nowrap"><?= escapeHtml($row['client_name']) ?></td>
<td>
<div class="d-flex align-items-center gap-2">
<?= credentialTile($row, 'sm') ?>
<div class="min-w-0">
<a class="fw-semibold" href="../credentials.php?client_id=<?= $client_id ?>&open=<?= intval($row['credential_id']) ?>"><?= escapeHtml($row['credential_name']) ?></a>
<?php if ($row['credential_description']) { ?><div class="small text-body-secondary"><?= escapeHtml($row['credential_description']) ?></div><?php } ?>
</div>
</div>
</td>
<td class="text-nowrap">
<?php if ($age) { ?>
<?= credentialAgePill($age) ?>
<div class="small text-body-secondary mt-1"><?= escapeHtml($age['date']) ?></div>
<?php } else { ?>
<span class="badge rounded-pill bg-danger-subtle text-danger-emphasis border border-danger-subtle fw-normal">Never recorded</span>
<?php } ?>
</td>
<td class="text-nowrap small text-body-secondary"><?= $row['credential_accessed_at'] ? timeAgo($row['credential_accessed_at']) : '-' ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php } ?>
<?= reportSectionOpen('Due for rotation', 'Never recorded, then the oldest', 'itflow-report-long') ?>
<?= reportTable($credential_columns, $due, ['limit' => 300, 'export_table' => 'credentials']) ?>
<div class="card-footer small text-body-secondary">
Credentials not archived, at active clients. A password counts from when it was last changed in ITFlow; one never recorded counts as due.
Open a credential to change it and the date updates on its own. Passwords and 2FA codes are never shown here or exported.
</div>
</div>
</div>
<?php
require_once "../../includes/footer.php";
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -0,0 +1,121 @@
<?php
/*
* Documentation Coverage - for each active client, whether the basics an
* agent reaches for are written down: who to call and who pays, where they
* are, their hardware (placed and with an owner), networks, logins,
* documents, domains, services and licenses. A check that cannot apply (no
* user devices to give owners) is left out of that client's score. Worst
* covered first, with what is missing linking to where to add it.
*/
require_once "includes/inc_report.php";
reportEnforce('documentation_coverage');
$gaps_only = !empty($_GET['gaps']);
$checks = reportCoverageChecks();
$clients = reportCoverage();
$all = array_values($clients);
usort($all, function ($a, $b) { return $a['score'] <=> $b['score'] ?: strcasecmp($a['client'], $b['client']); });
$rows = $gaps_only ? array_values(array_filter($all, function ($c) { return $c['missing']; })) : $all;
// How many clients miss each check
$missing_counts = array_fill_keys(array_keys($checks), 0);
foreach ($all as $client) {
foreach ($client['missing'] as $key) {
$missing_counts[$key]++;
}
}
arsort($missing_counts);
$columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr']);
}],
'score' => ['label' => 'Coverage', 'type' => 'percent', 'html' => function ($row) {
$tone = $row['score'] >= 90 ? 'success' : ($row['score'] >= 70 ? 'warning' : 'danger');
return '<div class="d-flex align-items-center justify-content-end gap-2"><div class="progress itflow-report-meter" style="width: 5rem" role="presentation">'
. '<div class="progress-bar bg-' . $tone . '" style="width: ' . round($row['score']) . '%"></div></div>'
. '<span class="fw-semibold text-' . $tone . '-emphasis" title="' . $row['passed'] . ' of ' . $row['applies'] . ' checks">' . reportPercent($row['score']) . '</span></div>';
}],
'missing' => ['label' => 'Missing', 'sort' => false, 'class' => 'itflow-report-text', 'csv' => function ($row) use ($checks) {
return implode(', ', array_map(function ($key) use ($checks) { return $checks[$key]['label']; }, $row['missing']));
}, 'html' => function ($row) {
return reportCoverageMissingHtml($row);
}],
'contacts' => ['label' => 'Contacts', 'type' => 'count'],
'locations' => ['label' => 'Locations', 'type' => 'count', 'screen' => false],
'assets' => ['label' => 'Assets', 'type' => 'count'],
'placed_share' => ['label' => 'Placed', 'type' => 'percent', 'title' => 'Assets with a location', 'html' => function ($row) {
return $row['placed_share'] === null ? '<span class="itflow-report-zero">–</span>' : reportRateHtml($row['placed_share'], 95, REPORT_COVERAGE_SHARE);
}],
'owned_share' => ['label' => 'Owned', 'type' => 'percent', 'title' => 'Laptops, desktops, phones and tablets with a contact', 'html' => function ($row) {
return $row['owned_share'] === null ? '<span class="itflow-report-zero">–</span>' : reportRateHtml($row['owned_share'], 95, REPORT_COVERAGE_SHARE);
}],
'documents' => ['label' => 'Documents', 'type' => 'count'],
];
// The export carries every check as Yes / No / blank (does not apply)
foreach ($checks as $key => $check) {
$columns["check_$key"] = ['label' => $check['label'], 'csv_label' => 'Check: ' . $check['label'], 'screen' => false, 'csv' => function ($row) use ($key) {
return $row['checks'][$key] === null ? '' : ($row['checks'][$key] ? 'Yes' : 'No');
}];
}
if (reportExporting()) {
reportCsv('Documentation Coverage', $columns, $rows);
}
require_once "includes/inc_report_layout.php";
$scores = array_column($all, 'score');
$average = $scores ? array_sum($scores) / count($scores) : null;
$complete = count(array_filter($all, function ($c) { return !$c['missing']; }));
$top_gap = array_key_first(array_filter($missing_counts));
?>
<div class="itflow-report">
<?php reportHeader('documentation_coverage', [
'subtitle' => 'As of ' . date('M j, Y'),
'controls' => reportSwitchControl('gaps', $gaps_only, 'Only clients with gaps'),
]); ?>
<?= reportStats([
['label' => 'Active clients', 'value' => reportCount(count($all)), 'sub' => reportCount(count($checks)) . ' <span class="text-body-tertiary">checks each</span>'],
['label' => 'Average coverage', 'value_html' => $average === null ? '-' : reportRateHtml($average, 90, 70)],
['label' => 'Fully documented', 'value' => reportCount($complete), 'tone' => $complete ? 'success' : '',
'sub' => count($all) ? reportPercent(reportShare($complete, count($all), 0)) . ' <span class="text-body-tertiary">of clients</span>' : ''],
['label' => 'Most often missing', 'value' => $top_gap ? $checks[$top_gap]['label'] : 'Nothing', 'tone' => $top_gap ? 'warning' : 'success',
'sub' => $top_gap ? reportCount($missing_counts[$top_gap]) . ' <span class="text-body-tertiary">' . ($missing_counts[$top_gap] === 1 ? 'client' : 'clients') . '</span>' : ''],
]) ?>
<?php if (array_filter($missing_counts)) { ?>
<?= reportSectionOpen('What is missing most', 'Clients without it') ?>
<div class="card-body">
<?php $gap_rows = array_filter($missing_counts); ?>
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_map(function ($key) use ($checks) { return $checks[$key]['label']; }, array_keys($gap_rows)),
'series' => [['label' => 'Clients without it', 'data' => array_values($gap_rows), 'tone' => 'warning']],
'format' => 'count',
'legend' => false,
], '', 'How many clients are missing each item') ?>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By client', 'Least covered first') ?>
<?= reportTable($columns, $rows, ['empty' => reportEmpty($gaps_only ? 'Every client has everything documented.' : 'No active clients.')]) ?>
<div class="card-footer small text-body-secondary">
Active clients, counting only what is not archived. Placed and owned pass at <?= REPORT_COVERAGE_SHARE ?>%: assets with a location, and laptops, desktops, phones and
tablets with a contact; a client without any is not scored on them. Each missing item opens the page to add it on.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,97 +1,173 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Spend by Vendor - who the money goes to: every vendor paid in the period,
* largest first, with how many expenses, their share of all spending, the
* category most of it went under, what it was the period before, and what
* is committed to them every month in recurring expenses.
*
* "Paid 600 or more" narrows it to the vendors a US business may owe a 1099
* for - pick a calendar year (This year, Last year or a year) for that.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('expense_by_vendor');
if (isset($_GET['year'])) {
if ($_GET['year'] === 'all') {
$year = 'all';
} else {
$year = intval($_GET['year']);
}
} else {
$year = date('Y');
$period = reportPeriod('this_year');
$only_1099 = !empty($_GET['over600']);
$range = reportRangeSql('expense_date', $period);
$prev_range = reportRangeSql('expense_date', $period, true);
$vendors = [];
$sql = mysqli_query($mysqli, "
SELECT expense_vendor_id AS vendor_id, vendor_name, vendor_client_id, COUNT(expense_id) AS n, SUM(expense_amount) AS v, MAX(expense_date) AS last_paid
FROM expenses
LEFT JOIN vendors ON expense_vendor_id = vendor_id
WHERE expense_vendor_id > 0 AND $range
GROUP BY expense_vendor_id, vendor_name, vendor_client_id
ORDER BY v DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$vendors[intval($row['vendor_id'])] = [
'vendor_id' => intval($row['vendor_id']),
'vendor' => $row['vendor_name'] ?? 'Deleted vendor',
'exists' => $row['vendor_name'] !== null,
'count' => intval($row['n']),
'total' => floatval($row['v']),
'last' => $row['last_paid'],
'prev' => 0.0,
'category' => '',
'recurring' => 0.0,
];
}
$sql_payment_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(payment_date) AS payment_year FROM payments
UNION SELECT DISTINCT YEAR(revenue_date) AS payment_year FROM revenues
ORDER BY payment_year DESC"
);
$sql = mysqli_query($mysqli, "SELECT expense_vendor_id AS vendor_id, SUM(expense_amount) AS v FROM expenses WHERE expense_vendor_id > 0 AND $prev_range GROUP BY expense_vendor_id");
$prev_total = 0.0;
while ($row = mysqli_fetch_assoc($sql)) {
$prev_total += floatval($row['v']);
if (isset($vendors[intval($row['vendor_id'])])) {
$vendors[intval($row['vendor_id'])]['prev'] = floatval($row['v']);
}
}
$year_condition = ($year == 'all') ? "" : "AND YEAR(expense_date) = $year";
// The category most of each vendor's money went under
$sql = mysqli_query($mysqli, "SELECT expense_vendor_id AS vendor_id, category_name, SUM(expense_amount) AS v
FROM expenses LEFT JOIN categories ON expense_category_id = category_id
WHERE expense_vendor_id > 0 AND $range
GROUP BY expense_vendor_id, category_name ORDER BY v DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$id = intval($row['vendor_id']);
if (isset($vendors[$id]) && $vendors[$id]['category'] === '') {
$vendors[$id]['category'] = $row['category_name'] ?? '';
}
}
$sql_vendor_expenses = mysqli_query($mysqli, "
SELECT
vendors.*,
SUM(expenses.expense_amount) AS amount_paid
FROM
vendors
LEFT JOIN
expenses ON vendors.vendor_id = expenses.expense_vendor_id $year_condition
GROUP BY
vendors.vendor_id
HAVING
amount_paid > 599
ORDER BY
amount_paid DESC
");
// What each is owed every month from now on
$sql = mysqli_query($mysqli, "SELECT recurring_expense_vendor_id AS vendor_id,
SUM(CASE WHEN recurring_expense_frequency = 2 THEN recurring_expense_amount / 12 ELSE recurring_expense_amount END) AS v
FROM recurring_expenses
WHERE recurring_expense_status = 1 AND recurring_expense_archived_at IS NULL AND recurring_expense_vendor_id > 0
GROUP BY recurring_expense_vendor_id");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($vendors[intval($row['vendor_id'])])) {
$vendors[intval($row['vendor_id'])]['recurring'] = floatval($row['v']);
}
}
$total = array_sum(array_column($vendors, 'total'));
$count_1099 = count(array_filter($vendors, function ($v) {
return $v['total'] >= 600;
}));
if ($only_1099) {
$vendors = array_filter($vendors, function ($v) {
return $v['total'] >= 600;
});
}
foreach ($vendors as &$vendor) {
$vendor['share'] = reportShare($vendor['total'], $total, 1);
$vendor['change'] = reportChange($vendor['total'], $vendor['prev']);
}
unset($vendor);
$columns = [
'vendor' => ['label' => 'Vendor', 'html' => function ($row) {
$name = escapeHtml($row['vendor']);
return $row['exists'] ? '<a class="fw-semibold text-body" href="/agent/vendor.php?vendor_id=' . $row['vendor_id'] . '">' . $name . '</a>' : '<span class="text-body-secondary fst-italic">' . $name . '</span>';
}],
'category' => ['label' => 'Mostly', 'class' => 'small text-body-secondary'],
'count' => ['label' => 'Expenses', 'type' => 'count'],
'total' => ['label' => 'Paid', 'type' => 'money', 'class' => 'fw-semibold', 'html' => function ($row) use ($period) {
return '<a class="itflow-report-amount" href="/agent/expenses.php?vendor=' . $row['vendor_id'] . '&canned_date=custom&dtf=' . $period['start'] . '&dtt=' . $period['end'] . '">' . reportMoney($row['total']) . '</a>';
}],
'share' => ['label' => 'Share', 'type' => 'percent', 'html' => function ($row) {
return '<div class="d-flex align-items-center justify-content-end gap-2"><div class="itflow-report-meter d-none d-lg-flex" style="width: 5rem"><span style="width: ' . min(100, floatval($row['share'])) . '%"></span></div>'
. '<span class="small text-body-secondary">' . reportPercent($row['share']) . '</span></div>';
}],
'prev' => ['label' => 'Period before', 'type' => 'money', 'class' => 'text-body-secondary'],
'change' => ['label' => 'Change', 'type' => 'percent', 'csv' => false, 'html' => function ($row) {
return $row['change'] === null ? '<span class="itflow-report-zero">New</span>' : '<span class="small">' . reportChangeHtml($row['total'], $row['prev'], 'down') . '</span>';
}],
'recurring' => ['label' => 'Recurring / month', 'type' => 'money', 'title' => 'Active recurring expenses to this vendor, per month', 'html' => function ($row) {
return $row['recurring'] > 0 ? reportMoney($row['recurring']) : '<span class="itflow-report-zero">–</span>';
}],
'last' => ['label' => 'Last paid', 'type' => 'date', 'class' => 'text-nowrap'],
];
if (reportExporting()) {
reportCsv('Spend by Vendor ' . $period['start'] . ' to ' . $period['end'], $columns, array_values($vendors), ['vendor' => 'Total', 'total' => $only_1099 ? array_sum(array_column($vendors, 'total')) : $total]);
}
require_once "includes/inc_report_layout.php";
$top = array_slice(array_values($vendors), 0, 12);
$biggest = $top[0] ?? null;
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-building me-2"></i>Expense By Vendor <small>(With expense amounts of 600 or more)</small></h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('expense_by_vendor', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(expense_date) AS y FROM expenses WHERE expense_vendor_id > 0"),
'controls' => reportSwitchControl('over600', $only_1099, 'Only vendors paid 600 or more'),
]); ?>
<?= reportStats([
['label' => 'Paid to vendors', 'value' => reportMoney($total), 'sub' => reportChangeHtml($total, $prev_total, 'down', $period['compare']),
'url' => '/agent/expenses.php?canned_date=custom&dtf=' . $period['start'] . '&dtt=' . $period['end']],
['label' => 'Vendors paid', 'value' => reportCount(count($vendors)), 'sub' => '<span class="text-body-tertiary">' . ($only_1099 ? 'Paid 600 or more' : 'In the period') . '</span>'],
['label' => 'Biggest', 'value' => $biggest ? $biggest['vendor'] : '-', 'sub' => $biggest ? reportMoney($biggest['total']) . ' <span class="text-body-tertiary">· ' . reportPercent($biggest['share']) . ' of spending</span>' : ''],
['label' => 'Paid 600 or more', 'value' => reportCount($count_1099), 'sub' => '<span class="text-body-tertiary">Vendors to check for a 1099</span>', 'url' => reportUrl(['over600' => 1])],
]) ?>
<?php if ($top) { ?>
<?= reportSectionOpen('Top vendors', escapeHtml($period['range'])) ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_map(function ($v) { return $v['vendor']; }, $top),
'series' => [['label' => 'Paid', 'data' => array_map(function ($v) { return round($v['total'], 2); }, $top), 'tone' => 'accent']],
'format' => 'money',
'legend' => false,
], '', 'What was paid to each of the biggest vendors') ?>
</div>
</div>
<?php } ?>
<?= reportSectionOpen($only_1099 ? 'Vendors paid 600 or more' : 'Every vendor paid', reportCount(count($vendors)) . ' vendor' . (count($vendors) === 1 ? '' : 's')) ?>
<?= reportTable($columns, array_values($vendors), [
'empty' => 'No vendor was paid in this period.',
'totals' => ['vendor' => 'Total', 'count' => array_sum(array_column($vendors, 'count')), 'total' => array_sum(array_column($vendors, 'total')),
'prev' => array_sum(array_column($vendors, 'prev')), 'recurring' => array_sum(array_column($vendors, 'recurring'))],
]) ?>
<div class="card-footer small text-body-secondary">
Expenses with a vendor, by the date they were paid. "Period before" is <?= escapeHtml($period['compare']) ?>.
<?php if ($only_1099) { ?>A 1099 is filed per calendar year - pick This year, Last year or a year above, and check with your accountant which vendors need one.<?php } ?>
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<option value="all" <?php if ($year == 'all') { ?> selected <?php } ?> >All Years</option>
<?php
while ($row = mysqli_fetch_assoc($sql_payment_years)) {
$payment_year = intval($row['payment_year']);
?>
<option <?php if ($year == $payment_year) { ?> selected <?php } ?> > <?= $payment_year ?></option>
<?php
}
?>
</select>
</form>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Vendor</th>
<th class="text-end">Paid</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_vendor_expenses)) {
$vendor_id = intval($row['vendor_id']);
$vendor_name = escapeHtml($row['vendor_name']);
$amount_paid = floatval($row['amount_paid']); ?>
<tr>
<td><?= $vendor_name ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $amount_paid, $session_company_currency) ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
<?php require_once "../../includes/footer.php";
?>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,194 +1,92 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Expenses - a year of spending by expense category and month: expenses with
* a vendor, the same as the Expenses list and the dashboard (an expense with
* no vendor is the out side of a transfer between accounts). Compared with
* last year to the same date; every amount opens the expenses behind it.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('expense_summary');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
[$year, $years] = reportYear("SELECT YEAR(expense_date) AS y FROM expenses WHERE expense_vendor_id > 0");
$current_year = $year === intval(date('Y'));
$from = "$year-01-01";
$to = $current_year ? date('Y-m-d') : "$year-12-31";
$prev_from = ($year - 1) . '-01-01';
$prev_to = $current_year ? dashboardShiftMonths(date('Y-m-d'), -12) : ($year - 1) . '-12-31';
$compare = $current_year ? 'the same time last year' : (string) ($year - 1);
$grid = reportExpensesByCategory($from, $to);
$categories = reportCategoriesWithAmounts(reportCategoryRows('Expense', $grid), $grid);
$totals = reportGridTotals($grid);
$prev_total = reportGridTotals(reportExpensesByCategory($prev_from, $prev_to))['total'];
if (reportExporting()) {
reportCategoryYearCsv($categories, $grid, $year, "Expenses $year", 'Total expenses');
}
$sql_expense_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(expense_date) AS expense_year FROM expenses WHERE expense_category_id > 0 ORDER BY expense_year DESC");
$months_elapsed = reportMonthsElapsed($year);
$average = $months_elapsed ? $totals['total'] / $months_elapsed : 0;
$sql_categories = mysqli_query($mysqli, "SELECT category_id, category_name FROM categories WHERE category_type = 'Expense' ORDER BY category_name ASC");
$biggest = null;
foreach ($categories as $cat => $category) {
if (!$biggest || $grid[$cat]['total'] > $grid[$biggest]['total']) {
$biggest = $cat;
}
}
// For chart Y-axis max
$largest_expense_month = 0;
// What is already committed every month
$recurring = dashboardSum("SELECT SUM(recurring_expense_amount) FROM recurring_expenses WHERE recurring_expense_status = 1 AND recurring_expense_archived_at IS NULL AND recurring_expense_vendor_id > 0 AND recurring_expense_frequency = 1")
+ dashboardSum("SELECT SUM(recurring_expense_amount) FROM recurring_expenses WHERE recurring_expense_status = 1 AND recurring_expense_archived_at IS NULL AND recurring_expense_vendor_id > 0 AND recurring_expense_frequency = 2") / 12;
$prev_full = reportGridTotals(reportExpensesByCategory(($year - 1) . '-01-01', ($year - 1) . '-12-31'))['months'];
require_once "includes/inc_report_layout.php";
?>
<!-- Responsive chart helpers -->
<style>
.chart-h-320 { position: relative; height: 320px; }
@media (max-width: 576px) { .chart-h-320 { height: 260px; } }
</style>
<div class="itflow-report">
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-coins me-2"></i>Expense Summary</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<?php reportHeader('expense_summary', [
'year' => [$year, $years],
'subtitle' => $current_year ? "$year to date" : (string) $year,
]); ?>
<?= reportStats([
['label' => 'Spending', 'value' => reportMoney($totals['total']), 'sub' => reportChangeHtml($totals['total'], $prev_total, 'down', $compare),
'url' => "/agent/expenses.php?canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Monthly average', 'value' => reportMoney($average), 'sub' => escapeHtml("Over $months_elapsed month" . ($months_elapsed === 1 ? '' : 's'))],
['label' => 'Biggest category', 'value' => $biggest !== null ? $categories[$biggest]['category_name'] : '-',
'sub' => $biggest !== null ? reportMoney($grid[$biggest]['total']) . ' <span class="text-body-tertiary">· ' . reportPercent(reportShare($grid[$biggest]['total'], $totals['total'])) . '</span>' : ''],
['label' => 'Recurring', 'value' => reportMoney($recurring), 'sub' => '<span class="text-body-tertiary">Per month, committed now</span>', 'url' => '/agent/recurring_expenses.php'],
]) ?>
<?= reportSectionOpen('Spending by month', escapeHtml("$year, with " . ($year - 1) . ' as a line')) ?>
<div class="card-body">
<?php
$series = reportCategoryChartSeries($categories, $grid, $current_year ? intval(date('n')) : 12);
$series[] = ['label' => (string) ($year - 1), 'data' => array_map(function ($v) { return round($v, 2); }, array_values($prev_full)), 'tone' => 'muted', 'type' => 'line', 'dashed' => true];
echo reportChart([
'type' => 'bar',
'labels' => array_map(function ($m) { return date('M', mktime(0, 0, 0, $m, 1)); }, range(1, 12)),
'series' => $series,
'stacked' => true,
'format' => 'money',
], 'lg', 'Spending per month by category, with last year as a line');
?>
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php while ($row = mysqli_fetch_assoc($sql_expense_years)) {
$expense_year = intval($row['expense_year']); ?>
<option <?php if ($year == $expense_year) { ?> selected <?php } ?>><?= $expense_year ?></option>
<?php } ?>
</select>
</form>
<div class="chart-h-320 mb-3">
<canvas id="cashFlow"></canvas>
</div>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead class="text-dark">
<tr>
<th>Category</th>
<th class="text-end">January</th>
<th class="text-end">February</th>
<th class="text-end">March</th>
<th class="text-end">April</th>
<th class="text-end">May</th>
<th class="text-end">June</th>
<th class="text-end">July</th>
<th class="text-end">August</th>
<th class="text-end">September</th>
<th class="text-end">October</th>
<th class="text-end">November</th>
<th class="text-end">December</th>
<th class="text-end">Total</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($sql_categories)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']); ?>
<tr>
<td><?= $category_name ?></td>
<?php
$total_expense_for_all_months = 0;
for ($month = 1; $month <= 12; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_amount_for_month FROM expenses WHERE expense_category_id = $category_id AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month");
$rowm = mysqli_fetch_assoc($sql_expenses);
$expense_amount_for_month = floatval($rowm['expense_amount_for_month']);
$total_expense_for_all_months += $expense_amount_for_month;
?>
<td class="text-end">
<a class="text-dark" href="expenses.php?q=<?= $category_name ?>&dtf=<?= "$year-$month" ?>-01&dtt=<?= "$year-$month" ?>-31">
<?= numfmt_format_currency($currency_format, $expense_amount_for_month, $session_company_currency) ?>
</a>
</td>
<?php } ?>
<th class="text-end">
<a class="text-dark" href="expenses.php?q=<?= $category_name ?>&dtf=<?= $year ?>-01-01&dtt=<?= $year ?>-12-31">
<?= numfmt_format_currency($currency_format, $total_expense_for_all_months, $session_company_currency) ?>
</a>
</th>
</tr>
<?php } ?>
<tr>
<th>Total</th>
<?php
$grand_total_all_months = 0;
for ($month = 1; $month <= 12; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_total_amount_for_month FROM expenses WHERE YEAR(expense_date) = $year AND MONTH(expense_date) = $month AND expense_vendor_id > 0");
$rowt = mysqli_fetch_assoc($sql_expenses);
$expense_total_amount_for_month = floatval($rowt['expense_total_amount_for_month']);
$grand_total_all_months += $expense_total_amount_for_month;
?>
<th class="text-end">
<a class="text-dark" href="expenses.php?dtf=<?= "$year-$month" ?>-01&dtt=<?= "$year-$month" ?>-31">
<?= numfmt_format_currency($currency_format, $expense_total_amount_for_month, $session_company_currency) ?>
</a>
</th>
<?php } ?>
<th class="text-end">
<a class="text-dark" href="expenses.php?dtf=<?= $year ?>-01-01&dtt=<?= $year ?>-12-31">
<?= numfmt_format_currency($currency_format, $grand_total_all_months, $session_company_currency) ?>
</a>
</th>
</tr>
</tbody>
</table>
<?= reportSectionOpen('By category', 'Click an amount to see the expenses behind it', 'itflow-report-long') ?>
<?= reportCategoryYearTable($categories, $grid, $year, 'expenses.php', 'Total expenses') ?>
<div class="card-footer small text-body-secondary">
Expenses with a vendor, by the date they were paid. Transfers between your own accounts are left out.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script>
// Bootstrap-like defaults for Chart.js v4
var itflowChart = itflowChartDefaults();
// EXPENSES LINE CHART
(function () {
var ctx = document.getElementById("cashFlow");
if (!ctx) return;
var dataPoints = [
<?php
// Build series and track the largest month for axis max
for ($month = 1; $month <= 12; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_amount_for_month FROM expenses WHERE YEAR(expense_date) = $year AND MONTH(expense_date) = $month AND expense_vendor_id > 0");
$rowm = mysqli_fetch_assoc($sql_expenses);
$expenses_for_month = floatval($rowm['expense_amount_for_month']);
if ($expenses_for_month > 0 && $expenses_for_month > $largest_expense_month) {
$largest_expense_month = $expenses_for_month;
}
echo "$expenses_for_month,";
}
?>
];
new Chart(ctx, {
type: 'line',
data: {
labels: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
datasets: [{
label: "Expense",
tension: 0.3, // v4 name (v2: lineTension)
fill: false,
borderColor: "#dc3545",
pointBackgroundColor: "#dc3545",
pointBorderColor: "#dc3545",
pointHoverRadius: 5,
pointHoverBackgroundColor: "#dc3545",
pointBorderWidth: 2,
data: dataPoints
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
grid: { display: false },
ticks: { maxTicksLimit: 12 }
},
y: {
beginAtZero: true,
min: 0,
max: <?php
$max = max(1000, $largest_expense_month);
echo roundUpToNearestMultiple($max);
?>,
ticks: { maxTicksLimit: 5 },
grid: { color: itflowChart.grid }
}
},
plugins: {
legend: { display: false }
}
}
});
})();
</script>
<script src="/js/reports.js"></script>

View File

@@ -1,16 +1,14 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/check_login.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/page_title.php';
// Reporting Perms
enforceUserPermission('module_reporting');
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/top_nav.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/agent/reports/includes/reports_side_nav.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/inc_wrapper.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/inc_alert_feedback.php';
/*
* The old single include for a report page - signed in, allowed to use
* reports, and the page drawn - kept for custom report pages that still use
* it. The pages here use inc_report.php and inc_report_layout.php, so they
* can send a CSV before anything is drawn.
*/
require_once __DIR__ . '/inc_report.php';
require_once __DIR__ . '/inc_report_layout.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/filter_header.php';
// Set variable default values

View File

@@ -0,0 +1,16 @@
<?php
/*
* A report page's start, before anything is drawn: signed in, and allowed to
* use reports at all. The page then checks its own report (reportEnforce()),
* works out its numbers, sends a CSV if one was asked for, and only then
* draws the page with inc_report_layout.php - so an export is never preceded
* by HTML.
*/
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/check_login.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/page_title.php';
enforceUserPermission('module_reporting');

View File

@@ -0,0 +1,13 @@
<?php
/*
* The page around a report - the top bar, the Reports menu and the content
* wrapper. Comes after inc_report.php and after the page has had its chance
* to send a CSV instead.
*/
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/top_nav.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/agent/reports/includes/reports_side_nav.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/inc_wrapper.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/inc_alert_feedback.php';

View File

@@ -1,3 +1,12 @@
<?php
/*
* The Reports menu - drawn from reportCatalog() (functions/reports.php), so it
* lists exactly the reports this user may open, in the same groups as the
* Reports home page. Custom links placed in Reports come last.
*/
$reports_menu = reportCatalogForUser();
$reports_current = basename($_SERVER['PHP_SELF'], '.php');
?>
<!-- Main Sidebar Container -->
<aside class="app-sidebar shadow d-print-none" data-bs-theme="dark">
@@ -16,127 +25,23 @@
<ul class="nav nav-pills sidebar-menu flex-column mt-2" data-lte-toggle="treeview" data-accordion="false">
<?php if ($config_module_enable_accounting == 1 && lookupUserPermission("module_financial") >= 1) { ?>
<li class="nav-header">INCOME</li>
<li class="nav-item">
<a href="/agent/reports/income_summary.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "income_summary.php") { echo "active"; } ?>">
<i class="fas fa-hand-holding-usd nav-icon"></i>
<p>Income</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/income_by_client.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "income_by_client.php") { echo "active"; } ?>">
<i class="far fa-user nav-icon"></i>
<p>Income by Client</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/recurring_by_client.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "recurring_by_client.php") { echo "active"; } ?>">
<i class="fa fa-sync nav-icon"></i>
<p>Recurring Income by Client</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/outstanding_balances.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "outstanding_balances.php") { echo "active"; } ?>">
<i class="fa fa-exclamation-triangle nav-icon"></i>
<p>Outstanding Balances</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/index.php" class="nav-link <?php if ($reports_current === 'index') { echo "active"; } ?>">
<i class="nav-icon fas fa-th-large"></i>
<p>All Reports</p>
</a>
</li>
<li class="nav-header">EXPENSES</li>
<li class="nav-item">
<a href="/agent/reports/expense_summary.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "expense_summary.php") { echo "active"; } ?>">
<i class="fas fa-shopping-cart nav-icon"></i>
<p>Expense</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/expense_by_vendor.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "expense_by_vendor.php") { echo "active"; } ?>">
<i class="far fa-building nav-icon"></i>
<p>Expense by Vendor</p>
</a>
</li>
<li class="nav-header">STATEMENTS</li>
<li class="nav-item">
<a href="/agent/reports/tax_summary.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "tax_summary.php") { echo "active"; } ?>">
<i class="fas fa-percent nav-icon"></i>
<p>Tax Summary</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/profit_loss.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "profit_loss.php") { echo "active"; } ?>">
<i class="fas fa-file-invoice-dollar nav-icon"></i>
<p>Profit & Loss</p>
</a>
</li>
<?php } // End financial reports IF statement ?>
<?php if (($config_module_enable_accounting == 1 && lookupUserPermission("module_financial") >= 1) || ($config_module_enable_ticketing && lookupUserPermission("module_support") >= 1)) { ?>
<li class="nav-header">TIME</li>
<?php } ?>
<?php if ($config_module_enable_accounting == 1 && lookupUserPermission("module_financial") >= 1) { ?>
<li class="nav-item">
<a href="/agent/reports/tickets_unbilled.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "tickets_unbilled.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-hourglass-half"></i>
<p>Unbilled Tickets</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/client_ticket_time_detail.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "client_ticket_time_detail.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-stopwatch"></i>
<p>Time Detail by Client</p>
</a>
</li>
<?php } ?>
<?php if ($config_module_enable_ticketing && lookupUserPermission("module_support") >= 1) { ?>
<li class="nav-item">
<a href="/agent/reports/time_by_tech.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "time_by_tech.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-user-clock"></i>
<p>Time by Technician</p>
</a>
</li>
<?php } ?>
<?php if (($config_module_enable_ticketing && lookupUserPermission("module_support") >= 1) || lookupUserPermission("module_credential") >= 1) { ?>
<li class="nav-header">TECHNICAL</li>
<?php } ?>
<?php if ($config_module_enable_ticketing && lookupUserPermission("module_support") >= 1) { ?>
<li class="nav-item">
<a href="/agent/reports/ticket_summary.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "ticket_summary.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-life-ring"></i>
<p>Tickets</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/ticket_by_client.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "ticket_by_client.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-life-ring"></i>
<p>Tickets by Client</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/sla_summary.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "sla_summary.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-stopwatch"></i>
<p>SLA Summary</p>
</a>
</li>
<li class="nav-item">
<a href="/agent/reports/sla_by_client.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "sla_by_client.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-stopwatch"></i>
<p>SLA by Client</p>
</a>
</li>
<?php } ?>
<?php if (lookupUserPermission("module_credential") >= 1) { ?>
<li class="nav-item">
<a href="/agent/reports/credential_rotation.php" class="nav-link <?php if (basename($_SERVER["PHP_SELF"]) == "credential_rotation.php") { echo "active"; } ?>">
<i class="nav-icon fas fa-key"></i>
<p>Credential Rotation</p>
</a>
</li>
<?php foreach ($reports_menu as $group) { ?>
<li class="nav-header"><?= escapeHtml(strtoupper($group['label'])) ?></li>
<?php foreach ($group['reports'] as $menu_key => $menu_report) { ?>
<li class="nav-item">
<a href="/agent/reports/<?= $menu_key ?>.php" class="nav-link <?php if ($reports_current === $menu_key) { echo "active"; } ?>">
<i class="nav-icon fas <?= escapeHtml($menu_report['icon']) ?>"></i>
<p><?= escapeHtml($menu_report['title']) ?></p>
</a>
</li>
<?php } ?>
<?php } ?>
<?php
@@ -145,6 +50,10 @@
ORDER BY custom_link_order ASC, custom_link_name ASC"
);
if (mysqli_num_rows($sql_custom_links)) { ?>
<li class="nav-header">MORE</li>
<?php }
while ($row = mysqli_fetch_assoc($sql_custom_links)) {
$custom_link_name = escapeHtml($row['custom_link_name']);
$custom_link_uri = escapeUrl($row['custom_link_uri']);
@@ -173,10 +82,6 @@
</nav>
<!-- /.sidebar-menu -->
<div class="sidebar-custom mb-3">
</div>
</div>
<!-- /.sidebar -->
</aside>
</aside>

View File

@@ -1,95 +1,143 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Income by Client - what each client paid in the period (invoice payments,
* and revenue entered against them), the most first, against the period
* before, with their share of the total and what they are on every month in
* recurring invoices. Clients this user may not see are left out.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('income_by_client');
if (isset($_GET['year'])) {
if ($_GET['year'] === 'all') {
$year = 'all';
} else {
$year = intval($_GET['year']);
$period = reportPeriod('this_year');
$only_600 = !empty($_GET['over600']);
$income_sql = function ($range_payment, $range_revenue) {
return "SELECT client_id, client_name, client_abbreviation, SUM(amount) AS v, COUNT(*) AS n, MAX(paid_on) AS last_paid FROM (
SELECT invoice_client_id AS client_id, payment_amount AS amount, payment_date AS paid_on FROM payments
JOIN invoices ON invoice_id = payment_invoice_id
WHERE $range_payment
UNION ALL
SELECT revenue_client_id, revenue_amount, revenue_date FROM revenues
WHERE revenue_client_id > 0 AND " . dashboardRevenueSql() . " AND $range_revenue
) AS income
JOIN clients USING (client_id)
WHERE 1 = 1 " . clientScopeSql('client_id') . "
GROUP BY client_id, client_name, client_abbreviation";
};
$clients = [];
$sql = mysqli_query($mysqli, $income_sql(reportRangeSql('payment_date', $period), reportRangeSql('revenue_date', $period)));
while ($row = mysqli_fetch_assoc($sql)) {
$clients[intval($row['client_id'])] = ['client_id' => intval($row['client_id']), 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation'],
'paid' => floatval($row['v']), 'payments' => intval($row['n']), 'last_paid' => $row['last_paid'], 'prev' => 0.0, 'mrr' => 0.0];
}
$prev_total = 0.0;
$sql = mysqli_query($mysqli, $income_sql(reportRangeSql('payment_date', $period, true), reportRangeSql('revenue_date', $period, true)));
while ($row = mysqli_fetch_assoc($sql)) {
$prev_total += floatval($row['v']);
if (isset($clients[intval($row['client_id'])])) {
$clients[intval($row['client_id'])]['prev'] = floatval($row['v']);
}
}
$sql = mysqli_query($mysqli, "SELECT recurring_invoice_client_id AS client_id,
SUM(CASE WHEN recurring_invoice_frequency = 'year' THEN recurring_invoice_amount / 12 ELSE recurring_invoice_amount END) AS v
FROM recurring_invoices WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL GROUP BY recurring_invoice_client_id");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($clients[intval($row['client_id'])])) {
$clients[intval($row['client_id'])]['mrr'] = floatval($row['v']);
}
} else {
$year = date('Y');
}
$sql_payment_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(payment_date) AS payment_year FROM payments
UNION SELECT DISTINCT YEAR(revenue_date) AS payment_year FROM revenues
ORDER BY payment_year DESC"
);
$total = array_sum(array_column($clients, 'paid'));
if ($only_600) {
$clients = array_filter($clients, function ($c) { return $c['paid'] >= 600; });
}
uasort($clients, function ($a, $b) { return $b['paid'] <=> $a['paid']; });
foreach ($clients as &$row) {
$row['share'] = reportShare($row['paid'], $total, 1);
$row['change'] = reportChange($row['paid'], $row['prev']);
}
unset($row);
$clients = array_values($clients);
$columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr']);
}],
'paid' => ['label' => 'Paid', 'type' => 'money', 'class' => 'fw-semibold', 'html' => function ($row) use ($period) {
return '<a class="itflow-report-amount" href="/agent/income.php?client_id=' . $row['client_id'] . '&canned_date=custom&dtf=' . $period['start'] . '&dtt=' . $period['end'] . '">' . reportMoney($row['paid']) . '</a>';
}],
'share' => ['label' => 'Share', 'type' => 'percent', 'html' => function ($row) {
return '<div class="d-flex align-items-center justify-content-end gap-2"><div class="itflow-report-meter d-none d-lg-flex" style="width: 5rem"><span style="width: ' . min(100, floatval($row['share'])) . '%"></span></div>'
. '<span class="small text-body-secondary">' . reportPercent($row['share']) . '</span></div>';
}],
'prev' => ['label' => 'Period before', 'type' => 'money', 'class' => 'text-body-secondary'],
'change' => ['label' => 'Change', 'type' => 'percent', 'csv' => false, 'html' => function ($row) {
return $row['change'] === null ? '<span class="itflow-report-zero">New</span>' : '<span class="small">' . reportChangeHtml($row['paid'], $row['prev'], 'up') . '</span>';
}],
'payments' => ['label' => 'Payments', 'type' => 'count'],
'mrr' => ['label' => 'Recurring / month', 'type' => 'money', 'html' => function ($row) {
return $row['mrr'] > 0 ? reportMoney($row['mrr']) : '<span class="itflow-report-zero">–</span>';
}],
'last_paid' => ['label' => 'Last paid', 'type' => 'date', 'class' => 'text-nowrap'],
];
$totals = ['client' => 'Total', 'paid' => array_sum(array_column($clients, 'paid')), 'prev' => array_sum(array_column($clients, 'prev')),
'payments' => array_sum(array_column($clients, 'payments')), 'mrr' => array_sum(array_column($clients, 'mrr'))];
if (reportExporting()) {
reportCsv('Income by Client ' . $period['start'] . ' to ' . $period['end'], $columns, $clients, $totals);
}
require_once "includes/inc_report_layout.php";
$top = array_slice($clients, 0, 12);
$top_five_share = reportShare(array_sum(array_column(array_slice($clients, 0, 5), 'paid')), $total);
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-users me-2"></i>Income By Client <small>(With payments of 600 or more)</small></h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('income_by_client', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(payment_date) AS y FROM payments"),
'controls' => reportSwitchControl('over600', $only_600, 'Only clients who paid 600 or more'),
]); ?>
<?= reportStats([
['label' => 'Paid by clients', 'value' => reportMoney($total), 'sub' => reportChangeHtml($total, $prev_total, 'up', $period['compare'])],
['label' => 'Clients who paid', 'value' => reportCount(count($clients)), 'sub' => '<span class="text-body-tertiary">' . ($only_600 ? 'Paid 600 or more' : 'In the period') . '</span>'],
['label' => 'Average per client', 'value' => count($clients) ? reportMoney(array_sum(array_column($clients, 'paid')) / count($clients)) : '-', 'sub' => '<span class="text-body-tertiary">Over the period</span>'],
['label' => 'Top five', 'value' => reportPercent($top_five_share), 'sub' => '<span class="text-body-tertiary">of income - how much rides on a few clients</span>',
'tone' => $top_five_share !== null && $top_five_share >= 60 ? 'warning' : ''],
]) ?>
<?php if ($top) { ?>
<?= reportSectionOpen('Who paid the most', escapeHtml($period['range'])) ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_map(function ($c) { return $c['client']; }, $top),
'series' => [
['label' => 'This period', 'data' => array_map(function ($c) { return round($c['paid'], 2); }, $top), 'tone' => 'accent'],
['label' => 'Period before', 'data' => array_map(function ($c) { return round($c['prev'], 2); }, $top), 'tone' => 'faint'],
],
'format' => 'money',
], '', 'What each of the biggest clients paid, this period and the period before') ?>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By client', 'Most paid first') ?>
<?= reportTable($columns, $clients, ['empty' => 'No client paid anything in this period.', 'totals' => $totals]) ?>
<div class="card-footer small text-body-secondary">
Invoice payments by the date they arrived, plus revenue entered against the client. "Period before" is <?= escapeHtml($period['compare']) ?>.
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<option value="all" <?php if ($year == 'all') { ?> selected <?php } ?> >All Years</option>
<?php
while ($row = mysqli_fetch_assoc($sql_payment_years)) {
$payment_year = intval($row['payment_year']);
?>
<option <?php if ($year == $payment_year) { ?> selected <?php } ?> > <?= $payment_year ?></option>
<?php } ?>
</select>
</form>
<?php
$sql_clients = "SELECT c.client_id, c.client_name, SUM(p.payment_amount) AS amount_paid
FROM clients AS c
JOIN invoices AS i ON c.client_id = i.invoice_client_id
JOIN payments AS p ON i.invoice_id = p.payment_invoice_id
WHERE 1=1" . clientScopeSql('c.client_id');
if ($year != 'all') {
$sql_clients .= " AND YEAR(p.payment_date) = $year";
}
$sql_clients .= " GROUP BY c.client_id
HAVING amount_paid > 599
ORDER BY amount_paid DESC";
$sql_clients = mysqli_query($mysqli, $sql_clients);
?>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Paid</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_clients)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$amount_paid = floatval($row['amount_paid']);
?>
<tr>
<td><a href="../../agent/client_overview.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $amount_paid, $session_company_currency) ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
<?php
require_once "../../includes/footer.php";
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,200 +1,97 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Income - a year of money received, by income category and month. Invoice
* payments are filed under the category of the invoice they paid; revenues
* entered on their own count when they have a category and are not one side
* of a transfer between accounts - the same income the dashboard and the
* Profit & Loss count. Compared with last year to the same date.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('income_summary');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
[$year, $years] = reportYear("SELECT YEAR(payment_date) AS y FROM payments UNION SELECT YEAR(revenue_date) FROM revenues");
$current_year = $year === intval(date('Y'));
$from = "$year-01-01";
$to = $current_year ? date('Y-m-d') : "$year-12-31";
$prev_from = ($year - 1) . '-01-01';
$prev_to = $current_year ? dashboardShiftMonths(date('Y-m-d'), -12) : ($year - 1) . '-12-31';
$compare = $current_year ? 'the same time last year' : (string) ($year - 1);
$grid = reportIncomeByCategory($from, $to);
$categories = reportCategoryRows('Income', $grid);
$categories = reportCategoriesWithAmounts($categories, $grid);
$totals = reportGridTotals($grid);
$prev_grid = reportIncomeByCategory($prev_from, $prev_to);
$prev_total = reportGridTotals($prev_grid)['total'];
if (reportExporting()) {
reportCategoryYearCsv($categories, $grid, $year, "Income $year", 'Total income');
}
$sql_payment_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(payment_date) AS payment_year FROM payments
UNION SELECT DISTINCT YEAR(revenue_date) AS payment_year FROM revenues
ORDER BY payment_year DESC");
// Where it came from: invoices paid, or revenue entered on its own
$from_invoices = dashboardSum("SELECT SUM(payment_amount) FROM payments WHERE " . reportRangeSql('payment_date', ['start' => $from, 'end' => $to]));
$from_other = $totals['total'] - $from_invoices;
$sql_categories = mysqli_query($mysqli, "SELECT category_id, category_name FROM categories WHERE category_type = 'Income' ORDER BY category_name ASC");
$months_elapsed = reportMonthsElapsed($year);
$average = $months_elapsed ? $totals['total'] / $months_elapsed : 0;
$best_month = 0;
foreach ($totals['months'] as $m => $v) {
if ($v > ($totals['months'][$best_month] ?? 0)) {
$best_month = $m;
}
}
// Used for chart y-axis max calculation
$largest_income_month = 0;
// Last year month by month, as a line behind this year's bars
$prev_full = reportGridTotals(reportIncomeByCategory(($year - 1) . '-01-01', ($year - 1) . '-12-31'))['months'];
require_once "includes/inc_report_layout.php";
?>
<!-- Responsive chart helpers -->
<style>
.chart-h-320 { position: relative; height: 320px; }
@media (max-width: 576px) { .chart-h-320 { height: 260px; } }
</style>
<div class="itflow-report">
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-coins me-2"></i>Income Summary</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<?php reportHeader('income_summary', [
'year' => [$year, $years],
'subtitle' => $current_year ? "$year to date" : (string) $year,
]); ?>
<?= reportStats([
['label' => 'Income', 'value' => reportMoney($totals['total']), 'sub' => reportChangeHtml($totals['total'], $prev_total, 'up', $compare),
'url' => "/agent/income.php?canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Invoice payments', 'value' => reportMoney($from_invoices), 'sub' => escapeHtml(reportPercent(reportShare($from_invoices, $totals['total']))) . ' <span class="text-body-tertiary">of income</span>',
'url' => "/agent/income.php?type=payment&canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Other revenue', 'value' => reportMoney($from_other), 'sub' => escapeHtml(reportPercent(reportShare($from_other, $totals['total']))) . ' <span class="text-body-tertiary">of income</span>',
'url' => "/agent/income.php?type=revenue&canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Monthly average', 'value' => reportMoney($average), 'sub' => $best_month ? 'Best month <span class="text-body">' . date('F', mktime(0, 0, 0, $best_month, 1)) . '</span>' : ''],
]) ?>
<?= reportSectionOpen('Income by month', escapeHtml("$year, with " . ($year - 1) . ' as a line')) ?>
<div class="card-body">
<?php
$series = reportCategoryChartSeries($categories, $grid, $current_year ? intval(date('n')) : 12);
$series[] = ['label' => (string) ($year - 1), 'data' => array_map(function ($v) { return round($v, 2); }, array_values($prev_full)), 'tone' => 'muted', 'type' => 'line', 'dashed' => true];
echo reportChart([
'type' => 'bar',
'labels' => array_map(function ($m) { return date('M', mktime(0, 0, 0, $m, 1)); }, range(1, 12)),
'series' => $series,
'stacked' => true,
'format' => 'money',
], 'lg', 'Income per month by category, with last year as a line');
?>
</div>
</div>
<div class="card-body p-0">
<form class="p-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php while ($row = mysqli_fetch_assoc($sql_payment_years)) {
$payment_year = intval($row['payment_year']); ?>
<option <?php if ($year == $payment_year) { ?> selected <?php } ?>><?= $payment_year ?></option>
<?php } ?>
</select>
</form>
<div class="px-3 pb-3">
<div class="chart-h-320">
<canvas id="cashFlow"></canvas>
</div>
</div>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Category</th>
<th class="text-end">January</th>
<th class="text-end">February</th>
<th class="text-end">March</th>
<th class="text-end">April</th>
<th class="text-end">May</th>
<th class="text-end">June</th>
<th class="text-end">July</th>
<th class="text-end">August</th>
<th class="text-end">September</th>
<th class="text-end">October</th>
<th class="text-end">November</th>
<th class="text-end">December</th>
<th class="text-end">Total</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($sql_categories)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']); ?>
<tr>
<td><?= $category_name ?></td>
<?php
$total_payment_for_all_months = 0;
for ($month = 1; $month <= 12; $month++) {
// Payments to Invoices
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_category_id = $category_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row2 = mysqli_fetch_assoc($sql_payments);
$payment_amount_for_month = floatval($row2['payment_amount_for_month']);
// Revenues
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_amount_for_month FROM revenues WHERE revenue_category_id = $category_id AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row3 = mysqli_fetch_assoc($sql_revenues);
$revenues_amount_for_month = floatval($row3['revenue_amount_for_month']);
$payment_amount_for_month = $payment_amount_for_month + $revenues_amount_for_month;
$total_payment_for_all_months += $payment_amount_for_month;
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $payment_amount_for_month, $session_company_currency) ?></td>
<?php } ?>
<td class="text-end text-bold"><?= numfmt_format_currency($currency_format, $total_payment_for_all_months, $session_company_currency) ?></td>
</tr>
<?php } ?>
<tr>
<th>Total</th>
<?php
$grand_total_all_months = 0;
for ($month = 1; $month <= 12; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_total_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row4 = mysqli_fetch_assoc($sql_payments);
$payment_total_amount_for_month = floatval($row4['payment_total_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_amount_for_month FROM revenues WHERE revenue_category_id > 0 AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row5 = mysqli_fetch_assoc($sql_revenues);
$revenues_total_amount_for_month = floatval($row5['revenue_amount_for_month']);
$payment_total_amount_for_month += $revenues_total_amount_for_month;
$grand_total_all_months += $payment_total_amount_for_month;
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $payment_total_amount_for_month, $session_company_currency) ?></th>
<?php } ?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $grand_total_all_months, $session_company_currency) ?></th>
</tr>
</tbody>
</table>
<?= reportSectionOpen('By category', 'Click an amount to see the payments and revenue behind it', 'itflow-report-long') ?>
<?= reportCategoryYearTable($categories, $grid, $year, 'income.php', 'Total income') ?>
<div class="card-footer small text-body-secondary">
Payments are filed under the category of the invoice they paid. Revenue counts when it has a category; transfers between your own accounts are left out.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script>
// Bootstrap-like defaults for Chart.js v4
var itflowChart = itflowChartDefaults();
// INCOME (Line)
(function () {
var ctx = document.getElementById("cashFlow");
if (!ctx) return;
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Income",
fill: false,
borderColor: "#007bff",
pointBackgroundColor: "#007bff",
pointBorderColor: "#007bff",
pointHoverRadius: 5,
pointHoverBackgroundColor: "#007bff",
pointBorderWidth: 2,
data: [
<?php
// Build series and track the largest month for axis max
for ($month = 1; $month <= 12; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$r1 = mysqli_fetch_assoc($sql_payments);
$payments_for_month = floatval($r1['payment_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_amount_for_month FROM revenues WHERE revenue_category_id > 0 AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$r2 = mysqli_fetch_assoc($sql_revenues);
$revenues_for_month = floatval($r2['revenue_amount_for_month']);
$income_for_month = $payments_for_month + $revenues_for_month;
if ($income_for_month > 0 && $income_for_month > $largest_income_month) {
$largest_income_month = $income_for_month;
}
echo "$income_for_month,";
}
?>
],
}],
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
grid: { display: false },
ticks: { maxTicksLimit: 12 }
},
y: {
beginAtZero: true,
min: 0,
max: <?php
$max = max(1000, $largest_income_month);
echo roundUpToNearestMultiple($max);
?>,
ticks: { maxTicksLimit: 5 },
grid: { color: itflowChart.grid }
}
},
plugins: {
legend: { display: false }
}
}
});
})();
</script>
<script src="/js/reports.js"></script>

View File

@@ -1,20 +1,68 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Reports - every report this user may open, in its group, with a line on
* what each one shows. Drawn from reportCatalog(), the same list as the menu.
*/
require_once "includes/inc_report.php";
require_once "includes/inc_report_layout.php";
$groups = reportCatalogForUser();
$group_tones = ['finance' => 'success', 'billing' => 'primary', 'service' => 'info', 'clients' => 'warning'];
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-coins me-2"></i>Reports</h3>
</div>
<div class="card-body p-0">
<form class="p-3">
<h3>Access different reports using the menu on the left</h3>
<small class="text-muted">In addition to the general reporting permission, you must have read permissions to the reporting area you wish to view (e.g. support/financial).</small>
<div class="itflow-report">
<div class="card">
<div class="card-header bg-dark py-2 d-flex flex-wrap align-items-center gap-2">
<h3 class="card-title mt-2 me-auto"><i class="fas fa-fw fa-chart-bar me-2"></i>Reports</h3>
</div>
<div class="card-body py-3">
<div class="row g-2 align-items-center">
<div class="col-md-6 col-lg-4">
<div class="input-group">
<span class="input-group-text"><i class="fas fa-fw fa-search"></i></span>
<input type="search" class="form-control" placeholder="Find a report..." data-report-find aria-label="Find a report" autofocus>
</div>
</div>
<div class="col">
<span class="small text-body-secondary">Each report shows what your role can see - pick a period, narrow it to one client, print it or export it to CSV.</span>
</div>
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<?php if (!$groups) { ?>
<div class="card"><div class="card-body"><?= reportEmpty('Your role does not include any reports yet - ask an administrator to give it read access to the area you need, such as Support or Financial.', 'fa-lock', 'secondary') ?></div></div>
<?php } ?>
<?php foreach ($groups as $group_key => $group) {
$tone = $group_tones[$group_key] ?? 'secondary'; ?>
<section class="mb-4" data-report-group>
<h2 class="itflow-report-group-title mb-2"><?= escapeHtml($group['label']) ?></h2>
<div class="row g-3">
<?php foreach ($group['reports'] as $key => $report) { ?>
<div class="col-md-6 col-xl-4" data-report-card data-report-text="<?= escapeHtml(strtolower($report['title'] . ' ' . $report['description'] . ' ' . $group['label'])) ?>">
<a class="card h-100 mb-0 itflow-report-card text-decoration-none" href="<?= $key ?>.php">
<div class="card-body d-flex gap-3">
<span class="itflow-report-card-icon bg-<?= $tone ?>-subtle text-<?= $tone ?>-emphasis"><i class="fas fa-fw <?= escapeHtml($report['icon']) ?>"></i></span>
<span class="min-w-0">
<span class="d-block fw-semibold text-body"><?= escapeHtml($report['title']) ?></span>
<span class="d-block small text-body-secondary"><?= escapeHtml($report['description']) ?></span>
</span>
</div>
</a>
</div>
<?php } ?>
</div>
</section>
<?php } ?>
<div class="text-center text-body-secondary py-4" data-report-none hidden>No report matches that.</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

188
agent/reports/mileage.php Normal file
View File

@@ -0,0 +1,188 @@
<?php
/*
* Mileage - the trips logged in the period: miles by agent and by client,
* every trip listed, and what it comes to at a rate per mile you enter (your
* reimbursement or tax-deduction rate - nothing is assumed). Miles count as
* entered on each trip, the same as the Trips list and the dashboard.
*/
require_once "includes/inc_report.php";
reportEnforce('mileage');
$period = reportPeriod('this_year');
$client_id = reportClientId();
$agent_id = reportAgentId();
$rate = round(max(0, floatval(str_replace(',', '.', (string) ($_GET['rate'] ?? '')))), 4);
$where = "trip_archived_at IS NULL AND " . reportRangeSql('trip_date', $period)
. reportClientSql('trip_client_id', $client_id)
. ($agent_id ? " AND trip_user_id = $agent_id" : '');
$trips = [];
$sql = mysqli_query($mysqli, "SELECT trip_id, trip_date, trip_purpose, trip_source, trip_destination, trip_miles, round_trip,
trip_user_id, user_name, user_avatar, trip_client_id, client_name, client_abbreviation
FROM trips
LEFT JOIN users ON trip_user_id = user_id
LEFT JOIN clients ON trip_client_id = client_id
WHERE $where
ORDER BY trip_date DESC, trip_id DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['miles'] = floatval($row['trip_miles']);
$row['value'] = $rate ? $row['miles'] * $rate : null;
$trips[] = $row;
}
$miles = array_sum(array_column($trips, 'miles'));
$prev_miles = dashboardSum("SELECT SUM(trip_miles) FROM trips WHERE trip_archived_at IS NULL AND " . reportRangeSql('trip_date', $period, true)
. reportClientSql('trip_client_id', $client_id) . ($agent_id ? " AND trip_user_id = $agent_id" : ''));
// Grouped by agent and by client
$by_agent = [];
$by_client = [];
foreach ($trips as $trip) {
$a = intval($trip['trip_user_id']);
$by_agent[$a] = $by_agent[$a] ?? ['user_id' => $a, 'agent' => $trip['user_name'] ?? '', 'avatar' => $trip['user_avatar'] ?? '', 'trips' => 0, 'miles' => 0.0];
$by_agent[$a]['trips']++;
$by_agent[$a]['miles'] += $trip['miles'];
$c = intval($trip['trip_client_id']);
$by_client[$c] = $by_client[$c] ?? ['client_id' => $c, 'client' => $c ? $trip['client_name'] : 'No client (our own)', 'abbr' => $trip['client_abbreviation'] ?? '', 'trips' => 0, 'miles' => 0.0];
$by_client[$c]['trips']++;
$by_client[$c]['miles'] += $trip['miles'];
}
foreach ($by_agent as &$row) {
$row['value'] = $rate ? $row['miles'] * $rate : null;
}
unset($row);
foreach ($by_client as &$row) {
$row['value'] = $rate ? $row['miles'] * $rate : null;
}
unset($row);
usort($by_agent, function ($a, $b) { return $b['miles'] <=> $a['miles']; });
usort($by_client, function ($a, $b) { return $b['miles'] <=> $a['miles']; });
$value_column = ['label' => 'At ' . ($rate ? reportMoney($rate) . ' a mile' : 'your rate'), 'type' => 'money', 'csv_label' => 'Amount'];
$trip_columns = [
'trip_date' => ['label' => 'Date', 'type' => 'date', 'class' => 'text-nowrap'],
'user_name' => ['label' => 'Agent', 'html' => function ($row) {
return reportAgentCell($row['trip_user_id'], $row['user_name'] ?? '', $row['user_avatar'] ?? '', 'No one');
}],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['trip_client_id'], $row['client_name'] ?? '', $row['client_abbreviation'] ?? '');
}],
'trip_purpose' => ['label' => 'Purpose', 'class' => 'itflow-report-text'],
'route' => ['label' => 'From → to', 'class' => 'small text-body-secondary', 'csv' => function ($row) {
return $row['trip_source'] . ' → ' . $row['trip_destination'];
}, 'html' => function ($row) {
return escapeHtml($row['trip_source']) . ' <i class="fas fa-long-arrow-alt-right mx-1"></i> ' . escapeHtml($row['trip_destination']);
}],
'round_trip' => ['label' => 'Round trip', 'csv' => function ($row) {
return intval($row['round_trip']) ? 'Yes' : 'No';
}, 'html' => function ($row) {
return intval($row['round_trip']) ? '<i class="fas fa-sync-alt text-body-secondary" title="Round trip"></i>' : '';
}, 'class' => 'text-center'],
'miles' => ['label' => 'Miles', 'type' => 'decimal', 'decimals' => 1],
];
if ($rate) {
$trip_columns['value'] = $value_column;
}
$agent_columns = [
'agent' => ['label' => 'Agent', 'html' => function ($row) {
return reportAgentCell($row['user_id'], $row['agent'], $row['avatar'], 'No one');
}],
'trips' => ['label' => 'Trips', 'type' => 'count'],
'miles' => ['label' => 'Miles', 'type' => 'decimal', 'decimals' => 1],
];
$client_columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return $row['client_id'] ? reportClientCell($row['client_id'], $row['client'], $row['abbr']) : '<span class="text-body-secondary fst-italic">No client (our own)</span>';
}],
'trips' => ['label' => 'Trips', 'type' => 'count'],
'miles' => ['label' => 'Miles', 'type' => 'decimal', 'decimals' => 1],
];
if ($rate) {
$agent_columns['value'] = $value_column;
$client_columns['value'] = $value_column;
}
$totals = ['trips' => count($trips), 'miles' => $miles, 'value' => $rate ? $miles * $rate : null];
$name = 'Mileage ' . $period['start'] . ' to ' . $period['end'];
if (reportExporting('agents')) {
reportCsv("$name by agent", $agent_columns, $by_agent, ['agent' => 'Total'] + $totals);
}
if (reportExporting('clients')) {
reportCsv("$name by client", $client_columns, $by_client, ['client' => 'Total'] + $totals);
}
if (reportExporting()) {
reportCsv($name, $trip_columns, $trips, ['trip_date' => 'Total', 'miles' => $miles, 'value' => $totals['value']]);
}
$buckets = reportBuckets($period);
$miles_series = reportSeries("SELECT " . reportBucketSql('trip_date', $buckets['unit']) . " AS b, SUM(trip_miles) AS v FROM trips WHERE $where GROUP BY b", $buckets['keys']);
require_once "includes/inc_report_layout.php";
$rate_control = '<div class="col-sm-6 col-lg-2"><div class="input-group">'
. '<span class="input-group-text"><i class="fas fa-fw fa-dollar-sign"></i></span>'
. '<input type="text" inputmode="decimal" class="form-control" name="rate" value="' . ($rate ? escapeHtml(rtrim(rtrim(number_format($rate, 4, '.', ''), '0'), '.')) : '') . '" placeholder="Rate per mile" aria-label="Rate per mile" data-report-autosubmit title="Your reimbursement rate per mile - press Enter">'
. '</div></div>';
?>
<div class="itflow-report">
<?php reportHeader('mileage', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(trip_date) AS y FROM trips"),
'client' => $client_id,
'agent' => $agent_id,
'controls' => $rate_control,
'export' => ['trips' => 'Every trip', 'agents' => 'By agent', 'clients' => 'By client'],
]); ?>
<?= reportStats([
['label' => 'Miles', 'value' => number_format($miles, 1), 'sub' => reportChangeHtml($miles, $prev_miles, 'up', $period['compare'])],
['label' => 'Trips', 'value' => reportCount(count($trips)), 'sub' => count($trips) ? reportCount(count(array_filter(array_column($trips, 'round_trip')))) . ' <span class="text-body-tertiary">round trips</span>' : ''],
['label' => 'Average trip', 'value' => count($trips) ? number_format($miles / count($trips), 1) . ' mi' : '-', 'sub' => '<span class="text-body-tertiary">Miles a trip</span>'],
['label' => $rate ? 'At ' . reportMoney($rate) . ' a mile' : 'Reimbursement', 'value' => $rate ? reportMoney($miles * $rate) : '-',
'sub' => $rate ? '<span class="text-body-tertiary">Miles × your rate</span>' : '<span class="text-body-tertiary">Enter a rate per mile above</span>'],
]) ?>
<?= reportSectionOpen('Miles driven', escapeHtml($period['range'])) ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'labels' => $buckets['labels'],
'series' => [['label' => 'Miles', 'data' => $miles_series, 'tone' => 'accent']],
'format' => 'decimal',
'legend' => false,
], 'sm', 'Miles driven over the period') ?>
</div>
</div>
<div class="row g-3">
<div class="col-xl-6">
<?= reportSectionOpen('By agent', '', 'h-100 mb-0') ?>
<?= reportTable($agent_columns, $by_agent, ['empty' => 'No trips in this period.', 'totals' => ['agent' => 'Total'] + $totals]) ?>
</div>
</div>
<div class="col-xl-6">
<?= reportSectionOpen('By client', '', 'h-100 mb-0') ?>
<?= reportTable($client_columns, $by_client, ['empty' => 'No trips in this period.', 'totals' => ['client' => 'Total'] + $totals]) ?>
</div>
</div>
</div>
<?= reportSectionOpen('Every trip', reportCount(count($trips)) . ' trip' . (count($trips) === 1 ? '' : 's'), 'itflow-report-long') ?>
<?= reportTable($trip_columns, $trips, ['empty' => 'No trips in this period.', 'limit' => 250, 'export_table' => 'trips', 'totals' => ['trip_date' => 'Total', 'miles' => $miles, 'value' => $totals['value']]]) ?>
<div class="card-footer small text-body-secondary">
Miles count as entered on each trip. Archived trips are left out. <a href="/agent/trips.php">Log a trip</a>
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,85 +1,197 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Receivables Aging - what clients owe right now on unpaid invoices (sent,
* viewed or part-paid), split by how long past due: not due yet, 1-30,
* 31-60, 61-90 and over 90 days. Per client with their oldest invoice and
* last payment, then every overdue invoice, latest first. The same invoices
* and total as the dashboard's Receivables, and the Unpaid invoice list.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('outstanding_balances');
$client_id = reportClientId();
$open = dashboardOpenInvoicesSql(reportClientSql('invoice_client_id', $client_id));
$buckets = ['current' => 'Not due yet', '1-30' => '1–30 days', '31-60' => '31–60 days', '61-90' => '61–90 days', '90+' => 'Over 90 days'];
$invoices = [];
$sql = mysqli_query($mysqli, "
SELECT open_invoices.invoice_id, open_invoices.invoice_client_id, open_invoices.invoice_due, balance,
invoice_prefix, invoice_number, invoice_date, invoice_amount, invoice_scope, client_name, client_abbreviation,
DATEDIFF(CURDATE(), open_invoices.invoice_due) AS days_late
FROM ($open) AS open_invoices
JOIN invoices ON invoices.invoice_id = open_invoices.invoice_id
JOIN clients ON client_id = open_invoices.invoice_client_id
WHERE balance > 0.004
ORDER BY open_invoices.invoice_due ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$late = intval($row['days_late']);
$row['bucket'] = $late <= 0 ? 'current' : ($late <= 30 ? '1-30' : ($late <= 60 ? '31-60' : ($late <= 90 ? '61-90' : '90+')));
$row['balance'] = floatval($row['balance']);
$row['paid'] = floatval($row['invoice_amount']) - $row['balance'];
$invoices[] = $row;
}
// Per client, a column per bucket
$clients = [];
$totals = array_fill_keys(array_keys($buckets), 0.0);
foreach ($invoices as $invoice) {
$id = intval($invoice['invoice_client_id']);
if (!isset($clients[$id])) {
$clients[$id] = ['client_id' => $id, 'client' => $invoice['client_name'], 'abbr' => $invoice['client_abbreviation'],
'count' => 0, 'total' => 0.0, 'oldest_late' => null, 'last_payment' => null] + array_fill_keys(array_keys($buckets), 0.0);
}
$clients[$id][$invoice['bucket']] += $invoice['balance'];
$clients[$id]['total'] += $invoice['balance'];
$clients[$id]['count']++;
$clients[$id]['oldest_late'] = max($clients[$id]['oldest_late'] ?? -100000, intval($invoice['days_late']));
$totals[$invoice['bucket']] += $invoice['balance'];
}
if ($clients) {
$sql = mysqli_query($mysqli, "SELECT invoice_client_id AS client_id, MAX(payment_date) AS last_paid FROM payments JOIN invoices ON payment_invoice_id = invoice_id
WHERE invoice_client_id IN (" . implode(',', array_keys($clients)) . ") GROUP BY invoice_client_id");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[intval($row['client_id'])]['last_payment'] = $row['last_paid'];
}
}
uasort($clients, function ($a, $b) {
return $b['total'] <=> $a['total'];
});
$total = array_sum($totals);
$overdue_total = $total - $totals['current'];
$bucket_cell = function ($key) {
return function ($row) use ($key) {
if ($row[$key] < 0.005) {
return '<span class="itflow-report-zero">–</span>';
}
$class = in_array($key, ['61-90', '90+'], true) ? 'text-danger-emphasis fw-semibold' : '';
return '<span class="' . $class . '">' . reportMoney($row[$key]) . '</span>';
};
};
$client_columns = ['client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'invoices.php') ;
}]];
foreach ($buckets as $key => $label) {
$client_columns[$key] = ['label' => $label, 'type' => 'money', 'html' => $bucket_cell($key)];
}
$client_columns += [
'total' => ['label' => 'Owed', 'type' => 'money', 'html' => function ($row) {
return '<a class="itflow-report-amount fw-semibold" href="/agent/invoices.php?client_id=' . $row['client_id'] . '&status=Unpaid">' . reportMoney($row['total']) . '</a>';
}],
'count' => ['label' => 'Invoices', 'type' => 'count'],
'oldest_late' => ['label' => 'Oldest', 'type' => 'count', 'csv_label' => 'Oldest days late', 'title' => 'Days the oldest unpaid invoice is past due', 'html' => function ($row) {
return $row['oldest_late'] > 0 ? '<span class="' . ($row['oldest_late'] > 60 ? 'text-danger-emphasis fw-semibold' : '') . '">' . $row['oldest_late'] . ' day' . ($row['oldest_late'] === 1 ? '' : 's') . ' late</span>' : '<span class="text-body-secondary">Not due</span>';
}],
'last_payment' => ['label' => 'Last paid', 'type' => 'date', 'class' => 'text-nowrap', 'html' => function ($row) {
return $row['last_payment'] ? '<span title="' . escapeHtml($row['last_payment']) . '">' . escapeHtml(timeAgo($row['last_payment'])) . '</span>' : '<span class="text-body-secondary">Never</span>';
}],
];
$invoice_columns = [
'invoice' => ['label' => 'Invoice', 'csv' => function ($row) { return $row['invoice_prefix'] . $row['invoice_number']; }, 'html' => function ($row) {
return '<a class="font-monospace" href="/agent/invoice.php?client_id=' . intval($row['invoice_client_id']) . '&invoice_id=' . intval($row['invoice_id']) . '">' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) . '</a>'
. ($row['invoice_scope'] !== '' && $row['invoice_scope'] !== null ? '<div class="small text-body-secondary text-truncate" style="max-width: 18rem">' . escapeHtml($row['invoice_scope']) . '</div>' : '');
}],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['invoice_client_id'], $row['client_name'], $row['client_abbreviation'], 'invoices.php');
}],
'invoice_date' => ['label' => 'Date', 'type' => 'date', 'class' => 'text-nowrap'],
'invoice_due' => ['label' => 'Due', 'type' => 'date', 'class' => 'text-nowrap'],
'days_late' => ['label' => 'Late', 'type' => 'count', 'csv_label' => 'Days late', 'html' => function ($row) {
$late = intval($row['days_late']);
if ($late <= 0) {
return '<span class="text-body-secondary">' . ($late === 0 ? 'Due today' : 'In ' . (-$late) . ' day' . ($late === -1 ? '' : 's')) . '</span>';
}
$tone = $late > 60 ? 'danger' : ($late > 30 ? 'warning' : 'secondary');
return '<span class="badge rounded-pill bg-' . $tone . '-subtle text-' . $tone . '-emphasis border border-' . $tone . '-subtle fw-normal">' . $late . ' day' . ($late === 1 ? '' : 's') . '</span>';
}],
'invoice_amount' => ['label' => 'Amount', 'type' => 'money', 'class' => 'text-body-secondary'],
'paid' => ['label' => 'Paid', 'type' => 'money', 'class' => 'text-body-secondary', 'html' => function ($row) {
return $row['paid'] > 0.004 ? reportMoney($row['paid']) : '<span class="itflow-report-zero">–</span>';
}],
'balance' => ['label' => 'Owed', 'type' => 'money', 'class' => 'fw-semibold'],
];
if (reportExporting('invoices')) {
reportCsv('Unpaid Invoices', $invoice_columns, $invoices, ['invoice' => 'Total', 'balance' => $total]);
}
if (reportExporting()) {
reportCsv('Receivables Aging', $client_columns, array_values($clients), ['client' => 'Total', 'total' => $total, 'count' => count($invoices)] + $totals);
}
require_once "includes/inc_report_layout.php";
$late_90 = $totals['90+'];
$late_60 = $totals['61-90'] + $totals['90+'];
$overdue = array_values(array_filter($invoices, function ($i) { return intval($i['days_late']) > 0; }));
usort($overdue, function ($a, $b) { return intval($b['days_late']) <=> intval($a['days_late']); });
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-exclamation-triangle me-2"></i>Clients with a Balance</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('outstanding_balances', [
'client' => $client_id,
'subtitle' => 'As of ' . date('M j, Y'),
'export' => ['clients' => 'By client', 'invoices' => 'Every unpaid invoice'],
]); ?>
<?= reportStats([
['label' => 'Owed to you', 'value' => reportMoney($total), 'url' => '/agent/invoices.php?status=Unpaid',
'sub' => reportCount(count($invoices)) . ' <span class="text-body-tertiary">unpaid invoice' . (count($invoices) === 1 ? '' : 's') . '</span>'],
['label' => 'Overdue', 'value' => reportMoney($overdue_total), 'tone' => $overdue_total > 0 ? 'danger' : '', 'url' => '/agent/invoices.php?status=Overdue',
'sub' => $total > 0 ? escapeHtml(reportPercent(reportShare($overdue_total, $total))) . ' <span class="text-body-tertiary">of what is owed</span>' : ''],
['label' => 'Over 60 days late', 'value' => reportMoney($late_60), 'tone' => $late_60 > 0 ? 'danger' : '',
'sub' => $late_90 > 0 ? escapeHtml(reportMoney($late_90)) . ' <span class="text-body-tertiary">over 90</span>' : '<span class="text-body-tertiary">Nothing over 90 days</span>'],
['label' => 'Clients owing', 'value' => reportCount(count($clients)),
'sub' => count(array_filter($clients, function ($c) { return $c['oldest_late'] > 0; })) . ' <span class="text-body-tertiary">with something overdue</span>'],
]) ?>
<?php if ($total > 0) { ?>
<?= reportSectionOpen('By how late', '') ?>
<div class="card-body">
<div class="itflow-dash-aging mb-3" role="img" aria-label="What is owed, by days past due">
<?php foreach ($buckets as $key => $label) {
if ($totals[$key] > 0) { ?>
<span class="itflow-dash-age-<?= str_replace('+', 'plus', $key) ?>" style="width: <?= round($totals[$key] / $total * 100, 2) ?>%" title="<?= escapeHtml($label . ': ' . reportMoney($totals[$key])) ?>"></span>
<?php }
} ?>
</div>
<div class="row row-cols-2 row-cols-md-5 g-2 small">
<?php foreach ($buckets as $key => $label) { ?>
<div>
<span class="d-block text-body-secondary text-nowrap"><span class="itflow-dash-legend-swatch d-inline-block me-1 itflow-dash-age-<?= str_replace('+', 'plus', $key) ?>"></span><?= escapeHtml($label) ?></span>
<span class="d-block fw-semibold fs-6 <?= $totals[$key] > 0 ? '' : 'text-body-tertiary' ?>"><?= reportMoney($totals[$key]) ?></span>
<span class="d-block text-body-tertiary"><?= reportPercent(reportShare($totals[$key], $total)) ?></span>
</div>
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By client', 'Most owed first') ?>
<?= reportTable($client_columns, array_values($clients), [
'empty' => reportEmpty('Nothing is owed on unpaid invoices.'),
'totals' => ['client' => 'Total', 'total' => $total, 'count' => count($invoices)] + $totals,
]) ?>
</div>
<?= reportSectionOpen('Overdue invoices', $overdue ? 'Longest overdue first' : '', 'itflow-report-long') ?>
<?= reportTable($invoice_columns, $overdue, [
'empty' => reportEmpty('No invoice is past its due date.'),
'limit' => 300, 'export_table' => 'invoices',
'totals' => ['invoice' => 'Total', 'balance' => array_sum(array_column($overdue, 'balance'))],
]) ?>
<div class="card-footer small text-body-secondary">
Unpaid invoices are the ones sent, viewed or part-paid; drafts and cancelled invoices are not owed. Days late count from the due date.
</div>
</div>
<div class="card-body">
<?php
$sql_clients = mysqli_query($mysqli, "
SELECT
clients.client_id,
clients.client_name,
IFNULL(SUM(invoices.invoice_amount), 0) - IFNULL(SUM(payments.payment_amount), 0) AS balance
FROM
clients
LEFT JOIN
invoices
ON
clients.client_id = invoices.invoice_client_id
AND invoices.invoice_status != 'Draft'
AND invoices.invoice_status != 'Cancelled'
AND invoice_status != 'Non-Billable'
LEFT JOIN
(SELECT
payment_invoice_id,
SUM(payment_amount) as payment_amount
FROM payments
GROUP BY payment_invoice_id) as payments
ON
invoices.invoice_id = payments.payment_invoice_id
WHERE 1=1 " . clientScopeSql('clients.client_id') . "
GROUP BY
clients.client_id,
clients.client_name
HAVING
balance > 0
ORDER BY
balance DESC
");
?>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Balance</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_clients)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$balance = floatval($row['balance']);
?>
<tr>
<td><a href="../../agent/invoices.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $balance, $session_company_currency) ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
<?php
require_once "../../includes/footer.php";
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,436 +1,228 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Profit & Loss - a year of income and spending by category, by month or by
* quarter, with the net profit and margin under it and last year beside it.
*
* Cash basis, as the dashboard: income is invoice payments (filed under the
* invoice's category) and revenues with a category; spending is vendor
* expenses. Transfers between accounts are neither. In the current year it
* runs to today and is compared with the same stretch of last year.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('profit_loss');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
[$year, $years] = reportYear("SELECT YEAR(payment_date) AS y FROM payments
UNION SELECT YEAR(revenue_date) FROM revenues
UNION SELECT YEAR(expense_date) FROM expenses");
$view = ($_GET['view'] ?? 'month') === 'quarter' ? 'quarter' : 'month';
$current_year = $year === intval(date('Y'));
$from = "$year-01-01";
$to = $current_year ? date('Y-m-d') : "$year-12-31";
$prev_from = ($year - 1) . '-01-01';
$prev_to = $current_year ? dashboardShiftMonths(date('Y-m-d'), -12) : ($year - 1) . '-12-31';
$compare = $current_year ? 'the same time last year' : (string) ($year - 1);
$income = reportIncomeByCategory($from, $to);
$expenses = reportExpensesByCategory($from, $to);
$income_categories = reportCategoryRows('Income', $income);
$expense_categories = reportCategoryRows('Expense', $expenses);
$income_prev = reportIncomeByCategory($prev_from, $prev_to);
$expenses_prev = reportExpensesByCategory($prev_from, $prev_to);
reportCategoryRows('Income', $income_prev);
reportCategoryRows('Expense', $expenses_prev);
$income_total = reportGridTotals($income);
$expense_total = reportGridTotals($expenses);
$income_prev_total = reportGridTotals($income_prev)['total'];
$expense_prev_total = reportGridTotals($expenses_prev)['total'];
$profit = $income_total['total'] - $expense_total['total'];
$profit_prev = $income_prev_total - $expense_prev_total;
$margin = reportShare($profit, $income_total['total'], 1);
$margin_prev = reportShare($profit_prev, $income_prev_total, 1);
$columns = reportYearColumns($view);
// The statement's lines, for the table and the CSV alike
$category_lines = function ($categories, $grid, $prev_grid, $kind) use ($columns) {
$lines = [];
foreach ($categories as $cat => $category) {
$row = reportGridRow($grid, $cat);
$lines[] = [
'kind' => $kind, 'cat' => $cat, 'name' => $category['category_name'],
'archived' => !empty($category['category_archived_at']),
'cells' => reportSumColumns($row['months'], $columns), 'total' => $row['total'],
'prev' => reportGridRow($prev_grid, $cat)['total'],
];
}
return $lines;
};
// A category with nothing in either year is left off - a statement lists what happened
$active = function ($line) {
return abs($line['total']) >= 0.005 || abs($line['prev']) >= 0.005;
};
$income_lines = array_values(array_filter($category_lines($income_categories, $income, $income_prev, 'income'), $active));
$expense_lines = array_values(array_filter($category_lines($expense_categories, $expenses, $expenses_prev, 'expense'), $active));
$income_line = ['kind' => 'income_total', 'name' => 'Total income', 'cells' => reportSumColumns($income_total['months'], $columns), 'total' => $income_total['total'], 'prev' => $income_prev_total];
$expense_line = ['kind' => 'expense_total', 'name' => 'Total expenses', 'cells' => reportSumColumns($expense_total['months'], $columns), 'total' => $expense_total['total'], 'prev' => $expense_prev_total];
$profit_cells = [];
foreach ($columns as $i => $column) {
$profit_cells[$i] = $income_line['cells'][$i] - $expense_line['cells'][$i];
}
$profit_line = ['kind' => 'profit', 'name' => 'Net profit', 'cells' => $profit_cells, 'total' => $profit, 'prev' => $profit_prev];
if (reportExporting()) {
$csv_columns = ['section' => ['label' => 'Section'], 'name' => ['label' => 'Category']];
foreach ($columns as $i => [$label]) {
$csv_columns["c$i"] = ['label' => $label, 'type' => 'money'];
}
$csv_columns['total'] = ['label' => $current_year ? "$year to date" : "$year total", 'type' => 'money'];
$csv_columns['prev'] = ['label' => $current_year ? 'Same time last year' : (string) ($year - 1), 'type' => 'money'];
$flatten = function ($line, $section) use ($columns) {
$row = ['section' => $section, 'name' => $line['name'], 'total' => $line['total'], 'prev' => $line['prev']];
foreach ($columns as $i => $column) {
$row["c$i"] = $line['cells'][$i];
}
return $row;
};
$csv_rows = [];
foreach ($income_lines as $line) {
$csv_rows[] = $flatten($line, 'Income');
}
$csv_rows[] = $flatten($income_line, 'Income');
foreach ($expense_lines as $line) {
$csv_rows[] = $flatten($line, 'Expenses');
}
$csv_rows[] = $flatten($expense_line, 'Expenses');
$csv_rows[] = $flatten($profit_line, 'Net profit');
reportCsv("Profit and Loss $year", $csv_columns, $csv_rows);
}
//GET unique years from expenses, payments and revenues
$sql_all_years = mysqli_query($mysqli, "SELECT YEAR(expense_date) AS all_years FROM expenses
UNION DISTINCT SELECT YEAR(payment_date) FROM payments
UNION DISTINCT SELECT YEAR(revenue_date) FROM revenues
ORDER BY all_years DESC"
);
// The chart goes a month at a time, whichever way the table is split
$months_shown = $current_year ? intval(date('n')) : 12;
$chart = ['income' => [], 'expenses' => [], 'profit' => []];
for ($m = 1; $m <= 12; $m++) {
$in = round($income_total['months'][$m], 2);
$out = round($expense_total['months'][$m], 2);
$chart['income'][] = $m <= $months_shown ? $in : null;
$chart['expenses'][] = $m <= $months_shown ? $out : null;
$chart['profit'][] = $m <= $months_shown ? round($in - $out, 2) : null;
}
$sql_categories_income = mysqli_query($mysqli, "SELECT category_id, category_name FROM categories WHERE category_type = 'Income' ORDER BY category_name ASC");
$sql_categories_expense = mysqli_query($mysqli, "SELECT category_id, category_name FROM categories WHERE category_type = 'Expense' ORDER BY category_name ASC");
require_once "includes/inc_report_layout.php";
// One line of the statement
$render = function ($line, $class = '') use ($columns, $year) {
$kind = $line['kind'];
$cat = $line['cat'] ?? 0;
$list = $kind === 'income' ? 'income.php' : ($kind === 'expense' ? 'expenses.php' : '');
$html = '<tr' . ($class !== '' ? ' class="' . $class . '"' : '') . '><td' . ($list ? ' class="itflow-report-sub"' : '') . '>'
. escapeHtml($line['name']) . (!empty($line['archived']) ? ' <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Archived</span>' : '') . '</td>';
foreach ($columns as $i => [$label, $first, $last]) {
$url = '';
if ($list && $cat) {
[$dtf, $dtt] = reportColumnDates($year, $first, $last);
$url = "/agent/$list?category=$cat&canned_date=custom&dtf=$dtf&dtt=$dtt";
}
$amount = $line['cells'][$i];
$html .= '<td class="text-end' . ($kind === 'profit' && $amount < 0 ? ' text-danger' : '') . '">' . reportGridAmount($amount, $url) . '</td>';
}
// Spending going up is not good news
$good = in_array($kind, ['expense', 'expense_total'], true) ? 'down' : 'up';
$html .= '<td class="text-end fw-semibold' . ($kind === 'profit' && $line['total'] < 0 ? ' text-danger' : '') . '">' . reportGridAmount($line['total']) . '</td>'
. '<td class="text-end text-body-secondary">' . reportGridAmount($line['prev']) . '</td>'
. '<td class="text-end small">' . (reportChange($line['total'], $line['prev']) === null ? '<span class="itflow-report-zero">–</span>' : reportChangeHtml($line['total'], $line['prev'], $good)) . '</td>'
. '</tr>';
return $html;
};
$span = count($columns) + 4;
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-balance-scale me-2"></i>Profit & Loss</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
</div>
</div>
<div class="card-body p-0">
<form class="p-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_all_years)) {
$all_years = intval($row['all_years']);
?>
<option <?php if ($year == $all_years) { ?> selected <?php } ?> > <?= $all_years ?></option>
<?php
}
?>
</select>
</form>
<div class="table-responsive-sm">
<table class="table table-sm">
<thead class="text-dark">
<tr>
<th></th>
<th class="text-end">Jan-Mar</th>
<th class="text-end">Apr-Jun</th>
<th class="text-end">Jul-Sep</th>
<th class="text-end">Oct-Dec</th>
<th class="text-end">Total</th>
</tr>
<tr>
<th><br><br>Income</th>
<th colspan="5"></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_categories_income)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<tr>
<td><?= $category_name ?></td>
<?php
$payment_amount_for_quarter_one = 0;
for($month = 1; $month<=3; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_category_id = $category_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_amount_for_month = floatval($row['payment_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_amount_for_month FROM revenues WHERE revenue_category_id = $category_id AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_amount_for_month = floatval($row['revenue_amount_for_month']);
$payment_amount_for_month = $payment_amount_for_month + $revenue_amount_for_month;
$payment_amount_for_quarter_one = $payment_amount_for_quarter_one + $payment_amount_for_month;
}
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $payment_amount_for_quarter_one, $session_company_currency) ?></td>
<?php
$payment_amount_for_quarter_two = 0;
for($month = 4; $month<=6; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_category_id = $category_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_amount_for_month = floatval($row['payment_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_amount_for_month FROM revenues WHERE revenue_category_id = $category_id AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_amount_for_month = floatval($row['revenue_amount_for_month']);
$payment_amount_for_month = $payment_amount_for_month + $revenue_amount_for_month;
$payment_amount_for_quarter_two = $payment_amount_for_quarter_two + $payment_amount_for_month;
}
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $payment_amount_for_quarter_two, $session_company_currency) ?></td>
<?php
$payment_amount_for_quarter_three = 0;
for($month = 7; $month<=9; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_category_id = $category_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_amount_for_month = floatval($row['payment_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_amount_for_month FROM revenues WHERE revenue_category_id = $category_id AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_amount_for_month = floatval($row['revenue_amount_for_month']);
$payment_amount_for_month = $payment_amount_for_month + $revenue_amount_for_month;
$payment_amount_for_quarter_three = $payment_amount_for_quarter_three + $payment_amount_for_month;
}
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $payment_amount_for_quarter_three, $session_company_currency) ?></td>
<?php
$payment_amount_for_quarter_four = 0;
for($month = 10; $month<=12; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND invoice_category_id = $category_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_amount_for_month = floatval($row['payment_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_amount_for_month FROM revenues WHERE revenue_category_id = $category_id AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_amount_for_month = floatval($row['revenue_amount_for_month']);
$payment_amount_for_month = $payment_amount_for_month + $revenue_amount_for_month;
$payment_amount_for_quarter_four = $payment_amount_for_quarter_four + $payment_amount_for_month;
}
$total_payments_for_all_four_quarters = $payment_amount_for_quarter_one + $payment_amount_for_quarter_two + $payment_amount_for_quarter_three + $payment_amount_for_quarter_four;
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $payment_amount_for_quarter_four, $session_company_currency) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $total_payments_for_all_four_quarters, $session_company_currency) ?></td>
</tr>
<?php
$total_payment_for_all_months = 0;
}
?>
<tr>
<th>Gross Revenue</th>
<?php
$payment_total_amount_for_quarter_one = 0;
for($month = 1; $month<=3; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_total_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_total_amount_for_month = floatval($row['payment_total_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_total_amount_for_month FROM revenues WHERE revenue_category_id > 0 AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_total_amount_for_month = floatval($row['revenue_total_amount_for_month']);
$payment_total_amount_for_month = $payment_total_amount_for_month + $revenue_total_amount_for_month;
$payment_total_amount_for_quarter_one = $payment_total_amount_for_quarter_one + $payment_total_amount_for_month;
}
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $payment_total_amount_for_quarter_one, $session_company_currency) ?></th>
<?php
$payment_total_amount_for_quarter_two = 0;
for($month = 4; $month<=6; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_total_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_total_amount_for_month = floatval($row['payment_total_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_total_amount_for_month FROM revenues WHERE revenue_category_id > 0 AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_total_amount_for_month = floatval($row['revenue_total_amount_for_month']);
$payment_total_amount_for_month = $payment_total_amount_for_month + $revenue_total_amount_for_month;
$payment_total_amount_for_quarter_two = $payment_total_amount_for_quarter_two + $payment_total_amount_for_month;
}
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $payment_total_amount_for_quarter_two, $session_company_currency) ?></th>
<?php
$payment_total_amount_for_quarter_three = 0;
for($month = 7; $month<=9; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_total_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_total_amount_for_month = floatval($row['payment_total_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_total_amount_for_month FROM revenues WHERE revenue_category_id > 0 AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_total_amount_for_month = floatval($row['revenue_total_amount_for_month']);
$payment_total_amount_for_month = $payment_total_amount_for_month + $revenue_total_amount_for_month;
$payment_total_amount_for_quarter_three = $payment_total_amount_for_quarter_three + $payment_total_amount_for_month;
}
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $payment_total_amount_for_quarter_three, $session_company_currency) ?></th>
<?php
$payment_total_amount_for_quarter_four = 0;
for($month = 10; $month<=12; $month++) {
$sql_payments = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS payment_total_amount_for_month FROM payments, invoices WHERE payment_invoice_id = invoice_id AND YEAR(payment_date) = $year AND MONTH(payment_date) = $month");
$row = mysqli_fetch_assoc($sql_payments);
$payment_total_amount_for_month = floatval($row['payment_total_amount_for_month']);
$sql_revenues = mysqli_query($mysqli, "SELECT SUM(revenue_amount) AS revenue_total_amount_for_month FROM revenues WHERE revenue_category_id > 0 AND YEAR(revenue_date) = $year AND MONTH(revenue_date) = $month");
$row = mysqli_fetch_assoc($sql_revenues);
$revenue_total_amount_for_month = floatval($row['revenue_total_amount_for_month']);
$payment_total_amount_for_month = $payment_total_amount_for_month + $revenue_total_amount_for_month;
$payment_total_amount_for_quarter_four = $payment_total_amount_for_quarter_four + $payment_total_amount_for_month;
}
$total_payments_for_all_four_quarters = $payment_total_amount_for_quarter_one + $payment_total_amount_for_quarter_two + $payment_total_amount_for_quarter_three + $payment_total_amount_for_quarter_four;
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $payment_total_amount_for_quarter_four, $session_company_currency) ?></th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $total_payments_for_all_four_quarters, $session_company_currency) ?></th>
</tr>
<tr>
<th><br><br>Expenses</th>
<th colspan="5"></th>
</tr>
<?php
while ($row = mysqli_fetch_assoc($sql_categories_expense)) {
$category_id = intval($row['category_id']);
$category_name = escapeHtml($row['category_name']);
?>
<tr>
<td><?= $category_name ?></td>
<?php
$expense_amount_for_quarter_one = 0;
for($month = 1; $month<=3; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_amount_for_month FROM expenses WHERE expense_category_id = $category_id AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_amount_for_quarter_one = $expense_amount_for_quarter_one + floatval($row['expense_amount_for_month']);
}
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $expense_amount_for_quarter_one, $session_company_currency) ?></td>
<?php
$expense_amount_for_quarter_two = 0;
for($month = 4; $month<=6; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_amount_for_month FROM expenses WHERE expense_category_id = $category_id AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_amount_for_quarter_two = $expense_amount_for_quarter_two + floatval($row['expense_amount_for_month']);
}
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $expense_amount_for_quarter_two, $session_company_currency) ?></td>
<?php
$expense_amount_for_quarter_three = 0;
for($month = 7; $month<=9; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_amount_for_month FROM expenses WHERE expense_category_id = $category_id AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_amount_for_quarter_three = $expense_amount_for_quarter_three + floatval($row['expense_amount_for_month']);
}
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $expense_amount_for_quarter_three, $session_company_currency) ?></td>
<?php
$expense_amount_for_quarter_four = 0;
for($month = 10; $month<=12; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_amount_for_month FROM expenses WHERE expense_category_id = $category_id AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_amount_for_quarter_four = $expense_amount_for_quarter_four + floatval($row['expense_amount_for_month']);
}
$total_expenses_for_all_four_quarters = $expense_amount_for_quarter_one + $expense_amount_for_quarter_two + $expense_amount_for_quarter_three + $expense_amount_for_quarter_four;
?>
<td class="text-end"><?= numfmt_format_currency($currency_format, $expense_amount_for_quarter_four, $session_company_currency) ?></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $total_expenses_for_all_four_quarters, $session_company_currency) ?></td>
</tr>
<?php
$total_expense_for_all_months = 0;
}
?>
<tr>
<th>Total Expenses<br><br><br></th>
<?php
$expense_total_amount_for_quarter_one = 0;
for($month = 1; $month<=3; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_total_amount_for_month FROM expenses WHERE expense_category_id > 0 AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month AND expense_vendor_id > 0");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_total_amount_for_quarter_one = $expense_total_amount_for_quarter_one + floatval($row['expense_total_amount_for_month']);
}
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $expense_total_amount_for_quarter_one, $session_company_currency) ?></th>
<?php
$expense_total_amount_for_quarter_two = 0;
for($month = 4; $month<=6; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_total_amount_for_month FROM expenses WHERE expense_category_id > 0 AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month AND expense_vendor_id > 0");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_total_amount_for_quarter_two = $expense_total_amount_for_quarter_two + floatval($row['expense_total_amount_for_month']);
}
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $expense_total_amount_for_quarter_two, $session_company_currency) ?></th>
<?php
$expense_total_amount_for_quarter_three = 0;
for($month = 7; $month<=9; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_total_amount_for_month FROM expenses WHERE expense_category_id > 0 AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month AND expense_vendor_id > 0");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_total_amount_for_quarter_three = $expense_total_amount_for_quarter_three + floatval($row['expense_total_amount_for_month']);
}
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $expense_total_amount_for_quarter_three, $session_company_currency) ?></th>
<?php
$expense_total_amount_for_quarter_four = 0;
for($month = 10; $month<=12; $month++) {
$sql_expenses = mysqli_query($mysqli, "SELECT SUM(expense_amount) AS expense_total_amount_for_month FROM expenses WHERE expense_category_id > 0 AND YEAR(expense_date) = $year AND MONTH(expense_date) = $month AND expense_vendor_id > 0");
$row = mysqli_fetch_assoc($sql_expenses);
$expense_total_amount_for_quarter_four = $expense_total_amount_for_quarter_four + floatval($row['expense_total_amount_for_month']);
}
$total_expenses_for_all_four_quarters = $expense_total_amount_for_quarter_one + $expense_total_amount_for_quarter_two + $expense_total_amount_for_quarter_three + $expense_total_amount_for_quarter_four;
?>
<th class="text-end"><?= numfmt_format_currency($currency_format, $expense_total_amount_for_quarter_four, $session_company_currency) ?></th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $total_expenses_for_all_four_quarters, $session_company_currency) ?></th>
</tr>
<tr>
<?php
$net_profit_quarter_one = $payment_total_amount_for_quarter_one - $expense_total_amount_for_quarter_one;
$net_profit_quarter_two = $payment_total_amount_for_quarter_two - $expense_total_amount_for_quarter_two;
$net_profit_quarter_three = $payment_total_amount_for_quarter_three - $expense_total_amount_for_quarter_three;
$net_profit_quarter_four = $payment_total_amount_for_quarter_four - $expense_total_amount_for_quarter_four;
$net_profit_year = $total_payments_for_all_four_quarters - $total_expenses_for_all_four_quarters;
?>
<th>Net Profit</th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $net_profit_quarter_one, $session_company_currency) ?></th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $net_profit_quarter_two, $session_company_currency) ?></th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $net_profit_quarter_three, $session_company_currency) ?></th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $net_profit_quarter_four, $session_company_currency) ?></th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $net_profit_year, $session_company_currency) ?></th>
</tr>
</tbody>
</table>
</div>
<div class="itflow-report">
<?php reportHeader('profit_loss', [
'year' => [$year, $years],
'controls' => reportSegmentControl('view', $view, ['month' => 'Monthly', 'quarter' => 'Quarterly']),
'subtitle' => $current_year ? "$year to date" : (string) $year,
'print_meta' => $current_year ? "January 1 to " . date('F j, Y') : "Year $year",
]); ?>
<?= reportStats([
['label' => 'Income', 'value' => reportMoney($income_total['total']), 'sub' => reportChangeHtml($income_total['total'], $income_prev_total, 'up', $compare),
'url' => "/agent/income.php?canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Expenses', 'value' => reportMoney($expense_total['total']), 'sub' => reportChangeHtml($expense_total['total'], $expense_prev_total, 'down', $compare),
'url' => "/agent/expenses.php?canned_date=custom&dtf=$from&dtt=$to"],
['label' => 'Net profit', 'value' => reportMoney($profit), 'tone' => $profit < 0 ? 'danger' : '', 'sub' => reportChangeHtml($profit, $profit_prev, 'up', $compare)],
['label' => 'Profit margin', 'value' => reportPercent($margin), 'tone' => $margin !== null && $margin < 0 ? 'danger' : '',
'sub' => $margin_prev === null ? '<span class="text-body-tertiary">Nothing before to compare</span>' : escapeHtml(reportPercent($margin_prev)) . ' <span class="text-body-tertiary">' . escapeHtml($current_year ? 'same time last year' : 'in ' . ($year - 1)) . '</span>'],
]) ?>
<?= reportSectionOpen('Income, expenses and profit by month', escapeHtml((string) $year)) ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'labels' => array_map(function ($m) { return date('M', mktime(0, 0, 0, $m, 1)); }, range(1, 12)),
'series' => [
['label' => 'Income', 'data' => $chart['income'], 'tone' => 'success'],
['label' => 'Expenses', 'data' => $chart['expenses'], 'tone' => 'danger'],
['label' => 'Net profit', 'data' => $chart['profit'], 'tone' => 'accent', 'type' => 'line'],
],
'format' => 'money',
], 'lg', 'Income, expenses and net profit per month') ?>
</div>
</div>
<?php require_once "../../includes/footer.php";
<?= reportSectionOpen('Statement', escapeHtml($current_year ? 'Last year is ' . ($year - 1) . ' to ' . date('M j', strtotime($prev_to)) : 'Last year is ' . ($year - 1)), 'itflow-report-long') ?>
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0 itflow-report-table itflow-report-grid">
<thead class="table-light">
<tr>
<th>Category</th>
<?php foreach ($columns as [$label, $first, $last]) { ?>
<th class="text-end"<?php if ($view === 'quarter') { ?> title="<?= date('M', mktime(0, 0, 0, $first, 1)) ?> – <?= date('M', mktime(0, 0, 0, $last, 1)) ?>"<?php } ?>><?= $label ?></th>
<?php } ?>
<th class="text-end"><?= $year ?></th>
<th class="text-end">Last year</th>
<th class="text-end">Change</th>
</tr>
</thead>
<tbody>
<tr class="itflow-report-group-row"><td colspan="<?= $span ?>">Income</td></tr>
<?php foreach ($income_lines as $line) { echo $render($line); } ?>
<?php if (!$income_lines) { ?><tr><td colspan="<?= $span ?>" class="itflow-report-sub text-body-secondary">No income this year or last.</td></tr><?php } ?>
<?= $render($income_line, 'fw-semibold') ?>
<tr class="itflow-report-group-row"><td colspan="<?= $span ?>">Expenses</td></tr>
<?php foreach ($expense_lines as $line) { echo $render($line); } ?>
<?php if (!$expense_lines) { ?><tr><td colspan="<?= $span ?>" class="itflow-report-sub text-body-secondary">No spending this year or last.</td></tr><?php } ?>
<?= $render($expense_line, 'fw-semibold') ?>
</tbody>
<tfoot>
<?= $render($profit_line, 'fw-semibold') ?>
<tr>
<td>Margin</td>
<?php foreach ($columns as $i => $column) {
$cell_margin = reportShare($profit_line['cells'][$i], $income_line['cells'][$i], 1); ?>
<td class="text-end<?= $cell_margin !== null && $cell_margin < 0 ? ' text-danger' : '' ?>"><?= $cell_margin === null ? '<span class="itflow-report-zero">–</span>' : reportPercent($cell_margin) ?></td>
<?php } ?>
<td class="text-end fw-semibold<?= $margin !== null && $margin < 0 ? ' text-danger' : '' ?>"><?= reportPercent($margin) ?></td>
<td class="text-end text-body-secondary"><?= reportPercent($margin_prev) ?></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
<div class="card-footer small text-body-secondary">
Cash basis - money counts when it arrives or leaves. Payments are filed under the category of the invoice they paid,
and transfers between your own accounts are left out of both sides. Click an amount to see what makes it up.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -0,0 +1,187 @@
<?php
/*
* Quotes Pipeline - what has been quoted in the period and how it went: won
* (accepted or invoiced), lost (declined) or still open (sent or viewed),
* with the win rate by number and by value. Below that, every quote still
* waiting for an answer today - soonest to expire first - and how each
* client's quotes went. Drafts have not gone out, so they count nowhere but
* their own figure; archived quotes are left out.
*/
require_once "includes/inc_report.php";
reportEnforce('quote_pipeline');
$period = reportPeriod('last_12');
$client_id = reportClientId();
$client_sql = reportClientSql('quote_client_id', $client_id);
$outcome_sql = "CASE WHEN quote_status IN ('Accepted', 'Invoiced') THEN 'won' WHEN quote_status = 'Declined' THEN 'lost'
WHEN quote_status IN ('Sent', 'Viewed') THEN 'open' ELSE 'draft' END";
// In the period, by outcome
$by = ['won' => ['n' => 0, 'v' => 0.0], 'lost' => ['n' => 0, 'v' => 0.0], 'open' => ['n' => 0, 'v' => 0.0], 'draft' => ['n' => 0, 'v' => 0.0]];
$sql = mysqli_query($mysqli, "SELECT $outcome_sql AS outcome, COUNT(quote_id) AS n, SUM(quote_amount) AS v FROM quotes
WHERE quote_archived_at IS NULL AND " . reportRangeSql('quote_date', $period) . " $client_sql GROUP BY outcome");
while ($row = mysqli_fetch_assoc($sql)) {
$by[$row['outcome']] = ['n' => intval($row['n']), 'v' => floatval($row['v'])];
}
$quoted_n = $by['won']['n'] + $by['lost']['n'] + $by['open']['n'];
$quoted_v = $by['won']['v'] + $by['lost']['v'] + $by['open']['v'];
$win_rate = reportShare($by['won']['n'], $by['won']['n'] + $by['lost']['n']);
$win_rate_value = reportShare($by['won']['v'], $by['won']['v'] + $by['lost']['v']);
$prev_won = dashboardSum("SELECT SUM(quote_amount) FROM quotes WHERE quote_archived_at IS NULL AND quote_status IN ('Accepted', 'Invoiced') AND " . reportRangeSql('quote_date', $period, true) . " $client_sql");
// Open right now, whenever quoted
$open = [];
$sql = mysqli_query($mysqli, "SELECT quote_id, quote_prefix, quote_number, quote_scope, quote_status, quote_date, quote_expire, quote_amount,
quote_client_id, client_name, client_abbreviation, DATEDIFF(quote_expire, CURDATE()) AS days_left, DATEDIFF(CURDATE(), quote_date) AS age
FROM quotes JOIN clients ON quote_client_id = client_id
WHERE quote_archived_at IS NULL AND quote_status IN ('Sent', 'Viewed') $client_sql
ORDER BY quote_expire IS NULL, quote_expire ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$open[] = $row;
}
$open_live = array_filter($open, function ($q) { return $q['quote_expire'] === null || intval($q['days_left']) >= 0; });
$open_expired = array_filter($open, function ($q) { return $q['quote_expire'] !== null && intval($q['days_left']) < 0; });
$expiring = array_filter($open_live, function ($q) { return $q['quote_expire'] !== null && intval($q['days_left']) <= 14; });
// By client, in the period
$clients = [];
$sql = mysqli_query($mysqli, "SELECT quote_client_id AS client_id, client_name, client_abbreviation, $outcome_sql AS outcome, COUNT(quote_id) AS n, SUM(quote_amount) AS v
FROM quotes JOIN clients ON quote_client_id = client_id
WHERE quote_archived_at IS NULL AND quote_status <> 'Draft' AND " . reportRangeSql('quote_date', $period) . " $client_sql
GROUP BY quote_client_id, client_name, client_abbreviation, outcome");
while ($row = mysqli_fetch_assoc($sql)) {
$id = intval($row['client_id']);
$clients[$id] = $clients[$id] ?? ['client_id' => $id, 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation'], 'quotes' => 0, 'quoted' => 0.0,
'won_n' => 0, 'won' => 0.0, 'lost_n' => 0, 'lost' => 0.0, 'open' => 0.0];
$clients[$id]['quotes'] += intval($row['n']);
$clients[$id]['quoted'] += floatval($row['v']);
if ($row['outcome'] === 'won') {
$clients[$id]['won_n'] += intval($row['n']);
$clients[$id]['won'] += floatval($row['v']);
} elseif ($row['outcome'] === 'lost') {
$clients[$id]['lost_n'] += intval($row['n']);
$clients[$id]['lost'] += floatval($row['v']);
} else {
$clients[$id]['open'] += floatval($row['v']);
}
}
foreach ($clients as &$row) {
$row['rate'] = reportShare($row['won_n'], $row['won_n'] + $row['lost_n']);
}
unset($row);
uasort($clients, function ($a, $b) { return $b['quoted'] <=> $a['quoted']; });
$clients = array_values($clients);
$quote_link = function ($row) {
return '<a class="font-monospace" href="/agent/quote.php?client_id=' . intval($row['quote_client_id']) . '&quote_id=' . intval($row['quote_id']) . '">' . escapeHtml($row['quote_prefix'] . $row['quote_number']) . '</a>';
};
$open_columns = [
'quote' => ['label' => 'Quote', 'csv' => function ($row) { return $row['quote_prefix'] . $row['quote_number']; }, 'html' => $quote_link],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['quote_client_id'], $row['client_name'], $row['client_abbreviation'], 'quotes.php');
}],
'quote_scope' => ['label' => 'Scope', 'class' => 'small itflow-report-text'],
'quote_status' => ['label' => 'Status', 'html' => function ($row) {
return '<span class="badge rounded-pill ' . ($row['quote_status'] === 'Viewed' ? 'text-bg-info' : 'text-bg-secondary') . '">' . escapeHtml($row['quote_status']) . '</span>';
}],
'quote_date' => ['label' => 'Quoted', 'type' => 'date', 'class' => 'text-nowrap'],
'quote_expire' => ['label' => 'Expires', 'type' => 'date', 'class' => 'text-nowrap', 'html' => function ($row) {
if ($row['quote_expire'] === null) {
return '<span class="text-body-secondary">No date</span>';
}
$left = intval($row['days_left']);
$date = escapeHtml(date('M j, Y', strtotime($row['quote_expire'])));
if ($left < 0) {
return '<span class="badge rounded-pill bg-danger-subtle text-danger-emphasis border border-danger-subtle fw-normal" title="' . $date . '">Expired ' . (-$left) . ' day' . ($left === -1 ? '' : 's') . ' ago</span>';
}
if ($left <= 14) {
return '<span class="badge rounded-pill bg-warning-subtle text-warning-emphasis border border-warning-subtle fw-normal" title="' . $date . '">' . ($left === 0 ? 'Today' : "In $left day" . ($left === 1 ? '' : 's')) . '</span>';
}
return $date;
}],
'age' => ['label' => 'Waiting', 'type' => 'count', 'csv_label' => 'Days waiting', 'html' => function ($row) {
return intval($row['age']) . ' day' . (intval($row['age']) === 1 ? '' : 's');
}],
'quote_amount' => ['label' => 'Amount', 'type' => 'money', 'class' => 'fw-semibold'],
];
$client_columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'quotes.php');
}],
'quotes' => ['label' => 'Quotes', 'type' => 'count'],
'quoted' => ['label' => 'Quoted', 'type' => 'money'],
'won' => ['label' => 'Won', 'type' => 'money', 'class' => 'text-success-emphasis'],
'lost' => ['label' => 'Lost', 'type' => 'money', 'class' => 'text-danger-emphasis'],
'open' => ['label' => 'Still open', 'type' => 'money', 'class' => 'text-body-secondary'],
'rate' => ['label' => 'Win rate', 'type' => 'percent', 'html' => function ($row) {
return reportRateHtml($row['rate'], 60, 35);
}],
];
if (reportExporting('clients')) {
reportCsv('Quotes by Client ' . $period['start'] . ' to ' . $period['end'], $client_columns, $clients);
}
if (reportExporting()) {
reportCsv('Open Quotes', $open_columns, $open, ['quote' => 'Total', 'quote_amount' => array_sum(array_column($open, 'quote_amount'))]);
}
$buckets = reportBuckets($period);
$series = [];
foreach (['won' => ['Won', 'success'], 'lost' => ['Lost', 'danger'], 'open' => ['Still open', 'info']] as $key => [$label, $tone]) {
$series[] = ['label' => $label, 'tone' => $tone, 'stack' => 'q', 'data' => reportSeries("SELECT " . reportBucketSql('quote_date', $buckets['unit']) . " AS b, SUM(quote_amount) AS v
FROM quotes WHERE quote_archived_at IS NULL AND $outcome_sql = '$key' AND " . reportRangeSql('quote_date', $period) . " $client_sql GROUP BY b", $buckets['keys'])];
}
require_once "includes/inc_report_layout.php";
?>
<div class="itflow-report">
<?php reportHeader('quote_pipeline', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(quote_date) AS y FROM quotes"),
'client' => $client_id,
'export' => ['open' => 'Open quotes', 'clients' => 'By client'],
]); ?>
<?= reportStats([
['label' => 'Quoted', 'value' => reportMoney($quoted_v), 'sub' => reportCount($quoted_n) . ' <span class="text-body-tertiary">quote' . ($quoted_n === 1 ? '' : 's') . ' sent' . ($by['draft']['n'] ? ', ' . $by['draft']['n'] . ' still drafts' : '') . '</span>'],
['label' => 'Won', 'value' => reportMoney($by['won']['v']), 'tone' => $by['won']['v'] > 0 ? 'success' : '', 'sub' => reportChangeHtml($by['won']['v'], $prev_won, 'up', $period['compare'])],
['label' => 'Win rate', 'value' => reportPercent($win_rate), 'sub' => $win_rate_value !== null ? escapeHtml(reportPercent($win_rate_value)) . ' <span class="text-body-tertiary">by value, of quotes decided</span>' : '<span class="text-body-tertiary">No quote decided yet</span>'],
['label' => 'Open now', 'value' => reportMoney(array_sum(array_column($open_live, 'quote_amount'))), 'url' => '/agent/quotes.php',
'sub' => count($expiring) ? '<span class="text-warning-emphasis fw-semibold">' . count($expiring) . ' expire within 14 days</span>' : reportCount(count($open_live)) . ' <span class="text-body-tertiary">waiting for an answer</span>'],
]) ?>
<?= reportSectionOpen('Quoted, by how it went', escapeHtml($period['range'])) ?>
<div class="card-body">
<?= reportChart(['type' => 'bar', 'labels' => $buckets['labels'], 'series' => $series, 'stacked' => true, 'format' => 'money'], '', 'Value quoted over the period, won, lost and still open') ?>
</div>
</div>
<?= reportSectionOpen('Waiting for an answer', count($open_expired) ? '<span class="text-danger-emphasis">' . count($open_expired) . ' past their expiry date - follow up or close them</span>' : 'Soonest to expire first') ?>
<?= reportTable($open_columns, $open, [
'empty' => reportEmpty('No quote is waiting for an answer.'),
'limit' => 300, 'export_table' => 'open',
'totals' => ['quote' => 'Total', 'quote_amount' => array_sum(array_column($open, 'quote_amount'))],
]) ?>
</div>
<?= reportSectionOpen('By client', escapeHtml($period['range'])) ?>
<?= reportTable($client_columns, $clients, [
'empty' => 'No quotes went out in this period.',
'totals' => ['client' => 'Total', 'quotes' => $quoted_n, 'quoted' => $quoted_v, 'won' => $by['won']['v'], 'lost' => $by['lost']['v'], 'open' => $by['open']['v'], 'rate' => $win_rate],
'totals_html' => ['rate' => reportRateHtml($win_rate, 60, 35)],
]) ?>
<div class="card-footer small text-body-secondary">
By quote date. Won is accepted or invoiced, lost is declined, open is sent or viewed and not yet answered. The win rate counts only quotes that have been decided.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,68 +1,199 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Recurring Revenue - what active recurring invoices bring in, as monthly
* recurring revenue (a yearly invoice counts a twelfth a month) and a year
* of it: per client, per income category, and every recurring invoice with
* when it next bills. With financial access, recurring expenses come off it
* for what is left each month. The same figure as the dashboard's
* Recurring revenue.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('recurring_by_client');
$sql = mysqli_query($mysqli, "
SELECT client_id, client_name,
SUM(CASE WHEN recurring_invoice_frequency = 'month' THEN recurring_invoice_amount
WHEN recurring_invoice_frequency = 'year' THEN recurring_invoice_amount / 12 END) AS recurring_monthly_total
FROM clients
LEFT JOIN recurring_invoices ON client_id = recurring_invoice_client_id
WHERE recurring_invoice_status = 1
" . clientScopeSql('clients.client_id') . "
GROUP BY clients.client_id
HAVING recurring_monthly_total > 0
ORDER BY recurring_monthly_total DESC
");
$client_id = reportClientId();
$can_see_costs = reportPermission('module_financial') >= 1;
$invoices = [];
$sql = mysqli_query($mysqli, "SELECT recurring_invoice_id, recurring_invoice_prefix, recurring_invoice_number, recurring_invoice_scope, recurring_invoice_frequency,
recurring_invoice_next_date, recurring_invoice_amount, recurring_invoice_auto_send, recurring_invoice_created_at,
recurring_invoice_client_id, client_name, client_abbreviation, category_name, category_id
FROM recurring_invoices
JOIN clients ON recurring_invoice_client_id = client_id
LEFT JOIN categories ON recurring_invoice_category_id = category_id
WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL
" . reportClientSql('recurring_invoice_client_id', $client_id) . "
ORDER BY client_name ASC, recurring_invoice_next_date ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$amount = floatval($row['recurring_invoice_amount']);
$row['monthly'] = $row['recurring_invoice_frequency'] === 'year' ? $amount / 12 : $amount;
$invoices[] = $row;
}
$clients = [];
$categories = [];
foreach ($invoices as $invoice) {
$id = intval($invoice['recurring_invoice_client_id']);
$clients[$id] = $clients[$id] ?? ['client_id' => $id, 'client' => $invoice['client_name'], 'abbr' => $invoice['client_abbreviation'],
'count' => 0, 'mrr' => 0.0, 'next' => null, 'since' => null];
$clients[$id]['count']++;
$clients[$id]['mrr'] += $invoice['monthly'];
$clients[$id]['next'] = $clients[$id]['next'] === null ? $invoice['recurring_invoice_next_date'] : min($clients[$id]['next'], $invoice['recurring_invoice_next_date']);
$since = substr($invoice['recurring_invoice_created_at'], 0, 10);
$clients[$id]['since'] = $clients[$id]['since'] === null ? $since : min($clients[$id]['since'], $since);
$cat = $invoice['category_name'] ?? 'No category';
$categories[$cat] = ($categories[$cat] ?? 0) + $invoice['monthly'];
}
$mrr = array_sum(array_column($clients, 'mrr'));
foreach ($clients as &$row) {
$row['arr'] = $row['mrr'] * 12;
$row['share'] = reportShare($row['mrr'], $mrr, 1);
}
unset($row);
uasort($clients, function ($a, $b) { return $b['mrr'] <=> $a['mrr']; });
$clients = array_values($clients);
$client_columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'recurring_invoices.php');
}],
'count' => ['label' => 'Recurring invoices', 'type' => 'count'],
'mrr' => ['label' => 'Per month', 'type' => 'money', 'class' => 'fw-semibold'],
'arr' => ['label' => 'Per year', 'type' => 'money', 'class' => 'text-body-secondary'],
'share' => ['label' => 'Share', 'type' => 'percent', 'html' => function ($row) {
return '<div class="d-flex align-items-center justify-content-end gap-2"><div class="itflow-report-meter d-none d-lg-flex" style="width: 5rem"><span style="width: ' . min(100, floatval($row['share'])) . '%"></span></div>'
. '<span class="small text-body-secondary">' . reportPercent($row['share']) . '</span></div>';
}],
'next' => ['label' => 'Next bills', 'type' => 'date', 'class' => 'text-nowrap'],
'since' => ['label' => 'Recurring since', 'type' => 'date', 'class' => 'text-nowrap text-body-secondary'],
];
$invoice_columns = [
'number' => ['label' => 'Recurring invoice', 'csv' => function ($row) { return $row['recurring_invoice_prefix'] . $row['recurring_invoice_number']; }, 'html' => function ($row) {
return '<a class="font-monospace" href="/agent/recurring_invoice.php?client_id=' . intval($row['recurring_invoice_client_id']) . '&recurring_invoice_id=' . intval($row['recurring_invoice_id']) . '">' . escapeHtml($row['recurring_invoice_prefix'] . $row['recurring_invoice_number']) . '</a>';
}],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['recurring_invoice_client_id'], $row['client_name'], $row['client_abbreviation'], 'recurring_invoices.php');
}],
'recurring_invoice_scope' => ['label' => 'Scope', 'class' => 'small itflow-report-text'],
'category_name' => ['label' => 'Category', 'class' => 'small text-body-secondary'],
'recurring_invoice_frequency' => ['label' => 'Every', 'csv' => function ($row) { return $row['recurring_invoice_frequency'] === 'year' ? 'Year' : 'Month'; }, 'html' => function ($row) {
return $row['recurring_invoice_frequency'] === 'year' ? 'Year' : 'Month';
}],
'recurring_invoice_amount' => ['label' => 'Amount', 'type' => 'money'],
'monthly' => ['label' => 'Per month', 'type' => 'money', 'class' => 'fw-semibold'],
'recurring_invoice_next_date' => ['label' => 'Next bills', 'type' => 'date', 'class' => 'text-nowrap'],
'auto' => ['label' => 'Sends', 'csv' => function ($row) { return intval($row['recurring_invoice_auto_send']) ? 'Automatically' : 'Draft for review'; }, 'html' => function ($row) {
return intval($row['recurring_invoice_auto_send']) ? '<span class="small text-body-secondary">Automatically</span>' : '<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis fw-normal">Draft first</span>';
}],
];
if (reportExporting('invoices')) {
reportCsv('Recurring Invoices', $invoice_columns, $invoices, ['number' => 'Total', 'monthly' => $mrr]);
}
if (reportExporting()) {
reportCsv('Recurring Revenue by Client', $client_columns, $clients, ['client' => 'Total', 'count' => count($invoices), 'mrr' => $mrr, 'arr' => $mrr * 12]);
}
// What comes off it every month
$costs = 0.0;
if ($can_see_costs && !$client_id) {
$costs = dashboardSum("SELECT SUM(recurring_expense_amount) FROM recurring_expenses WHERE recurring_expense_status = 1 AND recurring_expense_archived_at IS NULL AND recurring_expense_vendor_id > 0 AND recurring_expense_frequency = 1")
+ dashboardSum("SELECT SUM(recurring_expense_amount) FROM recurring_expenses WHERE recurring_expense_status = 1 AND recurring_expense_archived_at IS NULL AND recurring_expense_vendor_id > 0 AND recurring_expense_frequency = 2") / 12;
}
// What bills in the next 30 days
$next_30 = 0.0;
$limit = date('Y-m-d', strtotime('+30 days'));
foreach ($invoices as $invoice) {
if ($invoice['recurring_invoice_next_date'] <= $limit) {
$next_30 += floatval($invoice['recurring_invoice_amount']);
}
}
require_once "includes/inc_report_layout.php";
arsort($categories);
$cat_rows = reportTopN(array_map(function ($label, $value) { return ['label' => $label, 'value' => $value]; }, array_keys($categories), array_values($categories)), 6);
$cat_colors = array_map(function ($i) { return reportPalette($i); }, array_keys($cat_rows));
foreach ($cat_rows as $i => $row) {
if ($row['label'] === 'Other') {
$cat_colors[$i] = 'faint';
}
}
$stats = [
['label' => 'Recurring revenue', 'value' => reportMoney($mrr), 'sub' => '<span class="text-body-tertiary">Per month</span>', 'url' => '/agent/recurring_invoices.php'],
['label' => 'A year of it', 'value' => reportMoney($mrr * 12), 'sub' => '<span class="text-body-tertiary">At today\'s recurring invoices</span>'],
['label' => 'Recurring invoices', 'value' => reportCount(count($invoices)), 'sub' => reportCount(count($clients)) . ' <span class="text-body-tertiary">client' . (count($clients) === 1 ? '' : 's') . ', ' . (count($clients) ? escapeHtml(reportMoney($mrr / count($clients))) : '-') . ' each a month</span>'],
];
if ($can_see_costs && !$client_id) {
$stats[] = ['label' => 'After recurring expenses', 'value' => reportMoney($mrr - $costs), 'tone' => $mrr - $costs < 0 ? 'danger' : '',
'sub' => escapeHtml(reportMoney($costs)) . ' <span class="text-body-tertiary">a month goes out</span>', 'url' => '/agent/recurring_expenses.php'];
} else {
$stats[] = ['label' => 'Bills in the next 30 days', 'value' => reportMoney($next_30), 'sub' => '<span class="text-body-tertiary">From these recurring invoices</span>'];
}
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-sync me-2"></i>Recurring Income By Client</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('recurring_by_client', [
'client' => $client_id,
'subtitle' => 'As of ' . date('M j, Y'),
'export' => ['clients' => 'By client', 'invoices' => 'Every recurring invoice'],
]); ?>
<?= reportStats($stats) ?>
<?php if ($invoices) { ?>
<div class="row g-3">
<div class="col-lg-4">
<?= reportSectionOpen('By category', 'Per month', 'h-100 mb-0') ?>
<div class="card-body">
<?= reportChart([
'type' => 'doughnut',
'labels' => array_column($cat_rows, 'label'),
'series' => [['label' => 'Per month', 'data' => array_map(function ($r) { return round($r['value'], 2); }, $cat_rows)]],
'colors' => $cat_colors,
'format' => 'money',
], 'donut', 'Recurring revenue by category') ?>
<div class="mt-3"><?= reportLegendHtml(array_column($cat_rows, 'label'), array_column($cat_rows, 'value'), $cat_colors) ?></div>
</div>
</div>
</div>
<div class="col-lg-8">
<?php $top = array_slice($clients, 0, 12); ?>
<?= reportSectionOpen('Biggest recurring clients', 'Per month', 'h-100 mb-0') ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_map(function ($c) { return $c['client']; }, $top),
'series' => [['label' => 'Per month', 'data' => array_map(function ($c) { return round($c['mrr'], 2); }, $top), 'tone' => 'accent']],
'format' => 'money',
'legend' => false,
], '', 'Recurring revenue per month for the biggest clients') ?>
</div>
</div>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By client', 'Most per month first') ?>
<?= reportTable($client_columns, $clients, [
'empty' => 'No active recurring invoices.',
'totals' => ['client' => 'Total', 'count' => count($invoices), 'mrr' => $mrr, 'arr' => $mrr * 12],
]) ?>
</div>
<?= reportSectionOpen('Every recurring invoice', reportCount(count($invoices)) . ' active', 'itflow-report-long') ?>
<?= reportTable($invoice_columns, $invoices, ['empty' => 'No active recurring invoices.', 'limit' => 300, 'export_table' => 'invoices', 'totals' => ['number' => 'Total', 'monthly' => $mrr]]) ?>
<div class="card-footer small text-body-secondary">
Active recurring invoices only. A yearly invoice counts a twelfth of its amount each month.
</div>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Monthly Recurring</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$recurring_monthly_total = floatval($row['recurring_monthly_total']);
$recurring_total = $recurring_total + $recurring_monthly_total;
?>
<tr>
<td><a href="../../agent/client_overview.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
<td class="text-end"><?= numfmt_format_currency($currency_format, $recurring_monthly_total, $session_company_currency) ?></td>
</tr>
<?php
}
?>
<tr>
<th>Total Monthly Income</th>
<th class="text-end"><?= numfmt_format_currency($currency_format, $recurring_total, $session_company_currency) ?></th>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<?php require_once "../../includes/footer.php";
?>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

166
agent/reports/renewals.php Normal file
View File

@@ -0,0 +1,166 @@
<?php
/*
* Renewals & Expirations - domains, certificates, licenses and hardware
* warranties falling due in the window ahead, and any that lapsed in the last
* 90 days, soonest first: when, by month, by client and one by one. Domains
* on auto-renew and short-lived certificates (which renew themselves) show in
* blue and can be hidden, leaving what someone has to act on.
*/
require_once "includes/inc_report.php";
reportEnforce('renewals');
$windows = ['30' => 'Next 30 days', '60' => 'Next 60 days', '90' => 'Next 90 days', '180' => 'Next 6 months', '365' => 'Next 12 months'];
$ahead = isset($windows[$_GET['window'] ?? '']) ? intval($_GET['window']) : 90;
$kind = isset(REPORT_RENEWAL_KINDS[$_GET['kind'] ?? '']) ? $_GET['kind'] : '';
$manual_only = !empty($_GET['manual']);
$client_id = reportClientId();
$all = reportRenewals($client_id, $ahead, $kind ? [$kind] : []);
$items = $manual_only ? array_values(array_filter($all, function ($r) { return !$r['auto']; })) : $all;
$lapsed = array_filter($items, function ($r) { return $r['days'] < 0; });
$soon = array_filter($items, function ($r) { return $r['days'] >= 0 && $r['days'] <= 30; });
$auto = array_filter($all, function ($r) { return $r['auto'] && $r['days'] >= 0; });
$ahead_items = array_filter($items, function ($r) { return $r['days'] >= 0; });
// By client
$kind_keys = $kind ? [$kind] : array_keys(REPORT_RENEWAL_KINDS);
$by_client = [];
foreach ($items as $item) {
$c = $item['client_id'];
$by_client[$c] = $by_client[$c] ?? ['client_id' => $c, 'client' => $item['client'], 'abbr' => $item['abbr'], 'lapsed' => 0, 'soon' => 0, 'total' => 0] + array_fill_keys($kind_keys, 0);
$by_client[$c][$item['kind']]++;
$by_client[$c]['total']++;
$by_client[$c]['lapsed'] += $item['days'] < 0 ? 1 : 0;
$by_client[$c]['soon'] += $item['days'] >= 0 && $item['days'] <= 30 ? 1 : 0;
}
usort($by_client, function ($a, $b) {
return $b['lapsed'] <=> $a['lapsed'] ?: $b['soon'] <=> $a['soon'] ?: $b['total'] <=> $a['total'];
});
$count_cell = function ($key, $tone = '') {
return function ($row) use ($key, $tone) {
return $row[$key] ? '<span class="' . $tone . '">' . $row[$key] . '</span>' : '<span class="itflow-report-zero">–</span>';
};
};
$client_columns = ['client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr']);
}]];
foreach ($kind_keys as $key) {
$client_columns[$key] = ['label' => REPORT_RENEWAL_KINDS[$key]['label'], 'type' => 'count', 'html' => $count_cell($key)];
}
$client_columns += [
'lapsed' => ['label' => 'Lapsed', 'type' => 'count', 'html' => $count_cell('lapsed', 'text-danger-emphasis fw-semibold')],
'soon' => ['label' => 'Next 30 days', 'type' => 'count', 'html' => $count_cell('soon', 'text-warning-emphasis fw-semibold')],
'total' => ['label' => 'Total', 'type' => 'count', 'class' => 'fw-semibold'],
];
$item_columns = [
'days' => ['label' => 'Due', 'type' => 'count', 'csv_label' => 'Days until due', 'html' => function ($row) {
return reportDuePill($row['days'], $row['auto']);
}],
'name' => ['label' => 'What', 'class' => 'itflow-report-text', 'html' => function ($row) {
return '<div class="d-flex align-items-center gap-2">' . $row['tile'] . '<div class="min-w-0"><a class="fw-semibold text-body" href="' . escapeHtml($row['url']) . '">' . escapeHtml($row['name']) . '</a>'
. ($row['detail'] !== '' ? '<div class="small text-body-secondary">' . escapeHtml($row['detail']) . '</div>' : '') . '</div></div>';
}],
'kind' => ['label' => 'Type', 'csv' => function ($row) { return REPORT_RENEWAL_KINDS[$row['kind']]['one']; }, 'html' => function ($row) {
return '<span class="text-nowrap">' . REPORT_RENEWAL_KINDS[$row['kind']]['one'] . '</span>';
}],
'detail' => ['label' => 'Detail', 'screen' => false],
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr']);
}],
'date' => ['label' => 'Date', 'type' => 'date'],
'auto' => ['label' => 'Renews itself', 'screen' => false, 'csv' => function ($row) { return $row['auto'] ? 'Yes' : 'No'; }],
];
if (reportExporting('clients')) {
reportCsv('Renewals by Client', $client_columns, $by_client);
}
if (reportExporting()) {
reportCsv('Renewals', $item_columns, $items);
}
require_once "includes/inc_report_layout.php";
// By month: lapsed first, then each month from this one to the end of the window
$months = ['lapsed' => 'Lapsed'];
$cursor = new DateTime('first day of this month');
$last = (new DateTime('today'))->modify("+$ahead days");
while ($cursor <= $last) {
$months[$cursor->format('Y-m')] = $cursor->format('M y');
$cursor->modify('+1 month');
}
$series = [];
foreach ($kind_keys as $key) {
$counts = array_fill_keys(array_keys($months), 0);
foreach ($items as $item) {
if ($item['kind'] === $key) {
$counts[$item['days'] < 0 ? 'lapsed' : substr($item['date'], 0, 7)]++;
}
}
$series[] = ['label' => REPORT_RENEWAL_KINDS[$key]['label'], 'data' => array_values($counts), 'tone' => REPORT_RENEWAL_KINDS[$key]['tone'], 'stack' => 'due'];
}
$clients_affected = count(array_unique(array_column($items, 'client_id')));
$kind_choices = ['' => 'Everything'];
foreach (REPORT_RENEWAL_KINDS as $key => $meta) {
$kind_choices[$key] = $meta['label'];
}
?>
<div class="itflow-report">
<?php reportHeader('renewals', [
'subtitle' => $windows[$ahead],
'controls' => reportSelectControl('window', $ahead, $windows, 'fa-calendar-alt')
. reportClientControl($client_id)
. reportSelectControl('kind', $kind, $kind_choices, 'fa-filter')
. reportSwitchControl('manual', $manual_only, 'Hide ones that renew themselves'),
'export' => ['items' => 'Every renewal', 'clients' => 'By client'],
]); ?>
<?= reportStats([
['label' => 'Lapsed', 'value' => reportCount(count($lapsed)), 'tone' => $lapsed ? 'danger' : 'success', 'sub' => '<span class="text-body-tertiary">In the last ' . REPORT_RENEWAL_LAPSED_DAYS . ' days</span>'],
['label' => 'Due in 30 days', 'value' => reportCount(count($soon)), 'tone' => $soon ? 'warning' : '',
'sub' => reportCount(count(array_filter($soon, function ($r) { return $r['days'] <= 7; }))) . ' <span class="text-body-tertiary">this week</span>'],
['label' => 'Due in the window', 'value' => reportCount(count($ahead_items)), 'sub' => reportCount($clients_affected) . ' <span class="text-body-tertiary">' . ($clients_affected === 1 ? 'client' : 'clients') . '</span>'],
['label' => 'Renew themselves', 'value' => reportCount(count($auto)), 'tone' => $auto ? 'info' : '',
'title' => 'Domains on auto-renew and short-lived certificates', 'sub' => '<span class="text-body-tertiary">' . ($manual_only ? 'Hidden below' : 'Auto-renew and short-lived') . '</span>'],
]) ?>
<?php if (!$items) { ?>
<div class="card"><div class="card-body"><?= reportEmpty('Nothing comes up for renewal in this window, and nothing has lapsed lately.') ?></div></div>
<?php } else { ?>
<?= reportSectionOpen('When they fall due', 'By month') ?>
<div class="card-body">
<?= reportChart(['type' => 'bar', 'labels' => array_values($months), 'series' => $series, 'stacked' => true, 'format' => 'count', 'legend' => count($series) > 1],
'', 'Renewals falling due by month') ?>
</div>
</div>
<?php if (!$client_id && count($by_client) > 1) { ?>
<?= reportSectionOpen('By client', 'The most lapsed and soonest first') ?>
<?= reportTable($client_columns, $by_client, ['limit' => 50, 'export_table' => 'clients']) ?>
</div>
<?php } ?>
<?= reportSectionOpen('Every renewal', 'Soonest first', 'itflow-report-long') ?>
<?= reportTable($item_columns, $items, ['limit' => 300, 'export_table' => 'items']) ?>
<div class="card-footer small text-body-secondary">
Domains, certificates and licenses by their expiry date, hardware by its warranty end. Lapsed shows the last <?= REPORT_RENEWAL_LAPSED_DAYS ?> days;
older ones are on each list's Expired view. Archived items, archived clients and assets that are lost, stolen or retired are left out.
Blue ones renew themselves: domains set to auto-renew and short-lived certificates.
</div>
</div>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -0,0 +1,294 @@
<?php
/*
* Customer Satisfaction - how contacts rated their tickets once closed (the
* Good / Bad buttons in the client portal), for tickets closed in the period:
* the share rated good, how many get rated at all, the trend, by agent and by
* client, what the rating follows (a late first reply, a slow fix) and every
* bad rating so someone can follow up.
*/
require_once "includes/inc_report.php";
reportEnforce('satisfaction');
$period = reportPeriod('last_90');
$client_id = reportClientId();
$agent_id = reportAgentId();
$closed_sql = reportTicketSql($client_id, $agent_id) . " AND tickets.ticket_closed_at IS NOT NULL";
$filter = $closed_sql . " AND " . reportRangeSql('tickets.ticket_closed_at', $period);
const SATISFACTION_COLUMNS = "COUNT(tickets.ticket_id) AS closed,
SUM(tickets.ticket_feedback IS NOT NULL AND tickets.ticket_feedback != '') AS rated,
SUM(tickets.ticket_feedback = 'Good') AS good, SUM(tickets.ticket_feedback = 'Bad') AS bad";
/** Counts and shares from a row of SATISFACTION_COLUMNS. */
function satisfactionFigures($row) {
$out = [];
foreach (['closed', 'rated', 'good', 'bad'] as $key) {
$out[$key] = intval($row[$key] ?? 0);
}
$out['score'] = reportShare($out['good'], $out['good'] + $out['bad'], 1);
$out['rated_percent'] = reportShare($out['rated'], $out['closed'], 1);
return $out;
}
$grouped = function ($group_sql, $where, $join = '') {
global $mysqli;
$rows = [];
$sql = mysqli_query($mysqli, "SELECT $group_sql AS k, " . SATISFACTION_COLUMNS . " FROM tickets $join WHERE $where GROUP BY k");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[(string) $row['k']] = satisfactionFigures($row);
}
return $rows;
};
$overall = satisfactionFigures(mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT " . SATISFACTION_COLUMNS . " FROM tickets WHERE $filter")));
$previous = satisfactionFigures(mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT " . SATISFACTION_COLUMNS . " FROM tickets
WHERE $closed_sql AND " . reportRangeSql('tickets.ticket_closed_at', $period, true))));
$other = $overall['rated'] - $overall['good'] - $overall['bad'];
// Over the period - a day's two or three ratings make a jumpy line, so weeks at the least
$buckets = reportBuckets($period);
if ($buckets['unit'] === 'day') {
$buckets = reportBuckets(['start' => $period['start'], 'end' => $period['end'], 'days' => 60]);
}
$by_bucket = $grouped(reportBucketSql('tickets.ticket_closed_at', $buckets['unit']), $filter);
// By agent
$names = [];
$sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar FROM users WHERE user_type = 1");
while ($row = mysqli_fetch_assoc($sql)) {
$names[intval($row['user_id'])] = $row;
}
$agent_rows = [];
foreach ($grouped('tickets.ticket_assigned_to', $filter) as $user_id => $figures) {
$user_id = intval($user_id);
$agent_rows[] = ['user_id' => $user_id, 'agent' => $names[$user_id]['user_name'] ?? '', 'avatar' => $names[$user_id]['user_avatar'] ?? ''] + $figures;
}
usort($agent_rows, function ($a, $b) { return $b['rated'] <=> $a['rated'] ?: $b['closed'] <=> $a['closed']; });
// By client - the most bad ratings first, as those are the calls to make
$client_rows = [];
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, " . SATISFACTION_COLUMNS . "
FROM tickets JOIN clients ON tickets.ticket_client_id = client_id WHERE $filter GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$client_rows[] = ['client_id' => intval($row['client_id']), 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation']] + satisfactionFigures($row);
}
usort($client_rows, function ($a, $b) {
return $b['bad'] <=> $a['bad'] ?: ($a['score'] ?? 101) <=> ($b['score'] ?? 101) ?: $b['rated'] <=> $a['rated'];
});
// What the rating follows - the first reply against its SLA, and how long the fix took
$drivers = [];
$reply = $grouped('tickets.ticket_response_sla_met', $filter . " AND tickets.ticket_sla_id > 0");
foreach (['1' => 'First reply in time', '0' => 'First reply late'] as $key => $label) {
if (isset($reply[$key])) {
$drivers[] = ['label' => $label, 'group' => 'First reply against the SLA'] + $reply[$key];
}
}
$fix = $grouped("CASE WHEN tickets.ticket_resolved_at IS NULL THEN 'none'
WHEN TIMESTAMPDIFF(HOUR, tickets.ticket_created_at, tickets.ticket_resolved_at) < 24 THEN 'day'
WHEN TIMESTAMPDIFF(HOUR, tickets.ticket_created_at, tickets.ticket_resolved_at) < 72 THEN 'three'
WHEN TIMESTAMPDIFF(HOUR, tickets.ticket_created_at, tickets.ticket_resolved_at) < 168 THEN 'week' ELSE 'longer' END", $filter);
foreach (['day' => 'Resolved within a day', 'three' => 'Resolved in 1 to 3 days', 'week' => 'Resolved in 3 to 7 days', 'longer' => 'Resolved after a week'] as $key => $label) {
if (isset($fix[$key])) {
$drivers[] = ['label' => $label, 'group' => 'Time to resolve'] + $fix[$key];
}
}
$driver_rows = [];
foreach ($drivers as $driver) {
if (!$driver_rows || end($driver_rows)['group'] !== $driver['group']) {
$driver_rows[] = ['_heading' => $driver['group'], 'group' => $driver['group']];
}
$driver_rows[] = $driver;
}
// Every bad rating, newest first
$bad_rows = [];
$sql = mysqli_query($mysqli, "SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_client_id, ticket_assigned_to,
ticket_created_at, ticket_first_response_at, ticket_resolved_at, ticket_closed_at, ticket_sla_id, ticket_response_sla_met, ticket_resolution_sla_met,
client_name, client_abbreviation, contact_name, user_name, user_avatar,
TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) AS reply_seconds,
TIMESTAMPDIFF(SECOND, ticket_created_at, COALESCE(ticket_resolved_at, ticket_closed_at)) AS resolve_seconds,
(SELECT SUM(TIME_TO_SEC(ticket_reply_time_worked)) FROM ticket_replies WHERE ticket_reply_ticket_id = tickets.ticket_id AND ticket_reply_archived_at IS NULL) AS worked_seconds
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
WHERE $filter AND tickets.ticket_feedback = 'Bad'
ORDER BY ticket_closed_at DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$bad_rows[] = $row;
}
$figure_columns = [
'closed' => ['label' => 'Closed', 'type' => 'count'],
'rated' => ['label' => 'Rated', 'type' => 'count'],
'rated_percent' => ['label' => 'Rated share', 'type' => 'percent', 'class' => 'text-body-secondary', 'title' => 'Closed tickets the contact rated'],
'good' => ['label' => 'Good', 'type' => 'count'],
'bad' => ['label' => 'Bad', 'type' => 'count', 'html' => function ($row) {
return $row['bad'] ? '<span class="text-danger-emphasis fw-semibold">' . $row['bad'] . '</span>' : '<span class="itflow-report-zero">–</span>';
}],
'score' => ['label' => 'Satisfaction', 'type' => 'percent', 'title' => 'Good ratings, of the good and bad', 'html' => function ($row) {
return reportRateHtml($row['score']);
}],
];
$agent_columns = ['agent' => ['label' => 'Assigned to', 'csv' => function ($row) { return $row['user_id'] ? $row['agent'] : 'Unassigned'; }, 'html' => function ($row) {
return formatAssignee($row['user_id'], $row['agent'], $row['avatar'], true);
}]] + $figure_columns;
$client_columns = ['client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'tickets.php');
}]] + $figure_columns;
$driver_columns = [
'label' => ['label' => 'How the ticket went', 'sort' => false],
'rated' => ['label' => 'Rated', 'type' => 'count', 'sort' => false],
'good' => ['label' => 'Good', 'type' => 'count', 'sort' => false],
'bad' => $figure_columns['bad'] + ['sort' => false],
'score' => $figure_columns['score'] + ['sort' => false],
'meter' => ['label' => '', 'sort' => false, 'csv' => false, 'class' => 'w-25', 'html' => function ($row) {
return $row['score'] === null ? '' : '<div class="progress itflow-report-meter" role="presentation"><div class="progress-bar bg-success" style="width: ' . round($row['score']) . '%"></div>'
. '<div class="progress-bar bg-danger" style="width: ' . (100 - round($row['score'])) . '%"></div></div>';
}],
];
$bad_columns = [
'ticket' => ['label' => 'Ticket', 'class' => 'itflow-report-text', 'csv' => function ($row) { return ticketReference($row) . ' ' . $row['ticket_subject']; }, 'html' => function ($row) {
return reportPriorityDot($row['ticket_priority']) . reportTicketLink($row);
}],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['ticket_client_id'], $row['client_name'] ?? '', $row['client_abbreviation'] ?? '');
}],
'contact_name' => ['label' => 'Rated by', 'html' => function ($row) {
return $row['contact_name'] ? '<span class="text-nowrap">' . escapeHtml($row['contact_name']) . '</span>' : '<span class="text-body-tertiary">-</span>';
}],
'user_name' => ['label' => 'Assigned to', 'csv' => function ($row) { return $row['user_name'] ?: 'Unassigned'; }, 'html' => function ($row) {
return formatAssignee($row['ticket_assigned_to'], $row['user_name'] ?? '', $row['user_avatar'] ?? '', true);
}],
'reply_seconds' => ['label' => 'First reply', 'type' => 'duration', 'html' => function ($row) {
if ($row['reply_seconds'] === null) {
return '<span class="text-body-tertiary">-</span>';
}
$late = $row['ticket_response_sla_met'] !== null && intval($row['ticket_response_sla_met']) === 0;
return '<span class="' . ($late ? 'text-danger-emphasis fw-semibold' : '') . '"' . ($late ? ' title="Missed the response target"' : '') . '>'
. reportDuration($row['reply_seconds']) . ($late ? ' <i class="fas fa-fw fa-exclamation-circle small"></i>' : '') . '</span>';
}],
'resolve_seconds' => ['label' => 'To resolve', 'type' => 'duration', 'html' => function ($row) {
$late = $row['ticket_resolution_sla_met'] !== null && intval($row['ticket_resolution_sla_met']) === 0;
return '<span class="' . ($late ? 'text-danger-emphasis fw-semibold' : '') . '"' . ($late ? ' title="Missed the resolution target"' : '') . '>'
. reportDuration($row['resolve_seconds']) . ($late ? ' <i class="fas fa-fw fa-exclamation-circle small"></i>' : '') . '</span>';
}],
'worked_seconds' => ['label' => 'Time logged', 'type' => 'hours', 'decimals' => 1],
'ticket_closed_at' => ['label' => 'Closed', 'type' => 'date'],
];
$month_columns = ['when' => ['label' => ucfirst($buckets['unit']), 'sort' => false]] + $figure_columns;
$month_rows = [];
foreach ($buckets['keys'] as $i => $key) {
if (isset($by_bucket[$key])) {
$month_rows[] = ['when' => $buckets['labels'][$i]] + $by_bucket[$key];
}
}
if (reportExporting('agents')) {
reportCsv('Satisfaction by Agent', $agent_columns, $agent_rows, ['agent' => 'Total'] + $overall);
}
if (reportExporting('clients')) {
reportCsv('Satisfaction by Client', $client_columns, $client_rows, ['client' => 'Total'] + $overall);
}
if (reportExporting('bad')) {
reportCsv('Bad Ratings', $bad_columns, $bad_rows);
}
if (reportExporting()) {
reportCsv('Satisfaction by ' . ucfirst($buckets['unit']), $month_columns, $month_rows, ['when' => 'Total'] + $overall);
}
require_once "includes/inc_report_layout.php";
$bad_clients = count(array_unique(array_column($bad_rows, 'ticket_client_id')));
$was = function ($value) use ($period) {
return $value === null ? '' : 'Was <span class="text-body">' . reportPercent($value) . '</span> <span class="text-body-tertiary">' . escapeHtml($period['compare']) . '</span>';
};
?>
<div class="itflow-report">
<?php reportHeader('satisfaction', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_closed_at) AS y FROM tickets WHERE ticket_feedback IS NOT NULL AND ticket_closed_at IS NOT NULL"),
'client' => $client_id,
'agent' => $agent_id,
'export' => ['months' => 'By ' . $buckets['unit'], 'agents' => 'By agent', 'clients' => 'By client', 'bad' => 'Bad ratings'],
]); ?>
<?= reportStats([
['label' => 'Satisfaction', 'value_html' => reportRateHtml($overall['score']), 'title' => 'Good ratings, of the good and bad', 'sub' => $was($previous['score'])],
['label' => 'Ratings', 'value' => reportCount($overall['rated']),
'sub' => $overall['closed'] ? reportPercent($overall['rated_percent']) . ' <span class="text-body-tertiary">of ' . reportCount($overall['closed']) . ' closed tickets</span>' : ''],
['label' => 'Rated good', 'value' => reportCount($overall['good']), 'tone' => $overall['good'] ? 'success' : '',
'sub' => $previous['rated'] ? reportChangeHtml($overall['good'], $previous['good'], 'up', $period['compare']) : ''],
['label' => 'Rated bad', 'value' => reportCount($overall['bad']), 'tone' => $overall['bad'] ? 'danger' : 'success',
'sub' => $overall['bad'] ? reportCount($bad_clients) . ' <span class="text-body-tertiary">' . ($bad_clients === 1 ? 'client' : 'clients') . ' to follow up</span>' : '<span class="text-body-tertiary">Nothing to follow up</span>'],
]) ?>
<?php if (!$overall['rated']) { ?>
<div class="card"><div class="card-body">
<?= reportEmpty('No ticket closed in this period was rated. Contacts rate a ticket Good or Bad in the client portal once it is closed.', 'fa-smile', 'secondary') ?>
</div></div>
<?php } else { ?>
<?= reportSectionOpen('Ratings over the period', 'Bars are ratings, the line the share rated good') ?>
<div class="card-body">
<?php
$keys = $buckets['keys'];
echo reportChart([
'type' => 'bar',
'labels' => $buckets['labels'],
'stacked' => true,
'series' => [
['label' => 'Good', 'data' => array_map(function ($k) use ($by_bucket) { return $by_bucket[$k]['good'] ?? 0; }, $keys), 'tone' => 'success', 'stack' => 'ratings'],
['label' => 'Bad', 'data' => array_map(function ($k) use ($by_bucket) { return $by_bucket[$k]['bad'] ?? 0; }, $keys), 'tone' => 'danger', 'stack' => 'ratings'],
['label' => 'Satisfaction', 'data' => array_map(function ($k) use ($by_bucket) { return $by_bucket[$k]['score'] ?? null; }, $keys), 'tone' => 'accent', 'type' => 'line', 'axis' => 'y2'],
],
'format' => 'count',
'format2' => 'percent',
'max2' => 100,
], '', 'Good and bad ratings and the share rated good over the period');
?>
</div>
</div>
<?php if ($drivers) { ?>
<?= reportSectionOpen('What the rating follows', 'Satisfaction by how the ticket went') ?>
<?= reportTable($driver_columns, $driver_rows, ['sortable' => false]) ?>
</div>
<?php } ?>
<?php if (!$agent_id) { ?>
<?= reportSectionOpen('By agent', 'Who the ticket was assigned to') ?>
<?= reportTable($agent_columns, $agent_rows, ['totals' => ['agent' => 'Total'] + $overall, 'totals_html' => ['score' => reportRateHtml($overall['score'])]]) ?>
</div>
<?php } ?>
<?php if (!$client_id) { ?>
<?= reportSectionOpen('By client', 'The most bad ratings first') ?>
<?= reportTable($client_columns, $client_rows, ['limit' => 50, 'export_table' => 'clients', 'totals' => ['client' => 'Total'] + $overall, 'totals_html' => ['score' => reportRateHtml($overall['score'])]]) ?>
</div>
<?php } ?>
<?= reportSectionOpen('Bad ratings', $bad_rows ? 'Newest first - worth a call' : '') ?>
<?= reportTable($bad_columns, $bad_rows, ['limit' => 100, 'export_table' => 'bad', 'empty' => reportEmpty('No bad ratings in this period.', 'fa-smile', 'success')]) ?>
<div class="card-footer small text-body-secondary">
Tickets closed in the period. Contacts rate a ticket Good or Bad in the client portal once it is closed; satisfaction is the share rated good.
Times run on the clock from when the ticket was raised; a red time missed its SLA target.
<?php if ($other > 0) { ?>
<?= reportCount($other) ?> <?= $other === 1 ? 'rating has' : 'ratings have' ?> another value and <?= $other === 1 ? 'is' : 'are' ?> counted as rated, but neither good nor bad.
<?php } ?>
</div>
</div>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,177 +1,149 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* SLA by Client - for each client, how their tickets with an SLA did in the
* period: first replies and resolutions in time, the typical first reply,
* and the average SLA clock to resolve - business hours with the clock
* running, so paused time does not count, which is what the SLA itself
* judged. Worst first, so the clients to talk to are at the top. One
* agent's tickets only when an agent is picked.
*/
enforceUserPermission('module_support');
require_once "includes/inc_report.php";
reportEnforce('sla_by_client');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
$period = reportPeriod('last_90');
$agent_id = reportAgentId();
$filter = reportTicketSql(0, $agent_id) . " AND ticket_sla_id > 0 AND " . reportRangeSql('ticket_created_at', $period);
$clients = [];
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, " . REPORT_SLA_COLUMNS . "
FROM tickets JOIN clients ON ticket_client_id = client_id WHERE $filter GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[intval($row['client_id'])] = ['client_id' => intval($row['client_id']), 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation'],
'response' => null, 'resolve_clock' => null, 'breached_open' => 0] + reportSlaFigures($row);
}
if (isset($_GET['month'])) {
$month = intval($_GET['month']);
} else {
$month = 0; // 0 = whole year
$responses = [];
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) AS s FROM tickets WHERE $filter AND ticket_first_response_at IS NOT NULL");
while ($row = mysqli_fetch_assoc($sql)) {
$responses[intval($row['client_id'])][] = floatval($row['s']);
}
$period_query = "YEAR(ticket_created_at) = $year";
$period_label = $year;
if ($month) {
$period_query .= " AND MONTH(ticket_created_at) = $month";
$period_label = date("F", mktime(1, 1, 1, $month, 1)) . " $year";
// The SLA clock spent on resolved tickets - logged business minutes, or for a
// ticket with none logged (a response-only plan, or one resolved before
// pausing existed) the business time between being raised and resolved
$clock = [];
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, ticket_created_at, ticket_resolved_at, SUM(sla_history_minutes) AS logged
FROM tickets LEFT JOIN sla_history ON sla_history_ticket_id = ticket_id
WHERE $filter AND ticket_resolved_at IS NOT NULL
GROUP BY ticket_id, ticket_client_id, ticket_created_at, ticket_resolved_at");
while ($row = mysqli_fetch_assoc($sql)) {
$minutes = $row['logged'] === null ? businessMinutesBetween($row['ticket_created_at'], $row['ticket_resolved_at']) : intval($row['logged']);
$clock[intval($row['client_id'])][] = $minutes * 60;
}
$sql_ticket_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(ticket_created_at) AS ticket_year FROM tickets ORDER BY ticket_year DESC");
$sql_clients = mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('client_id') . " ORDER BY client_name ASC");
// Clock time spent on resolved tickets, gathered for every client at once
// rather than per ticket. Tickets with no interval rows - response-only plans,
// or anything resolved before SLA pausing existed - fall back to the business
// time that elapsed between being raised and resolved.
$resolve_totals = [];
$sql_resolve_times = mysqli_query($mysqli, "SELECT ticket_client_id, ticket_id, ticket_created_at, ticket_resolved_at, SUM(sla_history_minutes) AS logged_minutes
FROM tickets
LEFT JOIN sla_history ON sla_history_ticket_id = ticket_id
WHERE ticket_sla_id > 0
AND ticket_resolved_at IS NOT NULL
AND $period_query
GROUP BY ticket_id, ticket_client_id, ticket_created_at, ticket_resolved_at"
);
while ($resolve_row = mysqli_fetch_assoc($sql_resolve_times)) {
$resolve_client_id = intval($resolve_row['ticket_client_id']);
$resolve_minutes = is_null($resolve_row['logged_minutes'])
? businessMinutesBetween($resolve_row['ticket_created_at'], $resolve_row['ticket_resolved_at'])
: intval($resolve_row['logged_minutes']);
if (!isset($resolve_totals[$resolve_client_id])) {
$resolve_totals[$resolve_client_id] = ['minutes' => 0, 'count' => 0];
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, COUNT(ticket_id) AS n FROM tickets
WHERE " . reportTicketSql(0, $agent_id) . " AND " . TICKET_OPEN_SQL . " AND " . dashboardSlaBreachedSql() . " GROUP BY ticket_client_id");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($clients[intval($row['client_id'])])) {
$clients[intval($row['client_id'])]['breached_open'] = intval($row['n']);
}
$resolve_totals[$resolve_client_id]['minutes'] += $resolve_minutes;
$resolve_totals[$resolve_client_id]['count']++;
}
foreach ($clients as $id => &$row) {
$row['response'] = reportMedian($responses[$id] ?? []);
$row['resolve_clock'] = !empty($clock[$id]) ? array_sum($clock[$id]) / count($clock[$id]) : null;
$row['worst'] = min($row['response_percent'] ?? 101, $row['resolution_percent'] ?? 101);
}
unset($row);
uasort($clients, function ($a, $b) { return $a['worst'] <=> $b['worst'] ?: $b['tickets'] <=> $a['tickets']; });
$clients = array_values($clients);
// tickets.php's assigned= filter, so a click keeps to the same agent
$agent_link = $agent_id ? "&assigned=$agent_id" : '';
$columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'tickets.php');
}],
'tickets' => ['label' => 'Tickets', 'type' => 'count'],
// The late counts sit beside their share on screen; the export keeps them apart
'response_missed' => ['label' => 'Replied late', 'type' => 'count', 'screen' => false],
'response_percent' => ['label' => 'Response', 'type' => 'percent', 'title' => 'First replies in time, of those judged', 'html' => function ($row) {
return reportRateHtml($row['response_percent']) . reportLateHtml($row['response_missed']);
}],
'resolution_missed' => ['label' => 'Resolved late', 'type' => 'count', 'screen' => false],
'resolution_percent' => ['label' => 'Resolution', 'type' => 'percent', 'title' => 'Resolved in time, of those judged', 'html' => function ($row) {
return reportRateHtml($row['resolution_percent']) . reportLateHtml($row['resolution_missed']);
}],
'response' => ['label' => 'First reply', 'type' => 'duration', 'title' => 'Typical (middle) time to the first reply, on the clock'],
'resolve_clock' => ['label' => 'Clock to resolve', 'type' => 'duration', 'title' => 'Average business time with the SLA clock running, to resolve'],
'breached_open' => ['label' => 'Breached now', 'type' => 'count', 'csv_label' => 'Breached and still open', 'title' => 'Open tickets that have missed a target, whenever they were raised', 'html' => function ($row) use ($agent_link) {
return $row['breached_open'] ? '<a class="text-danger-emphasis fw-semibold" href="/agent/tickets.php?client_id=' . $row['client_id'] . '&sla=breached' . $agent_link . '">' . $row['breached_open'] . '</a>' : '<span class="itflow-report-zero">–</span>';
}],
];
$overall = reportSlaCompliance($filter);
$totals = ['client' => 'Total', 'tickets' => $overall['tickets'], 'response_missed' => $overall['response_missed'], 'response_percent' => $overall['response_percent'],
'resolution_missed' => $overall['resolution_missed'], 'resolution_percent' => $overall['resolution_percent'],
'breached_open' => array_sum(array_column($clients, 'breached_open'))];
if (reportExporting()) {
reportCsv('SLA by Client ' . $period['start'] . ' to ' . $period['end'], $columns, $clients, $totals);
}
require_once "includes/inc_report_layout.php";
$below = array_filter($clients, function ($c) { return $c['worst'] < 80; });
$chart_rows = array_slice($clients, 0, 15);
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-stopwatch me-2"></i>SLA by Client</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('sla_by_client', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_created_at) AS y FROM tickets WHERE ticket_sla_id > 0"),
'agent' => $agent_id,
]); ?>
<?= reportStats([
['label' => 'Clients with SLA tickets', 'value' => reportCount(count($clients)), 'sub' => reportCount($overall['tickets']) . ' <span class="text-body-tertiary">tickets</span>'],
['label' => 'First reply in time', 'value_html' => reportRateHtml($overall['response_percent']), 'sub' => '<span class="text-body-tertiary">Across all clients</span>'],
['label' => 'Resolved in time', 'value_html' => reportRateHtml($overall['resolution_percent']), 'sub' => '<span class="text-body-tertiary">Across all clients</span>'],
['label' => 'Clients under 80%', 'value' => reportCount(count($below)), 'tone' => $below ? 'danger' : 'success', 'sub' => '<span class="text-body-tertiary">On response or resolution</span>'],
]) ?>
<?php if ($chart_rows) { ?>
<?= reportSectionOpen('Targets met', 'Worst first') ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_column($chart_rows, 'client'),
'series' => [
['label' => 'First reply in time', 'data' => array_column($chart_rows, 'response_percent'), 'tone' => 'accent'],
['label' => 'Resolved in time', 'data' => array_column($chart_rows, 'resolution_percent'), 'tone' => 'success'],
],
'format' => 'percent',
'max' => 100,
], '', 'The share of SLA targets met for each client') ?>
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_ticket_years)) {
$ticket_year = intval($row['ticket_year']); ?>
<option <?php if ($year == $ticket_year) { ?> selected <?php } ?> > <?= $ticket_year ?></option>
<?php } ?>
</select>
<select onchange="this.form.submit()" class="form-select" name="month">
<option <?php if ($month == 0) { echo 'selected'; } ?> value="0">Whole year</option>
<?php for ($m = 1; $m <= 12; $m++) { ?>
<option <?php if ($month == $m) { echo 'selected'; } ?> value="<?= $m ?>"><?= date("F", mktime(1, 1, 1, $m, 1)) ?></option>
<?php } ?>
</select>
</form>
<div class="card card-dark mb-3">
<div class="card-header">
<h3 class="card-title"><i class="fas fa-fw fa-chart-area me-2"></i><?= $period_label ?></h3>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Tickets</th>
<th class="text-end">Response met</th>
<th class="text-end">Response missed</th>
<th class="text-end">Response %</th>
<th class="text-end">Resolution met</th>
<th class="text-end">Resolution missed</th>
<th class="text-end">Resolution %</th>
<th class="text-end">Avg time to respond</th>
<th class="text-end">Avg clock to resolve</th>
</tr>
</thead>
<tbody>
<?php
$any_rows = false;
while ($row = mysqli_fetch_assoc($sql_clients)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$stats = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT
COUNT(ticket_id) AS ticket_count,
SUM(ticket_response_sla_met = 1) AS response_met,
SUM(ticket_response_sla_met = 0) AS response_missed,
SUM(ticket_resolution_sla_met = 1) AS resolution_met,
SUM(ticket_resolution_sla_met = 0) AS resolution_missed,
AVG(CASE WHEN ticket_first_response_at IS NOT NULL THEN TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) END) AS avg_response_seconds
FROM tickets
WHERE ticket_sla_id > 0 AND ticket_client_id = $client_id AND $period_query"
));
$ticket_count = intval($stats['ticket_count']);
if ($ticket_count == 0) {
continue;
}
$any_rows = true;
$response_met = intval($stats['response_met']);
$response_missed = intval($stats['response_missed']);
$resolution_met = intval($stats['resolution_met']);
$resolution_missed = intval($stats['resolution_missed']);
$response_judged = $response_met + $response_missed;
$response_percent = $response_judged ? round($response_met / $response_judged * 100, 1) : null;
$resolution_judged = $resolution_met + $resolution_missed;
$resolution_percent = $resolution_judged ? round($resolution_met / $resolution_judged * 100, 1) : null;
$avg_time_to_respond = is_null($stats['avg_response_seconds']) ? '-' : secondsToTime($stats['avg_response_seconds']);
// Clock time actually spent - paused spells excluded, which is
// what the SLA itself judged on
$avg_time_to_resolve = '-';
if (!empty($resolve_totals[$client_id]['count'])) {
$avg_time_to_resolve = secondsToTime(($resolve_totals[$client_id]['minutes'] / $resolve_totals[$client_id]['count']) * 60);
}
?>
<tr>
<td><?= $client_name ?></td>
<td class="text-end"><?= $ticket_count ?></td>
<td class="text-end"><?= $response_met ?></td>
<td class="text-end"><?= $response_missed ?></td>
<td class="text-end"><?= slaPercentDisplay($response_percent) ?></td>
<td class="text-end"><?= $resolution_met ?></td>
<td class="text-end"><?= $resolution_missed ?></td>
<td class="text-end"><?= slaPercentDisplay($resolution_percent) ?></td>
<td class="text-end"><?= $avg_time_to_respond ?></td>
<td class="text-end"><?= $avg_time_to_resolve ?></td>
</tr>
<?php }
if (!$any_rows) { ?>
<tr><td colspan="10" class="text-secondary">No tickets with an SLA in this period.</td></tr>
<?php } ?>
</tbody>
</table>
</div>
<small class="text-muted">Time to respond is wall-clock from ticket creation. Time to resolve counts only business hours with the SLA clock running, so paused time is excluded.</small>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By client', 'Worst first') ?>
<?= reportTable($columns, $clients, ['empty' => reportEmpty('No ticket raised in this period carried an SLA.', 'fa-stopwatch', 'secondary'), 'totals' => $totals,
'totals_html' => ['response_percent' => reportRateHtml($overall['response_percent']) . reportLateHtml($overall['response_missed']),
'resolution_percent' => reportRateHtml($overall['resolution_percent']) . reportLateHtml($overall['resolution_missed'])]]) ?>
<div class="card-footer small text-body-secondary">
Tickets raised in the period that carry an SLA. Percentages count only targets already judged. The first reply runs on the clock;
the SLA clock to resolve counts business hours with the clock running, so time paused (On Hold) is left out.
</div>
</div>
<?php
require_once "../../includes/footer.php";
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,198 +1,171 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* SLA Performance - how tickets carrying an SLA did against their response
* and resolution targets, for tickets raised in the period: overall, month by
* month, by priority and by agent, and the SLAs breached on tickets still
* open now. A percentage counts only targets that have been judged - a ticket
* still waiting for its first reply is neither a hit nor a miss yet.
*/
enforceUserPermission('module_support');
require_once "includes/inc_report.php";
reportEnforce('sla_summary');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
}
$period = reportPeriod('last_90');
$client_id = reportClientId();
$filter = reportTicketSql($client_id) . " AND " . reportRangeSql('ticket_created_at', $period);
$sql_ticket_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(ticket_created_at) AS ticket_year FROM tickets ORDER BY ticket_year DESC");
$overall = reportSlaCompliance($filter);
$previous = reportSlaCompliance(reportTicketSql($client_id) . " AND " . reportRangeSql('ticket_created_at', $period, true));
$breached_open = dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE " . reportTicketSql($client_id) . " AND " . TICKET_OPEN_SQL . " AND " . dashboardSlaBreachedSql());
// Compliance figures for a slice of tickets carrying an SLA
function getSlaCompliance($where)
{
// Grouped figures
$grouped = function ($group_sql, $join = '') use ($filter) {
global $mysqli;
$rows = [];
$sql = mysqli_query($mysqli, "SELECT $group_sql AS k, " . REPORT_SLA_COLUMNS . " FROM tickets $join WHERE ticket_sla_id > 0 AND $filter GROUP BY k");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[(string) $row['k']] = reportSlaFigures($row);
}
return $rows;
};
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT
COUNT(ticket_id) AS ticket_count,
SUM(ticket_response_sla_met = 1) AS response_met,
SUM(ticket_response_sla_met = 0) AS response_missed,
SUM(ticket_response_sla_met IS NULL) AS response_pending,
SUM(ticket_resolution_sla_met = 1) AS resolution_met,
SUM(ticket_resolution_sla_met = 0) AS resolution_missed,
SUM(ticket_resolution_sla_met IS NULL AND ticket_resolution_due_at IS NOT NULL) AS resolution_pending
FROM tickets
WHERE ticket_sla_id > 0 $where"
));
$buckets = reportBuckets($period);
if ($buckets['unit'] === 'day') {
// A day's handful of tickets makes a jumpy line - weeks read better
$buckets = reportBuckets(['start' => $period['start'], 'end' => $period['end'], 'days' => 60]);
}
$by_bucket = $grouped(reportBucketSql('ticket_created_at', $buckets['unit']));
$by_priority = $grouped('ticket_priority');
$by_agent = $grouped('ticket_assigned_to');
$compliance = [
'ticket_count' => intval($row['ticket_count']),
'response_met' => intval($row['response_met']),
'response_missed' => intval($row['response_missed']),
'response_pending' => intval($row['response_pending']),
'resolution_met' => intval($row['resolution_met']),
'resolution_missed' => intval($row['resolution_missed']),
'resolution_pending' => intval($row['resolution_pending']),
];
$priority_rows = [];
foreach (['Urgent', 'High', 'Medium', 'Low'] as $priority) {
if (isset($by_priority[$priority])) {
$priority_rows[] = ['priority' => $priority] + $by_priority[$priority];
}
}
$agent_rows = [];
$names = [];
$sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar FROM users WHERE user_type = 1");
while ($row = mysqli_fetch_assoc($sql)) {
$names[intval($row['user_id'])] = $row;
}
foreach ($by_agent as $user_id => $figures) {
$user_id = intval($user_id);
$agent_rows[] = ['user_id' => $user_id, 'agent' => $names[$user_id]['user_name'] ?? '', 'avatar' => $names[$user_id]['user_avatar'] ?? ''] + $figures;
}
usort($agent_rows, function ($a, $b) { return $b['tickets'] <=> $a['tickets']; });
// Percentages count only judged tickets - a ticket still in flight is
// neither a hit nor a miss
$response_judged = $compliance['response_met'] + $compliance['response_missed'];
$compliance['response_percent'] = $response_judged ? round($compliance['response_met'] / $response_judged * 100, 1) : null;
// On screen each share carries its late count; the export keeps every count apart
$figure_columns = [
'tickets' => ['label' => 'Tickets', 'type' => 'count'],
'response_met' => ['label' => 'Replied in time', 'type' => 'count', 'screen' => false],
'response_missed' => ['label' => 'Replied late', 'type' => 'count', 'screen' => false],
'response_percent' => ['label' => 'Response', 'type' => 'percent', 'title' => 'First replies in time, of those judged', 'html' => function ($row) {
return reportRateHtml($row['response_percent']) . reportLateHtml($row['response_missed']);
}],
'resolution_met' => ['label' => 'Resolved in time', 'type' => 'count', 'screen' => false],
'resolution_missed' => ['label' => 'Resolved late', 'type' => 'count', 'screen' => false],
'resolution_percent' => ['label' => 'Resolution', 'type' => 'percent', 'title' => 'Resolved in time, of those judged', 'html' => function ($row) {
return reportRateHtml($row['resolution_percent']) . reportLateHtml($row['resolution_missed']);
}],
'resolution_pending' => ['label' => 'Still running', 'type' => 'count', 'class' => 'text-body-secondary', 'title' => 'Resolution clock still running'],
];
$priority_columns = ['priority' => ['label' => 'Priority', 'html' => function ($row) {
return reportPriorityDot($row['priority']) . escapeHtml($row['priority']);
}]] + $figure_columns;
$agent_columns = ['agent' => ['label' => 'Assigned to', 'csv' => function ($row) { return $row['user_id'] ? $row['agent'] : 'Unassigned'; }, 'html' => function ($row) {
return formatAssignee($row['user_id'], $row['agent'], $row['avatar'], true);
}]] + $figure_columns;
$month_rows = [];
foreach ($buckets['keys'] as $i => $key) {
if (isset($by_bucket[$key])) {
$month_rows[] = ['when' => $buckets['labels'][$i]] + $by_bucket[$key];
}
}
$month_columns = ['when' => ['label' => ucfirst($buckets['unit']), 'sort' => false]] + $figure_columns;
$resolution_judged = $compliance['resolution_met'] + $compliance['resolution_missed'];
$compliance['resolution_percent'] = $resolution_judged ? round($compliance['resolution_met'] / $resolution_judged * 100, 1) : null;
return $compliance;
if (reportExporting('agents')) {
reportCsv('SLA by Agent', $agent_columns, $agent_rows);
}
if (reportExporting('priorities')) {
reportCsv('SLA by Priority', $priority_columns, $priority_rows);
}
if (reportExporting()) {
reportCsv('SLA by ' . ucfirst($buckets['unit']), $month_columns, $month_rows, ['when' => 'Total'] + $overall);
}
require_once "includes/inc_report_layout.php";
$overall = getSlaCompliance("AND YEAR(ticket_created_at) = $year");
$has_sla = $overall['tickets'] > 0;
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-stopwatch me-2"></i>SLA Summary</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('sla_summary', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_created_at) AS y FROM tickets WHERE ticket_sla_id > 0"),
'client' => $client_id,
'export' => ['months' => 'By ' . $buckets['unit'], 'priorities' => 'By priority', 'agents' => 'By agent'],
]); ?>
<?= reportStats([
['label' => 'Tickets with an SLA', 'value' => reportCount($overall['tickets']), 'sub' => '<span class="text-body-tertiary">Raised in the period</span>'],
['label' => 'First reply in time', 'value_html' => reportRateHtml($overall['response_percent']),
'sub' => $previous['response_percent'] !== null ? 'Was <span class="text-body">' . reportPercent($previous['response_percent']) . '</span> <span class="text-body-tertiary">' . escapeHtml($period['compare']) . '</span>' : ''],
['label' => 'Resolved in time', 'value_html' => reportRateHtml($overall['resolution_percent']),
'sub' => $previous['resolution_percent'] !== null ? 'Was <span class="text-body">' . reportPercent($previous['resolution_percent']) . '</span> <span class="text-body-tertiary">' . escapeHtml($period['compare']) . '</span>' : ''],
['label' => 'Breached and still open', 'value' => reportCount($breached_open), 'tone' => $breached_open ? 'danger' : 'success', 'url' => '/agent/tickets.php?sla=breached' . ($client_id ? "&client_id=$client_id" : ''),
'sub' => '<span class="text-body-tertiary">Whenever they were raised</span>'],
]) ?>
<?php if (!$has_sla) { ?>
<div class="card"><div class="card-body"><?= reportEmpty('No ticket raised in this period carried an SLA. Set SLAs up in Admin > SLA to start measuring them.', 'fa-stopwatch', 'secondary') ?></div></div>
<?php } else { ?>
<?= reportSectionOpen('Targets met over the period', 'Bars are tickets, lines the share met') ?>
<div class="card-body">
<?php
$keys = $buckets['keys'];
echo reportChart([
'type' => 'bar',
'labels' => $buckets['labels'],
'series' => [
['label' => 'Tickets with an SLA', 'data' => array_map(function ($k) use ($by_bucket) { return $by_bucket[$k]['tickets'] ?? 0; }, $keys), 'tone' => 'faint'],
['label' => 'First reply in time', 'data' => array_map(function ($k) use ($by_bucket) { return $by_bucket[$k]['response_percent'] ?? null; }, $keys), 'tone' => 'accent', 'type' => 'line', 'axis' => 'y2'],
['label' => 'Resolved in time', 'data' => array_map(function ($k) use ($by_bucket) { return $by_bucket[$k]['resolution_percent'] ?? null; }, $keys), 'tone' => 'success', 'type' => 'line', 'axis' => 'y2'],
],
'format' => 'count',
'format2' => 'percent',
'max2' => 100,
], '', 'SLA tickets and the share of targets met over the period');
?>
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_ticket_years)) {
$ticket_year = intval($row['ticket_year']); ?>
<option <?php if ($year == $ticket_year) { ?> selected <?php } ?> > <?= $ticket_year ?></option>
<?php } ?>
</select>
</form>
<?php if ($overall['ticket_count'] == 0) { ?>
<p class="text-secondary">No tickets raised in <?= $year ?> carried an SLA. Assign SLAs under Admin &gt; SLAs to start tracking.</p>
<?php } else { ?>
<div class="row mb-3">
<div class="col-sm-4">
<div class="info-box">
<span class="info-box-icon bg-secondary"><i class="fas fa-life-ring"></i></span>
<div class="info-box-content">
<span class="info-box-text">Tickets with an SLA</span>
<span class="info-box-number"><?= $overall['ticket_count'] ?></span>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="info-box">
<span class="info-box-icon bg-secondary"><i class="fas fa-reply"></i></span>
<div class="info-box-content">
<span class="info-box-text">Response compliance</span>
<span class="info-box-number"><?= slaPercentDisplay($overall['response_percent']) ?></span>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="info-box">
<span class="info-box-icon bg-secondary"><i class="fas fa-flag-checkered"></i></span>
<div class="info-box-content">
<span class="info-box-text">Resolution compliance</span>
<span class="info-box-number"><?= slaPercentDisplay($overall['resolution_percent']) ?></span>
</div>
</div>
</div>
</div>
<div class="card card-dark mb-3">
<div class="card-header">
<h3 class="card-title"><i class="fas fa-fw fa-chart-area me-2"></i>By Priority (<?= $year ?>)</h3>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Priority</th>
<th class="text-end">Tickets</th>
<th class="text-end">Response met</th>
<th class="text-end">Response missed</th>
<th class="text-end">Response %</th>
<th class="text-end">Resolution met</th>
<th class="text-end">Resolution missed</th>
<th class="text-end">Resolution %</th>
</tr>
</thead>
<tbody>
<?php foreach (['Urgent', 'High', 'Medium', 'Low'] as $priority) {
$stats = getSlaCompliance("AND YEAR(ticket_created_at) = $year AND ticket_priority = '$priority'");
if ($stats['ticket_count'] == 0) {
continue;
}
?>
<tr>
<td><?= $priority ?></td>
<td class="text-end"><?= $stats['ticket_count'] ?></td>
<td class="text-end"><?= $stats['response_met'] ?></td>
<td class="text-end"><?= $stats['response_missed'] ?></td>
<td class="text-end"><?= slaPercentDisplay($stats['response_percent']) ?></td>
<td class="text-end"><?= $stats['resolution_met'] ?></td>
<td class="text-end"><?= $stats['resolution_missed'] ?></td>
<td class="text-end"><?= slaPercentDisplay($stats['resolution_percent']) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="card card-dark mb-3">
<div class="card-header">
<h3 class="card-title"><i class="fas fa-fw fa-calendar me-2"></i>By Month (<?= $year ?>)</h3>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Month</th>
<th class="text-end">Tickets</th>
<th class="text-end">Response %</th>
<th class="text-end">Resolution %</th>
<th class="text-end">Still open</th>
</tr>
</thead>
<tbody>
<?php for ($month = 1; $month <= 12; $month++) {
$stats = getSlaCompliance("AND YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month");
if ($stats['ticket_count'] == 0) {
continue;
}
?>
<tr>
<td><?= date("F", mktime(1, 1, 1, $month, 1)) ?></td>
<td class="text-end"><?= $stats['ticket_count'] ?></td>
<td class="text-end"><?= slaPercentDisplay($stats['response_percent']) ?></td>
<td class="text-end"><?= slaPercentDisplay($stats['resolution_percent']) ?></td>
<td class="text-end"><?= $stats['resolution_pending'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<small class="text-muted">Percentages count only tickets whose targets have been judged - tickets still awaiting a response or resolution are excluded until their outcome is known. Tickets raised before SLAs were assigned carry no SLA and are not counted.</small>
<?php } ?>
<?= reportSectionOpen('By priority', '') ?>
<?= reportTable($priority_columns, $priority_rows, ['sortable' => false]) ?>
</div>
</div>
<?php
require_once "../../includes/footer.php";
<?= reportSectionOpen('By agent', 'Who the ticket is assigned to') ?>
<?= reportTable($agent_columns, $agent_rows) ?>
</div>
<?= reportSectionOpen('By ' . $buckets['unit'], 'When the tickets were raised') ?>
<?= reportTable($month_columns, $month_rows, ['sortable' => false, 'totals' => ['when' => 'Total'] + $overall,
'totals_html' => ['response_percent' => reportRateHtml($overall['response_percent']) . reportLateHtml($overall['response_missed']),
'resolution_percent' => reportRateHtml($overall['resolution_percent']) . reportLateHtml($overall['resolution_missed'])]]) ?>
<div class="card-footer small text-body-secondary">
Tickets raised in the period that carry an SLA. Targets run in business hours, and a status that pauses the SLA stops the resolution clock.
Percentages count only targets already judged; tickets raised before SLAs were set up carry none and are not counted.
</div>
</div>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,149 +1,211 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Tax Collected - the tax on paid invoices, by tax and month or quarter, with
* the sales it was charged on beside it - what a sales tax return asks for.
*
* Cash basis, the same as getMonthlyTax(): tax counts when the payment
* arrives, in proportion to how much of the invoice that payment covered, so
* a part-paid invoice has only that part of its tax counted. Each invoice's
* line items are added up per tax first, so an invoice with several payments
* never multiplies its own tax.
*/
enforceUserPermission('module_financial');
require_once "includes/inc_report.php";
reportEnforce('tax_summary');
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');
[$year, $years] = reportYear("SELECT YEAR(payment_date) AS y FROM payments");
$view = ($_GET['view'] ?? 'quarter') === 'month' ? 'month' : 'quarter';
$current_year = $year === intval(date('Y'));
$columns = reportYearColumns($view);
$view = isset($_GET['view']) ? $_GET['view'] : 'quarterly';
/** Tax and taxable sales collected between two dates - [tax id => ['tax' => [1..12], 'sales' => [1..12]]]. */
function taxCollected($from, $to) {
global $mysqli;
$sql = mysqli_query($mysqli, "
SELECT item_tax.item_tax_id AS tax_id, MONTH(payment_date) AS m,
SUM(item_tax.tax_total * payment_amount / invoice_amount) AS tax,
SUM(item_tax.sales_total * payment_amount / invoice_amount) AS sales
FROM payments
JOIN invoices ON invoice_id = payment_invoice_id
JOIN (
SELECT item_invoice_id, item_tax_id, SUM(item_tax) AS tax_total, SUM(item_subtotal) AS sales_total
FROM invoice_items
WHERE item_tax_id > 0
GROUP BY item_invoice_id, item_tax_id
) AS item_tax ON item_tax.item_invoice_id = invoice_id
WHERE payment_date >= '$from' AND payment_date < '$to' + INTERVAL 1 DAY AND invoice_amount > 0
GROUP BY item_tax.item_tax_id, m");
$taxes = [];
while ($row = mysqli_fetch_assoc($sql)) {
$id = intval($row['tax_id']);
$taxes[$id] = $taxes[$id] ?? ['tax' => array_fill(1, 12, 0.0), 'sales' => array_fill(1, 12, 0.0)];
$taxes[$id]['tax'][intval($row['m'])] += floatval($row['tax']);
$taxes[$id]['sales'][intval($row['m'])] += floatval($row['sales']);
}
return $taxes;
}
$currency_row = mysqli_fetch_assoc(mysqli_query($mysqli,"SELECT company_currency FROM companies WHERE company_id = 1"));
$company_currency = escapeHtml($currency_row['company_currency']);
$to = $current_year ? date('Y-m-d') : "$year-12-31";
$collected = taxCollected("$year-01-01", $to);
$prev_collected = taxCollected(($year - 1) . '-01-01', $current_year ? dashboardShiftMonths(date('Y-m-d'), -12) : ($year - 1) . '-12-31');
$compare = $current_year ? 'the same time last year' : (string) ($year - 1);
// GET unique years from expenses, payments and revenues
$sql_all_years = mysqli_query($mysqli, "SELECT DISTINCT(YEAR(item_created_at)) AS all_years FROM invoice_items ORDER BY all_years DESC");
// Every tax not archived, and any archived one that collected something
$taxes = [];
$ids = array_keys($collected);
$sql = mysqli_query($mysqli, "SELECT tax_id, tax_name, tax_percent, tax_archived_at FROM taxes
WHERE tax_archived_at IS NULL" . ($ids ? " OR tax_id IN (" . implode(',', array_map('intval', $ids)) . ")" : '') . "
ORDER BY tax_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$taxes[intval($row['tax_id'])] = $row;
}
$sql_tax = mysqli_query($mysqli, "SELECT `tax_name` FROM `taxes`");
$lines = [];
$tax_total = 0.0;
$sales_total = 0.0;
$prev_tax_total = 0.0;
foreach ($taxes as $id => $tax) {
$amounts = $collected[$id] ?? ['tax' => array_fill(1, 12, 0.0), 'sales' => array_fill(1, 12, 0.0)];
$prev = array_sum($prev_collected[$id]['tax'] ?? []);
$lines[$id] = [
'name' => $tax['tax_name'], 'percent' => floatval($tax['tax_percent']), 'archived' => !empty($tax['tax_archived_at']),
'tax' => reportSumColumns($amounts['tax'], $columns), 'sales' => reportSumColumns($amounts['sales'], $columns),
'tax_total' => array_sum($amounts['tax']), 'sales_total' => array_sum($amounts['sales']), 'prev' => $prev,
'tax_months' => $amounts['tax'],
];
$tax_total += $lines[$id]['tax_total'];
$sales_total += $lines[$id]['sales_total'];
$prev_tax_total += $prev;
}
if (reportExporting()) {
$csv_columns = ['name' => ['label' => 'Tax'], 'what' => ['label' => 'Figure']];
foreach ($columns as $i => [$label]) {
$csv_columns["c$i"] = ['label' => $label, 'type' => 'money'];
}
$csv_columns['total'] = ['label' => (string) $year, 'type' => 'money'];
$rows = [];
foreach ($lines as $line) {
foreach (['tax' => 'Tax collected', 'sales' => 'Taxable sales'] as $key => $what) {
$row = ['name' => $line['name'] . ' (' . rtrim(rtrim(number_format($line['percent'], 3), '0'), '.') . '%)', 'what' => $what, 'total' => $line[$key . '_total']];
foreach ($columns as $i => $column) {
$row["c$i"] = $line[$key][$i];
}
$rows[] = $row;
}
}
reportCsv("Tax Collected $year", $csv_columns, $rows);
}
require_once "includes/inc_report_layout.php";
$percent_text = function ($percent) {
return rtrim(rtrim(number_format($percent, 3), '0'), '.') . '%';
};
$span = count($columns) + 2;
$stats = [
['label' => 'Tax collected', 'value' => reportMoney($tax_total), 'sub' => reportChangeHtml($tax_total, $prev_tax_total, 'up', $compare)],
['label' => 'Taxable sales', 'value' => reportMoney($sales_total), 'sub' => '<span class="text-body-tertiary">The paid sales the tax was on</span>'],
];
foreach (array_slice($lines, 0, 3, true) as $line) {
$stats[] = ['label' => $line['name'], 'value' => reportMoney($line['tax_total']), 'sub' => '<span class="text-body-tertiary">At ' . escapeHtml($percent_text($line['percent'])) . '</span>'];
}
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-balance-scale me-2"></i>Collected Tax Summary</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('tax_summary', [
'year' => [$year, $years],
'controls' => reportSegmentControl('view', $view, ['quarter' => 'Quarterly', 'month' => 'Monthly']),
'subtitle' => $current_year ? "$year to date" : (string) $year,
]); ?>
<?= reportStats($stats) ?>
<?php if (!$taxes) { ?>
<div class="card"><div class="card-body"><?= reportEmpty('No taxes are set up. Add them in Admin > Taxes, and the tax on paid invoices shows here.', 'fa-percent', 'secondary') ?></div></div>
<?php } else { ?>
<?= reportSectionOpen('Tax collected by month', escapeHtml((string) $year)) ?>
<div class="card-body">
<?php
$months_shown = $current_year ? intval(date('n')) : 12;
$series = [];
$i = 0;
foreach ($lines as $line) {
if ($line['tax_total'] <= 0) {
continue;
}
$series[] = ['label' => $line['name'], 'data' => array_map(function ($m) use ($line, $months_shown) {
return $m <= $months_shown ? round($line['tax_months'][$m], 2) : null;
}, range(1, 12)), 'tone' => reportPalette($i++), 'stack' => 'tax'];
}
echo reportChart([
'type' => 'bar',
'labels' => array_map(function ($m) { return date('M', mktime(0, 0, 0, $m, 1)); }, range(1, 12)),
'series' => $series,
'stacked' => true,
'format' => 'money',
], 'sm', 'Tax collected per month, by tax');
?>
</div>
</div>
<div class="card-body p-0">
<form class="p-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_all_years)) {
$all_years = intval($row['all_years']);
?>
<option <?php if ($year == $all_years) { echo "selected"; } ?> > <?= $all_years ?></option>
<?php
}
?>
</select>
<!-- View Selection Dropdown -->
<select onchange="this.form.submit()" class="form-select" name="view">
<option value="monthly" <?php if ($view == 'monthly') echo "selected"; ?>>Monthly</option>
<option value="quarterly" <?php if ($view == 'quarterly') echo "selected"; ?>>Quarterly</option>
</select>
</form>
<div class="table-responsive-sm">
<table class="table table-sm">
<thead class="text-dark">
<?= reportSectionOpen('By tax', $view === 'quarter' ? 'By calendar quarter' : 'By month') ?>
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0 itflow-report-table itflow-report-grid">
<thead class="table-light">
<tr>
<th>Tax</th>
<?php
if ($view == 'monthly') {
for ($i = 1; $i <= 12; $i++) {
echo "<th class='text-end'>" . date('M', mktime(0, 0, 0, $i, 10)) . "</th>";
}
} else {
echo "<th class='text-end'>Jan-Mar</th>";
echo "<th class='text-end'>Apr-Jun</th>";
echo "<th class='text-end'>Jul-Sep</th>";
echo "<th class='text-end'>Oct-Dec</th>";
}
?>
<th class="text-end">Total</th>
<?php foreach ($columns as [$label, $first, $last]) { ?>
<th class="text-end"<?php if ($view === 'quarter') { ?> title="<?= date('M', mktime(0, 0, 0, $first, 1)) ?> – <?= date('M', mktime(0, 0, 0, $last, 1)) ?>"<?php } ?>><?= $label ?></th>
<?php } ?>
<th class="text-end"><?= $year ?></th>
</tr>
</thead>
<tbody>
<?php
// Running totals
$monthly_totals = array_fill(1, 12, 0.0);
$quarterly_totals = array_fill(1, 4, 0.0);
$grand_total = 0.0;
while ($row = mysqli_fetch_assoc($sql_tax)) {
$tax_name_raw = $row['tax_name'];
$tax_name = escapeSql($tax_name_raw);
echo "<tr>";
echo "<td>" . escapeHtml($tax_name_raw) . "</td>";
if ($view == 'monthly') {
// Row total = sum of this tax’s 12 months, accumulated as we go
$row_total = 0.0;
for ($i = 1; $i <= 12; $i++) {
$monthly_tax = (float) getMonthlyTax($tax_name, $i, $year, $mysqli);
// Accumulate totals
$monthly_totals[$i] += $monthly_tax;
$grand_total += $monthly_tax;
$row_total += $monthly_tax;
echo "<td class='text-end'>" . numfmt_format_currency($currency_format, $monthly_tax, $company_currency) . "</td>";
}
echo "<td class='text-end text-bold'>" . numfmt_format_currency($currency_format, $row_total, $company_currency) . "</td>";
} else {
$row_total = 0.0;
for ($q = 1; $q <= 4; $q++) {
$quarterly_tax = (float) getQuarterlyTax($tax_name, $q, $year, $mysqli);
// Accumulate totals
$quarterly_totals[$q] += $quarterly_tax;
$grand_total += $quarterly_tax;
$row_total += $quarterly_tax;
echo "<td class='text-end'>" . numfmt_format_currency($currency_format, $quarterly_tax, $company_currency) . "</td>";
}
echo "<td class='text-end text-bold'>" . numfmt_format_currency($currency_format, $row_total, $company_currency) . "</td>";
}
echo "</tr>";
}
// Totals row
echo "<tr>";
echo "<th>Total</th>";
if ($view == 'monthly') {
for ($i = 1; $i <= 12; $i++) {
echo "<th class='text-end text-bold'>" . numfmt_format_currency($currency_format, $monthly_totals[$i], $company_currency) . "</th>";
}
} else {
for ($q = 1; $q <= 4; $q++) {
echo "<th class='text-end text-bold'>" . numfmt_format_currency($currency_format, $quarterly_totals[$q], $company_currency) . "</th>";
}
}
echo "<th class='text-end text-bold'>" . numfmt_format_currency($currency_format, $grand_total, $company_currency) . "</th>";
echo "</tr>";
?>
<tr class="itflow-report-group-row"><td colspan="<?= $span ?>">Tax collected</td></tr>
<?php foreach ($lines as $line) { ?>
<tr>
<td class="itflow-report-sub"><?= escapeHtml($line['name']) ?> <span class="text-body-secondary small"><?= escapeHtml($percent_text($line['percent'])) ?></span><?php if ($line['archived']) { ?> <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Archived</span><?php } ?></td>
<?php foreach ($columns as $i => $column) { ?>
<td class="text-end"><?= abs($line['tax'][$i]) < 0.005 ? '<span class="itflow-report-zero">–</span>' : reportMoney($line['tax'][$i]) ?></td>
<?php } ?>
<td class="text-end fw-semibold"><?= reportMoney($line['tax_total']) ?></td>
</tr>
<?php } ?>
<tr class="fw-semibold">
<td>Total tax</td>
<?php foreach ($columns as $i => $column) { ?>
<td class="text-end"><?= reportMoney(array_sum(array_map(function ($l) use ($i) { return $l['tax'][$i]; }, $lines))) ?></td>
<?php } ?>
<td class="text-end"><?= reportMoney($tax_total) ?></td>
</tr>
<tr class="itflow-report-group-row"><td colspan="<?= $span ?>">Sales the tax was charged on</td></tr>
<?php foreach ($lines as $line) { ?>
<tr>
<td class="itflow-report-sub"><?= escapeHtml($line['name']) ?></td>
<?php foreach ($columns as $i => $column) { ?>
<td class="text-end text-body-secondary"><?= abs($line['sales'][$i]) < 0.005 ? '<span class="itflow-report-zero">–</span>' : reportMoney($line['sales'][$i]) ?></td>
<?php } ?>
<td class="text-end"><?= reportMoney($line['sales_total']) ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="card-footer small text-body-secondary">
Counted when invoices are paid: each payment carries its share of the invoice's tax, so a part-paid invoice counts only the part that came in.
Taxable sales are the line items each tax was charged on, before tax. Check figures with your accountant before filing.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php";
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -0,0 +1,221 @@
<?php
/*
* Open Ticket Aging - the backlog right now: every open ticket by how long it
* has been open, per agent and per client, then the oldest tickets one by
* one with whose move it is (ours or the client's), their SLA and when
* anything last happened. "Waiting on us" uses the same rule as the ticket
* list's Needs reply view.
*/
require_once "includes/inc_report.php";
reportEnforce('ticket_aging');
$client_id = reportClientId();
$agent_filter = $_GET['agent'] ?? '';
$unassigned_only = $agent_filter === 'none';
$agent_id = $unassigned_only ? 0 : reportAgentId();
$where = reportTicketSql($client_id, $agent_id) . " AND " . TICKET_OPEN_SQL . ($unassigned_only ? " AND tickets.ticket_assigned_to = 0" : '');
$tickets = [];
$sql = mysqli_query($mysqli, "
SELECT tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_client_id, ticket_assigned_to, ticket_created_at, ticket_updated_at,
ticket_resolved_at, ticket_closed_at, ticket_due_at, ticket_sla_id, ticket_first_response_at, ticket_response_due_at, ticket_resolution_due_at,
ticket_response_sla_met, ticket_resolution_sla_met, ticket_response_sla_alert_stage, ticket_resolution_sla_alert_stage,
ticket_status_name, ticket_status_color, ticket_status_pauses_sla, user_name, user_avatar, client_name, client_abbreviation,
" . ticketLastSpokeSql() . " AS ticket_last_spoke,
TIMESTAMPDIFF(SECOND, ticket_created_at, NOW()) AS age_seconds,
(SELECT MAX(ticket_reply_created_at) FROM ticket_replies WHERE ticket_reply_ticket_id = tickets.ticket_id AND ticket_reply_archived_at IS NULL) AS last_reply
FROM tickets
LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id
LEFT JOIN users ON ticket_assigned_to = user_id
LEFT JOIN clients ON ticket_client_id = client_id
WHERE $where
ORDER BY ticket_created_at ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['age_days'] = intval($row['age_seconds']) / 86400;
$row['bucket'] = reportAgeBucket(intdiv(intval($row['age_seconds']), 86400));
$row['move'] = ticketWhoseMove($row);
$row['sla'] = ticketSlaState($row);
$row['due'] = ticketDueState($row);
$row['late'] = in_array($row['sla']['key'], ['breached'], true) || ($row['due']['key'] ?? '') === 'overdue';
$row['last_activity'] = max($row['last_reply'] ?? '', $row['ticket_updated_at'] ?? '', $row['ticket_created_at']);
$tickets[] = $row;
}
$bucket_keys = array_keys(REPORT_AGE_BUCKETS);
$empty = array_fill_keys($bucket_keys, 0) + ['total' => 0, 'us' => 0, 'late' => 0];
$totals = $empty;
$by_agent = [];
$by_client = [];
foreach ($tickets as $ticket) {
$a = intval($ticket['ticket_assigned_to']);
$c = intval($ticket['ticket_client_id']);
$by_agent[$a] = $by_agent[$a] ?? ['user_id' => $a, 'agent' => $a ? ($ticket['user_name'] ?? '') : '', 'avatar' => $ticket['user_avatar'] ?? ''] + $empty;
$by_client[$c] = $by_client[$c] ?? ['client_id' => $c, 'client' => $ticket['client_name'] ?? '', 'abbr' => $ticket['client_abbreviation'] ?? ''] + $empty;
foreach ([&$by_agent[$a], &$by_client[$c], &$totals] as &$group) {
$group[$ticket['bucket']]++;
$group['total']++;
$group['us'] += $ticket['move'] === 'us' ? 1 : 0;
$group['late'] += $ticket['late'] ? 1 : 0;
}
unset($group);
}
$sort = function ($a, $b) {
return $b['old'] + $b['90'] <=> $a['old'] + $a['90'] ?: $b['total'] <=> $a['total'];
};
uasort($by_agent, $sort);
uasort($by_client, $sort);
$count_cell = function ($key) {
return function ($row) use ($key) {
if (!$row[$key]) {
return '<span class="itflow-report-zero">–</span>';
}
$tone = in_array($key, ['90', 'old'], true) ? 'text-danger-emphasis fw-semibold' : ($key === '30' ? 'text-warning-emphasis fw-semibold' : '');
return '<span class="' . $tone . '">' . $row[$key] . '</span>';
};
};
$bucket_columns = [];
foreach (REPORT_AGE_BUCKETS as $key => [$label]) {
$bucket_columns[$key] = ['label' => $label, 'type' => 'count', 'html' => $count_cell($key)];
}
$tail_columns = [
'total' => ['label' => 'Open', 'type' => 'count', 'class' => 'fw-semibold'],
'us' => ['label' => 'Waiting on us', 'type' => 'count', 'title' => 'The client spoke last, or nobody has replied yet'],
'late' => ['label' => 'Late', 'type' => 'count', 'title' => 'Past their SLA or their due date', 'html' => function ($row) {
return $row['late'] ? '<span class="text-danger-emphasis fw-semibold">' . $row['late'] . '</span>' : '<span class="itflow-report-zero">–</span>';
}],
];
$agent_columns = ['agent' => ['label' => 'Agent', 'csv' => function ($row) { return $row['user_id'] ? $row['agent'] : 'Unassigned'; }, 'html' => function ($row) use ($client_id) {
$url = '/agent/tickets.php?' . http_build_query(array_filter(['client_id' => $client_id ?: null, 'assigned' => $row['user_id'] ?: 'unassigned']));
return '<a class="text-decoration-none" href="' . escapeHtml($url) . '">' . formatAssignee($row['user_id'], $row['agent'], $row['avatar'], true) . '</a>';
}]] + $bucket_columns + $tail_columns;
$client_columns = ['client' => ['label' => 'Client', 'csv' => function ($row) { return $row['client_id'] ? $row['client'] : 'No client'; }, 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'tickets.php');
}]] + $bucket_columns + $tail_columns;
$move_labels = ['us' => ['Waiting on us', 'danger', 'fa-reply'], 'client' => ['Waiting on client', 'secondary', 'fa-hourglass-half'], 'parked' => ['Parked', 'secondary', 'fa-pause']];
$ticket_columns = [
'ticket' => ['label' => 'Ticket', 'class' => 'itflow-report-text', 'csv' => function ($row) { return ticketReference($row) . ' ' . $row['ticket_subject']; }, 'html' => function ($row) {
return reportPriorityDot($row['ticket_priority']) . reportTicketLink($row);
}],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['ticket_client_id'], $row['client_name'] ?? '', $row['client_abbreviation'] ?? '');
}],
'user_name' => ['label' => 'Agent', 'csv' => function ($row) { return $row['user_name'] ?: 'Unassigned'; }, 'html' => function ($row) {
return formatAssignee($row['ticket_assigned_to'], $row['user_name'] ?? '', $row['user_avatar'] ?? '', true);
}],
'ticket_status_name' => ['label' => 'Status', 'html' => function ($row) {
$color = preg_match('/^#[0-9a-f]{3,8}$/i', (string) $row['ticket_status_color']) ? $row['ticket_status_color'] : '#6c757d';
return '<span class="badge rounded-pill text-white" style="background-color: ' . $color . '">' . escapeHtml($row['ticket_status_name']) . '</span>';
}],
'move' => ['label' => 'Whose move', 'csv' => function ($row) use ($move_labels) { return $move_labels[$row['move']][0] ?? ''; }, 'html' => function ($row) use ($move_labels) {
if (!isset($move_labels[$row['move']])) {
return '';
}
[$label, $tone, $icon] = $move_labels[$row['move']];
return '<span class="small text-nowrap text-' . $tone . '-emphasis"><i class="fas ' . $icon . ' me-1"></i>' . $label . '</span>';
}],
'sla' => ['label' => 'SLA / due', 'sort' => false, 'csv' => function ($row) { return trim(($row['sla']['key'] !== 'none' ? $row['sla']['key'] : '') . ' ' . ($row['due'] ? 'due ' . $row['ticket_due_at'] : '')); }, 'html' => function ($row) {
return '<span class="d-inline-flex flex-wrap gap-1">' . ticketSlaPill($row['sla']) . ticketDuePill($row['due']) . '</span>';
}],
'age_days' => ['label' => 'Open for', 'type' => 'decimal', 'decimals' => 1, 'csv_label' => 'Days open', 'html' => function ($row) {
$days = $row['age_days'];
$tone = $days > 30 ? 'text-danger-emphasis fw-semibold' : ($days > 7 ? 'text-warning-emphasis fw-semibold' : '');
return '<span class="' . $tone . '" title="Opened ' . escapeHtml($row['ticket_created_at']) . '">' . reportDuration($row['age_seconds']) . '</span>';
}],
'last_activity' => ['label' => 'Last activity', 'type' => 'date', 'csv' => function ($row) { return $row['last_activity']; }, 'html' => function ($row) {
return '<span class="small text-body-secondary text-nowrap" title="' . escapeHtml($row['last_activity']) . '">' . escapeHtml(timeAgo($row['last_activity'])) . '</span>';
}],
];
if (reportExporting('agents')) {
reportCsv('Open Tickets by Agent', $agent_columns, array_values($by_agent), ['agent' => 'Total'] + $totals);
}
if (reportExporting('clients')) {
reportCsv('Open Tickets by Client', $client_columns, array_values($by_client), ['client' => 'Total'] + $totals);
}
if (reportExporting()) {
reportCsv('Open Tickets', $ticket_columns, $tickets);
}
require_once "includes/inc_report_layout.php";
$unassigned = $by_agent[0]['total'] ?? 0;
$oldest = $tickets[0] ?? null;
$bucket_tones = ['day' => 'success', '3' => 'info', '7' => 'accent', '30' => 'warning', '90' => 'orange', 'old' => 'danger'];
$agent_choices = '<div class="col-sm-6 col-lg-2"><select class="form-select select2" name="agent" data-report-autosubmit aria-label="Agent">'
. '<option value="">- All agents -</option>'
. '<option value="none"' . ($unassigned_only ? ' selected' : '') . ' data-icon="fas fa-user-slash">Unassigned</option>';
$sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar FROM users WHERE user_type = 1 AND ((user_archived_at IS NULL AND user_status = 1) OR user_id = $agent_id) ORDER BY user_name");
while ($row = mysqli_fetch_assoc($sql)) {
$id = intval($row['user_id']);
$agent_choices .= '<option value="' . $id . '"' . ($id === $agent_id ? ' selected' : '') . selectOptionUser($id, $row['user_name'], $row['user_avatar'] ?? '') . '>' . escapeHtml($row['user_name']) . '</option>';
}
$agent_choices .= '</select></div>';
?>
<div class="itflow-report">
<?php reportHeader('ticket_aging', [
'client' => $client_id,
'controls' => $agent_choices,
'subtitle' => 'As of ' . date('M j, Y g:i A'),
'export' => ['tickets' => 'Every open ticket', 'agents' => 'By agent', 'clients' => 'By client'],
]); ?>
<?= reportStats([
['label' => 'Open tickets', 'value' => reportCount(count($tickets)), 'url' => '/agent/tickets.php' . ($client_id ? "?client_id=$client_id" : ''),
'sub' => reportCount($totals['30'] + $totals['90'] + $totals['old']) . ' <span class="text-body-tertiary">open over a week</span>'],
['label' => 'Waiting on us', 'value' => reportCount($totals['us']), 'tone' => $totals['us'] ? 'warning' : '', 'url' => '/agent/tickets.php?show=reply' . ($client_id ? "&client_id=$client_id" : ''),
'sub' => '<span class="text-body-tertiary">The client spoke last, or no reply yet</span>'],
['label' => 'Late', 'value' => reportCount($totals['late']), 'tone' => $totals['late'] ? 'danger' : 'success', 'url' => '/agent/tickets.php?show=overdue' . ($client_id ? "&client_id=$client_id" : ''),
'sub' => '<span class="text-body-tertiary">Past their SLA or due date</span>'],
['label' => 'Unassigned', 'value' => reportCount($unassigned), 'tone' => $unassigned ? 'warning' : '', 'url' => '/agent/tickets.php?assigned=unassigned' . ($client_id ? "&client_id=$client_id" : ''),
'sub' => $oldest ? 'Oldest open <span class="text-body">' . reportDuration($oldest['age_seconds']) . '</span>' : ''],
]) ?>
<?php if ($tickets) { ?>
<?= reportSectionOpen('How long they have been open', '') ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_map(function ($b) { return $b[0]; }, array_values(REPORT_AGE_BUCKETS)),
'series' => [['label' => 'Open tickets', 'data' => array_map(function ($k) use ($totals) { return $totals[$k]; }, $bucket_keys),
'tones' => array_map(function ($k) use ($bucket_tones) { return $bucket_tones[$k]; }, $bucket_keys)]],
'format' => 'count',
'legend' => false,
], '', 'Open tickets by how long they have been open') ?>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By agent', 'The longest-open work first') ?>
<?= reportTable($agent_columns, array_values($by_agent), ['empty' => reportEmpty('No open tickets.'), 'totals' => ['agent' => 'Total'] + $totals]) ?>
</div>
<?php if (!$client_id) { ?>
<?= reportSectionOpen('By client', 'The longest-open work first') ?>
<?= reportTable($client_columns, array_values($by_client), ['empty' => reportEmpty('No open tickets.'), 'limit' => 50, 'export_table' => 'clients', 'totals' => ['client' => 'Total'] + $totals]) ?>
</div>
<?php } ?>
<?php if ($tickets) { ?>
<?= reportSectionOpen('Every open ticket', 'Oldest first', 'itflow-report-long') ?>
<?= reportTable($ticket_columns, $tickets, ['limit' => 300, 'export_table' => 'tickets']) ?>
<div class="card-footer small text-body-secondary">
Open is neither resolved nor closed. Ages run on the clock from when the ticket was raised; the SLA pills use business hours.
"Waiting on us" means the client wrote last, or nobody has replied yet; a status that pauses the SLA (such as On Hold) parks a ticket.
</div>
</div>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,316 +1,193 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Tickets by Client - for each client in the period: tickets opened (and how
* many were urgent or high), resolved, still open now, time logged, how
* quickly they typically got a first reply and a resolution, SLA response
* compliance and how they rated their tickets. Busiest first; one agent's
* tickets only when an agent is picked.
*/
enforceUserPermission('module_support');
require_once "includes/inc_report.php";
reportEnforce('ticket_by_client');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
$period = reportPeriod('last_90');
$agent_id = reportAgentId();
$filter = reportTicketSql(0, $agent_id);
$opened_in = reportRangeSql('ticket_created_at', $period);
$clients = [];
$client = function ($row) use (&$clients) {
$id = intval($row['client_id']);
$clients[$id] = $clients[$id] ?? ['client_id' => $id, 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation'],
'opened' => 0, 'urgent' => 0, 'resolved' => 0, 'open_now' => 0, 'seconds' => 0, 'response' => null, 'resolve' => null,
'sla_met' => 0, 'sla_missed' => 0, 'good' => 0, 'bad' => 0, 'prev' => 0];
return $id;
};
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, COUNT(ticket_id) AS opened,
SUM(ticket_priority IN ('Urgent', 'High')) AS urgent,
SUM(ticket_response_sla_met = 1) AS sla_met, SUM(ticket_response_sla_met = 0) AS sla_missed
FROM tickets JOIN clients ON ticket_client_id = client_id
WHERE $filter AND $opened_in GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$id = $client($row);
$clients[$id]['opened'] = intval($row['opened']);
$clients[$id]['urgent'] = intval($row['urgent']);
$clients[$id]['sla_met'] = intval($row['sla_met']);
$clients[$id]['sla_missed'] = intval($row['sla_missed']);
}
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, COUNT(ticket_id) AS n
FROM tickets JOIN clients ON ticket_client_id = client_id
WHERE $filter AND " . reportRangeSql('ticket_resolved_at', $period) . " GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[$client($row)]['resolved'] = intval($row['n']);
}
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, COUNT(ticket_id) AS n
FROM tickets JOIN clients ON ticket_client_id = client_id
WHERE $filter AND " . TICKET_OPEN_SQL . " GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[$client($row)]['open_now'] = intval($row['n']);
}
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation, SUM(TIME_TO_SEC(ticket_reply_time_worked)) AS s
FROM ticket_replies JOIN tickets ON ticket_reply_ticket_id = ticket_id JOIN clients ON ticket_client_id = client_id
WHERE $filter AND ticket_reply_archived_at IS NULL AND " . reportRangeSql('ticket_reply_created_at', $period) . " GROUP BY client_id, client_name, client_abbreviation");
while ($row = mysqli_fetch_assoc($sql)) {
$clients[$client($row)]['seconds'] = intval($row['s']);
}
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, SUM(ticket_feedback = 'Good') AS good, SUM(ticket_feedback = 'Bad') AS bad
FROM tickets WHERE $filter AND " . reportRangeSql('ticket_closed_at', $period) . " GROUP BY ticket_client_id");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($clients[intval($row['client_id'])])) {
$clients[intval($row['client_id'])]['good'] = intval($row['good']);
$clients[intval($row['client_id'])]['bad'] = intval($row['bad']);
}
}
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, COUNT(ticket_id) AS n FROM tickets WHERE $filter AND " . reportRangeSql('ticket_created_at', $period, true) . " GROUP BY ticket_client_id");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($clients[intval($row['client_id'])])) {
$clients[intval($row['client_id'])]['prev'] = intval($row['n']);
}
}
if (isset($_GET['month'])) {
$month = intval($_GET['month']);
} else {
$month = date('m');
// The typical (middle) first reply and resolution, per client
$times = ['response' => [], 'resolve' => []];
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) AS s
FROM tickets WHERE $filter AND $opened_in AND ticket_first_response_at IS NOT NULL");
while ($row = mysqli_fetch_assoc($sql)) {
$times['response'][intval($row['client_id'])][] = floatval($row['s']);
}
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_resolved_at) AS s
FROM tickets WHERE $filter AND " . reportRangeSql('ticket_resolved_at', $period));
while ($row = mysqli_fetch_assoc($sql)) {
$times['resolve'][intval($row['client_id'])][] = floatval($row['s']);
}
foreach ($clients as $id => &$row) {
$row['response'] = reportMedian($times['response'][$id] ?? []);
$row['resolve'] = reportMedian($times['resolve'][$id] ?? []);
$row['sla'] = reportShare($row['sla_met'], $row['sla_met'] + $row['sla_missed']);
$row['csat'] = reportShare($row['good'], $row['good'] + $row['bad']);
$row['change'] = reportChange($row['opened'], $row['prev']);
}
unset($row);
uasort($clients, function ($a, $b) { return $b['opened'] <=> $a['opened'] ?: $b['open_now'] <=> $a['open_now']; });
$clients = array_values($clients);
$columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['client_id'], $row['client'], $row['abbr'], 'tickets.php');
}],
'opened' => ['label' => 'Opened', 'type' => 'count', 'class' => 'fw-semibold'],
'change' => ['label' => 'Change', 'type' => 'percent', 'csv' => false, 'html' => function ($row) {
return $row['change'] === null ? '<span class="itflow-report-zero">–</span>' : '<span class="small">' . reportChangeHtml($row['opened'], $row['prev'], 'down') . '</span>';
}],
'urgent' => ['label' => 'Urgent or high', 'type' => 'count', 'html' => function ($row) {
return $row['urgent'] ? '<span class="text-danger-emphasis">' . $row['urgent'] . '</span>' : '<span class="itflow-report-zero">–</span>';
}],
'resolved' => ['label' => 'Resolved', 'type' => 'count'],
'open_now' => ['label' => 'Open now', 'type' => 'count', 'html' => function ($row) {
return $row['open_now'] ? '<a class="itflow-report-amount" href="/agent/tickets.php?client_id=' . $row['client_id'] . '">' . $row['open_now'] . '</a>' : '<span class="itflow-report-zero">–</span>';
}],
'seconds' => ['label' => 'Time logged', 'type' => 'hours'],
'response' => ['label' => 'First reply', 'type' => 'duration', 'title' => 'Typical (middle) time to the first reply'],
'resolve' => ['label' => 'To resolve', 'type' => 'duration', 'title' => 'Typical (middle) time to resolve'],
'sla' => ['label' => 'SLA response', 'type' => 'percent', 'html' => function ($row) {
return reportRateHtml($row['sla']);
}],
'csat' => ['label' => 'Satisfaction', 'type' => 'percent', 'title' => 'Good ratings out of all good and bad', 'html' => function ($row) {
return $row['csat'] === null ? '<span class="itflow-report-zero">–</span>' : reportRateHtml($row['csat'], 90, 75) . ' <span class="small text-body-tertiary">' . ($row['good'] + $row['bad']) . '</span>';
}],
];
$totals = ['client' => 'Total'];
foreach (['opened', 'urgent', 'resolved', 'open_now', 'seconds'] as $key) {
$totals[$key] = array_sum(array_column($clients, $key));
}
$all_response = reportMedian(array_merge(...array_values($times['response'] ?: [[]])));
$all_resolve = reportMedian(array_merge(...array_values($times['resolve'] ?: [[]])));
$totals['response'] = $all_response;
$totals['resolve'] = $all_resolve;
$totals['sla'] = reportShare(array_sum(array_column($clients, 'sla_met')), array_sum(array_column($clients, 'sla_met')) + array_sum(array_column($clients, 'sla_missed')));
$totals['csat'] = reportShare(array_sum(array_column($clients, 'good')), array_sum(array_column($clients, 'good')) + array_sum(array_column($clients, 'bad')));
if (reportExporting()) {
reportCsv('Tickets by Client ' . $period['start'] . ' to ' . $period['end'], $columns, $clients, $totals);
}
$sql_ticket_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(ticket_created_at) AS ticket_year FROM tickets ORDER BY ticket_year DESC");
require_once "includes/inc_report_layout.php";
$sql_clients = mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('client_id') . " ORDER BY client_name ASC");
$top = array_slice(array_filter($clients, function ($c) { return $c['opened'] > 0; }), 0, 12);
$busiest = $clients[0] ?? null;
$with_tickets = count(array_filter($clients, function ($c) { return $c['opened'] > 0; }));
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-life-ring me-2"></i>Tickets By Client</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('ticket_by_client', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_created_at) AS y FROM tickets"),
'agent' => $agent_id,
]); ?>
<?= reportStats([
['label' => 'Tickets opened', 'value' => reportCount($totals['opened']), 'sub' => reportCount($with_tickets) . ' <span class="text-body-tertiary">clients raised them</span>'],
['label' => 'Average per client', 'value' => $with_tickets ? number_format($totals['opened'] / $with_tickets, 1) : '-', 'sub' => '<span class="text-body-tertiary">Of those who raised any</span>'],
['label' => 'Busiest', 'value' => $busiest && $busiest['opened'] ? $busiest['client'] : '-', 'sub' => $busiest && $busiest['opened'] ? $busiest['opened'] . ' <span class="text-body-tertiary">tickets · ' . reportPercent(reportShare($busiest['opened'], $totals['opened'])) . ' of all</span>' : ''],
['label' => 'Time logged', 'value' => reportHours($totals['seconds']) . ' h', 'sub' => $with_tickets ? reportHours($totals['seconds'] / $with_tickets) . ' h <span class="text-body-tertiary">per client</span>' : ''],
]) ?>
<?php if ($top) { ?>
<?= reportSectionOpen('Clients raising the most', 'By priority') ?>
<div class="card-body">
<?php
// Each client's tickets split by priority
$ids = array_column($top, 'client_id');
$split = [];
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, ticket_priority AS p, COUNT(ticket_id) AS n FROM tickets
WHERE $filter AND $opened_in AND ticket_client_id IN (" . implode(',', array_map('intval', $ids)) . ") GROUP BY ticket_client_id, ticket_priority");
while ($row = mysqli_fetch_assoc($sql)) {
$split[$row['p']][intval($row['client_id'])] = intval($row['n']);
}
$series = [];
foreach (['Urgent' => 'dark', 'High' => 'danger', 'Medium' => 'warning', 'Low' => 'info'] as $priority => $tone) {
$series[] = ['label' => $priority, 'tone' => $tone, 'stack' => 'p', 'data' => array_map(function ($id) use ($split, $priority) { return $split[$priority][$id] ?? 0; }, $ids)];
}
echo reportChart(['type' => 'bar', 'horizontal' => true, 'stacked' => true, 'labels' => array_column($top, 'client'), 'series' => $series, 'format' => 'count'], '', 'Tickets opened per client, by priority');
?>
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_ticket_years)) {
$ticket_year = intval($row['ticket_year']); ?>
<option <?php if ($year == $ticket_year) { ?> selected <?php } ?> > <?= $ticket_year ?></option>
<?php } ?>
</select>
<select onchange="this.form.submit()" class="form-select" name="month">
<option <?php if ($month == 1) { echo 'selected'; } ?> value="1">January</option>
<option <?php if ($month == 2) { echo 'selected'; } ?> value="2">February</option>
<option <?php if ($month == 3) { echo 'selected'; } ?> value="3">March</option>
<option <?php if ($month == 4) { echo 'selected'; } ?> value="4">April</option>
<option <?php if ($month == 5) { echo 'selected'; } ?> value="5">May</option>
<option <?php if ($month == 6) { echo 'selected'; } ?> value="6">June</option>
<option <?php if ($month == 7) { echo 'selected'; } ?> value="7">July</option>
<option <?php if ($month == 8) { echo 'selected'; } ?> value="8">August</option>
<option <?php if ($month == 9) { echo 'selected'; } ?> value="9">September</option>
<option <?php if ($month == 10) { echo 'selected'; } ?> value="10">October</option>
<option <?php if ($month == 11) { echo 'selected'; } ?> value="11">November</option>
<option <?php if ($month == 12) { echo 'selected'; } ?> value="12">December</option>
</select>
</form>
<div class="card card-dark mb-3">
<div class="card-header">
<h3 class="card-title"><i class="fas fa-fw fa-chart-area me-2"></i>Yearly (<?= $year ?>)</h3>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Raised</th>
<th class="text-end">Priority: Low</th>
<th class="text-end">Priority: Med</th>
<th class="text-end">Priority: High</th>
<th class="text-end">Priority: Urgent</th>
<th class="text-end">Resolved</th>
<th class="text-end">Total Time worked <i>(H:M:S)</i></th>
<th class="text-end">Avg time to respond</th>
<th class="text-end">Avg time to resolve</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_clients)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
// Calculate total tickets raised in period
$sql_ticket_raised_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS ticket_raised_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id");
$row = mysqli_fetch_assoc($sql_ticket_raised_count);
$ticket_raised_count = intval($row['ticket_raised_count']);
// Calculate total tickets raised in period that are resolved
$sql_ticket_resolved_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS ticket_resolved_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id AND ticket_resolved_at IS NOT NULL");
$row = mysqli_fetch_assoc($sql_ticket_resolved_count);
$ticket_resolved_count = intval($row['ticket_resolved_count']);
// Breakdown tickets for each priority - Low
$sql_low_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS low_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id AND ticket_priority = 'Low'");
$row = mysqli_fetch_assoc($sql_low_ticket_count);
$low_ticket_count = intval($row['low_ticket_count']);
// Breakdown tickets for each priority - Low
$sql_med_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS med_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id AND ticket_priority = 'Medium'");
$row = mysqli_fetch_assoc($sql_med_ticket_count);
$med_ticket_count = intval($row['med_ticket_count']);
// Breakdown tickets for each priority - Low
$sql_high_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS high_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id AND ticket_priority = 'High'");
$row = mysqli_fetch_assoc($sql_high_ticket_count);
$high_ticket_count = intval($row['high_ticket_count']);
// Breakdown tickets for each priority - Urgent
$sql_urgent_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS urgent_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id AND ticket_priority = 'Urgent'");
$row = mysqli_fetch_assoc($sql_urgent_ticket_count);
$urgent_ticket_count = intval($row['urgent_ticket_count']);
// Used to calculate average time to respond to tickets that were raised in period specified
$sql_tickets_respond = mysqli_query($mysqli, "SELECT ticket_created_at, ticket_first_response_at FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id");
// Used to calculate average time to resolve tickets that were raised in period specified
$sql_tickets_resolved = mysqli_query($mysqli, "SELECT ticket_created_at, ticket_resolved_at FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id AND ticket_resolved_at IS NOT NULL");
// Calculate total time tracked towards tickets in the period
$sql_time = mysqli_query($mysqli, "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(ticket_reply_time_worked))) as total_time FROM ticket_replies LEFT JOIN tickets ON tickets.ticket_id = ticket_replies.ticket_reply_ticket_id WHERE YEAR(ticket_created_at) = $year AND ticket_client_id = $client_id AND ticket_reply_time_worked IS NOT NULL");
$row = mysqli_fetch_assoc($sql_time);
$ticket_total_time_worked = escapeHtml($row['total_time']);
if ($ticket_raised_count > 0 || $ticket_resolved_count > 0) {
// Calculate average time to respond
$avg_time_to_respond = '-';
$count = 0;
$total = 0;
while ($row = mysqli_fetch_assoc($sql_tickets_respond)) {
if (!empty($row['ticket_first_response_at'])) {
$openedTime = new DateTime($row['ticket_created_at']);
$respondTime = new DateTime($row['ticket_first_response_at']);
$total += ($respondTime->getTimestamp() - $openedTime->getTimestamp());
$count++;
}
}
if ($count > 0) {
$avg_time_to_respond = secondsToTime($total / $count); // Avoids DivisionByZeroError
}
// Calculate average time to solve
$avg_time_to_resolve = '-';
if ($ticket_resolved_count > 0) {
$count = 0;
$total = 0;
while ($row = mysqli_fetch_assoc($sql_tickets_resolved)) {
$openedTime = new DateTime($row['ticket_created_at']);
$resolvedTime = new DateTime($row['ticket_resolved_at']);
$total += ($resolvedTime->getTimestamp() - $openedTime->getTimestamp());
$count++;
}
$avg_time_to_resolve = secondsToTime($total / $count);
}
?>
<tr>
<td><?= $client_name ?></td>
<td class="text-end"><?= $ticket_raised_count ?></td>
<td class="text-end"><?= $low_ticket_count ?></td>
<td class="text-end"><?= $med_ticket_count ?></td>
<td class="text-end"><?= $high_ticket_count ?></td>
<td class="text-end"><?= $urgent_ticket_count ?></td>
<td class="text-end"><?= $ticket_resolved_count ?></td>
<td class="text-end"><?= $ticket_total_time_worked ?></td>
<td class="text-end"><?= $avg_time_to_respond ?></td>
<td class="text-end"><?= $avg_time_to_resolve ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<div class="card card-dark mb-3">
<div class="card-header">
<h3 class="card-title"><i class="fas fa-fw fa-chart-area me-2"></i>Monthly (<?= date("F", mktime(1, 1, 1, $month, 1)) . ' ' . $year ?>)</h3>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Raised</th>
<th class="text-end">Priority: Low</th>
<th class="text-end">Priority: Med</th>
<th class="text-end">Priority: High</th>
<th class="text-end">Priority: Urgent</th>
<th class="text-end">Resolved</th>
<th class="text-end">Total Time worked <i>(H:M:S)</i></th>
<th class="text-end">Avg time to respond</th>
<th class="text-end">Avg time to resolve</th>
</tr>
</thead>
<tbody>
<?php
mysqli_data_seek($sql_clients, 0); // Reset
while ($row = mysqli_fetch_assoc($sql_clients)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
// Calculate total tickets raised in period
$sql_ticket_raised_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS ticket_raised_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id");
$row = mysqli_fetch_assoc($sql_ticket_raised_count);
$ticket_raised_count = intval($row['ticket_raised_count']);
// Calculate total tickets raised in period that are resolved
$sql_ticket_resolved_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS ticket_resolved_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id AND ticket_resolved_at IS NOT NULL");
$row = mysqli_fetch_assoc($sql_ticket_resolved_count);
$ticket_resolved_count = intval($row['ticket_resolved_count']);
// Breakdown tickets for each priority - Low
$sql_low_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS low_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id AND ticket_priority = 'Low'");
$row = mysqli_fetch_assoc($sql_low_ticket_count);
$low_ticket_count = intval($row['low_ticket_count']);
// Breakdown tickets for each priority - Low
$sql_med_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS med_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id AND ticket_priority = 'Medium'");
$row = mysqli_fetch_assoc($sql_med_ticket_count);
$med_ticket_count = intval($row['med_ticket_count']);
// Breakdown tickets for each priority - Low
$sql_high_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS high_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id AND ticket_priority = 'High'");
$row = mysqli_fetch_assoc($sql_high_ticket_count);
$high_ticket_count = intval($row['high_ticket_count']);
// Breakdown tickets for each priority - Urgent
$sql_urgent_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS urgent_ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id AND ticket_priority = 'Urgent'");
$row = mysqli_fetch_assoc($sql_urgent_ticket_count);
$urgent_ticket_count = intval($row['urgent_ticket_count']);
// Used to calculate average time to respond to tickets that were raised in period specified
$sql_tickets_respond = mysqli_query($mysqli, "SELECT ticket_created_at, ticket_first_response_at FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id");
// Used to calculate average time to resolve tickets that were raised in period specified
$sql_tickets_resolved = mysqli_query($mysqli, "SELECT ticket_created_at, ticket_resolved_at FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id AND ticket_resolved_at IS NOT NULL");
// Calculate total time tracked towards tickets in the period
$sql_time = mysqli_query($mysqli, "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(ticket_reply_time_worked))) as total_time FROM ticket_replies LEFT JOIN tickets ON tickets.ticket_id = ticket_replies.ticket_reply_ticket_id WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month AND ticket_client_id = $client_id AND ticket_reply_time_worked IS NOT NULL");
$row = mysqli_fetch_assoc($sql_time);
$ticket_total_time_worked = escapeHtml($row['total_time']);
if ($ticket_raised_count > 0 || $ticket_resolved_count > 0) {
// Calculate average time to respond
$avg_time_to_respond = '-';
$count = 0;
$total = 0;
while ($row = mysqli_fetch_assoc($sql_tickets_respond)) {
if (!empty($row['ticket_first_response_at'])) {
$openedTime = new DateTime($row['ticket_created_at']);
$respondTime = new DateTime($row['ticket_first_response_at']);
$total += ($respondTime->getTimestamp() - $openedTime->getTimestamp());
$count++;
}
}
if ($count > 0) {
$avg_time_to_respond = secondsToTime($total / $count); // Avoids DivisionByZeroError
}
// Calculate average time to solve
$avg_time_to_resolve = '-';
if ($ticket_resolved_count > 0) {
$count = 0;
$total = 0;
while ($row = mysqli_fetch_assoc($sql_tickets_resolved)) {
$openedTime = new DateTime($row['ticket_created_at']);
$resolvedTime = new DateTime($row['ticket_resolved_at']);
$total += ($resolvedTime->getTimestamp() - $openedTime->getTimestamp());
$count++;
}
$avg_time_to_resolve = secondsToTime($total / $count);
}
?>
<tr>
<td><?= $client_name ?></td>
<td class="text-end"><?= $ticket_raised_count ?></td>
<td class="text-end"><?= $low_ticket_count ?></td>
<td class="text-end"><?= $med_ticket_count ?></td>
<td class="text-end"><?= $high_ticket_count ?></td>
<td class="text-end"><?= $urgent_ticket_count ?></td>
<td class="text-end"><?= $ticket_resolved_count ?></td>
<td class="text-end"><?= $ticket_total_time_worked ?></td>
<td class="text-end"><?= $avg_time_to_respond ?></td>
<td class="text-end"><?= $avg_time_to_resolve ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<?php } ?>
<?= reportSectionOpen('By client', 'Busiest first', 'itflow-report-long') ?>
<?= reportTable($columns, $clients, ['empty' => 'No tickets in this period.', 'totals' => $totals, 'totals_html' => ['sla' => reportRateHtml($totals['sla']), 'csat' => $totals['csat'] === null ? '' : reportRateHtml($totals['csat'], 90, 75)]]) ?>
<div class="card-footer small text-body-secondary">
Opened counts tickets raised in the period; resolved counts those resolved in it, whenever raised. Times run on the clock and are the middle ticket's, so a few long ones do not skew them.
SLA response is the share of first-reply targets met. Satisfaction is from client ratings on tickets closed in the period.
</div>
</div>
<?php
require_once "../../includes/footer.php";
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,162 +1,312 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Ticket Overview - the service desk over a period: tickets opened and
* resolved, how quickly the first reply went out and how long tickets took
* to resolve (the middle ticket - a few that sat open for weeks do not skew
* it), where they came from, how urgent, what about, and on which days and
* hours they arrive. Narrow it to one client or one agent's tickets.
*
* Times are wall-clock, from the ticket being raised; the SLA reports
* measure business hours instead.
*/
enforceUserPermission('module_support');
require_once "includes/inc_report.php";
reportEnforce('ticket_summary');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
$period = reportPeriod('last_90');
$client_id = reportClientId();
$agent_id = reportAgentId();
$filter = reportTicketSql($client_id, $agent_id);
$opened_in = reportRangeSql('ticket_created_at', $period);
$opened_before = reportRangeSql('ticket_created_at', $period, true);
$resolved_in = reportRangeSql('ticket_resolved_at', $period);
$opened = dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND $opened_in");
$opened_prev = dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND $opened_before");
$resolved = dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND $resolved_in");
$resolved_prev = dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND " . reportRangeSql('ticket_resolved_at', $period, true));
$open_now = dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $filter AND " . TICKET_OPEN_SQL);
$response = reportMedian(reportColumn("SELECT TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) FROM tickets WHERE $filter AND $opened_in AND ticket_first_response_at IS NOT NULL"));
$response_prev = reportMedian(reportColumn("SELECT TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) FROM tickets WHERE $filter AND $opened_before AND ticket_first_response_at IS NOT NULL"));
$resolve = reportMedian(reportColumn("SELECT TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_resolved_at) FROM tickets WHERE $filter AND $resolved_in"));
$resolve_prev = reportMedian(reportColumn("SELECT TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_resolved_at) FROM tickets WHERE $filter AND " . reportRangeSql('ticket_resolved_at', $period, true)));
$time_logged = dashboardSum("SELECT SUM(TIME_TO_SEC(ticket_reply_time_worked)) FROM ticket_replies JOIN tickets ON ticket_reply_ticket_id = ticket_id
WHERE $filter AND ticket_reply_archived_at IS NULL AND " . reportRangeSql('ticket_reply_created_at', $period));
// Opened and resolved over the period
$buckets = reportBuckets($period);
$opened_series = reportSeries("SELECT " . reportBucketSql('ticket_created_at', $buckets['unit']) . " AS b, COUNT(ticket_id) AS v FROM tickets WHERE $filter AND $opened_in GROUP BY b", $buckets['keys']);
$resolved_series = reportSeries("SELECT " . reportBucketSql('ticket_resolved_at', $buckets['unit']) . " AS b, COUNT(ticket_id) AS v FROM tickets WHERE $filter AND $resolved_in GROUP BY b", $buckets['keys']);
// Breakdowns of what was opened
$breakdown = function ($column) use ($filter, $opened_in) {
global $mysqli;
$rows = [];
$sql = mysqli_query($mysqli, "SELECT $column AS k, COUNT(ticket_id) AS n FROM tickets WHERE $filter AND $opened_in GROUP BY k ORDER BY n DESC");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[(string) $row['k']] = intval($row['n']);
}
return $rows;
};
$sources = $breakdown("CASE WHEN ticket_source IN ('Email', 'Portal', 'Agent', 'API', 'Recurring', 'Project') THEN ticket_source WHEN ticket_source LIKE '%Recurring%' THEN 'Recurring' ELSE COALESCE(NULLIF(ticket_source, ''), 'Agent') END");
$priorities = $breakdown('ticket_priority');
// By category: opened, resolved, how long, how much time
$category_names = reportTicketCategories();
$categories = [];
$sql = mysqli_query($mysqli, "SELECT ticket_category AS cat, COUNT(ticket_id) AS opened, SUM(ticket_resolved_at IS NOT NULL) AS resolved,
SUM(ticket_priority IN ('Urgent', 'High')) AS urgent
FROM tickets WHERE $filter AND $opened_in GROUP BY ticket_category");
while ($row = mysqli_fetch_assoc($sql)) {
$cat = intval($row['cat']);
$categories[$cat] = ['category' => $category_names[$cat] ?? 'No category', 'cat' => $cat, 'opened' => intval($row['opened']), 'resolved' => intval($row['resolved']),
'urgent' => intval($row['urgent']), 'seconds' => 0, 'resolve' => null];
}
$resolve_times = [];
$sql = mysqli_query($mysqli, "SELECT ticket_category AS cat, TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_resolved_at) AS s FROM tickets WHERE $filter AND $opened_in AND ticket_resolved_at IS NOT NULL");
while ($row = mysqli_fetch_assoc($sql)) {
$resolve_times[intval($row['cat'])][] = floatval($row['s']);
}
$sql = mysqli_query($mysqli, "SELECT ticket_category AS cat, SUM(TIME_TO_SEC(ticket_reply_time_worked)) AS s FROM ticket_replies JOIN tickets ON ticket_reply_ticket_id = ticket_id
WHERE $filter AND $opened_in AND ticket_reply_archived_at IS NULL GROUP BY ticket_category");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($categories[intval($row['cat'])])) {
$categories[intval($row['cat'])]['seconds'] = intval($row['s']);
}
}
foreach ($categories as $cat => &$row) {
$row['resolve'] = reportMedian($resolve_times[$cat] ?? []);
$row['share'] = reportShare($row['opened'], $opened, 1);
}
unset($row);
uasort($categories, function ($a, $b) { return $b['opened'] <=> $a['opened']; });
$categories = array_values($categories);
// Weekday by hour, of what was opened
$heat = [];
$sql = mysqli_query($mysqli, "SELECT WEEKDAY(ticket_created_at) + 1 AS d, HOUR(ticket_created_at) AS h, COUNT(ticket_id) AS n FROM tickets WHERE $filter AND $opened_in GROUP BY d, h");
while ($row = mysqli_fetch_assoc($sql)) {
$heat[intval($row['d'])][intval($row['h'])] = intval($row['n']);
}
$sql_ticket_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(ticket_created_at) AS ticket_year FROM tickets ORDER BY ticket_year DESC");
// Who raises the most
$top_clients = [];
if (!$client_id) {
$sql = mysqli_query($mysqli, "SELECT ticket_client_id AS client_id, client_name, client_abbreviation, COUNT(ticket_id) AS n
FROM tickets JOIN clients ON ticket_client_id = client_id WHERE $filter AND $opened_in
GROUP BY ticket_client_id, client_name, client_abbreviation ORDER BY n DESC LIMIT 8");
while ($row = mysqli_fetch_assoc($sql)) {
$top_clients[] = $row;
}
}
$top_contacts = [];
$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_client_id, client_name, COUNT(ticket_id) AS n
FROM tickets JOIN contacts ON ticket_contact_id = contact_id LEFT JOIN clients ON contact_client_id = client_id
WHERE $filter AND $opened_in GROUP BY contact_id, contact_name, contact_client_id, client_name ORDER BY n DESC LIMIT 8");
while ($row = mysqli_fetch_assoc($sql)) {
$top_contacts[] = $row;
}
$sql_tickets = mysqli_query($mysqli, "SELECT ticket_id FROM tickets");
$category_columns = [
'category' => ['label' => 'Category'],
'opened' => ['label' => 'Opened', 'type' => 'count'],
'share' => ['label' => 'Share', 'type' => 'percent', 'class' => 'text-body-secondary'],
'urgent' => ['label' => 'Urgent or high', 'type' => 'count'],
'resolved' => ['label' => 'Resolved', 'type' => 'count'],
'resolve' => ['label' => 'Typical time to resolve', 'type' => 'duration', 'title' => 'The middle ticket - half took longer, half less'],
'seconds' => ['label' => 'Time logged', 'type' => 'hours'],
];
// Track largest month for chart y-axis max
$largest_ticket_month = 0;
if (reportExporting('tickets')) {
$tickets = [];
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_category, ticket_priority, ticket_source, ticket_status_name,
ticket_created_at, ticket_first_response_at, ticket_resolved_at, client_name, user_name,
(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) AS seconds
FROM tickets
LEFT JOIN clients ON ticket_client_id = client_id
LEFT JOIN users ON ticket_assigned_to = user_id
LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id
WHERE $filter AND $opened_in ORDER BY ticket_created_at ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$row['category'] = $category_names[intval($row['ticket_category'])] ?? '';
$row['response'] = $row['ticket_first_response_at'] ? strtotime($row['ticket_first_response_at']) - strtotime($row['ticket_created_at']) : null;
$tickets[] = $row;
}
reportCsv('Tickets ' . $period['start'] . ' to ' . $period['end'], [
'ticket' => ['label' => 'Ticket', 'csv' => function ($row) { return ticketReference($row); }],
'ticket_subject' => ['label' => 'Subject'],
'client_name' => ['label' => 'Client'],
'category' => ['label' => 'Category'],
'ticket_priority' => ['label' => 'Priority'],
'ticket_source' => ['label' => 'Source'],
'ticket_status_name' => ['label' => 'Status'],
'user_name' => ['label' => 'Assigned to'],
'ticket_created_at' => ['label' => 'Opened'],
'response' => ['label' => 'Hours to first reply', 'type' => 'hours'],
'ticket_resolved_at' => ['label' => 'Resolved'],
'seconds' => ['label' => 'Hours logged', 'type' => 'hours'],
], $tickets);
}
if (reportExporting()) {
reportCsv('Tickets by Category ' . $period['start'] . ' to ' . $period['end'], $category_columns, $categories, ['category' => 'Total', 'opened' => $opened]);
}
require_once "includes/inc_report_layout.php";
$ticket_list = '/agent/tickets.php?' . http_build_query(array_filter(['client_id' => $client_id ?: null, 'assigned' => $agent_id ?: null]));
$source_icons = ['Email' => 'envelope', 'Portal' => 'globe', 'Agent' => 'headset', 'API' => 'plug', 'Recurring' => 'redo-alt', 'Project' => 'project-diagram'];
$priority_tones = ['Urgent' => 'dark', 'High' => 'danger', 'Medium' => 'warning', 'Low' => 'info'];
$source_rows = reportTopN(array_map(function ($k, $v) { return ['label' => $k, 'value' => $v]; }, array_keys($sources), array_values($sources)), 6);
$source_colors = array_map(function ($i) { return reportPalette($i); }, array_keys($source_rows));
$priority_order = array_filter(['Urgent' => $priorities['Urgent'] ?? 0, 'High' => $priorities['High'] ?? 0, 'Medium' => $priorities['Medium'] ?? 0, 'Low' => $priorities['Low'] ?? 0]);
$top_categories = array_slice($categories, 0, 10);
?>
<!-- Responsive chart helpers -->
<style>
.chart-h-320 { position: relative; height: 320px; }
@media (max-width: 576px) { .chart-h-320 { height: 260px; } }
</style>
<div class="itflow-report">
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-life-ring me-2"></i>Ticket Summary</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<?php reportHeader('ticket_summary', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_created_at) AS y FROM tickets"),
'client' => $client_id,
'agent' => $agent_id,
'export' => ['categories' => 'By category', 'tickets' => 'Every ticket opened'],
]); ?>
<?= reportStats([
['label' => 'Opened', 'value' => reportCount($opened), 'sub' => reportChangeHtml($opened, $opened_prev, 'down', $period['compare']), 'url' => $ticket_list . '&show=all'],
['label' => 'Resolved', 'value' => reportCount($resolved), 'sub' => reportChangeHtml($resolved, $resolved_prev, 'up', $period['compare'])],
['label' => 'Open now', 'value' => reportCount($open_now), 'url' => $ticket_list, 'sub' => '<span class="text-body-tertiary">Whenever they were raised</span>'],
['label' => 'First reply', 'value' => reportDuration($response), 'title' => 'The middle ticket - half got a first reply sooner, half later',
'sub' => $response_prev !== null ? 'Typically · <span class="text-body-tertiary">was ' . reportDuration($response_prev) . '</span>' : '<span class="text-body-tertiary">Typically</span>'],
['label' => 'Time to resolve', 'value' => reportDuration($resolve), 'title' => 'The middle ticket - half were resolved sooner, half later',
'sub' => $resolve_prev !== null ? 'Typically · <span class="text-body-tertiary">was ' . reportDuration($resolve_prev) . '</span>' : '<span class="text-body-tertiary">Typically</span>'],
['label' => 'Time logged', 'value' => reportHours($time_logged) . ' h', 'sub' => '<span class="text-body-tertiary">On replies in the period</span>'],
]) ?>
<?= reportSectionOpen('Opened and resolved', escapeHtml($period['range']) . ' · by ' . $buckets['unit']) ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'labels' => $buckets['labels'],
'series' => [
['label' => 'Opened', 'data' => $opened_series, 'tone' => 'accent'],
['label' => 'Resolved', 'data' => $resolved_series, 'tone' => 'success'],
],
'format' => 'count',
], '', 'Tickets opened and resolved over the period') ?>
</div>
</div>
<div class="card-body p-0">
<form class="p-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_ticket_years)) {
$ticket_year = intval($row['ticket_year']); ?>
<option <?php if ($year == $ticket_year) { ?> selected <?php } ?>><?= $ticket_year ?></option>
<?php } ?>
</select>
</form>
<div class="px-3 pb-3">
<div class="chart-h-320">
<canvas id="tickets"></canvas>
<div class="row g-3">
<div class="col-md-6 col-xl-3">
<?= reportSectionOpen('Where they came from', '', 'h-100 mb-0') ?>
<div class="card-body">
<?php if ($source_rows) { ?>
<?= reportChart(['type' => 'doughnut', 'labels' => array_column($source_rows, 'label'), 'series' => [['label' => 'Tickets', 'data' => array_column($source_rows, 'value')]], 'colors' => $source_colors, 'format' => 'count'], 'donut', 'Tickets by source') ?>
<div class="mt-3"><?= reportLegendHtml(array_column($source_rows, 'label'), array_column($source_rows, 'value'), $source_colors, 'count') ?></div>
<?php } else { ?>
<div class="text-center text-body-secondary py-4">No tickets.</div>
<?php } ?>
</div>
</div>
</div>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th class="text-end">January</th>
<th class="text-end">February</th>
<th class="text-end">March</th>
<th class="text-end">April</th>
<th class="text-end">May</th>
<th class="text-end">June</th>
<th class="text-end">July</th>
<th class="text-end">August</th>
<th class="text-end">September</th>
<th class="text-end">October</th>
<th class="text-end">November</th>
<th class="text-end">December</th>
<th class="text-end">Total</th>
</tr>
</thead>
<tbody>
<?php
$total_tickets_for_all_months = 0;
for ($month = 1; $month <= 12; $month++) {
$sql_tickets = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS tickets_for_month FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month");
$row = mysqli_fetch_assoc($sql_tickets);
$tickets_for_month = intval($row['tickets_for_month']);
if ($tickets_for_month > 0 && $tickets_for_month > $largest_ticket_month) {
$largest_ticket_month = $tickets_for_month;
}
$total_tickets_for_all_months += $tickets_for_month; ?>
<td class="text-end"><?= $tickets_for_month ?></td>
<?php } ?>
<td class="text-end"><b><?= $total_tickets_for_all_months ?></b></td>
</tbody>
</table>
<div class="col-md-6 col-xl-3">
<?= reportSectionOpen('How urgent', '', 'h-100 mb-0') ?>
<div class="card-body">
<?php if ($priority_order) {
$priority_colors = ['Urgent' => 'dark', 'High' => 'danger', 'Medium' => 'warning', 'Low' => 'info'];
$colors = array_map(function ($p) use ($priority_colors) { return $priority_colors[$p]; }, array_keys($priority_order)); ?>
<?= reportChart(['type' => 'doughnut', 'labels' => array_keys($priority_order), 'series' => [['label' => 'Tickets', 'data' => array_values($priority_order)]], 'colors' => $colors, 'format' => 'count'], 'donut', 'Tickets by priority') ?>
<div class="mt-3"><?= reportLegendHtml(array_keys($priority_order), array_values($priority_order), $colors, 'count') ?></div>
<?php } else { ?>
<div class="text-center text-body-secondary py-4">No tickets.</div>
<?php } ?>
</div>
</div>
</div>
<div class="col-xl-6">
<?= reportSectionOpen('When they come in', 'Opened, by weekday and hour', 'h-100 mb-0') ?>
<div class="card-body">
<?= reportHeatmap($heat) ?>
<p class="small text-body-secondary mt-2 mb-0">Darker is busier - useful for planning who is on when.</p>
</div>
</div>
</div>
</div>
<?php if ($top_categories) { ?>
<?= reportSectionOpen('What they were about', 'The most common categories') ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'labels' => array_column($top_categories, 'category'),
'series' => [['label' => 'Opened', 'data' => array_column($top_categories, 'opened'), 'tone' => 'accent']],
'format' => 'count',
'legend' => false,
], '', 'Tickets opened in the most common categories') ?>
</div>
</div>
<?php } ?>
<div class="row g-3">
<?php if (!$client_id) { ?>
<div class="col-lg-6">
<?= reportSectionOpen('Clients raising the most', '', 'h-100 mb-0') ?>
<?php if ($top_clients) {
$max = max(1, intval($top_clients[0]['n'])); ?>
<div class="card-body pt-2">
<div class="itflow-dash-bars">
<?php foreach ($top_clients as $row) { ?>
<a class="itflow-dash-bar" href="/agent/tickets.php?client_id=<?= intval($row['client_id']) ?>&show=all">
<span class="itflow-dash-bar-label"><?= escapeHtml($row['client_name']) ?></span>
<span class="itflow-dash-bar-value"><?= intval($row['n']) ?></span>
<span class="itflow-dash-bar-track"><span class="itflow-dash-bar-fill" style="width: <?= round(intval($row['n']) / $max * 100, 1) ?>%"></span></span>
</a>
<?php } ?>
</div>
</div>
<?php } else { ?>
<div class="card-body text-center text-body-secondary py-4">No tickets.</div>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="<?= $client_id ? 'col-12' : 'col-lg-6' ?>">
<?= reportSectionOpen('People raising the most', 'Contacts, with their client', 'h-100 mb-0') ?>
<?php if ($top_contacts) {
$max = max(1, intval($top_contacts[0]['n'])); ?>
<div class="card-body pt-2">
<div class="itflow-dash-bars">
<?php foreach ($top_contacts as $row) { ?>
<a class="itflow-dash-bar" href="/agent/contact.php?client_id=<?= intval($row['contact_client_id']) ?>&contact_id=<?= intval($row['contact_id']) ?>">
<span class="itflow-dash-bar-label"><?= escapeHtml($row['contact_name']) ?> <span class="small text-body-secondary"><?= escapeHtml($row['client_name'] ?? '') ?></span></span>
<span class="itflow-dash-bar-value"><?= intval($row['n']) ?></span>
<span class="itflow-dash-bar-track"><span class="itflow-dash-bar-fill bg-info" style="width: <?= round(intval($row['n']) / $max * 100, 1) ?>%"></span></span>
</a>
<?php } ?>
</div>
</div>
<?php } else { ?>
<div class="card-body text-center text-body-secondary py-4">No tickets with a contact.</div>
<?php } ?>
</div>
</div>
</div>
<?= reportSectionOpen('By category', 'Tickets opened in the period') ?>
<?= reportTable($category_columns, $categories, ['empty' => 'No tickets were opened in this period.', 'totals' => ['category' => 'Total', 'opened' => $opened,
'urgent' => array_sum(array_column($categories, 'urgent')), 'resolved' => array_sum(array_column($categories, 'resolved')), 'seconds' => array_sum(array_column($categories, 'seconds'))]]) ?>
<div class="card-footer small text-body-secondary">
Times run on the clock from when a ticket was raised. "Typical" is the middle ticket, so a few that sat open for weeks do not skew it. Business-hours targets are in the SLA reports.
</div>
</div>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script>
// Bootstrap-like defaults for Chart.js v4
var itflowChart = itflowChartDefaults();
(function () {
var ctx = document.getElementById("tickets");
if (!ctx) return;
var dataPoints = [
<?php
// Recompute for the chart dataset (values already gathered above, but we echo directly again)
for ($month = 1; $month <= 12; $month++) {
$sql_tickets = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS tickets_for_month FROM tickets WHERE YEAR(ticket_created_at) = $year AND MONTH(ticket_created_at) = $month");
$row = mysqli_fetch_assoc($sql_tickets);
$tickets_for_month = intval($row['tickets_for_month']);
echo "$tickets_for_month,";
}
?>
];
new Chart(ctx, {
type: 'line',
data: {
labels: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
datasets: [{
label: "Tickets Raised",
fill: false,
borderColor: "#007bff",
pointBackgroundColor: "#007bff",
pointBorderColor: "#007bff",
pointHoverRadius: 5,
pointHoverBackgroundColor: "#007bff",
pointBorderWidth: 2,
data: dataPoints
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
grid: { display: false },
ticks: { maxTicksLimit: 12 }
},
y: {
beginAtZero: true,
min: 0,
max: <?php
// use your helper if available, otherwise largest_ticket_month as-is
$max = max(5, $largest_ticket_month);
echo function_exists('roundUpToNearestMultiple') ? roundUpToNearestMultiple($max) : $max;
?>,
ticks: { maxTicksLimit: 5, precision: 0 },
grid: { color: itflowChart.grid }
}
},
plugins: {
legend: { display: false }
}
}
});
})();
</script>
<script src="/js/reports.js"></script>

View File

@@ -1,143 +1,182 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* 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.
*/
enforceUserPermission('module_sales', 1);
require_once "includes/inc_report.php";
reportEnforce('tickets_unbilled');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
$client_id = reportClientId();
$default_rate = floatval($config_default_hourly_rate);
$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']);
$tickets[] = $row;
}
$sql_ticket_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(ticket_created_at) AS ticket_year FROM tickets ORDER BY ticket_year DESC");
$clients = [];
foreach ($tickets as $ticket) {
$id = intval($ticket['ticket_client_id']);
$clients[$id] = $clients[$id] ?? ['client_id' => $id, 'client' => $ticket['client_name'], 'abbr' => $ticket['client_abbreviation'], 'rate' => $ticket['rate'],
'default_rate' => $ticket['default_rate'], 'tickets' => 0, 'seconds' => 0, 'billable_hours' => 0.0, 'value' => 0.0, 'oldest' => 0, 'no_time' => 0];
$clients[$id]['tickets']++;
$clients[$id]['seconds'] += $ticket['seconds'];
$clients[$id]['billable_hours'] += $ticket['billable_hours'];
$clients[$id]['value'] += $ticket['value'];
$clients[$id]['oldest'] = max($clients[$id]['oldest'], $ticket['waiting']);
$clients[$id]['no_time'] += $ticket['billable_hours'] <= 0 ? 1 : 0;
}
uasort($clients, function ($a, $b) { return $b['value'] <=> $a['value'] ?: $b['tickets'] <=> $a['tickets']; });
$clients = array_values($clients);
$sql_clients = mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE 1=1 " . clientScopeSql('client_id') . " ORDER BY client_name ASC");
$waiting_html = function ($days) {
$tone = $days > 30 ? 'danger' : ($days > 7 ? 'warning' : 'secondary');
return '<span class="badge rounded-pill bg-' . $tone . '-subtle text-' . $tone . '-emphasis border border-' . $tone . '-subtle fw-normal">'
. ($days <= 0 ? 'Today' : $days . ' day' . ($days === 1 ? '' : 's')) . '</span>';
};
$rate_html = function ($row) {
if ($row['rate'] <= 0) {
return '<span class="text-warning-emphasis small" title="Set an hourly rate on the client, or a default in Admin > Settings > Invoices">No rate</span>';
}
return reportMoney($row['rate']) . ($row['default_rate'] ? ' <span class="small text-body-tertiary" title="The client has no rate of its own - this is the default hourly rate">default</span>' : '');
};
$rows = 0;
$client_columns = [
'client' => ['label' => 'Client', 'html' => function ($row) {
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>' : '');
}],
'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'],
'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) {
return $waiting_html($row['oldest']);
}],
];
$ticket_columns = [
'ticket' => ['label' => 'Ticket', 'csv' => function ($row) { return ticketReference($row) . ' ' . $row['ticket_subject']; }, 'html' => function ($row) {
return reportTicketLink($row);
}, 'class' => 'itflow-report-text'],
'client_name' => ['label' => 'Client', 'html' => function ($row) {
return reportClientCell($row['ticket_client_id'], $row['client_name'], $row['client_abbreviation']);
}],
'user_name' => ['label' => 'Agent', 'html' => function ($row) {
return reportAgentCell($row['ticket_assigned_to'], $row['user_name'] ?? '', $row['user_avatar'] ?? '');
}],
'resolved' => ['label' => 'Done', 'type' => 'date', 'class' => 'text-nowrap', 'csv' => function ($row) {
return substr($row['ticket_resolved_at'] ?: $row['ticket_closed_at'], 0, 10);
}, 'html' => function ($row) {
return escapeHtml(date('M j, Y', strtotime($row['ticket_resolved_at'] ?: $row['ticket_closed_at'])));
}],
'waiting' => ['label' => 'Waiting', 'type' => 'count', 'csv_label' => 'Days waiting', 'html' => function ($row) use ($waiting_html) {
return $waiting_html($row['waiting']);
}],
'seconds' => ['label' => 'Time logged', 'type' => 'hours', 'decimals' => 2, 'html' => function ($row) {
return $row['seconds'] <= 0 ? '<span class="text-warning-emphasis" title="No time logged on this ticket">None</span>' : reportHours($row['seconds'], 2);
}],
'billable_hours' => ['label' => 'To bill', 'type' => 'decimal', 'decimals' => 2],
'value' => ['label' => 'Value', 'type' => 'money', 'class' => 'fw-semibold'],
];
foreach ($tickets as &$ticket) {
$ticket['resolved'] = $ticket['ticket_resolved_at'] ?: $ticket['ticket_closed_at'];
}
unset($ticket);
$totals = ['tickets' => count($tickets), 'seconds' => array_sum(array_column($tickets, 'seconds')),
'billable_hours' => array_sum(array_column($tickets, 'billable_hours')), 'value' => array_sum(array_column($tickets, 'value'))];
if (reportExporting('tickets')) {
reportCsv('Unbilled Tickets', $ticket_columns, $tickets, ['ticket' => 'Total'] + $totals);
}
if (reportExporting()) {
reportCsv('Unbilled Work by Client', $client_columns, $clients, ['client' => 'Total'] + $totals);
}
require_once "includes/inc_report_layout.php";
$no_time = count(array_filter($tickets, function ($t) { return $t['billable_hours'] <= 0; }));
$no_rate = count(array_filter($tickets, function ($t) { return $t['rate'] <= 0; }));
$over_30 = array_filter($tickets, function ($t) { return $t['waiting'] > 30; });
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-life-ring me-2"></i>Unbilled Tickets By Client</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
<div class="itflow-report">
<?php reportHeader('tickets_unbilled', [
'client' => $client_id,
'subtitle' => 'As of ' . date('M j, Y'),
'export' => ['clients' => 'By client', 'tickets' => 'Every ticket'],
]); ?>
<?= 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',
'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' => '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>'],
]) ?>
<?php if ($no_time || $no_rate) { ?>
<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_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>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_ticket_years)) {
$ticket_year = intval($row['ticket_year']); ?>
<option <?php if ($year == $ticket_year) { ?> selected <?php } ?> > <?= $ticket_year ?></option>
<?php } ?>
</select>
</form>
<?php } ?>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Tickets Raised</th>
<th class="text-end">Billable Tickets</th>
<th class="text-end">Unbilled Tickets</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql_clients)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
// Calculate total tickets raised in period
$sql_ticket_raised_count = mysqli_query(
$mysqli,
"SELECT
COUNT(ticket_id) AS ticket_raised_count
FROM
tickets
WHERE
YEAR(ticket_created_at) = $year
AND
ticket_client_id = $client_id"
);
$row = mysqli_fetch_assoc($sql_ticket_raised_count);
$ticket_raised_count = intval($row['ticket_raised_count']);
// Calculate total tickets raised in period that are closed and billable
$sql_ticket_closed_count = mysqli_query(
$mysqli,
"SELECT
COUNT(ticket_id) AS ticket_closed_count
FROM
tickets
WHERE
YEAR(ticket_created_at) = $year
AND
ticket_client_id = $client_id
AND
ticket_closed_at IS NOT NULL
AND
ticket_billable = 1
");
$row = mysqli_fetch_assoc($sql_ticket_closed_count);
$ticket_closed_count = intval($row['ticket_closed_count']);
// Calculate total tickets raised in period that are closed and billable, but not invoiced
$sql_ticket_unbilled_count = mysqli_query(
$mysqli,
"SELECT
COUNT(ticket_id) AS ticket_unbilled_count
FROM
tickets
WHERE
YEAR(ticket_created_at) = $year
AND
ticket_client_id = $client_id
AND
ticket_closed_at IS NOT NULL
AND
ticket_billable = 1
AND
ticket_invoice_id = 0");
$row = mysqli_fetch_assoc($sql_ticket_unbilled_count);
$ticket_unbilled_count = intval($row['ticket_unbilled_count']);
if ($ticket_unbilled_count > 0) {
$rows = $rows + 1;
?>
<tr>
<td>
<a href="../../agent/tickets.php?client_id=<?= $client_id ?>&billable=1&unbilled"><?= $client_name ?></a>
</td>
<td class="text-end"><?= $ticket_raised_count ?></td>
<td class="text-end"><?= $ticket_closed_count ?></td>
<td class="text-end"><?= $ticket_unbilled_count ?></td>
</tr>
<?php
}
}
if ($rows == 0) {
?>
<tr>
<td colspan="4">You are all caught up! There are no unbilled tickets for this year.
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<?= reportSectionOpen('By client', 'Most to bill first') ?>
<?= reportTable($client_columns, $clients, [
'empty' => reportEmpty('You are all caught up - every billable ticket that is done has been invoiced.'),
'totals' => ['client' => 'Total'] + $totals,
]) ?>
</div>
<?php
require_once "../../includes/footer.php";
<?php if ($tickets) { ?>
<?= 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.
</div>
</div>
<?php } ?>
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -1,140 +1,220 @@
<?php
require_once "includes/inc_all_reports.php";
/*
* Technician Performance - each agent over the period: time logged and how
* much of it was on billable tickets, utilization against the hours they
* were available (working days in the period - the business days and
* closure days set for SLAs - times the hours in a working day), replies
* sent, tickets resolved and still open, the typical first reply on their
* tickets, SLA response compliance and client ratings.
*
* Utilization is a guide, not a timesheet - it only counts time logged on
* ticket replies.
*/
enforceUserPermission('module_support');
require_once "includes/inc_report.php";
reportEnforce('time_by_tech');
if (isset($_GET['year'])) {
$year = intval($_GET['year']);
} else {
$year = date('Y');
$period = reportPeriod('last_30');
$client_id = reportClientId();
$workday = isset($_GET['hours']) && floatval($_GET['hours']) > 0 ? min(24, round(floatval($_GET['hours']), 2)) : reportWorkdayHours();
$working_days = reportWorkingDays($period['start'], $period['end']);
$capacity = $working_days * $workday * 3600;
$scope = reportClientSql('ticket_client_id', $client_id);
// Every active agent, and anyone else with something in the period
$agents = [];
$sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar, user_status, user_archived_at FROM users WHERE user_type = 1 ORDER BY user_name");
while ($row = mysqli_fetch_assoc($sql)) {
$agents[intval($row['user_id'])] = ['user_id' => intval($row['user_id']), 'agent' => $row['user_name'], 'avatar' => $row['user_avatar'] ?? '',
'active' => intval($row['user_status']) === 1 && $row['user_archived_at'] === null,
'seconds' => 0, 'billable' => 0, 'replies' => 0, 'tickets_touched' => 0, 'resolved' => 0, 'open_now' => 0, 'response' => null,
'sla_met' => 0, 'sla_missed' => 0, 'good' => 0, 'bad' => 0];
}
if (isset($_GET['month'])) {
$month = intval($_GET['month']);
} else {
$month = date('m');
$sql = mysqli_query($mysqli, "SELECT ticket_reply_by AS u, SUM(TIME_TO_SEC(ticket_reply_time_worked)) AS s,
SUM(CASE WHEN ticket_billable = 1 THEN TIME_TO_SEC(ticket_reply_time_worked) ELSE 0 END) AS b,
SUM(ticket_reply_type = 'Public') AS replies, COUNT(DISTINCT ticket_id) AS touched
FROM ticket_replies JOIN tickets ON ticket_reply_ticket_id = ticket_id
WHERE ticket_reply_archived_at IS NULL AND tickets.ticket_archived_at IS NULL AND " . reportRangeSql('ticket_reply_created_at', $period) . " $scope
GROUP BY ticket_reply_by");
while ($row = mysqli_fetch_assoc($sql)) {
$u = intval($row['u']);
if (isset($agents[$u])) {
$agents[$u]['seconds'] = intval($row['s']);
$agents[$u]['billable'] = intval($row['b']);
$agents[$u]['replies'] = intval($row['replies']);
$agents[$u]['tickets_touched'] = intval($row['touched']);
}
}
$sql = mysqli_query($mysqli, "SELECT ticket_assigned_to AS u, COUNT(ticket_id) AS n, SUM(ticket_response_sla_met = 1) AS met, SUM(ticket_response_sla_met = 0) AS missed
FROM tickets WHERE ticket_archived_at IS NULL AND " . reportRangeSql('ticket_resolved_at', $period) . " $scope GROUP BY ticket_assigned_to");
while ($row = mysqli_fetch_assoc($sql)) {
$u = intval($row['u']);
if (isset($agents[$u])) {
$agents[$u]['resolved'] = intval($row['n']);
$agents[$u]['sla_met'] = intval($row['met']);
$agents[$u]['sla_missed'] = intval($row['missed']);
}
}
$sql = mysqli_query($mysqli, "SELECT ticket_assigned_to AS u, COUNT(ticket_id) AS n FROM tickets WHERE ticket_archived_at IS NULL AND " . TICKET_OPEN_SQL . " $scope GROUP BY ticket_assigned_to");
$unassigned_open = 0;
while ($row = mysqli_fetch_assoc($sql)) {
$u = intval($row['u']);
if (isset($agents[$u])) {
$agents[$u]['open_now'] = intval($row['n']);
} elseif (!$u) {
$unassigned_open = intval($row['n']);
}
}
$sql = mysqli_query($mysqli, "SELECT ticket_assigned_to AS u, SUM(ticket_feedback = 'Good') AS good, SUM(ticket_feedback = 'Bad') AS bad
FROM tickets WHERE ticket_archived_at IS NULL AND " . reportRangeSql('ticket_closed_at', $period) . " $scope GROUP BY ticket_assigned_to");
while ($row = mysqli_fetch_assoc($sql)) {
if (isset($agents[intval($row['u'])])) {
$agents[intval($row['u'])]['good'] = intval($row['good']);
$agents[intval($row['u'])]['bad'] = intval($row['bad']);
}
}
$responses = [];
$sql = mysqli_query($mysqli, "SELECT ticket_assigned_to AS u, TIMESTAMPDIFF(SECOND, ticket_created_at, ticket_first_response_at) AS s
FROM tickets WHERE ticket_archived_at IS NULL AND ticket_first_response_at IS NOT NULL AND " . reportRangeSql('ticket_created_at', $period) . " $scope");
while ($row = mysqli_fetch_assoc($sql)) {
$responses[intval($row['u'])][] = floatval($row['s']);
}
$sql_ticket_years = mysqli_query($mysqli, "SELECT DISTINCT YEAR(ticket_created_at) AS ticket_year FROM tickets ORDER BY ticket_year DESC");
foreach ($agents as $u => &$row) {
$row['billable_share'] = reportShare($row['billable'], $row['seconds']);
$row['utilization'] = $capacity > 0 ? reportShare($row['seconds'], $capacity) : null;
$row['response'] = reportMedian($responses[$u] ?? []);
$row['sla'] = reportShare($row['sla_met'], $row['sla_met'] + $row['sla_missed']);
$row['csat'] = reportShare($row['good'], $row['good'] + $row['bad']);
}
unset($row);
// Leave out anyone gone with nothing to show
$agents = array_values(array_filter($agents, function ($a) {
return $a['active'] || $a['seconds'] || $a['resolved'] || $a['open_now'] || $a['replies'];
}));
usort($agents, function ($a, $b) { return $b['seconds'] <=> $a['seconds'] ?: strcasecmp($a['agent'], $b['agent']); });
$sql_clients = mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE client_archived_at IS NULL ORDER BY client_name ASC");
$columns = [
'agent' => ['label' => 'Agent', 'html' => function ($row) {
return reportAgentCell($row['user_id'], $row['agent'], $row['avatar']) . ($row['active'] ? '' : ' <span class="badge bg-secondary-subtle text-secondary-emphasis fw-normal">Inactive</span>');
}],
'seconds' => ['label' => 'Hours logged', 'type' => 'hours', 'class' => 'fw-semibold'],
'billable' => ['label' => 'Billable', 'type' => 'hours', 'title' => 'Time on billable tickets'],
'billable_share' => ['label' => 'Billable share', 'type' => 'percent', 'class' => 'text-body-secondary'],
'utilization' => ['label' => 'Utilization', 'type' => 'percent', 'title' => 'Hours logged against the hours available in the period', 'html' => function ($row) {
if ($row['utilization'] === null) {
return '<span class="itflow-report-zero">–</span>';
}
$share = $row['utilization'];
$tone = $share >= 70 ? 'bg-success' : ($share >= 40 ? '' : 'bg-warning');
return '<div class="d-flex align-items-center justify-content-end gap-2"><div class="itflow-report-meter d-none d-lg-flex" style="width: 5rem"><span class="' . $tone . '" style="width: ' . min(100, round($share, 1)) . '%"></span></div>'
. '<span class="small">' . reportPercent(round($share)) . '</span></div>';
}],
'replies' => ['label' => 'Replies sent', 'type' => 'count', 'title' => 'Replies the client can see'],
'tickets_touched' => ['label' => 'Tickets worked', 'type' => 'count', 'title' => 'Tickets they replied on or logged time to'],
'resolved' => ['label' => 'Resolved', 'type' => 'count', 'title' => 'Tickets assigned to them, resolved in the period'],
'open_now' => ['label' => 'Open now', 'type' => 'count', 'html' => function ($row) {
return $row['open_now'] ? '<a class="itflow-report-amount" href="/agent/tickets.php?assigned=' . $row['user_id'] . '">' . $row['open_now'] . '</a>' : '<span class="itflow-report-zero">–</span>';
}],
'response' => ['label' => 'First reply', 'type' => 'duration', 'title' => 'Typical (middle) time to the first reply on tickets assigned to them'],
'sla' => ['label' => 'SLA response', 'type' => 'percent', 'html' => function ($row) { return reportRateHtml($row['sla']); }],
'csat' => ['label' => 'Satisfaction', 'type' => 'percent', 'html' => function ($row) {
return $row['csat'] === null ? '<span class="itflow-report-zero">–</span>' : reportRateHtml($row['csat'], 90, 75) . ' <span class="small text-body-tertiary">' . ($row['good'] + $row['bad']) . '</span>';
}],
];
$sql_users = mysqli_query($mysqli, "
SELECT users.user_id, user_name FROM users
LEFT JOIN user_settings on users.user_id = user_settings.user_id
WHERE user_type = 1
AND user_status = 1
AND user_archived_at IS NULL
ORDER BY user_name DESC"
);
// TODO: Maybe try and filter this to just users with the support module perm
$total_seconds = array_sum(array_column($agents, 'seconds'));
$total_billable = array_sum(array_column($agents, 'billable'));
$active_count = count(array_filter($agents, function ($a) { return $a['active']; }));
$totals = ['agent' => 'Total', 'seconds' => $total_seconds, 'billable' => $total_billable, 'billable_share' => reportShare($total_billable, $total_seconds),
'utilization' => $capacity > 0 && $active_count ? reportShare($total_seconds, $capacity * $active_count) : null,
'replies' => array_sum(array_column($agents, 'replies')), 'resolved' => array_sum(array_column($agents, 'resolved')), 'open_now' => array_sum(array_column($agents, 'open_now'))];
if (reportExporting()) {
reportCsv('Technician Performance ' . $period['start'] . ' to ' . $period['end'], $columns, $agents, $totals);
}
// Hours per agent over the period, billable and not
$buckets = reportBuckets($period);
$weekly = [];
foreach (array_slice($agents, 0, 8) as $i => $agent) {
$data = reportSeries("SELECT " . reportBucketSql('ticket_reply_created_at', $buckets['unit']) . " AS b, SUM(TIME_TO_SEC(ticket_reply_time_worked)) / 3600 AS v
FROM ticket_replies JOIN tickets ON ticket_reply_ticket_id = ticket_id
WHERE ticket_reply_by = " . intval($agent['user_id']) . " AND ticket_reply_archived_at IS NULL AND tickets.ticket_archived_at IS NULL AND " . reportRangeSql('ticket_reply_created_at', $period) . " $scope
GROUP BY b", $buckets['keys']);
if (array_sum($data) > 0) {
$weekly[] = ['label' => $agent['agent'], 'data' => $data, 'tone' => reportPalette($i), 'type' => 'line'];
}
}
require_once "includes/inc_report_layout.php";
$hours_control = '<div class="col-sm-6 col-lg-auto"><div class="input-group" title="Hours an agent works in a day - from the business hours in Admin > SLA unless you enter another">'
. '<span class="input-group-text"><i class="fas fa-fw fa-business-time"></i></span>'
. '<input type="text" inputmode="decimal" class="form-control" style="max-width: 6rem" name="hours" value="' . escapeHtml(rtrim(rtrim(number_format($workday, 2, '.', ''), '0'), '.')) . '" aria-label="Hours in a working day" data-report-autosubmit>'
. '<span class="input-group-text">h a day</span></div></div>';
$with_time = array_values(array_filter($agents, function ($a) { return $a['seconds'] > 0; }));
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-life-ring me-2"></i>Time Logged By Technician</h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
</div>
</div>
<div class="card-body">
<form class="mb-3">
<select onchange="this.form.submit()" class="form-select" name="year">
<?php
while ($row = mysqli_fetch_assoc($sql_ticket_years)) {
$ticket_year = intval($row['ticket_year']); ?>
<option <?php if ($year == $ticket_year) { ?> selected <?php } ?> > <?= $ticket_year ?></option>
<?php } ?>
</select>
</form>
<div class="itflow-report">
<div class="card card-dark mb-3">
<div class="card-header">
<h3 class="card-title"><i class="fas fa-fw fa-chart-area me-2"></i>Yearly (<?= $year ?>)</h3>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Technician</th>
<th class="text-end">Tickets assigned</th>
<th class="text-end">Tickets touched</th>
<th class="text-end">Total time worked <i>(H:M:S)</i></th>
</tr>
</thead>
<tbody>
<?php
<?php reportHeader('time_by_tech', [
'period' => $period,
'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_reply_created_at) AS y FROM ticket_replies"),
'client' => $client_id,
'controls' => $hours_control,
]); ?>
while ($agent_row = mysqli_fetch_assoc($sql_users)) {
$user_id = intval($agent_row['user_id']);
$user_name = escapeHtml($agent_row['user_name']);
<?= reportStats([
['label' => 'Hours logged', 'value' => reportHours($total_seconds) . ' h', 'sub' => '<span class="text-body-tertiary">By ' . count($with_time) . ' agent' . (count($with_time) === 1 ? '' : 's') . '</span>'],
['label' => 'Billable', 'value' => reportPercent(reportShare($total_billable, $total_seconds)), 'sub' => escapeHtml(reportHours($total_billable)) . ' h <span class="text-body-tertiary">on billable tickets</span>'],
['label' => 'Utilization', 'value' => reportPercent($totals['utilization'] === null ? null : round($totals['utilization'])),
'sub' => '<span class="text-body-tertiary">Of ' . $working_days . ' working day' . ($working_days === 1 ? '' : 's') . ' × ' . escapeHtml(rtrim(rtrim(number_format($workday, 2), '0'), '.')) . ' h each</span>'],
['label' => 'Resolved', 'value' => reportCount($totals['resolved']), 'sub' => reportCount($totals['open_now']) . ' <span class="text-body-tertiary">open now' . ($unassigned_open ? ', ' . $unassigned_open . ' unassigned' : '') . '</span>'],
]) ?>
// Get tickets in period that are still assigned to the technician/agent
$sql_ticket_count = mysqli_query($mysqli, "SELECT COUNT(ticket_id) AS ticket_count FROM tickets WHERE YEAR(ticket_created_at) = $year AND ticket_assigned_to = $user_id");
$row = mysqli_fetch_assoc($sql_ticket_count);
$ticket_raised_count = intval($row['ticket_count']);
// Get unique tickets in period that the agent replied to/touched
$sql_tickets_touched = mysqli_query($mysqli, "
SELECT COUNT(DISTINCT ticket_id) AS tickets_touched
FROM (
-- Tickets the agent replied to
SELECT ticket_reply_ticket_id AS ticket_id
FROM ticket_replies
WHERE YEAR(ticket_reply_created_at) = $year AND ticket_reply_by = $user_id
UNION
-- Tickets the agent opened
SELECT ticket_id
FROM tickets
WHERE YEAR(ticket_created_at) = $year AND ticket_created_by = $user_id
UNION
-- Tickets the agent closed
SELECT ticket_id
FROM tickets
WHERE YEAR(ticket_created_at) = $year AND ticket_closed_by = $user_id
)
AS tickets_touched
");
$row = mysqli_fetch_assoc($sql_tickets_touched);
$tickets_touched = intval($row['tickets_touched']);
// Calculate total time tracked towards tickets in the period (for this agent)
$sql_time = mysqli_query($mysqli, "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(ticket_reply_time_worked))) as total_time FROM ticket_replies LEFT JOIN tickets ON tickets.ticket_id = ticket_replies.ticket_reply_ticket_id WHERE YEAR(ticket_created_at) = $year AND ticket_reply_by = $user_id AND ticket_reply_time_worked IS NOT NULL");
$row = mysqli_fetch_assoc($sql_time);
$ticket_total_time_worked = escapeHtml($row['total_time']);
?>
<tr>
<td><?= $user_name ?></td>
<td class="text-end"><?= $ticket_raised_count ?></td>
<td class="text-end"><?= $tickets_touched ?></td>
<td class="text-end"><?= $ticket_total_time_worked ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php if ($with_time) { ?>
<div class="row g-3">
<div class="col-xl-5">
<?= reportSectionOpen('Hours logged', 'Billable and not', 'h-100 mb-0') ?>
<div class="card-body">
<?= reportChart([
'type' => 'bar',
'horizontal' => true,
'stacked' => true,
'labels' => array_column($with_time, 'agent'),
'series' => [
['label' => 'Billable', 'data' => array_map(function ($a) { return round($a['billable'] / 3600, 1); }, $with_time), 'tone' => 'accent', 'stack' => 'h'],
['label' => 'Not billable', 'data' => array_map(function ($a) { return round(($a['seconds'] - $a['billable']) / 3600, 1); }, $with_time), 'tone' => 'faint', 'stack' => 'h'],
],
'format' => 'hours',
], '', 'Hours logged per agent, billable and not') ?>
</div>
</div>
</div>
<div class="col-xl-7">
<?= reportSectionOpen('Hours over the period', 'By ' . $buckets['unit'], 'h-100 mb-0') ?>
<div class="card-body">
<?= reportChart(['type' => 'line', 'labels' => $buckets['labels'], 'series' => $weekly, 'format' => 'hours', 'legend' => true], '', 'Hours logged by each agent over the period') ?>
</div>
</div>
</div>
</div>
<?php } ?>
<!-- TODO: Monthly version of this report -->
<?= reportSectionOpen('By agent', 'Most hours first') ?>
<?= reportTable($columns, $agents, ['empty' => 'No agents.', 'totals' => $totals, 'totals_html' => ['utilization' => $totals['utilization'] === null ? '' : reportPercent(round($totals['utilization']))]]) ?>
<div class="card-footer small text-body-secondary">
Hours come from time logged on ticket replies in the period. Utilization compares them with the working days in the period
(the business days in Admin > SLA, less closure days) at <?= escapeHtml(rtrim(rtrim(number_format($workday, 2), '0'), '.')) ?> hours a day - it is a guide, not a timesheet.
Resolved, SLA and first reply go by who the ticket is assigned to.
</div>
</div>
<?php
require_once "../../includes/footer.php";
</div>
<?php require_once "../../includes/footer.php"; ?>
<script src="/js/reports.js"></script>

View File

@@ -311,7 +311,8 @@ if (isset($_POST['add_ticket_feedback'])) {
validateCSRFToken();
$ticket_id = intval($_POST['ticket_id']);
$feedback = escapeSql($_POST['add_ticket_feedback']);
// Only the two ratings the portal offers - the reports count Good against Bad
$feedback = $_POST['add_ticket_feedback'] === 'Bad' ? 'Bad' : 'Good';
// Verify the contact has access to the provided ticket ID
if (verifyContactTicketAccess($ticket_id, "Closed")) {

View File

@@ -5443,3 +5443,333 @@ img.itflow-contact-avatar {
flex-wrap: wrap;
row-gap: .25rem;
}
/* Reports - agent/reports/, functions/reports.php
The report header (title and dates on the dark bar, the filters under it),
a strip of figures, then cards of charts and tables. Section cards have the
dashboard's quiet headers, and every figure uses tabular numbers so columns
of amounts line up. Charts are drawn by js/reports.js. Printed, the menu,
the filters and the buttons drop away and the company, the date printed and
who printed it appear under the title instead. */
.itflow-report {
font-variant-numeric: tabular-nums;
}
.itflow-report > .card,
.itflow-report > .row {
margin-bottom: 1rem;
}
.itflow-report-subtitle {
margin-left: .6rem;
font-size: .875rem;
font-weight: 400;
opacity: .75;
}
.itflow-report-print-meta {
display: none;
}
.itflow-report-group-title {
font-size: 1.125rem;
font-weight: 600;
}
/* Sections: a heading and its chart or table, without the heavy header bar */
.itflow-report-section > .card-header {
background: transparent;
border-bottom: 0;
padding-bottom: .25rem;
}
.itflow-report-section .card-title {
font-size: 1rem;
font-weight: 600;
}
.itflow-report-section > .table-responsive,
.itflow-report-section > .list-group {
border-top: var(--bs-border-width) solid var(--bs-border-color-translucent);
margin-top: .5rem;
}
.itflow-report-section .list-group {
--bs-list-group-action-color: var(--bs-body-color);
}
/* The figures along the top: cells that wrap onto as many rows as they need,
with hairlines between them drawn by the 1px gap over the border colour */
.itflow-report-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr));
gap: 1px;
overflow: hidden;
background-color: var(--bs-border-color-translucent);
}
.itflow-report-stat {
display: flex;
flex-direction: column;
justify-content: center;
min-width: 0;
padding: .9rem 1rem;
background-color: var(--bs-card-bg, var(--bs-body-bg));
color: inherit;
text-decoration: none;
}
a.itflow-report-stat:hover,
a.itflow-report-stat:focus-visible {
background-color: var(--bs-tertiary-bg);
color: inherit;
}
.itflow-report-stat-label {
font-size: .8rem;
color: var(--bs-secondary-color);
}
.itflow-report-stat-value {
margin: .1rem 0;
overflow: hidden;
font-size: 1.45rem;
font-weight: 600;
line-height: 1.2;
text-overflow: ellipsis;
white-space: nowrap;
}
.itflow-report-stat-sub {
font-size: .8rem;
color: var(--bs-secondary-color);
}
.itflow-report-chart {
position: relative;
height: 260px;
}
.itflow-report-chart-sm {
height: 200px;
}
.itflow-report-chart-lg {
height: 320px;
}
.itflow-report-chart-donut {
height: 190px;
}
@media (max-width: 575.98px) {
.itflow-report-chart,
.itflow-report-chart-lg {
height: 240px;
}
}
/* Tables: sortable headings, and a totals row that reads as one */
.itflow-report-table > tfoot > tr > td {
border-top: 2px solid var(--bs-border-color);
border-bottom: 0;
background-color: var(--bs-tertiary-bg);
}
.itflow-report-sortable {
cursor: pointer;
user-select: none;
}
.itflow-report-sortable::after {
content: "\f0dc";
margin-left: .35rem;
font-family: "Font Awesome 5 Free";
font-weight: 900;
font-size: .7rem;
opacity: .25;
}
.itflow-report-sortable[aria-sort=ascending]::after {
content: "\f0de";
opacity: .8;
}
.itflow-report-sortable[aria-sort=descending]::after {
content: "\f0dd";
opacity: .8;
}
.itflow-report-table td.itflow-report-sub {
padding-left: 1.75rem;
}
.itflow-report-table tr.itflow-report-group-row > td {
background-color: var(--bs-tertiary-bg);
font-weight: 600;
}
/* A year of months is wide - the first column stays put while it scrolls */
.itflow-report-grid > :not(caption) > tr > :first-child {
position: sticky;
left: 0;
z-index: 1;
min-width: 11rem;
background-color: var(--bs-card-bg, var(--bs-body-bg));
}
.itflow-report-grid > thead > tr > :first-child {
background-color: var(--bs-tertiary-bg);
}
.itflow-report-grid > tfoot > tr > :first-child,
.itflow-report-grid tr.itflow-report-group-row > :first-child {
background-color: var(--bs-tertiary-bg);
}
.itflow-report-grid {
font-size: .875rem;
}
.itflow-report-grid td,
.itflow-report-grid th {
white-space: nowrap;
}
.itflow-report a.itflow-report-amount {
color: inherit;
text-decoration: none;
}
.itflow-report a.itflow-report-amount:hover,
.itflow-report a.itflow-report-amount:focus-visible {
color: var(--bs-link-hover-color);
text-decoration: underline;
}
.itflow-report-table .font-monospace {
white-space: nowrap;
}
/* A tight table wraps its headings and long client names before it scrolls */
.itflow-report-table > thead > tr > th {
vertical-align: bottom;
}
.itflow-report-table:not(.itflow-report-grid) > thead > tr > th:not(:first-child) {
min-width: 4.5rem;
}
.itflow-report-client-name {
min-width: 9rem;
}
/* A column of free text (a scope, a purpose) gets room before the numbers do */
.itflow-report-text {
min-width: 14rem;
}
.itflow-report-zero {
color: var(--bs-tertiary-color);
}
/* A share of something as a thin bar under or beside a figure */
.itflow-report-meter {
display: flex;
height: .375rem;
min-width: 4rem;
overflow: hidden;
border-radius: 1rem;
background-color: var(--bs-secondary-bg);
}
.itflow-report-meter > span {
height: 100%;
background-color: var(--itflow-accent);
}
/* When tickets come in: weekday by hour, darker for more */
.itflow-report-heat {
width: 100%;
border-collapse: separate;
border-spacing: 2px;
font-size: .7rem;
}
.itflow-report-heat th {
padding: 0 .25rem;
font-weight: 500;
color: var(--bs-secondary-color);
text-align: center;
white-space: nowrap;
}
.itflow-report-heat th[scope=row] {
text-align: right;
}
.itflow-report-heat td {
height: 1.4rem;
min-width: .7rem;
border-radius: 3px;
background-color: color-mix(in srgb, var(--itflow-accent) calc(var(--heat, 0) * 100%), var(--bs-secondary-bg));
}
/* The Reports page: a card per report */
.itflow-report-card {
transition: border-color .12s ease-in-out, background-color .12s ease-in-out;
}
.itflow-report-card:hover,
.itflow-report-card:focus-visible {
border-color: var(--itflow-accent);
background-color: var(--bs-tertiary-bg);
}
.itflow-report-card-icon {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
justify-content: center;
width: 2.5rem;
height: 2.5rem;
border-radius: var(--bs-border-radius-lg);
font-size: 1.05rem;
}
/* Client review: notes on what to do next */
.itflow-report-advice {
margin: 0;
padding: 0;
list-style: none;
}
.itflow-report-advice li {
display: flex;
gap: .75rem;
padding: .55rem 0;
border-top: var(--bs-border-width) solid var(--bs-border-color-translucent);
}
.itflow-report-advice li:first-child {
border-top: 0;
}
.itflow-report-advice i {
margin-top: .2rem;
}
@media print {
.itflow-report-print-meta {
display: block;
padding: 0 1rem .5rem;
font-size: .8rem;
color: var(--bs-secondary-color);
}
.itflow-report-head .card-header {
background-color: transparent !important;
color: var(--bs-body-color) !important;
}
.itflow-report-head .card-title {
font-size: 1.4rem;
}
.itflow-report .card {
break-inside: avoid;
}
.itflow-report .card.itflow-report-long {
break-inside: auto;
}
.itflow-report-stats,
.itflow-report-heat td,
.itflow-report-meter,
.itflow-report-meter > span,
.itflow-dash-aging > span,
.itflow-dash-legend-swatch {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.itflow-report-sortable::after {
display: none;
}
.itflow-report-grid > :not(caption) > tr > :first-child {
position: static;
}
.itflow-report .table-responsive {
overflow: visible;
}
/* A printed page is narrower than the large breakpoint - keep side-by-side cards side by side */
.itflow-report .row > .col-lg-4 { flex: 0 0 auto; width: 33.333%; }
.itflow-report .row > .col-lg-5 { flex: 0 0 auto; width: 41.667%; }
.itflow-report .row > .col-lg-6 { flex: 0 0 auto; width: 50%; }
.itflow-report .row > .col-lg-7 { flex: 0 0 auto; width: 58.333%; }
.itflow-report .row > .col-lg-8 { flex: 0 0 auto; width: 66.667%; }
/* Chrome drops what a stretched card holds when it splits a row of them across pages */
.itflow-report .row {
break-inside: avoid;
}
.itflow-report .row .card.h-100 {
height: auto !important;
}
.itflow-report .badge,
.itflow-report .itflow-dash-dot,
.itflow-report .progress-bar {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}

View File

@@ -41,6 +41,7 @@ require_once __DIR__ . '/functions/backup.php';
require_once __DIR__ . '/functions/search.php';
require_once __DIR__ . '/functions/notifications.php';
require_once __DIR__ . '/functions/dashboard.php';
require_once __DIR__ . '/functions/reports.php';
require_once __DIR__ . '/functions/client_overview.php';
require_once __DIR__ . '/functions/tags.php';
require_once __DIR__ . '/functions/ticket_fields.php';

View File

@@ -583,10 +583,21 @@ function dashboardMoney($amount) {
return numfmt_format_currency($currency_format, floatval($amount), $session_company_currency);
}
/**
* SQL: a revenue that is income - it has a category, and it is not the in
* side of a transfer between accounts. The transfer handler leaves both
* halves without a category; one that has been given one since (the demo data
* files them as "Account Transfer") is still only money moving between
* accounts. The out side is never spending: it has no vendor.
*/
function dashboardRevenueSql() {
return "revenue_category_id > 0 AND revenue_id NOT IN (SELECT transfer_revenue_id FROM transfers)";
}
/** Cash basis, as the Income reports: invoice payments plus categorised revenues. */
function dashboardIncome($start, $end) {
return dashboardSum("SELECT SUM(payment_amount) FROM payments WHERE payment_date BETWEEN '$start' AND '$end'")
+ dashboardSum("SELECT SUM(revenue_amount) FROM revenues WHERE revenue_category_id > 0 AND revenue_date BETWEEN '$start' AND '$end'");
+ dashboardSum("SELECT SUM(revenue_amount) FROM revenues WHERE " . dashboardRevenueSql() . " AND revenue_date BETWEEN '$start' AND '$end'");
}
/** Vendor expenses - expenses with no vendor are transfers between accounts. */
@@ -689,7 +700,7 @@ function dashboardCashFlow($period) {
dashboardMonthly("SELECT DATE_FORMAT(payment_date, '%Y-%m') AS m, SUM(payment_amount) AS v FROM payments
WHERE payment_date BETWEEN '$from' AND '$to' GROUP BY m", $range),
dashboardMonthly("SELECT DATE_FORMAT(revenue_date, '%Y-%m') AS m, SUM(revenue_amount) AS v FROM revenues
WHERE revenue_category_id > 0 AND revenue_date BETWEEN '$from' AND '$to' GROUP BY m", $range)
WHERE " . dashboardRevenueSql() . " AND revenue_date BETWEEN '$from' AND '$to' GROUP BY m", $range)
);
};
$round = function ($values) {
@@ -942,7 +953,7 @@ function dashboardBreakdowns($period) {
WHERE payment_date BETWEEN '$start' AND '$end' AND invoice_category_id > 0
UNION ALL
SELECT revenue_category_id, revenue_amount FROM revenues
WHERE revenue_date BETWEEN '$start' AND '$end' AND revenue_category_id > 0
WHERE revenue_date BETWEEN '$start' AND '$end' AND " . dashboardRevenueSql() . "
) AS income
JOIN categories USING (category_id)
GROUP BY category_id, category_name, category_color ORDER BY v DESC"),

2012
functions/reports.php Normal file

File diff suppressed because it is too large Load Diff

418
js/reports.js Normal file
View File

@@ -0,0 +1,418 @@
/*
* ITFlow - reports (agent/reports/).
*
* The filters at the top of a report submit as soon as they change, except
* "Custom dates", which opens From and To. Charts are declared in the page as
* <canvas data-report-chart="{...}"> (reportChart() in functions/reports.php
* documents the settings) and drawn here in the page's own colours, so they
* follow the theme accent and dark mode. Tables with data-report-sort sort by
* any column whose heading is clicked. On the Reports page, typing in the
* search box narrows the list of reports.
*
* Loaded once per report page, after includes/footer.php.
*/
(function () {
'use strict';
/* ---------- filters ---------- */
document.querySelectorAll('[data-report-filters]').forEach(function (form) {
form.addEventListener('change', function (e) {
const field = e.target;
if (field.matches('[data-report-period]')) {
const custom = form.querySelector('[data-report-custom]');
const isCustom = field.value === 'custom';
if (custom) {
custom.hidden = !isCustom;
custom.querySelectorAll('input').forEach(function (input) {
input.disabled = !isCustom;
});
}
if (isCustom) {
const from = custom && custom.querySelector('input');
if (from) {
from.focus();
}
return;
}
form.requestSubmit ? form.requestSubmit() : form.submit();
return;
}
if (field.matches('[data-report-autosubmit]')) {
form.requestSubmit ? form.requestSubmit() : form.submit();
}
});
});
/* ---------- colours and numbers ---------- */
const style = getComputedStyle(document.body);
function cssVar(name, fallback) {
return (style.getPropertyValue(name) || '').trim() || fallback;
}
const tones = {
accent: cssVar('--itflow-accent', '#007bff'),
success: cssVar('--bs-success', '#198754'),
danger: cssVar('--bs-danger', '#dc3545'),
warning: cssVar('--bs-warning', '#ffc107'),
info: cssVar('--bs-info', '#0dcaf0'),
muted: cssVar('--bs-secondary-color', '#6c757d'),
faint: cssVar('--bs-tertiary-color', '#adb5bd'),
purple: cssVar('--bs-purple', '#6f42c1'),
teal: cssVar('--bs-teal', '#20c997'),
orange: cssVar('--bs-orange', '#fd7e14'),
indigo: cssVar('--bs-indigo', '#6610f2'),
pink: cssVar('--bs-pink', '#d63384'),
dark: cssVar('--bs-emphasis-color', '#212529')
};
function tone(name) {
if (typeof name === 'string' && /^#[0-9a-f]{3,8}$/i.test(name)) {
return name;
}
return tones[name] || tones.accent;
}
function alpha(color, a) {
let m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color);
if (m) {
return 'rgba(' + parseInt(m[1], 16) + ',' + parseInt(m[2], 16) + ',' + parseInt(m[3], 16) + ',' + a + ')';
}
m = /^rgba?\(([^)]+)\)$/i.exec(color);
if (m) {
const parts = m[1].split(',').slice(0, 3);
return 'rgba(' + parts.join(',') + ',' + a + ')';
}
return color;
}
// The legend swatches beside a doughnut take the same colours as its slices
document.querySelectorAll('[data-report-swatch]').forEach(function (swatch) {
swatch.style.backgroundColor = tone(swatch.dataset.reportSwatch);
});
function formatter(format, currency, compact) {
let money;
try {
money = new Intl.NumberFormat(undefined, compact
? { style: 'currency', currency: currency || 'USD', notation: 'compact', maximumFractionDigits: 1 }
: { style: 'currency', currency: currency || 'USD', maximumFractionDigits: 0 });
} catch (e) {
money = new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 });
}
const number = new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 });
return function (value) {
if (value === null || value === undefined || value === '') {
return '';
}
switch (format) {
case 'money':
return money.format(value);
case 'hours':
return number.format(value) + ' h';
case 'percent':
return number.format(value) + '%';
case 'count':
return Number.isInteger(value) ? value.toLocaleString() : (compact ? '' : number.format(value));
default:
return number.format(value);
}
};
}
/* ---------- charts ---------- */
const charts = [];
function drawChart(canvas) {
if (typeof Chart === 'undefined') {
return;
}
let config;
try {
config = JSON.parse(canvas.dataset.reportChart);
} catch (e) {
return;
}
const base = typeof itflowChartDefaults === 'function' ? itflowChartDefaults() : { grid: 'rgba(0,0,0,.1)' };
const type = config.type || 'bar';
const format = config.format || 'count';
const tick = formatter(format, config.currency, true);
const full = formatter(format, config.currency, false);
const tick2 = formatter(config.format2 || format, config.currency, true);
const full2 = formatter(config.format2 || format, config.currency, false);
const horizontal = !!config.horizontal;
const showLegend = config.legend !== undefined ? !!config.legend : (type !== 'doughnut' && (config.series || []).length > 1);
let datasets;
if (type === 'doughnut') {
const series = (config.series || [])[0] || { data: [] };
const colors = (config.colors || []).map(tone);
datasets = [{
label: series.label || '',
data: series.data,
backgroundColor: series.data.map(function (v, i) { return colors[i] || tone(['accent', 'info', 'success', 'warning', 'purple', 'danger'][i % 6]); }),
borderColor: cssVar('--bs-body-bg', '#fff'),
borderWidth: 2
}];
} else {
datasets = (config.series || []).map(function (s, i) {
const color = tone(s.tone || ['accent', 'success', 'info', 'warning', 'purple', 'danger'][i % 6]);
const line = s.type === 'line' || type === 'line';
const set = {
label: s.label,
data: s.data,
type: s.type || undefined,
yAxisID: s.axis === 'y2' ? 'y2' : (horizontal ? undefined : 'y'),
xAxisID: horizontal ? 'x' : undefined,
stack: s.stack,
hidden: !!s.hidden,
order: line ? 0 : 1
};
if (line) {
Object.assign(set, {
borderColor: color,
backgroundColor: s.fill ? alpha(color, 0.15) : color,
fill: !!s.fill,
borderWidth: 2,
// Monotone curves never swing past the points - a share stays within 0-100%
cubicInterpolationMode: 'monotone',
pointRadius: s.data.length > 40 ? 0 : 2,
pointHoverRadius: 4,
borderDash: s.dashed ? [5, 4] : undefined,
spanGaps: true
});
} else if (s.ghost) {
Object.assign(set, {
backgroundColor: alpha(color, 0.22),
borderColor: alpha(color, 0.8),
borderWidth: 1.5,
borderRadius: 3,
maxBarThickness: 28
});
} else {
Object.assign(set, {
// A colour per bar when the series has one (tones), e.g. red where below target
backgroundColor: Array.isArray(s.tones) ? s.tones.map(tone) : color,
borderRadius: 3,
maxBarThickness: horizontal ? 18 : 28
});
}
return set;
});
}
const valueAxis = {
beginAtZero: true,
stacked: !!config.stacked,
grid: { color: base.grid },
border: { display: false },
ticks: { maxTicksLimit: 5, callback: function (v) { return tick(v); } }
};
if (config.max !== undefined) {
valueAxis.max = config.max;
}
const categoryAxis = {
stacked: !!config.stacked,
grid: { display: false },
ticks: { maxRotation: 0, autoSkipPadding: 10 }
};
if (horizontal) {
categoryAxis.ticks = { autoSkip: false, callback: function (v) { const l = this.getLabelForValue(v); return l && l.length > 28 ? l.slice(0, 27) + '…' : l; } };
}
const options = {
responsive: true,
maintainAspectRatio: false,
interaction: { mode: type === 'doughnut' ? 'nearest' : 'index', intersect: type === 'doughnut' },
plugins: {
legend: { display: showLegend, position: 'bottom', labels: { boxWidth: 10, boxHeight: 10, usePointStyle: true, padding: 14 } },
tooltip: {
callbacks: {
label: function (c) {
const value = horizontal ? c.parsed.x : (type === 'doughnut' ? c.parsed : c.parsed.y);
const shown = c.dataset.yAxisID === 'y2' ? full2(value) : full(value);
if (type === 'doughnut') {
const total = c.dataset.data.reduce(function (a, b) { return a + b; }, 0);
return ' ' + c.label + ': ' + shown + (total ? ' (' + Math.round(value / total * 100) + '%)' : '');
}
return ' ' + (c.dataset.label ? c.dataset.label + ': ' : '') + shown;
}
}
}
}
};
if (type === 'doughnut') {
options.cutout = '68%';
} else if (horizontal) {
options.indexAxis = 'y';
options.scales = { x: valueAxis, y: categoryAxis };
} else {
options.scales = { x: categoryAxis, y: valueAxis };
if (datasets.some(function (d) { return d.yAxisID === 'y2'; })) {
options.scales.y2 = {
position: 'right',
beginAtZero: true,
grid: { display: false },
border: { display: false },
ticks: { maxTicksLimit: 5, callback: function (v) { return tick2(v); } }
};
if (config.max2 !== undefined) {
options.scales.y2.max = config.max2;
}
}
}
charts.push(new Chart(canvas, {
type: type === 'line' ? 'line' : (type === 'doughnut' ? 'doughnut' : 'bar'),
data: { labels: config.labels || [], datasets: datasets },
options: options
}));
}
document.querySelectorAll('canvas[data-report-chart]').forEach(drawChart);
// A printed page is narrower than the screen - fit the charts to it, and back
window.addEventListener('beforeprint', function () {
charts.forEach(function (chart) { chart.resize(); });
});
window.addEventListener('afterprint', function () {
charts.forEach(function (chart) { chart.resize(); });
});
/* ---------- sortable tables ---------- */
document.querySelectorAll('table[data-report-sort]').forEach(function (table) {
const heads = table.querySelectorAll('thead th');
heads.forEach(function (th, index) {
if (!th.dataset.sort) {
return;
}
th.tabIndex = 0;
th.classList.add('itflow-report-sortable');
function sort() {
const tbody = table.tBodies[0];
const rows = Array.from(tbody.rows).filter(function (r) { return r.cells.length === heads.length; });
if (rows.length < 2) {
return;
}
const ascending = th.getAttribute('aria-sort') !== 'ascending' && (th.getAttribute('aria-sort') === 'descending' || th.dataset.sort === 'text');
heads.forEach(function (h) { h.removeAttribute('aria-sort'); });
th.setAttribute('aria-sort', ascending ? 'ascending' : 'descending');
const numeric = th.dataset.sort === 'num';
function key(row) {
const cell = row.cells[index];
const raw = cell.dataset.value !== undefined ? cell.dataset.value : cell.textContent.trim().toLowerCase();
if (numeric) {
return raw === '' ? null : parseFloat(raw);
}
return raw;
}
rows.sort(function (a, b) {
const ka = key(a);
const kb = key(b);
// Blanks go last whichever way it is sorted
if (ka === null || ka === '') { return 1; }
if (kb === null || kb === '') { return -1; }
const cmp = numeric ? ka - kb : String(ka).localeCompare(String(kb), undefined, { numeric: true });
return ascending ? cmp : -cmp;
});
rows.forEach(function (row) { tbody.appendChild(row); });
}
th.addEventListener('click', sort);
th.addEventListener('keydown', function (e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
sort();
}
});
});
});
/* ---------- the budget editor ---------- */
const budget = document.querySelector('[data-budget-form]');
if (budget) {
let money;
try {
money = new Intl.NumberFormat(undefined, { style: 'currency', currency: budget.dataset.currency || 'USD' });
} catch (e) {
money = new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
const amount = function (input) {
const value = parseFloat(String(input.value).replace(/,/g, ''));
return isNaN(value) ? 0 : value;
};
const totals = function () {
const months = {};
let all = 0;
budget.querySelectorAll('[data-budget-row]').forEach(function (row) {
let sum = 0;
row.querySelectorAll('[data-budget-cell]').forEach(function (cell, i) {
const value = amount(cell);
sum += value;
months[i + 1] = (months[i + 1] || 0) + value;
});
all += sum;
row.querySelector('[data-budget-row-total]').textContent = money.format(sum);
});
budget.querySelectorAll('[data-budget-month-total]').forEach(function (cell) {
cell.textContent = money.format(months[cell.dataset.budgetMonthTotal] || 0);
});
const total = budget.querySelector('[data-budget-total]');
if (total) {
total.textContent = money.format(all);
}
};
budget.addEventListener('input', function (e) {
if (e.target.matches('[data-budget-cell]')) {
totals();
}
});
budget.addEventListener('click', function (e) {
const fill = e.target.closest('[data-budget-fill]');
if (!fill) {
return;
}
const row = fill.closest('[data-budget-row]');
const source = row.querySelector('[data-budget-fill-value]');
const value = amount(source);
row.querySelectorAll('[data-budget-cell]').forEach(function (cell) {
cell.value = value > 0 ? value.toFixed(2) : '';
});
source.value = '';
totals();
});
// Enter in "every month" fills the row instead of saving the form
budget.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && e.target.matches('[data-budget-fill-value]')) {
e.preventDefault();
e.target.closest('[data-budget-row]').querySelector('[data-budget-fill]').click();
}
});
}
/* ---------- finding a report ---------- */
const find = document.querySelector('[data-report-find]');
if (find) {
find.addEventListener('input', function () {
const words = find.value.toLowerCase().split(/\s+/).filter(Boolean);
let shown = 0;
document.querySelectorAll('[data-report-group]').forEach(function (group) {
let inGroup = 0;
group.querySelectorAll('[data-report-card]').forEach(function (card) {
const text = card.dataset.reportText || '';
const match = words.every(function (w) { return text.indexOf(w) !== -1; });
card.hidden = !match;
inGroup += match ? 1 : 0;
});
group.hidden = inGroup === 0;
shown += inGroup;
});
const none = document.querySelector('[data-report-none]');
if (none) {
none.hidden = shown > 0;
}
});
}
})();