From ac00bf1bda4b047027271eef4e770774b600699c Mon Sep 17 00:00:00 2001 From: Adam Daley Date: Mon, 18 May 2026 08:57:37 +0100 Subject: [PATCH] Refactor dashboard and enhance charts with transaction support (#3581) * Support optional `transaction.ipn_hash` with repair * Refactor dashboard tables and product sales card * Refactor dashboard client/avatar and activity tables * Replace ApexCharts with Chart.js sparklines * Preserve decimal income and enhance chart tooltips * Normalize admin navigation URIs * Fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * refactor(Stats): split _genFlotArray into typed _genFlotArrayInt and _genFlotArrayFloat helpers Agent-Logs-Url: https://github.com/FOSSBilling/FOSSBilling/sessions/fb8520de-2038-4e33-af3e-3520d999c939 Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> * fix(Invoice): use processTransaction return value in markAsPaidByAdmin instead of returning true unconditionally Agent-Logs-Url: https://github.com/FOSSBilling/FOSSBilling/sessions/fc7131ac-81aa-416b-af57-7d65d9bd20c3 Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> * fix(Invoice): remove runtime DDL migration from ServiceTransaction; simplify supportsTransactionIpnHash to schema-check only Agent-Logs-Url: https://github.com/FOSSBilling/FOSSBilling/sessions/e4b07e3f-7660-4fba-84c0-0105d6b2a318 Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> --------- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> --- package-lock.json | 26 +- src/modules/Extension/Service.php | 40 ++- src/modules/Invoice/Controller/Admin.php | 2 +- src/modules/Invoice/Service.php | 4 +- src/modules/Invoice/ServiceTransaction.php | 33 ++- src/modules/Stats/Service.php | 33 ++- .../admin_default/assets/fossbilling.js | 2 - .../admin_default/assets/js/fossbilling.js | 5 + .../admin_default/assets/js/ui/charts.js | 198 +++++++++++++ .../html/layout_default.html.twig | 6 +- .../html/mod_index_dashboard.html.twig | 181 ++++++------ src/themes/admin_default/package.json | 2 +- .../modules/Extension/ServiceTest.php | 13 +- tests-legacy/modules/Invoice/ServiceTest.php | 50 ++++ .../Invoice/ServiceTransactionTest.php | 270 ++++++++++++++++++ tests-legacy/modules/Stats/ServiceTest.php | 62 ++++ 16 files changed, 799 insertions(+), 128 deletions(-) create mode 100644 src/themes/admin_default/assets/js/ui/charts.js diff --git a/package-lock.json b/package-lock.json index a9045879d..531242ea3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1403,6 +1403,12 @@ "node": ">=18" } }, + "node_modules/@kurkle/color": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", + "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==", + "license": "MIT" + }, "node_modules/@melloware/coloris": { "version": "0.25.0", "resolved": "https://registry.npmjs.org/@melloware/coloris/-/coloris-0.25.0.tgz", @@ -2223,12 +2229,6 @@ "dev": true, "license": "MIT" }, - "node_modules/apexcharts": { - "version": "5.12.0", - "resolved": "https://registry.npmjs.org/apexcharts/-/apexcharts-5.12.0.tgz", - "integrity": "sha512-vNCw62M5rhVg09FHFCL/ztpH7VlTOF8/+lWLUVjBdQffIAgQaxtyDGfojCyYoZHM3Hh17srWwz6rrD/XzblRSw==", - "license": "SEE LICENSE IN LICENSE" - }, "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", @@ -2467,6 +2467,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/chart.js": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", + "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==", + "license": "MIT", + "dependencies": { + "@kurkle/color": "^0.3.0" + }, + "engines": { + "pnpm": ">=8" + } + }, "node_modules/chokidar": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", @@ -5622,7 +5634,7 @@ "@dicebear/identicon": "^9.0.0", "@melloware/coloris": "^0.25.0", "@tabler/core": "^1.2.0", - "apexcharts": "^5.0.0", + "chart.js": "^4.5.1", "flag-icons": "^7.2.3", "litepicker": "^2.0.12", "sortable-tablesort": "^4.1.7", diff --git a/src/modules/Extension/Service.php b/src/modules/Extension/Service.php index 981a2f10c..eff33a52c 100644 --- a/src/modules/Extension/Service.php +++ b/src/modules/Extension/Service.php @@ -279,8 +279,6 @@ class Service implements InjectionAwareInterface public function getAdminNavigation($admin, $url = null) { $staff_service = $this->di['mod_service']('staff'); - $current_mod = null; - $current_url = null; $nav = []; $subpages = []; @@ -301,6 +299,7 @@ class Service implements InjectionAwareInterface $l = $n['group']['location']; unset($n['group']['location']); $n['group']['active'] = false; + $n['group']['uri'] = $this->normalizeNavigationUri($n['group']['uri'] ?? null); $nav[$l] = $n['group']; } @@ -331,17 +330,54 @@ class Service implements InjectionAwareInterface $l = $page['location']; unset($page['location']); + $page['uri'] = $this->normalizeNavigationUri($page['uri'] ?? null); $nav[$l]['subpages'][] = $page; } // submenu sorting foreach ($nav as &$group) { $group['subpages'] = $this->di['tools']->sortByOneKey($group['subpages'], 'index'); + $group['uri'] = $this->resolveNavigationGroupUri($group); } return $nav; } + private function resolveNavigationGroupUri(array $group): ?string + { + $groupUri = $this->normalizeNavigationUri($group['uri'] ?? null); + if (!empty($groupUri)) { + return $groupUri; + } + + foreach ($group['subpages'] ?? [] as $subpage) { + $subpageUri = $this->normalizeNavigationUri($subpage['uri'] ?? null); + if (!empty($subpageUri)) { + return $subpageUri; + } + } + + return null; + } + + private function normalizeNavigationUri(?string $uri): ?string + { + if (is_null($uri)) { + return null; + } + + $uri = trim($uri); + if ($uri === '') { + return null; + } + + if (preg_match('/^(?:[a-z][a-z0-9+.-]*:|\/|#|\?)/i', $uri) === 1) { + return $uri; + } + + return $this->di['url']->adminLink(ltrim($uri, '/')); + } + /** * @return \Model_Extension */ diff --git a/src/modules/Invoice/Controller/Admin.php b/src/modules/Invoice/Controller/Admin.php index ec674d224..95dc7af20 100644 --- a/src/modules/Invoice/Controller/Admin.php +++ b/src/modules/Invoice/Controller/Admin.php @@ -35,7 +35,7 @@ class Admin implements \FOSSBilling\InjectionAwareInterface 'index' => 400, 'location' => 'invoice', 'label' => __trans('Invoices'), - 'uri' => 'invoice', + 'uri' => $this->di['url']->adminLink('invoice'), 'class' => 'invoices', ], 'subpages' => [ diff --git a/src/modules/Invoice/Service.php b/src/modules/Invoice/Service.php index f7da3076e..465555a59 100644 --- a/src/modules/Invoice/Service.php +++ b/src/modules/Invoice/Service.php @@ -528,7 +528,9 @@ class Service implements InjectionAwareInterface 'txn_id' => $transactionId, ]); - return $transactionService->processTransaction($newtx); + $result = $transactionService->processTransaction($newtx); + + return (bool) $result; } return $this->markAsPaid($invoice, false, $execute); diff --git a/src/modules/Invoice/ServiceTransaction.php b/src/modules/Invoice/ServiceTransaction.php index d6bea5a3f..907c9f82d 100644 --- a/src/modules/Invoice/ServiceTransaction.php +++ b/src/modules/Invoice/ServiceTransaction.php @@ -21,6 +21,7 @@ class ServiceTransaction implements InjectionAwareInterface private const int PROCESSING_RECOVERY_TIMEOUT = 300; protected ?\Pimple\Container $di = null; + private ?bool $transactionIpnHashColumnExists = null; public function setDi(\Pimple\Container $di): void { @@ -139,7 +140,8 @@ class ServiceTransaction implements InjectionAwareInterface // Fallback dedupe: compute a canonical hash of the IPN payload and // look up an existing transaction by (gateway_id, ipn_hash). $ipn_hash = $this->ipnHash($ipn); - if (!empty($data['gateway_id']) && !empty($ipn_hash)) { + $supportsIpnHash = $this->supportsTransactionIpnHash(); + if ($supportsIpnHash && !empty($data['gateway_id']) && !empty($ipn_hash)) { $existingByHash = $this->di['db']->findOne('Transaction', 'gateway_id = ? AND ipn_hash = ?', [$data['gateway_id'], $ipn_hash]); if ($existingByHash instanceof \Model_Transaction) { $this->di['logger']->info('Duplicate transaction detected by IPN hash, returning existing transaction #%s', $existingByHash->id); @@ -152,7 +154,9 @@ class ServiceTransaction implements InjectionAwareInterface $transaction->gateway_id = $data['gateway_id'] ?? null; $transaction->invoice_id = $data['invoice_id'] ?? null; $transaction->txn_id = $data['txn_id'] ?? null; - $transaction->ipn_hash = $ipn_hash ?? null; + if ($supportsIpnHash) { + $transaction->ipn_hash = $ipn_hash ?? null; + } $transaction->status = 'received'; $transaction->ip = $this->di['request']->getClientIp(); $transaction->ipn = json_encode($ipn); @@ -168,6 +172,31 @@ class ServiceTransaction implements InjectionAwareInterface return $newId; } + private function supportsTransactionIpnHash(): bool + { + if ($this->transactionIpnHashColumnExists !== null) { + return $this->transactionIpnHashColumnExists; + } + + try { + $schemaManager = $this->di['dbal']->createSchemaManager(); + $columns = array_map(static fn ($column) => $column->getName(), $schemaManager->listTableColumns('transaction')); + $indexes = array_map(static fn ($index) => $index->getName(), $schemaManager->listTableIndexes('transaction')); + + $supported = in_array('ipn_hash', $columns, true) && in_array('transaction_ipn_hash_idx', $indexes, true); + } catch (\Throwable $e) { + if (isset($this->di['logger'])) { + $this->di['logger']->warn('Could not determine whether transaction.ipn_hash exists; disabling IPN hash dedupe: %s', $e->getMessage()); + } + + return false; + } + + $this->transactionIpnHashColumnExists = $supported; + + return $this->transactionIpnHashColumnExists; + } + public function delete(\Model_Transaction $model): bool { $id = $model->id; diff --git a/src/modules/Stats/Service.php b/src/modules/Stats/Service.php index 99c46e243..177e212c0 100644 --- a/src/modules/Stats/Service.php +++ b/src/modules/Stats/Service.php @@ -239,7 +239,7 @@ class Service implements InjectionAwareInterface $results = $result->fetchAllKeyValue(); - return $this->_genFlotArray($results, $time_from, $time_to); + return $this->_genFlotArrayFloat($results, $time_from, $time_to); } public function getIncome($data) @@ -272,7 +272,7 @@ class Service implements InjectionAwareInterface $results = $result->fetchAllKeyValue(); - return $this->_genFlotArray($results, $time_from, $time_to); + return $this->_genFlotArrayFloat($results, $time_from, $time_to); } public function getClientCountries($data) @@ -355,24 +355,41 @@ class Service implements InjectionAwareInterface $results = $result->fetchAllKeyValue(); - return $this->_genFlotArray($results, $time_from, $time_to); + return $this->_genFlotArrayInt($results, $time_from, $time_to); } /** * @param int $time_from * @param int $time_to * - * @return int[][] + * @return array */ - private function _genFlotArray($results, $time_from, $time_to): array + private function _genFlotArrayInt(array $results, int $time_from, int $time_to): array { $data = []; - // Loop between timestamps, 1 day at a time do { $time_from = strtotime('+1 day', $time_from); $dom = date('Y-m-d', $time_from); - $c = $results[$dom] ?? 0; - $data[] = [$time_from * 1000, (int) $c]; + $data[] = [$time_from * 1000, (int) ($results[$dom] ?? 0)]; + } while ($time_to > $time_from); + array_pop($data); + + return $data; + } + + /** + * @param int $time_from + * @param int $time_to + * + * @return array + */ + private function _genFlotArrayFloat(array $results, int $time_from, int $time_to): array + { + $data = []; + do { + $time_from = strtotime('+1 day', $time_from); + $dom = date('Y-m-d', $time_from); + $data[] = [$time_from * 1000, round((float) ($results[$dom] ?? 0), 2)]; } while ($time_to > $time_from); array_pop($data); diff --git a/src/themes/admin_default/assets/fossbilling.js b/src/themes/admin_default/assets/fossbilling.js index 4af2f2813..e34a267a4 100644 --- a/src/themes/admin_default/assets/fossbilling.js +++ b/src/themes/admin_default/assets/fossbilling.js @@ -4,12 +4,10 @@ import { coloris, init } from '@melloware/coloris'; import * as tabler from '@tabler/core/js/tabler.js'; import './js/tomselect'; import './js/datepicker'; -import ApexCharts from 'apexcharts'; import './js/ui/theme_settings'; import './js/fossbilling'; import 'sortable-tablesort/dist/sortable.min.js'; -globalThis.ApexCharts = ApexCharts; globalThis.bootstrap = tabler.bootstrap; init(); diff --git a/src/themes/admin_default/assets/js/fossbilling.js b/src/themes/admin_default/assets/js/fossbilling.js index ebaa3a307..09ce15c5c 100644 --- a/src/themes/admin_default/assets/js/fossbilling.js +++ b/src/themes/admin_default/assets/js/fossbilling.js @@ -1,4 +1,5 @@ import backToTop from "./ui/backToTop"; +import { renderTimeSeriesSparkline } from "./ui/charts"; globalThis.FOSSBilling = { message: (message, type = "info") => { @@ -87,6 +88,10 @@ globalThis.FOSSBilling = { if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; + }, + + charts: { + renderTimeSeriesSparkline, } }; diff --git a/src/themes/admin_default/assets/js/ui/charts.js b/src/themes/admin_default/assets/js/ui/charts.js new file mode 100644 index 000000000..2026b00e5 --- /dev/null +++ b/src/themes/admin_default/assets/js/ui/charts.js @@ -0,0 +1,198 @@ +import Chart from 'chart.js/auto'; + +const chartInstances = new WeakMap(); + +function getChartElement(target) { + if (typeof target === 'string') { + return document.getElementById(target) || document.querySelector(target); + } + + return target instanceof HTMLElement ? target : null; +} + +function getThemeMode() { + const rootTheme = document.documentElement.getAttribute('data-bs-theme'); + const storedTheme = localStorage.getItem('theme'); + + return rootTheme || storedTheme || 'light'; +} + +function getThemeColors() { + if (getThemeMode() === 'dark') { + return { + border: '#91bbed', + fill: 'rgba(145, 187, 237, 0.16)', + }; + } + + return { + border: '#206bc4', + fill: 'rgba(32, 107, 196, 0.16)', + }; +} + +function normalizeTimeSeriesData(data) { + if (!Array.isArray(data)) { + return []; + } + + return data + .filter(point => Array.isArray(point) && point.length >= 2) + .map(point => ({ + x: Number(point[0]), + y: Number(point[1]), + })) + .filter(point => Number.isFinite(point.x) && Number.isFinite(point.y)); +} + +function formatTooltipDate(timestamp) { + return new Intl.DateTimeFormat(undefined, { + year: 'numeric', + month: 'short', + day: 'numeric', + }).format(new Date(timestamp)); +} + +function formatTooltipValue(value, options) { + const numericValue = Number(value); + if (!Number.isFinite(numericValue)) { + return String(value); + } + + if (options.valueFormat === 'currency' && options.currency) { + try { + return new Intl.NumberFormat(undefined, { + style: 'currency', + currency: options.currency, + currencyDisplay: 'narrowSymbol', + }).format(numericValue); + } catch (error) { + // Ignore invalid currency codes and fall back to numeric formatting. + } + } + + return new Intl.NumberFormat(undefined, { + maximumFractionDigits: 0, + }).format(numericValue); +} + +export function renderTimeSeriesSparkline(target, data, options = {}) { + const container = getChartElement(target); + if (!container) { + return null; + } + + const existingChart = chartInstances.get(container); + if (existingChart) { + existingChart.destroy(); + chartInstances.delete(container); + } + + const series = normalizeTimeSeriesData(data); + const label = options.label || 'Series'; + const height = Number.isFinite(options.height) ? options.height : 140; + const { border, fill } = getThemeColors(); + const firstPoint = series[0] || null; + const lastPoint = series[series.length - 1] || null; + + container.replaceChildren(); + container.style.width = '100%'; + container.style.height = `${height}px`; + + const canvas = document.createElement('canvas'); + canvas.setAttribute('aria-label', label); + canvas.setAttribute('role', 'img'); + container.appendChild(canvas); + + const chart = new Chart(canvas, { + type: 'line', + data: { + datasets: [{ + label, + data: series, + parsing: false, + borderColor: border, + backgroundColor: fill, + borderWidth: 2, + tension: 0.4, + cubicInterpolationMode: 'monotone', + fill: true, + pointRadius: 0, + pointHoverRadius: options.showTooltip ? 3 : 0, + pointHitRadius: options.showTooltip ? 16 : 8, + borderCapStyle: 'round', + }], + }, + options: { + responsive: true, + maintainAspectRatio: false, + animation: false, + normalized: true, + interaction: { + mode: 'nearest', + axis: 'x', + intersect: false, + }, + layout: { + padding: 0, + }, + plugins: { + legend: { + display: false, + }, + tooltip: { + enabled: Boolean(options.showTooltip), + displayColors: false, + callbacks: { + title(items) { + const timestamp = items[0]?.raw?.x; + return Number.isFinite(timestamp) ? formatTooltipDate(timestamp) : ''; + }, + label(context) { + const formattedValue = formatTooltipValue(context.raw?.y, options); + return `${label}: ${formattedValue}`; + }, + }, + }, + }, + scales: { + x: { + type: 'linear', + bounds: 'data', + display: false, + min: firstPoint ? firstPoint.x : undefined, + max: lastPoint ? lastPoint.x : undefined, + offset: false, + grid: { + display: false, + drawBorder: false, + }, + border: { + display: false, + }, + }, + y: { + display: false, + beginAtZero: true, + grace: 0, + grid: { + display: false, + drawBorder: false, + }, + border: { + display: false, + }, + }, + }, + elements: { + line: { + capBezierPoints: true, + }, + }, + }, + }); + + chartInstances.set(container, chart); + + return chart; +} diff --git a/src/themes/admin_default/html/layout_default.html.twig b/src/themes/admin_default/html/layout_default.html.twig index 2ffae6533..3337049e5 100644 --- a/src/themes/admin_default/html/layout_default.html.twig +++ b/src/themes/admin_default/html/layout_default.html.twig @@ -150,13 +150,13 @@ {% for location, group in navigation %} {% if group.subpages %}