High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
Add sorting different date fields to campaigns. Closes #2563.
Kailash Nadhe7c79a60164e
diff --git a/docs/docs/content/apis/campaigns.md b/docs/docs/content/apis/campaigns.mdindex 737c597b..6c451b5b 100644--- a/docs/docs/content/apis/campaigns.md+++ b/docs/docs/content/apis/campaigns.md@@ -32,7 +32,7 @@ Retrieve all campaigns.| Name | Type | Required | Description || :------- | :------- | :------- | :----------------------------------------------------------------------- || order | string | | Sorting order: ASC for ascending, DESC for descending. |-| order_by | string | | Result sorting field. Options: name, status, created_at, updated_at. |+| order_by | string | | Result sorting field. Options: name, status, created_at, updated_at, started_at, send_at. || query | string | | String to filtter by campaign name and subject (fulltext and substring). || status | []string | | Status to filter campaigns. Repeat in the query for multiple values. || tags | []string | | Tags to filter campaigns. Repeat in the query for multiple values. |diff --git a/internal/core/core.go b/internal/core/core.goindex 1641b3f5..0dfa6e5d 100644--- a/internal/core/core.go+++ b/internal/core/core.go@@ -69,7 +69,7 @@ var (var (regexpSpaces = regexp.MustCompile(`[\s]+`)- campQuerySortFields = []string{"name", "status", models.FieldCreatedAt, "updated_at"}+ campQuerySortFields = []string{"name", "status", models.FieldCreatedAt, "updated_at", "started_at", "send_at"}subQuerySortFields = []string{"email", "status", "name", models.FieldCreatedAt, "updated_at"}userQuerySortFields = []string{"username", "email", models.FieldCreatedAt, "loggedin_at"}roleQuerySortFields = []string{"name", models.FieldCreatedAt, "updated_at"}diff --git a/static/admin/assets/css/style.css b/static/admin/assets/css/style.cssindex 8af37142..f6f6e135 100644--- a/static/admin/assets/css/style.css+++ b/static/admin/assets/css/style.css@@ -948,6 +948,12 @@ td > .empty-state {}}+ .timestamp-sort {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ }+th a[data-sort-field] {display: flex;align-items: center;@@ -1969,7 +1975,7 @@ section.users {}/* Sort links become pills. */- th a[data-sort-field] {+ th a[data-sort-field]:not([role="menuitem"]) {display: inline-flex;align-items: center;gap: var(--space-1);diff --git a/static/admin/partials/campaigns-table.html b/static/admin/partials/campaigns-table.htmlindex e711bcb2..c84c16a7 100644--- a/static/admin/partials/campaigns-table.html+++ b/static/admin/partials/campaigns-table.html@@ -5,6 +5,20 @@{{- $base := URI "/admin/campaigns" -}}{{- $tableBase := .Base -}}{{- $defaultAnalyticsDate := now.AddDate 0 0 -30 -}}++{{- $dateFields := list (dict "Field" "created_at" "Label" "globals.fields.createdAt")+ (dict "Field" "started_at" "Label" "campaigns.startedAt")+ (dict "Field" "updated_at" "Label" "campaigns.ended")+ (dict "Field" "send_at" "Label" "campaigns.status.scheduled") -}}+{{- $dateField := "" -}}+{{- $dateLabel := $root.L.T "campaigns.timestamps" -}}+{{- range $dateFields -}}+ {{- if eq ($d.Page.Param "order_by") .Field -}}+ {{- $dateField = .Field -}}+ {{- $dateLabel = $root.L.T .Label -}}+ {{- end -}}+{{- end -}}+<div class="table-wrapper" x-data="table({ query: {{ ToJSON $d.Page.Query }}, filters: {{ ToJSON $d.Page.QueryParams }}, total: {{ $d.Page.Total }} })" :aria-busy="isLoading('campaigns')" @change="onChange($event)">{{- if .ClearFilters }}<div class="bulk-actions">@@ -39,7 +53,24 @@<th width="12%" class="cy-type">{{ $root.L.T "globals.fields.status" }}</th><th width="12%">{{ $root.L.T "campaigns.stats" }}</th><th width="10%">{{ $root.L.T "globals.terms.analytics" }}</th>- <th width="18%" class="cy-timestamp">{{ $d.Page.SortLink $tableBase "created_at" ($root.L.T "campaigns.timestamps") }}</th>+ <th width="18%" class="cy-timestamp">+ <div class="timestamp-sort">+ {{ $d.Page.SortLink $tableBase (default "created_at" $dateField) $dateLabel }}+ <ot-dropdown>+ <button type="button" class="ghost small icon" popovertarget="camp-timestamp-sort" aria-label="{{ $root.L.T "campaigns.timestamps" }}" aria-haspopup="menu">+ {{ Icon "chevron-down" }}+ </button>+ <menu popover id="camp-timestamp-sort">+ <a role="menuitem" class="button ghost" href="{{ $d.Page.FilterURL $tableBase "order_by" "order" }}">{{ $root.L.T "globals.terms.all" }}</a>+ {{- range $dateFields }}+ {{- $order := "asc" -}}+ {{- if and (eq ($d.Page.Param "order_by") .Field) (eq ($d.Page.Param "order") "asc") }}{{ $order = "desc" }}{{ end -}}+ <a role="menuitem" class="button ghost" href="{{ printf "%s?%s&order_by=%s&order=%s" $tableBase ($d.Page.Encode "order_by" "order" "page") .Field $order }}" data-sort-field="{{ .Field }}"{{ if eq ($d.Page.Param "order_by") .Field }} data-sorted="{{ $d.Page.Param "order" }}"{{ end }}>{{ $root.L.T .Label }}</a>+ {{- end }}+ </menu>+ </ot-dropdown>+ </div>+ </th><th width="5%" class="align-right"></th></tr></thead>@@ -131,23 +162,35 @@<div>{{ FormatNumber .Clicks }} <span class="text-8 text-light">{{ $root.L.T "campaigns.clicks" | lower }}</span></div></div></td>- <td class="timestamp" data-label="{{ $root.L.T "campaigns.timestamps" }}">- {{- $timeline := printf "%s: %s" ($root.L.T "globals.fields.createdAt") (ExactDate .CreatedAt) }}- {{- if .SendAt.Valid }}{{ $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "campaigns.status.scheduled") (ExactDate .SendAt) }}{{ end }}- {{- if .StartedAt.Valid }}{{ $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "campaigns.startedAt") (ExactDate .StartedAt) }}{{ end }}- {{- if $hasEnded }}- {{- $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "campaigns.ended") (ExactDate .UpdatedAt) }}- {{- end }}- {{- with Duration .StartedAt .UpdatedAt }}{{ $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "settings.performance.slidingWindowDuration") . }}{{ end }}- <span tabindex="0" title="{{ $timeline }}" @click="$el.focus()" data-tooltip-placement="bottom">- {{- if $hasEnded }}- {{ FormatTimestamps .StartedAt .UpdatedAt }}- {{- else if and (not (or (eq .Status "draft") (eq .Status "scheduled"))) .StartedAt.Valid }}- {{ CompactDate .StartedAt true }} <span class="text-8 text-light">{{ $root.L.T "campaigns.startedAt" | lower }}</span>+ <td class="timestamp" data-label="{{ $dateLabel }}">+ {{- if $dateField }}+ {{- $date := .CreatedAt -}}+ {{- if eq $dateField "started_at" }}{{ $date = .StartedAt }}{{ end -}}+ {{- if eq $dateField "updated_at" }}{{ $date = .UpdatedAt }}{{ end -}}+ {{- if eq $dateField "send_at" }}{{ $date = .SendAt }}{{ end -}}+ {{- if and $date.Valid (or (ne $dateField "updated_at") $hasEnded) }}+ <span tabindex="0" title="{{ ExactDate $date }}" @click="$el.focus()" data-tooltip-placement="bottom">{{ NiceDate $date true }}</span>{{- else }}- {{ NiceDate .CreatedAt }}+ —+ {{- end }}+ {{- else }}+ {{- $timeline := printf "%s: %s" ($root.L.T "globals.fields.createdAt") (ExactDate .CreatedAt) }}+ {{- if .SendAt.Valid }}{{ $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "campaigns.status.scheduled") (ExactDate .SendAt) }}{{ end }}+ {{- if .StartedAt.Valid }}{{ $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "campaigns.startedAt") (ExactDate .StartedAt) }}{{ end }}+ {{- if $hasEnded }}+ {{- $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "campaigns.ended") (ExactDate .UpdatedAt) }}{{- end }}- </span>+ {{- with Duration .StartedAt .UpdatedAt }}{{ $timeline = printf "%s\n%s: %s" $timeline ($root.L.T "settings.performance.slidingWindowDuration") . }}{{ end }}+ <span tabindex="0" title="{{ $timeline }}" @click="$el.focus()" data-tooltip-placement="bottom">+ {{- if $hasEnded }}+ {{ FormatTimestamps .StartedAt .UpdatedAt }}+ {{- else if and (not (or (eq .Status "draft") (eq .Status "scheduled"))) .StartedAt.Valid }}+ {{ CompactDate .StartedAt true }} <span class="text-8 text-light">{{ $root.L.T "campaigns.startedAt" | lower }}</span>+ {{- else }}+ {{ NiceDate .CreatedAt }}+ {{- end }}+ </span>+ {{- end }}</td><td class="actions align-right"><ot-dropdown>diff --git a/tests/helpers.js b/tests/helpers.jsindex ef3bb111..00132dda 100644--- a/tests/helpers.js+++ b/tests/helpers.js@@ -61,7 +61,7 @@ export async function getMail() {// Run a SQL statement against the listmonk DB. Credentials come from the// LISTMONK_db__* env, falling back to config.toml defaults.-function psql(sql) {+export function psql(sql) {const args = ['-h', process.env.LISTMONK_db__host || 'localhost','-p', process.env.LISTMONK_db__port || '5432',diff --git a/tests/specs/campaigns.spec.js b/tests/specs/campaigns.spec.jsindex 70e3638d..660eaa89 100644--- a/tests/specs/campaigns.spec.js+++ b/tests/specs/campaigns.spec.js@@ -1,11 +1,13 @@import { test, expect } from '@playwright/test';-import { confirm, openMenu, resetDB, selectList, getMail } from '../helpers.js';+import { confirm, openMenu, resetDB, selectList, getMail, psql } from '../helpers.js';const CAMPAIGNS = '/admin/campaigns';const expression = 'Hello {{ .Subscriber.Name }} from {{ .Subscriber.Attribs.city }}';const rendered = 'Hello Demo Subscriber from Bengaluru';const rows = (page) => page.locator('tbody tr[data-campaign-id]');const row = (page, name) => rows(page).filter({ has: page.getByRole('link', { name, exact: true }) });+const campaignNames = (page) => rows(page).locator('td.name > .avatar > .avatar-label > div > a.unstyled');+const timestampHeading = (page) => page.locator('.cy-timestamp .timestamp-sort > a');const tab = (page, name) => page.getByRole('tab', { name, exact: true });const button = (scope, name) => scope.getByRole('button', { name, exact: true });@@ -311,7 +313,7 @@ test('clones full content into a draft and cancels cloning and deletion', asyncawait expect(row(page, c.name)).toBeVisible();});-test('searches, filters and sorts campaigns through SSR navigation', async ({ page }) => {+test('searches and filters campaigns through SSR navigation', async ({ page }) => {await data(await page.request.delete('/api/campaigns?all=true'));for (const name of ['Bravo', 'Alpha', 'Charlie']) await create(page, { name, tags: [name === 'Charlie' ? 'other' : 'news'] });const scheduled = await create(page, { name: 'Scheduled', send_at: new Date(Date.now() + 86400000).toISOString() });@@ -336,16 +338,113 @@ test('searches, filters and sorts campaigns through SSR navigation', async ({ paawait row(page, 'Alpha').getByTitle('Filter Draft', { exact: true }).click();await expect(page).toHaveURL(/[?&]status=draft/);await expect(rows(page)).toHaveCount(3);- for (const [field, orders] of [- ['name', [['Alpha', 'Bravo', 'Charlie'], ['Charlie', 'Bravo', 'Alpha']]],- ['created_at', [['Bravo', 'Alpha', 'Charlie'], ['Charlie', 'Alpha', 'Bravo']]],- ]) {- for (const names of orders) {- await page.locator(`a[data-sort-field="${field}"]`).click();- await expect(rows(page).locator('td.name > .avatar > .avatar-label > div > a.unstyled')).toHaveText(names);- await expect(page).toHaveURL(/[?&]status=draft/);+});++async function selectTimestamp(page, label) {+ await page.locator('[popovertarget="camp-timestamp-sort"]').click();+ await page.locator('#camp-timestamp-sort').getByRole('menuitem', { name: label, exact: true }).click();+}++// Give each timestamp a distinct order so falling back to created_at cannot pass.+async function createSortableCampaigns(page) {+ const fixtures = [+ { name: 'Sort Alpha', created_at: '2021-01-12', started_at: '2022-02-13', updated_at: '2023-03-12', send_at: '2022-01-11' },+ { name: 'Sort Bravo', created_at: '2021-01-13', started_at: '2022-02-11', updated_at: '2023-03-11', send_at: '2022-01-13' },+ { name: 'Sort Charlie', created_at: '2021-01-11', started_at: '2022-02-12', updated_at: '2023-03-13', send_at: '2022-01-12' },+ ];+ for (const fixture of fixtures) {+ const c = await create(page, { name: fixture.name, tags: ['sort-test'] });+ // Historical start/end dates cannot be set through the campaign API.+ psql(`UPDATE campaigns SET status = 'finished',+ created_at = '${fixture.created_at}T12:00:00Z', started_at = '${fixture.started_at}T12:00:00Z',+ updated_at = '${fixture.updated_at}T12:00:00Z', send_at = '${fixture.send_at}T12:00:00Z'+ WHERE id = ${c.id}`);+ }+ return fixtures;+}++const sortFilters = { query: 'Sort', tag: 'sort-test', status: 'finished', type: 'regular', per_page: '10' };+const sortURL = (params = {}) => `${CAMPAIGNS}?${new URLSearchParams({ ...sortFilters, ...params })}`;++async function expectCampaignSort(page, field, order, names) {+ await expect(page).toHaveURL((url) =>+ Object.entries({ ...sortFilters, order_by: field, order }).every(([key, value]) => url.searchParams.get(key) === value)+ && !url.searchParams.has('page'));+ await expect(campaignNames(page)).toHaveText(names);+}++test('sorts campaigns by name in both directions', async ({ page }) => {+ await createSortableCampaigns(page);+ await page.goto(sortURL({ page: '2' }));+ const heading = page.locator('.cy-name').getByRole('link', { name: 'Name', exact: true });+ await heading.click();+ await expectCampaignSort(page, 'name', 'asc', ['Sort Alpha', 'Sort Bravo', 'Sort Charlie']);+ await heading.click();+ await expectCampaignSort(page, 'name', 'desc', ['Sort Charlie', 'Sort Bravo', 'Sort Alpha']);+});++for (const { field, label, names } of [+ { field: 'created_at', label: 'Created', names: ['Sort Charlie', 'Sort Alpha', 'Sort Bravo'] },+ { field: 'started_at', label: 'Started', names: ['Sort Bravo', 'Sort Charlie', 'Sort Alpha'] },+ { field: 'updated_at', label: 'Ended', names: ['Sort Bravo', 'Sort Alpha', 'Sort Charlie'] },+ { field: 'send_at', label: 'Scheduled', names: ['Sort Alpha', 'Sort Charlie', 'Sort Bravo'] },+]) {+ test(`sorts campaigns by ${label} through the timestamp dropdown`, async ({ page }) => {+ const fixtures = await createSortableCampaigns(page);+ await page.goto(sortURL());+ const defaultCells = await rows(page).locator('td.timestamp').allTextContents();+ await page.goto(sortURL({ page: '2' }));++ await selectTimestamp(page, label);+ await expectCampaignSort(page, field, 'asc', names);+ await expect(timestampHeading(page)).toHaveText(label);+ await expect(timestampHeading(page)).toHaveAttribute('data-sorted', 'asc');+ for (const fixture of fixtures) {+ const cell = row(page, fixture.name).locator('td.timestamp');+ const date = new Date(`${fixture[field]}T12:00:00Z`);+ const month = date.toLocaleString('en-GB', { month: 'short', timeZone: 'UTC' });+ await expect(cell).toHaveAttribute('data-label', label);+ await expect(cell).toContainText(`${date.getUTCDate()} ${month} ${date.getUTCFullYear()}`);+ await expect(cell.locator('span')).toHaveCount(1);+ await expect(cell.locator('span')).not.toHaveAttribute('title', /Created:|Started:|Ended:|Scheduled:/);}++ // Re-selecting the option and clicking its heading both toggle direction.+ await selectTimestamp(page, label);+ await expectCampaignSort(page, field, 'desc', [...names].reverse());+ await expect(timestampHeading(page)).toHaveAttribute('data-sorted', 'desc');+ await timestampHeading(page).click();+ await expectCampaignSort(page, field, 'asc', names);+ await page.reload();+ await expect(timestampHeading(page)).toHaveText(label);++ await page.goto(sortURL({ order_by: field, order: 'asc', page: '2' }));+ await selectTimestamp(page, 'All');+ await expect(page).toHaveURL((url) =>+ Object.entries(sortFilters).every(([key, value]) => url.searchParams.get(key) === value)+ && ['order_by', 'order', 'page'].every((key) => !url.searchParams.has(key)));+ await expect(timestampHeading(page)).toHaveText('Timestamps');+ await expect(campaignNames(page)).toHaveText(['Sort Bravo', 'Sort Alpha', 'Sort Charlie']);+ await expect(rows(page).locator('td.timestamp')).toHaveText(defaultCells.map((text) => text.trim()));+ await expect(rows(page).locator('td.timestamp > span').first()).toHaveAttribute('title', /Created:.*\nScheduled:.*\nStarted:.*\nEnded:/);+ });+}++test('shows missing campaign timestamps as a dash and restores the default view', async ({ page }) => {+ const c = await create(page, { name: 'Unsent campaign' });+ await page.goto(`${CAMPAIGNS}?query=Unsent`);+ const cell = row(page, c.name).locator('td.timestamp');+ const defaultText = await cell.textContent();+ for (const label of ['Started', 'Ended', 'Scheduled']) {+ await selectTimestamp(page, label);+ await expect(timestampHeading(page)).toHaveText(label);+ await expect(cell).toHaveText('—');}+ await selectTimestamp(page, 'Created');+ await expect(cell.locator('span')).toBeVisible();+ await selectTimestamp(page, 'All');+ await expect(timestampHeading(page)).toHaveText('Timestamps');+ await expect(cell).toHaveText(defaultText.trim());});for (const { label, all, filter, unrelated } of [