From 15844faa9b55f8416399a292872e10d107e95cf7 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Fri, 16 Oct 2026 00:04:40 -0400 Subject: [PATCH] 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 --- CHANGELOG.md | 55 + admin/post/demo_data_model.php | 15 +- agent/credentials.php | 2 +- agent/includes/client_actions_menu.php | 7 +- agent/modals/ticket/ticket_invoice_add.php | 2 +- agent/post/budget.php | 114 + agent/reports/asset_lifecycle.php | 295 +++ agent/reports/budget.php | 458 +++- agent/reports/client_profitability.php | 228 ++ agent/reports/client_review.php | 585 +++++ agent/reports/client_ticket_time_detail.php | 572 ++--- agent/reports/credential_rotation.php | 265 ++- agent/reports/documentation_coverage.php | 121 ++ agent/reports/expense_by_vendor.php | 238 ++- agent/reports/expense_summary.php | 246 +-- agent/reports/includes/inc_all_reports.php | 20 +- agent/reports/includes/inc_report.php | 16 + agent/reports/includes/inc_report_layout.php | 13 + agent/reports/includes/reports_side_nav.php | 155 +- agent/reports/income_by_client.php | 208 +- agent/reports/income_summary.php | 257 +-- agent/reports/index.php | 68 +- agent/reports/mileage.php | 188 ++ agent/reports/outstanding_balances.php | 260 ++- agent/reports/profit_loss.php | 636 ++---- agent/reports/quote_pipeline.php | 187 ++ agent/reports/recurring_by_client.php | 243 ++- agent/reports/renewals.php | 166 ++ agent/reports/satisfaction.php | 294 +++ agent/reports/sla_by_client.php | 284 ++- agent/reports/sla_summary.php | 325 ++- agent/reports/tax_summary.php | 312 +-- agent/reports/ticket_aging.php | 221 ++ agent/reports/ticket_by_client.php | 473 ++-- agent/reports/ticket_summary.php | 430 ++-- agent/reports/tickets_unbilled.php | 291 +-- agent/reports/time_by_tech.php | 314 ++- client/post.php | 3 +- css/itflow_custom.css | 330 +++ functions.php | 1 + functions/dashboard.php | 17 +- functions/reports.php | 2012 ++++++++++++++++++ js/reports.js | 418 ++++ 43 files changed, 8400 insertions(+), 2945 deletions(-) create mode 100644 agent/post/budget.php create mode 100644 agent/reports/asset_lifecycle.php create mode 100644 agent/reports/client_profitability.php create mode 100644 agent/reports/client_review.php create mode 100644 agent/reports/documentation_coverage.php create mode 100644 agent/reports/includes/inc_report.php create mode 100644 agent/reports/includes/inc_report_layout.php create mode 100644 agent/reports/mileage.php create mode 100644 agent/reports/quote_pipeline.php create mode 100644 agent/reports/renewals.php create mode 100644 agent/reports/satisfaction.php create mode 100644 agent/reports/ticket_aging.php create mode 100644 functions/reports.php create mode 100644 js/reports.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 14add1a7a..49bb4afa4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/admin/post/demo_data_model.php b/admin/post/demo_data_model.php index 829555258..5ec1e8e25 100644 --- a/admin/post/demo_data_model.php +++ b/admin/post/demo_data_model.php @@ -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); diff --git a/agent/credentials.php b/agent/credentials.php index f0abd31d1..8cab11d63 100644 --- a/agent/credentials.php +++ b/agent/credentials.php @@ -170,7 +170,7 @@ $filter_url = function ($changes) use ($client_url) { Export - + Rotation report diff --git a/agent/includes/client_actions_menu.php b/agent/includes/client_actions_menu.php index d9498c582..c08a98bc6 100644 --- a/agent/includes/client_actions_menu.php +++ b/agent/includes/client_actions_menu.php @@ -1,6 +1,6 @@ Export Data + + + Client Review + + diff --git a/agent/modals/ticket/ticket_invoice_add.php b/agent/modals/ticket/ticket_invoice_add.php index 762551b8a..4437f0362 100644 --- a/agent/modals/ticket/ticket_invoice_add.php +++ b/agent/modals/ticket/ticket_invoice_add.php @@ -252,7 +252,7 @@ ob_start(); - From the worked on the ticket, rounded up to the next 15 minutes. + From the worked on the ticket, rounded to the nearest 15 minutes. diff --git a/agent/post/budget.php b/agent/post/budget.php new file mode 100644 index 000000000..56486f4de --- /dev/null +++ b/agent/post/budget.php @@ -0,0 +1,114 @@ + 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"); + +} diff --git a/agent/reports/asset_lifecycle.php b/agent/reports/asset_lifecycle.php new file mode 100644 index 000000000..a063766f6 --- /dev/null +++ b/agent/reports/asset_lifecycle.php @@ -0,0 +1,295 @@ + '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] ? '' . reportCount($row[$key]) . '' : '–'; + }; +}; +$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 ? '–' : 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'] ? '' . reportCount($row['undated']) . '' : '–'; + }], +]; +$type_columns = ['type' => ['label' => 'Type', 'html' => function ($row) { + return '' + . '' . escapeHtml($row['type']) . ''; +}]] + $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 'No date'; + } + $tone = $warranty['tone']; + return '' + . escapeHtml($warranty['short']) . ''; +}; +$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 '' . escapeHtml(trim($row['asset_make'] . ' ' . $row['asset_model'])) . ''; + }], + 'asset_os' => ['label' => 'Operating system', 'html' => function ($row) { + if ($row['os_eol'] === '') { + return '' . escapeHtml($row['asset_os']) . ''; + } + return '' . escapeHtml($row['asset_os']) . ' '; + }], + '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 ? '–' + : '' . reportYears($row['age_days']) . ''; + }], + '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'] ? '' . escapeHtml($row['contact_name']) . '' : '-'; + }], + '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; + +?> + +
+ + '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'], + ]); ?> + + 'Assets in use', 'value' => reportCount($totals['assets']), 'url' => '/agent/assets.php' . ($client_id ? "?client_id=$client_id" : ''), + 'sub' => $totals['average'] !== null ? 'Average age ' . reportYears($totals['average']) . '' : ''], + ['label' => "Over $years years old", 'value' => reportCount($totals['old']), 'tone' => $totals['old'] ? 'danger' : 'success', + 'sub' => $dated_share !== null ? reportPercent($dated_share) . ' of dated hardware' : ''], + ['label' => 'Out of warranty', 'value' => reportCount($totals['expired']), 'tone' => $totals['expired'] ? 'warning' : '', + 'sub' => reportCount($totals['ending']) . ' more within 90 days'], + ['label' => 'Unsupported OS', 'value' => reportCount($totals['os']), 'tone' => $totals['os'] ? 'danger' : 'success', + 'sub' => $os_names ? escapeHtml(array_key_first($os_names)) . ' the most' : 'All supported or unknown'], + ]) ?> + + +
+ + +
+
+ +
+ 'bar', 'labels' => $age_labels, 'series' => [['label' => 'Assets', 'data' => array_values($age_counts), 'tones' => $age_tones]], + 'format' => 'count', 'legend' => false], '', 'Assets in use by age') ?> +
+
+
+
+ +
+ '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') ?> +
+
+
+
+ + + +
+ '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") ?> +
+ + + + + ['type' => 'Total'] + $totals, 'totals_html' => ['average' => $totals['average'] === null ? '' : reportYears($totals['average'])]]) ?> + + + + + + 50, 'export_table' => 'clients', 'totals' => ['client' => 'Total'] + $totals, + 'totals_html' => ['average' => $totals['average'] === null ? '' : reportYears($totals['average'])]]) ?> + + + + + 300, 'export_table' => 'candidates', + 'empty' => reportEmpty("Nothing is over $years years old or on an unsupported operating system.")]) ?> + + + + + + + + + diff --git a/agent/reports/budget.php b/agent/reports/budget.php index 91aead881..1cff2badc 100644 --- a/agent/reports/budget.php +++ b/agent/reports/budget.php @@ -1,107 +1,393 @@ 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 ? 'No budget' : ''; + } + $share = $spent / $plan * 100; + $tone = $share > 100 ? 'bg-danger' : ($share > 90 ? 'bg-warning' : ''); + return '
' + . '' . reportPercent(round($share)) . '
'; +}; ?> -
-
-

Annual Budget

-
- -
-
-
-
- + + + + +
+
+

Plan for

+ + + +
+
+ + + + + + + + + + + + + $line) { + if ($line['archived'] && $line['plan_total'] <= 0) { + continue; + } ?> + + + + + + + + + + + + + + + + + + + + +
CategoryEvery month
Archived +
+ + +
+
Total
+
+ +
- + -
- - - - - - - - - - - - - - - - - - - - + $year === $current_year ? 'Budget this year' : "Budget $year", 'value' => reportMoney($plan_total), + 'sub' => $plan_total > 0 ? escapeHtml(reportMoney($plan_total / 12)) . ' a month on average' : 'No budget set yet'], + ['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)) . ' of the budget' . ($year === $current_year ? ', ' . round($year_elapsed * 100) . '% of the year gone' : '') . '' : ''], + ['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) ? '' . count($over) . ' categor' . (count($over) === 1 ? 'y' : 'ies') . ' over budget' : 'No category over budget'], + ]); + ?> + + +
+
+ +
No budget for yet
+
Set what you plan to spend each month by category, and this report compares it with what you actually spend.
+ + Set the budget + +
+
+ + + +
num_rows > 0) { - while($category = $categories->fetch_assoc()) { - echo "
"; - echo ""; - $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 ""; - } else { - echo ""; - } - } - echo ""; - echo ""; - } - - // Displaying the monthly totals row - echo ""; - $grandTotal = 0; - for ($month = 1; $month <= 12; $month++) { - $grandTotal += $monthlyTotals[$month]; - echo ""; - } - echo ""; - echo ""; - } + $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'); ?> - -
CategoryJanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecemberTotal
" . escapeHtml($category['category_name']) . "" . $amount . "0" . $categoryTotal . "
Total" . $monthlyTotals[$month] . "" . $grandTotal . "
+
-
+ + + + +
+ + + + + + + + + + + + $line) { ?> + + + + + + + + + + + + + + + + + + + + + +
Category
+
+
0 ? reportMoneyWhole($plan) : ' ' ?>
+
+
+
0 ? reportMoneyWhole($line['plan_total']) : ' ' ?>
+
No budget and no spending in .
Total +
+
0 ? reportMoneyWhole($plan_months[$m]) : ' ' ?>
+
+
+
+
+
+ + + + + ['label' => 'Category', 'html' => function ($row) { + return escapeHtml($row['name']) . ($row['archived'] ? ' Archived' : ''); + }], + 'plan_total' => ['label' => "Budget $year", 'type' => 'money', 'html' => function ($row) { + return $row['plan_total'] > 0 ? reportMoney($row['plan_total']) : '–'; + }], + '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']) : '–'; + }], + 'spent_total' => ['label' => 'Spent', 'type' => 'money', 'html' => function ($row) use ($year) { + if (abs($row['spent_total']) < 0.005) { + return '–'; + } + return '" . reportMoney($row['spent_total']) . ''; + }], + '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 '–'; + } + return '' . reportMoney($row['difference']) . ''; + }], + 'remaining' => ['label' => 'Left this year', 'type' => 'money', 'html' => function ($row) { + if ($row['plan_total'] <= 0) { + return '–'; + } + return '' . reportMoney($row['remaining']) . ''; + }], + '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']), + ]; + } + ?> + + ' . count($unbudgeted) . ' categor' . (count($unbudgeted) === 1 ? 'y has' : 'ies have') . ' spending but no budget' : '') ?> + "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' => '' . reportMoney($plan_to_date - $spent_total) . ''], + ]) ?> + + + + + + + - + + diff --git a/agent/reports/client_profitability.php b/agent/reports/client_profitability.php new file mode 100644 index 000000000..a4a588ac1 --- /dev/null +++ b/agent/reports/client_profitability.php @@ -0,0 +1,228 @@ + $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']) : '–'; + }], + '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 'No time'; + } + $tone = $row['flag'] ? 'text-danger fw-semibold' : ($target > 0 && $row['rate'] >= $target ? 'text-success-emphasis fw-semibold' : 'fw-semibold'); + return '' . reportMoney($row['rate']) . ''; + }]; + $columns['tickets'] = ['label' => 'Tickets', 'type' => 'count']; +} +$columns['mrr'] = ['label' => 'Recurring / month', 'type' => 'money', 'html' => function ($row) { + return $row['mrr'] > 0 ? reportMoney($row['mrr']) : '–'; +}]; +$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 'Time, no income'; + } + if ($row['flag'] === 'below') { + return 'Below target'; + } + 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 = '
' + . '' + . '' + . '
'; + +?> + +
+ + $period, + 'years' => reportPastYears("SELECT DISTINCT YEAR(payment_date) AS y FROM payments"), + 'controls' => $target_control, + ]); ?> + + 'Income from clients', 'value' => reportMoney($income), 'sub' => $costs > 0 ? escapeHtml(reportMoney($costs)) . ' in direct costs' : 'No direct costs filed'], + ['label' => 'Hours worked', 'value' => $with_tickets ? reportHours($seconds) : '-', 'sub' => $with_tickets ? escapeHtml(reportPercent(reportShare(array_sum(array_column($clients, 'billable_seconds')), $seconds))) . ' on billable tickets' : 'Ticketing is off'], + ['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 ' . reportMoney($target) . '' : 'Enter a target above'], + ['label' => 'Clients to look at', 'value' => reportCount(count($flagged)), 'tone' => $flagged ? 'danger' : 'success', + 'sub' => 'Below target, or time with no income'], + ]) ?> + + + +
+ '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') ?> +
+
+ + + + 'No income or time logged for any client in this period.', 'totals' => $totals]) ?> + + + + + + + diff --git a/agent/reports/client_review.php b/agent/reports/client_review.php new file mode 100644 index 000000000..3e8e5c7b8 --- /dev/null +++ b/agent/reports/client_review.php @@ -0,0 +1,585 @@ += 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', '' . $plural($hw['os'], 'device runs', 'devices run') . ' an operating system past its end of support (' . 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', '' . reportMoney($money['overdue']) . ' is past due 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', 'First replies met the SLA ' . reportPercent($t['sla']['response_percent']) . ' of the time. 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', '' . $plural($t['bad'], 'ticket was', 'tickets were') . ' rated bad. 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', 'Tickets were up ' . reportChange($t['opened'], $t['opened_prev']) . '% 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', '' . escapeHtml($top['label']) . ' was ' . reportPercent(reportShare($top['value'], $t['opened'], 0)) . ' of tickets (' . 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', '' . escapeHtml($asset['asset_name']) . ' was on ' . reportCount(intval($asset['n'])) . ' tickets. 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', '' . $plural($hw['old'], 'device is', 'devices are') . ' over ' . REVIEW_OLD_YEARS . ' years old. 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', '' . $plural(count($manual_due), 'domain, certificate or license needs', 'domains, certificates or licenses need') . ' renewing' + . ($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', '' . $plural($hw['ending'], 'warranty ends', 'warranties end') . ' in the next 90 days. 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', '' . $plural($t['open_old'], 'ticket has', 'tickets have') . ' been open over 30 days. Close them out or agree a plan.', + '/agent/reports/ticket_aging.php?client_id=' . $client_id]; + } + if ($services) { + $advice[] = ['info', 'fa-stream', '' . $plural(count($services), 'service needs', 'services need') . ' a look - 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', '' . $plural(intval($credentials['stale']), 'password has', 'passwords have') . ' not changed in over a year.', + '/agent/reports/credential_rotation.php?client_id=' . $client_id . '&days=365']; + } + if ($coverage && $coverage['missing']) { + $checks = reportCoverageChecks(); + $advice[] = ['info', 'fa-tasks', 'Documentation is missing: ' . 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', '' . $plural($money['unbilled'], 'billable ticket is', 'billable tickets are') . ' done but not invoiced yet.', '/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'] : '', +]; + +?> + +
+ + + + + +
+ +
+ + + + +
+
+ + +
+

+
Business review ·
+
+
+ +
Contact
+
+ +
Client since
+
+
+
+
+ + +
+ +

Nothing stands out - a quiet, healthy period.

+ + + +
+
+ + +

Service desk

+ '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']) . ' open now'], + ['label' => 'Typical first reply', 'value' => $t['response'] === null ? '-' : reportDuration($t['response']), + 'sub' => $t['resolve'] === null ? '' : 'Resolved in ' . reportDuration($t['resolve']) . ''], + ['label' => 'SLA met', 'value_html' => $t['sla']['response_percent'] === null ? '-' : reportRateHtml($t['sla']['response_percent']), + 'sub' => $t['sla']['resolution_percent'] === null ? 'No SLA tickets' : 'Resolution ' . reportPercent($t['sla']['resolution_percent']) . ''], + ['label' => 'Satisfaction', 'value_html' => $t['satisfaction'] === null ? '-' : reportRateHtml($t['satisfaction']), + 'sub' => ($t['good'] + $t['bad']) ? reportCount($t['good'] + $t['bad']) . ' ratings' : 'No ratings'], + ['label' => 'Time spent', 'value' => reportHours($t['seconds']) . ' h', 'sub' => 'Logged on their tickets'], + ]) ?> + + + 0) { ?> +
+
+ +
+ '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') ?> +
+
+
+
+ +
+ + + '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') ?> + + + +
+
+ + + +
+
+ + ['label' => 'Contact', 'html' => function ($row) use ($client_id) { + return '' . escapeHtml($row['contact_name']) . '' + . ($row['contact_title'] ? '
' . escapeHtml($row['contact_title']) . '
' : ''); + }], + 'n' => ['label' => 'Tickets', 'type' => 'count'], + ], $t['contacts'], ['sortable' => false, 'empty' => 'No tickets had a contact.']) ?> +
+
+
+ + ['label' => 'Device', 'html' => function ($row) { return reportAssetCell($row); }], + 'model' => ['label' => 'Make and model', 'html' => function ($row) { + return '' . escapeHtml(trim($row['asset_make'] . ' ' . $row['asset_model'])) . ''; + }], + 'n' => ['label' => 'Tickets', 'type' => 'count'], + ], $t['assets'], ['sortable' => false, 'empty' => 'No tickets were linked to a device.']) ?> +
+ + + + + + ['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 '' . escapeHtml($row['ticket_status_name']) . ''; + }], + 'ticket_created_at' => ['label' => 'Raised', 'type' => 'date'], + 'took' => ['label' => 'Resolved in', 'type' => 'duration', 'html' => function ($row) { + return $row['ticket_resolved_at'] ? reportDuration($row['took']) : 'Open ' . reportDuration($row['took']) . ''; + }], + ], $t['urgent'], ['sortable' => false, 'limit' => 15]) ?> + + + + + + + ['label' => 'Project', 'class' => 'itflow-report-text', 'html' => function ($row) { + return '' . escapeHtml($row['project_name']) . '' + . '
' . escapeHtml(projectReference($row)) . '
'; + }], + 'state' => ['label' => 'Status', 'html' => function ($row) { + return '' . projectStatePill($row) . (projectIsOpen($row) ? projectDuePill($row) : '') . ''; + }], + '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]) ?> + + + + +

