reports-charts.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /**
  2. * reports-charts.js
  3. * Chart initialization and PDF export logic for the reports view.
  4. * Reads chart data from the #chart-data JSON script tag injected by the template.
  5. */
  6. document.addEventListener("DOMContentLoaded", function () {
  7. const chartDataEl = document.getElementById("chart-data");
  8. if (!chartDataEl) return;
  9. const chartData = JSON.parse(chartDataEl.textContent);
  10. const CHART_COLORS = [
  11. "#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6",
  12. "#EC4899", "#14B8A6", "#F97316", "#64748B", "#84CC16",
  13. "#06B6D4", "#D946EF", "#F43F5E", "#0EA5E9", "#22C55E",
  14. "#EAB308", "#F43F5E", "#8B5CF6", "#EC4899", "#14B8A6",
  15. ];
  16. function getTextColor() {
  17. return document.documentElement.classList.contains("dark")
  18. ? "#d1d5db"
  19. : "#374151";
  20. }
  21. function getBorderColor() {
  22. return document.documentElement.classList.contains("dark")
  23. ? "#374151"
  24. : "#fff";
  25. }
  26. // ─── Bar chart helper ─────────────────────────────────────────────────────
  27. function buildBarChart(canvasId, payload, label, valueSuffix) {
  28. const el = document.getElementById(canvasId);
  29. if (!el || !payload) return;
  30. new Chart(el.getContext("2d"), {
  31. type: "bar",
  32. data: {
  33. labels: payload.labels,
  34. datasets: [
  35. {
  36. label: label,
  37. data: payload.data,
  38. backgroundColor: CHART_COLORS.slice(0, payload.data.length),
  39. borderColor: CHART_COLORS.slice(0, payload.data.length).map(
  40. (c) => c + "DD"
  41. ),
  42. borderWidth: 1,
  43. },
  44. ],
  45. },
  46. options: {
  47. responsive: true,
  48. maintainAspectRatio: false,
  49. plugins: {
  50. legend: { display: false },
  51. tooltip: {
  52. mode: "index",
  53. intersect: false,
  54. callbacks: {
  55. label: function (context) {
  56. return `${context.dataset.label}: ${context.raw.toFixed(2)} ${valueSuffix}`;
  57. },
  58. },
  59. },
  60. datalabels: { display: false },
  61. },
  62. scales: {
  63. y: {
  64. beginAtZero: true,
  65. title: { display: true, text: label },
  66. ticks: { color: getTextColor() },
  67. },
  68. x: {
  69. ticks: { autoSkip: false, color: getTextColor() },
  70. },
  71. },
  72. },
  73. });
  74. }
  75. // ─── Pie chart helper ─────────────────────────────────────────────────────
  76. function buildPieChart(canvasId, payload) {
  77. const el = document.getElementById(canvasId);
  78. if (!el || !payload) return;
  79. const colors = payload.colors || CHART_COLORS.slice(0, payload.data.length);
  80. new Chart(el.getContext("2d"), {
  81. type: "pie",
  82. data: {
  83. labels: payload.labels,
  84. datasets: [
  85. {
  86. data: payload.data,
  87. backgroundColor: colors,
  88. borderColor: getBorderColor(),
  89. borderWidth: 2,
  90. },
  91. ],
  92. },
  93. options: {
  94. responsive: true,
  95. maintainAspectRatio: false,
  96. plugins: {
  97. legend: {
  98. position: "right",
  99. labels: { font: { size: 12 }, color: getTextColor() },
  100. },
  101. tooltip: {
  102. callbacks: {
  103. label: function (context) {
  104. const total = context.dataset.data.reduce((a, b) => a + b, 0);
  105. const pct = ((context.raw / total) * 100).toFixed(1);
  106. return `${context.label}: ${context.raw} (${pct}%)`;
  107. },
  108. },
  109. },
  110. datalabels: {
  111. formatter: function (value, ctx) {
  112. const total = ctx.chart.data.datasets[0].data.reduce(
  113. (a, b) => a + b,
  114. 0
  115. );
  116. const pct = ((value / total) * 100).toFixed(1);
  117. return pct > 3 ? `${pct}%` : "";
  118. },
  119. color: "#fff",
  120. font: { weight: "bold", size: 12 },
  121. },
  122. },
  123. },
  124. plugins: [ChartDataLabels],
  125. });
  126. }
  127. // ─── Hourly traffic chart ────────────────────────────────────────────────
  128. function buildHourlyActivityChart(payload) {
  129. const el = document.getElementById("hourlyActivityChart");
  130. if (!el || !payload) return;
  131. const labels = (payload.labels || []).map(
  132. (hour) => `${String(hour).padStart(2, "0")}:00`
  133. );
  134. new Chart(el.getContext("2d"), {
  135. data: {
  136. labels: labels,
  137. datasets: [
  138. {
  139. type: "bar",
  140. label: chartData.chartLabels.requests,
  141. data: payload.requests || [],
  142. yAxisID: "requests",
  143. backgroundColor: "#3B82F6B3",
  144. borderColor: "#2563EB",
  145. borderWidth: 1,
  146. borderRadius: 4,
  147. },
  148. {
  149. type: "line",
  150. label: chartData.chartLabels.dataMb,
  151. data: payload.data || [],
  152. yAxisID: "data",
  153. borderColor: "#8B5CF6",
  154. backgroundColor: "#8B5CF633",
  155. pointBackgroundColor: "#8B5CF6",
  156. pointRadius: 3,
  157. tension: 0.25,
  158. fill: true,
  159. },
  160. ],
  161. },
  162. options: {
  163. responsive: true,
  164. maintainAspectRatio: false,
  165. interaction: { mode: "index", intersect: false },
  166. plugins: {
  167. legend: { labels: { color: getTextColor() } },
  168. tooltip: {
  169. callbacks: {
  170. label: function (context) {
  171. const value = Number(context.raw || 0);
  172. const suffix =
  173. context.dataset.yAxisID === "data"
  174. ? ` ${chartData.chartLabels.dataUnit}`
  175. : "";
  176. return `${context.dataset.label}: ${value.toLocaleString(undefined, {
  177. maximumFractionDigits: 2,
  178. })}${suffix}`;
  179. },
  180. },
  181. },
  182. datalabels: { display: false },
  183. },
  184. scales: {
  185. x: {
  186. ticks: { autoSkip: true, maxTicksLimit: 12, color: getTextColor() },
  187. },
  188. requests: {
  189. position: "left",
  190. beginAtZero: true,
  191. title: { display: true, text: chartData.chartLabels.requests, color: getTextColor() },
  192. ticks: { color: getTextColor(), precision: 0 },
  193. },
  194. data: {
  195. position: "right",
  196. beginAtZero: true,
  197. title: { display: true, text: chartData.chartLabels.dataMb, color: getTextColor() },
  198. ticks: { color: getTextColor() },
  199. grid: { drawOnChartArea: false },
  200. },
  201. },
  202. },
  203. });
  204. }
  205. // ─── Initialize charts ────────────────────────────────────────────────────
  206. buildBarChart(
  207. "usersActivityChart",
  208. chartData.usersActivity,
  209. chartData.chartLabels.numberOfVisits,
  210. ""
  211. );
  212. buildBarChart(
  213. "usersDataChart",
  214. chartData.usersData,
  215. chartData.chartLabels.dataMb,
  216. chartData.chartLabels.dataUnit
  217. );
  218. buildHourlyActivityChart(chartData.hourlyActivity);
  219. buildPieChart("httpCodesChart", chartData.httpCodes);
  220. buildPieChart("countriesChart", chartData.countries);
  221. // ─── PDF export ───────────────────────────────────────────────────────────
  222. const pdfButton = document.getElementById("reports-export-pdf");
  223. const dateInput = document.getElementById("reports-date");
  224. if (pdfButton) {
  225. pdfButton.addEventListener("click", function () {
  226. let isoDate = null;
  227. // Prefer the datepicker's Date object to avoid display-format issues (MM/DD/YYYY vs YYYY-MM-DD)
  228. try {
  229. const dpDate = dateInput && dateInput.datepicker?.getDate?.();
  230. if (dpDate instanceof Date && !isNaN(dpDate)) {
  231. isoDate = dpDate.toISOString().slice(0, 10);
  232. }
  233. } catch (_) {
  234. // datepicker API unavailable — fall through
  235. }
  236. // Fallback: raw input value already in YYYY-MM-DD (e.g. set programmatically)
  237. if (!isoDate && dateInput && /^\d{4}-\d{2}-\d{2}$/.test(dateInput.value)) {
  238. isoDate = dateInput.value;
  239. }
  240. // Fallback: parse MM/DD/YYYY display format produced by Flowbite datepicker
  241. if (!isoDate && dateInput && dateInput.value) {
  242. const parts = dateInput.value.split("/");
  243. if (parts.length === 3) {
  244. const [month, day, year] = parts;
  245. isoDate = `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
  246. }
  247. }
  248. // Last resort: today
  249. if (!isoDate) {
  250. isoDate = new Date().toISOString().slice(0, 10);
  251. }
  252. window.location.href = `/reports/download/pdf?date=${encodeURIComponent(isoDate)}`;
  253. });
  254. }
  255. // ─── Dark mode observer ───────────────────────────────────────────────────
  256. const observer = new MutationObserver(function (mutations) {
  257. mutations.forEach(function (mutation) {
  258. if (
  259. mutation.type === "attributes" &&
  260. mutation.attributeName === "class"
  261. ) {
  262. setTimeout(function () {
  263. Chart.helpers.each(Chart.instances, function (instance) {
  264. const opts = instance.config.options;
  265. if (opts && opts.scales) {
  266. const textColor = getTextColor();
  267. Object.values(opts.scales).forEach(function (scale) {
  268. if (scale.ticks) scale.ticks.color = textColor;
  269. if (scale.title) scale.title.color = textColor;
  270. });
  271. }
  272. if (opts && opts.plugins && opts.plugins.legend && opts.plugins.legend.labels) {
  273. opts.plugins.legend.labels.color = getTextColor();
  274. }
  275. instance.update();
  276. });
  277. }, 100);
  278. }
  279. });
  280. });
  281. observer.observe(document.documentElement, {
  282. attributes: true,
  283. attributeFilter: ["class"],
  284. });
  285. });