mirror of
https://github.com/itflow-org/itflow
synced 2026-11-21 03:47:25 +00:00
Rebuild dashboard: needs-attention rail, your day (tickets, schedule, time, team workload), finance with cash flow forecast, receivables aging and top clients
This commit is contained in:
1750
agent/dashboard.php
1750
agent/dashboard.php
File diff suppressed because it is too large
Load Diff
@@ -2014,3 +2014,323 @@ html {
|
||||
margin-top: .25rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Dashboard - agent/dashboard.php
|
||||
|
||||
Built on cards, list-groups and Bootstrap's subtle colour utilities; this is
|
||||
only what those do not cover: the greeting and section headings, quieter
|
||||
card headers, the "Needs attention" rail, the money strip, the priority dot
|
||||
and chart heights. Every number on the page uses tabular figures so columns
|
||||
of amounts line up without a monospace font. */
|
||||
.itflow-dash {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.itflow-dash-greeting {
|
||||
font-size: 1.6rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: -.01em;
|
||||
}
|
||||
.itflow-dash-section {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.itflow-dash .card-header {
|
||||
background: transparent;
|
||||
border-bottom: 0;
|
||||
padding-bottom: .25rem;
|
||||
}
|
||||
.itflow-dash .card-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.itflow-dash .card > .list-group-flush {
|
||||
border-top: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
}
|
||||
.itflow-dash .card-header + .list-group {
|
||||
margin-top: .5rem;
|
||||
}
|
||||
/* Clickable rows read as normal text, not the greyed default */
|
||||
.itflow-dash .list-group {
|
||||
--bs-list-group-action-color: var(--bs-body-color);
|
||||
}
|
||||
|
||||
/* Needs attention: one card split into cells, each with a severity bar on top.
|
||||
The -1px margins tuck every cell's left/top hairline under the card edge, so
|
||||
only the lines between cells show however the row wraps. */
|
||||
.itflow-dash-rail {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
margin: -1px 0 0 -1px;
|
||||
}
|
||||
.itflow-dash-rail-item {
|
||||
display: flex;
|
||||
flex: 1 1 10rem;
|
||||
flex-direction: column;
|
||||
gap: .15rem;
|
||||
min-width: 0;
|
||||
padding: 1rem 1.1rem .9rem;
|
||||
border-top: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
border-left: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
box-shadow: inset 0 3px 0 var(--itflow-dash-tone, var(--bs-secondary));
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
a.itflow-dash-rail-item:hover,
|
||||
a.itflow-dash-rail-item:focus-visible {
|
||||
background-color: var(--bs-tertiary-bg);
|
||||
color: inherit;
|
||||
}
|
||||
.itflow-dash-rail-count {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.1;
|
||||
}
|
||||
.itflow-dash-rail-label {
|
||||
font-size: .875rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.itflow-dash-rail-label .fas {
|
||||
margin-right: .35rem;
|
||||
}
|
||||
.itflow-dash-rail-detail {
|
||||
font-size: .8rem;
|
||||
color: var(--bs-secondary-color);
|
||||
}
|
||||
.itflow-dash-rail-clear {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
/* Finance: the period figures side by side, then "Right now" beside them */
|
||||
.itflow-dash-money + .itflow-dash-money {
|
||||
border-top: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
}
|
||||
.itflow-dash-money a:hover,
|
||||
.itflow-dash-money a:focus-visible {
|
||||
background-color: var(--bs-tertiary-bg);
|
||||
}
|
||||
.itflow-dash-money-value {
|
||||
margin: .1rem 0 .15rem;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.itflow-dash-now {
|
||||
border-top: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
background-color: var(--bs-tertiary-bg);
|
||||
}
|
||||
.itflow-dash-now .list-group {
|
||||
--bs-list-group-bg: transparent;
|
||||
}
|
||||
@media (min-width: 768px) {
|
||||
.itflow-dash-money + .itflow-dash-money {
|
||||
border-top: 0;
|
||||
border-left: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
}
|
||||
}
|
||||
@media (min-width: 992px) {
|
||||
.itflow-dash-now {
|
||||
border-top: 0;
|
||||
border-left: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
}
|
||||
}
|
||||
|
||||
/* Your schedule: day headings, then time | colour mark | what */
|
||||
.itflow-dash-schedule {
|
||||
border-top: var(--bs-border-width) solid var(--bs-border-color-translucent);
|
||||
margin-top: .5rem;
|
||||
padding-bottom: .4rem;
|
||||
}
|
||||
/* Beside the ticket list it takes that card's height and scrolls the rest;
|
||||
stacked on smaller screens it stops at a sensible height */
|
||||
@media (max-width: 1199.98px) {
|
||||
.itflow-dash-schedule {
|
||||
max-height: 26rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
}
|
||||
@media (min-width: 1200px) {
|
||||
.itflow-dash-schedule {
|
||||
flex: 1 1 0;
|
||||
min-height: 14rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
}
|
||||
.itflow-dash-schedule-day {
|
||||
padding: .6rem 1rem .2rem;
|
||||
font-size: .8rem;
|
||||
font-weight: 600;
|
||||
color: var(--bs-secondary-color);
|
||||
}
|
||||
.itflow-dash-schedule-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: .75rem;
|
||||
padding: .4rem 1rem;
|
||||
color: var(--bs-body-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
.itflow-dash-schedule-item:hover,
|
||||
.itflow-dash-schedule-item:focus-visible {
|
||||
background-color: var(--bs-tertiary-bg);
|
||||
color: var(--bs-body-color);
|
||||
}
|
||||
/* Earlier today - still listed, but stepped back */
|
||||
.itflow-dash-schedule-item.is-past {
|
||||
opacity: .55;
|
||||
}
|
||||
.itflow-dash-schedule-time {
|
||||
flex: 0 0 4.25rem;
|
||||
font-size: .8rem;
|
||||
color: var(--bs-secondary-color);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.itflow-dash-schedule-mark {
|
||||
flex: 0 0 auto;
|
||||
align-self: stretch;
|
||||
width: 3px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
/* Ranked rows with a bar underneath: open tickets by tech, top clients */
|
||||
.itflow-dash-bars {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: .35rem;
|
||||
margin-inline: -.5rem;
|
||||
}
|
||||
.itflow-dash-bar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
column-gap: .75rem;
|
||||
row-gap: .3rem;
|
||||
padding: .35rem .5rem;
|
||||
border-radius: var(--bs-border-radius-sm);
|
||||
color: var(--bs-body-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
.itflow-dash-bar:hover,
|
||||
.itflow-dash-bar:focus-visible {
|
||||
background-color: var(--bs-tertiary-bg);
|
||||
color: var(--bs-body-color);
|
||||
}
|
||||
.itflow-dash-bar-label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.itflow-dash-bar-value {
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.itflow-dash-bar-track {
|
||||
display: flex;
|
||||
grid-column: 1 / -1;
|
||||
height: .375rem;
|
||||
overflow: hidden;
|
||||
border-radius: 1rem;
|
||||
background-color: var(--bs-secondary-bg);
|
||||
}
|
||||
.itflow-dash-bar-fill {
|
||||
height: 100%;
|
||||
background-color: var(--itflow-accent);
|
||||
}
|
||||
|
||||
/* Receivables aging: one bar split by lateness, green through to deep red */
|
||||
.itflow-dash-aging {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
height: .75rem;
|
||||
overflow: hidden;
|
||||
border-radius: 1rem;
|
||||
background-color: var(--bs-secondary-bg);
|
||||
}
|
||||
.itflow-dash-age-current {
|
||||
background-color: var(--bs-success);
|
||||
}
|
||||
.itflow-dash-age-1-30 {
|
||||
background-color: var(--bs-warning);
|
||||
}
|
||||
.itflow-dash-age-31-60 {
|
||||
background-color: var(--bs-orange);
|
||||
}
|
||||
.itflow-dash-age-61-90 {
|
||||
background-color: var(--bs-danger);
|
||||
}
|
||||
.itflow-dash-age-90plus {
|
||||
background-color: #842029;
|
||||
}
|
||||
[data-bs-theme=dark] .itflow-dash-age-90plus {
|
||||
background-color: #a52834;
|
||||
}
|
||||
|
||||
.itflow-dash-dot {
|
||||
flex: 0 0 auto;
|
||||
width: .55rem;
|
||||
height: .55rem;
|
||||
border-radius: 50%;
|
||||
}
|
||||
/* Urgent is "dark" everywhere else in the ticket lists - invisible on a dark page */
|
||||
[data-bs-theme=dark] .itflow-dash-dot.bg-dark {
|
||||
background-color: var(--bs-emphasis-color) !important;
|
||||
}
|
||||
.itflow-dash-chart {
|
||||
position: relative;
|
||||
height: 240px;
|
||||
}
|
||||
.itflow-dash-chart-donut {
|
||||
height: 180px;
|
||||
}
|
||||
.itflow-dash-donut-total {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
line-height: 1.25;
|
||||
pointer-events: none;
|
||||
}
|
||||
.itflow-dash-donut-total [data-donut-total] {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
.itflow-dash-legend {
|
||||
margin-inline: -.4rem;
|
||||
font-size: .85rem;
|
||||
}
|
||||
.itflow-dash-legend li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: .5rem;
|
||||
padding: .2rem .4rem;
|
||||
border-radius: var(--bs-border-radius-sm);
|
||||
}
|
||||
.itflow-dash-legend li:hover {
|
||||
background-color: var(--bs-tertiary-bg);
|
||||
}
|
||||
.itflow-dash-legend-swatch {
|
||||
flex: 0 0 auto;
|
||||
width: .6rem;
|
||||
height: .6rem;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.itflow-dash-legend-label {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.itflow-dash-legend-value {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.itflow-dash-legend-share {
|
||||
flex: 0 0 2.5rem;
|
||||
text-align: right;
|
||||
color: var(--bs-secondary-color);
|
||||
}
|
||||
.itflow-dash-chart-lg {
|
||||
height: 300px;
|
||||
}
|
||||
.itflow-dash-chart-sm {
|
||||
min-height: 150px;
|
||||
}
|
||||
|
||||
@@ -29,3 +29,4 @@ require_once __DIR__ . '/functions/calendar.php';
|
||||
require_once __DIR__ . '/functions/backup.php';
|
||||
require_once __DIR__ . '/functions/search.php';
|
||||
require_once __DIR__ . '/functions/notifications.php';
|
||||
require_once __DIR__ . '/functions/dashboard.php';
|
||||
|
||||
964
functions/dashboard.php
Normal file
964
functions/dashboard.php
Normal file
@@ -0,0 +1,964 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Dashboard data - agent/dashboard.php.
|
||||
*
|
||||
* The page renders; everything it shows is worked out here, so each number has
|
||||
* one definition. Where a number links somewhere, it is counted the way that
|
||||
* page filters, so clicking "4 unassigned" lands on a list of 4 tickets.
|
||||
*
|
||||
* Two kinds of number:
|
||||
* - point in time ("needs attention", my tickets, receivables, recurring) -
|
||||
* what is true right now, whatever period is picked
|
||||
* - period (income, expenses, profit, the donuts, miles, top clients) - for
|
||||
* the picked period, compared with the same span before it
|
||||
*
|
||||
* The cash flow chart also looks ahead: from this month on it shows what is
|
||||
* expected in and out, worked out from unpaid invoices and the recurring
|
||||
* invoices and expenses (dashboardExpectedIncome / dashboardExpectedExpenses).
|
||||
*
|
||||
* Anything tied to a client goes through clientScopeSql(), so a technician
|
||||
* restricted to some clients sees counts for those clients only.
|
||||
*/
|
||||
|
||||
/*
|
||||
* ---------- periods ----------
|
||||
*/
|
||||
|
||||
/** The preset periods, plus every year that has data. Key => label. */
|
||||
function dashboardPeriodOptions() {
|
||||
global $mysqli;
|
||||
|
||||
$options = [
|
||||
'month' => 'This month',
|
||||
'30d' => 'Last 30 days',
|
||||
'quarter' => 'This quarter',
|
||||
'ytd' => 'Year to date',
|
||||
];
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT YEAR(payment_date) AS y FROM payments
|
||||
UNION SELECT YEAR(revenue_date) FROM revenues
|
||||
UNION SELECT YEAR(expense_date) FROM expenses
|
||||
UNION SELECT YEAR(invoice_date) FROM invoices
|
||||
UNION SELECT YEAR(ticket_created_at) FROM tickets
|
||||
ORDER BY y DESC
|
||||
");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$year = intval($row['y']);
|
||||
if ($year > 1970 && $year <= intval(date('Y'))) {
|
||||
$options["year-$year"] = (string) $year;
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/** $date moved by $months, keeping the day but never spilling into the next month. */
|
||||
function dashboardShiftMonths($date, $months) {
|
||||
$d = new DateTime($date);
|
||||
$day = intval($d->format('j'));
|
||||
$d->modify('first day of this month')->modify(($months >= 0 ? '+' : '') . $months . ' months');
|
||||
$d->setDate(intval($d->format('Y')), intval($d->format('n')), min($day, intval($d->format('t'))));
|
||||
return $d->format('Y-m-d');
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a period key into dates. "To date" periods end today and compare
|
||||
* with the same number of days the period before, so day 9 of this month is
|
||||
* measured against days 1-9 of last month, not all of it.
|
||||
*/
|
||||
function dashboardPeriod($key) {
|
||||
$today = date('Y-m-d');
|
||||
$current_year = intval(date('Y'));
|
||||
|
||||
// ?year=2025 is how the old dashboard linked to a year
|
||||
if (preg_match('/^year-(\d{4})$/', (string) $key, $m) && intval($m[1]) <= $current_year) {
|
||||
$year = intval($m[1]);
|
||||
return [
|
||||
'key' => "year-$year",
|
||||
'label' => (string) $year,
|
||||
'start' => "$year-01-01",
|
||||
'end' => "$year-12-31",
|
||||
'prev_start' => ($year - 1) . '-01-01',
|
||||
'prev_end' => ($year - 1) . '-12-31',
|
||||
'compare' => 'vs ' . ($year - 1),
|
||||
'compare_long' => 'compared with ' . ($year - 1),
|
||||
'chart_end' => "$year-12-01",
|
||||
'chart_label' => (string) $year,
|
||||
];
|
||||
}
|
||||
|
||||
switch ($key) {
|
||||
case 'month':
|
||||
$start = date('Y-m-01');
|
||||
$prev_start = dashboardShiftMonths($start, -1);
|
||||
$prev_end = dashboardShiftMonths($today, -1);
|
||||
$label = 'This month';
|
||||
$compare = 'vs last month';
|
||||
$compare_long = 'compared with the same days last month';
|
||||
break;
|
||||
case '30d':
|
||||
$start = date('Y-m-d', strtotime('-29 days'));
|
||||
$prev_start = date('Y-m-d', strtotime('-59 days'));
|
||||
$prev_end = date('Y-m-d', strtotime('-30 days'));
|
||||
$label = 'Last 30 days';
|
||||
$compare = 'vs prior 30 days';
|
||||
$compare_long = 'compared with the 30 days before';
|
||||
break;
|
||||
case 'quarter':
|
||||
$quarter_month = intval((intval(date('n')) - 1) / 3) * 3 + 1;
|
||||
$start = sprintf('%d-%02d-01', $current_year, $quarter_month);
|
||||
$prev_start = dashboardShiftMonths($start, -3);
|
||||
$prev_end = dashboardShiftMonths($today, -3);
|
||||
$label = 'This quarter';
|
||||
$compare = 'vs last quarter';
|
||||
$compare_long = 'compared with the same point last quarter';
|
||||
break;
|
||||
default:
|
||||
$key = 'ytd';
|
||||
$start = "$current_year-01-01";
|
||||
$prev_start = ($current_year - 1) . '-01-01';
|
||||
$prev_end = dashboardShiftMonths($today, -12);
|
||||
$label = 'Year to date';
|
||||
$compare = 'vs last year';
|
||||
$compare_long = 'compared with the same period last year';
|
||||
}
|
||||
|
||||
return [
|
||||
'key' => $key,
|
||||
'label' => $label,
|
||||
'start' => $start,
|
||||
'end' => $today,
|
||||
'prev_start' => $prev_start,
|
||||
'prev_end' => $prev_end,
|
||||
'compare' => $compare,
|
||||
'compare_long' => $compare_long,
|
||||
'chart_end' => date('Y-m-01'),
|
||||
'chart_label' => 'Last 12 months',
|
||||
];
|
||||
}
|
||||
|
||||
/** The 12 months a monthly chart covers, oldest first, as Y-m. */
|
||||
function dashboardChartMonths($period) {
|
||||
$months = [];
|
||||
for ($i = 11; $i >= 0; $i--) {
|
||||
$months[] = substr(dashboardShiftMonths($period['chart_end'], -$i), 0, 7);
|
||||
}
|
||||
return $months;
|
||||
}
|
||||
|
||||
/** Percentage change, or null when there is nothing to compare against. */
|
||||
function dashboardChange($current, $previous) {
|
||||
if (abs($previous) < 0.005) {
|
||||
return null;
|
||||
}
|
||||
return round(($current - $previous) / abs($previous) * 100);
|
||||
}
|
||||
|
||||
/*
|
||||
* ---------- who sees what ----------
|
||||
*/
|
||||
|
||||
function dashboardAccess() {
|
||||
global $config_module_enable_ticketing, $config_module_enable_accounting;
|
||||
|
||||
$ticketing = intval($config_module_enable_ticketing) === 1;
|
||||
$accounting = intval($config_module_enable_accounting) === 1;
|
||||
|
||||
return [
|
||||
'support' => lookupUserPermission('module_support') >= 1,
|
||||
'tickets' => $ticketing && lookupUserPermission('module_support') >= 1,
|
||||
'sales' => $accounting && lookupUserPermission('module_sales') >= 1,
|
||||
'financial' => $accounting && lookupUserPermission('module_financial') >= 1,
|
||||
];
|
||||
}
|
||||
|
||||
function dashboardCount($sql) {
|
||||
global $mysqli;
|
||||
return intval(mysqli_fetch_row(mysqli_query($mysqli, $sql))[0]);
|
||||
}
|
||||
|
||||
function dashboardSum($sql) {
|
||||
global $mysqli;
|
||||
return floatval(mysqli_fetch_row(mysqli_query($mysqli, $sql))[0]);
|
||||
}
|
||||
|
||||
/** A ticket that has missed its response or resolution target - the rule tickets.php?sla=breached uses. */
|
||||
function dashboardSlaBreachedSql() {
|
||||
return "(ticket_sla_id > 0 AND (ticket_response_sla_alert_stage = 2 OR ticket_resolution_sla_alert_stage = 2
|
||||
OR ticket_response_sla_met = 0 OR ticket_resolution_sla_met = 0))";
|
||||
}
|
||||
|
||||
/** "Today", "Tomorrow", or "Monday, Oct 12" for a date or datetime. */
|
||||
function dashboardDayLabel($datetime) {
|
||||
$day = substr($datetime, 0, 10);
|
||||
if ($day === date('Y-m-d')) {
|
||||
return 'Today';
|
||||
}
|
||||
if ($day === date('Y-m-d', strtotime('+1 day'))) {
|
||||
return 'Tomorrow';
|
||||
}
|
||||
return date('l, M j', strtotime($day));
|
||||
}
|
||||
|
||||
/** Seconds as "3h 20m", "45m" or "2h". */
|
||||
function dashboardDuration($seconds) {
|
||||
$minutes = intdiv(max(0, intval($seconds)) + 30, 60);
|
||||
$hours = intdiv($minutes, 60);
|
||||
$minutes %= 60;
|
||||
if (!$hours) {
|
||||
return $minutes . 'm';
|
||||
}
|
||||
return $minutes ? "{$hours}h {$minutes}m" : "{$hours}h";
|
||||
}
|
||||
|
||||
/*
|
||||
* ---------- needs attention ----------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Things to act on now. Only ones with a count are returned, so the strip is
|
||||
* empty on a good day. Each count matches the list its link opens.
|
||||
*/
|
||||
function dashboardAttention($access) {
|
||||
$items = [];
|
||||
$ticket_scope = clientScopeSql('ticket_client_id');
|
||||
|
||||
if ($access['tickets']) {
|
||||
// Same rule as tickets.php?sla=breached, on open tickets
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE ticket_resolved_at IS NULL
|
||||
AND " . dashboardSlaBreachedSql() . " $ticket_scope"),
|
||||
'label' => 'SLA breached', 'icon' => 'stopwatch', 'tone' => 'danger',
|
||||
'url' => '/agent/tickets.php?sla=breached',
|
||||
];
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE ticket_resolved_at IS NULL AND ticket_assigned_to = 0 $ticket_scope"),
|
||||
'label' => 'Unassigned tickets', 'icon' => 'user-slash', 'tone' => 'warning',
|
||||
'url' => '/agent/tickets.php?assigned=unassigned',
|
||||
];
|
||||
}
|
||||
|
||||
if ($access['sales']) {
|
||||
$invoice_scope = clientScopeSql('invoice_client_id');
|
||||
$overdue_where = "invoice_status IN ('Sent', 'Viewed', 'Partial') AND invoice_due < CURDATE() $invoice_scope";
|
||||
$overdue_count = dashboardCount("SELECT COUNT(invoice_id) FROM invoices WHERE $overdue_where");
|
||||
$overdue_amount = dashboardSum("SELECT SUM(invoice_amount) FROM invoices WHERE $overdue_where")
|
||||
- dashboardSum("SELECT SUM(payment_amount) FROM payments JOIN invoices ON payment_invoice_id = invoice_id WHERE $overdue_where");
|
||||
$items[] = [
|
||||
'count' => $overdue_count,
|
||||
'label' => 'Overdue invoices', 'icon' => 'file-invoice-dollar', 'tone' => 'danger',
|
||||
'detail' => $overdue_count ? dashboardMoney($overdue_amount) . ' outstanding' : null,
|
||||
'url' => '/agent/invoices.php?status=Overdue',
|
||||
];
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(invoice_id) FROM invoices WHERE invoice_status = 'Draft' $invoice_scope"),
|
||||
'label' => 'Draft invoices', 'icon' => 'pen', 'tone' => 'secondary',
|
||||
'url' => '/agent/invoices.php?status=Draft',
|
||||
];
|
||||
if ($access['tickets']) {
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE ticket_resolved_at IS NOT NULL
|
||||
AND ticket_billable = 1 AND ticket_invoice_id = 0 $ticket_scope"),
|
||||
'label' => 'Resolved, not invoiced', 'icon' => 'receipt', 'tone' => 'info',
|
||||
'url' => '/agent/tickets.php?billing=unbilled&state=closed',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($access['support']) {
|
||||
$soon = "BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY";
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(domain_id) FROM domains WHERE domain_archived_at IS NULL AND domain_expire $soon " . clientScopeSql('domain_client_id')),
|
||||
'label' => 'Domains expiring', 'icon' => 'globe', 'tone' => 'warning', 'detail' => 'Next 30 days',
|
||||
'url' => '/agent/domains.php?expire_days=30&sort=domain_expire&order=ASC',
|
||||
];
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(certificate_id) FROM certificates WHERE certificate_archived_at IS NULL AND certificate_expire $soon " . clientScopeSql('certificate_client_id')),
|
||||
'label' => 'Certificates expiring', 'icon' => 'lock', 'tone' => 'warning', 'detail' => 'Next 30 days',
|
||||
'url' => '/agent/certificates.php?expire_days=30&sort=certificate_expire&order=ASC',
|
||||
];
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(software_id) FROM software WHERE software_archived_at IS NULL AND software_expire $soon " . clientScopeSql('software_client_id')),
|
||||
'label' => 'Licenses expiring', 'icon' => 'cube', 'tone' => 'warning', 'detail' => 'Next 30 days',
|
||||
'url' => '/agent/software.php?expire_days=30&sort=software_expire&order=ASC',
|
||||
];
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(asset_id) FROM assets WHERE asset_archived_at IS NULL AND asset_warranty_expire $soon " . clientScopeSql('asset_client_id')),
|
||||
'label' => 'Warranties expiring', 'icon' => 'shield-alt', 'tone' => 'warning', 'detail' => 'Next 30 days',
|
||||
'url' => '/agent/assets.php?expire_days=30&sort=asset_warranty_expire&order=ASC&show_column[]=Warranty_Expire',
|
||||
];
|
||||
}
|
||||
|
||||
return array_values(array_filter($items, function ($item) {
|
||||
return $item['count'] > 0;
|
||||
}));
|
||||
}
|
||||
|
||||
/*
|
||||
* ---------- my work ----------
|
||||
*/
|
||||
|
||||
/** My open tickets, the ones most in need of me first: breached SLA, then priority, then waiting longest. */
|
||||
function dashboardMyTickets($limit = 8) {
|
||||
global $mysqli, $session_user_id;
|
||||
|
||||
$user_id = intval($session_user_id);
|
||||
$where = "ticket_assigned_to = $user_id AND ticket_resolved_at IS NULL " . clientScopeSql('ticket_client_id');
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_priority, ticket_client_id,
|
||||
ticket_created_at, ticket_updated_at, ticket_status_name, ticket_status_color, client_name,
|
||||
" . dashboardSlaBreachedSql() . " AS sla_breached
|
||||
FROM tickets
|
||||
LEFT JOIN clients ON ticket_client_id = client_id
|
||||
LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id
|
||||
WHERE $where
|
||||
ORDER BY sla_breached DESC, FIELD(ticket_priority, 'Urgent', 'High', 'Medium', 'Low'),
|
||||
COALESCE(ticket_updated_at, ticket_created_at) ASC
|
||||
LIMIT " . intval($limit)
|
||||
);
|
||||
|
||||
$tickets = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$tickets[] = $row;
|
||||
}
|
||||
|
||||
return [
|
||||
'tickets' => $tickets,
|
||||
'total' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $where"),
|
||||
'breached' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE $where AND " . dashboardSlaBreachedSql()),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The next 7 days for me: open tickets scheduled with me, and calendar events.
|
||||
* The calendar is shared, so every event shows; repeating events are expanded
|
||||
* the way the calendar page does it. Soonest first, all-day items at the top
|
||||
* of their day.
|
||||
*/
|
||||
function dashboardSchedule($days = 7, $limit = 30) {
|
||||
global $mysqli, $session_user_id;
|
||||
|
||||
$user_id = intval($session_user_id);
|
||||
$from = date('Y-m-d 00:00:00');
|
||||
$to = date('Y-m-d 23:59:59', strtotime('+' . ($days - 1) . ' days'));
|
||||
$items = [];
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_schedule, ticket_onsite, ticket_client_id, client_name
|
||||
FROM tickets
|
||||
LEFT JOIN clients ON ticket_client_id = client_id
|
||||
WHERE ticket_assigned_to = $user_id AND ticket_resolved_at IS NULL
|
||||
AND ticket_schedule BETWEEN '$from' AND '$to' " . clientScopeSql('ticket_client_id')
|
||||
);
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$items[] = [
|
||||
'when' => $row['ticket_schedule'],
|
||||
'all_day' => false,
|
||||
'ongoing' => false,
|
||||
'title' => $row['ticket_subject'],
|
||||
'ref' => $row['ticket_prefix'] . $row['ticket_number'],
|
||||
'detail' => $row['client_name'] ?: '',
|
||||
'onsite' => intval($row['ticket_onsite']) === 1,
|
||||
'color' => null,
|
||||
'url' => '/agent/ticket.php?' . http_build_query(array_filter([
|
||||
'client_id' => intval($row['ticket_client_id']) ?: null,
|
||||
'ticket_id' => intval($row['ticket_id']),
|
||||
])),
|
||||
];
|
||||
}
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT event_id, event_title, event_start, event_end, event_all_day, event_repeat, event_location, client_name, calendar_color
|
||||
FROM calendar_events
|
||||
LEFT JOIN calendars ON event_calendar_id = calendar_id
|
||||
LEFT JOIN clients ON event_client_id = client_id
|
||||
WHERE event_archived_at IS NULL AND event_start <= '$to'
|
||||
AND ((event_repeat IS NOT NULL AND event_repeat != '') OR event_start >= '$from' OR event_end >= '$from') " . clientScopeSql('event_client_id')
|
||||
);
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
foreach (expandRecurringEvent($row, $from, $to) as $occurrence) {
|
||||
$start = $occurrence['start'];
|
||||
$end = $occurrence['end'] ?: $start;
|
||||
if ($start > $to || max($start, $end) < $from) {
|
||||
continue;
|
||||
}
|
||||
$items[] = [
|
||||
// An event already under way shows on today
|
||||
'when' => max($start, $from),
|
||||
'all_day' => !empty($row['event_all_day']),
|
||||
'ongoing' => $start < $from,
|
||||
'title' => $row['event_title'],
|
||||
'ref' => '',
|
||||
'detail' => $row['client_name'] ?: ($row['event_location'] ?: ''),
|
||||
'onsite' => false,
|
||||
'color' => preg_match('/^#[0-9a-f]{3,8}$/i', (string) $row['calendar_color']) ? $row['calendar_color'] : null,
|
||||
'url' => '/agent/calendar.php',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
usort($items, function ($a, $b) {
|
||||
$key = function ($item) {
|
||||
return substr($item['when'], 0, 10) . (($item['all_day'] || $item['ongoing']) ? '0' : '1') . substr($item['when'], 11);
|
||||
};
|
||||
return strcmp($key($a), $key($b));
|
||||
});
|
||||
|
||||
return ['items' => array_slice($items, 0, $limit), 'total' => count($items)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Time I logged on ticket replies this week (Monday on), per day and split by
|
||||
* whether the ticket is billable, with last week's total to compare.
|
||||
*/
|
||||
function dashboardTimeThisWeek() {
|
||||
global $mysqli, $session_user_id;
|
||||
|
||||
$user_id = intval($session_user_id);
|
||||
$monday = new DateTime('monday this week');
|
||||
$this_monday = $monday->format('Y-m-d');
|
||||
$last_monday = (clone $monday)->modify('-1 week')->format('Y-m-d');
|
||||
|
||||
$days = [];
|
||||
for ($i = 0; $i < 7; $i++) {
|
||||
$day = (clone $monday)->modify("+$i days");
|
||||
$days[$day->format('Y-m-d')] = ['label' => $day->format('D'), 'billable' => 0, 'other' => 0];
|
||||
}
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT DATE(ticket_reply_created_at) AS d, ticket_billable AS billable, SUM(TIME_TO_SEC(ticket_reply_time_worked)) AS s
|
||||
FROM ticket_replies
|
||||
JOIN tickets ON ticket_reply_ticket_id = ticket_id
|
||||
WHERE ticket_reply_by = $user_id AND ticket_reply_archived_at IS NULL
|
||||
AND ticket_reply_created_at >= '$this_monday'
|
||||
GROUP BY d, billable
|
||||
");
|
||||
|
||||
$total = 0;
|
||||
$billable = 0;
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
if (!isset($days[$row['d']])) {
|
||||
continue;
|
||||
}
|
||||
$seconds = intval($row['s']);
|
||||
$is_billable = intval($row['billable']) === 1;
|
||||
$days[$row['d']][$is_billable ? 'billable' : 'other'] += $seconds;
|
||||
$total += $seconds;
|
||||
$billable += $is_billable ? $seconds : 0;
|
||||
}
|
||||
|
||||
return [
|
||||
// Hours, for the chart
|
||||
'days' => array_map(function ($day) {
|
||||
return ['label' => $day['label'], 'billable' => round($day['billable'] / 3600, 2), 'other' => round($day['other'] / 3600, 2)];
|
||||
}, array_values($days)),
|
||||
'total' => $total,
|
||||
'billable' => $billable,
|
||||
'last_week' => intval(dashboardSum("SELECT SUM(TIME_TO_SEC(ticket_reply_time_worked)) FROM ticket_replies
|
||||
WHERE ticket_reply_by = $user_id AND ticket_reply_archived_at IS NULL
|
||||
AND ticket_reply_created_at >= '$last_monday' AND ticket_reply_created_at < '$this_monday'")),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Open tickets per technician, busiest first, with how many are past SLA -
|
||||
* for admins balancing the load. Unassigned tickets are counted separately.
|
||||
*/
|
||||
function dashboardTeamWorkload($limit = 8) {
|
||||
global $mysqli;
|
||||
|
||||
$scope = clientScopeSql('ticket_client_id');
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT user_id, user_name, COUNT(ticket_id) AS open, SUM(" . dashboardSlaBreachedSql() . ") AS breached
|
||||
FROM tickets
|
||||
JOIN users ON ticket_assigned_to = user_id
|
||||
WHERE ticket_resolved_at IS NULL $scope
|
||||
GROUP BY user_id, user_name
|
||||
ORDER BY open DESC, user_name
|
||||
LIMIT " . intval($limit)
|
||||
);
|
||||
|
||||
$techs = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$techs[] = $row;
|
||||
}
|
||||
|
||||
return [
|
||||
'techs' => $techs,
|
||||
'unassigned' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE ticket_resolved_at IS NULL AND ticket_assigned_to = 0 $scope"),
|
||||
];
|
||||
}
|
||||
|
||||
/** Tickets opened and resolved per week, the last 12 weeks (Monday to Sunday). */
|
||||
function dashboardTicketTrend() {
|
||||
global $mysqli;
|
||||
|
||||
$scope = clientScopeSql('ticket_client_id');
|
||||
$this_monday = new DateTime('monday this week');
|
||||
$first_monday = (clone $this_monday)->modify('-11 weeks')->format('Y-m-d');
|
||||
|
||||
$weeks = [];
|
||||
for ($i = 11; $i >= 0; $i--) {
|
||||
$monday = (clone $this_monday)->modify("-$i weeks");
|
||||
$weeks[$monday->format('Y-m-d')] = ['label' => $monday->format('M j'), 'opened' => 0, 'resolved' => 0];
|
||||
}
|
||||
|
||||
foreach (['opened' => 'ticket_created_at', 'resolved' => 'ticket_resolved_at'] as $series => $column) {
|
||||
$sql = mysqli_query($mysqli, "SELECT DATE($column) AS d, COUNT(ticket_id) AS n FROM tickets
|
||||
WHERE $column >= '$first_monday' $scope GROUP BY DATE($column)");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$week = (new DateTime($row['d']))->modify('monday this week')->format('Y-m-d');
|
||||
if (isset($weeks[$week])) {
|
||||
$weeks[$week][$series] += intval($row['n']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($weeks);
|
||||
}
|
||||
|
||||
/*
|
||||
* ---------- money ----------
|
||||
*/
|
||||
|
||||
function dashboardMoney($amount) {
|
||||
global $currency_format, $session_company_currency;
|
||||
return numfmt_format_currency($currency_format, floatval($amount), $session_company_currency);
|
||||
}
|
||||
|
||||
/** 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'");
|
||||
}
|
||||
|
||||
/** Vendor expenses - expenses with no vendor are transfers between accounts. */
|
||||
function dashboardExpenses($start, $end) {
|
||||
return dashboardSum("SELECT SUM(expense_amount) FROM expenses WHERE expense_vendor_id > 0 AND expense_date BETWEEN '$start' AND '$end'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Every unpaid invoice with what is still owed on it - the list
|
||||
* invoices.php?status=Unpaid shows. Callers keep the rows with balance > 0.
|
||||
*/
|
||||
function dashboardOpenInvoicesSql($scope = '') {
|
||||
return "SELECT invoice_id, invoice_client_id, invoice_due,
|
||||
invoice_amount - COALESCE((SELECT SUM(payment_amount) FROM payments WHERE payment_invoice_id = invoice_id), 0) AS balance
|
||||
FROM invoices
|
||||
WHERE invoice_status IN ('Sent', 'Viewed', 'Partial') $scope";
|
||||
}
|
||||
|
||||
/** The headline money cards. Change is null when the previous period had nothing to compare. */
|
||||
function dashboardMoneyCards($access, $period) {
|
||||
$cards = [];
|
||||
|
||||
if ($access['financial']) {
|
||||
$income = dashboardIncome($period['start'], $period['end']);
|
||||
$income_prev = dashboardIncome($period['prev_start'], $period['prev_end']);
|
||||
$expenses = dashboardExpenses($period['start'], $period['end']);
|
||||
$expenses_prev = dashboardExpenses($period['prev_start'], $period['prev_end']);
|
||||
|
||||
$cards[] = ['label' => 'Income', 'value' => $income, 'change' => dashboardChange($income, $income_prev), 'good' => 'up',
|
||||
'url' => '/agent/income.php?canned_date=custom&dtf=' . $period['start'] . '&dtt=' . $period['end']];
|
||||
$cards[] = ['label' => 'Expenses', 'value' => $expenses, 'change' => dashboardChange($expenses, $expenses_prev), 'good' => 'down',
|
||||
'url' => '/agent/expenses.php?canned_date=custom&dtf=' . $period['start'] . '&dtt=' . $period['end']];
|
||||
$cards[] = ['label' => 'Profit', 'value' => $income - $expenses, 'change' => dashboardChange($income - $expenses, $income_prev - $expenses_prev), 'good' => 'up',
|
||||
'url' => '/agent/reports/profit_loss.php'];
|
||||
}
|
||||
|
||||
if ($access['sales']) {
|
||||
// What is still owed on unpaid invoices - the same total as the aging card and
|
||||
// the list the card opens. Scoped to the clients this user can open.
|
||||
$invoice_scope = clientScopeSql('invoice_client_id');
|
||||
$recurring_scope = clientScopeSql('recurring_invoice_client_id');
|
||||
$receivables = dashboardSum("SELECT SUM(balance) FROM (" . dashboardOpenInvoicesSql($invoice_scope) . ") AS open_invoices WHERE balance > 0");
|
||||
$mrr = dashboardSum("SELECT SUM(recurring_invoice_amount) FROM recurring_invoices WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL AND recurring_invoice_frequency = 'month' $recurring_scope")
|
||||
+ dashboardSum("SELECT SUM(recurring_invoice_amount) FROM recurring_invoices WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL AND recurring_invoice_frequency = 'year' $recurring_scope") / 12;
|
||||
|
||||
$cards[] = ['label' => 'Receivables', 'value' => $receivables, 'change' => null, 'note' => 'Owed to you now',
|
||||
'url' => '/agent/invoices.php?status=Unpaid'];
|
||||
$cards[] = ['label' => 'Recurring revenue', 'value' => $mrr, 'change' => null, 'note' => 'Per month',
|
||||
'url' => '/agent/recurring_invoices.php'];
|
||||
}
|
||||
|
||||
if ($access['financial']) {
|
||||
$recurring_expenses = dashboardSum("SELECT SUM(recurring_expense_amount) FROM recurring_expenses WHERE recurring_expense_status = 1 AND recurring_expense_archived_at IS NULL 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_frequency = 2") / 12;
|
||||
$cards[] = ['label' => 'Recurring expenses', 'value' => $recurring_expenses, 'change' => null, 'note' => 'Per month',
|
||||
'url' => '/agent/recurring_expenses.php'];
|
||||
}
|
||||
|
||||
return $cards;
|
||||
}
|
||||
|
||||
/** Monthly amounts from a "SELECT DATE_FORMAT(..., '%Y-%m') AS m, SUM(...) AS v ... GROUP BY m" query, laid on $months. */
|
||||
function dashboardMonthly($sql, $months) {
|
||||
global $mysqli;
|
||||
$values = array_fill_keys($months, 0.0);
|
||||
$result = mysqli_query($mysqli, $sql);
|
||||
while ($row = mysqli_fetch_assoc($result)) {
|
||||
if (isset($values[$row['m']])) {
|
||||
$values[$row['m']] += floatval($row['v']);
|
||||
}
|
||||
}
|
||||
return array_values($values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Income and expenses per month over the chart's 12 months, plus income for
|
||||
* the 12 before. A chart that reaches this month runs three months further,
|
||||
* and from this month on carries what is expected in and out on top of what
|
||||
* has already happened.
|
||||
*/
|
||||
function dashboardCashFlow($period) {
|
||||
$months = dashboardChartMonths($period);
|
||||
$this_month = date('Y-m');
|
||||
|
||||
$extended = end($months) === $this_month;
|
||||
if ($extended) {
|
||||
for ($i = 1; $i <= 3; $i++) {
|
||||
$months[] = substr(dashboardShiftMonths(date('Y-m-01'), $i), 0, 7);
|
||||
}
|
||||
}
|
||||
|
||||
$last_year = array_map(function ($m) {
|
||||
return substr(dashboardShiftMonths("$m-01", -12), 0, 7);
|
||||
}, $months);
|
||||
|
||||
$income = function ($from, $to, $range) {
|
||||
return array_map(function ($a, $b) {
|
||||
return round($a + $b, 2);
|
||||
},
|
||||
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)
|
||||
);
|
||||
};
|
||||
$round = function ($values) {
|
||||
return array_map(function ($v) {
|
||||
return round($v, 2);
|
||||
}, $values);
|
||||
};
|
||||
|
||||
$from = $months[0] . '-01';
|
||||
$to = date('Y-m-t', strtotime(end($months) . '-01'));
|
||||
$ly_from = $last_year[0] . '-01';
|
||||
$ly_to = date('Y-m-t', strtotime(end($last_year) . '-01'));
|
||||
|
||||
// The forecast covers today to the end of the chart, when the chart reaches that far
|
||||
$expected_income = array_fill(0, count($months), 0);
|
||||
$expected_expenses = $expected_income;
|
||||
if (end($months) >= $this_month) {
|
||||
$today = date('Y-m-d');
|
||||
$expected_income = $round(dashboardExpectedIncome($today, $to, $months));
|
||||
$expected_expenses = $round(dashboardExpectedExpenses($today, $to, $months));
|
||||
}
|
||||
|
||||
// First month entirely in the future: actuals there are always nothing, so the chart hides them
|
||||
$first_future = -1;
|
||||
foreach ($months as $i => $m) {
|
||||
if ($m > $this_month) {
|
||||
$first_future = $i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'labels' => array_map(function ($m) {
|
||||
return date('M y', strtotime("$m-01"));
|
||||
}, $months),
|
||||
'income' => $income($from, $to, $months),
|
||||
'expenses' => $round(dashboardMonthly("SELECT DATE_FORMAT(expense_date, '%Y-%m') AS m, SUM(expense_amount) AS v FROM expenses
|
||||
WHERE expense_vendor_id > 0 AND expense_date BETWEEN '$from' AND '$to' GROUP BY m", $months)),
|
||||
'income_last_year' => $income($ly_from, $ly_to, $last_year),
|
||||
'expected_income' => $expected_income,
|
||||
'expected_expenses' => $expected_expenses,
|
||||
'first_future' => $first_future,
|
||||
'extended' => $extended,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Money expected in between $from and $to: what is still owed on unpaid
|
||||
* invoices, in the month each is due, plus what active recurring invoices
|
||||
* will bill, in the month each runs. Recurring revenue goes by bill date
|
||||
* rather than bill date plus net terms so each month carries one month of it,
|
||||
* as the "Recurring revenue" figure does. Overdue invoices are left out -
|
||||
* when, or whether, they get paid is anyone's guess.
|
||||
*/
|
||||
function dashboardExpectedIncome($from, $to, $months) {
|
||||
global $mysqli;
|
||||
|
||||
$values = array_fill_keys($months, 0.0);
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT DATE_FORMAT(invoice_due, '%Y-%m') AS m, SUM(balance) AS v
|
||||
FROM (" . dashboardOpenInvoicesSql() . ") AS open_invoices
|
||||
WHERE balance > 0 AND invoice_due BETWEEN '$from' AND '$to' GROUP BY m");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
if (isset($values[$row['m']])) {
|
||||
$values[$row['m']] += floatval($row['v']);
|
||||
}
|
||||
}
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT recurring_invoice_next_date, recurring_invoice_frequency, recurring_invoice_amount
|
||||
FROM recurring_invoices
|
||||
WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL AND recurring_invoice_next_date <= '$to'");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$step = $row['recurring_invoice_frequency'] === 'year' ? 12 : 1;
|
||||
// A bill date already passed is one the nightly job has yet to run - it goes out today
|
||||
$bill = max($row['recurring_invoice_next_date'], $from);
|
||||
for ($guard = 0; $bill <= $to && $guard < 120; $guard++) {
|
||||
if (isset($values[substr($bill, 0, 7)])) {
|
||||
$values[substr($bill, 0, 7)] += floatval($row['recurring_invoice_amount']);
|
||||
}
|
||||
$bill = dashboardShiftMonths($bill, $step);
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($values);
|
||||
}
|
||||
|
||||
/** Money expected out between $from and $to: active recurring vendor expenses on their schedule. */
|
||||
function dashboardExpectedExpenses($from, $to, $months) {
|
||||
global $mysqli;
|
||||
|
||||
$values = array_fill_keys($months, 0.0);
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT recurring_expense_next_date, recurring_expense_frequency, 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_next_date <= '$to'");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$step = intval($row['recurring_expense_frequency']) === 2 ? 12 : 1;
|
||||
$date = max($row['recurring_expense_next_date'], $from);
|
||||
for ($guard = 0; $date <= $to && $guard < 120; $guard++) {
|
||||
if (isset($values[substr($date, 0, 7)])) {
|
||||
$values[substr($date, 0, 7)] += floatval($row['recurring_expense_amount']);
|
||||
}
|
||||
$date = dashboardShiftMonths($date, $step);
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($values);
|
||||
}
|
||||
|
||||
/**
|
||||
* What clients owe, split by how late it is, and the clients who owe the
|
||||
* most. Same invoices and total as the Receivables figure.
|
||||
*/
|
||||
function dashboardReceivablesAging($limit = 4) {
|
||||
global $mysqli;
|
||||
|
||||
$open = dashboardOpenInvoicesSql(clientScopeSql('invoice_client_id'));
|
||||
|
||||
$buckets = [];
|
||||
foreach (['current' => 'Not due yet', '1-30' => '1–30 days', '31-60' => '31–60 days', '61-90' => '61–90 days', '90+' => '90+ days'] as $key => $label) {
|
||||
$buckets[$key] = ['label' => $label, 'amount' => 0.0, 'count' => 0];
|
||||
}
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT CASE
|
||||
WHEN invoice_due >= CURDATE() THEN 'current'
|
||||
WHEN invoice_due >= CURDATE() - INTERVAL 30 DAY THEN '1-30'
|
||||
WHEN invoice_due >= CURDATE() - INTERVAL 60 DAY THEN '31-60'
|
||||
WHEN invoice_due >= CURDATE() - INTERVAL 90 DAY THEN '61-90'
|
||||
ELSE '90+'
|
||||
END AS bucket, COUNT(invoice_id) AS n, SUM(balance) AS v
|
||||
FROM ($open) AS open_invoices
|
||||
WHERE balance > 0
|
||||
GROUP BY bucket
|
||||
");
|
||||
$total = 0.0;
|
||||
$count = 0;
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$buckets[$row['bucket']]['amount'] = floatval($row['v']);
|
||||
$buckets[$row['bucket']]['count'] = intval($row['n']);
|
||||
$total += floatval($row['v']);
|
||||
$count += intval($row['n']);
|
||||
}
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT client_id, client_name, SUM(balance) AS v, COUNT(invoice_id) AS n, MAX(DATEDIFF(CURDATE(), invoice_due)) AS days_late
|
||||
FROM ($open) AS open_invoices
|
||||
JOIN clients ON invoice_client_id = client_id
|
||||
WHERE balance > 0
|
||||
GROUP BY client_id, client_name
|
||||
ORDER BY v DESC
|
||||
LIMIT " . intval($limit)
|
||||
);
|
||||
$clients = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$clients[] = $row;
|
||||
}
|
||||
|
||||
return ['buckets' => $buckets, 'total' => $total, 'count' => $count, 'clients' => $clients];
|
||||
}
|
||||
|
||||
/** The clients who paid the most in the period, from invoice payments and client revenues. */
|
||||
function dashboardTopClients($period, $limit = 8) {
|
||||
global $mysqli;
|
||||
|
||||
$start = $period['start'];
|
||||
$end = $period['end'];
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT client_id, client_name, 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 payment_date BETWEEN '$start' AND '$end' " . clientScopeSql('invoice_client_id') . "
|
||||
UNION ALL
|
||||
SELECT revenue_client_id, revenue_amount FROM revenues
|
||||
WHERE revenue_category_id > 0 AND revenue_client_id > 0 AND revenue_date BETWEEN '$start' AND '$end' " . clientScopeSql('revenue_client_id') . "
|
||||
) AS income
|
||||
JOIN clients USING (client_id)
|
||||
GROUP BY client_id, client_name
|
||||
ORDER BY v DESC
|
||||
LIMIT " . intval($limit)
|
||||
);
|
||||
|
||||
$clients = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$clients[] = $row;
|
||||
}
|
||||
|
||||
return ['clients' => $clients, 'income' => dashboardIncome($start, $end)];
|
||||
}
|
||||
|
||||
/** Miles per month over the chart's 12 months, and the total for the period. */
|
||||
function dashboardTrips($period) {
|
||||
$months = dashboardChartMonths($period);
|
||||
$from = $months[0] . '-01';
|
||||
$to = date('Y-m-t', strtotime(end($months) . '-01'));
|
||||
|
||||
return [
|
||||
'labels' => array_map(function ($m) {
|
||||
return date('M y', strtotime("$m-01"));
|
||||
}, $months),
|
||||
'miles' => dashboardMonthly("SELECT DATE_FORMAT(trip_date, '%Y-%m') AS m, SUM(trip_miles) AS v FROM trips
|
||||
WHERE trip_archived_at IS NULL AND trip_date BETWEEN '$from' AND '$to' GROUP BY m", $months),
|
||||
'period_total' => dashboardSum("SELECT SUM(trip_miles) FROM trips WHERE trip_archived_at IS NULL AND trip_date BETWEEN '{$period['start']}' AND '{$period['end']}'"),
|
||||
];
|
||||
}
|
||||
|
||||
/** Top five of a "SELECT name, color, SUM() AS v ... GROUP BY ..." query, with the rest summed as Other. */
|
||||
function dashboardTopFive($sql) {
|
||||
global $mysqli;
|
||||
|
||||
$rows = [];
|
||||
$result = mysqli_query($mysqli, $sql);
|
||||
while ($row = mysqli_fetch_assoc($result)) {
|
||||
if (floatval($row['v']) > 0) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
$top = array_slice($rows, 0, 5);
|
||||
$other = array_sum(array_map(function ($r) {
|
||||
return floatval($r['v']);
|
||||
}, array_slice($rows, 5)));
|
||||
|
||||
$out = ['labels' => [], 'values' => [], 'colors' => []];
|
||||
foreach ($top as $row) {
|
||||
$out['labels'][] = $row['name'];
|
||||
$out['values'][] = round(floatval($row['v']), 2);
|
||||
$out['colors'][] = preg_match('/^#[0-9a-f]{3,8}$/i', (string) ($row['color'] ?? '')) ? $row['color'] : null;
|
||||
}
|
||||
if ($other > 0) {
|
||||
$out['labels'][] = 'Other';
|
||||
$out['values'][] = round($other, 2);
|
||||
$out['colors'][] = null;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
function dashboardBreakdowns($period) {
|
||||
$start = $period['start'];
|
||||
$end = $period['end'];
|
||||
|
||||
return [
|
||||
'income_by_category' => dashboardTopFive("
|
||||
SELECT category_name AS name, category_color AS color, SUM(amount) AS v FROM (
|
||||
SELECT invoice_category_id AS category_id, payment_amount AS amount FROM payments
|
||||
JOIN invoices ON invoice_id = payment_invoice_id
|
||||
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
|
||||
) AS income
|
||||
JOIN categories USING (category_id)
|
||||
GROUP BY category_id, category_name, category_color ORDER BY v DESC"),
|
||||
'expenses_by_category' => dashboardTopFive("
|
||||
SELECT category_name AS name, category_color AS color, SUM(expense_amount) AS v FROM expenses
|
||||
JOIN categories ON expense_category_id = category_id
|
||||
WHERE expense_vendor_id > 0 AND expense_date BETWEEN '$start' AND '$end'
|
||||
GROUP BY category_id, category_name, category_color ORDER BY v DESC"),
|
||||
'expenses_by_vendor' => dashboardTopFive("
|
||||
SELECT vendor_name AS name, NULL AS color, SUM(expense_amount) AS v FROM expenses
|
||||
JOIN vendors ON expense_vendor_id = vendor_id
|
||||
WHERE expense_date BETWEEN '$start' AND '$end'
|
||||
GROUP BY vendor_id, vendor_name ORDER BY v DESC"),
|
||||
];
|
||||
}
|
||||
|
||||
/** Balance of every open account: opening balance, plus money in, minus money out. */
|
||||
function dashboardAccountBalances() {
|
||||
global $mysqli;
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT account_id, account_name, opening_balance
|
||||
+ COALESCE((SELECT SUM(payment_amount) FROM payments WHERE payment_account_id = account_id), 0)
|
||||
+ COALESCE((SELECT SUM(revenue_amount) FROM revenues WHERE revenue_account_id = account_id), 0)
|
||||
- COALESCE((SELECT SUM(expense_amount) FROM expenses WHERE expense_account_id = account_id), 0) AS balance
|
||||
FROM accounts
|
||||
WHERE account_archived_at IS NULL
|
||||
ORDER BY account_name
|
||||
");
|
||||
|
||||
$accounts = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$accounts[] = $row;
|
||||
}
|
||||
return $accounts;
|
||||
}
|
||||
|
||||
function dashboardLatestIncome($limit = 5) {
|
||||
global $mysqli;
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT payment_amount, payment_date, invoice_id, invoice_prefix, invoice_number, invoice_client_id, client_name
|
||||
FROM payments
|
||||
JOIN invoices ON payment_invoice_id = invoice_id
|
||||
JOIN clients ON invoice_client_id = client_id
|
||||
WHERE 1 = 1 " . clientScopeSql('invoice_client_id') . "
|
||||
ORDER BY payment_date DESC, payment_id DESC
|
||||
LIMIT " . intval($limit));
|
||||
|
||||
$rows = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
function dashboardLatestExpenses($limit = 5) {
|
||||
global $mysqli;
|
||||
|
||||
$sql = mysqli_query($mysqli, "
|
||||
SELECT expense_amount, expense_date, vendor_name, category_name
|
||||
FROM expenses
|
||||
JOIN vendors ON expense_vendor_id = vendor_id
|
||||
LEFT JOIN categories ON expense_category_id = category_id
|
||||
ORDER BY expense_date DESC, expense_id DESC
|
||||
LIMIT " . intval($limit));
|
||||
|
||||
$rows = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
279
js/dashboard.js
Normal file
279
js/dashboard.js
Normal file
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
* ITFlow - dashboard charts.
|
||||
*
|
||||
* agent/dashboard.php hands the numbers over as window.itflowDashboardData;
|
||||
* this draws them. Colours are read from the page's own CSS variables when
|
||||
* the charts are built, so they follow the theme accent and dark mode the
|
||||
* same way everything else on the page does.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const data = window.itflowDashboardData;
|
||||
if (!data || typeof Chart === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const base = typeof itflowChartDefaults === 'function' ? itflowChartDefaults() : { text: '#6c757d', grid: 'rgba(0,0,0,.1)' };
|
||||
const root = getComputedStyle(document.body);
|
||||
|
||||
function cssVar(name, fallback) {
|
||||
return (root.getPropertyValue(name) || '').trim() || fallback;
|
||||
}
|
||||
|
||||
function alpha(color, a) {
|
||||
// #rrggbb -> rgba(); anything else is returned as is
|
||||
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color);
|
||||
return m ? 'rgba(' + parseInt(m[1], 16) + ',' + parseInt(m[2], 16) + ',' + parseInt(m[3], 16) + ',' + a + ')' : color;
|
||||
}
|
||||
|
||||
const colors = {
|
||||
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'),
|
||||
grid: base.grid
|
||||
};
|
||||
// For slices with no colour of their own (vendors, uncoloured categories)
|
||||
const palette = [colors.accent, colors.info, colors.success, colors.warning, cssVar('--bs-purple', '#6f42c1'), colors.danger];
|
||||
|
||||
let money;
|
||||
try {
|
||||
money = new Intl.NumberFormat(undefined, { style: 'currency', currency: data.currency || 'USD', maximumFractionDigits: 0 });
|
||||
} catch (e) {
|
||||
money = new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 });
|
||||
}
|
||||
const moneyShort = new Intl.NumberFormat(undefined, { notation: 'compact', maximumFractionDigits: 1 });
|
||||
let moneyCompact;
|
||||
try {
|
||||
moneyCompact = new Intl.NumberFormat(undefined, { style: 'currency', currency: data.currency || 'USD', notation: 'compact', maximumFractionDigits: 1 });
|
||||
} catch (e) {
|
||||
moneyCompact = moneyShort;
|
||||
}
|
||||
const share = new Intl.NumberFormat(undefined, { style: 'percent', maximumFractionDigits: 0 });
|
||||
|
||||
const legend = { position: 'bottom', labels: { boxWidth: 10, boxHeight: 10, usePointStyle: true, padding: 14 } };
|
||||
|
||||
function draw(id, config) {
|
||||
const canvas = document.getElementById(id);
|
||||
if (!canvas) {
|
||||
return null;
|
||||
}
|
||||
config.options = Object.assign({ responsive: true, maintainAspectRatio: false }, config.options || {});
|
||||
return new Chart(canvas, config);
|
||||
}
|
||||
|
||||
function axes(tickFormat, stacked) {
|
||||
return {
|
||||
x: { stacked: !!stacked, grid: { display: false }, ticks: { maxRotation: 0, autoSkipPadding: 10 } },
|
||||
y: { stacked: !!stacked, beginAtZero: true, grid: { color: colors.grid }, border: { display: false }, ticks: { maxTicksLimit: 5, callback: tickFormat } }
|
||||
};
|
||||
}
|
||||
|
||||
// In a stack, only the top bar gets rounded corners: a bar with something
|
||||
// stacked on it in that column stays square
|
||||
function roundUnless(above) {
|
||||
return function (c) {
|
||||
return above[c.dataIndex] > 0 ? 0 : 3;
|
||||
};
|
||||
}
|
||||
|
||||
function hoursMinutes(hours) {
|
||||
const minutes = Math.round(hours * 60);
|
||||
const h = Math.floor(minutes / 60);
|
||||
const m = minutes % 60;
|
||||
return h ? (m ? h + 'h ' + m + 'm' : h + 'h') : m + 'm';
|
||||
}
|
||||
|
||||
/* Tickets opened vs resolved per week */
|
||||
if (data.ticket_trend) {
|
||||
draw('dashTicketTrend', {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: data.ticket_trend.map(function (w) { return w.label; }),
|
||||
datasets: [
|
||||
{ label: 'Opened', data: data.ticket_trend.map(function (w) { return w.opened; }), backgroundColor: colors.accent, borderRadius: 3, maxBarThickness: 14 },
|
||||
{ label: 'Resolved', data: data.ticket_trend.map(function (w) { return w.resolved; }), backgroundColor: alpha(colors.success, 0.75), borderRadius: 3, maxBarThickness: 14 }
|
||||
]
|
||||
},
|
||||
options: {
|
||||
plugins: { legend: legend },
|
||||
scales: axes(function (v) { return Number.isInteger(v) ? v : ''; })
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* Cash flow: income and expense bars, last year's income as a line. From
|
||||
this month on, what is expected in and out sits on top of each bar as a
|
||||
lighter "ghost" of the same colour. */
|
||||
if (data.cash_flow) {
|
||||
const cf = data.cash_flow;
|
||||
const forecast = cf.expected_income.some(function (v) { return v > 0; }) || cf.expected_expenses.some(function (v) { return v > 0; });
|
||||
|
||||
function ghost(color) {
|
||||
return {
|
||||
backgroundColor: alpha(color, 0.2),
|
||||
borderColor: alpha(color, 0.85),
|
||||
borderWidth: { top: 1.5, left: 1.5, right: 1.5, bottom: 0 },
|
||||
borderRadius: 3,
|
||||
maxBarThickness: 22,
|
||||
forecast: true
|
||||
};
|
||||
}
|
||||
|
||||
const datasets = [
|
||||
{ label: 'Income', data: cf.income, backgroundColor: alpha(colors.success, 0.8), borderRadius: roundUnless(cf.expected_income), maxBarThickness: 22, stack: 'income' }
|
||||
];
|
||||
if (forecast) {
|
||||
datasets.push(Object.assign({ label: 'Expected income', data: cf.expected_income, stack: 'income' }, ghost(colors.success)));
|
||||
}
|
||||
datasets.push({ label: 'Expenses', data: cf.expenses, backgroundColor: alpha(colors.danger, 0.75), borderRadius: roundUnless(cf.expected_expenses), maxBarThickness: 22, stack: 'expenses' });
|
||||
if (forecast) {
|
||||
datasets.push(Object.assign({ label: 'Expected expenses', data: cf.expected_expenses, stack: 'expenses' }, ghost(colors.danger)));
|
||||
}
|
||||
datasets.push({ type: 'line', label: 'Income last year', data: cf.income_last_year, borderColor: colors.muted, borderDash: [4, 4], borderWidth: 1.5, pointRadius: 0, tension: 0.3, stack: 'last-year', order: -1 });
|
||||
|
||||
draw('dashCashFlow', {
|
||||
type: 'bar',
|
||||
data: { labels: cf.labels, datasets: datasets },
|
||||
options: {
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: {
|
||||
legend: legend,
|
||||
tooltip: {
|
||||
// Leave out the nothing: no expected amount in a past month, no actuals in a future one
|
||||
filter: function (item) {
|
||||
if (item.dataset.forecast) {
|
||||
return item.parsed.y > 0;
|
||||
}
|
||||
return item.dataset.type === 'line' || cf.first_future < 0 || item.dataIndex < cf.first_future;
|
||||
},
|
||||
callbacks: { label: function (c) { return c.dataset.label + ': ' + money.format(c.parsed.y); } }
|
||||
}
|
||||
},
|
||||
scales: axes(function (v) { return moneyShort.format(v); }, true)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* My hours this week, billable under not billable */
|
||||
if (data.time_week) {
|
||||
const tw = data.time_week;
|
||||
const other = tw.map(function (d) { return d.other; });
|
||||
draw('dashTimeWeek', {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: tw.map(function (d) { return d.label; }),
|
||||
datasets: [
|
||||
{ label: 'Billable', data: tw.map(function (d) { return d.billable; }), backgroundColor: colors.accent, borderRadius: roundUnless(other), maxBarThickness: 18, stack: 'time' },
|
||||
{ label: 'Not billable', data: other, backgroundColor: colors.faint, borderRadius: 3, maxBarThickness: 18, stack: 'time' }
|
||||
]
|
||||
},
|
||||
options: {
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
filter: function (item) { return item.parsed.y > 0; },
|
||||
callbacks: { label: function (c) { return c.dataset.label + ': ' + hoursMinutes(c.parsed.y); } }
|
||||
}
|
||||
},
|
||||
scales: axes(function (v) { return Number.isInteger(v) ? v + 'h' : ''; }, true)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* The three donuts: the total in the hole, and a legend underneath with
|
||||
each slice's amount and share. The legend is plain HTML so long vendor
|
||||
and category names truncate with CSS instead of wrapping the card. */
|
||||
function donut(id, set) {
|
||||
if (!set || !set.values.length) {
|
||||
return;
|
||||
}
|
||||
let next = 0;
|
||||
const slices = set.colors.map(function (c, i) {
|
||||
if (set.labels[i] === 'Other') {
|
||||
return alpha(colors.muted, 0.5);
|
||||
}
|
||||
return c || palette[next++ % palette.length];
|
||||
});
|
||||
const total = set.values.reduce(function (sum, v) { return sum + v; }, 0);
|
||||
|
||||
const chart = draw(id, {
|
||||
type: 'doughnut',
|
||||
data: { labels: set.labels, datasets: [{ data: set.values, backgroundColor: slices, borderWidth: 0, hoverOffset: 6 }] },
|
||||
options: {
|
||||
cutout: '72%',
|
||||
layout: { padding: 6 },
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: { callbacks: { label: function (c) { return c.label + ': ' + money.format(c.parsed); } } }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const totalEl = document.querySelector('[data-donut-total="' + id + '"]');
|
||||
if (totalEl) {
|
||||
totalEl.textContent = moneyCompact.format(total);
|
||||
totalEl.title = money.format(total);
|
||||
}
|
||||
|
||||
const list = document.querySelector('[data-donut-legend="' + id + '"]');
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
set.labels.forEach(function (label, i) {
|
||||
const item = document.createElement('li');
|
||||
const parts = ['swatch', 'label', 'value', 'share'].map(function (name) {
|
||||
const span = document.createElement('span');
|
||||
span.className = 'itflow-dash-legend-' + name;
|
||||
item.appendChild(span);
|
||||
return span;
|
||||
});
|
||||
parts[0].style.backgroundColor = slices[i];
|
||||
parts[1].textContent = label;
|
||||
parts[1].title = label;
|
||||
parts[2].textContent = money.format(set.values[i]);
|
||||
parts[3].textContent = share.format(total ? set.values[i] / total : 0);
|
||||
|
||||
// Pointing at a row lifts its slice out of the ring
|
||||
if (chart) {
|
||||
item.addEventListener('mouseenter', function () {
|
||||
chart.setActiveElements([{ datasetIndex: 0, index: i }]);
|
||||
chart.update();
|
||||
});
|
||||
item.addEventListener('mouseleave', function () {
|
||||
chart.setActiveElements([]);
|
||||
chart.update();
|
||||
});
|
||||
}
|
||||
list.appendChild(item);
|
||||
});
|
||||
}
|
||||
if (data.breakdowns) {
|
||||
donut('dashIncomeByCategory', data.breakdowns.income_by_category);
|
||||
donut('dashExpensesByCategory', data.breakdowns.expenses_by_category);
|
||||
donut('dashExpensesByVendor', data.breakdowns.expenses_by_vendor);
|
||||
}
|
||||
|
||||
/* Miles per month */
|
||||
if (data.trips) {
|
||||
draw('dashTrips', {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: data.trips.labels,
|
||||
datasets: [{
|
||||
label: 'Miles', data: data.trips.miles, borderColor: colors.accent, backgroundColor: alpha(colors.accent, 0.12),
|
||||
fill: true, cubicInterpolationMode: 'monotone', pointRadius: 2, borderWidth: 2
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
plugins: { legend: { display: false } },
|
||||
scales: axes(function (v) { return moneyShort.format(v); })
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user