Hardware and documentation

+ '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) . ' ' . reportCount($n) . ''; }, + 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']) . ' more within 90 days'], + ['label' => 'Unsupported OS', 'value' => reportCount($hw['os']), 'tone' => $hw['os'] ? 'danger' : 'success'], + ]) ?> + + + + ['label' => 'Device', 'html' => function ($row) { return reportAssetCell($row); }], + 'model' => ['label' => 'Make and model', 'html' => function ($row) { + return '' . escapeHtml(trim($row['asset_make'] . ' ' . $row['asset_model'])) . ''; + }], + 'contact_name' => ['label' => 'Used by', 'html' => function ($row) { + return $row['contact_name'] ? escapeHtml($row['contact_name']) : '-'; + }], + 'reasons' => ['label' => 'Why', 'html' => function ($row) { + $html = ''; + foreach ($row['reasons'] as [$tone, $text]) { + $html .= '' . escapeHtml($text) . ''; + } + return $html . ''; + }], + ], $hw['plan'], ['sortable' => false, 'limit' => 20]) ?> + + + + + + + ['label' => 'Due', 'html' => function ($row) { return reportDuePill($row['days'], $row['auto']); }], + 'name' => ['label' => 'What', 'class' => 'itflow-report-text', 'html' => function ($row) { + return '
' . $row['tile'] . '
' . escapeHtml($row['name']) . '' + . ($row['detail'] !== '' ? '
' . escapeHtml($row['detail']) . '
' : '') . '
'; + }], + 'kind' => ['label' => 'Type', 'html' => function ($row) { return REPORT_RENEWAL_KINDS[$row['kind']]['one']; }], + 'date' => ['label' => 'Date', 'type' => 'date'], + ], $renewals, ['sortable' => false, 'limit' => 20]) ?> + + + + + + ['label' => 'Service', 'html' => function ($row) { + return '' . serviceTile($row['service_category'], 'sm') + . '' . escapeHtml($row['service_name']) . ''; + }], + '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']) ? 'Something expiring or out of action' : 'All fine'; + }], + ], $services, ['sortable' => false]) ?> + + + + + +
+ = 90 ? 'success' : ($coverage['score'] >= 70 ? 'warning' : 'danger'); ?> + + + Missing + + + Everything we check is documented + +
+ + + + +

Billing

+ 'Invoiced', 'value' => reportMoney($money['invoiced']), 'sub' => 'In the period', 'url' => '/agent/invoices.php?client_id=' . $client_id], + ['label' => 'Paid', 'value' => reportMoney($money['paid']), 'sub' => 'In the period'], + ['label' => 'Balance owing', 'value' => reportMoney($money['balance']), 'tone' => $money['overdue'] > 0.004 ? 'danger' : '', + 'sub' => $money['overdue'] > 0.004 ? reportMoney($money['overdue']) . ' past due' : 'Nothing past due'], + ['label' => 'Monthly recurring', 'value' => reportMoney($money['mrr']), 'sub' => reportMoney($money['mrr'] * 12) . ' a year'], + ]) ?> + + +

+ 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. +

+ + + + + + + diff --git a/agent/reports/client_ticket_time_detail.php b/agent/reports/client_ticket_time_detail.php index 7585e26f7..f5800bbd8 100644 --- a/agent/reports/client_ticket_time_detail.php +++ b/agent/reports/client_ticket_time_detail.php @@ -1,418 +1,200 @@ 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(['
', '
', '
', '

', ''], "\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); +}; ?> -
-
-

- - Client Time Detail Audit Report ( to ) - - Billable Only - -

-
- -
-
-
- -
-
-
- - -
+
-
- - -
+ $period, + 'client' => $client_id, + 'agent' => $agent_id, + 'controls' => $controls, + ]); ?> -
- - -
- -
- -
- -
-
- - > - -
-
+ 'Time logged', 'value' => reportHours($total_seconds, 2) . ' h', 'sub' => reportCount(count($replies)) . ' replies on ' . reportCount($ticket_count) . ' tickets'], + ['label' => 'To bill', 'value' => reportHours($total_to_bill, 2) . ' h', 'sub' => 'On billable tickets, each reply rounded up to ' . escapeHtml($increment_label) . ''], + ['label' => 'Value', 'value' => reportMoney($total_value), 'sub' => 'The hours to bill at each client\'s rate'], + ['label' => 'Clients', 'value' => reportCount(count($clients)), 'sub' => 'With time in the period'], + ]) ?> + +
+ + $client) { ?> +
+
+

+ + ticket · + h logged · + h to bill + 0) { ?>· /h · +
- -
-
- -
-
- - - - - - - - - - - - - - - - - '; - } - - // Client subtotal (billable based on sum of rounded replies across all tickets) - ?> - - - - - - - - - - - '; - - // 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++; - - ?> +
+
Ticket / Replies with TimeTime WorkedBillable (hrs)
Ticket Total for
- Total for ( tickets) -
+ - - - + + + + - + + + + + + + + + + + + + + + + + +
Ticket and work doneAgentLoggedRounded
+ + +
+
+ + Internal note +
+ +
+ +
+
+
+ - // Reply row (indented) - ?> - - - - -
- -
- - - - - +
+
+ All clients - tickets + h logged · h to bill · +
+ +
+ - // 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) { - ?> - - - No ticket replies with time worked found for this date range. - - - '; - } - - // Close last client subtotal - ?> - - - Total for ( tickets) - - - - - - - - - - - Grand Total ( tickets) - - - - - - - - - - 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 minutes ( hours), - then summing those rounded values for ticket/client/grand totals. -
- Reply content is displayed under each reply timestamp. -
-
- + diff --git a/agent/reports/credential_rotation.php b/agent/reports/credential_rotation.php index 8f76803ea..8ff47c0d3 100644 --- a/agent/reports/credential_rotation.php +++ b/agent/reports/credential_rotation.php @@ -1,130 +1,187 @@ '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 '' + . reportCount($row['due']) . ''; + }], + 'overdue' => ['label' => 'Over a year or never', 'type' => 'count', 'html' => function ($row) { + return $row['overdue'] ? '' . reportCount($row['overdue']) . '' : '–'; + }], + 'oldest' => ['label' => 'Oldest change', 'type' => 'count', 'csv_label' => 'Oldest change (days ago)', 'html' => function ($row) { + return $row['oldest'] === null ? '–' : '' . escapeHtml(timeAgo(date('Y-m-d', strtotime('-' . $row['oldest'] . ' days')))) . ''; + }], + '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 '
' . credentialTile($row, 'sm') . '
' + . '' . escapeHtml($row['credential_name']) . '' + . ($row['credential_description'] ? '
' . escapeHtml($row['credential_description']) . '
' : '') . '
'; + }], + '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 'Never recorded'; + } + return credentialAgePill($row['age']) . '
' . escapeHtml($row['age']['date']) . '
'; + }], + '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'] ? 'Yes' : '–'; + }], + 'credential_accessed_at' => ['label' => 'Last opened', 'type' => 'date', 'html' => function ($row) { + return $row['credential_accessed_at'] ? '' . escapeHtml(timeAgo($row['credential_accessed_at'])) . '' + : '–'; + }], +]; + +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]; ?> -
-
-

Credentials not changed in

-
- +
+ + $day_options[$days], + 'controls' => reportSelectControl('days', $days, $day_options, 'fa-history') . reportClientControl($client_id), + 'export' => ['credentials' => 'Credentials due', 'clients' => 'By client'], + ]); ?> + + 'Credentials', 'value' => reportCount(count($credentials)), 'url' => '/agent/credentials.php' . ($client_id ? "?client_id=$client_id" : ''), + 'sub' => reportCount($otp) . ' with a 2FA code'], + ['label' => 'Due for rotation', 'value' => reportCount(count($due)), 'tone' => $due ? 'warning' : 'success', + 'sub' => $credentials ? reportPercent(reportShare(count($due), count($credentials), 0)) . ' of them' : ''], + ['label' => 'Over a year or never', 'value' => reportCount($overdue), 'tone' => $overdue ? 'danger' : 'success', + 'sub' => reportCount($age_counts['Never recorded']) . ' never recorded'], + ['label' => 'Clients with some due', 'value' => reportCount($clients_due), 'tone' => $clients_due ? 'warning' : ''], + ]) ?> + + + +
+ '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') ?>
-
-
- - - credential across client -
+ - -
Every password has changed in the last .
- + +
+ -
By client
-
- - - - $client) { ?> - - - - - - - -
ClientDueOver a year or never
' . $client['year'] . '' : '0' ?>
-
+ + + 50, 'export_table' => 'clients']) ?> +
+ -
Credentials, oldest first
-
- - - - - - - - - - - - - - - - - - - -
ClientCredentialPassword last changedLast used
-
- -
- -
-
-
-
- - -
- - Never recorded - -
-
- + + 300, 'export_table' => 'credentials']) ?> +
-
- + +
+ + + diff --git a/agent/reports/documentation_coverage.php b/agent/reports/documentation_coverage.php new file mode 100644 index 000000000..e52b05179 --- /dev/null +++ b/agent/reports/documentation_coverage.php @@ -0,0 +1,121 @@ + $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 '
' + . '' . reportPercent($row['score']) . '
'; + }], + '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 ? '–' : 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 ? '–' : 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)); + +?> + +
+ + 'As of ' . date('M j, Y'), + 'controls' => reportSwitchControl('gaps', $gaps_only, 'Only clients with gaps'), + ]); ?> + + 'Active clients', 'value' => reportCount(count($all)), 'sub' => reportCount(count($checks)) . ' checks each'], + ['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)) . ' of clients' : ''], + ['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]) . ' ' . ($missing_counts[$top_gap] === 1 ? 'client' : 'clients') . '' : ''], + ]) ?> + + + +
+ + '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') ?> +
+
+ + + + reportEmpty($gaps_only ? 'Every client has everything documented.' : 'No active clients.')]) ?> + +
+ + + + + diff --git a/agent/reports/expense_by_vendor.php b/agent/reports/expense_by_vendor.php index fe5d5dff7..15d3beb6b 100644 --- a/agent/reports/expense_by_vendor.php +++ b/agent/reports/expense_by_vendor.php @@ -1,97 +1,173 @@ 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'] ? '' . $name . '' : '' . $name . ''; + }], + '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 '' . reportMoney($row['total']) . ''; + }], + 'share' => ['label' => 'Share', 'type' => 'percent', 'html' => function ($row) { + return '
' + . '' . reportPercent($row['share']) . '
'; + }], + 'prev' => ['label' => 'Period before', 'type' => 'money', 'class' => 'text-body-secondary'], + 'change' => ['label' => 'Change', 'type' => 'percent', 'csv' => false, 'html' => function ($row) { + return $row['change'] === null ? 'New' : '' . reportChangeHtml($row['total'], $row['prev'], 'down') . ''; + }], + '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']) : '–'; + }], + '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; ?> -
-
-

Expense By Vendor (With expense amounts of 600 or more)

-
- +
+ + $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'), + ]); ?> + + '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' => '' . ($only_1099 ? 'Paid 600 or more' : 'In the period') . ''], + ['label' => 'Biggest', 'value' => $biggest ? $biggest['vendor'] : '-', 'sub' => $biggest ? reportMoney($biggest['total']) . ' · ' . reportPercent($biggest['share']) . ' of spending' : ''], + ['label' => 'Paid 600 or more', 'value' => reportCount($count_1099), 'sub' => 'Vendors to check for a 1099', 'url' => reportUrl(['over600' => 1])], + ]) ?> + + + +
+ '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') ?> +
+
+ + + + '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'))], + ]) ?> +
-
-
- -
- -
- - - - - - - - - - - - - - - - -
VendorPaid
-
-
- + + diff --git a/agent/reports/expense_summary.php b/agent/reports/expense_summary.php index a55df5944..54d87f9a3 100644 --- a/agent/reports/expense_summary.php +++ b/agent/reports/expense_summary.php @@ -1,194 +1,92 @@ 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"; ?> - - +
-
-
-

Expense Summary

-
- + [$year, $years], + 'subtitle' => $current_year ? "$year to date" : (string) $year, + ]); ?> + + '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']) . ' · ' . reportPercent(reportShare($grid[$biggest]['total'], $totals['total'])) . '' : ''], + ['label' => 'Recurring', 'value' => reportMoney($recurring), 'sub' => 'Per month, committed now', 'url' => '/agent/recurring_expenses.php'], + ]) ?> + + +
+ (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'); + ?>
-
-
- -
-
- -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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; - ?> - - - - - -
CategoryJanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecemberTotal
- -01&dtt=-31"> - - - - - - -
Total - -01&dtt=-31"> - - - - - - -
+ + +
+
- - + diff --git a/agent/reports/includes/inc_all_reports.php b/agent/reports/includes/inc_all_reports.php index 24fa2ed05..cafed7d61 100644 --- a/agent/reports/includes/inc_all_reports.php +++ b/agent/reports/includes/inc_all_reports.php @@ -1,16 +1,14 @@
- \ No newline at end of file + diff --git a/agent/reports/income_by_client.php b/agent/reports/income_by_client.php index 5d5c8a27f..fe762565f 100644 --- a/agent/reports/income_by_client.php +++ b/agent/reports/income_by_client.php @@ -1,95 +1,143 @@ 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 '' . reportMoney($row['paid']) . ''; + }], + 'share' => ['label' => 'Share', 'type' => 'percent', 'html' => function ($row) { + return '
' + . '' . reportPercent($row['share']) . '
'; + }], + 'prev' => ['label' => 'Period before', 'type' => 'money', 'class' => 'text-body-secondary'], + 'change' => ['label' => 'Change', 'type' => 'percent', 'csv' => false, 'html' => function ($row) { + return $row['change'] === null ? 'New' : '' . reportChangeHtml($row['paid'], $row['prev'], 'up') . ''; + }], + 'payments' => ['label' => 'Payments', 'type' => 'count'], + 'mrr' => ['label' => 'Recurring / month', 'type' => 'money', 'html' => function ($row) { + return $row['mrr'] > 0 ? reportMoney($row['mrr']) : '–'; + }], + '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); ?> -
-
-

Income By Client (With payments of 600 or more)

-
- +
+ + $period, + 'years' => reportPastYears("SELECT DISTINCT YEAR(payment_date) AS y FROM payments"), + 'controls' => reportSwitchControl('over600', $only_600, 'Only clients who paid 600 or more'), + ]); ?> + + 'Paid by clients', 'value' => reportMoney($total), 'sub' => reportChangeHtml($total, $prev_total, 'up', $period['compare'])], + ['label' => 'Clients who paid', 'value' => reportCount(count($clients)), 'sub' => '' . ($only_600 ? 'Paid 600 or more' : 'In the period') . ''], + ['label' => 'Average per client', 'value' => count($clients) ? reportMoney(array_sum(array_column($clients, 'paid')) / count($clients)) : '-', 'sub' => 'Over the period'], + ['label' => 'Top five', 'value' => reportPercent($top_five_share), 'sub' => 'of income - how much rides on a few clients', + 'tone' => $top_five_share !== null && $top_five_share >= 60 ? 'warning' : ''], + ]) ?> + + + +
+ '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') ?> +
+
+ + + + 'No client paid anything in this period.', 'totals' => $totals]) ?> +
-
-
- -
- - 599 - ORDER BY amount_paid DESC"; - - $sql_clients = mysqli_query($mysqli, $sql_clients); - ?> - -
- - - - - - - - - - - - - - - - -
ClientPaid
-
-
- + diff --git a/agent/reports/income_summary.php b/agent/reports/income_summary.php index 2a23e4489..f43475e92 100644 --- a/agent/reports/income_summary.php +++ b/agent/reports/income_summary.php @@ -1,200 +1,97 @@ $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"; ?> - - +
-
-
-

Income Summary

-
- + [$year, $years], + 'subtitle' => $current_year ? "$year to date" : (string) $year, + ]); ?> + + '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']))) . ' of income', + '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']))) . ' of income', + 'url' => "/agent/income.php?type=revenue&canned_date=custom&dtf=$from&dtt=$to"], + ['label' => 'Monthly average', 'value' => reportMoney($average), 'sub' => $best_month ? 'Best month ' . date('F', mktime(0, 0, 0, $best_month, 1)) . '' : ''], + ]) ?> + + +
+ (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'); + ?>
-
-
- -
-
-
- -
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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; - ?> - - - - - -
CategoryJanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecemberTotal
Total
+ + +
+
- - + diff --git a/agent/reports/index.php b/agent/reports/index.php index ac19b3591..ccf1b230c 100644 --- a/agent/reports/index.php +++ b/agent/reports/index.php @@ -1,20 +1,68 @@ 'success', 'billing' => 'primary', 'service' => 'info', 'clients' => 'warning']; ?> -
-
-

Reports

-
-
-
-

Access different reports using the menu on the left

- In addition to the general reporting permission, you must have read permissions to the reporting area you wish to view (e.g. support/financial). +
+
+
+

Reports

