Skip to content

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

Add `interval` to time grouping in campaign anlytics (#3201)

Oladosu Ibrahim4f9b998bae79
diff --git a/cmd/campaign_analytics.go b/cmd/campaign_analytics.go
index e52b0123..c49b1da6 100644
--- a/cmd/campaign_analytics.go
+++ b/cmd/campaign_analytics.go
@@ -31,6 +31,7 @@ type campaignAnalyticsView struct {
Campaigns []analyticsCampaign
FromInput string
ToInput string
+ Interval string
DisableTracking bool
IndividualTracking bool
@@ -77,10 +78,15 @@ func (a *App) ViewCampaignAnalytics(c echo.Context) error {
Campaigns: campaigns,
FromInput: from.Format("2006-01-02T15:04"),
ToInput: to.Format("2006-01-02T15:04"),
+ Interval: c.QueryParam("interval"),
DisableTracking: a.cfg.Privacy.DisableTracking,
IndividualTracking: a.cfg.Privacy.IndividualTracking,
}
+ if data.Interval == "" {
+ data.Interval = "day"
+ }
+
// Pull analytics for the selected campaigns.
if len(campaigns) > 0 {
var (
@@ -92,17 +98,17 @@ func (a *App) ViewCampaignAnalytics(c echo.Context) error {
ids[i] = camp.ID
}
- views, err := a.core.GetCampaignAnalyticsCounts(ids, "views", fromStr, toStr)
+ views, err := a.core.GetCampaignAnalyticsCounts(ids, "views", fromStr, toStr, data.Interval)
if err != nil {
return err
}
- clicks, err := a.core.GetCampaignAnalyticsCounts(ids, "clicks", fromStr, toStr)
+ clicks, err := a.core.GetCampaignAnalyticsCounts(ids, "clicks", fromStr, toStr, data.Interval)
if err != nil {
return err
}
- bounces, err := a.core.GetCampaignAnalyticsCounts(ids, "bounces", fromStr, toStr)
+ bounces, err := a.core.GetCampaignAnalyticsCounts(ids, "bounces", fromStr, toStr, data.Interval)
if err != nil {
return err
}
@@ -161,8 +167,13 @@ func (a *App) GetCampaignViewAnalytics(c echo.Context) error {
return c.JSON(http.StatusOK, okResp{out})
}
+ interval := c.QueryParam("interval")
+ if interval == "" {
+ interval = "day"
+ }
+
// Get the analytics numbers from the DB for the campaigns.
- out, err := a.core.GetCampaignAnalyticsCounts(ids, typ, from, to)
+ out, err := a.core.GetCampaignAnalyticsCounts(ids, typ, from, to, interval)
if err != nil {
return err
}
diff --git a/docs/docs/content/apis/campaigns.md b/docs/docs/content/apis/campaigns.md
index 58faaa6f..737c597b 100644
--- a/docs/docs/content/apis/campaigns.md
+++ b/docs/docs/content/apis/campaigns.md
@@ -202,12 +202,13 @@ Retrieve stats of specified campaigns.
##### Parameters
-| Name | Type | Required | Description |
-| :--- | :--------- | :------- | :-------------------------------------------- |
-| id | number\[\] | Yes | Campaign IDs to get stats for. |
-| type | string | Yes | Analytics type: views, links, clicks, bounces |
-| from | string | Yes | Start value of date range. |
-| to | string | Yes | End value of date range. |
+| Name | Type | Required | Description |
+| :------- | :--------- | :------- | :----------------------------------------------------------------- |
+| id | number\[\] | Yes | Campaign IDs to get stats for. |
+| type | string | Yes | Analytics type: views, links, clicks, bounces. |
+| from | string | Yes | Start value of date range. |
+| to | string | Yes | End value of date range. |
+| interval | string | | Interval for views, clicks, and bounces: `hour`, `day`, `week`, or `month`. Default is `day` when empty. |
##### Example Request
@@ -289,23 +290,23 @@ Create a new campaign.
##### Parameters
-| Name | Type | Required | Description |
-| :----------- | :--------- | :------- | :--------------------------------------------------------------------------------------------------------------------- |
-| name | string | Yes | Campaign name. |
-| subject | string | Yes | Campaign email subject. |
-| lists | number\[\] | Yes | List IDs to send campaign to. |
-| from_email | string | | 'From' email in campaign emails. Defaults to value from settings if not provided. |
-| type | string | Yes | Campaign type: 'regular' or 'optin'. |
-| content_type | string | Yes | Content type: 'richtext', 'html', 'markdown', 'plain', 'visual'. |
-| body | string | Yes | Content body of campaign. |
-| body_source | string | | If content_type is `visual`, the JSON block source of the body. |
-| altbody | string | | Alternate plain text body for HTML (and richtext) emails. |
-| send_at | string | | Timestamp to schedule campaign. Format: 'YYYY-MM-DDTHH:MM:SSZ'. |
-| messenger | string | | 'email' or a custom messenger defined in settings. Defaults to 'email' if not provided. |
-| template_id | number | | Template ID to use. Defaults to default template if not provided. |
-| tags | string\[\] | | Tags to mark campaign. |
+| Name | Type | Required | Description |
+| :----------- | :--------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| name | string | Yes | Campaign name. |
+| subject | string | Yes | Campaign email subject. |
+| lists | number\[\] | Yes | List IDs to send campaign to. |
+| from_email | string | | 'From' email in campaign emails. Defaults to value from settings if not provided. |
+| type | string | Yes | Campaign type: 'regular' or 'optin'. |
+| content_type | string | Yes | Content type: 'richtext', 'html', 'markdown', 'plain', 'visual'. |
+| body | string | Yes | Content body of campaign. |
+| body_source | string | | If content_type is `visual`, the JSON block source of the body. |
+| altbody | string | | Alternate plain text body for HTML (and richtext) emails. |
+| send_at | string | | Timestamp to schedule campaign. Format: 'YYYY-MM-DDTHH:MM:SSZ'. |
+| messenger | string | | 'email' or a custom messenger defined in settings. Defaults to 'email' if not provided. |
+| template_id | number | | Template ID to use. Defaults to default template if not provided. |
+| tags | string\[\] | | Tags to mark campaign. |
| headers | JSON | | Key-value pairs to send as SMTP headers. Supports template expressions (e.g., `{{ .Subscriber.UUID }}`). Example: \[{"x-custom-header": "value"}, {"x-subscriber": "{{ .Subscriber.UUID }}"}\]. |
-| attribs | JSON | | Optional JSON object attributes that can be used in the campaign message template. Example `{"location": "Somewhere"}` |
+| attribs | JSON | | Optional JSON object attributes that can be used in the campaign message template. Example `{"location": "Somewhere"}` |
##### Example request
diff --git a/i18n/en.json b/i18n/en.json
index 1a219c58..52bff574 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -2,6 +2,7 @@
"_.code": "en",
"_.name": "English (en)",
"analytics.fromDate": "From",
+ "analytics.interval": "Interval",
"analytics.invalidDates": "Invalid `from` or `to` dates.",
"analytics.links": "Links",
"analytics.nonIndividualTracking": "The counts are non-unique as individual subscriber tracking is turned off.",
@@ -293,6 +294,7 @@
"globals.terms.tx": "Transactional | Transactional",
"globals.terms.user": "User | Users",
"globals.terms.users": "Users",
+ "globals.terms.week": "Week | Weeks",
"globals.terms.value": "Value",
"globals.terms.year": "Year | Years",
"globals.terms.import": "Import",
diff --git a/internal/core/campaigns.go b/internal/core/campaigns.go
index 7006ad55..b3494ad0 100644
--- a/internal/core/campaigns.go
+++ b/internal/core/campaigns.go
@@ -381,7 +381,7 @@ func (c *Core) GetRunningCampaignStats() ([]models.CampaignStats, error) {
return out, nil
}
-func (c *Core) GetCampaignAnalyticsCounts(campIDs []int, typ, fromDate, toDate string) ([]models.CampaignAnalyticsCount, error) {
+func (c *Core) GetCampaignAnalyticsCounts(campIDs []int, typ, fromDate, toDate, interval string) ([]models.CampaignAnalyticsCount, error) {
// Pick campaign view counts or click counts.
var stmt *sqlx.Stmt
switch typ {
@@ -398,9 +398,14 @@ func (c *Core) GetCampaignAnalyticsCounts(campIDs []int, typ, fromDate, toDate s
if !strHasLen(fromDate, 10, 30) || !strHasLen(toDate, 10, 30) {
return nil, echo.NewHTTPError(http.StatusBadRequest, c.i18n.T("analytics.invalidDates"))
}
+ switch interval {
+ case "hour", "day", "week", "month":
+ default:
+ return nil, echo.NewHTTPError(http.StatusBadRequest, c.i18n.T("globals.messages.invalidData"))
+ }
out := []models.CampaignAnalyticsCount{}
- if err := stmt.Select(&out, pq.Array(campIDs), fromDate, toDate); err != nil {
+ if err := stmt.Select(&out, pq.Array(campIDs), fromDate, toDate, interval); err != nil {
c.log.Printf("error fetching campaign %s: %v", typ, err)
return nil, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.analytics}", "error", pqErrMsg(err)))
diff --git a/queries/campaigns.sql b/queries/campaigns.sql
index f6a0739f..0bee3e2d 100644
--- a/queries/campaigns.sql
+++ b/queries/campaigns.sql
@@ -233,12 +233,8 @@ u AS (
SELECT camps.*, campMedia.media_id FROM camps LEFT JOIN campMedia ON (campMedia.campaign_id = camps.id);
-- name: get-campaign-analytics-unique-counts
-WITH intval AS (
- -- For intervals < a week, aggregate counts hourly, otherwise daily.
- SELECT CASE WHEN (EXTRACT (EPOCH FROM ($3::TIMESTAMP - $2::TIMESTAMP)) / 86400) >= 7 THEN 'day' ELSE 'hour' END
-),
-uniqIDs AS (
- SELECT DISTINCT ON(subscriber_id, campaign_id) subscriber_id, campaign_id, DATE_TRUNC((SELECT * FROM intval), created_at) AS "timestamp"
+WITH uniqIDs AS (
+ SELECT DISTINCT ON(subscriber_id, campaign_id) subscriber_id, campaign_id, DATE_TRUNC($4::TEXT, created_at) AS "timestamp"
FROM %s
WHERE campaign_id=ANY($1) AND created_at >= $2 AND created_at <= $3
ORDER BY subscriber_id, campaign_id, "timestamp"
@@ -248,21 +244,13 @@ SELECT COUNT(*) AS "count", campaign_id, "timestamp"
-- name: get-campaign-analytics-counts
-- raw: true
-WITH intval AS (
- -- For intervals < a week, aggregate counts hourly, otherwise daily.
- SELECT CASE WHEN (EXTRACT (EPOCH FROM ($3::TIMESTAMP - $2::TIMESTAMP)) / 86400) >= 7 THEN 'day' ELSE 'hour' END
-)
-SELECT campaign_id, COUNT(*) AS "count", DATE_TRUNC((SELECT * FROM intval), created_at) AS "timestamp"
+SELECT campaign_id, COUNT(*) AS "count", DATE_TRUNC($4::TEXT, created_at) AS "timestamp"
FROM %s
WHERE campaign_id=ANY($1) AND created_at >= $2 AND created_at <= $3
GROUP BY campaign_id, "timestamp" ORDER BY "timestamp" ASC;
-- name: get-campaign-bounce-counts
-WITH intval AS (
- -- For intervals < a week, aggregate counts hourly, otherwise daily.
- SELECT CASE WHEN (EXTRACT (EPOCH FROM ($3::TIMESTAMP - $2::TIMESTAMP)) / 86400) >= 7 THEN 'day' ELSE 'hour' END
-)
-SELECT campaign_id, COUNT(*) AS "count", DATE_TRUNC((SELECT * FROM intval), created_at) AS "timestamp"
+SELECT campaign_id, COUNT(*) AS "count", DATE_TRUNC($4::TEXT, created_at) AS "timestamp"
FROM bounces
WHERE campaign_id=ANY($1) AND created_at >= $2 AND created_at <= $3
GROUP BY campaign_id, "timestamp" ORDER BY "timestamp" ASC;
diff --git a/static/admin/views/analytics.html b/static/admin/views/analytics.html
index 924d732d..315ccad7 100644
--- a/static/admin/views/analytics.html
+++ b/static/admin/views/analytics.html
@@ -17,7 +17,7 @@
<div class="card float">
<h4 class="title">{{ .L.T "analytics.title" }}</h4>
<div class="row">
- <div class="col-5">
+ <div class="col-4">
<label data-field>
{{ .L.T "globals.terms.campaigns" }}
<ot-taginput x-model="campaigns">
@@ -30,15 +30,12 @@
</template>
</div>
- <div class="col-7">
+ <div class="col-5">
<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>
@@ -47,6 +44,27 @@
{{- end }}
</data>
</div>
+
+ <div class="col-2">
+ <data data-field>
+ <label for="analytics-interval">{{ .L.T "analytics.interval" }}</label>
+ <select id="analytics-interval" name="interval" data-cy="interval">
+ <option value="day" {{ if eq $d.Interval "day" }}selected{{ end }}>{{ .L.T "globals.terms.day" }}</option>
+ <option value="hour" {{ if eq $d.Interval "hour" }}selected{{ end }}>{{ .L.T "globals.terms.hour" }}</option>
+ <option value="week" {{ if eq $d.Interval "week" }}selected{{ end }}>{{ .L.T "globals.terms.week" }}</option>
+ <option value="month" {{ if eq $d.Interval "month" }}selected{{ end }}>{{ .L.T "globals.terms.month" }}</option>
+ </select>
+ </data>
+ </div>
+
+ <div class="col-1">
+ <data data-field>
+ <label aria-hidden="true">&nbsp;</label>
+ <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>
+ </data>
+ </div>
</div>
</div>
</form>