reports-charts.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. // ─── Initialize charts ────────────────────────────────────────────────────
  128. buildBarChart(
  129. "usersActivityChart",
  130. chartData.usersActivity,
  131. "Número de Visitas",
  132. ""
  133. );
  134. buildBarChart("usersDataChart", chartData.usersData, "Datos (MB)", "MB");
  135. buildPieChart("httpCodesChart", chartData.httpCodes);
  136. buildPieChart("countriesChart", chartData.countries);
  137. // ─── PDF export ───────────────────────────────────────────────────────────
  138. const pdfButton = document.getElementById("reports-export-pdf");
  139. const dateInput = document.getElementById("reports-date");
  140. if (pdfButton) {
  141. pdfButton.addEventListener("click", function () {
  142. let isoDate = null;
  143. // Prefer the datepicker's Date object to avoid display-format issues (MM/DD/YYYY vs YYYY-MM-DD)
  144. try {
  145. const dpDate = dateInput && dateInput.datepicker?.getDate?.();
  146. if (dpDate instanceof Date && !isNaN(dpDate)) {
  147. isoDate = dpDate.toISOString().slice(0, 10);
  148. }
  149. } catch (_) {
  150. // datepicker API unavailable — fall through
  151. }
  152. // Fallback: raw input value already in YYYY-MM-DD (e.g. set programmatically)
  153. if (!isoDate && dateInput && /^\d{4}-\d{2}-\d{2}$/.test(dateInput.value)) {
  154. isoDate = dateInput.value;
  155. }
  156. // Fallback: parse MM/DD/YYYY display format produced by Flowbite datepicker
  157. if (!isoDate && dateInput && dateInput.value) {
  158. const parts = dateInput.value.split("/");
  159. if (parts.length === 3) {
  160. const [month, day, year] = parts;
  161. isoDate = `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
  162. }
  163. }
  164. // Last resort: today
  165. if (!isoDate) {
  166. isoDate = new Date().toISOString().slice(0, 10);
  167. }
  168. window.location.href = `/reports/download/pdf?date=${encodeURIComponent(isoDate)}`;
  169. });
  170. }
  171. // ─── Dark mode observer ───────────────────────────────────────────────────
  172. const observer = new MutationObserver(function (mutations) {
  173. mutations.forEach(function (mutation) {
  174. if (
  175. mutation.type === "attributes" &&
  176. mutation.attributeName === "class"
  177. ) {
  178. setTimeout(function () {
  179. Chart.helpers.each(Chart.instances, function (instance) {
  180. const opts = instance.config.options;
  181. if (opts && opts.scales) {
  182. const textColor = getTextColor();
  183. if (opts.scales.y && opts.scales.y.ticks) {
  184. opts.scales.y.ticks.color = textColor;
  185. }
  186. if (opts.scales.x && opts.scales.x.ticks) {
  187. opts.scales.x.ticks.color = textColor;
  188. }
  189. }
  190. if (opts && opts.plugins && opts.plugins.legend && opts.plugins.legend.labels) {
  191. opts.plugins.legend.labels.color = getTextColor();
  192. }
  193. instance.update();
  194. });
  195. }, 100);
  196. }
  197. });
  198. });
  199. observer.observe(document.documentElement, {
  200. attributes: true,
  201. attributeFilter: ["class"],
  202. });
  203. });