+
+
+
+
+
+ + +
+
+
+ Each report shows what your role can see - pick a period, narrow it to one client, print it or export it to CSV. +
+
- + +
+ + $group) { + $tone = $group_tones[$group_key] ?? 'secondary'; ?> +
+

+
+ $report) { ?> + + +
+
+ + + + +
+ + + diff --git a/agent/reports/mileage.php b/agent/reports/mileage.php new file mode 100644 index 000000000..d7ccbb113 --- /dev/null +++ b/agent/reports/mileage.php @@ -0,0 +1,188 @@ + $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']) . ' ' . 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']) ? '' : ''; + }, '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']) : 'No client (our own)'; + }], + '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 = '
' + . '' + . '' + . '
'; + +?> + +
+ + $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'], + ]); ?> + + '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')))) . ' round trips' : ''], + ['label' => 'Average trip', 'value' => count($trips) ? number_format($miles / count($trips), 1) . ' mi' : '-', 'sub' => 'Miles a trip'], + ['label' => $rate ? 'At ' . reportMoney($rate) . ' a mile' : 'Reimbursement', 'value' => $rate ? reportMoney($miles * $rate) : '-', + 'sub' => $rate ? 'Miles × your rate' : 'Enter a rate per mile above'], + ]) ?> + + +
+ 'bar', + 'labels' => $buckets['labels'], + 'series' => [['label' => 'Miles', 'data' => $miles_series, 'tone' => 'accent']], + 'format' => 'decimal', + 'legend' => false, + ], 'sm', 'Miles driven over the period') ?> +
+
+ +
+
+ + 'No trips in this period.', 'totals' => ['agent' => 'Total'] + $totals]) ?> +
+
+
+ + 'No trips in this period.', 'totals' => ['client' => 'Total'] + $totals]) ?> +
+
+
+ + + 'No trips in this period.', 'limit' => 250, 'export_table' => 'trips', 'totals' => ['trip_date' => 'Total', 'miles' => $miles, 'value' => $totals['value']]]) ?> + +
+ +
+ + + diff --git a/agent/reports/outstanding_balances.php b/agent/reports/outstanding_balances.php index 6af09b0e9..f70b1d74c 100644 --- a/agent/reports/outstanding_balances.php +++ b/agent/reports/outstanding_balances.php @@ -1,85 +1,197 @@ '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 '–'; + } + $class = in_array($key, ['61-90', '90+'], true) ? 'text-danger-emphasis fw-semibold' : ''; + return '' . reportMoney($row[$key]) . ''; + }; +}; + +$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 '' . reportMoney($row['total']) . ''; + }], + '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 ? '' . $row['oldest_late'] . ' day' . ($row['oldest_late'] === 1 ? '' : 's') . ' late' : 'Not due'; + }], + 'last_payment' => ['label' => 'Last paid', 'type' => 'date', 'class' => 'text-nowrap', 'html' => function ($row) { + return $row['last_payment'] ? '' . escapeHtml(timeAgo($row['last_payment'])) . '' : 'Never'; + }], +]; + +$invoice_columns = [ + 'invoice' => ['label' => 'Invoice', 'csv' => function ($row) { return $row['invoice_prefix'] . $row['invoice_number']; }, 'html' => function ($row) { + return '' . escapeHtml($row['invoice_prefix'] . $row['invoice_number']) . '' + . ($row['invoice_scope'] !== '' && $row['invoice_scope'] !== null ? '
' . escapeHtml($row['invoice_scope']) . '
' : ''); + }], + '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 '' . ($late === 0 ? 'Due today' : 'In ' . (-$late) . ' day' . ($late === -1 ? '' : 's')) . ''; + } + $tone = $late > 60 ? 'danger' : ($late > 30 ? 'warning' : 'secondary'); + return '' . $late . ' day' . ($late === 1 ? '' : 's') . ''; + }], + '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']) : '–'; + }], + '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']); }); ?> -
-
-

Clients with a Balance

-
- +
+ + $client_id, + 'subtitle' => 'As of ' . date('M j, Y'), + 'export' => ['clients' => 'By client', 'invoices' => 'Every unpaid invoice'], + ]); ?> + + 'Owed to you', 'value' => reportMoney($total), 'url' => '/agent/invoices.php?status=Unpaid', + 'sub' => reportCount(count($invoices)) . ' unpaid invoice' . (count($invoices) === 1 ? '' : 's') . ''], + ['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))) . ' of what is owed' : ''], + ['label' => 'Over 60 days late', 'value' => reportMoney($late_60), 'tone' => $late_60 > 0 ? 'danger' : '', + 'sub' => $late_90 > 0 ? escapeHtml(reportMoney($late_90)) . ' over 90' : 'Nothing over 90 days'], + ['label' => 'Clients owing', 'value' => reportCount(count($clients)), + 'sub' => count(array_filter($clients, function ($c) { return $c['oldest_late'] > 0; })) . ' with something overdue'], + ]) ?> + + 0) { ?> + +
+ +
+ $label) { ?> +
+ + + +
+ +
+
+
+ + + + reportEmpty('Nothing is owed on unpaid invoices.'), + 'totals' => ['client' => 'Total', 'total' => $total, 'count' => count($invoices)] + $totals, + ]) ?> +
+ + + reportEmpty('No invoice is past its due date.'), + 'limit' => 300, 'export_table' => 'invoices', + 'totals' => ['invoice' => 'Total', 'balance' => array_sum(array_column($overdue, 'balance'))], + ]) ?> +
-
- 0 - ORDER BY - balance DESC - "); - - ?> - -
- - - - - - - - - - - - - - - - -
ClientBalance
-
-
- + diff --git a/agent/reports/profit_loss.php b/agent/reports/profit_loss.php index f7d1f5472..90b023c5e 100644 --- a/agent/reports/profit_loss.php +++ b/agent/reports/profit_loss.php @@ -1,436 +1,228 @@ $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 = '' + . escapeHtml($line['name']) . (!empty($line['archived']) ? ' Archived' : '') . ''; + 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 .= '' . reportGridAmount($amount, $url) . ''; + } + // Spending going up is not good news + $good = in_array($kind, ['expense', 'expense_total'], true) ? 'down' : 'up'; + $html .= '' . reportGridAmount($line['total']) . '' + . '' . reportGridAmount($line['prev']) . '' + . '' . (reportChange($line['total'], $line['prev']) === null ? '–' : reportChangeHtml($line['total'], $line['prev'], $good)) . '' + . ''; + return $html; +}; +$span = count($columns) + 4; ?> -
-
-

Profit & Loss

-
- -
-
-
- - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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; - } - - ?> - - - - 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; - } - - ?> - - - - 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; - } - - ?> - - - - 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; - - ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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']); - } - - ?> - - - - 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']); - } - - ?> - - - - 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']); - } - - ?> - - - - 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; - - ?> - - - - - - - - - - - - - - - - -
Jan-MarApr-JunJul-SepOct-DecTotal


Income
Gross Revenue


Expenses
Total Expenses


Net Profit
-
+
+ + [$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", + ]); ?> + + '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 ? 'Nothing before to compare' : escapeHtml(reportPercent($margin_prev)) . ' ' . escapeHtml($current_year ? 'same time last year' : 'in ' . ($year - 1)) . ''], + ]) ?> + + +
+ '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') ?>
- +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + $column) { + $cell_margin = reportShare($profit_line['cells'][$i], $income_line['cells'][$i], 1); ?> + + + + + + + +
Category title=" – ">Last yearChange
Income
No income this year or last.
Expenses
No spending this year or last.
Margin–' : reportPercent($cell_margin) ?>
+
+ +
+ +
+ + + diff --git a/agent/reports/quote_pipeline.php b/agent/reports/quote_pipeline.php new file mode 100644 index 000000000..ddaad1a0d --- /dev/null +++ b/agent/reports/quote_pipeline.php @@ -0,0 +1,187 @@ + ['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 '' . escapeHtml($row['quote_prefix'] . $row['quote_number']) . ''; +}; +$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 '' . escapeHtml($row['quote_status']) . ''; + }], + '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 'No date'; + } + $left = intval($row['days_left']); + $date = escapeHtml(date('M j, Y', strtotime($row['quote_expire']))); + if ($left < 0) { + return 'Expired ' . (-$left) . ' day' . ($left === -1 ? '' : 's') . ' ago'; + } + if ($left <= 14) { + return '' . ($left === 0 ? 'Today' : "In $left day" . ($left === 1 ? '' : 's')) . ''; + } + 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"; + +?> + +
+ + $period, + 'years' => reportPastYears("SELECT DISTINCT YEAR(quote_date) AS y FROM quotes"), + 'client' => $client_id, + 'export' => ['open' => 'Open quotes', 'clients' => 'By client'], + ]); ?> + + 'Quoted', 'value' => reportMoney($quoted_v), 'sub' => reportCount($quoted_n) . ' quote' . ($quoted_n === 1 ? '' : 's') . ' sent' . ($by['draft']['n'] ? ', ' . $by['draft']['n'] . ' still drafts' : '') . ''], + ['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)) . ' by value, of quotes decided' : 'No quote decided yet'], + ['label' => 'Open now', 'value' => reportMoney(array_sum(array_column($open_live, 'quote_amount'))), 'url' => '/agent/quotes.php', + 'sub' => count($expiring) ? '' . count($expiring) . ' expire within 14 days' : reportCount(count($open_live)) . ' waiting for an answer'], + ]) ?> + + +
+ 'bar', 'labels' => $buckets['labels'], 'series' => $series, 'stacked' => true, 'format' => 'money'], '', 'Value quoted over the period, won, lost and still open') ?> +
+
+ + ' . count($open_expired) . ' past their expiry date - follow up or close them' : 'Soonest to expire first') ?> + 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'))], + ]) ?> +
+ + + '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)], + ]) ?> + +
+ +
+ + + diff --git a/agent/reports/recurring_by_client.php b/agent/reports/recurring_by_client.php index 3a5f76b44..c23fd3fc6 100644 --- a/agent/reports/recurring_by_client.php +++ b/agent/reports/recurring_by_client.php @@ -1,68 +1,199 @@ 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 '
' + . '' . reportPercent($row['share']) . '
'; + }], + '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 '' . escapeHtml($row['recurring_invoice_prefix'] . $row['recurring_invoice_number']) . ''; + }], + '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']) ? 'Automatically' : 'Draft first'; + }], +]; + +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' => 'Per month', 'url' => '/agent/recurring_invoices.php'], + ['label' => 'A year of it', 'value' => reportMoney($mrr * 12), 'sub' => 'At today\'s recurring invoices'], + ['label' => 'Recurring invoices', 'value' => reportCount(count($invoices)), 'sub' => reportCount(count($clients)) . ' client' . (count($clients) === 1 ? '' : 's') . ', ' . (count($clients) ? escapeHtml(reportMoney($mrr / count($clients))) : '-') . ' each a month'], +]; +if ($can_see_costs && !$client_id) { + $stats[] = ['label' => 'After recurring expenses', 'value' => reportMoney($mrr - $costs), 'tone' => $mrr - $costs < 0 ? 'danger' : '', + 'sub' => escapeHtml(reportMoney($costs)) . ' a month goes out', 'url' => '/agent/recurring_expenses.php']; +} else { + $stats[] = ['label' => 'Bills in the next 30 days', 'value' => reportMoney($next_30), 'sub' => 'From these recurring invoices']; +} ?> -
-
-

Recurring Income By Client

-
- +
+ + $client_id, + 'subtitle' => 'As of ' . date('M j, Y'), + 'export' => ['clients' => 'By client', 'invoices' => 'Every recurring invoice'], + ]); ?> + + + + +
+
+ +
+ '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') ?> +
+
+
+
+
+ + +
+ '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') ?> +
+
+
+
+ + + + 'No active recurring invoices.', + 'totals' => ['client' => 'Total', 'count' => count($invoices), 'mrr' => $mrr, 'arr' => $mrr * 12], + ]) ?> +
+ + + 'No active recurring invoices.', 'limit' => 300, 'export_table' => 'invoices', 'totals' => ['number' => 'Total', 'monthly' => $mrr]]) ?> +
-
-
- - - - - - - - - - - - - - - - - - - - - -
ClientMonthly Recurring
Total Monthly Income
-
-
- + + diff --git a/agent/reports/renewals.php b/agent/reports/renewals.php new file mode 100644 index 000000000..ecaaccdb5 --- /dev/null +++ b/agent/reports/renewals.php @@ -0,0 +1,166 @@ + '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] ? '' . $row[$key] . '' : '–'; + }; +}; +$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 '
' . $row['tile'] . '
' . escapeHtml($row['name']) . '' + . ($row['detail'] !== '' ? '
' . escapeHtml($row['detail']) . '
' : '') . '
'; + }], + 'kind' => ['label' => 'Type', 'csv' => function ($row) { return REPORT_RENEWAL_KINDS[$row['kind']]['one']; }, 'html' => function ($row) { + return '' . REPORT_RENEWAL_KINDS[$row['kind']]['one'] . ''; + }], + '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']; +} + +?> + +
+ + $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'], + ]); ?> + + 'Lapsed', 'value' => reportCount(count($lapsed)), 'tone' => $lapsed ? 'danger' : 'success', 'sub' => 'In the last ' . REPORT_RENEWAL_LAPSED_DAYS . ' days'], + ['label' => 'Due in 30 days', 'value' => reportCount(count($soon)), 'tone' => $soon ? 'warning' : '', + 'sub' => reportCount(count(array_filter($soon, function ($r) { return $r['days'] <= 7; }))) . ' this week'], + ['label' => 'Due in the window', 'value' => reportCount(count($ahead_items)), 'sub' => reportCount($clients_affected) . ' ' . ($clients_affected === 1 ? 'client' : 'clients') . ''], + ['label' => 'Renew themselves', 'value' => reportCount(count($auto)), 'tone' => $auto ? 'info' : '', + 'title' => 'Domains on auto-renew and short-lived certificates', 'sub' => '' . ($manual_only ? 'Hidden below' : 'Auto-renew and short-lived') . ''], + ]) ?> + + +
+ + + +
+ 'bar', 'labels' => array_values($months), 'series' => $series, 'stacked' => true, 'format' => 'count', 'legend' => count($series) > 1], + '', 'Renewals falling due by month') ?> +
+
+ + 1) { ?> + + 50, 'export_table' => 'clients']) ?> +
+ + + + 300, 'export_table' => 'items']) ?> + + + + + + + + + diff --git a/agent/reports/satisfaction.php b/agent/reports/satisfaction.php new file mode 100644 index 000000000..53bd9896d --- /dev/null +++ b/agent/reports/satisfaction.php @@ -0,0 +1,294 @@ + $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'] ? '' . $row['bad'] . '' : '–'; + }], + '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 ? '' : ''; + }], +]; +$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'] ? '' . escapeHtml($row['contact_name']) . '' : '-'; + }], + '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 '-'; + } + $late = $row['ticket_response_sla_met'] !== null && intval($row['ticket_response_sla_met']) === 0; + return '' + . reportDuration($row['reply_seconds']) . ($late ? ' ' : '') . ''; + }], + '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 '' + . reportDuration($row['resolve_seconds']) . ($late ? ' ' : '') . ''; + }], + '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 ' . reportPercent($value) . ' ' . escapeHtml($period['compare']) . ''; +}; + +?> + +
+ + $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'], + ]); ?> + + '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']) . ' of ' . reportCount($overall['closed']) . ' closed tickets' : ''], + ['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) . ' ' . ($bad_clients === 1 ? 'client' : 'clients') . ' to follow up' : 'Nothing to follow up'], + ]) ?> + + +
+ +
+ + + +
+ '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'); + ?> +
+
+ + + + false]) ?> + + + + + + ['agent' => 'Total'] + $overall, 'totals_html' => ['score' => reportRateHtml($overall['score'])]]) ?> + + + + + + 50, 'export_table' => 'clients', 'totals' => ['client' => 'Total'] + $overall, 'totals_html' => ['score' => reportRateHtml($overall['score'])]]) ?> + + + + + 100, 'export_table' => 'bad', 'empty' => reportEmpty('No bad ratings in this period.', 'fa-smile', 'success')]) ?> + + + + + + + + + diff --git a/agent/reports/sla_by_client.php b/agent/reports/sla_by_client.php index 1b00305cf..0e79cce42 100644 --- a/agent/reports/sla_by_client.php +++ b/agent/reports/sla_by_client.php @@ -1,177 +1,149 @@ 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'] ? '' . $row['breached_open'] . '' : '–'; + }], +]; + +$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); + ?> -
-
-

SLA by Client

-
- +
+ + $period, + 'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_created_at) AS y FROM tickets WHERE ticket_sla_id > 0"), + 'agent' => $agent_id, + ]); ?> + + 'Clients with SLA tickets', 'value' => reportCount(count($clients)), 'sub' => reportCount($overall['tickets']) . ' tickets'], + ['label' => 'First reply in time', 'value_html' => reportRateHtml($overall['response_percent']), 'sub' => 'Across all clients'], + ['label' => 'Resolved in time', 'value_html' => reportRateHtml($overall['resolution_percent']), 'sub' => 'Across all clients'], + ['label' => 'Clients under 80%', 'value' => reportCount(count($below)), 'tone' => $below ? 'danger' : 'success', 'sub' => 'On response or resolution'], + ]) ?> + + + +
+ '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') ?>
-
-
- - -
- -
-
-

-
-
-
- - - - - - - - - - - - - - - - - 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); - } - ?> - - - - - - - - - - - - - - - - -
ClientTicketsResponse metResponse missedResponse %Resolution metResolution missedResolution %Avg time to respondAvg clock to resolve
No tickets with an SLA in this period.
-
- - 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. - -
-
+ + + 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'])]]) ?> +
- + + + diff --git a/agent/reports/sla_summary.php b/agent/reports/sla_summary.php index 6fce8c104..1e43dc823 100644 --- a/agent/reports/sla_summary.php +++ b/agent/reports/sla_summary.php @@ -1,198 +1,171 @@ 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; ?> -
-
-

SLA Summary

-
- +
+ + $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'], + ]); ?> + + 'Tickets with an SLA', 'value' => reportCount($overall['tickets']), 'sub' => 'Raised in the period'], + ['label' => 'First reply in time', 'value_html' => reportRateHtml($overall['response_percent']), + 'sub' => $previous['response_percent'] !== null ? 'Was ' . reportPercent($previous['response_percent']) . ' ' . escapeHtml($period['compare']) . '' : ''], + ['label' => 'Resolved in time', 'value_html' => reportRateHtml($overall['resolution_percent']), + 'sub' => $previous['resolution_percent'] !== null ? 'Was ' . reportPercent($previous['resolution_percent']) . ' ' . escapeHtml($period['compare']) . '' : ''], + ['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' => 'Whenever they were raised'], + ]) ?> + + +
SLA to start measuring them.', 'fa-stopwatch', 'secondary') ?>
+ + + +
+ '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'); + ?>
-
-
- -
- - -

No tickets raised in carried an SLA. Assign SLAs under Admin > SLAs to start tracking.

- - -
-
-
- -
- Tickets with an SLA - -
-
-
-
-
- -
- Response compliance - -
-
-
-
-
- -
- Resolution compliance - -
-
-
-
- -
-
-

By Priority ()

-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
PriorityTicketsResponse metResponse missedResponse %Resolution metResolution missedResolution %
-
-
-
- -
-
-

By Month ()

-
-
-
- - - - - - - - - - - - - - - - - - - - - -
MonthTicketsResponse %Resolution %Still open
-
-
-
- - 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. - - + + false]) ?>
-
- + +
+ + + 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'])]]) ?> + +
+ + + +
+ + + diff --git a/agent/reports/tax_summary.php b/agent/reports/tax_summary.php index 5be9f825a..4b6f51ecf 100644 --- a/agent/reports/tax_summary.php +++ b/agent/reports/tax_summary.php @@ -1,149 +1,211 @@ ['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' => 'The paid sales the tax was on'], +]; +foreach (array_slice($lines, 0, 3, true) as $line) { + $stats[] = ['label' => $line['name'], 'value' => reportMoney($line['tax_total']), 'sub' => 'At ' . escapeHtml($percent_text($line['percent'])) . '']; +} ?> -
-
-

