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
SSR: Port old subscribers/users tests from Cypress to Playwright.
Kailash Nadh7c5ec3017fa5
diff --git a/static/admin/partials/manage-lists-form.html b/static/admin/partials/manage-lists-form.htmlindex 4113eeb3..a1776031 100644--- a/static/admin/partials/manage-lists-form.html+++ b/static/admin/partials/manage-lists-form.html@@ -5,13 +5,13 @@<fieldset class="hstack"><legend>{{ $root.L.T "settings.bounces.action" }}</legend>- <label><input type="radio" name="{{ $id }}-action" value="add" x-model="{{ $model }}.action" data-cy="check-list-add" /> {{ $root.L.T "globals.buttons.add" }}</label>- <label><input type="radio" name="{{ $id }}-action" value="remove" x-model="{{ $model }}.action" data-cy="check-list-remove" /> {{ $root.L.T "globals.buttons.remove" }}</label>- <label><input type="radio" name="{{ $id }}-action" value="unsubscribe" x-model="{{ $model }}.action" data-cy="check-list-unsubscribe" /> {{ $root.L.T "subscribers.markUnsubscribed" }}</label>+ <label><input type="radio" name="{{ $id }}-action" value="add" x-model="{{ $model }}.action" data-testid="check-list-add" /> {{ $root.L.T "globals.buttons.add" }}</label>+ <label><input type="radio" name="{{ $id }}-action" value="remove" x-model="{{ $model }}.action" data-testid="check-list-remove" /> {{ $root.L.T "globals.buttons.remove" }}</label>+ <label><input type="radio" name="{{ $id }}-action" value="unsubscribe" x-model="{{ $model }}.action" data-testid="check-list-unsubscribe" /> {{ $root.L.T "subscribers.markUnsubscribed" }}</label></fieldset>{{ template "list-selector" dict "Root" $root "Model" (printf "%s.lists" $model) "ListID" $id "Label" "subscribers.lists" "Placeholder" "subscribers.listsPlaceholder" }}<label data-field :aria-disabled="!{{ $model }}HasOptinList">- <input type="checkbox" x-model="{{ $model }}.preconfirm" data-cy="preconfirm" :disabled="!{{ $model }}HasOptinList" /> {{ $root.L.T "subscribers.preconfirm" }}+ <input type="checkbox" x-model="{{ $model }}.preconfirm" data-testid="preconfirm" :disabled="!{{ $model }}HasOptinList" /> {{ $root.L.T "subscribers.preconfirm" }}<small data-hint>{{ $root.L.T "subscribers.preconfirmHelp" }}</small></label>{{- end }}diff --git a/static/admin/partials/subscriber-form.html b/static/admin/partials/subscriber-form.htmlindex 07c088d0..9df3cdf9 100644--- a/static/admin/partials/subscriber-form.html+++ b/static/admin/partials/subscriber-form.html@@ -15,7 +15,7 @@{{ template "subscriber-fields" $root }}{{ template "list-selector" dict "Root" $root "Model" "form.lists" "ListID" "form-lists" "Label" "subscribers.lists" "Placeholder" "subscribers.listsPlaceholder" }}<label data-field :aria-disabled="!hasOptinList">- <input type="checkbox" x-model="form.preconfirm" :disabled="!hasOptinList" /> {{ $root.L.T "subscribers.preconfirm" }}+ <input type="checkbox" x-model="form.preconfirm" data-testid="preconfirm" :disabled="!hasOptinList" /> {{ $root.L.T "subscribers.preconfirm" }}<small data-hint>{{ $root.L.T "subscribers.preconfirmHelp" }}</small></label>{{ template "subscriber-attribs" $root }}@@ -23,7 +23,7 @@<footer class="dialog-foot hstack gap-3 justify-end"><button type="button" class="outline" @click="onClose">{{ $root.L.T "globals.buttons.close" }}</button>{{- if $canSave }}- <button type="submit" data-variant="primary" data-cy="btn-save" :disabled="isLoading('subscribers.save')" :aria-busy="isLoading('subscribers.save')">{{ $root.L.T "globals.buttons.save" }}</button>+ <button type="submit" data-variant="primary" data-testid="btn-save" :disabled="isLoading('subscribers.save')" :aria-busy="isLoading('subscribers.save')">{{ $root.L.T "globals.buttons.save" }}</button>{{- end }}</footer>{{- else }}@@ -41,7 +41,7 @@<div class="hstack gap-3 justify-end"><a href="{{ URI "/admin/subscribers" }}" class="button outline">{{ $root.L.T "globals.buttons.back" }}</a>{{- if $canSave }}- <button type="submit" data-variant="primary" data-cy="btn-save" :disabled="isLoading('subscribers.save')" :aria-busy="isLoading('subscribers.save')">{{ $root.L.T "globals.buttons.save" }}</button>+ <button type="submit" data-variant="primary" data-testid="btn-save" :disabled="isLoading('subscribers.save')" :aria-busy="isLoading('subscribers.save')">{{ $root.L.T "globals.buttons.save" }}</button>{{- end }}</div></footer>diff --git a/static/admin/partials/subscriber-lists.html b/static/admin/partials/subscriber-lists.htmlindex a14858d9..879d4be7 100644--- a/static/admin/partials/subscriber-lists.html+++ b/static/admin/partials/subscriber-lists.html@@ -41,14 +41,14 @@<button popovertarget="sub-list-{{ .ID }}" type="button" class="ghost more icon" aria-label="{{ $root.L.T "globals.buttons.more" }}">{{ Icon "more-vertical" }}</button><menu popover id="sub-list-{{ .ID }}">{{- if and (eq .Optin "double") (eq .SubscriptionStatus "unconfirmed") }}- <button type="button" role="menuitem" class="ghost" @click.prevent="onConfirmSub({{ .ID }})">{{ Icon "check-circle" }} {{ $root.L.T "email.optin.confirmSub" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-confirm-sub" @click.prevent="onConfirmSub({{ .ID }})">{{ Icon "check-circle" }} {{ $root.L.T "email.optin.confirmSub" }}</button>{{- end }}{{- if eq .SubscriptionStatus "unsubscribed" }}- <button type="button" role="menuitem" class="ghost" @click.prevent="onResubscribe({{ .ID }})">{{ Icon "refresh-cw" }} {{ $root.L.T "subscribers.reSubscribe" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-resubscribe" @click.prevent="onResubscribe({{ .ID }})">{{ Icon "refresh-cw" }} {{ $root.L.T "subscribers.reSubscribe" }}</button>{{- else }}- <button type="button" role="menuitem" class="ghost" @click.prevent="onUnsubscribe({{ .ID }})">{{ Icon "user-x" }} {{ $root.L.T "email.unsub" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-unsubscribe" @click.prevent="onUnsubscribe({{ .ID }})">{{ Icon "user-x" }} {{ $root.L.T "email.unsub" }}</button>{{- end }}- <button type="button" role="menuitem" class="ghost" data-variant="danger" @click.prevent="onDeleteSub({{ .ID }})">{{ Icon "trash-2" }} {{ $root.L.T "globals.buttons.delete" }}</button>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete-sub" @click.prevent="onDeleteSub({{ .ID }})">{{ Icon "trash-2" }} {{ $root.L.T "globals.buttons.delete" }}</button></menu></ot-dropdown></td>diff --git a/static/admin/views/bounces.html b/static/admin/views/bounces.htmlindex 5c72a9d5..8fce968e 100644--- a/static/admin/views/bounces.html+++ b/static/admin/views/bounces.html@@ -28,19 +28,19 @@<div class="table-wrapper" x-data="table({ query: {{ ToJSON $d.Page.Query }}, filters: {{ ToJSON $d.Page.QueryParams }}, total: {{ $d.Page.Total }} })" :aria-busy="isLoading('bounces')" @change="onChange($event)"><template x-if="numSelected > 0"><ot-dropdown class="bulk-actions">- <button popovertarget="bounce-bulk-actions" type="button" class="small" data-cy="btn-bulk-actions">+ <button popovertarget="bounce-bulk-actions" type="button" class="small" data-testid="btn-bulk-actions"><span x-text="numSelectedLabel"></span> {{ Icon "more-vertical" }}</button><menu popover id="bounce-bulk-actions">{{- if gt $d.Page.Total $d.Page.PerPage }}- <button type="button" role="menuitem" class="ghost" data-cy="select-all-bounces" x-cloak x-show="!allSelected" @click.prevent="onSelectAllQuery()">+ <button type="button" role="menuitem" class="ghost" data-testid="select-all-bounces" x-cloak x-show="!allSelected" @click.prevent="onSelectAllQuery()">{{ Icon "list" }} <span x-text="selectAllLabel"></span></button>{{- end }}{{- if $d.Can "bounces:manage" }}- <button type="button" role="menuitem" class="ghost" data-cy="btn-manage-blocklist" @click.prevent="onBlocklistSelected(allSelected, total)">{{ Icon "user-x" }} {{ .L.T "import.blocklist" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-manage-blocklist" @click.prevent="onBlocklistSelected(allSelected, total)">{{ Icon "user-x" }} {{ .L.T "import.blocklist" }}</button><hr />- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete-bounces" :disabled="isLoading('bounces')" @click.prevent="onDeleteSelected(allSelected, selected, total)">{{ Icon "trash-2" }} {{ .L.T "globals.buttons.delete" }} <span x-text="numSelected"></span></button>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete-bounces" :disabled="isLoading('bounces')" @click.prevent="onDeleteSelected(allSelected, selected, total)">{{ Icon "trash-2" }} {{ .L.T "globals.buttons.delete" }} <span x-text="numSelected"></span></button>{{- end }}</menu></ot-dropdown>@@ -50,17 +50,17 @@<thead><tr><th width="5%"><input type="checkbox" aria-label="{{ .L.T "globals.buttons.toggleSelect" }}"></th>- <th class="cy-email">{{ $d.Page.SortLink $base "email" (.L.T "subscribers.email") }}</th>- <th class="cy-campaign">{{ .L.T "globals.terms.campaign" }}</th>- <th class="cy-source">{{ $d.Page.SortLink $base "source" (.L.T "bounces.source") }}</th>- <th class="cy-type">{{ $d.Page.SortLink $base "type" (.L.T "globals.fields.type") }}</th>- <th class="cy-created_at">{{ $d.Page.SortLink $base "created_at" (.L.T "globals.fields.createdAt") }}</th>+ <th>{{ $d.Page.SortLink $base "email" (.L.T "subscribers.email") }}</th>+ <th>{{ .L.T "globals.terms.campaign" }}</th>+ <th>{{ $d.Page.SortLink $base "source" (.L.T "bounces.source") }}</th>+ <th>{{ $d.Page.SortLink $base "type" (.L.T "globals.fields.type") }}</th>+ <th>{{ $d.Page.SortLink $base "created_at" (.L.T "globals.fields.createdAt") }}</th><th class="align-right"></th></tr></thead><tbody>{{- range $d.Bounces }}- <tr>+ <tr data-testid="bounce-row" data-id="{{ .ID }}"><td><input name="id" type="checkbox" value="{{ .ID }}" data-subscriber-id="{{ .SubscriberID }}"></td><td><a href="{{ URI "/admin/subscribers" }}/{{ .SubscriberID }}" {{ if eq .SubscriberStatus "blocklisted" }}class="blocklisted"{{ end }}>{{ .Email }}</a>@@ -78,9 +78,9 @@{{ Icon "more-vertical" }}</button><menu popover id="bounce-actions-{{ .ID }}">- <button type="button" role="menuitem" class="ghost" data-cy="btn-meta" @click.prevent="onView({{ ToJSON .Email }}, {{ ToJSON .Meta }})">{{ Icon "file-text" }} {{ $.L.T "globals.buttons.view" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-meta" @click.prevent="onView({{ ToJSON .Email }}, {{ ToJSON .Meta }})">{{ Icon "file-text" }} {{ $.L.T "globals.buttons.view" }}</button>{{- if $d.Can "bounces:manage" }}- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" :disabled="isLoading('bounces')" @click.prevent="onDeleteBounce({{ .ID }}, {{ ToJSON .Email }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete" :disabled="isLoading('bounces')" @click.prevent="onDeleteBounce({{ .ID }}, {{ ToJSON .Email }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>{{- end }}</menu></ot-dropdown>diff --git a/static/admin/views/list-role.html b/static/admin/views/list-role.htmlindex 19069dcf..c128ce15 100644--- a/static/admin/views/list-role.html+++ b/static/admin/views/list-role.html@@ -36,7 +36,7 @@<option :value="l.id" x-text="l.name"></option></template></select>- <button type="button" data-variant="primary" @click="onAddListPerm" :disabled="disabled || !form.curList">{{ .L.T "globals.buttons.add" }}</button>+ <button type="button" data-variant="primary" data-testid="btn-add-list" @click="onAddListPerm" :disabled="disabled || !form.curList">{{ .L.T "globals.buttons.add" }}</button></fieldset></div>@@ -84,7 +84,7 @@</div><div class="col-6 hstack justify-end"><a href="{{ $base }}" class="button outline">{{ .L.T "globals.buttons.back" }}</a>- <button type="submit" data-variant="primary" data-cy="btn-save" x-show="!disabled" :disabled="isLoading('roles.save')" :aria-busy="isLoading('roles.save')">{{ .L.T "globals.buttons.save" }}</button>+ <button type="submit" data-variant="primary" data-testid="btn-save" x-show="!disabled" :disabled="isLoading('roles.save')" :aria-busy="isLoading('roles.save')">{{ .L.T "globals.buttons.save" }}</button></div></div></footer>diff --git a/static/admin/views/roles.html b/static/admin/views/roles.htmlindex 1600fe9a..513b0730 100644--- a/static/admin/views/roles.html+++ b/static/admin/views/roles.html@@ -16,7 +16,7 @@</div><div class="col-6 col-end align-right hstack justify-end">{{- if $d.Can "roles:manage" }}- <a href="{{ $base }}/new" class="button" data-variant="primary" data-cy="btn-new">+ <a href="{{ $base }}/new" class="button" data-variant="primary" data-testid="btn-new">{{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}</a>{{- end }}@@ -28,15 +28,15 @@<table><thead><tr>- <th class="cy-name">{{ .L.Tc "users.role" 1 }}</th>- <th class="cy-created_at">{{ .L.T "globals.fields.createdAt" }}</th>- <th class="cy-updated_at">{{ .L.T "globals.fields.updatedAt" }}</th>+ <th>{{ .L.Tc "users.role" 1 }}</th>+ <th>{{ .L.T "globals.fields.createdAt" }}</th>+ <th>{{ .L.T "globals.fields.updatedAt" }}</th><th class="actions align-right"></th></tr></thead><tbody>{{- range $d.Roles }}- <tr data-id="{{ .ID }}">+ <tr data-testid="role-row" data-id="{{ .ID }}"><td><a href="{{ $base }}/{{ .ID }}">{{- if eq .ID 1 }}{{ Badge (list (Icon "star") .Name) "enum" }}{{ else }}{{ .Name }}{{ end -}}@@ -51,10 +51,10 @@{{ Icon "more-vertical" }}</button><menu popover id="role-actions-{{ .ID }}">- <a href="{{ $base }}/{{ .ID }}" role="menuitem" class="button ghost" data-cy="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>- <button type="button" role="menuitem" class="ghost" data-cy="btn-clone" :disabled="isLoading('roles')" @click.prevent="onCloneRole({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "copy" }} {{ $.L.T "globals.buttons.clone" }}</button>+ <a href="{{ $base }}/{{ .ID }}" role="menuitem" class="button ghost" data-testid="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-clone" :disabled="isLoading('roles')" @click.prevent="onCloneRole({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "copy" }} {{ $.L.T "globals.buttons.clone" }}</button>{{- if ne .ID 1 }}- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" :disabled="isLoading('roles')" @click.prevent="onDeleteRole({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete" :disabled="isLoading('roles')" @click.prevent="onDeleteRole({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>{{- end }}</menu></ot-dropdown>diff --git a/static/admin/views/subscriber.html b/static/admin/views/subscriber.htmlindex fd6d1575..99a5dea7 100644--- a/static/admin/views/subscriber.html+++ b/static/admin/views/subscriber.html@@ -22,9 +22,9 @@<div class="col-6 col-end align-right hstack justify-end">{{- if and (eq $d.Tab "lists") ($d.Can "subscribers:manage") }}{{ if ne $sub.Status "blocklisted" }}- <button type="button" class="outline" @click.prevent="onSendOptin" :disabled="!hasOptinSub">{{ Icon "mail" }} {{ .L.T "subscribers.sendOptinConfirm" }}</button>+ <button type="button" class="outline" data-testid="btn-send-optin" @click.prevent="onSendOptin" :disabled="!hasOptinSub">{{ Icon "mail" }} {{ .L.T "subscribers.sendOptinConfirm" }}</button>{{ end }}- <button type="button" data-variant="primary" @click.prevent="onOpenManage">{{ Icon "list" }} {{ .L.T "globals.buttons.manage" }}</button>+ <button type="button" data-variant="primary" data-testid="btn-manage" @click.prevent="onOpenManage">{{ Icon "list" }} {{ .L.T "globals.buttons.manage" }}</button>{{- end }}{{- if and (eq $d.Tab "bounces") $d.Bounces }}<button type="button" class="outline" data-variant="danger" @click.prevent="onDeleteBounces">{{ Icon "trash-2" }} {{ .L.T "globals.buttons.clear" }}</button>diff --git a/static/admin/views/subscribers.html b/static/admin/views/subscribers.htmlindex c804223b..b8713c67 100644--- a/static/admin/views/subscribers.html+++ b/static/admin/views/subscribers.html@@ -34,27 +34,27 @@{{- $d.Page.FormFields "search" "query" "page" -}}<ot-dropdown><fieldset class="group">- <input name="search" aria-label="Search" data-cy="search" placeholder="{{ .L.T "subscribers.queryPlaceholder" }}" value="{{ $d.Page.Search }}" :disabled="isSqlOpen || advanced" autofocus />- <button type="button" class="outline sql-btn dot-indicator" :class="{ 'is-active': advanced }" popovertarget="sql-editor" data-cy="btn-advanced-search" :data-variant="advanced ? 'primary' : null" aria-label="{{ .L.T "subscribers.advancedQuery" }}">SQL {}</button>- <button type="submit" data-cy="btn-search" aria-label="{{ .L.T "globals.buttons.search" }}">{{ Icon "search" }}</button>+ <input name="search" aria-label="Search" data-testid="search" placeholder="{{ .L.T "subscribers.queryPlaceholder" }}" value="{{ $d.Page.Search }}" :disabled="isSqlOpen || advanced" autofocus />+ <button type="button" class="outline sql-btn dot-indicator" :class="{ 'is-active': advanced }" popovertarget="sql-editor" data-testid="btn-advanced-search" :data-variant="advanced ? 'primary' : null" aria-label="{{ .L.T "subscribers.advancedQuery" }}">SQL {}</button>+ <button type="submit" data-testid="btn-search" aria-label="{{ .L.T "globals.buttons.search" }}">{{ Icon "search" }}</button></fieldset>- <div popover id="sql-editor" class="sql-editor" data-cy="query-editor" @toggle="isSqlOpen = ($event.newState === 'open'); if (isSqlOpen) $nextTick(() => $refs.queryInput.focus())">+ <div popover id="sql-editor" class="sql-editor" data-testid="query-editor" @toggle="isSqlOpen = ($event.newState === 'open'); if (isSqlOpen) $nextTick(() => $refs.queryInput.focus())"><div data-field>- <textarea x-ref="queryInput" name="query" data-cy="query" rows="6" placeholder="subscribers.name LIKE '%user%' or subscribers.status='blocklisted'" x-model="query" :disabled="!isSqlOpen && !advanced"></textarea>+ <textarea x-ref="queryInput" name="query" data-testid="query" rows="6" placeholder="subscribers.name LIKE '%user%' or subscribers.status='blocklisted'" x-model="query" :disabled="!isSqlOpen && !advanced"></textarea><small data-hint>{{ .L.T "subscribers.advancedQueryHelp" }}.<a href="https://listmonk.app/docs/querying-and-segmentation" target="_blank" rel="noopener noreferrer">{{ .L.T "globals.buttons.learnMore" }}.</a></small></div><div class="hstack justify-end">- <button type="button" class="outline" data-cy="btn-query-reset" @click="query = ''" :disabled="query.trim() === ''">{{ .L.T "subscribers.reset" }}</button>- <button type="submit" data-variant="primary" data-cy="btn-query">{{ .L.T "subscribers.query" }}</button>+ <button type="button" class="outline" data-testid="btn-query-reset" @click="query = ''" :disabled="query.trim() === ''">{{ .L.T "subscribers.reset" }}</button>+ <button type="submit" data-variant="primary" data-testid="btn-query">{{ .L.T "subscribers.query" }}</button></div></div></ot-dropdown></form>{{- if $d.Can "subscribers:manage" }}- <button type="button" data-variant="primary" class="btn-new" data-cy="btn-new" @click="onOpenNew">+ <button type="button" data-variant="primary" class="btn-new" data-testid="btn-new" @click="onOpenNew">{{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}</button>{{- end }}@@ -65,21 +65,21 @@<div class="table-wrapper" x-data="table({ query: {{ ToJSON $d.Page.Query }}, filters: {{ ToJSON $d.Page.QueryParams }}, total: {{ $d.Page.Total }} })" :aria-busy="isLoading('subscribers')" @change="onChange($event)"><template x-if="numSelected > 0"><ot-dropdown class="bulk-actions">- <button popovertarget="sub-bulk-actions" type="button" class="small" data-cy="btn-bulk-actions">+ <button popovertarget="sub-bulk-actions" type="button" class="small" data-testid="btn-bulk-actions"><span x-text="numSelectedLabel"></span> {{ Icon "more-vertical" }}</button><menu popover id="sub-bulk-actions">{{- if gt $d.Page.Total $d.Page.PerPage }}- <button type="button" role="menuitem" class="ghost" data-cy="select-all-subscribers" x-cloak x-show="!allSelected" @click.prevent="onSelectAllQuery()">+ <button type="button" role="menuitem" class="ghost" data-testid="select-all-subscribers" x-cloak x-show="!allSelected" @click.prevent="onSelectAllQuery()">{{ Icon "check-square" }} <span x-text="selectAllLabel"></span></button>{{- end }}- <button type="button" role="menuitem" class="ghost" data-cy="btn-export-subscribers" @click.prevent="onExport(allSelected, selected, total)">{{ Icon "download-cloud" }} {{ .L.T "subscribers.export" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-export-subscribers" @click.prevent="onExport(allSelected, selected, total)">{{ Icon "download-cloud" }} {{ .L.T "subscribers.export" }}</button>{{- if $d.Can "subscribers:manage" }}- <button type="button" role="menuitem" class="ghost" data-cy="btn-manage-lists" @click.prevent="onOpenManageLists(allSelected, selected)">{{ Icon "list" }} {{ .L.T "subscribers.manageLists" }}</button>- <button type="button" role="menuitem" class="ghost" data-cy="btn-manage-blocklist" @click.prevent="onBlocklistSelected(allSelected, selected, total)">{{ Icon "user-x" }} {{ .L.T "import.blocklist" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-manage-lists" @click.prevent="onOpenManageLists(allSelected, selected)">{{ Icon "list" }} {{ .L.T "subscribers.manageLists" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-manage-blocklist" @click.prevent="onBlocklistSelected(allSelected, selected, total)">{{ Icon "user-x" }} {{ .L.T "import.blocklist" }}</button><hr />- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete-subscribers" :disabled="isLoading('subscribers')" @click.prevent="onDeleteSelected(allSelected, selected, total)">{{ Icon "trash-2" }} {{ .L.T "globals.buttons.delete" }} <span x-text="numSelected"></span></button>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete-subscribers" :disabled="isLoading('subscribers')" @click.prevent="onDeleteSelected(allSelected, selected, total)">{{ Icon "trash-2" }} {{ .L.T "globals.buttons.delete" }} <span x-text="numSelected"></span></button>{{- end }}</menu></ot-dropdown>@@ -89,18 +89,18 @@<thead><tr><th width="5%"><input type="checkbox" aria-label="{{ .L.T "globals.buttons.toggleSelect" }}"></th>- <th class="cy-email">{{ $d.Page.SortLink $base "email" (.L.T "subscribers.email") }}</th>- <th class="cy-name">{{ $d.Page.SortLink $base "name" (.L.T "globals.fields.name") }}</th>- <th class="align-center cy-lists">{{ .L.T "globals.terms.lists" }}</th>- <th class="cy-created_at">{{ $d.Page.SortLink $base "created_at" (.L.T "globals.fields.createdAt") }}</th>- <th class="cy-updated_at">{{ $d.Page.SortLink $base "updated_at" (.L.T "globals.fields.updatedAt") }}</th>+ <th>{{ $d.Page.SortLink $base "email" (.L.T "subscribers.email") }}</th>+ <th>{{ $d.Page.SortLink $base "name" (.L.T "globals.fields.name") }}</th>+ <th class="align-center">{{ .L.T "globals.terms.lists" }}</th>+ <th>{{ $d.Page.SortLink $base "created_at" (.L.T "globals.fields.createdAt") }}</th>+ <th>{{ $d.Page.SortLink $base "updated_at" (.L.T "globals.fields.updatedAt") }}</th><th class="align-right"></th></tr></thead><tbody>{{- range $d.Subscribers }}{{- $sub := . }}- <tr {{ if eq .Status "blocklisted" }}class="blocklisted"{{ end }}>+ <tr data-testid="sub-row" data-id="{{ .ID }}" {{ if eq .Status "blocklisted" }}class="blocklisted"{{ end }}><td><input name="id" type="checkbox" value="{{ .ID }}"></td><td class="email"><a href="{{ URI "/admin/subscribers" }}/{{ .ID }}">{{ .Email }}</a>@@ -127,11 +127,11 @@{{ Icon "more-vertical" }}</button><menu popover id="sub-actions-{{ .ID }}">- <a href="{{ URI "/api/subscribers" }}/{{ .ID }}/export" role="menuitem" class="button ghost" data-cy="btn-download">{{ Icon "download-cloud" }} {{ $.L.T "subscribers.downloadData" }}</a>+ <a href="{{ URI "/api/subscribers" }}/{{ .ID }}/export" role="menuitem" class="button ghost" data-testid="btn-download">{{ Icon "download-cloud" }} {{ $.L.T "subscribers.downloadData" }}</a>{{- if $d.Can "subscribers:manage" }}- <a href="{{ URI "/admin/subscribers" }}/{{ .ID }}" role="menuitem" class="button ghost" data-cy="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>+ <a href="{{ URI "/admin/subscribers" }}/{{ .ID }}" role="menuitem" class="button ghost" data-testid="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a><hr />- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" :disabled="isLoading('subscribers')" @click.prevent="onDeleteSubscriber({{ .ID }}, {{ ToJSON .Email }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete" :disabled="isLoading('subscribers')" @click.prevent="onDeleteSubscriber({{ .ID }}, {{ ToJSON .Email }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>{{- end }}</menu></ot-dropdown>diff --git a/static/admin/views/template.html b/static/admin/views/template.htmlindex 405ba65c..9f2505dc 100644--- a/static/admin/views/template.html+++ b/static/admin/views/template.html@@ -24,7 +24,7 @@</div></div><div class="col-6 col-end hstack justify-end">- <button type="button" class="outline" data-cy="btn-preview" @click="onPreviewBody" aria-keyshortcuts="F9">{{ Icon "eye" }} {{ .L.T "templates.preview" }}</button>+ <button type="button" class="outline" data-testid="btn-preview" @click="onPreviewBody" aria-keyshortcuts="F9">{{ Icon "eye" }} {{ .L.T "templates.preview" }}</button></div></header>@@ -83,7 +83,7 @@</div><div class="hstack gap-3 justify-end">{{- if $canManage }}- <button type="submit" data-variant="primary" data-cy="btn-save" :disabled="isLoading('templates')" :aria-busy="isLoading('templates')">{{ Icon "save" }} {{ .L.T "globals.buttons.save" }}</button>+ <button type="submit" data-variant="primary" data-testid="btn-save" :disabled="isLoading('templates')" :aria-busy="isLoading('templates')">{{ Icon "save" }} {{ .L.T "globals.buttons.save" }}</button>{{- end }}</div></footer>diff --git a/static/admin/views/templates.html b/static/admin/views/templates.htmlindex 41f21303..73160f58 100644--- a/static/admin/views/templates.html+++ b/static/admin/views/templates.html@@ -21,7 +21,7 @@</div><div class="col-6 col-end align-right hstack justify-end">{{- if $canManage }}- <a href="{{ $base }}/new" class="button" data-variant="primary" data-cy="btn-new">+ <a href="{{ $base }}/new" class="button" data-variant="primary" data-testid="btn-new">{{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}</a>{{- end }}@@ -33,18 +33,18 @@<table><thead><tr>- <th class="cy-name">{{ .L.T "globals.fields.name" }}</th>- <th class="cy-type">{{ .L.T "globals.fields.type" }}</th>- <th class="cy-id">{{ .L.T "globals.fields.id" }}</th>- <th class="cy-created_at">{{ .L.T "globals.fields.createdAt" }}</th>+ <th>{{ .L.T "globals.fields.name" }}</th>+ <th>{{ .L.T "globals.fields.type" }}</th>+ <th>{{ .L.T "globals.fields.id" }}</th>+ <th>{{ .L.T "globals.fields.createdAt" }}</th><th class="actions align-right"></th></tr></thead><tbody>{{- range $d.Templates }}- <tr data-id="{{ .ID }}">+ <tr data-testid="template-row" data-id="{{ .ID }}"><td>- <a href="{{ $base }}/{{ .ID }}" data-cy="btn-edit">{{ .Name }}</a>+ <a href="{{ $base }}/{{ .ID }}" data-testid="btn-edit">{{ .Name }}</a>{{ if .IsDefault }}{{ Badge ($.L.T "templates.default") }}{{ end }}{{- if eq .Type "tx" }}<p class="text-light">{{ .Subject }}</p>{{ end }}</td>@@ -70,17 +70,17 @@{{ Icon "more-vertical" }}</button><menu popover id="tpl-actions-{{ .ID }}">- <button type="button" role="menuitem" class="ghost" data-cy="btn-preview" @click.prevent="onPreview({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "eye" }} {{ $.L.T "templates.preview" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-preview" @click.prevent="onPreview({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "eye" }} {{ $.L.T "templates.preview" }}</button><hr />- <a href="{{ $base }}/{{ .ID }}" role="menuitem" class="button ghost" data-cy="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>+ <a href="{{ $base }}/{{ .ID }}" role="menuitem" class="button ghost" data-testid="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>{{- if $canManage }}- <button type="button" role="menuitem" class="ghost" data-cy="btn-clone" @click.prevent="onClone({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "copy" }} {{ $.L.T "globals.buttons.clone" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-clone" @click.prevent="onClone({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "copy" }} {{ $.L.T "globals.buttons.clone" }}</button>{{- if and (not .IsDefault) (eq .Type "campaign") }}- <button type="button" role="menuitem" class="ghost" data-cy="btn-set-default" :disabled="isLoading('templates')" @click.prevent="onSetDefault({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "check-circle" }} {{ $.L.T "templates.makeDefault" }}</button>+ <button type="button" role="menuitem" class="ghost" data-testid="btn-set-default" :disabled="isLoading('templates')" @click.prevent="onSetDefault({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "check-circle" }} {{ $.L.T "templates.makeDefault" }}</button>{{- end }}{{- if not .IsDefault }}<hr />- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" :disabled="isLoading('templates')" @click.prevent="onDelete({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete" :disabled="isLoading('templates')" @click.prevent="onDelete({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>{{- end }}{{- end }}</menu>diff --git a/static/admin/views/user-role.html b/static/admin/views/user-role.htmlindex 08553b60..2ac71c4a 100644--- a/static/admin/views/user-role.html+++ b/static/admin/views/user-role.html@@ -88,7 +88,7 @@</div><div class="col-6 hstack justify-end"><a href="{{ $base }}" class="button outline">{{ .L.T "globals.buttons.back" }}</a>- <button type="submit" data-variant="primary" data-cy="btn-save" x-show="!disabled" :disabled="isLoading('roles.save')" :aria-busy="isLoading('roles.save')">{{ .L.T "globals.buttons.save" }}</button>+ <button type="submit" data-variant="primary" data-testid="btn-save" x-show="!disabled" :disabled="isLoading('roles.save')" :aria-busy="isLoading('roles.save')">{{ .L.T "globals.buttons.save" }}</button></div></div></footer>diff --git a/static/admin/views/user.html b/static/admin/views/user.htmlindex 04f1fdde..38070d4d 100644--- a/static/admin/views/user.html+++ b/static/admin/views/user.html@@ -62,7 +62,7 @@<fieldset :disabled="form.type === 'api'"><legend>{{ .L.T "users.password" }}</legend><label data-field>- <input type="checkbox" x-model="form.password_login" /> {{ .L.T "users.passwordEnable" }}+ <input type="checkbox" x-model="form.password_login" data-testid="password-login" /> {{ .L.T "users.passwordEnable" }}</label><label data-field>{{ .L.T "users.password" }}@@ -107,7 +107,7 @@<div class="hstack gap-3 justify-end"><a href="{{ $base }}" class="button outline">{{ .L.T "globals.buttons.back" }}</a>{{- if $canSave }}- <button type="submit" data-variant="primary" data-cy="btn-save" :disabled="isLoading('users.save')" :aria-busy="isLoading('users.save')">{{ .L.T "globals.buttons.save" }}</button>+ <button type="submit" data-variant="primary" data-testid="btn-save" :disabled="isLoading('users.save')" :aria-busy="isLoading('users.save')">{{ .L.T "globals.buttons.save" }}</button>{{- end }}</div></footer>diff --git a/static/admin/views/users.html b/static/admin/views/users.htmlindex 6f34cf5b..cd2d5650 100644--- a/static/admin/views/users.html+++ b/static/admin/views/users.html@@ -28,7 +28,7 @@</div><div class="col-6 col-end align-right hstack justify-end">{{- if $d.Can "users:manage" }}- <a href="{{ URI "/admin/users" }}/new" class="button" data-variant="primary" data-cy="btn-new">+ <a href="{{ URI "/admin/users" }}/new" class="button" data-variant="primary" data-testid="btn-new">{{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}</a>{{- end }}@@ -40,11 +40,11 @@{{- if $d.Can "users:manage" }}<template x-if="numSelected > 0"><ot-dropdown class="bulk-actions">- <button popovertarget="bulk-actions" type="button" class="small" data-cy="btn-bulk-actions">+ <button popovertarget="bulk-actions" type="button" class="small" data-testid="btn-bulk-actions"><span x-text="numSelectedLabel"></span> {{ Icon "more-vertical" }}</button><menu popover id="bulk-actions">- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete-users" :disabled="isLoading('users')" @click.prevent="onDeleteSelected(numSelected, selectedQueryParams().toString())">+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete-users" :disabled="isLoading('users')" @click.prevent="onDeleteSelected(numSelected, selectedQueryParams().toString())">{{ Icon "trash-2" }} {{ .L.T "globals.buttons.delete" }} <span x-text="numSelected"></span></button></menu>@@ -58,17 +58,17 @@{{- if $d.Can "users:manage" }}<th width="5%"><input type="checkbox" aria-label="{{ .L.T "globals.buttons.toggleSelect" }}"></th>{{- end }}- <th class="cy-username">{{ .L.T "users.username" }}</th>- <th class="cy-role">{{ .L.Tc "users.role" 1 }}</th>- <th class="cy-name">{{ .L.T "subscribers.email" }}</th>- <th class="cy-created_at">{{ .L.T "globals.fields.createdAt" }}</th>+ <th>{{ .L.T "users.username" }}</th>+ <th>{{ .L.Tc "users.role" 1 }}</th>+ <th>{{ .L.T "subscribers.email" }}</th>+ <th>{{ .L.T "globals.fields.createdAt" }}</th><th>{{ .L.T "users.lastLogin" }}</th><th class="actions align-right"></th></tr></thead><tbody>{{- range $d.Users }}- <tr data-id="{{ .ID }}">+ <tr data-testid="user-row" data-id="{{ .ID }}">{{- if $d.Can "users:manage" }}<td><input name="id" type="checkbox" value="{{ .ID }}"></td>{{- end }}@@ -104,8 +104,8 @@{{ Icon "more-vertical" }}</button><menu popover id="user-actions-{{ .ID }}">- <a href="{{ URI "/admin/users" }}/{{ .ID }}" role="menuitem" class="button ghost" data-cy="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>- <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" :disabled="isLoading('users')" @click.prevent="onDeleteUser({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>+ <a href="{{ URI "/admin/users" }}/{{ .ID }}" role="menuitem" class="button ghost" data-testid="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-testid="btn-delete" :disabled="isLoading('users')" @click.prevent="onDeleteUser({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button></menu></ot-dropdown>{{- end }}diff --git a/tests/helpers.js b/tests/helpers.jsindex 77ee6e72..ae4ea204 100644--- a/tests/helpers.js+++ b/tests/helpers.js@@ -1,5 +1,6 @@import { execSync, execFileSync, spawn } from 'node:child_process';import { setTimeout as sleep } from 'node:timers/promises';+import { expect } from '@playwright/test';const BASE_URL = process.env.LISTMONK_URL || 'http://localhost:9000';const MAILHOG_URL = process.env.MAILHOG_URL || 'http://localhost:8025';@@ -25,6 +26,15 @@ export async function confirm(page) {await page.locator('dialog[open] [data-confirm-ok]').click();}+// Pick a list by name in an <ot-taginput> list selector. Filling the input+// matches a datalist option, which the component turns into a tag/badge.+export async function selectList(scope, name) {+ const input = scope.locator('ot-taginput input');+ await input.click();+ await input.fill(name);+ await expect(scope.locator('ot-taginput .badge').filter({ hasText: name })).toBeVisible();+}+// Log in and persist the session to the shared storage state file.export async function login(context) {const page = await context.newPage();@@ -47,25 +57,46 @@ export async function getMail() {return (await (await fetch(`${MAILHOG_URL}/api/v2/messages`)).json()).items;}-// Point listmonk's SMTP config at MailHog on the freshly installed DB. DB-// credentials come from the LISTMONK_db__* env, falling back to config.toml defaults.-function configureSMTP() {+// Run a SQL statement against the listmonk DB. Credentials come from the+// LISTMONK_db__* env, falling back to config.toml defaults.+function psql(sql) {execFileSync('psql', ['-h', process.env.LISTMONK_db__host || 'localhost','-p', process.env.LISTMONK_db__port || '5432','-U', process.env.LISTMONK_db__user || 'listmonk','-d', process.env.LISTMONK_db__database || 'listmonk',- '-c', `UPDATE settings SET value = '${MAILHOG_SMTP}' WHERE key = 'smtp';`,+ '-c', sql,], { env: { ...process.env, PGPASSWORD: process.env.LISTMONK_db__password || 'listmonk' }, stdio: 'ignore' });}+// Point listmonk's SMTP config at MailHog on the freshly installed DB.+function configureSMTP() {+ psql(`UPDATE settings SET value = '${MAILHOG_SMTP}' WHERE key = 'smtp';`);+}++// Enable bounce processing + the webhook endpoint, and delete on complaints.+// Bounce settings are read into config at boot, so this must run before start.+function configureBounces() {+ const actions = JSON.stringify({+ soft: { count: 2, action: 'none' },+ hard: { count: 1, action: 'blocklist' },+ complaint: { count: 1, action: 'delete' },+ });+ psql(`UPDATE settings SET value = 'true' WHERE key = 'bounce.enabled';+ UPDATE settings SET value = 'true' WHERE key = 'bounce.webhooks_enabled';+ UPDATE settings SET value = '${actions}' WHERE key = 'bounce.actions';`);+}+// Wipe and reinstall the DB by restarting listmonk, then refresh the login// session (a reinstall clears the DB-backed session). The schema can't be// reinstalled under a running server, so the process is killed and relaunched.-export async function resetDB(browser) {+export async function resetDB(browser, { bounces = false } = {}) {try { execSync('pkill -9 listmonk', { stdio: 'ignore' }); } catch { /* none running */ }execSync('./listmonk --install --yes', { cwd: ROOT, env: ENV, stdio: 'ignore' });configureSMTP();+ if (bounces) {+ configureBounces();+ }spawn('./listmonk', ['--static-dir', 'static'], {cwd: ROOT, env: ENV, detached: true, stdio: 'ignore',}).unref();@@ -83,3 +114,26 @@ export async function resetDB(browser) {await login(context);await context.close();}++// Reinstall the DB with no admin user so the app boots into first-time user+// setup mode. Unlike resetDB, it doesn't create a session (there's no user yet).+export async function resetDBBlank() {+ try { execSync('pkill -9 listmonk', { stdio: 'ignore' }); } catch { /* none running */ }++ const env = { ...process.env };+ delete env.LISTMONK_ADMIN_USER;+ delete env.LISTMONK_ADMIN_PASSWORD;++ execSync('./listmonk --install --yes', { cwd: ROOT, env, stdio: 'ignore' });+ configureSMTP();+ spawn('./listmonk', ['--static-dir', 'static'], {+ cwd: ROOT, env, detached: true, stdio: 'ignore',+ }).unref();++ for (let i = 0; i < 100; i += 1) {+ try {+ if ((await fetch(`${BASE_URL}/health`)).ok) break;+ } catch { /* not up yet */ }+ await sleep(200);+ }+}diff --git a/tests/specs/bounces.spec.js b/tests/specs/bounces.spec.jsnew file mode 100644index 00000000..17c714af--- /dev/null+++ b/tests/specs/bounces.spec.js@@ -0,0 +1,82 @@+import { test, expect } from '@playwright/test';+import { openMenu, confirm, resetDB } from '../helpers.js';++const BOUNCES = '/admin/subscribers/bounces';++function bounceRow(page, email) {+ const rows = page.getByTestId('bounce-row');+ return email ? rows.filter({ hasText: email }) : rows;+}++// Register a bounce for an email via the webhook endpoint.+async function postBounce(page, type, email) {+ const res = await page.request.post('/webhooks/bounce', { data: { source: 'api', type, email } });+ expect(res.ok()).toBeTruthy();+}++async function subStatus(page, id) {+ const res = await page.request.get(`/api/subscribers/${id}`);+ return res.ok() ? (await res.json()).data.status : null;+}++test.describe.configure({ mode: 'serial' });++test.describe('Bounces', () => {+ let subs;++ // Bounce processing + webhooks are enabled at install (they're read at boot).+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser, { bounces: true });+ });++ test('reads the seeded subscribers', async ({ page }) => {+ subs = (await (await page.request.get('/api/subscribers')).json()).data.results;+ expect(subs.length).toBe(2);+ });++ test('applies bounce actions by type', async ({ page }) => {+ const [a, b] = subs;++ // Soft bounces don't cross the threshold: the subscriber stays enabled.+ await postBounce(page, 'soft', a.email);+ await postBounce(page, 'soft', a.email);+ expect(await subStatus(page, a.id)).toBe('enabled');++ // Hard bounces blocklist.+ await postBounce(page, 'hard', a.email);+ await postBounce(page, 'hard', a.email);+ expect(await subStatus(page, a.id)).toBe('blocklisted');++ // Complaints delete the subscriber outright.+ await postBounce(page, 'complaint', b.email);+ const res = await page.request.get(`/api/subscribers/${b.id}`);+ expect(res.status()).toBe(400);+ });++ test('lists the recorded bounces', async ({ page }) => {+ await page.goto(BOUNCES);++ // The complaint subscriber (and its bounce) were deleted. The blocklisted+ // subscriber kept its bounces up to the point it was blocklisted.+ const count = await bounceRow(page).count();+ expect(count).toBeGreaterThan(0);+ await expect(bounceRow(page, subs[0].email)).toHaveCount(count);+ await expect(bounceRow(page, subs[1].email)).toHaveCount(0);+ });++ test('views a bounce record and deletes it', async ({ page }) => {+ await page.goto(BOUNCES);+ const before = await bounceRow(page).count();++ const row = bounceRow(page).first();+ await openMenu(row);+ await row.getByTestId('btn-meta').click();+ await expect(page.locator('dialog[open] pre')).toBeVisible();+ await page.locator('dialog[open] button').click();++ await openMenu(row);+ await row.getByTestId('btn-delete').click();+ await confirm(page);+ await expect(bounceRow(page)).toHaveCount(before - 1);+ });+});diff --git a/tests/specs/lists.spec.js b/tests/specs/lists.spec.jsindex 7c94d737..e8e55eb2 100644--- a/tests/specs/lists.spec.js+++ b/tests/specs/lists.spec.js@@ -129,6 +129,12 @@ test.describe('Lists', () => {await expect(row).toContainText('#test');await expect(row).toContainText(`#tag${n}`);}++ // The description isn't on the listing; reopen each edit view to confirm it saved.+ for (const [n, id] of ids.entries()) {+ await page.goto(`${LISTS}/${id}`);+ await expect(page.locator('textarea[name="description"]')).toHaveValue(`desc${n}`);+ }});test('deletes all lists', async ({ page }) => {diff --git a/tests/specs/subscribers.spec.js b/tests/specs/subscribers.spec.jsnew file mode 100644index 00000000..03254dfb--- /dev/null+++ b/tests/specs/subscribers.spec.js@@ -0,0 +1,615 @@+import { test, expect } from '@playwright/test';+import { setTimeout as sleep } from 'node:timers/promises';+import {+ openMenu, confirm, resetDB, selectList, getMail, clearMail,+} from '../helpers.js';++const SUBSCRIBERS = '/admin/subscribers';+const SUB_FORM = '/subscription/form';++// Seeded lists: 1 = Default (private, single opt-in), 2 = Opt-in (public, double opt-in).+const LIST_DEFAULT = 1;+const LIST_OPTIN = 2;++function subRow(page, text) {+ const rows = page.getByTestId('sub-row');+ return text ? rows.filter({ hasText: text }) : rows;+}++function subRowIDs(page) {+ return page.getByTestId('sub-row').evaluateAll((els) => els.map((el) => Number(el.dataset.id)));+}++// The (filtered) total the listing header shows, e.g. "Subscribers (47)".+async function readTotal(page) {+ const txt = await page.locator('.page-title').innerText();+ return Number(txt.match(/\((\d+)\)/)[1]);+}++// Create `n` subscribers via the API. Returns nothing; assert on the DB after.+async function seedSubscribers(page, n, { prefix = 'seed', lists = [], status = 'enabled' } = {}) {+ for (let i = 0; i < n; i += 1) {+ const res = await page.request.post('/api/subscribers', {+ data: {+ email: `${prefix}${i}@example.com`,+ name: `${prefix} ${i}`,+ status,+ lists,+ attribs: { city: 'Bengaluru', age: 20 + (i % 40) },+ },+ });+ expect(res.ok()).toBeTruthy();+ }+}++// Select rows and open the bulk-actions menu. With selectAll, promote the visible+// selection to the whole query (needs total > per-page for the button to render).+async function openBulkMenu(page, { selectAll = false } = {}) {+ await page.locator('thead input[type=checkbox]').check();+ await page.getByTestId('btn-bulk-actions').click();+ if (selectAll) {+ await page.getByTestId('select-all-subscribers').click();+ }+}++// Open the bulk manage-lists dialog and apply an action to the given lists.+async function bulkManageLists(page, {+ action, lists, preconfirm = false, selectAll = false,+}) {+ await openBulkMenu(page, { selectAll });+ await page.getByTestId('btn-manage-lists').click();++ const dialog = page.locator('dialog[open]');+ await dialog.getByTestId(`check-list-${action}`).check();+ for (const l of lists) {+ await selectList(dialog, l);+ }+ if (preconfirm) {+ await dialog.getByTestId('preconfirm').check();+ }++ await Promise.all([+ page.waitForResponse((r) => /\/api\/subscribers(\/query)?\/lists/.test(r.url()) && r.request().method() === 'PUT'),+ dialog.locator('button[type=submit]').click(),+ ]);+}++// Trigger a confirm-guarded bulk action and wait for its API call.+async function bulkConfirm(page, {+ testid, selectAll = false, match,+}) {+ await openBulkMenu(page, { selectAll });+ await page.getByTestId(testid).click();+ await Promise.all([page.waitForResponse(match), confirm(page)]);+}++test.describe.configure({ mode: 'serial' });++test.describe('Subscribers: listing, search & sort', () => {+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ });++ test('shows the two seeded subscribers', async ({ page }) => {+ await page.goto(SUBSCRIBERS);++ await expect(subRow(page)).toHaveCount(2);+ await expect(subRow(page, '[email protected]')).toBeVisible();+ await expect(subRow(page, '[email protected]')).toBeVisible();+ });++ test('searches subscribers', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ const search = page.getByTestId('search');++ for (const c of [+ { q: 'john', email: '[email protected]' },+ { q: 'anon', email: '[email protected]' },+ ]) {+ await search.fill(c.q);+ await search.press('Enter');+ await expect(subRow(page)).toHaveCount(1);+ await expect(subRow(page)).toContainText(c.email);+ }++ await search.fill('');+ await search.press('Enter');+ await expect(subRow(page)).toHaveCount(2);+ });++ test('runs advanced SQL queries', async ({ page }) => {+ const cases = [+ { sql: "subscribers.attribs->>'city'='Bengaluru'", count: 2 },+ { sql: "subscribers.attribs->>'city'='Bengaluru' AND id=1", count: 1 },+ { sql: "(subscribers.attribs->>'good')::BOOLEAN = true AND name like 'Anon%'", count: 1 },+ ];++ for (const c of cases) {+ await page.goto(SUBSCRIBERS);+ await page.getByTestId('btn-advanced-search').click();+ await page.getByTestId('query').fill(c.sql);+ await Promise.all([page.waitForLoadState(), page.getByTestId('btn-query').click()]);+ await expect(subRow(page)).toHaveCount(c.count);+ }+ });++ test('resets the advanced query editor', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await page.getByTestId('btn-advanced-search').click();++ const query = page.getByTestId('query');+ await query.fill("name LIKE '%x%'");+ await expect(page.getByTestId('btn-query-reset')).toBeEnabled();++ await page.getByTestId('btn-query-reset').click();+ await expect(query).toHaveValue('');+ await expect(page.getByTestId('btn-query-reset')).toBeDisabled();+ });++ test('sorts subscribers by every column', async ({ page }) => {+ await page.goto(SUBSCRIBERS);++ const clickSort = async (field, expected) => {+ await page.locator(`a[data-sort-field="${field}"]`).click();+ await expect.poll(() => subRowIDs(page)).toEqual(expected);+ };++ // Seeded: john (id 1, "John Doe"), anon (id 2, "Anon Doe").+ await clickSort('email', [2, 1]);+ await clickSort('email', [1, 2]);+ await clickSort('name', [2, 1]);+ await clickSort('name', [1, 2]);+ await clickSort('created_at', [1, 2]);+ await clickSort('created_at', [2, 1]);+ await clickSort('updated_at', [1, 2]);+ await clickSort('updated_at', [2, 1]);+ });++ test('exports subscribers via the API', async ({ page }) => {+ const cases = [+ { query: '', length: 3 },+ { query: "name ILIKE '%anon%'", length: 2 },+ { query: "name like 'nope'", length: 1 },+ ];++ for (const c of cases) {+ const res = await page.request.get('/api/subscribers/export', { params: { query: c.query } });+ expect(res.ok()).toBeTruthy();+ const lines = (await res.text()).trim().split('\n');+ expect(lines).toHaveLength(c.length);+ }+ });+});++test.describe('Subscribers: create, edit & delete', () => {+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ });++ test('creates a subscriber on a list', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await page.getByTestId('btn-new').click();++ const dialog = page.locator('dialog[open]');+ await dialog.locator('input[name=email]').fill('[email protected]');+ await dialog.locator('input[name=name]').fill('Created');+ await selectList(dialog, 'Default list');+ await Promise.all([+ page.waitForResponse((r) => /\/api\/subscribers$/.test(r.url()) && r.request().method() === 'POST'),+ dialog.getByTestId('btn-save').click(),+ ]);++ // The listing shows the new subscriber on the Default list.+ await page.goto(SUBSCRIBERS);+ const row = subRow(page, '[email protected]');+ await expect(row).toBeVisible();+ await expect(row).toContainText('Default list');+ await expect(row.locator('td.align-center')).toContainText('1');+ });++ test('creates a pre-confirmed subscriber on a double opt-in list', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await page.getByTestId('btn-new').click();++ const dialog = page.locator('dialog[open]');+ await dialog.locator('input[name=email]').fill('[email protected]');+ await dialog.locator('input[name=name]').fill('Confirmed');+ await selectList(dialog, 'Opt-in list');+ // Pre-confirm only enables once a double opt-in list is picked.+ await expect(dialog.getByTestId('preconfirm')).toBeEnabled();+ await dialog.getByTestId('preconfirm').check();+ await Promise.all([+ page.waitForResponse((r) => /\/api\/subscribers$/.test(r.url()) && r.request().method() === 'POST'),+ dialog.getByTestId('btn-save').click(),+ ]);++ // The listing badge shows the Opt-in list subscription as confirmed.+ await page.goto(SUBSCRIBERS);+ const row = subRow(page, '[email protected]');+ await expect(row).toContainText('Opt-in list');+ await expect(row).toContainText('Confirmed');+ });++ test('edits a subscriber and blocklists via the status field', async ({ page }) => {+ await page.goto(`${SUBSCRIBERS}/1`);+ await page.locator('input[name=email]').fill('[email protected]');+ await page.locator('input[name=name]').fill('Edited Name');+ await page.locator('select[name=status]').selectOption('blocklisted');+ await page.locator('textarea[name=attribs]').fill('{"string": "hello", "ints": [1, 2, 3], "sub": {"bool": true}}');+ // Saving reloads the edit view; it re-renders with the persisted values.+ await Promise.all([page.waitForEvent('load'), page.getByTestId('btn-save').click()]);+ await expect(page.locator('input[name=email]')).toHaveValue('[email protected]');+ await expect(page.locator('input[name=name]')).toHaveValue('Edited Name');+ await expect(page.locator('select[name=status]')).toHaveValue('blocklisted');+ const attribs = await page.locator('textarea[name=attribs]').inputValue();+ expect(attribs).toContain('"string": "hello"');+ expect(attribs).toContain('"bool": true');++ // The listing marks blocklisted subscribers.+ await page.goto(SUBSCRIBERS);+ await expect(subRow(page, '[email protected]')).toHaveClass(/blocklisted/);+ });++ test('rejects invalid attribs JSON', async ({ page }) => {+ await page.goto(`${SUBSCRIBERS}/1`);+ await page.locator('textarea[name=attribs]').fill('{ not valid json');+ await page.getByTestId('btn-save').click();++ await expect(page.locator('.toast')).toBeVisible();+ // No navigation happened: still on the edit page.+ expect(page.url()).toContain(`${SUBSCRIBERS}/1`);+ });++ test('exposes a per-row data download link', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ const row = subRow(page, '[email protected]');+ await openMenu(row);+ await expect(row.getByTestId('btn-download')).toHaveAttribute('href', /\/api\/subscribers\/2\/export$/);+ });++ test('deletes a subscriber from the row menu', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ const before = await subRow(page).count();++ const row = subRow(page, '[email protected]');+ await openMenu(row);+ await row.getByTestId('btn-delete').click();+ await confirm(page);++ await expect(subRow(page)).toHaveCount(before - 1);+ await expect(subRow(page, '[email protected]')).toHaveCount(0);+ });+});++test.describe('Subscribers: filters & pagination', () => {+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ const context = await browser.newContext({+ storageState: new URL('../.auth/admin.json', import.meta.url).pathname,+ });+ const page = await context.newPage();+ // 25 on the Default list → 27 total (2 seeded), spanning two pages.+ await seedSubscribers(page, 25, { prefix: 'pag', lists: [LIST_DEFAULT] });+ await context.close();+ });++ test('paginates the listing', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await expect(subRow(page)).toHaveCount(20);++ const nav = page.locator('nav.pagination');+ await expect(nav).toBeVisible();+ await Promise.all([page.waitForLoadState(), nav.locator('a', { hasText: '2' }).click()]);++ await expect(page).toHaveURL(/[?&]page=2/);+ await expect(subRow(page)).toHaveCount(7);+ await expect(nav.locator('a.pg-selected')).toHaveText('2');+ });++ test('filters by list', async ({ page }) => {+ // Only anon (id 2) is on the Opt-in list.+ await page.goto(`${SUBSCRIBERS}/lists/${LIST_OPTIN}`);+ await expect(subRow(page)).toHaveCount(1);+ await expect(subRow(page, '[email protected]')).toBeVisible();+ await expect(page.locator('.page-title')).toContainText('Opt-in list');++ // Clearing the filter badge returns to the full listing.+ await Promise.all([page.waitForLoadState(), page.getByTestId('btn-remove-filter').click()]);+ await expect(page).toHaveURL(/\/admin\/subscribers$/);+ });++ test('filters by subscriber status', async ({ page }) => {+ await page.request.put('/api/subscribers/blocklist', { data: { ids: [1] } });++ await page.goto(`${SUBSCRIBERS}?status=blocklisted`);+ await expect(subRow(page)).toHaveCount(1);+ await expect(subRow(page, '[email protected]')).toBeVisible();+ await expect(page.locator('.page-title')).toContainText('Blocklisted');+ });++ test('filters a list by subscription status', async ({ page }) => {+ // anon (id 2) is the sole Opt-in list member; confirm its subscription.+ await page.request.put('/api/subscribers/lists', {+ data: {+ ids: [2], action: 'add', target_list_ids: [LIST_OPTIN], status: 'confirmed',+ },+ });++ // The confirmed filter shows only anon, with a Confirmed badge.+ await page.goto(`${SUBSCRIBERS}/lists/${LIST_OPTIN}?subscription_status=confirmed`);+ await expect(page.locator('.page-title')).toContainText('Confirmed');+ await expect(subRow(page)).toHaveCount(1);+ await expect(subRow(page, '[email protected]')).toContainText('Confirmed');+ });+});++test.describe('Subscribers: bulk actions', () => {+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ const context = await browser.newContext({+ storageState: new URL('../.auth/admin.json', import.meta.url).pathname,+ });+ const page = await context.newPage();+ // 45 fresh subscribers → 47 total, spanning three pages.+ await seedSubscribers(page, 45, { prefix: 'bulk' });+ await context.close();+ });++ test('adds a list to the selected (visible) page', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ const count = await subRow(page).count();++ await bulkManageLists(page, { action: 'add', lists: ['Default list'] });++ // Every subscriber on the reloaded page now carries the Default list badge.+ await expect(subRow(page)).toHaveCount(count);+ await expect(subRow(page).filter({ hasText: 'Default list' })).toHaveCount(count);+ });++ test('adds a pre-confirmed list to all via select-all query', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await bulkManageLists(page, {+ action: 'add', lists: ['Opt-in list'], preconfirm: true, selectAll: true,+ });++ // Everyone (47) ends up on the Opt-in list.+ await page.goto(`${SUBSCRIBERS}/lists/${LIST_OPTIN}`);+ expect(await readTotal(page)).toBe(47);+ // New subscriptions are confirmed; only the pre-existing anon stays unconfirmed.+ await page.goto(`${SUBSCRIBERS}/lists/${LIST_OPTIN}?subscription_status=confirmed`);+ expect(await readTotal(page)).toBe(46);+ });++ test('unsubscribes all from a list via query', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await bulkManageLists(page, { action: 'unsubscribe', lists: ['Opt-in list'], selectAll: true });++ // All 47 Opt-in subscriptions are now unsubscribed.+ await page.goto(`${SUBSCRIBERS}/lists/${LIST_OPTIN}?subscription_status=unsubscribed`);+ expect(await readTotal(page)).toBe(47);+ });++ test('removes a list from all via query', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await bulkManageLists(page, { action: 'remove', lists: ['Opt-in list'], selectAll: true });++ // The Opt-in list has no members left.+ await page.goto(`${SUBSCRIBERS}/lists/${LIST_OPTIN}`);+ await expect(page.locator('.empty-state')).toBeVisible();+ });++ test('blocklists the selected (visible) page', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ const count = await subRow(page).count();++ await bulkConfirm(page, {+ testid: 'btn-manage-blocklist',+ match: (r) => /\/api\/subscribers\/blocklist$/.test(r.url()) && r.request().method() === 'PUT',+ });++ // Exactly the selected page's subscribers are blocklisted; nobody else.+ await page.goto(`${SUBSCRIBERS}?status=blocklisted`);+ expect(await readTotal(page)).toBe(count);+ });++ test('blocklists all via query', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await bulkConfirm(page, {+ testid: 'btn-manage-blocklist',+ selectAll: true,+ match: (r) => /\/api\/subscribers\/query\/blocklist$/.test(r.url()) && r.request().method() === 'PUT',+ });++ await page.goto(`${SUBSCRIBERS}?status=blocklisted`);+ expect(await readTotal(page)).toBe(47);+ });++ test('exports the selection via the UI', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await openBulkMenu(page, { selectAll: true });++ const [download] = await Promise.all([+ page.waitForEvent('download'),+ (async () => {+ await page.getByTestId('btn-export-subscribers').click();+ await confirm(page);+ })(),+ ]);+ expect(download.suggestedFilename()).toBe('subscribers.csv');+ });++ test('deletes the selected (visible) page', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ const before = await readTotal(page);+ const count = await subRow(page).count();++ await bulkConfirm(page, {+ testid: 'btn-delete-subscribers',+ match: (r) => /\/api\/subscribers\?/.test(r.url()) && r.request().method() === 'DELETE',+ });++ // The total dropped by exactly the page's worth of subscribers.+ expect(await readTotal(page)).toBe(before - count);+ });++ test('deletes everything via query', async ({ page }) => {+ await page.goto(SUBSCRIBERS);+ await bulkConfirm(page, {+ testid: 'btn-delete-subscribers',+ selectAll: true,+ match: (r) => /\/api\/subscribers\/query\/delete$/.test(r.url()) && r.request().method() === 'POST',+ });++ await expect(page.locator('.empty-state')).toBeVisible();+ expect(await readTotal(page)).toBe(0);+ });+});++test.describe('Subscriber detail: lists & subscriptions', () => {+ const listRow = (page, name) => page.locator('.subscriptions tbody tr').filter({ hasText: name });++ // Per-subscription actions confirm, then reload the page on success.+ async function rowAction(page, name, testid) {+ const row = listRow(page, name);+ await openMenu(row);+ await Promise.all([+ page.waitForEvent('load'),+ (async () => { await row.getByTestId(testid).click(); await confirm(page); })(),+ ]);+ }++ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ });++ test('adds a list via the manage dialog', async ({ page }) => {+ await page.goto(`${SUBSCRIBERS}/1/lists`);+ await page.getByTestId('btn-manage').click();++ const dialog = page.locator('dialog[open]');+ await dialog.getByTestId('check-list-add').check();+ await selectList(dialog, 'Opt-in list');+ await Promise.all([+ page.waitForEvent('load'),+ dialog.locator('button[type=submit]').click(),+ ]);++ await expect(listRow(page, 'Opt-in list')).toBeVisible();+ await expect(listRow(page, 'Opt-in list').locator('.status-unconfirmed')).toBeVisible();+ });++ test('sends an opt-in confirmation email', async ({ page }) => {+ await clearMail();+ await page.goto(`${SUBSCRIBERS}/1/lists`);++ const btn = page.getByTestId('btn-send-optin');+ await expect(btn).toBeEnabled();+ // Sending shows a toast (no reload), so wait on the API call.+ await Promise.all([+ page.waitForResponse((r) => /\/api\/subscribers\/1\/optin$/.test(r.url()) && r.request().method() === 'POST'),+ (async () => { await btn.click(); await confirm(page); })(),+ ]);++ await expect.poll(async () => (await getMail()).length, { timeout: 10000 }).toBeGreaterThan(0);+ expect((await getMail())[0].Content.Headers.To[0]).toContain('[email protected]');+ });++ test('confirms a double opt-in subscription', async ({ page }) => {+ await page.goto(`${SUBSCRIBERS}/1/lists`);+ await rowAction(page, 'Opt-in list', 'btn-confirm-sub');+ await expect(listRow(page, 'Opt-in list').locator('.status-confirmed')).toBeVisible();+ });++ test('unsubscribes and re-subscribes a subscription', async ({ page }) => {+ await page.goto(`${SUBSCRIBERS}/1/lists`);+ await rowAction(page, 'Opt-in list', 'btn-unsubscribe');+ await expect(listRow(page, 'Opt-in list').locator('.status-unsubscribed')).toBeVisible();++ await page.goto(`${SUBSCRIBERS}/1/lists`);+ await rowAction(page, 'Opt-in list', 'btn-resubscribe');+ await expect(listRow(page, 'Opt-in list').locator('.status-unconfirmed')).toBeVisible();+ });++ test('deletes a subscription', async ({ page }) => {+ await page.goto(`${SUBSCRIBERS}/1/lists`);+ await rowAction(page, 'Default list', 'btn-delete-sub');+ await expect(listRow(page, 'Default list')).toHaveCount(0);+ });+});++test.describe('Subscriber detail: activity tab', () => {+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ });++ test('shows the activity stat cards', async ({ page }) => {+ await page.goto(`${SUBSCRIBERS}/1/activity`);+ const stats = page.locator('.activity .stat-value');+ await expect(stats).toHaveCount(3);+ // No campaigns yet: campaigns, views and clicks are all zero.+ for (let i = 0; i < 3; i += 1) {+ await expect(stats.nth(i)).toHaveText('0');+ }+ });+});++test.describe('Domain blocklist', () => {+ let publicUUID;++ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);++ const context = await browser.newContext({+ storageState: new URL('../.auth/admin.json', import.meta.url).pathname,+ });+ const page = await context.newPage();++ const { data } = await (await page.request.get('/api/lists')).json();+ publicUUID = data.results.find((l) => l.type === 'public').uuid;++ // Blocklisting domains SIGHUPs the server, which re-execs. Wait for it to boot.+ await page.request.put('/api/settings/privacy.domain_blocklist', { data: ['ban.net', 'ban.org', 'ban.com'] });+ await sleep(1500);+ await expect.poll(async () => {+ try {+ return (await page.request.get('/health')).ok();+ } catch {+ return false;+ }+ }, { timeout: 20000, intervals: [300] }).toBe(true);++ await context.close();+ });++ test('rejects blocklisted domains on the public form', async ({ page }) => {+ const submit = async (email) => {+ const res = await page.request.post(SUB_FORM, {+ form: { email, name: 'test', l: publicUUID }, maxRedirects: 0,+ });+ return res.text();+ };++ expect(await submit('[email protected]')).not.toMatch(/error/i);+ expect(await submit('[email protected]')).toMatch(/error/i);+ });++ test('rejects blocklisted domains via the admin API', async ({ page }) => {+ // Allowed domain is accepted.+ let res = await page.request.post('/api/subscribers', {+ data: { email: '[email protected]', name: 'test', lists: [1], status: 'enabled' },+ });+ expect(res.status()).toBe(200);++ // New subscriber on a banned domain is rejected.+ res = await page.request.post('/api/subscribers', {+ data: { email: '[email protected]', name: 'test', lists: [1], status: 'enabled' },+ });+ expect(res.status()).toBe(400);++ // Editing an existing subscriber onto a banned domain is rejected.+ res = await page.request.put('/api/subscribers/1', {+ data: { email: '[email protected]', name: 'test', lists: [1], status: 'enabled' },+ });+ expect(res.status()).toBe(400);+ });+});diff --git a/tests/specs/templates.spec.js b/tests/specs/templates.spec.jsnew file mode 100644index 00000000..a674bc8a--- /dev/null+++ b/tests/specs/templates.spec.js@@ -0,0 +1,123 @@+import { test, expect } from '@playwright/test';+import { openMenu, confirm, resetDB } from '../helpers.js';++const TEMPLATES = '/admin/templates';++// Find a template row by name.+function tplRow(page, name) {+ const rows = page.getByTestId('template-row');+ return name ? rows.filter({ hasText: name }) : rows;+}++// Map of template name -> id from the API.+async function templateIDs(page) {+ const { data } = await (await page.request.get('/api/templates')).json();+ return Object.fromEntries(data.map((t) => [t.name, t.id]));+}++test.describe.configure({ mode: 'serial' });++test.describe('Templates', () => {+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ });++ test('shows the seeded default templates', async ({ page }) => {+ await page.goto(TEMPLATES);++ await expect(tplRow(page)).toHaveCount(4);+ for (const name of ['Default campaign template', 'Default archive template',+ 'Sample transactional template', 'Sample visual template']) {+ await expect(tplRow(page, name)).toBeVisible();+ }+ });++ test('clones a campaign template', async ({ page }) => {+ await page.goto(TEMPLATES);++ const row = tplRow(page, 'Default campaign template');+ // The clone name is entered via a native prompt().+ page.once('dialog', (d) => d.accept('cloned campaign'));+ await openMenu(row);+ await row.getByTestId('btn-clone').click();++ await expect(tplRow(page, 'cloned campaign')).toBeVisible();+ });++ test('clones a transactional template', async ({ page }) => {+ await page.goto(TEMPLATES);++ const row = tplRow(page, 'Sample transactional template');+ page.once('dialog', (d) => d.accept('cloned tx'));+ await openMenu(row);+ await row.getByTestId('btn-clone').click();++ await expect(tplRow(page, 'cloned tx')).toBeVisible();+ });++ test('edits a template name and body', async ({ page }) => {+ const ids = await templateIDs(page);+ await page.goto(`${TEMPLATES}/${ids['Default campaign template']}`);++ await page.locator('input[name=name]').fill('edited');++ // The body is a CodeMirror <code-editor>; set its value directly.+ const body = '<span>test</span><div class="wrap">{{ template "content" . }}</div>';+ await page.locator('code-editor').evaluate((el, v) => { el.value = v; }, body);++ // Saving PUTs then reloads the same page; wait for the reload before navigating.+ await Promise.all([+ page.waitForEvent('load'),+ page.getByTestId('btn-save').click(),+ ]);++ await page.goto(TEMPLATES);+ await expect(tplRow(page, 'edited')).toBeVisible();+ });++ test('previews templates with the edited and cloned bodies', async ({ page }) => {+ const ids = await templateIDs(page);++ // The edited template has a bare body (the raw "test" markup).+ const edited = await (await page.request.get(`/api/templates/${ids.edited}/preview`)).text();+ expect(edited).toContain('test');+ expect(edited).toContain('Hi there');++ // The clone kept the full campaign template (wrapper + unsubscribe footer).+ const cloned = await (await page.request.get(`/api/templates/${ids['cloned campaign']}/preview`)).text();+ expect(cloned).toContain('Hi there');+ expect(cloned).toContain('Unsubscribe');++ // The cloned transactional template renders its sample content.+ const tx = await (await page.request.get(`/api/templates/${ids['cloned tx']}/preview`)).text();+ expect(tx).toContain('Order number');+ });++ test('sets a new default template', async ({ page }) => {+ await page.goto(TEMPLATES);++ const row = tplRow(page, 'cloned campaign');+ await openMenu(row);+ await row.getByTestId('btn-set-default').click();+ await confirm(page);++ // The new default can't be deleted; the previous default now can.+ await expect(tplRow(page, 'cloned campaign')).toContainText('Default');+ await expect(tplRow(page, 'cloned campaign').getByTestId('btn-delete')).toHaveCount(0);+ await expect(tplRow(page, 'edited').getByTestId('btn-delete')).toHaveCount(1);+ });++ test('deletes templates', async ({ page }) => {+ await page.goto(TEMPLATES);++ for (const name of ['Default archive template', 'Sample transactional template']) {+ const row = tplRow(page, name);+ await openMenu(row);+ await row.getByTestId('btn-delete').click();+ await confirm(page);+ await expect(row).toHaveCount(0);+ }++ await expect(tplRow(page)).toHaveCount(4);+ });+});diff --git a/tests/specs/users.spec.js b/tests/specs/users.spec.jsnew file mode 100644index 00000000..6047f490--- /dev/null+++ b/tests/specs/users.spec.js@@ -0,0 +1,305 @@+import { test, expect } from '@playwright/test';+import { openMenu, confirm, resetDB, resetDBBlank } from '../helpers.js';++const USERS = '/admin/users';+const USER_ROLES = '/admin/users/roles';+const LIST_ROLES = '/admin/users/roles/lists';++function roleRow(page, name) {+ const rows = page.getByTestId('role-row');+ return name ? rows.filter({ hasText: name }) : rows;+}++function userRow(page, name) {+ const rows = page.getByTestId('user-row');+ return name ? rows.filter({ hasText: name }) : rows;+}++// Open a role's edit view by name (via the listing), reloading it from the server.+async function gotoRoleEdit(page, base, name) {+ await page.goto(base);+ const id = await roleRow(page, name).getAttribute('data-id');+ await page.goto(`${base}/${id}`);+}++// Open a user's edit view by name, reloading it from the server.+async function gotoUserEdit(page, name) {+ await page.goto(USERS);+ const id = await userRow(page, name).getAttribute('data-id');+ await page.goto(`${USERS}/${id}`);+}++async function login(page, username, password) {+ await page.goto('/admin/login?next=/admin/lists');+ await page.locator('input[name=username]').fill(username);+ await page.locator('input[name=password]').fill(password);+ await Promise.all([+ page.waitForURL('**/admin/lists'),+ page.locator('form[action="/admin/login"] button[type=submit]').click(),+ ]);+}++test.describe.configure({ mode: 'serial' });++test.describe('First-time user setup', () => {+ // Start unauthenticated: the blank DB has no users yet.+ test.use({ storageState: { cookies: [], origins: [] } });++ test.beforeAll(async () => {+ await resetDBBlank();+ });++ test('creates the initial superadmin user', async ({ page }) => {+ await page.goto('/admin/login');++ await page.locator('input[name=email]').fill('[email protected]');+ await page.locator('input[name=username]').fill('super');+ await page.locator('input[name=password]').fill('super123');+ await page.locator('input[name=password2]').fill('super123');+ await Promise.all([+ page.waitForURL((url) => !url.pathname.includes('/login')),+ page.locator('button[type=submit]').click(),+ ]);++ // The new user is the "Super Admin" (role id 1).+ await page.goto(USERS);+ const row = userRow(page, 'super');+ await openMenu(row);+ await Promise.all([page.waitForURL('**/admin/users/*'), row.getByTestId('btn-edit').click()]);+ await expect(page.locator('select[name=user_role]')).toHaveValue('1');+ });+});++test.describe('Users, roles & login', () => {+ test.beforeAll(async ({ browser }) => {+ await resetDB(browser);+ });++ test('adds user roles', async ({ page }) => {+ // "first": accept the default permissions.+ await page.goto(USER_ROLES);+ await page.getByTestId('btn-new').click();+ await page.locator('input[name=name]').fill('first');+ await Promise.all([+ page.waitForURL((url) => url.pathname.endsWith('/users/roles')),+ page.getByTestId('btn-save').click(),+ ]);++ // "second": every permission checked.+ await page.getByTestId('btn-new').click();+ await page.locator('input[name=name]').fill('second');+ const boxes = page.locator('form input[type=checkbox]');+ for (let i = 0, n = await boxes.count(); i < n; i += 1) {+ await boxes.nth(i).check();+ }+ await Promise.all([+ page.waitForURL((url) => url.pathname.endsWith('/users/roles')),+ page.getByTestId('btn-save').click(),+ ]);++ await expect(roleRow(page)).toHaveCount(3);++ // Reopen "second": every permission checkbox came back checked.+ await gotoRoleEdit(page, USER_ROLES, 'second');+ await expect(page.locator('form input[type=checkbox]:checked')).not.toHaveCount(0);+ await expect(page.locator('form input[type=checkbox]:not(:checked)')).toHaveCount(0);+ });++ test('edits a user role', async ({ page }) => {+ await page.goto(USER_ROLES);+ const row = roleRow(page, 'first');+ await openMenu(row);+ await row.getByTestId('btn-edit').click();++ await page.locator('input[value="users:get"]').check();+ await Promise.all([+ page.waitForResponse((r) => /\/api\/roles\/users\/\d+/.test(r.url()) && r.request().method() === 'PUT'),+ page.getByTestId('btn-save').click(),+ ]);++ // Reopen the role: "users:get" (not a default) is checked, proving the edit stuck.+ await gotoRoleEdit(page, USER_ROLES, 'first');+ await expect(page.locator('input[value="users:get"]')).toBeChecked();+ });++ test('clones and deletes a user role', async ({ page }) => {+ await page.goto(USER_ROLES);++ const clone = roleRow(page).last();+ page.once('dialog', (d) => d.accept('second copy'));+ await openMenu(clone);+ await clone.getByTestId('btn-clone').click();+ await expect(roleRow(page)).toHaveCount(4);+ await expect(roleRow(page, 'second copy')).toBeVisible();++ const last = roleRow(page).last();+ await openMenu(last);+ await last.getByTestId('btn-delete').click();+ await confirm(page);+ await expect(roleRow(page)).toHaveCount(3);+ await expect(roleRow(page, 'second copy')).toHaveCount(0);+ });++ test('adds list roles', async ({ page }) => {+ // "first": a single list.+ await page.goto(LIST_ROLES);+ await page.getByTestId('btn-new').click();+ await page.locator('input[name=name]').fill('first');+ await page.getByTestId('btn-add-list').click();+ await Promise.all([+ page.waitForURL((url) => url.pathname.endsWith('/roles/lists')),+ page.getByTestId('btn-save').click(),+ ]);++ // "second": both lists.+ await page.getByTestId('btn-new').click();+ await page.locator('input[name=name]').fill('second');+ await page.getByTestId('btn-add-list').click();+ await page.getByTestId('btn-add-list').click();+ await Promise.all([+ page.waitForURL((url) => url.pathname.endsWith('/roles/lists')),+ page.getByTestId('btn-save').click(),+ ]);++ await expect(roleRow(page)).toHaveCount(2);++ // Reopen each: "first" lists one row, "second" lists both.+ await gotoRoleEdit(page, LIST_ROLES, 'first');+ await expect(page.locator('form tbody tr')).toHaveCount(1);+ await gotoRoleEdit(page, LIST_ROLES, 'second');+ await expect(page.locator('form tbody tr')).toHaveCount(2);+ });++ test('edits a list role', async ({ page }) => {+ await page.goto(LIST_ROLES);+ const row = roleRow(page, 'second');+ await openMenu(row);+ await row.getByTestId('btn-edit').click();++ // Drop the "manage" permission on the second list.+ await page.locator('tbody tr').nth(1).locator('input[value="list:manage"]').uncheck();+ await Promise.all([+ page.waitForResponse((r) => /\/api\/roles\/lists\/\d+/.test(r.url()) && r.request().method() === 'PUT'),+ page.getByTestId('btn-save').click(),+ ]);++ // Reopen the role: both lists keep "view", exactly one lost "manage".+ await gotoRoleEdit(page, LIST_ROLES, 'second');+ await expect(page.locator('input[value="list:get"]:checked')).toHaveCount(2);+ await expect(page.locator('input[value="list:manage"]:checked')).toHaveCount(1);+ });++ test('clones and deletes a list role', async ({ page }) => {+ await page.goto(LIST_ROLES);++ const clone = roleRow(page).last();+ page.once('dialog', (d) => d.accept('second copy'));+ await openMenu(clone);+ await clone.getByTestId('btn-clone').click();+ await expect(roleRow(page)).toHaveCount(3);+ await expect(roleRow(page, 'second copy')).toBeVisible();++ const last = roleRow(page).last();+ await openMenu(last);+ await last.getByTestId('btn-delete').click();+ await confirm(page);+ await expect(roleRow(page)).toHaveCount(2);+ await expect(roleRow(page, 'second copy')).toHaveCount(0);+ });++ test('adds users', async ({ page }) => {+ const cases = [+ { name: 'first', userRole: 'first', listRole: 'first' },+ { name: 'second', userRole: 'second', listRole: 'second' },+ { name: 'third', userRole: 'first', listRole: 'first' },+ ];++ for (const c of cases) {+ await page.goto(USERS);+ await page.getByTestId('btn-new').click();+ await page.locator('input[name=username]').fill(c.name);+ await page.locator('input[name=name]').fill(c.name);+ await page.locator('input[name=email]').fill(`${c.name}@domain.com`);+ await page.getByTestId('password-login').check();+ await page.locator('input[name=password]').fill(`${c.name}000000`);+ await page.locator('input[name=password2]').fill(`${c.name}000000`);+ await page.locator('select[name=user_role]').selectOption({ label: c.userRole });+ await page.locator('select[name=list_role]').selectOption({ label: c.listRole });+ await Promise.all([+ page.waitForURL((url) => url.pathname.endsWith('/admin/users')),+ page.getByTestId('btn-save').click(),+ ]);+ }++ // admin + 3 created.+ await expect(userRow(page)).toHaveCount(4);++ // The listing renders each user's role badges. Read the rows and confirm the+ // roles match (usernames and role names overlap, so match on the username link).+ const rows = await userRow(page).evaluateAll((els) => els.map((el) => ({+ username: el.querySelector('a[href*="/admin/users/"]').textContent.trim(),+ userRole: el.querySelector('a[href*="user_role_id"]')?.textContent.trim(),+ listRole: el.querySelector('a[href*="list_role_id"]')?.textContent.trim(),+ })));+ for (const c of cases) {+ const row = rows.find((r) => r.username === c.name);+ expect(row.userRole).toBe(c.userRole);+ expect(row.listRole).toBe(c.listRole);+ }+ });++ test('edits a user', async ({ page }) => {+ await gotoUserEdit(page, 'third');+ await page.getByTestId('password-login').uncheck();+ await page.locator('select[name=user_role]').selectOption({ label: 'second' });+ await page.locator('select[name=list_role]').selectOption({ label: 'second' });+ await Promise.all([+ page.waitForResponse((r) => /\/api\/users\/\d+/.test(r.url()) && r.request().method() === 'PUT'),+ page.getByTestId('btn-save').click(),+ ]);++ // Reopen the edit view: the new roles and disabled password login are reflected.+ await gotoUserEdit(page, 'third');+ await expect(page.getByTestId('password-login')).not.toBeChecked();+ await expect(page.locator('select[name=user_role] option:checked')).toContainText('second');+ await expect(page.locator('select[name=list_role] option:checked')).toContainText('second');+ });++ test('deletes a user', async ({ page }) => {+ await page.goto(USERS);+ const row = userRow(page, 'third');+ await openMenu(row);+ await row.getByTestId('btn-delete').click();+ await confirm(page);++ await expect(userRow(page)).toHaveCount(3);+ await expect(userRow(page, 'third')).toHaveCount(0);+ });++ test('logs in as a single-list user', async ({ browser }) => {+ const context = await browser.newContext({ storageState: { cookies: [], origins: [] } });+ const page = await context.newPage();+ await login(page, 'first', 'first000000');++ // Only the one list granted by the list role, with no create button.+ await expect(page.getByTestId('list-row')).toHaveCount(1);+ await expect(page.getByTestId('list-row')).toContainText('Default list');+ await expect(page.getByTestId('btn-new')).toHaveCount(0);+ await expect(page.getByTestId('list-row').getByTestId('btn-edit')).toHaveCount(1);++ await context.close();+ });++ test('logs in as an all-permissions user', async ({ browser }) => {+ const context = await browser.newContext({ storageState: { cookies: [], origins: [] } });+ const page = await context.newPage();+ await login(page, 'second', 'second000000');++ // The superadmin-equivalent role sees every list with full actions.+ await expect(page.getByTestId('list-row')).toHaveCount(2);+ await expect(page.getByTestId('list-row').getByTestId('btn-edit')).toHaveCount(2);+ await expect(page.getByTestId('list-row').getByTestId('btn-delete')).toHaveCount(2);++ await context.close();+ });+});