Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

SSR: Port campaign analytics page.

Kailash Nadhf91b7bd3caa2
diff --git a/cmd/campaign_analytics.go b/cmd/campaign_analytics.go
new file mode 100644
index 00000000..e52b0123
--- /dev/null
+++ b/cmd/campaign_analytics.go
@@ -0,0 +1,201 @@
+package main
+
+import (
+ "net/http"
+ "time"
+
+ "github.com/knadh/listmonk/internal/auth"
+ "github.com/knadh/listmonk/models"
+ "github.com/labstack/echo/v4"
+)
+
+// analyticsCampaign is used to render campaign items in the campaign analytics page selector.
+type analyticsCampaign struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+}
+
+// analyticsData is the chart data embedded into the analytics page for the Chart.js renderer.
+type analyticsData struct {
+ Campaigns []analyticsCampaign `json:"campaigns"`
+ Views []models.CampaignAnalyticsCount `json:"views"`
+ Clicks []models.CampaignAnalyticsCount `json:"clicks"`
+ Bounces []models.CampaignAnalyticsCount `json:"bounces"`
+ Links []models.CampaignAnalyticsLink `json:"links"`
+}
+
+// campaignAnalyticsView is the admin view for the campaign analytics page.
+type campaignAnalyticsView struct {
+ adminView
+
+ Campaigns []analyticsCampaign
+ FromInput string
+ ToInput string
+ DisableTracking bool
+ IndividualTracking bool
+
+ HasData bool
+ Counts struct {
+ Views int
+ Clicks int
+ Bounces int
+ }
+ Data analyticsData
+}
+
+// ViewCampaignAnalytics renders the HTML view for campaign analytics.
+func (a *App) ViewCampaignAnalytics(c echo.Context) error {
+ var campaigns []analyticsCampaign
+ if ids, err := getQueryInts("id", c.QueryParams()); err == nil {
+ for _, id := range ids {
+ // Skip campaigns the user doesn't have access to.
+ if err := a.checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
+ continue
+ }
+
+ camp, err := a.core.GetCampaign(id, "", "")
+ if err != nil {
+ continue
+ }
+
+ campaigns = append(campaigns, analyticsCampaign{ID: camp.ID, Name: camp.Name})
+ }
+ }
+
+ // Resolve the date range, defaulting to the last 7 days.
+ to := time.Now()
+ from := to.AddDate(0, 0, -7)
+ if t, ok := parseAnalyticsDate(c.QueryParam("from")); ok {
+ from = t
+ }
+ if t, ok := parseAnalyticsDate(c.QueryParam("to")); ok {
+ to = t
+ }
+
+ data := campaignAnalyticsView{
+ adminView: newAdminView(c, a.i18n.T("analytics.title"), "", "campaigns.analytics"),
+ Campaigns: campaigns,
+ FromInput: from.Format("2006-01-02T15:04"),
+ ToInput: to.Format("2006-01-02T15:04"),
+ DisableTracking: a.cfg.Privacy.DisableTracking,
+ IndividualTracking: a.cfg.Privacy.IndividualTracking,
+ }
+
+ // Pull analytics for the selected campaigns.
+ if len(campaigns) > 0 {
+ var (
+ fromStr = from.Format("2006-01-02 15:04:05")
+ toStr = to.Format("2006-01-02 15:04:05")
+ ids = make([]int, len(campaigns))
+ )
+ for i, camp := range campaigns {
+ ids[i] = camp.ID
+ }
+
+ views, err := a.core.GetCampaignAnalyticsCounts(ids, "views", fromStr, toStr)
+ if err != nil {
+ return err
+ }
+
+ clicks, err := a.core.GetCampaignAnalyticsCounts(ids, "clicks", fromStr, toStr)
+ if err != nil {
+ return err
+ }
+
+ bounces, err := a.core.GetCampaignAnalyticsCounts(ids, "bounces", fromStr, toStr)
+ if err != nil {
+ return err
+ }
+
+ links, err := a.core.GetCampaignAnalyticsLinks(ids, "links", fromStr, toStr)
+ if err != nil {
+ return err
+ }
+
+ data.HasData = true
+ data.Data = analyticsData{Campaigns: campaigns, Views: views, Clicks: clicks, Bounces: bounces, Links: links}
+ data.Counts.Views = sumAnalyticsCounts(views)
+ data.Counts.Clicks = sumAnalyticsCounts(clicks)
+ data.Counts.Bounces = sumAnalyticsCounts(bounces)
+ }
+
+ return c.Render(http.StatusOK, "admin-campaign-analytics", data)
+}
+
+// GetCampaignViewAnalytics retrieves view counts for a campaign.
+func (a *App) GetCampaignViewAnalytics(c echo.Context) error {
+ ids, err := parseStringIDs(c.Request().URL.Query()["id"])
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest,
+ a.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
+ }
+
+ if len(ids) == 0 {
+ return echo.NewHTTPError(http.StatusBadRequest,
+ a.i18n.Ts("globals.messages.missingFields", "name", "`id`"))
+ }
+
+ // Ensure the user has access to campaigns via lists.
+ for _, id := range ids {
+ if err := a.checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
+ return err
+ }
+ }
+
+ var (
+ typ = c.Param("type")
+ from = c.QueryParams().Get("from")
+ to = c.QueryParams().Get("to")
+ )
+ if !strHasLen(from, 10, 30) || !strHasLen(to, 10, 30) {
+ return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("analytics.invalidDates"))
+ }
+
+ // Campaign link stats.
+ if typ == "links" {
+ out, err := a.core.GetCampaignAnalyticsLinks(ids, typ, from, to)
+ if err != nil {
+ return err
+ }
+
+ return c.JSON(http.StatusOK, okResp{out})
+ }
+
+ // Get the analytics numbers from the DB for the campaigns.
+ out, err := a.core.GetCampaignAnalyticsCounts(ids, typ, from, to)
+ if err != nil {
+ return err
+ }
+
+ return c.JSON(http.StatusOK, okResp{out})
+}
+
+// parseAnalyticsDate parses a `datetime-local` form value (with or without seconds).
+func parseAnalyticsDate(s string) (time.Time, bool) {
+ if s == "" {
+ return time.Time{}, false
+ }
+
+ var layout string
+ switch len(s) {
+ case 16:
+ layout = "2006-01-02T15:04"
+ case 19:
+ layout = "2006-01-02T15:04:05"
+ default:
+ return time.Time{}, false
+ }
+ t, err := time.ParseInLocation(layout, s, time.Local)
+
+ return t, err == nil
+}
+
+// sumAnalyticsCounts returns the total count across the given analytics rows.
+func sumAnalyticsCounts(rows []models.CampaignAnalyticsCount) int {
+ total := 0
+ for _, r := range rows {
+ total += r.Count
+ }
+
+ return total
+}
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index cac2aafe..e96e6ae3 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -607,54 +607,6 @@ func (a *App) TestCampaign(c echo.Context) error {
return c.JSON(http.StatusOK, okResp{true})
}
-// GetCampaignViewAnalytics retrieves view counts for a campaign.
-func (a *App) GetCampaignViewAnalytics(c echo.Context) error {
- ids, err := parseStringIDs(c.Request().URL.Query()["id"])
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest,
- a.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
- }
-
- if len(ids) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest,
- a.i18n.Ts("globals.messages.missingFields", "name", "`id`"))
- }
-
- // Ensure the user has access to campaigns via lists.
- for _, id := range ids {
- if err := a.checkCampaignPerm(auth.PermTypeGet, id, c); err != nil {
- return err
- }
- }
-
- var (
- typ = c.Param("type")
- from = c.QueryParams().Get("from")
- to = c.QueryParams().Get("to")
- )
- if !strHasLen(from, 10, 30) || !strHasLen(to, 10, 30) {
- return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("analytics.invalidDates"))
- }
-
- // Campaign link stats.
- if typ == "links" {
- out, err := a.core.GetCampaignAnalyticsLinks(ids, typ, from, to)
- if err != nil {
- return err
- }
-
- return c.JSON(http.StatusOK, okResp{out})
- }
-
- // Get the analytics numbers from the DB for the campaigns.
- out, err := a.core.GetCampaignAnalyticsCounts(ids, typ, from, to)
- if err != nil {
- return err
- }
-
- return c.JSON(http.StatusOK, okResp{out})
-}
-
// sendTestMessage takes a campaign and a subscriber and sends out a sample campaign message.
func (a *App) sendTestMessage(sub models.Subscriber, camp *models.Campaign) error {
if err := a.manager.LoadInlineImages(camp); err != nil {
diff --git a/cmd/handlers.go b/cmd/handlers.go
index c6414731..1efe8399 100644
--- a/cmd/handlers.go
+++ b/cmd/handlers.go
@@ -76,6 +76,7 @@ func initHTTPHandlers(e *echo.Echo, a *App) {
g.GET(path.Join(uriAdmin, "/lists/:id"), hasID(a.ViewList))
g.GET(path.Join(uriAdmin, "/lists/forms"), a.ViewForms)
g.GET(path.Join(uriAdmin, "/campaigns/media"), a.ViewMedia)
+ g.GET(path.Join(uriAdmin, "/campaigns/analytics"), a.ViewCampaignAnalytics)
g.GET(path.Join(uriAdmin, "/subscribers/import"), a.ViewImport)
g.GET(path.Join(uriAdmin, "/subscribers/bounces"), a.ViewBounces)
g.GET(path.Join(uriAdmin, "/subscribers"), a.ViewSubscribers)
diff --git a/static/admin/build.mjs b/static/admin/build.mjs
index 10356e19..d169ae28 100644
--- a/static/admin/build.mjs
+++ b/static/admin/build.mjs
@@ -18,6 +18,7 @@ const vendor = [
['node_modules/alpinejs/dist/cdn.min.js', 'vendor/alpinejs.min.js'],
['node_modules/@knadh/oat/oat.min.js', 'vendor/oat.min.js'],
['node_modules/@knadh/oat/oat.min.css', 'vendor/oat.min.css'],
+ ['node_modules/chart.js/dist/chart.umd.js', 'vendor/chart.min.js'],
];
async function build() {
diff --git a/static/admin/bun.lock b/static/admin/bun.lock
index e9b5634d..dfd2e4d1 100644
--- a/static/admin/bun.lock
+++ b/static/admin/bun.lock
@@ -17,6 +17,7 @@
"@knadh/oat": "^0.7.0",
"@lezer/highlight": "^1.2.3",
"alpinejs": "^3.15.12",
+ "chart.js": "^4.4.1",
},
},
},
@@ -45,6 +46,8 @@
"@knadh/oat": ["@knadh/[email protected]", "", {}, "sha512-WVfaj/07sdLT9i99oR+4JObyy/YrlTXiwSDs/ZeIBE63i9WaksrIQhj+v9HjFHqRgEvZBCU8q6ALpu5sSDARIw=="],
+ "@kurkle/color": ["@kurkle/[email protected]", "", {}, "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w=="],
+
"@lezer/common": ["@lezer/[email protected]", "", {}, "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ=="],
"@lezer/css": ["@lezer/[email protected]", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-N+tn9tej2hPvyKgHEApMOQfHczDJCwxrRFS3SPn9QjYN+uwHvEDnCgKRrb3mxDYxRS8sKMM8fhC3+lc04Abz5Q=="],
@@ -67,6 +70,8 @@
"alpinejs": ["[email protected]", "", { "dependencies": { "@vue/reactivity": "~3.1.1" } }, "sha512-nJvPAQVNPdZZ0NrExJ/kzQco3ijR8LwvCOadQecllESiqT4NyZ/57sN9V2XyvhlBGAbmlKYgeWZvYdKq99ij/Q=="],
+ "chart.js": ["[email protected]", "", { "dependencies": { "@kurkle/color": "^0.3.0" } }, "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw=="],
+
"crelt": ["[email protected]", "", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="],
"style-mod": ["[email protected]", "", {}, "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ=="],
diff --git a/static/admin/package.json b/static/admin/package.json
index 9250504d..8caf9541 100644
--- a/static/admin/package.json
+++ b/static/admin/package.json
@@ -20,6 +20,7 @@
"@codemirror/view": "^6.43.4",
"@knadh/oat": "^0.7.0",
"@lezer/highlight": "^1.2.3",
- "alpinejs": "^3.15.12"
+ "alpinejs": "^3.15.12",
+ "chart.js": "^4.4.1"
}
}
diff --git a/static/admin/src/css/style.css b/static/admin/src/css/style.css
index 6dd7549a..a0c52051 100644
--- a/static/admin/src/css/style.css
+++ b/static/admin/src/css/style.css
@@ -944,26 +944,15 @@ section.campaigns {
}
section.analytics {
- .charts {
- min-height: 100px;
- position: relative;
- }
-
- .chart {
- margin-block-end: var(--space-16);
- max-width: 100%;
- }
-
+ /* Fixed-height, position:relative wrappers so Chart.js can size the canvas
+ without the responsive resize feedback loop. */
+ .chart-box,
.donut-container {
position: relative;
+ height: 340px;
}
}
-.chart canvas {
- height: 400px;
- max-width: 100%;
-}
-
.preview {
padding: 0;
position: relative;
diff --git a/static/admin/src/js/views/analytics.js b/static/admin/src/js/views/analytics.js
new file mode 100644
index 00000000..a5a1e1a4
--- /dev/null
+++ b/static/admin/src/js/views/analytics.js
@@ -0,0 +1,246 @@
+import { api } from '../main.js';
+
+const chartColorRed = '#ee7d5b';
+const chartColors = [
+ '#0055d4',
+ '#FFB50D',
+ '#41AC9C',
+ chartColorRed,
+ '#7FC7BC',
+ '#3a82d6',
+ '#688ED9',
+ '#FFC43D',
+];
+
+const DEFAULT_DONUT = {
+ type: 'doughnut',
+ options: {
+ responsive: true,
+ cutout: '70%',
+ maintainAspectRatio: false,
+ plugins: {
+ legend: { display: false },
+ tooltip: {
+ backgroundColor: '#fff',
+ borderColor: '#ddd',
+ borderWidth: 1,
+ titleColor: '#666',
+ bodyColor: '#666',
+ bodyFont: { size: 15 },
+ bodySpacing: 10,
+ padding: 10,
+ callbacks: {
+ label: (item) => {
+ const data = item.chart.data.datasets[item.datasetIndex];
+ const total = data.data.reduce((acc, val) => acc + val, 0);
+ const val = data.data[item.dataIndex];
+ const percentage = ((val / total) * 100).toFixed(2);
+ return `${val} (${percentage}%)`;
+ },
+ },
+ },
+ },
+ },
+};
+
+const DEFAULT_LINE = {
+ type: 'line',
+ options: {
+ responsive: true,
+ lineTension: 0.5,
+ maintainAspectRatio: false,
+ interaction: { intersect: false, axis: 'index' },
+ plugins: {
+ legend: { display: false },
+ tooltip: {
+ backgroundColor: '#fff',
+ borderColor: '#ddd',
+ borderWidth: 1,
+ bodyColor: '#666',
+ displayColors: true,
+ bodyFont: { size: 15 },
+ bodySpacing: 10,
+ padding: 10,
+ },
+ },
+ scales: {
+ x: { grid: { display: false } },
+ y: { grid: { display: false }, ticks: { precision: 0 } },
+ },
+ },
+};
+
+const DEFAULT_BAR = {
+ type: 'bar',
+ options: {
+ responsive: true,
+ indexAxis: 'y',
+ barThickness: 40,
+ maintainAspectRatio: false,
+ plugins: {
+ legend: { display: false },
+ tooltip: {
+ backgroundColor: '#fff',
+ borderColor: '#ddd',
+ borderWidth: 1,
+ titleColor: '#666',
+ bodyColor: '#666',
+ bodyFont: { size: 15 },
+ bodySpacing: 10,
+ padding: 10,
+ },
+ },
+ scales: {
+ x: { grid: { display: false } },
+ y: { grid: { display: false } },
+ },
+ },
+};
+
+// Zero-pad a number to two digits.
+const pad = (n) => String(n).padStart(2, '0');
+
+// Format a timestamp string into a chart axis label.
+function toLabel(s) {
+ const d = new Date(s);
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+// CampaignTag is the object used in the <ot-taginput> campaign selector.
+class CampaignTag {
+ constructor(c) {
+ this.id = c.id;
+ this.name = c.name;
+ }
+
+ toString() {
+ return `#${this.id}: ${this.name}`;
+ }
+}
+
+// analyticsForm is the Alpine component for the campaign analytics page.
+function analyticsForm() {
+ let queryTimer = null;
+
+ return {
+ campaigns: (window._selectedCampaigns || []).map((c) => new CampaignTag(c)),
+
+ // Set on submit to give feedback during the full-page reload.
+ submitting: false,
+
+ // Populate the selector's suggestions with the campaigns API.
+ onQuery(el) {
+ clearTimeout(queryTimer);
+ queryTimer = setTimeout(async () => {
+ const ti = el.closest('ot-taginput');
+ const chosen = new Set((ti ? ti.value : []).map((c) => c.id));
+ const params = new URLSearchParams({
+ query: el.value.trim(),
+ order_by: 'created_at',
+ order: 'DESC',
+ no_body: 'true',
+ per_page: '10',
+ });
+
+ try {
+ const data = await api('analytics.campaigns', `/campaigns?${params.toString()}`, 'GET');
+ el.list.replaceChildren(...(data.results || [])
+ .filter((c) => !chosen.has(c.id))
+ .map((c) => {
+ const o = new Option(`#${c.id}: ${c.name}`);
+ o.data = new CampaignTag(c);
+ return o;
+ }));
+ } catch (err) { /* api() shows a toast. */ }
+ }, 200);
+ },
+ };
+}
+
+// Create a Chart.js instance on the canvas with the given id.
+function draw(id, def, data, extraOptions) {
+ const canvas = document.getElementById(id);
+ if (!canvas) {
+ return;
+ }
+
+ // eslint-disable-next-line no-new
+ new window.Chart(canvas, {
+ type: def.type,
+ data,
+ options: { ...def.options, ...(extraOptions || {}) },
+ });
+}
+
+// Render a line chart (time series per campaign) and its donut (totals per campaign).
+function renderCounts(key, camps, rows) {
+ const datasets = camps.map((c, n) => ({
+ label: `#${c.id}: ${c.name}`,
+ data: rows.filter((item) => item.campaign_id === c.id)
+ .map((item) => ({ x: toLabel(item.timestamp), y: item.count })),
+ borderColor: chartColors[n % chartColors.length],
+ borderWidth: 2,
+ pointHoverBorderWidth: 5,
+ pointBorderWidth: 0.5,
+ }));
+
+ const labels = [];
+ const totals = camps.map((c) => {
+ labels.push(`#${c.id}: ${c.name}`);
+ return rows.reduce((a, item) => (item.campaign_id === c.id ? a + item.count : a), 0);
+ });
+
+ draw(`chart-${key}`, DEFAULT_LINE, { datasets });
+ draw(`chart-${key}-donut`, DEFAULT_DONUT, {
+ labels,
+ datasets: [{ data: totals, backgroundColor: chartColors, borderWidth: 6 }],
+ });
+}
+
+// Render the link-clicks bar chart.
+function renderLinks(rows) {
+ const urls = rows.map((l) => l.url);
+ const labels = rows.map((l) => {
+ try {
+ const u = new URL(l.url);
+ if (l.url.length > 80) {
+ return `${u.hostname}${u.pathname.substr(0, 50)}..`;
+ }
+ return u.hostname + u.pathname;
+ } catch {
+ return l.url;
+ }
+ });
+
+ draw('chart-links', DEFAULT_BAR, {
+ labels,
+ datasets: [{ data: rows.map((l) => l.count), backgroundColor: chartColors }],
+ }, {
+ onClick: (e) => {
+ const bars = e.chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
+ if (bars.length > 0) {
+ window.open(urls[bars[0].index], '_blank', 'noopener noreferrer');
+ }
+ },
+ });
+}
+
+// Render all charts from the server-embedded analytics data.
+function renderCharts() {
+ const d = window._analytics;
+ if (!d || !window.Chart) {
+ return;
+ }
+
+ const camps = d.campaigns || [];
+ renderCounts('views', camps, d.views || []);
+ renderCounts('clicks', camps, d.clicks || []);
+ renderCounts('bounces', camps, d.bounces || []);
+ renderLinks(d.links || []);
+}
+
+document.addEventListener('alpine:init', () => {
+ window.Alpine.data('analyticsForm', analyticsForm);
+}, { once: true });
+
+renderCharts();
diff --git a/static/admin/src/js/views/media.js b/static/admin/src/js/views/media.js
new file mode 100644
index 00000000..361ff2c9
--- /dev/null
+++ b/static/admin/src/js/views/media.js
@@ -0,0 +1,68 @@
+import {
+ urls,
+ api,
+ i18n,
+} from '../main.js';
+import * as u from '../utils.js';
+
+function component() {
+ return {
+ files: [],
+ isUploading: false,
+
+ // ===============
+ // Event handlers.
+ onOpenUpload() {
+ this.files = [];
+ this.$refs.dialog.showModal();
+ },
+
+ onClose() {
+ this.$refs.dialog.close();
+ },
+
+ async onUpload() {
+ if (this.files.length === 0) {
+ return;
+ }
+
+ this.isUploading = true;
+
+ // Upload each file with an independent request.
+ const results = await Promise.all(this.files.map((file) => {
+ const params = new FormData();
+ params.set('file', file);
+
+ return fetch(`${urls.api}/media`, {
+ method: 'POST',
+ body: params,
+ headers: { Accept: 'application/json' },
+ }).then(async (resp) => {
+ if (!resp.ok) {
+ const out = await resp.json().catch(() => ({}));
+ throw new Error(out.message || resp.statusText);
+ }
+ }).catch((err) => {
+ u.toast(`${file.name}: ${err.message}`, 'danger');
+ });
+ }));
+
+ this.isUploading = false;
+ u.reload({ message: i18n.ts('globals.messages.done') });
+ return results;
+ },
+
+ async onDelete(id, name) {
+ if (!(await u.confirm())) {
+ return;
+ }
+
+ await api('media', `/media/${id}`, 'DELETE');
+ u.reload({ message: i18n.ts('globals.messages.deleted', { name }) });
+ },
+ };
+}
+
+document.addEventListener('alpine:init', () => {
+ window.Alpine.data('mediaView', component);
+}, { once: true });
diff --git a/static/admin/views/analytics.html b/static/admin/views/analytics.html
new file mode 100644
index 00000000..2019ffda
--- /dev/null
+++ b/static/admin/views/analytics.html
@@ -0,0 +1,90 @@
+{{ define "admin-campaign-analytics" -}}
+{{ template "admin-header" . }}
+{{- $d := .Data -}}
+
+<script>
+ window._selectedCampaigns = {{ ToJSON $d.Campaigns }};
+ window._analytics = {{ if $d.HasData }}{{ ToJSON $d.Data }}{{ else }}null{{ end }};
+</script>
+
+<section class="analytics">
+ <header class="row page-header">
+ <div class="col-8">
+ <h1 class="page-title">{{ .L.T "analytics.title" }}</h1>
+ </div>
+ </header>
+
+ <div class="vstack gap-6">
+ <form method="get" action="{{ URI "/admin/campaigns/analytics" }}" class="card" x-data="analyticsForm()" @submit="submitting = true">
+ <div class="row">
+ <div class="col-5">
+ <label data-field>
+ {{ .L.T "globals.terms.campaigns" }}
+ <ot-taginput x-model="campaigns">
+ <input list="analytics-campaigns" placeholder="{{ .L.T "globals.terms.campaigns" }}" @input="onQuery($el)" @pointerdown="onQuery($el)" @focus="onQuery($el)" />
+ <datalist id="analytics-campaigns"></datalist>
+ </ot-taginput>
+ </label>
+ <template x-for="c in campaigns" :key="c.id">
+ <input type="hidden" name="id" :value="c.id" />
+ </template>
+ </div>
+
+ <div class="col-7">
+ <data data-field>
+ <label>{{ .L.T "analytics.fromDate" }} &rarr; {{ .L.T "analytics.toDate" }}</label>
+ <fieldset class="group">
+ <input type="datetime-local" name="from" value="{{ $d.FromInput }}" aria-label="{{ .L.T "analytics.fromDate" }}" data-cy="from" />
+ <input type="datetime-local" name="to" value="{{ $d.ToInput }}" aria-label="{{ .L.T "analytics.toDate" }}" data-cy="to" />
+ <button type="submit" data-cy="btn-search" aria-label="{{ .L.T "globals.buttons.search" }}" :disabled="campaigns.length === 0 || submitting" :aria-busy="submitting" data-spinner="small">
+ {{ .L.T "globals.buttons.view" }}
+ </button>
+ </fieldset>
+ {{- if $d.DisableTracking }}
+ <span data-hint>{{ Icon "alert-triangle" }} {{ .L.T "analytics.trackingDisabled" }}</span>
+ {{- else if not $d.IndividualTracking }}
+ <span data-hint>{{ Icon "alert-triangle" }} {{ .L.T "analytics.nonIndividualTracking" }}</span>
+ {{- end }}
+ </data>
+ </div>
+ </div>
+ </form>
+
+ {{- if $d.HasData }}
+ {{- $empty := .L.T "globals.messages.emptyState" }}
+ {{ template "analytics-chart" dict "Title" (.L.T "campaigns.views") "Count" $d.Counts.Views "Key" "views" "Empty" $empty }}
+ {{ template "analytics-chart" dict "Title" (.L.T "campaigns.clicks") "Count" $d.Counts.Clicks "Key" "clicks" "Empty" $empty }}
+ {{ template "analytics-chart" dict "Title" (.L.T "globals.terms.bounces") "Count" $d.Counts.Bounces "Key" "bounces" "Empty" $empty }}
+
+ <article class="card">
+ <h4>{{ .L.T "analytics.links" }}</h4>
+ {{- if $d.Data.Links }}
+ <div class="chart-box"><canvas id="chart-links"></canvas></div>
+ {{- else }}
+ <p class="text-light align-center">{{ $empty }}</p>
+ {{- end }}
+ </article>
+ {{- end }}
+ </div>
+</section>
+
+<script src="{{ URI "/admin/static/vendor/chart.min.js" }}?v={{ .AssetVersion }}" defer></script>
+<script type="module" src="{{ URI "/admin/static/js/views/analytics.js" }}?v={{ .AssetVersion }}" defer></script>
+
+{{ template "admin-footer" . -}}
+{{ end }}
+
+{{ define "analytics-chart" -}}
+{{- $key := .Key -}}
+<article class="card">
+ <h4>{{ .Title }}{{ if gt .Count 0 }} <span class="text-lighter">({{ FormatNumber .Count }})</span>{{ end }}</h4>
+ {{- if gt .Count 0 }}
+ <div class="row">
+ <div class="col-9"><div class="chart-box"><canvas id="chart-{{ $key }}"></canvas></div></div>
+ <div class="col-3 donut-container"><canvas id="chart-{{ $key }}-donut"></canvas></div>
+ </div>
+ {{- else }}
+ <p class="text-light align-center">{{ .Empty }}</p>
+ {{- end }}
+</article>
+{{- end }}
diff --git a/static/admin/views/media.html b/static/admin/views/media.html
new file mode 100644
index 00000000..24a38322
--- /dev/null
+++ b/static/admin/views/media.html
@@ -0,0 +1,101 @@
+{{ define "admin-media" -}}
+{{ template "admin-header" . }}
+{{- $d := .Data -}}
+
+<section class="media-files" x-data="mediaView">
+ <header class="row page-header">
+ <div class="col-6">
+ <div class="hstack">
+ <h1 class="page-title">
+ {{ .L.T "media.title" }}
+ <span>({{ $d.Page.Total }})</span>
+ </h1>
+ {{- if $d.Provider }}<div class="text-7 text-lighter">{{ $d.Provider }}</div>{{ end }}
+ </div>
+ </div>
+ <div class="col-6 col-end align-right hstack justify-end">
+ <form method="get" action="{{ URI "/admin/campaigns/media" }}" class="search-form">
+ {{- $d.Page.FormFields "query" -}}
+ <fieldset class="group">
+ <input name="query" aria-label="Search" data-cy="query" placeholder="Search" value="{{ $d.Page.Query }}" autofocus />
+ <button type="submit" class="outline" data-cy="btn-query" aria-label="Search">{{ Icon "search" }}</button>
+ </fieldset>
+ </form>
+ {{- if $d.Can "media:manage" }}
+ <button type="button" data-variant="primary" class="btn-new" data-cy="btn-upload" @click="onOpenUpload">
+ {{ Icon "upload" }} {{ .L.T "media.upload" }}
+ </button>
+ {{- end }}
+ </div>
+ </header>
+
+ <div class="card page-content">
+ {{- if $d.Media }}
+ <ul class="unstyled gallery">
+ {{- range $d.Media }}
+ <li data-cy="media-item">
+ <figure class="card">
+ <a class="thumb" href="{{ .URL }}" target="_blank" rel="noopener noreferrer" title="{{ .Filename }}">
+ {{- if .ThumbURL.Valid }}
+ <img src="{{ .ThumbURL.String }}" alt="{{ .Filename }}" />
+ {{- else }}
+ <span class="ext">{{ .Filename | ext | trimPrefix "." | upper }}</span>
+ {{- end }}
+ </a>
+ <figcaption>
+ <span class="filename" title="{{ .Filename }}">{{ .Filename }}</span>
+ <span class="text-light text-8">{{ NiceDate .CreatedAt }}</span>
+ </figcaption>
+ {{- if $d.Can "media:manage" }}
+ <ot-dropdown class="actions">
+ <button popovertarget="media-actions-{{ .ID }}" type="button" class="ghost small icon" aria-label="{{ $.L.T "globals.buttons.more" }}">{{ Icon "more-vertical" }}</button>
+ <menu popover id="media-actions-{{ .ID }}">
+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" @click.prevent="onDelete({{ .ID }}, {{ ToJSON .Filename }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>
+ </menu>
+ </ot-dropdown>
+ {{- end }}
+ </figure>
+ </li>
+ {{- end }}
+ </ul>
+ {{- else }}
+ <div class="align-center text-light">{{ .L.T "globals.messages.emptyState" }}</div>
+ {{- end }}
+
+ {{- template "pagination" $d.Page.Pagination }}
+ </div>
+
+ {{- if $d.Can "media:manage" }}
+ <dialog class="b-modal" x-ref="dialog">
+ <form @submit.prevent="onUpload">
+ <div class="dialog-card content">
+ <header class="dialog-head">
+ <h3 class="dialog-title">{{ .L.T "media.upload" }}</h3>
+ </header>
+ <section class="dialog-body">
+ <div data-field>
+ <ot-upload>
+ <div data-field class="vstack">
+ <input type="file" name="file" multiple hidden @change="files = [...$event.target.files]" />
+ <button type="button" class="ghost" aria-label="{{ .L.T "media.upload" }}">{{ Icon "upload" }}</button>
+ <div data-files><small data-hint>{{ .L.T "media.uploadHelp" }}</small></div>
+ </div>
+ </ot-upload>
+ </div>
+ </section>
+ <footer class="dialog-foot hstack gap-3 justify-end">
+ <button type="button" class="outline" @click="onClose">{{ .L.T "globals.buttons.close" }}</button>
+ <button type="submit" data-variant="primary" data-cy="btn-submit" data-spinner="small" :disabled="files.length === 0 || isUploading" :aria-busy="isUploading">
+ {{ Icon "upload" }} {{ .L.T "media.upload" }}
+ </button>
+ </footer>
+ </div>
+ </form>
+ </dialog>
+ {{- end }}
+</section>
+
+<script type="module" src="{{ URI "/admin/static/js/views/media.js" }}?v={{ .AssetVersion }}" defer></script>
+
+{{ template "admin-footer" . -}}
+{{ end }}