Collected Tax Summary

-
- +
+ + [$year, $years], + 'controls' => reportSegmentControl('view', $view, ['quarter' => 'Quarterly', 'month' => 'Monthly']), + 'subtitle' => $current_year ? "$year to date" : (string) $year, + ]); ?> + + + + +
Taxes, and the tax on paid invoices shows here.', 'fa-percent', 'secondary') ?>
+ + + +
+ $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'); + ?>
-
-
- - - - -
- -
- - + +
+
+ - " . date('M', mktime(0, 0, 0, $i, 10)) . ""; - } - } else { - echo ""; - echo ""; - echo ""; - echo ""; - } - ?> - + + + + - "; - echo ""; - - 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 ""; - } - - echo ""; - - } 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 ""; - } - - echo ""; - } - - echo ""; - } - - // Totals row - echo ""; - echo ""; - - if ($view == 'monthly') { - for ($i = 1; $i <= 12; $i++) { - echo ""; - } - } else { - for ($q = 1; $q <= 4; $q++) { - echo ""; - } - } - - echo ""; - echo ""; - - ?> + + + + + $column) { ?> + + + + + + + + $column) { ?> + + + + + + + + + $column) { ?> + + + + +
TaxJan-MarApr-JunJul-SepOct-DecTotal title=" – ">
" . escapeHtml($tax_name_raw) . "" . numfmt_format_currency($currency_format, $monthly_tax, $company_currency) . "" . numfmt_format_currency($currency_format, $row_total, $company_currency) . "" . numfmt_format_currency($currency_format, $quarterly_tax, $company_currency) . "" . numfmt_format_currency($currency_format, $row_total, $company_currency) . "
Total" . numfmt_format_currency($currency_format, $monthly_totals[$i], $company_currency) . "" . numfmt_format_currency($currency_format, $quarterly_totals[$q], $company_currency) . "" . numfmt_format_currency($currency_format, $grand_total, $company_currency) . "
Tax collected
Archived–' : reportMoney($line['tax'][$i]) ?>
Total tax
Sales the tax was charged on
–' : reportMoney($line['sales'][$i]) ?>
+
-
- + +
+ + + diff --git a/agent/reports/ticket_aging.php b/agent/reports/ticket_aging.php new file mode 100644 index 000000000..ab423950e --- /dev/null +++ b/agent/reports/ticket_aging.php @@ -0,0 +1,221 @@ + 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 '–'; + } + $tone = in_array($key, ['90', 'old'], true) ? 'text-danger-emphasis fw-semibold' : ($key === '30' ? 'text-warning-emphasis fw-semibold' : ''); + return '' . $row[$key] . ''; + }; +}; +$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'] ? '' . $row['late'] . '' : '–'; + }], +]; +$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 '' . formatAssignee($row['user_id'], $row['agent'], $row['avatar'], true) . ''; +}]] + $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 '' . escapeHtml($row['ticket_status_name']) . ''; + }], + '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 '' . $label . ''; + }], + '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 '' . ticketSlaPill($row['sla']) . ticketDuePill($row['due']) . ''; + }], + '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 '' . reportDuration($row['age_seconds']) . ''; + }], + 'last_activity' => ['label' => 'Last activity', 'type' => 'date', 'csv' => function ($row) { return $row['last_activity']; }, 'html' => function ($row) { + return '' . escapeHtml(timeAgo($row['last_activity'])) . ''; + }], +]; + +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 = '
'; + +?> + +
+ + $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'], + ]); ?> + + 'Open tickets', 'value' => reportCount(count($tickets)), 'url' => '/agent/tickets.php' . ($client_id ? "?client_id=$client_id" : ''), + 'sub' => reportCount($totals['30'] + $totals['90'] + $totals['old']) . ' open over a week'], + ['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' => 'The client spoke last, or no reply yet'], + ['label' => 'Late', 'value' => reportCount($totals['late']), 'tone' => $totals['late'] ? 'danger' : 'success', 'url' => '/agent/tickets.php?show=overdue' . ($client_id ? "&client_id=$client_id" : ''), + 'sub' => 'Past their SLA or due date'], + ['label' => 'Unassigned', 'value' => reportCount($unassigned), 'tone' => $unassigned ? 'warning' : '', 'url' => '/agent/tickets.php?assigned=unassigned' . ($client_id ? "&client_id=$client_id" : ''), + 'sub' => $oldest ? 'Oldest open ' . reportDuration($oldest['age_seconds']) . '' : ''], + ]) ?> + + + +
+ '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') ?> +
+
+ + + + reportEmpty('No open tickets.'), 'totals' => ['agent' => 'Total'] + $totals]) ?> +
+ + + + reportEmpty('No open tickets.'), 'limit' => 50, 'export_table' => 'clients', 'totals' => ['client' => 'Total'] + $totals]) ?> +
+ + + + + 300, 'export_table' => 'tickets']) ?> + +
+ + + + + + diff --git a/agent/reports/ticket_by_client.php b/agent/reports/ticket_by_client.php index 03661e840..0392de121 100644 --- a/agent/reports/ticket_by_client.php +++ b/agent/reports/ticket_by_client.php @@ -1,316 +1,193 @@ $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 ? '–' : '' . reportChangeHtml($row['opened'], $row['prev'], 'down') . ''; + }], + 'urgent' => ['label' => 'Urgent or high', 'type' => 'count', 'html' => function ($row) { + return $row['urgent'] ? '' . $row['urgent'] . '' : '–'; + }], + 'resolved' => ['label' => 'Resolved', 'type' => 'count'], + 'open_now' => ['label' => 'Open now', 'type' => 'count', 'html' => function ($row) { + return $row['open_now'] ? '' . $row['open_now'] . '' : '–'; + }], + '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 ? '–' : reportRateHtml($row['csat'], 90, 75) . ' ' . ($row['good'] + $row['bad']) . ''; + }], +]; + +$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; })); ?> -
-
-

Tickets By Client

-
- +
+ + $period, + 'years' => reportPastYears("SELECT DISTINCT YEAR(ticket_created_at) AS y FROM tickets"), + 'agent' => $agent_id, + ]); ?> + + 'Tickets opened', 'value' => reportCount($totals['opened']), 'sub' => reportCount($with_tickets) . ' clients raised them'], + ['label' => 'Average per client', 'value' => $with_tickets ? number_format($totals['opened'] / $with_tickets, 1) : '-', 'sub' => 'Of those who raised any'], + ['label' => 'Busiest', 'value' => $busiest && $busiest['opened'] ? $busiest['client'] : '-', 'sub' => $busiest && $busiest['opened'] ? $busiest['opened'] . ' tickets · ' . reportPercent(reportShare($busiest['opened'], $totals['opened'])) . ' of all' : ''], + ['label' => 'Time logged', 'value' => reportHours($totals['seconds']) . ' h', 'sub' => $with_tickets ? reportHours($totals['seconds'] / $with_tickets) . ' h per client' : ''], + ]) ?> + + + +
+ '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'); + ?>
-
-
- - -
- -
-
-

Yearly ()

-
-
-
- - - - - - - - - - - - - - - - - 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); - - } - - ?> - - - - - - - - - - - - - - - -
ClientRaisedPriority: LowPriority: MedPriority: HighPriority: UrgentResolvedTotal Time worked (H:M:S)Avg time to respondAvg time to resolve
-
-
-
- - - -
-
-

Monthly ()

-
-
-
- - - - - - - - - - - - - - - - - 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); - } - - ?> - - - - - - - - - - - - - - - -
ClientRaisedPriority: LowPriority: MedPriority: HighPriority: UrgentResolvedTotal Time worked (H:M:S)Avg time to respondAvg time to resolve
-
- -
-
+ + + 'No tickets in this period.', 'totals' => $totals, 'totals_html' => ['sla' => reportRateHtml($totals['sla']), 'csat' => $totals['csat'] === null ? '' : reportRateHtml($totals['csat'], 90, 75)]]) ?> +
- + + + diff --git a/agent/reports/ticket_summary.php b/agent/reports/ticket_summary.php index 1c3aeff89..d5e826f3f 100644 --- a/agent/reports/ticket_summary.php +++ b/agent/reports/ticket_summary.php @@ -1,162 +1,312 @@ $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); ?> - - +
-
-
-

Ticket Summary

-
- + $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'], + ]); ?> + + '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' => 'Whenever they were raised'], + ['label' => 'First reply', 'value' => reportDuration($response), 'title' => 'The middle ticket - half got a first reply sooner, half later', + 'sub' => $response_prev !== null ? 'Typically · was ' . reportDuration($response_prev) . '' : 'Typically'], + ['label' => 'Time to resolve', 'value' => reportDuration($resolve), 'title' => 'The middle ticket - half were resolved sooner, half later', + 'sub' => $resolve_prev !== null ? 'Typically · was ' . reportDuration($resolve_prev) . '' : 'Typically'], + ['label' => 'Time logged', 'value' => reportHours($time_logged) . ' h', 'sub' => 'On replies in the period'], + ]) ?> + + +
+ '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') ?>
-
-
- -
-
-
- +
+
+ +
+ + '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') ?> +
+ +
No tickets.
+ +
- -
- - - - - - - - - - - - - - - - - - - - - 0 && $tickets_for_month > $largest_ticket_month) { - $largest_ticket_month = $tickets_for_month; - } - - $total_tickets_for_all_months += $tickets_for_month; ?> - - - - - - -
JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecemberTotal
+
+ +
+ 'dark', 'High' => 'danger', 'Medium' => 'warning', 'Low' => 'info']; + $colors = array_map(function ($p) use ($priority_colors) { return $priority_colors[$p]; }, array_keys($priority_order)); ?> + 'doughnut', 'labels' => array_keys($priority_order), 'series' => [['label' => 'Tickets', 'data' => array_values($priority_order)]], 'colors' => $colors, 'format' => 'count'], 'donut', 'Tickets by priority') ?> +
+ +
No tickets.
+ +
+
+
+
+ +
+ +

Darker is busier - useful for planning who is on when.

+
+
+ + + +
+ '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') ?> +
+
+ + +
+ +
+ + +
+
+ + + + + + + +
+
+ +
No tickets.
+ +
+
+ +
+ + +
+
+ + + + + + + +
+
+ +
No tickets with a contact.
+ +
+
+
+ + + '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'))]]) ?> + +
+
- - + diff --git a/agent/reports/tickets_unbilled.php b/agent/reports/tickets_unbilled.php index 840ec0edd..99b270756 100644 --- a/agent/reports/tickets_unbilled.php +++ b/agent/reports/tickets_unbilled.php @@ -1,143 +1,182 @@ 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 '' + . ($days <= 0 ? 'Today' : $days . ' day' . ($days === 1 ? '' : 's')) . ''; +}; +$rate_html = function ($row) { + if ($row['rate'] <= 0) { + return 'No rate'; + } + return reportMoney($row['rate']) . ($row['default_rate'] ? ' default' : ''); +}; -$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 '' . reportCount($row['tickets']) . '' + . ($row['no_time'] ? ' (' . $row['no_time'] . ' with no time)' : ''); + }], + '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 ? 'None' : 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; }); ?> -
-
-

Unbilled Tickets By Client

-
- +
+ + $client_id, + 'subtitle' => 'As of ' . date('M j, Y'), + 'export' => ['clients' => 'By client', 'tickets' => 'Every ticket'], + ]); ?> + + 'Not invoiced yet', 'value' => reportMoney($totals['value']), 'tone' => $totals['value'] > 0 ? 'warning' : '', + 'sub' => 'At each client\'s rate'], + ['label' => 'Tickets', 'value' => reportCount(count($tickets)), 'url' => '/agent/tickets.php?billing=unbilled&state=closed', + 'sub' => reportCount(count($clients)) . ' client' . (count($clients) === 1 ? '' : 's') . ''], + ['label' => 'Hours to bill', 'value' => number_format($totals['billable_hours'], 2), 'sub' => escapeHtml(reportHours($totals['seconds'], 2)) . ' logged', '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')))) . ' of it' : 'Nothing left that long'], + ]) ?> + + +
+ +
+
billable ticket under 8 minutes logged, so nothing here - log the time, or mark not billable.
+
ticket for a client with no hourly rate - set one on the client, or a default hourly rate in Admin > Settings.
-
-
- -
+ -
- - - - - - - - - - - 0) { - $rows = $rows + 1; - - ?> - - - - - - - - - - - - - -
ClientTickets RaisedBillable TicketsUnbilled Tickets
- -
You are all caught up! There are no unbilled tickets for this year. -
-
-
+ + reportEmpty('You are all caught up - every billable ticket that is done has been invoiced.'), + 'totals' => ['client' => 'Total'] + $totals, + ]) ?>
- + + 300, 'export_table' => 'tickets', 'totals' => ['ticket' => 'Total'] + $totals]) ?> + +
+ + +
+ + + diff --git a/agent/reports/time_by_tech.php b/agent/reports/time_by_tech.php index f26a1928c..834edf4a5 100644 --- a/agent/reports/time_by_tech.php +++ b/agent/reports/time_by_tech.php @@ -1,140 +1,220 @@ 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'] ? '' : ' Inactive'); + }], + '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 '–'; + } + $share = $row['utilization']; + $tone = $share >= 70 ? 'bg-success' : ($share >= 40 ? '' : 'bg-warning'); + return '
' + . '' . reportPercent(round($share)) . '
'; + }], + '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'] ? '' . $row['open_now'] . '' : '–'; + }], + '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 ? '–' : reportRateHtml($row['csat'], 90, 75) . ' ' . ($row['good'] + $row['bad']) . ''; + }], +]; -$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 = '
' + . '' + . '' + . 'h a day
'; +$with_time = array_values(array_filter($agents, function ($a) { return $a['seconds'] > 0; })); ?> -
-
-

Time Logged By Technician

-
- -
-
-
-
- -
+
-
-
-

Yearly ()

