reports-charts.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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: "Datos (MB)",
  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 = context.dataset.yAxisID === "data" ? " MB" : "";
  173. return `${context.dataset.label}: ${value.toLocaleString(undefined, {
  174. maximumFractionDigits: 2,
  175. })}${suffix}`;
  176. },
  177. },
  178. },
  179. datalabels: { display: false },
  180. },
  181. scales: {
  182. x: {
  183. ticks: { autoSkip: true, maxTicksLimit: 12, color: getTextColor() },
  184. },
  185. requests: {
  186. position: "left",
  187. beginAtZero: true,
  188. title: { display: true, text: chartData.chartLabels.requests, color: getTextColor() },
  189. ticks: { color: getTextColor(), precision: 0 },
  190. },
  191. data: {
  192. position: "right",
  193. beginAtZero: true,
  194. title: { display: true, text: "Datos (MB)", color: getTextColor() },
  195. ticks: { color: getTextColor() },
  196. grid: { drawOnChartArea: false },
  197. },
  198. },
  199. },
  200. });
  201. }
  202. // ─── Initialize charts ────────────────────────────────────────────────────
  203. buildBarChart(
  204. "usersActivityChart",
  205. chartData.usersActivity,
  206. chartData.chartLabels.numberOfVisits,
  207. ""
  208. );
  209. buildBarChart("usersDataChart", chartData.usersData, chartData.chartLabels.dataMb, "MB");
  210. buildHourlyActivityChart(chartData.hourlyActivity);
  211. buildPieChart("httpCodesChart", chartData.httpCodes);
  212. buildPieChart("countriesChart", chartData.countries);
  213. // ─── PDF export ───────────────────────────────────────────────────────────
  214. const pdfButton = document.getElementById("reports-export-pdf");
  215. const dateInput = document.getElementById("reports-date");
  216. if (pdfButton) {
  217. pdfButton.addEventListener("click", function () {
  218. let isoDate = null;
  219. // Prefer the datepicker's Date object to avoid display-format issues (MM/DD/YYYY vs YYYY-MM-DD)
  220. try {
  221. const dpDate = dateInput && dateInput.datepicker?.getDate?.();
  222. if (dpDate instanceof Date && !isNaN(dpDate)) {
  223. isoDate = dpDate.toISOString().slice(0, 10);
  224. }
  225. } catch (_) {
  226. // datepicker API unavailable — fall through
  227. }
  228. // Fallback: raw input value already in YYYY-MM-DD (e.g. set programmatically)
  229. if (!isoDate && dateInput && /^\d{4}-\d{2}-\d{2}$/.test(dateInput.value)) {
  230. isoDate = dateInput.value;
  231. }
  232. // Fallback: parse MM/DD/YYYY display format produced by Flowbite datepicker
  233. if (!isoDate && dateInput && dateInput.value) {
  234. const parts = dateInput.value.split("/");
  235. if (parts.length === 3) {
  236. const [month, day, year] = parts;
  237. isoDate = `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
  238. }
  239. }
  240. // Last resort: today
  241. if (!isoDate) {
  242. isoDate = new Date().toISOString().slice(0, 10);
  243. }
  244. window.location.href = `/reports/download/pdf?date=${encodeURIComponent(isoDate)}`;
  245. });
  246. }
  247. // ─── Dark mode observer ───────────────────────────────────────────────────
  248. const observer = new MutationObserver(function (mutations) {
  249. mutations.forEach(function (mutation) {
  250. if (
  251. mutation.type === "attributes" &&
  252. mutation.attributeName === "class"
  253. ) {
  254. setTimeout(function () {
  255. Chart.helpers.each(Chart.instances, function (instance) {
  256. const opts = instance.config.options;
  257. if (opts && opts.scales) {
  258. const textColor = getTextColor();
  259. Object.values(opts.scales).forEach(function (scale) {
  260. if (scale.ticks) scale.ticks.color = textColor;
  261. if (scale.title) scale.title.color = textColor;
  262. });
  263. }
  264. if (opts && opts.plugins && opts.plugins.legend && opts.plugins.legend.labels) {
  265. opts.plugins.legend.labels.color = getTextColor();
  266. }
  267. instance.update();
  268. });
  269. }, 100);
  270. }
  271. });
  272. });
  273. observer.observe(document.documentElement, {
  274. attributes: true,
  275. attributeFilter: ["class"],
  276. });
  277. });