-
-
-
- - - - - - - - - - - $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']); + 'Hours logged', 'value' => reportHours($total_seconds) . ' h', 'sub' => 'By ' . count($with_time) . ' agent' . (count($with_time) === 1 ? '' : 's') . ''], + ['label' => 'Billable', 'value' => reportPercent(reportShare($total_billable, $total_seconds)), 'sub' => escapeHtml(reportHours($total_billable)) . ' h on billable tickets'], + ['label' => 'Utilization', 'value' => reportPercent($totals['utilization'] === null ? null : round($totals['utilization'])), + 'sub' => 'Of ' . $working_days . ' working day' . ($working_days === 1 ? '' : 's') . ' × ' . escapeHtml(rtrim(rtrim(number_format($workday, 2), '0'), '.')) . ' h each'], + ['label' => 'Resolved', 'value' => reportCount($totals['resolved']), 'sub' => reportCount($totals['open_now']) . ' open now' . ($unassigned_open ? ', ' . $unassigned_open . ' unassigned' : '') . ''], + ]) ?> - // 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']); - - ?> - - - - - - - - - - -
TechnicianTickets assignedTickets touchedTotal time worked (H:M:S)
+ +
+
+ +
+ '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') ?>
+
+ +
+ 'line', 'labels' => $buckets['labels'], 'series' => $weekly, 'format' => 'hours', 'legend' => true], '', 'Hours logged by each agent over the period') ?> +
+
+
+
+ - - + + 'No agents.', 'totals' => $totals, 'totals_html' => ['utilization' => $totals['utilization'] === null ? '' : reportPercent(round($totals['utilization']))]]) ?> +
- + + + diff --git a/client/post.php b/client/post.php index 5aaba6e77..636f12e76 100644 --- a/client/post.php +++ b/client/post.php @@ -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")) { diff --git a/css/itflow_custom.css b/css/itflow_custom.css index d7190d444..3af1b408c 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -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; + } +} diff --git a/functions.php b/functions.php index c8a053349..75cb84dd9 100644 --- a/functions.php +++ b/functions.php @@ -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'; diff --git a/functions/dashboard.php b/functions/dashboard.php index dabb981a0..cc153c299 100644 --- a/functions/dashboard.php +++ b/functions/dashboard.php @@ -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"), diff --git a/functions/reports.php b/functions/reports.php new file mode 100644 index 000000000..080b239ee --- /dev/null +++ b/functions/reports.php @@ -0,0 +1,2012 @@ + $period]); + * ... reportStats(), reportChart(), reportTable() ... + * require_once "../../includes/footer.php"; + * + * Money is counted the way the dashboard counts it: income is what came in - + * invoice payments, and revenues with a category; spending is expenses with a + * vendor, as an expense with no vendor is the out side of a transfer between + * accounts. Anything tied to a client goes through clientScopeSql(), so an + * agent restricted to some clients only ever sees those clients' rows; the + * company's own books (income, expenses, profit and loss, tax, budget) are + * company-wide, as they are on the dashboard. + */ + +/* + * ---------- the catalogue ---------- + */ + +/** + * Every report, in the groups the menu shows them in. Per report: + * 'title', 'icon', 'description' - what the menu and the Reports page say + * 'module' - the permission it needs (read), on top of module_reporting + * 'feature' - the parts of ITFlow that have to be turned on: accounting, + * ticketing and/or itdoc + * The array key is the page's file name without .php. + */ +function reportCatalog() { + return [ + 'finance' => [ + 'label' => 'Finance', + 'reports' => [ + 'profit_loss' => [ + 'title' => 'Profit & Loss', 'icon' => 'fa-balance-scale', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Income against spending by month or quarter, with the margin and last year beside it.', + ], + 'income_summary' => [ + 'title' => 'Income', 'icon' => 'fa-hand-holding-usd', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Money received by category and month - invoice payments and other revenue.', + ], + 'expense_summary' => [ + 'title' => 'Expenses', 'icon' => 'fa-shopping-cart', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Spending by category and month.', + ], + 'budget' => [ + 'title' => 'Budget vs Actual', 'icon' => 'fa-bullseye', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Plan what you will spend each month by category, and see how the real spending compares.', + ], + 'expense_by_vendor' => [ + 'title' => 'Spend by Vendor', 'icon' => 'fa-building', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Who you pay the most - and the vendors paid 600 or more, for 1099 forms.', + ], + 'tax_summary' => [ + 'title' => 'Tax Collected', 'icon' => 'fa-percent', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Tax collected on paid invoices, and the sales it was collected on, by month or quarter.', + ], + 'mileage' => [ + 'title' => 'Mileage', 'icon' => 'fa-route', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Miles driven by agent and client, with a reimbursement estimate at your rate.', + ], + ], + ], + 'billing' => [ + 'label' => 'Sales & Billing', + 'reports' => [ + 'outstanding_balances' => [ + 'title' => 'Receivables Aging', 'icon' => 'fa-hourglass-half', 'module' => 'module_sales', 'feature' => ['accounting'], + 'description' => 'What each client owes, split by how late it is.', + ], + 'income_by_client' => [ + 'title' => 'Income by Client', 'icon' => 'fa-users', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'What each client paid in the period, against the period before.', + ], + 'client_profitability' => [ + 'title' => 'Client Profitability', 'icon' => 'fa-chart-line', 'module' => 'module_financial', 'feature' => ['accounting'], + 'description' => 'Each client\'s income against the hours spent on them - your effective hourly rate.', + ], + 'recurring_by_client' => [ + 'title' => 'Recurring Revenue', 'icon' => 'fa-sync-alt', 'module' => 'module_sales', 'feature' => ['accounting'], + 'description' => 'Monthly and yearly recurring revenue by client and category.', + ], + 'quote_pipeline' => [ + 'title' => 'Quotes Pipeline', 'icon' => 'fa-comment-dollar', 'module' => 'module_sales', 'feature' => ['accounting'], + 'description' => 'Open quotes, your win rate, and the value won and lost.', + ], + 'tickets_unbilled' => [ + 'title' => 'Unbilled Work', 'icon' => 'fa-receipt', 'module' => 'module_sales', 'feature' => ['accounting', 'ticketing'], + 'description' => 'Billable tickets that are done but not invoiced yet, with the time and value on them.', + ], + 'client_ticket_time_detail' => [ + 'title' => 'Time Detail by Client', 'icon' => 'fa-stopwatch', 'module' => 'module_sales', 'feature' => ['accounting', 'ticketing'], + 'description' => 'Every reply with time on it, by client and ticket, rounded up to your billing increment.', + ], + ], + ], + 'service' => [ + 'label' => 'Service Desk', + 'reports' => [ + 'ticket_summary' => [ + 'title' => 'Ticket Overview', 'icon' => 'fa-life-ring', 'module' => 'module_support', 'feature' => ['ticketing'], + 'description' => 'Tickets opened and resolved, how fast, where they came from and when.', + ], + 'ticket_aging' => [ + 'title' => 'Open Ticket Aging', 'icon' => 'fa-hourglass-start', 'module' => 'module_support', 'feature' => ['ticketing'], + 'description' => 'Every open ticket by age, agent and client - the backlog, oldest first.', + ], + 'ticket_by_client' => [ + 'title' => 'Tickets by Client', 'icon' => 'fa-building', 'module' => 'module_support', 'feature' => ['ticketing'], + 'description' => 'Ticket volume, time worked and response times for each client.', + ], + 'time_by_tech' => [ + 'title' => 'Technician Performance', 'icon' => 'fa-user-clock', 'module' => 'module_support', 'feature' => ['ticketing'], + 'description' => 'Hours logged, billable share, utilization and tickets for each agent.', + ], + 'sla_summary' => [ + 'title' => 'SLA Performance', 'icon' => 'fa-tachometer-alt', 'module' => 'module_support', 'feature' => ['ticketing'], + 'description' => 'Response and resolution targets met, by month, priority and agent.', + ], + 'sla_by_client' => [ + 'title' => 'SLA by Client', 'icon' => 'fa-handshake', 'module' => 'module_support', 'feature' => ['ticketing'], + 'description' => 'Response and resolution targets met for each client.', + ], + 'satisfaction' => [ + 'title' => 'Customer Satisfaction', 'icon' => 'fa-smile', 'module' => 'module_support', 'feature' => ['ticketing'], + 'description' => 'How clients rated their closed tickets, by agent and client.', + ], + ], + ], + 'clients' => [ + 'label' => 'Clients & Documentation', + 'reports' => [ + 'client_review' => [ + 'title' => 'Client Review', 'icon' => 'fa-clipboard-list', 'module' => 'module_support', 'feature' => [], + 'description' => 'One client\'s quarter on a page - tickets, SLAs, assets, renewals and what to do next. Made to print for a business review.', + ], + 'renewals' => [ + 'title' => 'Renewals & Expirations', 'icon' => 'fa-calendar-alt', 'module' => 'module_support', 'feature' => ['itdoc'], + 'description' => 'Domains, certificates, licenses and warranties coming up for renewal, or already lapsed.', + ], + 'asset_lifecycle' => [ + 'title' => 'Asset Lifecycle', 'icon' => 'fa-recycle', 'module' => 'module_support', 'feature' => ['itdoc'], + 'description' => 'How old the hardware is, its warranty and operating system support - and what is due for replacement.', + ], + 'documentation_coverage' => [ + 'title' => 'Documentation Coverage', 'icon' => 'fa-tasks', 'module' => 'module_support', 'feature' => ['itdoc'], + 'description' => 'What is documented for each client, and what is missing.', + ], + 'credential_rotation' => [ + 'title' => 'Credential Rotation', 'icon' => 'fa-key', 'module' => 'module_credential', 'feature' => ['itdoc'], + 'description' => 'Passwords that have not changed in a while, oldest first.', + ], + ], + ], + ]; +} + +/** A report's catalogue entry, with its key - or null. */ +function reportFind($key) { + foreach (reportCatalog() as $group) { + if (isset($group['reports'][$key])) { + return $group['reports'][$key] + ['key' => $key]; + } + } + return null; +} + +/** The user's permission on a module, looked up once per page. */ +function reportPermission($module) { + static $levels = []; + if (!array_key_exists($module, $levels)) { + $levels[$module] = intval(lookupUserPermission($module)); + } + return $levels[$module]; +} + +/** Is that part of ITFlow turned on - accounting, ticketing or itdoc? */ +function reportFeatureOn($feature) { + global $config_module_enable_accounting, $config_module_enable_ticketing, $config_module_enable_itdoc; + $on = [ + 'accounting' => intval($config_module_enable_accounting) === 1, + 'ticketing' => intval($config_module_enable_ticketing) === 1, + 'itdoc' => intval($config_module_enable_itdoc) === 1, + ]; + return !empty($on[$feature]); +} + +/** May this user open this report? */ +function reportCan(array $report) { + foreach ($report['feature'] ?? [] as $feature) { + if (!reportFeatureOn($feature)) { + return false; + } + } + return reportPermission('module_reporting') >= 1 && reportPermission($report['module']) >= 1; +} + +/** The catalogue with only the reports this user may open, and only the groups left with any. */ +function reportCatalogForUser() { + $groups = []; + foreach (reportCatalog() as $group_key => $group) { + $reports = []; + foreach ($group['reports'] as $key => $report) { + if (reportCan($report)) { + $reports[$key] = $report + ['key' => $key]; + } + } + if ($reports) { + $groups[$group_key] = ['label' => $group['label'], 'reports' => $reports]; + } + } + return $groups; +} + +/** Stop here unless this user may open this report. */ +function reportEnforce($key) { + $report = reportFind($key); + if (!$report) { + exit('No such report.'); + } + foreach ($report['feature'] ?? [] as $feature) { + if (!reportFeatureOn($feature)) { + exit('This report needs the ' . ucfirst($feature === 'itdoc' ? 'documentation' : $feature) . ' module, which is turned off in Admin > Settings > Modules.'); + } + } + enforceUserPermission($report['module']); + return $report; +} + +/* + * ---------- periods ---------- + */ + +const REPORT_PERIODS = [ + 'this_month' => 'This month', + 'last_month' => 'Last month', + 'this_quarter' => 'This quarter', + 'last_quarter' => 'Last quarter', + 'this_year' => 'This year', + 'last_year' => 'Last year', + 'last_30' => 'Last 30 days', + 'last_90' => 'Last 90 days', + 'last_12' => 'Last 12 months', + 'custom' => 'Custom dates', +]; + +/** The URL parameters that pick this period again - for a link to another report over the same dates. */ +function reportPeriodQuery(array $period) { + if ($period['key'] === 'custom') { + return ['period' => 'custom', 'from' => $period['start'], 'to' => $period['end']]; + } + return ['period' => $period['key']]; +} + +/** A Y-m-d date from the request, or $fallback. */ +function reportDateParam($name, $fallback) { + $value = (string) ($_GET[$name] ?? ''); + $date = DateTime::createFromFormat('!Y-m-d', $value); + return ($date && $date->format('Y-m-d') === $value) ? $value : $fallback; +} + +/** + * The period picked (?period=, with ?from= and ?to= for custom dates), as + * dates: 'start' and 'end' (Y-m-d, inclusive), the span before it to compare + * with ('prev_start', 'prev_end' and 'compare', "last quarter"), a 'label' + * and the dates written out ('range'). A period still running - this month, + * quarter or year - ends today and is compared with the same stretch of the + * one before, so day 15 is weighed against days 1-15, not a whole month. + */ +function reportPeriod($default = 'this_year') { + $key = (string) ($_GET['period'] ?? $default); + if (!isset(REPORT_PERIODS[$key]) && !preg_match('/^year-\d{4}$/', $key)) { + $key = $default; + } + + $today = date('Y-m-d'); + $year = intval(date('Y')); + $quarter_start = sprintf('%d-%02d-01', $year, intdiv(intval(date('n')) - 1, 3) * 3 + 1); + $month_end = function ($date) { + return date('Y-m-t', strtotime($date)); + }; + + switch ($key) { + case 'this_month': + $start = date('Y-m-01'); + $end = $today; + $prev_start = dashboardShiftMonths($start, -1); + $prev_end = dashboardShiftMonths($today, -1); + $compare = 'the same days last month'; + break; + case 'last_month': + $start = dashboardShiftMonths(date('Y-m-01'), -1); + $end = $month_end($start); + $prev_start = dashboardShiftMonths($start, -1); + $prev_end = $month_end($prev_start); + $compare = 'the month before'; + break; + case 'this_quarter': + $start = $quarter_start; + $end = $today; + $prev_start = dashboardShiftMonths($start, -3); + $prev_end = dashboardShiftMonths($today, -3); + $compare = 'the same point last quarter'; + break; + case 'last_quarter': + $start = dashboardShiftMonths($quarter_start, -3); + $end = $month_end(dashboardShiftMonths($start, 2)); + $prev_start = dashboardShiftMonths($start, -3); + $prev_end = $month_end(dashboardShiftMonths($prev_start, 2)); + $compare = 'the quarter before'; + break; + case 'last_year': + $start = ($year - 1) . '-01-01'; + $end = ($year - 1) . '-12-31'; + $prev_start = ($year - 2) . '-01-01'; + $prev_end = ($year - 2) . '-12-31'; + $compare = $year - 2; + break; + case 'last_30': + case 'last_90': + $days = $key === 'last_30' ? 30 : 90; + $start = date('Y-m-d', strtotime('-' . ($days - 1) . ' days')); + $end = $today; + $prev_start = date('Y-m-d', strtotime('-' . (2 * $days - 1) . ' days')); + $prev_end = date('Y-m-d', strtotime("-$days days")); + $compare = "the $days days before"; + break; + case 'last_12': + $start = dashboardShiftMonths(date('Y-m-01'), -11); + $end = $today; + $prev_start = dashboardShiftMonths($start, -12); + $prev_end = dashboardShiftMonths($today, -12); + $compare = 'the 12 months before'; + break; + case 'custom': + $start = reportDateParam('from', date('Y-m-01')); + $end = reportDateParam('to', $today); + if ($start > $end) { + [$start, $end] = [$end, $start]; + } + $span = intval((new DateTime($start))->diff(new DateTime($end))->days) + 1; + $prev_end = date('Y-m-d', strtotime("$start -1 day")); + $prev_start = date('Y-m-d', strtotime("$prev_end -" . ($span - 1) . ' days')); + $compare = 'the ' . $span . ' day' . ($span === 1 ? '' : 's') . ' before'; + break; + default: + if (preg_match('/^year-(\d{4})$/', $key, $m)) { + $picked = intval($m[1]); + $start = "$picked-01-01"; + $end = "$picked-12-31"; + $prev_start = ($picked - 1) . '-01-01'; + $prev_end = ($picked - 1) . '-12-31'; + $compare = $picked - 1; + break; + } + // this_year + $key = 'this_year'; + $start = "$year-01-01"; + $end = $today; + $prev_start = ($year - 1) . '-01-01'; + $prev_end = dashboardShiftMonths($today, -12); + $compare = 'the same point last year'; + } + + $days = intval((new DateTime($start))->diff(new DateTime($end))->days) + 1; + + return [ + 'key' => $key, + 'label' => REPORT_PERIODS[$key] ?? substr($key, 5), + 'start' => $start, + 'end' => $end, + 'prev_start' => $prev_start, + 'prev_end' => $prev_end, + 'compare' => (string) $compare, + 'range' => reportRangeText($start, $end), + 'days' => $days, + ]; +} + +/** "Jul 1 - Sep 30, 2026", "Dec 1, 2025 - Jan 15, 2026" or "Oct 15, 2026". */ +function reportRangeText($start, $end) { + $s = strtotime($start); + $e = strtotime($end); + if ($start === $end) { + return date('M j, Y', $s); + } + if (date('Y', $s) === date('Y', $e)) { + return date('M j', $s) . ' – ' . date('M j, Y', $e); + } + return date('M j, Y', $s) . ' – ' . date('M j, Y', $e); +} + +/** SQL: $column falls in the period (or the one before it, with $previous). Works on DATE and DATETIME columns. */ +function reportRangeSql($column, $period, $previous = false) { + $start = $previous ? $period['prev_start'] : $period['start']; + $end = $previous ? $period['prev_end'] : $period['end']; + return "($column >= '$start' AND $column < '$end' + INTERVAL 1 DAY)"; +} + +/** + * The steps a chart over the period is drawn in - days up to a month, weeks + * up to four months, months beyond that - as 'keys' (what reportBucketSql() + * returns for each) and 'labels'. + */ +function reportBuckets($period) { + $unit = $period['days'] <= 31 ? 'day' : ($period['days'] <= 120 ? 'week' : 'month'); + $cursor = new DateTime($period['start']); + $end = new DateTime($period['end']); + if ($unit === 'week') { + $cursor->modify('-' . (intval($cursor->format('N')) - 1) . ' days'); + } elseif ($unit === 'month') { + $cursor->modify('first day of this month'); + } + $multi_year = substr($period['start'], 0, 4) !== substr($period['end'], 0, 4); + + $keys = []; + $labels = []; + for ($guard = 0; $cursor <= $end && $guard < 400; $guard++) { + if ($unit === 'month') { + $keys[] = $cursor->format('Y-m'); + $labels[] = $cursor->format($multi_year ? 'M y' : 'M'); + $cursor->modify('+1 month'); + } else { + $keys[] = $cursor->format('Y-m-d'); + $labels[] = $cursor->format('M j'); + $cursor->modify($unit === 'week' ? '+7 days' : '+1 day'); + } + } + + return ['unit' => $unit, 'keys' => $keys, 'labels' => $labels]; +} + +/** SQL for the bucket a date falls in - the same keys reportBuckets() lays out. */ +function reportBucketSql($column, $unit) { + if ($unit === 'month') { + return "DATE_FORMAT($column, '%Y-%m')"; + } + if ($unit === 'week') { + return "DATE_FORMAT(DATE($column) - INTERVAL WEEKDAY($column) DAY, '%Y-%m-%d')"; + } + return "DATE_FORMAT($column, '%Y-%m-%d')"; +} + +/** A query returning "b" (bucket) and "v" (value) rows, laid on the buckets in order. */ +function reportSeries($sql, array $keys) { + global $mysqli; + $values = array_fill_keys($keys, 0.0); + $result = mysqli_query($mysqli, $sql); + while ($row = mysqli_fetch_assoc($result)) { + if (isset($values[$row['b']])) { + $values[$row['b']] += floatval($row['v']); + } + } + return array_map(function ($v) { + return round($v, 2); + }, array_values($values)); +} + +/** + * For the reports laid out as a year of months: the year picked (?year=) and + * the years to offer - every year $sql (returning "y") finds, plus this year. + */ +function reportYear($sql) { + global $mysqli; + $current = intval(date('Y')); + $years = [$current]; + $result = mysqli_query($mysqli, $sql); + while ($row = mysqli_fetch_assoc($result)) { + $y = intval($row['y']); + if ($y > 1970 && $y <= $current + 1) { + $years[] = $y; + } + } + $years = array_values(array_unique($years)); + rsort($years); + $year = intval($_GET['year'] ?? $current); + if (!in_array($year, $years, true)) { + $year = $current; + } + return [$year, $years]; +} + +/** + * Years before last year that $sql (returning "y") finds data in, newest + * first - for the period picker, beside its This year and Last year. + */ +function reportPastYears($sql) { + global $mysqli; + $years = []; + $result = mysqli_query($mysqli, $sql); + while ($row = mysqli_fetch_assoc($result)) { + $y = intval($row['y']); + if ($y > 1970 && $y < intval(date('Y')) - 1) { + $years[] = $y; + } + } + $years = array_values(array_unique($years)); + rsort($years); + return $years; +} + +/** How many months of $year have started - 12 for a past year. */ +function reportMonthsElapsed($year) { + $current = intval(date('Y')); + if ($year < $current) { + return 12; + } + return $year > $current ? 0 : intval(date('n')); +} + +/* + * ---------- request ---------- + */ + +/** The client picked, if this user may see it - else 0, meaning every client they can see. */ +function reportClientId() { + global $mysqli; + $client_id = intval($_GET['client_id'] ?? 0); + if ($client_id <= 0 || !hasClientAccess($client_id)) { + return 0; + } + $exists = mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id")); + return $exists ? $client_id : 0; +} + +/** The agent picked (?agent=), or 0. */ +function reportAgentId() { + global $mysqli; + $user_id = intval($_GET['agent'] ?? 0); + if ($user_id <= 0) { + return 0; + } + return mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM users WHERE user_id = $user_id AND user_type = 1")) ? $user_id : 0; +} + +/** A client's name, for headings. */ +function reportClientName($client_id) { + global $mysqli; + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = " . intval($client_id))); + return $row ? $row[0] : ''; +} + +/** SQL limiting $column to the client picked, or to every client this user may see. */ +function reportClientSql($column, $client_id) { + $client_id = intval($client_id); + return ($client_id ? " AND $column = $client_id" : '') . clientScopeSql($column); +} + +/* + * ---------- numbers ---------- + */ + +function reportMoney($amount) { + global $currency_format, $session_company_currency; + return numfmt_format_currency($currency_format, floatval($amount), $session_company_currency); +} + +/** Money to the whole unit - for the wide year-of-months grids, where cents only crowd the columns. */ +function reportMoneyWhole($amount) { + global $currency_format, $session_company_currency; + static $formatter = null; + if ($formatter === null) { + $formatter = clone $currency_format; + $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 0); + $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 0); + } + return numfmt_format_currency($formatter, round(floatval($amount)), $session_company_currency); +} + +function reportCount($count) { + return number_format(intval($count)); +} + +/** Seconds as decimal hours - 12.5. */ +function reportHours($seconds, $decimals = 1) { + return number_format(max(0, floatval($seconds)) / 3600, $decimals); +} + +/** Seconds as a duration that fits a cell - "45m", "5h 20m", "3d 4h". '-' for none. */ +function reportDuration($seconds) { + if ($seconds === null || $seconds === '') { + return '-'; + } + $minutes = intval(round(floatval($seconds) / 60)); + if ($minutes < 1) { + return '<1m'; + } + if ($minutes < 60) { + return $minutes . 'm'; + } + $hours = intdiv($minutes, 60); + if ($hours < 24) { + $rest = $minutes % 60; + return $hours . 'h' . ($rest ? " {$rest}m" : ''); + } + $days = intdiv($hours, 24); + $rest = $hours % 24; + return $days . 'd' . ($rest ? " {$rest}h" : ''); +} + +/** $part of $whole as a percentage, or null when there is no whole. */ +function reportShare($part, $whole, $decimals = 0) { + return floatval($whole) != 0.0 ? round(floatval($part) / floatval($whole) * 100, $decimals) : null; +} + +/** A percentage for a cell - '-' when there is none. */ +function reportPercent($percent) { + return $percent === null ? '-' : rtrim(rtrim(number_format($percent, 1), '0'), '.') . '%'; +} + +/** Change from $previous to $current in whole percent - null when there is nothing before to compare with. */ +function reportChange($current, $previous) { + if (abs(floatval($previous)) < 0.005) { + return null; + } + return intval(round((floatval($current) - floatval($previous)) / abs(floatval($previous)) * 100)); +} + +/** + * The change as an arrow and a percentage, green when it went the right way + * ($good 'up' or 'down'), with what it is compared with after it. + */ +function reportChangeHtml($current, $previous, $good = 'up', $compare = '') { + $change = reportChange($current, $previous); + $against = $compare !== '' ? ' vs ' . escapeHtml($compare) . '' : ''; + if ($change === null) { + return 'Nothing before to compare'; + } + if ($change === 0) { + return 'No change' . $against; + } + $better = $good === 'up' ? $change > 0 : $change < 0; + return '' + . '' . abs($change) . '%' . $against; +} + +/** A compliance percentage coloured by how good it is - 95 and up green, 80 amber, below red. */ +function reportRateHtml($percent, $good = 95, $fair = 80) { + if ($percent === null) { + return '-'; + } + $tone = $percent >= $good ? 'success' : ($percent >= $fair ? 'warning' : 'danger'); + return '' . reportPercent($percent) . ''; +} + +/* + * ---------- building blocks ---------- + */ + +/** + * The strip of figures along the top of a report. Each is + * ['label' => .., 'value' => plain text, 'sub' => HTML line under it, + * 'url' => .., 'tone' => danger | warning | success | info, 'title' => ..] + * 'value_html' instead of 'value' for a value with markup in it. + */ +function reportStats(array $stats) { + $html = '
'; + foreach ($stats as $stat) { + $tag = !empty($stat['url']) ? 'a' : 'div'; + $href = !empty($stat['url']) ? ' href="' . escapeHtml($stat['url']) . '"' : ''; + $title = !empty($stat['title']) ? ' title="' . escapeHtml($stat['title']) . '"' : ''; + $tone = !empty($stat['tone']) ? ' text-' . $stat['tone'] . '-emphasis' : ''; + $value = $stat['value_html'] ?? escapeHtml((string) ($stat['value'] ?? '')); + $html .= "<$tag class=\"itflow-report-stat\"$href$title>" + . '' . escapeHtml($stat['label']) . '' + . '' . $value . '' + . (isset($stat['sub']) && $stat['sub'] !== '' ? '' . $stat['sub'] . '' : '') + . ""; + } + return $html . '
'; +} + +/** + * A chart, drawn by js/reports.js. $config: + * 'type' bar | line | doughnut + * 'labels' the x axis (or the slices) + * 'series' [['label' => .., 'data' => [..], 'tone' => accent | success | danger | + * warning | info | muted | purple | #hex, 'type' => line (on a bar + * chart), 'dashed' => true, 'stack' => .., 'axis' => y2, 'ghost' => true, + * 'tones' => [a tone per bar, in place of 'tone']], ..] + * 'format' money | count | hours | percent | decimal - the axis and tooltips + * 'format2' the same, for a second axis + * 'stacked' true to stack the bars + * 'horizontal' true for bars running left to right + * 'legend' false to hide it + * 'colors' a colour (tone or #hex) per slice, for a doughnut + * 'max' the top of the value axis + * $size: '' | sm | lg | donut. A horizontal chart grows with its rows. + */ +function reportChart(array $config, $size = '', $label = '') { + global $session_company_currency; + $config['currency'] = $config['currency'] ?? $session_company_currency; + $style = ''; + if (!empty($config['horizontal'])) { + $style = ' style="height: ' . max(140, count($config['labels'] ?? []) * 30 + 50) . 'px"'; + } + $class = 'itflow-report-chart' . ($size !== '' ? " itflow-report-chart-$size" : ''); + return '
'; +} + +/** One row of a doughnut chart's legend list: swatch, label, value and share. */ +function reportLegendHtml(array $labels, array $values, array $colors, $format = 'money') { + $total = array_sum($values); + $html = '
    '; + foreach ($labels as $i => $label) { + $value = $values[$i] ?? 0; + $shown = $format === 'money' ? reportMoney($value) : ($format === 'hours' ? reportHours($value * 3600) . ' h' : reportCount($value)); + $html .= '
  • ' + . '' . escapeHtml($label) . '' + . '' . $shown . '' + . '' . reportPercent(reportShare($value, $total)) . '
  • '; + } + return $html . '
'; +} + +/** + * Turn rows into "top $n and the rest as Other" - for doughnuts and short + * lists. Each row is ['label' => .., 'value' => .., 'color' => ..]. + */ +function reportTopN(array $rows, $n = 6, $other_label = 'Other') { + usort($rows, function ($a, $b) { + return $b['value'] <=> $a['value']; + }); + $rows = array_values(array_filter($rows, function ($r) { + return $r['value'] > 0; + })); + if (count($rows) <= $n) { + return $rows; + } + $top = array_slice($rows, 0, $n - 1); + $rest = array_sum(array_column(array_slice($rows, $n - 1), 'value')); + $top[] = ['label' => $other_label, 'value' => $rest, 'color' => 'muted']; + return $top; +} + +/** The tones a series of slices cycles through. */ +function reportPalette($i) { + $tones = ['accent', 'info', 'success', 'warning', 'purple', 'danger', 'teal', 'orange', 'indigo', 'pink']; + return $tones[$i % count($tones)]; +} + +/** A category's own colour when it has a usable one, else a palette tone. */ +function reportCategoryColor($color, $i) { + $color = trim((string) $color); + return preg_match('/^#[0-9a-f]{6}$/i', $color) ? $color : reportPalette($i); +} + +/* + * ---------- tables ---------- + * + * $columns, keyed by the field each reads from a row: + * 'label' the heading + * 'type' text | money | count | hours (seconds) | decimal | percent | date | duration (seconds) + * 'html' function ($row) returning the cell's HTML, instead of the plain value + * 'csv' false to leave it out of the export, or function ($row) for the value + * 'csv_label' the export heading, when it should differ from the label + * 'screen' false to keep it for the export only (when another cell already shows it) + * 'class' classes for the cell + * 'sort' false to make the heading not sortable + * 'title' a tooltip on the heading + * Rows are plain arrays of raw values; 'totals' (same keys) goes in the footer. + * A row ['_heading' => 'Label'] is a quiet heading over the rows after it (left out + * of the export) - for tables that are not sortable; '_class' adds classes to a row. + */ + +function reportColumnIsNumber(array $column) { + return in_array($column['type'] ?? 'text', ['money', 'count', 'hours', 'decimal', 'percent', 'duration'], true); +} + +/** A cell's value as text - for the table, when there is no 'html'. */ +function reportCellText(array $column, $value) { + if ($value === null || $value === '') { + return '-'; + } + switch ($column['type'] ?? 'text') { + case 'money': + return reportMoney($value); + case 'count': + return reportCount($value); + case 'hours': + return reportHours($value, $column['decimals'] ?? 1); + case 'decimal': + return number_format(floatval($value), $column['decimals'] ?? 1); + case 'percent': + return reportPercent($value); + case 'duration': + return reportDuration($value); + case 'date': + return date('M j, Y', strtotime($value)); + } + return (string) $value; +} + +/** A cell's value for the CSV - numbers bare, so a spreadsheet can add them up. */ +function reportCsvValue(array $column, $row, $key) { + if (isset($column['csv']) && is_callable($column['csv'])) { + return (string) $column['csv']($row); + } + $value = $row[$key] ?? ''; + if ($value === null || $value === '') { + return ''; + } + switch ($column['type'] ?? 'text') { + case 'money': + return number_format(floatval($value), 2, '.', ''); + case 'hours': + case 'duration': + return number_format(floatval($value) / 3600, 2, '.', ''); + case 'decimal': + return number_format(floatval($value), $column['decimals'] ?? 1, '.', ''); + case 'percent': + return (string) round(floatval($value), 1); + case 'count': + return (string) intval($value); + } + return trim(html_entity_decode(strip_tags((string) $value), ENT_QUOTES, 'UTF-8')); +} + +function reportTable(array $columns, array $rows, array $options = []) { + $columns = array_filter($columns, function ($column) { + return ($column['screen'] ?? true) !== false; + }); + $sortable = $options['sortable'] ?? true; + // A long list shows its first rows; the CSV always has them all + $all = count($rows); + $limit = intval($options['limit'] ?? 0); + if ($limit && $all > $limit) { + $rows = array_slice($rows, 0, $limit); + } + $html = '
'; + + $html .= ''; + foreach ($columns as $key => $column) { + $number = reportColumnIsNumber($column); + $attrs = ($number ? ' class="text-end"' : ''); + if ($sortable && ($column['sort'] ?? true)) { + $attrs .= ' data-sort="' . ($number || ($column['type'] ?? '') === 'date' ? 'num' : 'text') . '"'; + } + if (!empty($column['title'])) { + $attrs .= ' title="' . escapeHtml($column['title']) . '"'; + } + $html .= "" . escapeHtml($column['label']) . ''; + } + $html .= ''; + + if (!$rows) { + $html .= ''; + } + + foreach ($rows as $row) { + if (isset($row['_heading'])) { + // A quiet heading over the rows that follow - for an unsorted table + $html .= ''; + continue; + } + $html .= ''; + foreach ($columns as $key => $column) { + $value = $row[$key] ?? null; + $number = reportColumnIsNumber($column); + $classes = trim(($number ? 'text-end text-nowrap ' : '') . ($column['class'] ?? '')); + $sort_value = ''; + if ($sortable && ($column['sort'] ?? true)) { + if (($column['type'] ?? '') === 'date') { + $sort_value = ' data-value="' . ($value ? strtotime($value) : 0) . '"'; + } elseif ($number) { + $sort_value = ' data-value="' . ($value === null || $value === '' ? '' : floatval($value)) . '"'; + } elseif (isset($column['html'])) { + $sort_value = ' data-value="' . escapeHtml(mb_strtolower(trim(html_entity_decode(strip_tags((string) $value), ENT_QUOTES, 'UTF-8')))) . '"'; + } + } + $cell = isset($column['html']) ? $column['html']($row) : escapeHtml(reportCellText($column, $value)); + $html .= '' . $cell . ''; + } + $html .= ''; + } + if ($limit && $all > $limit) { + $html .= ''; + } + $html .= ''; + + if (!empty($options['totals']) && $rows) { + $html .= ''; + $first = true; + foreach ($columns as $key => $column) { + $number = reportColumnIsNumber($column); + if ($first) { + $html .= ''; + $first = false; + continue; + } + $value = $options['totals'][$key] ?? null; + $cell = isset($options['totals_html'][$key]) ? $options['totals_html'][$key] : ($value === null ? '' : escapeHtml(reportCellText($column, $value))); + $html .= ''; + } + $html .= ''; + } + + return $html . '
' + . ($options['empty'] ?? 'Nothing to show for this period.') . '
' . escapeHtml($row['_heading']) . '
Showing the first ' . reportCount($limit) . ' of ' . reportCount($all) + . ' - export them all
' . escapeHtml($options['totals'][$key] ?? 'Total') . '' . $cell . '
'; +} + +/* + * ---------- export ---------- + */ + +/** Is this a request for the CSV (?export=csv)? $table names one of several tables on the page. */ +function reportExporting($table = null) { + if (($_GET['export'] ?? '') !== 'csv') { + return false; + } + return $table === null || ($_GET['table'] ?? '') === $table; +} + +/** Send rows as a CSV file and stop. Numbers go out bare; text is guarded against formulas. */ +function reportCsv($name, array $columns, array $rows, array $totals = null) { + global $session_name; + + $columns = array_filter($columns, function ($column) { + return ($column['csv'] ?? true) !== false; + }); + + $out = fopen('php://memory', 'w'); + fputcsv($out, array_map(function ($column) { + if (isset($column['csv_label'])) { + return $column['csv_label']; + } + // Times go out as decimal hours and shares as bare numbers - say so in the heading + $label = $column['label']; + $type = $column['type'] ?? 'text'; + if (in_array($type, ['hours', 'duration'], true) && stripos($label, 'hour') === false) { + return "$label (hours)"; + } + if ($type === 'percent' && strpos($label, '%') === false) { + return "$label %"; + } + return $label; + }, array_values($columns)), ',', '"', '\\'); + foreach ($rows as $row) { + if (isset($row['_heading'])) { + continue; + } + $values = []; + foreach ($columns as $key => $column) { + $values[] = escapeCsvFormula(reportCsvValue($column, $row, $key)); + } + fputcsv($out, $values, ',', '"', '\\'); + } + if ($totals) { + $values = []; + foreach ($columns as $key => $column) { + $values[] = escapeCsvFormula(array_key_exists($key, $totals) ? reportCsvValue($column, $totals, $key) : ''); + } + fputcsv($out, $values, ',', '"', '\\'); + } + + logAudit('Report', 'Export', escapeSql("$session_name exported the $name report")); + + fseek($out, 0); + header('Content-Type: text/csv; charset=utf-8'); + header('Content-Disposition: attachment; filename="' . sanitizeFilename($name . '-' . date('Y-m-d') . '.csv') . '"'); + fpassthru($out); + fclose($out); + exit; +} + +/** This page's URL with some query values changed (null drops one). */ +function reportUrl(array $changes = []) { + $params = $_GET; + foreach ($changes as $name => $value) { + if ($value === null) { + unset($params[$name]); + } else { + $params[$name] = $value; + } + } + $query = http_build_query($params); + return basename($_SERVER['PHP_SELF']) . ($query !== '' ? "?$query" : ''); +} + +/* + * ---------- the page header ---------- + */ + +/** The period picker - the presets, the years given, and From / To for custom dates. */ +function reportPeriodControl($period, array $options = []) { + $allowed = $options['periods'] ?? array_keys(REPORT_PERIODS); + $years = $options['years'] ?? []; + $custom = $period['key'] === 'custom'; + + $html = '
' + . '' + . '
'; + + if (in_array('custom', $allowed, true)) { + $html .= '
' + . 'From' + . '' + . 'to' + . '' + . '' + . '
'; + } + return $html; +} + +/** A year picker, for the reports laid out as a year of months. */ +function reportYearControl($year, array $years) { + $html = '
' + . '' + . '
'; +} + +/** The client picker - every client this user may see, or one. */ +function reportClientControl($client_id, $all_label = 'All clients', $required = false) { + global $mysqli; + $client_id = intval($client_id); + $sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients + WHERE (client_archived_at IS NULL OR client_id = $client_id) " . clientScopeSql('client_id') . " + ORDER BY client_name ASC"); + $html = '
'; +} + +/** The agent picker - active agents, and whoever is picked. */ +function reportAgentControl($user_id, $all_label = 'All agents') { + global $mysqli; + $user_id = intval($user_id); + $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 = $user_id) + ORDER BY user_name ASC"); + $html = '
'; +} + +/** A plain select that submits when changed - $choices value => label. */ +function reportSelectControl($name, $value, array $choices, $icon = '', $label = '', $col = 'col-sm-6 col-lg-auto') { + $html = '
'; + if ($icon !== '') { + $html .= ''; + } elseif ($label !== '') { + $html .= '' . escapeHtml($label) . ''; + } + $html .= '
'; +} + +/** A switch that submits when flipped. */ +function reportSwitchControl($name, $on, $label, $col = 'col-auto') { + $id = 'reportSwitch' . preg_replace('/[^a-z0-9]/i', '', $name); + return '
' + . '' + . '
'; +} + +/** Segmented choice (Monthly / Quarterly) as links that keep the other filters. */ +function reportSegmentControl($name, $value, array $choices, $col = 'col-auto') { + $html = '
'; + foreach ($choices as $key => $text) { + $active = (string) $key === (string) $value; + $html .= '' . escapeHtml($text) . ''; + } + return $html . '
'; +} + +/** + * The top of every report: its name and the dates it covers, Export and + * Print, the filters, and one line on what it shows. $options: + * 'period' the reportPeriod() in use - draws the period picker + * 'periods' the period keys to offer (default all); 'years' years to add + * 'year' [year, years] - a year picker instead, for the year-of-months reports + * 'client' the client picked, to draw the client picker (null: none) + * 'agent' the agent picked, to draw the agent picker (null: none) + * 'controls' more filter controls, HTML, in the same form + * 'subtitle' what shows beside the name (default: the dates) + * 'export' false for no CSV; or [table => label] for a choice of tables + * 'client_required' the client picker asks for a client rather than offering all + * 'note' replaces the description line + * 'actions' more buttons beside Export and Print, HTML + * 'keep' [name => value] hidden inputs, so the filters keep them + * 'print_meta' a line added to the printed header (such as the client) + */ +function reportHeader($key, array $options = []) { + global $session_company_name, $session_name; + + $report = reportFind($key); + $period = $options['period'] ?? null; + $subtitle = $options['subtitle'] ?? ($period ? $period['range'] : (isset($options['year']) ? (string) $options['year'][0] : '')); + + $export = $options['export'] ?? true; + $export_html = ''; + if ($export === true) { + $export_html = 'Export'; + } elseif (is_array($export) && $export) { + $export_html = ''; + } + + $controls = ''; + if ($period) { + $controls .= reportPeriodControl($period, $options); + } + if (isset($options['year'])) { + $controls .= reportYearControl($options['year'][0], $options['year'][1]); + } + if (array_key_exists('client', $options) && $options['client'] !== null) { + $controls .= reportClientControl($options['client'], 'All clients', !empty($options['client_required'])); + } + if (array_key_exists('agent', $options) && $options['agent'] !== null) { + $controls .= reportAgentControl($options['agent']); + } + $controls .= $options['controls'] ?? ''; + + ?> +
+
+

+ + +

+
+ + + +
+
+ +
+
+ $value) { ?> + + + +
+

+
+ +
+

+
+ +
+ + · + · Printed by +
+
+ '. */ +function reportSectionOpen($title, $meta = '', $class = '') { + return '
' + . '

' . escapeHtml($title) . '

' + . ($meta !== '' ? '' . $meta . '' : '') + . '
'; +} + +/** An empty state - an icon and a sentence. */ +function reportEmpty($text, $icon = 'fa-check-circle', $tone = 'success') { + return '
' . $text . '
'; +} + +/* + * ---------- links into the app ---------- + * + * Reports live a folder down from the rest of the agent pages, so every link + * out is absolute. + */ + +function reportClientLink($client_id, $client_name, $page = 'client_overview.php') { + $client_id = intval($client_id); + if (!$client_id) { + return 'No client'; + } + return '' . escapeHtml($client_name) . ''; +} + +/** A client's initials tile and name, linking to it. */ +function reportClientCell($client_id, $client_name, $client_abbreviation = '', $page = 'client_overview.php') { + $client_id = intval($client_id); + if (!$client_id) { + return 'No client'; + } + $tone = clientInitialsTone($client_id); + $initials = escapeHtml(clientInitials((string) $client_abbreviation, (string) $client_name)); + return '' + . '' . $initials . '' + . '' . escapeHtml($client_name) . ''; +} + +/** A ticket's reference and subject, opening the ticket. */ +function reportTicketLink($row, $with_subject = true) { + $url = '/agent/' . ticketUrl($row['ticket_id'], $row['ticket_client_id'] ?? 0); + $html = '' . escapeHtml(ticketReference($row)) . ''; + if ($with_subject && isset($row['ticket_subject'])) { + $html .= ' ' . escapeHtml($row['ticket_subject']) . ''; + } + return $html; +} + +/** An agent's avatar and name. */ +function reportAgentCell($user_id, $user_name, $user_avatar = '', $none = 'Unassigned') { + return formatAssignee($user_id, $user_name, $user_avatar, false, $none); +} + +/** A ticket priority's coloured dot, as on the dashboard. */ +function reportPriorityDot($priority) { + $colors = ['Urgent' => 'dark', 'High' => 'danger', 'Medium' => 'warning', 'Low' => 'info']; + return ''; +} + +/* + * ---------- money by category ---------- + */ + +/** Rows of cat / m / v as [category id => ['total' => .., 'months' => [1 .. 12 => ..]]]. */ +function reportCategoryGrid($result) { + $grid = []; + while ($row = mysqli_fetch_assoc($result)) { + $cat = intval($row['cat']); + $month = intval($row['m']); + if (!isset($grid[$cat])) { + $grid[$cat] = ['total' => 0.0, 'months' => array_fill(1, 12, 0.0)]; + } + $grid[$cat]['months'][$month] += floatval($row['v']); + $grid[$cat]['total'] += floatval($row['v']); + } + return $grid; +} + +/** + * Income between two dates by income category and month (pass dates inside + * one year - months are by number). A payment takes the category of the + * invoice it paid; 0 is income with no category to show. + */ +function reportIncomeByCategory($from, $to, $client_id = 0) { + global $mysqli; + $client_id = intval($client_id); + $payment_client = $client_id ? " AND invoice_client_id = $client_id" : ''; + $revenue_client = $client_id ? " AND revenue_client_id = $client_id" : ''; + return reportCategoryGrid(mysqli_query($mysqli, " + SELECT cat, m, SUM(v) AS v FROM ( + SELECT COALESCE(invoice_category_id, 0) AS cat, MONTH(payment_date) AS m, payment_amount AS v + FROM payments LEFT JOIN invoices ON payment_invoice_id = invoice_id + WHERE payment_date >= '$from' AND payment_date < '$to' + INTERVAL 1 DAY $payment_client + UNION ALL + SELECT revenue_category_id, MONTH(revenue_date), revenue_amount + FROM revenues + WHERE " . dashboardRevenueSql() . " AND revenue_date >= '$from' AND revenue_date < '$to' + INTERVAL 1 DAY $revenue_client + ) AS income + GROUP BY cat, m")); +} + +/** Spending between two dates by expense category and month - vendor expenses, as the Expenses list. */ +function reportExpensesByCategory($from, $to) { + global $mysqli; + return reportCategoryGrid(mysqli_query($mysqli, " + SELECT expense_category_id AS cat, MONTH(expense_date) AS m, SUM(expense_amount) AS v + FROM expenses + WHERE expense_vendor_id > 0 AND expense_date >= '$from' AND expense_date < '$to' + INTERVAL 1 DAY + GROUP BY cat, m")); +} + +/** + * The categories of $type to list - every one not archived, and any archived + * one with an amount in $grid - [id => row], by name. Amounts filed under an + * id that is not one of these (deleted, or another type) move to 0, which + * lists as "No category". + */ +function reportCategoryRows($type, array &$grid) { + global $mysqli; + $type = escapeSql($type); + $ids = array_map('intval', array_keys($grid)); + $with = $ids ? ' OR category_id IN (' . implode(',', $ids) . ')' : ''; + $sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_archived_at FROM categories + WHERE category_type = '$type' AND (category_archived_at IS NULL $with) + ORDER BY category_name ASC"); + $rows = []; + while ($row = mysqli_fetch_assoc($sql)) { + $rows[intval($row['category_id'])] = $row; + } + foreach (array_keys($grid) as $cat) { + if ($cat !== 0 && !isset($rows[$cat])) { + if (!isset($grid[0])) { + $grid[0] = ['total' => 0.0, 'months' => array_fill(1, 12, 0.0)]; + } + foreach ($grid[$cat]['months'] as $m => $v) { + $grid[0]['months'][$m] += $v; + } + $grid[0]['total'] += $grid[$cat]['total']; + unset($grid[$cat]); + } + } + if (isset($grid[0]) && abs($grid[0]['total']) > 0.004) { + $rows[0] = ['category_id' => 0, 'category_name' => 'No category', 'category_color' => '', 'category_archived_at' => null]; + } + return $rows; +} + +/** A category's amounts for a year - zeros when it has none. */ +function reportGridRow(array $grid, $cat) { + return $grid[$cat] ?? ['total' => 0.0, 'months' => array_fill(1, 12, 0.0)]; +} + +/** Every category added together, month by month. */ +function reportGridTotals(array $grid) { + $months = array_fill(1, 12, 0.0); + $total = 0.0; + foreach ($grid as $row) { + foreach ($row['months'] as $m => $v) { + $months[$m] += $v; + } + $total += $row['total']; + } + return ['total' => $total, 'months' => $months]; +} + +/** The months or quarters a year-of-months report shows: [index => [label, first month, last month]]. */ +function reportYearColumns($view) { + if ($view === 'quarter') { + return [1 => ['Q1', 1, 3], 2 => ['Q2', 4, 6], 3 => ['Q3', 7, 9], 4 => ['Q4', 10, 12]]; + } + $columns = []; + for ($m = 1; $m <= 12; $m++) { + $columns[$m] = [date('M', mktime(0, 0, 0, $m, 1)), $m, $m]; + } + return $columns; +} + +/** One category's amounts summed into the report's columns. */ +function reportSumColumns(array $months, array $columns) { + $out = []; + foreach ($columns as $i => [$label, $first, $last]) { + $sum = 0.0; + for ($m = $first; $m <= $last; $m++) { + $sum += $months[$m] ?? 0; + } + $out[$i] = $sum; + } + return $out; +} + +/** An amount in a year-of-months grid - a dash for nothing, a link to the list behind it when given. */ +function reportGridAmount($amount, $url = '') { + if (abs($amount) < 0.005) { + return '–'; + } + $text = reportMoneyWhole($amount); + return $url !== '' ? '' . $text . '' : $text; +} + +/** The first and last day of a column of a year-of-months report. */ +function reportColumnDates($year, $first, $last) { + $from = sprintf('%d-%02d-01', $year, $first); + return [$from, date('Y-m-t', strtotime(sprintf('%d-%02d-01', $year, $last)))]; +} + +/** Drop the categories with nothing in $grid (or in $also, the year before). */ +function reportCategoriesWithAmounts(array $categories, array $grid, array $also = []) { + return array_filter($categories, function ($cat) use ($grid, $also) { + return abs($grid[$cat]['total'] ?? 0) >= 0.005 || abs($also[$cat]['total'] ?? 0) >= 0.005; + }, ARRAY_FILTER_USE_KEY); +} + +/** + * Stacked monthly bars for the biggest categories (the rest as Other), for + * the Income and Expenses reports. Months not yet reached are left empty. + */ +function reportCategoryChartSeries(array $categories, array $grid, $months_shown, $top = 5) { + $ranked = []; + foreach ($categories as $cat => $category) { + $ranked[$cat] = $grid[$cat]['total'] ?? 0; + } + arsort($ranked); + $series = []; + $other = array_fill(1, 12, 0.0); + $i = 0; + foreach ($ranked as $cat => $total) { + if ($total <= 0) { + continue; + } + $months = $grid[$cat]['months']; + if ($i < $top) { + $data = []; + for ($m = 1; $m <= 12; $m++) { + $data[] = $m <= $months_shown ? round($months[$m], 2) : null; + } + $series[] = ['label' => html_entity_decode($categories[$cat]['category_name'], ENT_QUOTES, 'UTF-8'), 'data' => $data, 'tone' => reportPalette($i), 'stack' => 'year']; + } else { + foreach ($months as $m => $v) { + $other[$m] += $v; + } + } + $i++; + } + if (array_sum($other) > 0) { + $data = []; + for ($m = 1; $m <= 12; $m++) { + $data[] = $m <= $months_shown ? round($other[$m], 2) : null; + } + $series[] = ['label' => 'Other', 'data' => $data, 'tone' => 'faint', 'stack' => 'year']; + } + return $series; +} + +/** + * A year of a category grid as a table - a row per category with each month, + * the year and its share, a totals row, and each amount opening the list it + * came from ($list: income.php or expenses.php). + */ +function reportCategoryYearTable(array $categories, array $grid, $year, $list, $total_label) { + $columns = reportYearColumns('month'); + $totals = reportGridTotals($grid); + $html = '
' + . ''; + foreach ($columns as [$label]) { + $html .= ''; + } + $html .= ''; + if (!$categories) { + $html .= ''; + } + foreach ($categories as $cat => $category) { + $row = reportGridRow($grid, $cat); + $html .= ''; + foreach ($columns as $i => [$label, $first, $last]) { + [$dtf, $dtt] = reportColumnDates($year, $first, $last); + $url = $cat ? "/agent/$list?category=$cat&canned_date=custom&dtf=$dtf&dtt=$dtt" : ''; + $html .= ''; + } + $url = $cat ? "/agent/$list?category=$cat&canned_date=custom&dtf=$year-01-01&dtt=$year-12-31" : ''; + $share = reportShare($row['total'], $totals['total'], 1); + $html .= '' + . ''; + } + $html .= ''; + foreach ($columns as $i => [$label, $first, $last]) { + [$dtf, $dtt] = reportColumnDates($year, $first, $last); + $html .= ''; + } + $html .= '
Category' . $label . '' . intval($year) . 'Share
Nothing in ' . intval($year) . '.
' . escapeHtml($category['category_name']) + . (!empty($category['category_archived_at']) ? ' Archived' : '') . '' . reportGridAmount($row['months'][$i], $url) . '' . reportGridAmount($row['total'], $url) . '' . reportPercent($share) . '
' . escapeHtml($total_label) . '' . reportGridAmount($totals['months'][$i], "/agent/$list?canned_date=custom&dtf=$dtf&dtt=$dtt") . '' . reportGridAmount($totals['total'], "/agent/$list?canned_date=custom&dtf=$year-01-01&dtt=$year-12-31") . '' . ($totals['total'] ? '100%' : '') . '
'; + return $html; +} + +/** The same grid as CSV rows: category, each month, the year. */ +function reportCategoryYearCsv(array $categories, array $grid, $year, $name, $total_label) { + $columns = ['name' => ['label' => 'Category']]; + foreach (reportYearColumns('month') as $i => [$label]) { + $columns["m$i"] = ['label' => $label, 'type' => 'money']; + } + $columns['total'] = ['label' => (string) $year, 'type' => 'money']; + $rows = []; + foreach ($categories as $cat => $category) { + $line = reportGridRow($grid, $cat); + $row = ['name' => $category['category_name'], 'total' => $line['total']]; + foreach ($line['months'] as $m => $v) { + $row["m$m"] = $v; + } + $rows[] = $row; + } + $totals = reportGridTotals($grid); + $total_row = ['name' => $total_label, 'total' => $totals['total']]; + foreach ($totals['months'] as $m => $v) { + $total_row["m$m"] = $v; + } + reportCsv($name, $columns, $rows, $total_row); +} + +/* + * ---------- tickets ---------- + */ + +/** SQL on tickets for the filters: archived left out, the clients this user may see, and the client and agent picked. */ +function reportTicketSql($client_id = 0, $agent_id = 0) { + $agent_id = intval($agent_id); + return "tickets.ticket_archived_at IS NULL" . reportClientSql('tickets.ticket_client_id', $client_id) + . ($agent_id ? " AND tickets.ticket_assigned_to = $agent_id" : ''); +} + +/** The middle value - half are above it - or null for none. Steadier than an average when a few tickets sat open for weeks. */ +function reportMedian(array $values) { + $values = array_values(array_filter($values, function ($v) { + return $v !== null; + })); + $count = count($values); + if (!$count) { + return null; + } + sort($values); + $mid = intdiv($count, 2); + return $count % 2 ? $values[$mid] : ($values[$mid - 1] + $values[$mid]) / 2; +} + +/** A column of numbers from a query - for medians. */ +function reportColumn($sql) { + global $mysqli; + $values = []; + $result = mysqli_query($mysqli, $sql); + while ($row = mysqli_fetch_row($result)) { + if ($row[0] !== null) { + $values[] = floatval($row[0]); + } + } + return $values; +} + +/** Ticket categories by id - every one, archived included, as old tickets carry them. */ +function reportTicketCategories() { + global $mysqli; + $categories = []; + $sql = mysqli_query($mysqli, "SELECT category_id, category_name FROM categories WHERE category_type = 'Ticket'"); + while ($row = mysqli_fetch_assoc($sql)) { + $categories[intval($row['category_id'])] = $row['category_name']; + } + return $categories; +} + +/** How long open tickets have been open - the buckets the aging report counts in, with the most days each takes. */ +const REPORT_AGE_BUCKETS = [ + 'day' => ['Under a day', 0], + '3' => ['1–3 days', 3], + '7' => ['4–7 days', 7], + '30' => ['8–30 days', 30], + '90' => ['31–90 days', 90], + 'old' => ['Over 90 days', null], +]; + +/** The bucket for a ticket open $days days. */ +function reportAgeBucket($days) { + if ($days < 1) { + return 'day'; + } + foreach (REPORT_AGE_BUCKETS as $key => [$label, $max]) { + if ($max !== null && $max > 0 && $days <= $max) { + return $key; + } + } + return 'old'; +} + +/** + * How tickets with an SLA did, from a WHERE on tickets: how many, and met / + * missed / still open for the response and the resolution targets. The + * percentages count only tickets whose target has been judged - one still + * waiting is neither a hit nor a miss. + */ +function reportSlaCompliance($where) { + global $mysqli; + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT + COUNT(ticket_id) AS tickets, + 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, + 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 AND $where")); + return reportSlaFigures($row); +} + +/** The percentages for a row of met / missed counts (as reportSlaCompliance() selects them). */ +function reportSlaFigures($row) { + $out = []; + foreach (['tickets', 'response_met', 'response_missed', 'resolution_met', 'resolution_missed', 'resolution_pending'] as $key) { + $out[$key] = intval($row[$key] ?? 0); + } + $out['response_percent'] = reportShare($out['response_met'], $out['response_met'] + $out['response_missed'], 1); + $out['resolution_percent'] = reportShare($out['resolution_met'], $out['resolution_met'] + $out['resolution_missed'], 1); + return $out; +} + +/** " · 3 late" after an SLA share, or nothing when none were late. */ +function reportLateHtml($late) { + $late = intval($late); + return $late ? ' · ' . reportCount($late) . ' late' : ''; +} + +/** The SELECT list reportSlaFigures() reads - for grouped queries. */ +const REPORT_SLA_COLUMNS = "COUNT(ticket_id) AS tickets, + 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, + SUM(ticket_resolution_sla_met IS NULL AND ticket_resolution_due_at IS NOT NULL) AS resolution_pending"; + +/** + * Working days between two dates (up to today): the business days set in + * Admin > SLA, less closure days. Monday to Friday when none are set. + */ +function reportWorkingDays($start, $end) { + $end = min($end, date('Y-m-d')); + $settings = getSlaSettings(); + $days = $settings['business_days'] ?: [1, 2, 3, 4, 5]; + $holidays = getBusinessHolidays(); + $count = 0; + $cursor = new DateTime($start); + $last = new DateTime($end); + for ($guard = 0; $cursor <= $last && $guard < 4000; $guard++) { + if (in_array(intval($cursor->format('N')), $days, true) && !isset($holidays[$cursor->format('Y-m-d')])) { + $count++; + } + $cursor->modify('+1 day'); + } + return $count; +} + +/** Hours in a working day, from the business hours set for SLAs - 8 when they are not set. */ +function reportWorkdayHours() { + $settings = getSlaSettings(); + $start = strtotime('1970-01-01 ' . ($settings['business_hours_start'] ?: '00:00:00') . ' UTC'); + $end = strtotime('1970-01-01 ' . ($settings['business_hours_end'] ?: '00:00:00') . ' UTC'); + $hours = ($end - $start) / 3600; + return $hours > 0 && $hours <= 24 ? round($hours, 2) : 8.0; +} + +/** + * When tickets come in - a weekday by hour grid, darker for more. $counts + * is [ISO weekday 1-7][hour 0-23] => count. + */ +function reportHeatmap(array $counts, $noun = 'ticket') { + $max = 1; + foreach ($counts as $hours) { + $max = max($max, ...array_values($hours ?: [0])); + } + $html = '
'; + for ($h = 0; $h < 24; $h++) { + $html .= ''; + } + $html .= ''; + for ($d = 1; $d <= 7; $d++) { + $day = date('D', strtotime("Monday this week +" . ($d - 1) . " days")); + $html .= ''; + for ($h = 0; $h < 24; $h++) { + $n = intval($counts[$d][$h] ?? 0); + $html .= ''; + } + $html .= ''; + } + return $html . '
' . ($h % 3 === 0 ? date('ga', mktime($h, 0, 0)) : '') . '
' . $day . '
'; +} + +/* + * ---------- assets, renewals and documentation ---------- + */ + +/** Statuses that mean the asset is gone - left out of lifecycle figures. */ +const REPORT_ASSET_GONE = ['Lost', 'Stolen', 'Retired']; + +/** + * Operating systems past their maker's end of support, as [pattern, name], + * matched against an asset's OS. Only versions whose support has plainly + * ended (late 2026) - long-term-servicing editions are left alone. Add to it + * as more versions reach the end. + */ +const REPORT_OS_END_OF_LIFE = [ + ['/\bwindows\s+(xp|vista)\b/i', 'Windows XP / Vista'], + ['/\bwindows\s+(7|8(\.1)?)\b/i', 'Windows 7 / 8'], + ['/\bwindows\s+10\b(?!.*\bltsc\b)/i', 'Windows 10'], + ['/\bserver\s+(2000|2003|2008|2012)\b/i', 'Windows Server 2012 or older'], + ['/\b(mac\s?os|os\s?x)\s*(x\s*)?(10\.\d+|11|12|13)\b/i', 'macOS 13 or older'], + ['/\bcentos\b(?!\s*stream\s*(9|10))/i', 'CentOS'], + ['/\bubuntu\b\D*(1\d|20)\.\d\d\b/i', 'Ubuntu 20.04 or older'], + ['/\bdebian\b\D*\b([6-9]|1[01])\b/i', 'Debian 11 or older'], +]; + +/** The end-of-support name for an asset's OS ('Windows 10'), or '' while it is supported or unknown. */ +function reportOsEndOfLife($os) { + $os = trim((string) $os); + if ($os === '') { + return ''; + } + foreach (REPORT_OS_END_OF_LIFE as [$pattern, $name]) { + if (preg_match($pattern, $os)) { + return $name; + } + } + return ''; +} + +/** + * Assets still in use (not archived, not lost, stolen or retired) at active + * clients, with what their lifecycle needs: 'age_days' from purchase (else + * install), 'warranty' (assetWarranty()) and 'os_eol' (reportOsEndOfLife()). + * A virtual machine has no hardware to age or cover, so neither is set. + */ +function reportLifecycleAssets($client_id = 0, $type = '') { + global $mysqli; + $gone = "'" . implode("', '", REPORT_ASSET_GONE) . "'"; + $type_sql = $type !== '' ? " AND asset_type = '" . escapeSql($type) . "'" : ''; + $rows = []; + $sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model, asset_os, asset_status, asset_purchase_date, asset_install_date, + asset_warranty_expire, asset_client_id, client_name, client_abbreviation, contact_name, location_name + FROM assets + JOIN clients ON asset_client_id = client_id + LEFT JOIN contacts ON asset_contact_id = contact_id + LEFT JOIN locations ON asset_location_id = location_id + WHERE asset_archived_at IS NULL AND client_archived_at IS NULL AND COALESCE(asset_status, '') NOT IN ($gone)" + . reportClientSql('asset_client_id', $client_id) . $type_sql . " + ORDER BY client_name, asset_name"); + $today = new DateTime('today'); + while ($row = mysqli_fetch_assoc($sql)) { + $physical = $row['asset_type'] !== 'Virtual Machine'; + $row['age_date'] = null; + $row['age_days'] = null; + foreach (['asset_purchase_date', 'asset_install_date'] as $column) { + $date = $physical ? DateTime::createFromFormat('!Y-m-d', substr((string) $row[$column], 0, 10)) : false; + if ($date && $date->format('Y') > 1900) { + $row['age_date'] = $date->format('Y-m-d'); + $row['age_days'] = max(0, (int) $date->diff($today)->format('%r%a')); + break; + } + } + $row['warranty'] = $physical ? assetWarranty($row['asset_warranty_expire']) : null; + $row['os_eol'] = reportOsEndOfLife($row['asset_os']); + $rows[] = $row; + } + return $rows; +} + +/** An asset's type tile and name, opening its page. */ +function reportAssetCell($row) { + return '' + . '' + . '' . escapeHtml($row['asset_name']) . ''; +} + +/** "3.4 yrs" from days, or '' without. */ +function reportYears($days, $decimals = 1) { + return $days === null ? '' : number_format($days / 365.25, $decimals) . ' yrs'; +} + +/** What comes up for renewal, and how each kind is shown. */ +const REPORT_RENEWAL_KINDS = [ + 'domain' => ['label' => 'Domains', 'one' => 'Domain', 'tone' => 'accent'], + 'certificate' => ['label' => 'Certificates', 'one' => 'Certificate', 'tone' => 'purple'], + 'license' => ['label' => 'Licenses', 'one' => 'License', 'tone' => 'teal'], + 'warranty' => ['label' => 'Warranties', 'one' => 'Warranty', 'tone' => 'orange'], +]; + +/** How far back a lapsed renewal still shows - older ones are on each list's Expired view. */ +const REPORT_RENEWAL_LAPSED_DAYS = 90; + +/** + * Domains, certificates, licenses and warranties due in the next $ahead days, + * or lapsed in the last REPORT_RENEWAL_LAPSED_DAYS, soonest first. Each row: + * kind, id, name, detail, client_id, client, abbr, date, days (negative once + * lapsed), auto (renews itself), url, tile. Archived items, archived clients + * and assets that are gone are left out. + */ +function reportRenewals($client_id, $ahead, array $kinds = []) { + global $mysqli; + $ahead = intval($ahead); + $back = REPORT_RENEWAL_LAPSED_DAYS; + $kinds = $kinds ?: array_keys(REPORT_RENEWAL_KINDS); + $window = function ($column) use ($ahead, $back) { + return "$column BETWEEN CURDATE() - INTERVAL $back DAY AND CURDATE() + INTERVAL $ahead DAY"; + }; + $today = new DateTime('today'); + $rows = []; + $add = function ($kind, $id, $name, $detail, $row, $date, $auto, $url, $tile) use (&$rows, $today) { + $due = DateTime::createFromFormat('!Y-m-d', substr((string) $date, 0, 10)); + if (!$due) { + return; + } + $rows[] = [ + 'kind' => $kind, 'id' => intval($id), 'name' => (string) $name, 'detail' => trim((string) $detail, " ·"), + 'client_id' => intval($row['client_id']), 'client' => $row['client_name'], 'abbr' => $row['client_abbreviation'], + 'date' => $due->format('Y-m-d'), 'days' => (int) $today->diff($due)->format('%r%a'), 'auto' => (bool) $auto, 'url' => $url, 'tile' => $tile, + ]; + }; + + if (in_array('domain', $kinds, true)) { + $sql = mysqli_query($mysqli, "SELECT domain_id, domain_name, domain_expire, domain_auto_renew, vendor_name, client_id, client_name, client_abbreviation + FROM domains JOIN clients ON domain_client_id = client_id LEFT JOIN vendors ON domain_registrar = vendor_id + WHERE domain_archived_at IS NULL AND client_archived_at IS NULL AND " . $window('domain_expire') . reportClientSql('domain_client_id', $client_id)); + while ($row = mysqli_fetch_assoc($sql)) { + $auto = intval($row['domain_auto_renew']) === 1; + $add('domain', $row['domain_id'], $row['domain_name'], ($auto ? 'Auto-renew' : 'Manual renewal') . ($row['vendor_name'] ? ' · ' . $row['vendor_name'] : ''), + $row, $row['domain_expire'], $auto, '/agent/domains.php?client_id=' . intval($row['client_id']) . '&open=' . intval($row['domain_id']), domainTile('sm')); + } + } + if (in_array('certificate', $kinds, true)) { + $sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_issued_by, certificate_issued_at, certificate_expire, client_id, client_name, client_abbreviation + FROM certificates JOIN clients ON certificate_client_id = client_id + WHERE certificate_archived_at IS NULL AND client_archived_at IS NULL AND " . $window('certificate_expire') . reportClientSql('certificate_client_id', $client_id)); + while ($row = mysqli_fetch_assoc($sql)) { + $auto = certificateShortLived($row); + $add('certificate', $row['certificate_id'], $row['certificate_name'], ($auto ? 'Short-lived, renews itself' : 'Manual renewal') . ($row['certificate_issued_by'] ? ' · ' . $row['certificate_issued_by'] : ''), + $row, $row['certificate_expire'], $auto, '/agent/certificates.php?client_id=' . intval($row['client_id']) . '&open=' . intval($row['certificate_id']), certificateTile('sm')); + } + } + if (in_array('license', $kinds, true)) { + $sql = mysqli_query($mysqli, "SELECT software_id, software_name, software_version, software_type, software_license_type, software_seats, software_expire, vendor_name, client_id, client_name, client_abbreviation + FROM software JOIN clients ON software_client_id = client_id LEFT JOIN vendors ON software_vendor_id = vendor_id + WHERE software_archived_at IS NULL AND client_archived_at IS NULL AND " . $window('software_expire') . reportClientSql('software_client_id', $client_id)); + while ($row = mysqli_fetch_assoc($sql)) { + $seats = intval($row['software_seats']); + $add('license', $row['software_id'], trim($row['software_name'] . ' ' . $row['software_version']), + implode(' · ', array_filter([$row['software_license_type'], $seats ? $seats . ' seat' . ($seats === 1 ? '' : 's') : '', $row['vendor_name']])), + $row, $row['software_expire'], false, '/agent/license.php?client_id=' . intval($row['client_id']) . '&software_id=' . intval($row['software_id']), softwareTile($row['software_type'], 'sm')); + } + } + if (in_array('warranty', $kinds, true)) { + $gone = "'" . implode("', '", REPORT_ASSET_GONE) . "'"; + $sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model, asset_warranty_expire, client_id, client_name, client_abbreviation + FROM assets JOIN clients ON asset_client_id = client_id + WHERE asset_archived_at IS NULL AND client_archived_at IS NULL AND asset_type != 'Virtual Machine' AND COALESCE(asset_status, '') NOT IN ($gone) + AND " . $window('asset_warranty_expire') . reportClientSql('asset_client_id', $client_id)); + while ($row = mysqli_fetch_assoc($sql)) { + $add('warranty', $row['asset_id'], $row['asset_name'], $row['asset_type'] . ' · ' . trim($row['asset_make'] . ' ' . $row['asset_model']), + $row, $row['asset_warranty_expire'], false, '/agent/asset.php?client_id=' . intval($row['client_id']) . '&asset_id=' . intval($row['asset_id']), + ''); + } + } + + usort($rows, function ($a, $b) { + return $a['days'] <=> $b['days'] ?: strcasecmp($a['client'], $b['client']) ?: strcasecmp($a['name'], $b['name']); + }); + return $rows; +} + +/** When a renewal falls due, as a soft pill - red lapsed or within a week, amber within 30 days, blue when it renews itself. */ +function reportDuePill($days, $auto = false) { + $days = intval($days); + if ($days < 0) { + $ago = -$days; + $tone = 'danger'; + $icon = 'fa-calendar-times'; + $text = 'Lapsed ' . ($ago === 1 ? 'yesterday' : "$ago days ago"); + } else { + $text = $days === 0 ? 'Today' : ($days === 1 ? 'Tomorrow' : ($days <= 60 ? "In $days days" : 'In ' . round($days / 30.4) . ' months')); + $tone = $auto ? 'info' : ($days <= 7 ? 'danger' : ($days <= 30 ? 'warning' : 'secondary')); + $icon = $auto ? 'fa-sync-alt' : ($days <= 30 ? 'fa-hourglass-half' : 'fa-calendar'); + } + return '' . $text . ''; +} + +/** Placed and owned pass when at least this share of assets has a location / an owner. */ +const REPORT_COVERAGE_SHARE = 80; + +/** + * What documentation coverage checks: each with its label, the client page + * to add it on and, where it needs one, a line on how it passes. Credentials + * only for agents who may see them. + */ +function reportCoverageChecks() { + $share = REPORT_COVERAGE_SHARE; + $checks = [ + 'primary_contact' => ['label' => 'Primary contact', 'page' => 'contacts.php'], + 'billing_contact' => ['label' => 'Billing contact', 'page' => 'contacts.php'], + 'primary_location' => ['label' => 'Primary location', 'page' => 'locations.php'], + 'assets' => ['label' => 'Assets', 'page' => 'assets.php'], + 'asset_locations' => ['label' => 'Assets placed', 'page' => 'assets.php', 'title' => "At least $share% of assets have a location"], + 'device_owners' => ['label' => 'Device owners', 'page' => 'assets.php', 'title' => "At least $share% of laptops, desktops, phones and tablets have a contact"], + 'networks' => ['label' => 'Networks', 'page' => 'networks.php'], + 'credentials' => ['label' => 'Credentials', 'page' => 'credentials.php'], + 'documents' => ['label' => 'Documents', 'page' => 'files.php'], + 'domains' => ['label' => 'Domains', 'page' => 'domains.php'], + 'services' => ['label' => 'Services', 'page' => 'services.php'], + 'licenses' => ['label' => 'Licenses', 'page' => 'software.php'], + ]; + if (reportPermission('module_credential') < 1) { + unset($checks['credentials']); + } + return $checks; +} + +/** + * Documentation coverage for active clients (or one), keyed by client id: + * the counts behind each check, 'checks' (true passes, false is missing, + * null does not apply - no user devices to give owners), 'missing', and + * 'score', the share of the checks that apply which pass. + */ +function reportCoverage($client_id = 0) { + global $mysqli; + $checks = reportCoverageChecks(); + $client_id = intval($client_id); + + $clients = []; + $sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL" . reportClientSql('client_id', $client_id) . " ORDER BY client_name"); + 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'], + 'contacts' => 0, 'primary' => 0, 'billing' => 0, 'locations' => 0, 'primary_loc' => 0, 'assets' => 0, 'placed' => 0, 'devices' => 0, 'owned' => 0, + 'networks' => 0, 'credentials' => 0, 'documents' => 0, 'domains' => 0, 'services' => 0, 'licenses' => 0]; + } + if (!$clients) { + return []; + } + $only = $client_id ? " = $client_id" : ' > 0'; + + $fill = function ($query, array $fields) use (&$clients, $mysqli) { + $sql = mysqli_query($mysqli, $query); + while ($row = mysqli_fetch_assoc($sql)) { + $id = intval($row['c']); + if (isset($clients[$id])) { + foreach ($fields as $field) { + $clients[$id][$field] = intval($row[$field]); + } + } + } + }; + $devices = "'" . implode("', '", SERVICE_USER_DEVICE_TYPES) . "'"; + $gone = "'" . implode("', '", REPORT_ASSET_GONE) . "'"; + $fill("SELECT contact_client_id AS c, COUNT(*) AS contacts, SUM(contact_primary = 1) AS `primary`, SUM(contact_billing = 1) AS billing + FROM contacts WHERE contact_archived_at IS NULL AND contact_client_id $only GROUP BY contact_client_id", ['contacts', 'primary', 'billing']); + $fill("SELECT location_client_id AS c, COUNT(*) AS locations, SUM(location_primary = 1) AS primary_loc + FROM locations WHERE location_archived_at IS NULL AND location_client_id $only GROUP BY location_client_id", ['locations', 'primary_loc']); + $fill("SELECT asset_client_id AS c, COUNT(*) AS assets, SUM(asset_location_id > 0) AS placed, + SUM(asset_type IN ($devices)) AS devices, SUM(asset_type IN ($devices) AND asset_contact_id > 0) AS owned + FROM assets WHERE asset_archived_at IS NULL AND COALESCE(asset_status, '') NOT IN ($gone) AND asset_client_id $only GROUP BY asset_client_id", ['assets', 'placed', 'devices', 'owned']); + foreach (['networks' => ['networks', 'network'], 'documents' => ['documents', 'document'], 'domains' => ['domains', 'domain'], 'services' => ['services', 'service'], + 'licenses' => ['software', 'software'], 'credentials' => ['credentials', 'credential']] as $field => [$table, $prefix]) { + if (isset($checks[$field])) { + $fill("SELECT {$prefix}_client_id AS c, COUNT(*) AS $field FROM $table WHERE {$prefix}_archived_at IS NULL AND {$prefix}_client_id $only GROUP BY {$prefix}_client_id", [$field]); + } + } + + foreach ($clients as &$client) { + $client['placed_share'] = $client['assets'] ? $client['placed'] / $client['assets'] * 100 : null; + $client['owned_share'] = $client['devices'] ? $client['owned'] / $client['devices'] * 100 : null; + $result = [ + 'primary_contact' => $client['primary'] > 0, + 'billing_contact' => $client['billing'] > 0, + 'primary_location' => $client['primary_loc'] > 0, + 'assets' => $client['assets'] > 0, + 'asset_locations' => $client['placed_share'] === null ? null : $client['placed_share'] >= REPORT_COVERAGE_SHARE, + 'device_owners' => $client['owned_share'] === null ? null : $client['owned_share'] >= REPORT_COVERAGE_SHARE, + 'networks' => $client['networks'] > 0, + 'credentials' => $client['credentials'] > 0, + 'documents' => $client['documents'] > 0, + 'domains' => $client['domains'] > 0, + 'services' => $client['services'] > 0, + 'licenses' => $client['licenses'] > 0, + ]; + $client['checks'] = array_intersect_key($result, $checks); + $applies = array_filter($client['checks'], function ($v) { return $v !== null; }); + $client['passed'] = count(array_filter($applies)); + $client['applies'] = count($applies); + $client['score'] = reportShare($client['passed'], $client['applies'], 0); + $client['missing'] = array_keys(array_filter($client['checks'], function ($v) { return $v === false; })); + } + unset($client); + return $clients; +} + +/** What a client is missing, as pills that open the page to add each on. */ +function reportCoverageMissingHtml($client) { + $checks = reportCoverageChecks(); + if (!$client['missing']) { + return 'Nothing'; + } + $html = ''; + foreach ($client['missing'] as $key) { + $html .= '' . escapeHtml($checks[$key]['label']) . ''; + } + return $html . ''; +} diff --git a/js/reports.js b/js/reports.js new file mode 100644 index 000000000..2f7f0b064 --- /dev/null +++ b/js/reports.js @@ -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 + * (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; + } + }); + } +})();