Skip to content

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

SSR: Port subscribers pages/forms completely.

Kailash Nadh7cd1092a45a7
diff --git a/cmd/admin.go b/cmd/admin.go
index 5ac83ae1..9b99485b 100644
--- a/cmd/admin.go
+++ b/cmd/admin.go
@@ -68,10 +68,25 @@ var adminJSI18nKeys = []string{
"lists.confirmSub",
"lists.optinTo",
"lists.newList",
+ "lists.optins.single",
+ "lists.optins.double",
"public.sub",
"public.subName",
"subscribers.email",
+ "subscribers.confirmDelete",
+ "subscribers.confirmExport",
+ "subscribers.confirmBlocklist",
+ "subscribers.subscribersDeleted",
+ "subscribers.listChangeApplied",
+ "subscribers.sentOptinConfirm",
+ "subscribers.invalidJSON",
+ "subscribers.status.enabled",
+ "subscribers.status.blocklisted",
+ "subscribers.status.subscribed",
+ "subscribers.status.unsubscribed",
+ "subscribers.status.confirmed",
+ "subscribers.status.unconfirmed",
}
func (a *App) makeServerConfig() (serverConfig, error) {
diff --git a/cmd/handlers.go b/cmd/handlers.go
index 21ed56e0..72f899be 100644
--- a/cmd/handlers.go
+++ b/cmd/handlers.go
@@ -75,6 +75,14 @@ func initHTTPHandlers(e *echo.Echo, a *App) {
g.GET(path.Join(uriAdmin, "/lists"), a.ViewLists)
g.GET(path.Join(uriAdmin, "/lists/:id"), hasID(a.ViewList))
g.GET(path.Join(uriAdmin, "/lists/forms"), a.ViewForms)
+ g.GET(path.Join(uriAdmin, "/subscribers"), a.ViewSubscribers)
+ g.POST(path.Join(uriAdmin, "/subscribers"), a.ViewSubscribers)
+ g.GET(path.Join(uriAdmin, "/subscribers/lists/:id"), hasID(a.ViewSubscribers))
+ g.POST(path.Join(uriAdmin, "/subscribers/lists/:id"), hasID(a.ViewSubscribers))
+ g.GET(path.Join(uriAdmin, "/subscribers/:id"), hasID(a.ViewSubscriber))
+ g.GET(path.Join(uriAdmin, "/subscribers/:id/lists"), hasID(a.ViewSubscriber))
+ g.GET(path.Join(uriAdmin, "/subscribers/:id/bounces"), hasID(a.ViewSubscriberBounces))
+ g.GET(path.Join(uriAdmin, "/subscribers/:id/activity"), hasID(a.ViewSubscriberActivity))
}
// =================================================================
@@ -307,7 +315,6 @@ func initHTTPHandlers(e *echo.Echo, a *App) {
}
}
-
// HealthCheck is a healthcheck endpoint that returns a 200 response.
func (a *App) HealthCheck(c echo.Context) error {
return c.JSON(http.StatusOK, okResp{true})
diff --git a/cmd/subscribers.go b/cmd/subscribers.go
index 086aa2aa..f83f1384 100644
--- a/cmd/subscribers.go
+++ b/cmd/subscribers.go
@@ -9,6 +9,7 @@ import (
"net/url"
"strconv"
"strings"
+ "time"
"github.com/knadh/listmonk/internal/auth"
"github.com/knadh/listmonk/internal/i18n"
@@ -55,6 +56,252 @@ var (
}
)
+// subscribersView is the admin page view for the subscribers list page.
+type subscribersView struct {
+ adminView
+
+ Subscribers []models.Subscriber
+ Page models.PageProps
+ AllLists []models.List
+ CurrentList *models.List
+}
+
+// subscriberView is the admin page view for a single subscriber.
+type subscriberView struct {
+ adminView
+
+ Tab string
+ Subscriber models.Subscriber
+ AllLists []models.List
+ Bounces []models.Bounce
+ CampaignViews []subCampaignView
+ LinkClicks []subLinkClick
+ TotalViews int
+ TotalClicks int
+}
+
+// subCampaignView and subLinkClick are the parsed rows of a subscriber's activity,
+// unmarshalled from the JSON returned by GetSubscriberActivity.
+type subCampaignView struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Subject string `json:"subject"`
+ ViewCount int `json:"view_count"`
+ LastViewedAt time.Time `json:"last_viewed_at"`
+}
+
+type subLinkClick struct {
+ URL string `json:"url"`
+ CampaignID int `json:"campaign_id"`
+ CampaignName string `json:"campaign_name"`
+ CampaignSubject string `json:"campaign_subject"`
+ ClickCount int `json:"click_count"`
+ LastClickedAt time.Time `json:"last_clicked_at"`
+}
+
+// ViewSubscribers renders the HTML view for subscribers, optionally filtered by a list.
+func (a *App) ViewSubscribers(c echo.Context) error {
+ listID, _ := strconv.Atoi(c.Param("id"))
+
+ subs, props, err := a.getSubscribers(c, listID)
+ if err != nil {
+ return err
+ }
+
+ // All lists the user can access, for the subscriber form's list selector.
+ allLists, err := a.getViewableLists(c)
+ if err != nil {
+ return err
+ }
+
+ // Fetch the list being filtered by, if any, to show its name in the header.
+ var curList *models.List
+ if listID > 0 {
+ if l, err := a.core.GetList(listID, ""); err == nil {
+ curList = &l
+ }
+ }
+
+ data := subscribersView{
+ adminView: newAdminView(c, a.i18n.T("globals.terms.subscribers"), ""),
+ Subscribers: subs,
+ Page: props,
+ AllLists: allLists,
+ CurrentList: curList,
+ }
+
+ return c.Render(http.StatusOK, "admin-subscribers", data)
+}
+
+// ViewSubscriber renders the profile and subscriptions tabs of a subscriber.
+func (a *App) ViewSubscriber(c echo.Context) error {
+ out, err := a.getViewSubscriber(c)
+ if err != nil {
+ return err
+ }
+
+ allLists, err := a.getViewableLists(c)
+ if err != nil {
+ return err
+ }
+
+ tab := "profile"
+ if strings.HasSuffix(c.Path(), "/lists") {
+ tab = "lists"
+ }
+
+ data := subscriberView{
+ adminView: newAdminView(c, out.Email, ""),
+ Tab: tab,
+ Subscriber: out,
+ AllLists: allLists,
+ }
+
+ return c.Render(http.StatusOK, "admin-subscriber", data)
+}
+
+// ViewSubscriberBounces renders the bounces tab of a subscriber.
+func (a *App) ViewSubscriberBounces(c echo.Context) error {
+ out, err := a.getViewSubscriber(c)
+ if err != nil {
+ return err
+ }
+
+ bounces, _, err := a.core.QueryBounces(0, out.ID, "", "", "", 0, 1000)
+ if err != nil {
+ return err
+ }
+
+ data := subscriberView{
+ adminView: newAdminView(c, out.Email, ""),
+ Tab: "bounces",
+ Subscriber: out,
+ Bounces: bounces,
+ }
+
+ return c.Render(http.StatusOK, "admin-subscriber", data)
+}
+
+// ViewSubscriberActivity renders the activity tab (campaign views and link clicks) of a subscriber.
+func (a *App) ViewSubscriberActivity(c echo.Context) error {
+ out, err := a.getViewSubscriber(c)
+ if err != nil {
+ return err
+ }
+
+ act, err := a.core.GetSubscriberActivity(out.ID)
+ if err != nil {
+ return err
+ }
+
+ data := subscriberView{
+ adminView: newAdminView(c, out.Email, ""),
+ Tab: "activity",
+ Subscriber: out,
+ }
+
+ // Parse the JSON activity blobs.
+ _ = json.Unmarshal(act.CampaignViews, &data.CampaignViews)
+ _ = json.Unmarshal(act.LinkClicks, &data.LinkClicks)
+ for _, v := range data.CampaignViews {
+ data.TotalViews += v.ViewCount
+ }
+ for _, cl := range data.LinkClicks {
+ data.TotalClicks += cl.ClickCount
+ }
+
+ return c.Render(http.StatusOK, "admin-subscriber", data)
+}
+
+// getViewSubscriber fetches the subscriber in the request path after validating permissions.
+func (a *App) getViewSubscriber(c echo.Context) (models.Subscriber, error) {
+ user := auth.GetUser(c)
+
+ id := getID(c)
+ if err := a.hasSubPerm(user, []int{id}); err != nil {
+ return models.Subscriber{}, err
+ }
+
+ out, err := a.core.GetSubscriber(id, "", "")
+ if err != nil {
+ return models.Subscriber{}, err
+ }
+ maskRestrictedSubLists(user, &out)
+
+ return out, nil
+}
+
+// getViewableLists returns all active lists the user has access to.
+func (a *App) getViewableLists(c echo.Context) ([]models.List, error) {
+ user := auth.GetUser(c)
+
+ hasAllPerm, permittedIDs := user.GetPermittedLists(auth.PermTypeGet)
+ return a.core.GetLists("", models.ListStatusActive, hasAllPerm, permittedIDs)
+}
+
+// getSubscribers queries subscribers from query params for the HTML view. If listID > 0,
+// results are filtered by that list (the per-list subscribers view).
+func (a *App) getSubscribers(c echo.Context, listID int) ([]models.Subscriber, models.PageProps, error) {
+ // GET and POST are both supported. `query` (SQL query) is sent by the frontend
+ // as a POST form param.
+ params, err := c.FormParams()
+ if err != nil {
+ return nil, models.PageProps{}, err
+ }
+
+ q := makeQuery(params, map[string]string{
+ "page": "",
+ "search": "",
+ "query": "",
+ "order_by": "",
+ "order": "",
+ "subscription_status": "",
+ })
+
+ // Get the authenticated user.
+ user := auth.GetUser(c)
+
+ // Filter the list IDs by permission.
+ var listIDs []int
+ if listID > 0 {
+ listIDs = user.GetPermittedListIDs([]int{listID})
+ } else {
+ ids, err := a.filterListQueryByPerm("list_id", params, user)
+ if err != nil {
+ return nil, models.PageProps{}, err
+ }
+ listIDs = ids
+ }
+
+ // Does the user have the subscribers:sql_query permission for advanced queries?
+ query := formatSQLExp(q.Get("query"))
+ if query != "" && !user.HasPerm(auth.PermSubscribersSqlQuery) {
+ return nil, models.PageProps{}, echo.NewHTTPError(http.StatusForbidden,
+ a.i18n.Ts("globals.messages.permissionDenied", "name", auth.PermSubscribersSqlQuery))
+ }
+
+ // Run the DB query.
+ pg := a.pg.NewFromURL(q)
+ res, total, err := a.core.QuerySubscribers(
+ q.Get("search"),
+ query,
+ listIDs,
+ q.Get("subscription_status"),
+ q.Get("order"),
+ q.Get("order_by"),
+ pg.Offset,
+ pg.Limit)
+ if err != nil {
+ return nil, models.PageProps{}, err
+ }
+
+ for i := range res {
+ maskRestrictedSubLists(user, &res[i])
+ }
+
+ return res, models.NewPageProps(q, total, pg.Page, pg.PerPage), nil
+}
+
// GetSubscriber handles the retrieval of a single subscriber by ID.
func (a *App) GetSubscriber(c echo.Context) error {
user := auth.GetUser(c)
diff --git a/frontend-vue/feathericons/icons.txt b/frontend-vue/feathericons/icons.txt
index f2c49379..e38200d1 100644
--- a/frontend-vue/feathericons/icons.txt
+++ b/frontend-vue/feathericons/icons.txt
@@ -39,3 +39,4 @@ tool
code
refresh-cw
more-vertical
+check-square
\ No newline at end of file
diff --git a/frontend-vue/src/router/index.js b/frontend-vue/src/router/index.js
index f5d59560..14d50fd4 100644
--- a/frontend-vue/src/router/index.js
+++ b/frontend-vue/src/router/index.js
@@ -17,12 +17,6 @@ const routes = [
meta: { title: '' },
component: () => import('../views/Dashboard.vue'),
},
- {
- path: '/subscribers',
- name: 'subscribers',
- meta: { title: 'globals.terms.subscribers', group: 'subscribers' },
- component: () => import('../views/Subscribers.vue'),
- },
{
path: '/subscribers/import',
name: 'import',
@@ -35,18 +29,6 @@ const routes = [
meta: { title: 'globals.terms.bounces', group: 'subscribers' },
component: () => import('../views/Bounces.vue'),
},
- {
- path: '/subscribers/lists/:listID',
- name: 'subscribers_list',
- meta: { title: 'globals.terms.subscribers', group: 'subscribers' },
- component: () => import('../views/Subscribers.vue'),
- },
- {
- path: '/subscribers/:id',
- name: 'subscriber',
- meta: { title: 'globals.terms.subscribers', group: 'subscribers' },
- component: () => import('../views/Subscribers.vue'),
- },
{
path: '/campaigns',
name: 'campaigns',
diff --git a/i18n/en.json b/i18n/en.json
index 7e7d3962..6db81762 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -165,6 +165,7 @@
"globals.buttons.toggleSelect": "Toggle selection",
"globals.buttons.refresh": "Refresh",
"globals.buttons.view": "View",
+ "globals.buttons.search": "Search",
"globals.days.0": "Sun",
"globals.days.1": "Sun",
"globals.days.2": "Mon",
@@ -626,6 +627,7 @@
"subscribers.query": "Query",
"subscribers.queryPlaceholder": "E-mail or name",
"subscribers.reset": "Reset",
+ "subscribers.reSubscribe": "Re-subscribe",
"subscribers.selectAll": "Select all {num}",
"subscribers.sendOptinConfirm": "Send opt-in confirmation",
"subscribers.sentOptinConfirm": "Opt-in confirmation sent",
diff --git a/models/bounces.go b/models/bounces.go
index 0d9c4b09..49ad2189 100644
--- a/models/bounces.go
+++ b/models/bounces.go
@@ -32,3 +32,24 @@ type Bounce struct {
// in searches and queries.
Total int `db:"total" json:"-"`
}
+
+// BounceCampaign is parsed from the bounce's raw campaign JSON for rendering in HTML views.
+type BounceCampaign struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+}
+
+// ParsedCampaign unmarshals the bounce's raw campaign JSON, or returns nil if the
+// bounce isn't associated with a campaign.
+func (b Bounce) ParsedCampaign() *BounceCampaign {
+ if b.Campaign == nil || len(*b.Campaign) == 0 {
+ return nil
+ }
+
+ var out BounceCampaign
+ if err := json.Unmarshal(*b.Campaign, &out); err != nil {
+ return nil
+ }
+
+ return &out
+}
diff --git a/models/subscribers.go b/models/subscribers.go
index 0ee42d92..4aaa3bbc 100644
--- a/models/subscribers.go
+++ b/models/subscribers.go
@@ -41,6 +41,34 @@ type subLists struct {
Lists types.JSONText `db:"lists"`
}
+// SubscriberListView is a minimal representation of a subscriber's list
+// subscription, parsed from the raw Lists JSON for use in HTML views.
+type SubscriberListView struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Optin string `json:"optin"`
+ SubscriptionStatus string `json:"subscription_status"`
+ SubscriptionCreatedAt null.Time `json:"subscription_created_at"`
+ SubscriptionUpdatedAt null.Time `json:"subscription_updated_at"`
+ Restricted bool `json:"restricted"`
+}
+
+// ParsedLists unmarshals the subscriber's raw Lists JSON into a slice for
+// rendering in HTML views.
+func (s Subscriber) ParsedLists() []SubscriberListView {
+ if len(s.Lists) == 0 {
+ return nil
+ }
+
+ var out []SubscriberListView
+ if err := json.Unmarshal(s.Lists, &out); err != nil {
+ return nil
+ }
+
+ return out
+}
+
// GetIDs returns the list of subscriber IDs.
func (subs Subscribers) GetIDs() []int {
IDs := make([]int, len(subs))
@@ -106,6 +134,7 @@ type Subscription struct {
List
SubscriptionStatus null.String `db:"subscription_status" json:"subscription_status"`
SubscriptionCreatedAt null.String `db:"subscription_created_at" json:"subscription_created_at"`
+ SubscriptionUpdatedAt null.String `db:"subscription_updated_at" json:"subscription_updated_at"`
Meta json.RawMessage `db:"meta" json:"meta"`
}
diff --git a/static/admin/partials/list-form.html b/static/admin/partials/list-form.html
index 5c464da7..6f5492f9 100644
--- a/static/admin/partials/list-form.html
+++ b/static/admin/partials/list-form.html
@@ -4,8 +4,8 @@
{{- $method := .Method -}}
{{- $isDialog := eq $method "dialog" -}}
{{- $canSave := .CanSave -}}
-<form method="{{ $method }}" :aria-busy="isLoading('lists')" @submit.prevent="{{ $submit }}">
- <div class="{{ if $isDialog }}dialog-card content{{ else }}card page-content content p-6{{ end }}">
+<form method="{{ $method }}" @submit.prevent="{{ $submit }}">
+ <div class="{{ if $isDialog }}dialog-card content{{ else }}card page-content content{{ end }}">
{{- if $isDialog }}
<header class="dialog-head">
<h3 class="dialog-title">{{ $root.L.T "globals.terms.new" }} {{ $root.L.T "globals.terms.list" }}</h3>
diff --git a/static/admin/partials/list-selector.html b/static/admin/partials/list-selector.html
new file mode 100644
index 00000000..4a76f32b
--- /dev/null
+++ b/static/admin/partials/list-selector.html
@@ -0,0 +1,13 @@
+{{ define "list-selector" -}}
+{{- $root := .Root -}}
+{{- $model := .Model -}}
+{{- $listID := .ListID -}}
+<label data-field>
+ {{ $root.L.T .Label }}
+ <ot-taginput x-model="{{ $model }}">
+ <input list="{{ $listID }}" placeholder="{{ $root.L.T .Placeholder }}" oninput="_listAutocomplete(this)" onpointerdown="_listAutocomplete(this)" onfocus="_listAutocomplete(this)" />
+ <datalist id="{{ $listID }}"></datalist>
+ </ot-taginput>
+ <small data-hint>{{ $root.L.T "subscribers.listsHelp" }}</small>
+</label>
+{{- end }}
diff --git a/static/admin/partials/manage-lists-form.html b/static/admin/partials/manage-lists-form.html
new file mode 100644
index 00000000..4113eeb3
--- /dev/null
+++ b/static/admin/partials/manage-lists-form.html
@@ -0,0 +1,17 @@
+{{ define "manage-lists-form" -}}
+{{- $root := .Root -}}
+{{- $model := .Model -}}
+{{- $id := .ListID -}}
+
+<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>
+</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" }}
+ <small data-hint>{{ $root.L.T "subscribers.preconfirmHelp" }}</small>
+</label>
+{{- end }}
diff --git a/static/admin/partials/subscriber-activity.html b/static/admin/partials/subscriber-activity.html
new file mode 100644
index 00000000..699eddc1
--- /dev/null
+++ b/static/admin/partials/subscriber-activity.html
@@ -0,0 +1,43 @@
+{{ define "subscriber-activity" -}}
+{{- $d := .Data -}}
+<div class="card page-content content activity">
+ <div class="row">
+ <div class="col-4"><div class="card stat-card"><small class="text-light">{{ .L.T "globals.terms.campaigns" }}</small><div class="stat-value">{{ len $d.CampaignViews }}</div></div></div>
+ <div class="col-4"><div class="card stat-card"><small class="text-light">{{ .L.T "campaigns.views" }}</small><div class="stat-value">{{ $d.TotalViews }}</div></div></div>
+ <div class="col-4"><div class="card stat-card"><small class="text-light">{{ .L.T "campaigns.clicks" }}</small><div class="stat-value">{{ $d.TotalClicks }}</div></div></div>
+ </div>
+
+ {{- if $d.CampaignViews }}
+ <h5 class="mt-6">{{ .L.T "campaigns.views" }}</h5>
+ <table>
+ <thead><tr><th>{{ .L.T "globals.terms.campaign" }}</th><th width="10%">{{ .L.T "campaigns.views" }}</th><th width="20%">{{ .L.T "globals.fields.createdAt" }}</th></tr></thead>
+ <tbody>
+ {{- range $d.CampaignViews }}
+ <tr>
+ <td><a href="{{ URI "/admin/campaigns" }}/{{ .ID }}">{{ .Name }}</a><p class="text-light text-7">{{ .Subject }}</p></td>
+ <td>{{ .ViewCount }}</td>
+ <td>{{ NiceDate .LastViewedAt }}</td>
+ </tr>
+ {{- end }}
+ </tbody>
+ </table>
+ {{- end }}
+
+ {{- if $d.LinkClicks }}
+ <h5 class="mt-6">{{ .L.T "campaigns.clicks" }}</h5>
+ <table>
+ <thead><tr><th>{{ .L.T "globals.terms.campaign" }}</th><th>{{ .L.T "globals.terms.url" }}</th><th width="10%">{{ .L.T "campaigns.clicks" }}</th><th width="20%">{{ .L.T "globals.fields.createdAt" }}</th></tr></thead>
+ <tbody>
+ {{- range $d.LinkClicks }}
+ <tr>
+ <td>{{- if .CampaignID }}<a href="{{ URI "/admin/campaigns" }}/{{ .CampaignID }}">{{ or .CampaignSubject .CampaignName }}</a>{{- end }}</td>
+ <td class="link-click-url"><a href="{{ .URL }}" target="_blank" rel="noopener noreferrer">{{ .URL }}</a></td>
+ <td>{{ .ClickCount }}</td>
+ <td>{{ NiceDate .LastClickedAt }}</td>
+ </tr>
+ {{- end }}
+ </tbody>
+ </table>
+ {{- end }}
+</div>
+{{- end }}
diff --git a/static/admin/partials/subscriber-bounces.html b/static/admin/partials/subscriber-bounces.html
new file mode 100644
index 00000000..006c963b
--- /dev/null
+++ b/static/admin/partials/subscriber-bounces.html
@@ -0,0 +1,32 @@
+{{ define "subscriber-bounces" -}}
+{{- $d := .Data -}}
+<div class="card page-content content bounces">
+ {{- if $d.Bounces }}
+ <table>
+ <thead><tr>
+ <th>{{ .L.T "globals.terms.campaign" }}</th>
+ <th>{{ .L.T "globals.fields.createdAt" }}</th>
+ <th>{{ .L.T "globals.fields.type" }}</th>
+ </tr></thead>
+ <tbody>
+ {{- range $d.Bounces }}
+ <tr>
+ <td>
+ {{- with .ParsedCampaign }}
+ <a href="{{ URI "/admin/campaigns" }}/{{ .ID }}">{{ .Name }}</a>
+ {{- end }}
+ </td>
+ <td>{{ NiceDate .CreatedAt }}</td>
+ <td>
+ <a href="#" @click.prevent="toggleMeta({{ .ID }})">{{ .Source }} {{ Icon "chevron-down" }}</a>
+ <pre x-show="visibleMeta[{{ .ID }}]" x-cloak>{{ printf "%s" .Meta }}</pre>
+ </td>
+ </tr>
+ {{- end }}
+ </tbody>
+ </table>
+ {{- else }}
+ <p class="align-center text-light">{{ .L.T "globals.messages.emptyState" }}</p>
+ {{- end }}
+</div>
+{{- end }}
diff --git a/static/admin/partials/subscriber-form.html b/static/admin/partials/subscriber-form.html
new file mode 100644
index 00000000..dfda92ba
--- /dev/null
+++ b/static/admin/partials/subscriber-form.html
@@ -0,0 +1,82 @@
+{{ define "subscriber-form" -}}
+{{- $root := .Root -}}
+{{- $submit := .Submit -}}
+{{- $method := .Method -}}
+{{- $isDialog := eq $method "dialog" -}}
+{{- $canSave := .CanSave -}}
+<form method="{{ $method }}" @submit.prevent="{{ $submit }}">
+ <div class="{{ if $isDialog }}dialog-card content{{ else }}card page-content content{{ end }}">
+ {{- if $isDialog }}
+ <header class="dialog-head">
+ <h3 class="dialog-title">{{ $root.L.T "subscribers.newSubscriber" }}</h3>
+ </header>
+
+ <section class="dialog-body">
+ {{ 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" }}
+ <small data-hint>{{ $root.L.T "subscribers.preconfirmHelp" }}</small>
+ </label>
+ {{ template "subscriber-attribs" $root }}
+ </section>
+ <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>
+ {{- end }}
+ </footer>
+ {{- else }}
+ {{ template "subscriber-fields" $root }}
+ {{ template "subscriber-attribs" $root }}
+ <footer class="dialog-foot hstack justify-between mt-6">
+ <div class="hstack gap-1">
+ <button type="button" class="small" data-variant="secondary" title="{{ $root.L.T "globals.messages.clickToCopy" }}" aria-label="{{ $root.L.T "globals.fields.id" }}" @click="copyToClipboard(form.id)">
+ <strong>{{ $root.L.T "globals.fields.id" }}</strong> <span x-text="form.id"></span>
+ </button>
+ <button type="button" class="small" data-variant="secondary" title="{{ $root.L.T "globals.messages.clickToCopy" }}" aria-label="{{ $root.L.T "globals.fields.uuid" }}" @click="copyToClipboard(form.uuid)">
+ <strong>{{ $root.L.T "globals.fields.uuid" }}</strong> <span x-text="form.uuid"></span>
+ </button>
+ </div>
+ <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>
+ {{- end }}
+ </div>
+ </footer>
+ {{- end }}
+ </div>
+</form>
+{{- end }}
+
+{{ define "subscriber-fields" -}}
+{{- $root := . -}}
+<label data-field>
+ {{ $root.L.T "subscribers.email" }}
+ <input name="email" type="email" maxlength="200" autofocus required x-model="form.email" />
+</label>
+
+<label data-field>
+ {{ $root.L.T "globals.fields.name" }}
+ <input name="name" maxlength="200" x-model="form.name" />
+</label>
+
+<div data-field>
+ <label for="sub-status">{{ $root.L.T "globals.fields.status" }}</label>
+ <select name="status" id="sub-status" required x-model="form.status">
+ <option value="enabled">{{ $root.L.T "subscribers.status.enabled" }}</option>
+ <option value="blocklisted">{{ $root.L.T "subscribers.status.blocklisted" }}</option>
+ </select>
+ <small data-hint>{{ $root.L.T "subscribers.blocklistedHelp" }}</small>
+</div>
+{{- end }}
+
+{{ define "subscriber-attribs" -}}
+{{- $root := . -}}
+<label data-field class="mt-6">
+ {{ $root.L.T "globals.terms.attribs" }}
+ <textarea name="attribs" rows="4" x-model="form.strAttribs" class="monospace"></textarea>
+ <small data-hint>{{ $root.L.T "subscribers.attribsHelp" }} <code>{"job": "developer", "location": "Mars", "has_rocket": true}</code></small>
+</label>
+{{- end }}
diff --git a/static/admin/partials/subscriber-lists.html b/static/admin/partials/subscriber-lists.html
new file mode 100644
index 00000000..dc0782c6
--- /dev/null
+++ b/static/admin/partials/subscriber-lists.html
@@ -0,0 +1,84 @@
+{{ define "subscriber-lists" -}}
+{{- $root := .Root -}}
+{{- $canSave := .CanSave -}}
+<div class="card page-content has-table subscriptions">
+ <div class="table-wrapper">
+ <table>
+ <thead><tr>
+ <th>{{ $root.L.T "globals.terms.list" }}</th>
+ <th>{{ $root.L.T "lists.optin" }}</th>
+ <th>{{ $root.L.T "globals.fields.status" }}</th>
+ <th>{{ $root.L.T "globals.fields.createdAt" }}</th>
+ <th>{{ $root.L.T "globals.fields.updatedAt" }}</th>
+ {{- if $canSave }}<th></th>{{ end }}
+ </tr></thead>
+ <tbody>
+ {{- range $root.Data.Subscriber.ParsedLists }}
+ <tr>
+ <td>
+ {{- if .Restricted }}
+ <span class="text-light">{{ .Name }}</span>
+ {{- else }}
+ <a href="{{ URI "/admin/lists" }}/{{ .ID }}">{{ .Name }}</a>
+ {{- end }}
+ </td>
+ <td>
+ <span class="badge enum" data-variant="secondary" data-cy="optin-{{ .Optin }}">
+ {{ if eq .Optin "double" }}{{ Icon "user-check" }}{{ else }}{{ Icon "user-x" }}{{ end }}
+ {{ $root.L.T (printf "lists.optins.%s" .Optin) }}
+ </span>
+
+ </span></td>
+ <td>
+ {{- if and (eq .Optin "single") (eq .SubscriptionStatus "unconfirmed") -}}
+ <span class="text-light">&ndash;</span>
+ {{- else -}}
+ <span class="badge enum status-{{ .SubscriptionStatus }}" data-variant="secondary">{{ $root.L.T (printf "subscribers.status.%s" .SubscriptionStatus) }}</span>
+ {{- end -}}
+ </td>
+ <td>{{ NiceDate .SubscriptionCreatedAt }}</td>
+ <td>{{ NiceDate .SubscriptionUpdatedAt }}</td>
+ {{- if $canSave }}
+ <td class="actions align-right">
+ <ot-dropdown>
+ <button popovertarget="sub-list-{{ .ID }}" type="button" class="ghost small 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>
+ {{- 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>
+ {{- else }}
+ <button type="button" role="menuitem" class="ghost" @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>
+ </menu>
+ </ot-dropdown>
+ </td>
+ {{- end }}
+ </tr>
+ {{- else }}
+ <tr><td colspan="6" class="align-center text-light">{{ $root.L.T "globals.messages.emptyState" }}</td></tr>
+ {{- end }}
+ </tbody>
+ </table>
+ </div>
+
+ {{- if $canSave }}
+ <dialog class="b-modal" x-ref="manageDialog">
+ <form @submit.prevent="onManageLists">
+ <div class="dialog-card content">
+ <header class="dialog-head"><h3 class="dialog-title">{{ $root.L.T "subscribers.manageLists" }}</h3></header>
+ <section class="dialog-body">
+ {{ template "manage-lists-form" dict "Root" $root "Model" "manage" "ListID" "manage-lists" }}
+ </section>
+ <footer class="dialog-foot hstack gap-3 justify-end">
+ <button type="button" class="outline" @click="$refs.manageDialog.close()">{{ $root.L.T "globals.buttons.close" }}</button>
+ <button type="submit" data-variant="primary" :disabled="manage.lists.length === 0 || isLoading('subscribers')" :aria-busy="isLoading('subscribers')">{{ $root.L.T "globals.buttons.save" }}</button>
+ </footer>
+ </div>
+ </form>
+ </dialog>
+ {{- end }}
+</div>
+{{- end }}
diff --git a/static/admin/src/css/style.css b/static/admin/src/css/style.css
index 344eb233..5aa92cac 100644
--- a/static/admin/src/css/style.css
+++ b/static/admin/src/css/style.css
@@ -77,8 +77,24 @@ table {
vertical-align: top;
border-bottom: 1px solid var(--border);
}
+
+ .view {
+ color: var(--faint-foreground);
+ font-size: var(--text-8);
+
+ &:hover {
+ color: var(--primary);
+ }
+ }
+
+ .badge-list {
+ margin-top: var(--space-1);
+ }
}
+.text-light {
+ color: var(--muted-foreground);
+}
.text-1 { font-size: var(--text-1); }
.text-2 { font-size: var(--text-2); }
.text-3 { font-size: var(--text-3); }
@@ -104,7 +120,6 @@ table {
.ml-6 { margin-inline-start: var(--space-6); }
.ml-3 { margin-inline-start: var(--space-3); }
.mr-4 { margin-inline-end: var(--space-4); }
-.p-6 { padding: var(--space-6); }
.py-6 { padding-block: var(--space-6); }
.pb-0 { padding-block-end: 0; }
.float-right { float: right; }
@@ -125,6 +140,13 @@ table {
}
}
+.stat-card {
+ .stat-value {
+ font-size: var(--text-1);
+ font-weight: var(--font-semibold);
+ }
+}
+
dialog {
border-radius: var(--radius-medium);
@@ -134,14 +156,27 @@ dialog {
}
.badge {
+ padding: calc(var(--space-1) * 0.75) var(--space-4);
+
+ sup {
+ margin-top: -5px;
+ font-size: calc(var(--text-8) / 1.3);
+ }
+
+ &.outline {
+ color: var(--muted-foreground);
+ }
+
+ &.enum {
+ min-width: 7rem;
+ }
+
&.private,
&.scheduled,
&.paused,
&.tx,
&.api,
&.double,
- &.status-unconfirmed,
- &.status_unconfirmed,
&.unconfirmed {
background: #fff1e0;
color: #ed7b00;
@@ -157,24 +192,31 @@ dialog {
color: #3b8cff;
}
- &.finished,
- &.enabled,
- &.status-confirmed,
- &.status_confirmed,
- &.confirmed {
+
+ /* Subscription statuses */
+ sup.status-confirmed {
+ color: #36995b;
+ }
+ &.status-confirmed {
background: #dcfce7;
color: #36995b;
}
- &.blocklisted,
- &.cancelled,
- &.status-unsubscribed,
- &.status_unsubscribed,
- &.unsubscribed,
- &.campaign_visual {
+ sup.status-unsubscribed {
+ color: #ff5722;
+ }
+ &.status-unsubscribed {
background: #fff1f0;
color: #ff5722;
}
+ &.status-blocklisted {
+ background: #fff1f0;
+ color: var(--danger);
+ }
+
+ sup.status-unconfirmed {
+ color: var(--muted-foreground);
+ }
&.disabled,
&.draft,
@@ -195,9 +237,7 @@ dialog {
letter-spacing: 0.03em;
}
- &.unsubscribed sup,
- &.status-unsubscribed sup,
- &.status_unsubscribed sup {
+ &.status-unsubscribed sup {
color: #fa8c16;
}
@@ -217,6 +257,10 @@ body[data-sidebar-layout] {
display: block;
}
+textarea.monospace {
+ font-family: var(--font-mono);
+}
+
#app {
min-height: 100dvh;
}
@@ -386,10 +430,59 @@ aside[data-sidebar] {
}
.search-form {
- fieldset.group button {
+ button.outline {
border-color: var(--input);
}
}
+.sql-btn {
+ position: relative;
+ border-right: 0;
+
+ &.is-active::before {
+ content: "";
+ position: absolute;
+ inset-block: -5px auto;
+ inset-inline: auto 7px;
+ width: 10px;
+ height: 10px;
+ border: 0;
+ border-radius: 50%;
+ background: var(--danger);
+ opacity: 1;
+ visibility: visible;
+ transform: none;
+ transition: none;
+ }
+}
+
+/* The advanced SQL query editor, shown in an ot-dropdown popover off the search box. */
+.sql-editor.sql-editor {
+ width: min(90vw, 40rem);
+ padding: var(--space-3);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+
+ textarea {
+ width: 100%;
+ box-sizing: border-box;
+ font-family: var(--font-mono);
+ resize: vertical;
+ }
+}
+
+@supports (anchor-name: --a) {
+ .sql-btn {
+ anchor-name: --sql-anchor;
+ }
+
+ .sql-editor.sql-editor {
+ position-anchor: --sql-anchor;
+ inset: auto !important;
+ top: calc(anchor(bottom) + var(--space-1)) !important;
+ right: anchor(right) !important;
+ }
+}
@media (min-width: 769px) {
aside[data-sidebar] {
@@ -601,6 +694,7 @@ svg.icon {
}
.bulk-actions {
+ box-shadow: -10px 0 10px var(--background);
position: absolute;
right: var(--space-6);
top: var(--space-2);
@@ -757,15 +851,6 @@ section.lists {
}
}
- .view {
- color: var(--faint-foreground);
- font-size: var(--text-8);
-
- &:hover {
- color: var(--primary);
- }
- }
-
.date-stack small {
display: block;
margin-block-start: var(--space-1);
@@ -790,7 +875,9 @@ section.users {
}
.blocklisted {
- color: var(--danger);
+ td > a:not(.badge) {
+ color: var(--danger);
+ }
}
td.link-click-url {
diff --git a/static/admin/src/js/views/subscribers.js b/static/admin/src/js/views/subscribers.js
new file mode 100644
index 00000000..fd869fcd
--- /dev/null
+++ b/static/admin/src/js/views/subscribers.js
@@ -0,0 +1,382 @@
+import {
+ api,
+ urls,
+ i18n,
+} from '../main.js';
+import * as u from '../utils.js';
+
+// ListTag is the object used in <ot-taginput> list selector.
+class ListTag {
+ constructor(list) {
+ Object.assign(this, list);
+ }
+
+ toString() {
+ return this.name;
+ }
+}
+
+// _listAutocomplete populates the <ot-taginput> listselector's suggestions with lists.
+window._listAutocomplete = (el) => {
+ const ti = el.closest('ot-taginput');
+ const chosen = new Set((ti ? ti.value : []).map((l) => l.id));
+ const q = el.value.toLowerCase();
+
+ el.list.replaceChildren(...(window._lists || [])
+ .filter((l) => !chosen.has(l.id) && l.name.toLowerCase().includes(q))
+ // Cap suggestions (so focusing with an empty input still shows a usable list of items).
+ .slice(0, 10)
+ .map((l) => {
+ const o = new Option(l.name);
+ o.data = new ListTag(l);
+ return o;
+ }));
+};
+
+function component(sub = null) {
+ // The current view's filters are injected by the template.
+ const filters = window._filters || {};
+
+ // Init a fresh form payload.
+ const makeForm = () => ({
+ id: null,
+ uuid: '',
+ email: '',
+ name: '',
+ status: 'enabled',
+ lists: [],
+ preconfirm: false,
+ strAttribs: '{}',
+ });
+ const makeFormFromSub = (s) => ({
+ ...makeForm(),
+ ...s,
+ lists: (Array.isArray(s.lists) ? s.lists : []).map((l) => new ListTag(l)),
+ strAttribs: JSON.stringify(s.attribs || {}, null, 4),
+ });
+
+ return {
+ filters,
+ query: filters.query || '',
+ isSqlOpen: false,
+ get advanced() {
+ return this.query.trim() !== '';
+ },
+
+ form: sub ? makeFormFromSub(sub) : makeForm(),
+
+ subscriptions: sub && Array.isArray(sub.lists) ? sub.lists : [],
+
+ // Manage-lists box state (subscriber edit page).
+ manage: {
+ action: 'add', lists: [], preconfirm: false,
+ },
+
+ // Bulk manage-lists dialog state.
+ bulk: {
+ action: 'add', lists: [], preconfirm: false, allSelected: false, selected: [],
+ },
+
+ // Bounces tab: controls the per-row meta JSON toggle (the rows are SSR-rendered).
+ visibleMeta: {},
+
+ // ===============
+ // New / edit form.
+ onOpenNew() {
+ this.form = makeForm();
+ this.$refs.dialog.showModal();
+ },
+
+ onClose() {
+ this.$refs.dialog.close();
+ },
+
+ onDialogClose() {
+ this.form = makeForm();
+ },
+
+ async onSubmitNew() {
+ const payload = this._payload();
+ if (!payload) {
+ return;
+ }
+ const data = await api('subscribers.save', '/subscribers', 'POST', payload);
+ u.reload({ message: i18n.ts('globals.messages.created', { name: data.email }) });
+ },
+
+ async onSubmitUpdate() {
+ // PATCH the profile. Subscriptions (lists) are managed separately via the manage-lists dialog.
+ const attribs = this._validateAttribs(this.form.strAttribs);
+ if (attribs === null) {
+ return;
+ }
+ const data = await api('subscribers.save', `/subscribers/${this.form.id}`, 'PATCH', {
+ email: this.form.email,
+ name: this.form.name,
+ status: this.form.status,
+ attribs,
+ });
+
+ u.reload({ message: i18n.ts('globals.messages.updated', { name: data.email }) });
+ },
+
+ onOpenManage() {
+ this.manage = { action: 'add', lists: [], preconfirm: false };
+ this.$refs.manageDialog.showModal();
+ },
+
+ // Apply the manage-lists action (add / remove / unsubscribe) to the subscriber for
+ // the picked lists.
+ async onManageLists() {
+ const lists = this.manage.lists.map((l) => l.id);
+ if (lists.length === 0) {
+ return;
+ }
+
+ const data = {
+ ids: [this.form.id],
+ action: this.manage.action,
+ target_list_ids: lists,
+ };
+ if (this.manage.preconfirm) {
+ data.status = 'confirmed';
+ }
+
+ await api('subscribers', '/subscribers/lists', 'PUT', data);
+ u.reload({ message: i18n.t('subscribers.listChangeApplied') });
+ },
+
+ async onDeleteSubscriber(id, email) {
+ if (!(await u.confirm(i18n.ts('subscribers.confirmDelete', { num: 1 })))) {
+ return;
+ }
+
+ await api('subscribers', `/subscribers/${id}`, 'DELETE');
+ u.reload({ message: i18n.ts('globals.messages.deleted', { name: email }) });
+ },
+
+ async onSendOptin() {
+ if (!this.hasOptinSub) {
+ return;
+ }
+ if (!(await u.confirm())) {
+ return;
+ }
+
+ await api('subscribers', `/subscribers/${this.form.id}/optin`, 'POST');
+ u.toast(i18n.t('subscribers.sentOptinConfirm'), 'success');
+ },
+
+ // ===============
+ // Per-subscription actions in the Subscriptions tab.
+ async _manageSub(action, listID, status) {
+ if (!(await u.confirm())) {
+ return;
+ }
+
+ await api('subscribers', '/subscribers/lists', 'PUT', {
+ ids: [this.form.id],
+ action,
+ target_list_ids: [listID],
+ status: status || '',
+ });
+
+ u.reload({ message: i18n.t('subscribers.listChangeApplied') });
+ },
+
+ onConfirmSub(id) {
+ return this._manageSub('add', id, 'confirmed');
+ },
+
+ onResubscribe(id) {
+ return this._manageSub('add', id, 'unconfirmed');
+ },
+
+ onUnsubscribe(id) {
+ return this._manageSub('unsubscribe', id);
+ },
+
+ onDeleteSub(id) {
+ return this._manageSub('remove', id);
+ },
+
+ // ===============
+ // List selector helpers.
+ get hasOptinList() {
+ return this.form.lists.some((l) => l.optin === 'double');
+ },
+
+ get manageHasOptinList() {
+ return this.manage.lists.some((l) => l.optin === 'double');
+ },
+
+ get hasOptinSub() {
+ return this.subscriptions.some((l) => l.optin === 'double');
+ },
+
+ get bulkHasOptinList() {
+ return this.bulk.lists.some((l) => l.optin === 'double');
+ },
+
+ // ===============
+ // Bulk actions.
+ onExport(allSelected, selected, total) {
+ const num = (!allSelected && selected.length > 0) ? selected.length : total;
+ u.confirm(i18n.ts('subscribers.confirmExport', { num })).then((ok) => {
+ if (!ok) {
+ return;
+ }
+
+ const q = new URLSearchParams();
+ if (this.filters.search) {
+ q.append('search', this.filters.search);
+ } else if (this.filters.query) {
+ q.append('query', this.filters.query);
+ }
+ if (this.filters.listID) {
+ q.append('list_id', this.filters.listID);
+ }
+ if (this.filters.subStatus) {
+ q.append('subscription_status', this.filters.subStatus);
+ }
+ if (!allSelected && selected.length > 0) {
+ selected.forEach((id) => q.append('id', id));
+ }
+
+ window.location.href = `${urls.api}/subscribers/export?${q.toString()}`;
+ });
+ },
+
+ async onDeleteSelected(allSelected, selected, total) {
+ const num = allSelected ? total : selected.length;
+ if (!(await u.confirm(i18n.ts('subscribers.confirmDelete', { num })))) {
+ return;
+ }
+
+ if (!allSelected) {
+ const q = new URLSearchParams();
+ selected.forEach((id) => q.append('id', id));
+ await api('subscribers', `/subscribers?${q.toString()}`, 'DELETE');
+ } else {
+ await api('subscribers', '/subscribers/query/delete', 'POST', this._queryBody());
+ }
+
+ u.reload({ message: i18n.ts('subscribers.subscribersDeleted', { num }) });
+ },
+
+ async onBlocklistSelected(allSelected, selected, total) {
+ const num = allSelected ? total : selected.length;
+ if (!(await u.confirm(i18n.ts('subscribers.confirmBlocklist', { num })))) {
+ return;
+ }
+
+ if (!allSelected) {
+ await api('subscribers', '/subscribers/blocklist', 'PUT', { ids: selected.map(Number) });
+ } else {
+ await api('subscribers', '/subscribers/query/blocklist', 'PUT', this._queryBody());
+ }
+
+ u.reload();
+ },
+
+ onOpenManageLists(allSelected, selected) {
+ this.bulk = {
+ action: 'add',
+ lists: [],
+ preconfirm: false,
+ allSelected,
+ selected: selected.map(Number),
+ };
+ this.$refs.listDialog.showModal();
+ },
+
+ async onSubmitManageLists() {
+ const lists = this.bulk.lists.map((l) => l.id);
+ if (lists.length === 0) {
+ return;
+ }
+
+ const data = { action: this.bulk.action, target_list_ids: lists };
+ if (this.bulk.preconfirm) {
+ data.status = 'confirmed';
+ }
+
+ if (!this.bulk.allSelected) {
+ data.ids = this.bulk.selected;
+ await api('subscribers', '/subscribers/lists', 'PUT', data);
+ } else {
+ Object.assign(data, this._queryBody());
+ await api('subscribers', '/subscribers/query/lists', 'PUT', data);
+ }
+
+ this.$refs.listDialog.close();
+ u.reload({ message: i18n.t('subscribers.listChangeApplied') });
+ },
+
+ // ===============
+ // Bounces tab.
+ toggleMeta(id) {
+ this.visibleMeta[id] = !this.visibleMeta[id];
+ },
+
+ async onDeleteBounces() {
+ if (!(await u.confirm())) {
+ return;
+ }
+ await api('subscribers', `/subscribers/${this.form.id}/bounces`, 'DELETE');
+ u.reload({ message: i18n.t('globals.messages.done') });
+ },
+
+ // ===============
+ // Private functions.
+ // Body for the "by query" bulk endpoints.
+ _queryBody() {
+ const search = this.filters.search || '';
+ const query = this.filters.query || '';
+ return {
+ all: query.trim() === '' && search.trim() === '',
+ search,
+ query,
+ list_ids: this.filters.listID ? [this.filters.listID] : null,
+ subscription_status: this.filters.subStatus || null,
+ };
+ },
+
+ _payload() {
+ const attribs = this._validateAttribs(this.form.strAttribs);
+ if (attribs === null) {
+ return null;
+ }
+
+ return {
+ email: this.form.email,
+ name: this.form.name,
+ status: this.form.status,
+ attribs,
+ preconfirm_subscriptions: this.form.preconfirm,
+ lists: this.form.lists.map((l) => l.id),
+ };
+ },
+
+ _validateAttribs(str) {
+ if (!str || !str.trim()) {
+ return {};
+ }
+ try {
+ const a = JSON.parse(str);
+ if (Array.isArray(a)) {
+ u.toast(i18n.t('subscribers.invalidJSON'), 'danger');
+ return null;
+ }
+ return a;
+ } catch (e) {
+ u.toast(`${i18n.t('subscribers.invalidJSON')}: ${e.toString()}`, 'danger');
+ return null;
+ }
+ },
+ };
+}
+
+document.addEventListener('alpine:init', () => {
+ window.Alpine.data('subscribersView', component);
+}, { once: true });
diff --git a/static/admin/views/lists.html b/static/admin/views/lists.html
index f389bed1..5ab265b6 100644
--- a/static/admin/views/lists.html
+++ b/static/admin/views/lists.html
@@ -80,8 +80,8 @@
</td>
<td>
<div class="hstack">
- <span class="badge {{ .Type }}" data-cy="type-{{ .Type }}">{{ $.L.T (printf "lists.types.%s" .Type) }}</span>
- <span class="badge {{ .Optin }}" data-cy="optin-{{ .Optin }}">
+ <span class="badge enum {{ .Type }}" data-cy="type-{{ .Type }}">{{ $.L.T (printf "lists.types.%s" .Type) }}</span>
+ <span class="badge enum" data-variant="secondary" data-cy="optin-{{ .Optin }}">
{{ if eq .Optin "double" }}{{ Icon "user-check" }}{{ else }}{{ Icon "user-x" }}{{ end }}
{{ $.L.T (printf "lists.optins.%s" .Optin) }}
</span>
diff --git a/static/admin/views/subscriber.html b/static/admin/views/subscriber.html
new file mode 100644
index 00000000..1244fd6c
--- /dev/null
+++ b/static/admin/views/subscriber.html
@@ -0,0 +1,58 @@
+{{ define "admin-subscriber" -}}
+{{ template "admin-header" . }}
+{{- $d := .Data -}}
+{{- $sub := $d.Subscriber -}}
+{{- $base := printf "%s/%d" (URI "/admin/subscribers") $sub.ID -}}
+
+<script>
+ window._lists = {{ ToJSON $d.AllLists }};
+ const _sub = {{ ToJSON $sub }};
+</script>
+<section class="subscribers" x-data="subscribersView(_sub)">
+ <header class="row page-header">
+ <div class="col-6">
+ <div class="hstack gap-1">
+ <a href="{{ URI "/admin/subscribers" }}" class="back" aria-label="{{ .L.T "globals.buttons.back" }}">{{ Icon "chevron-left" }}</a>
+ <h1 class="page-title">
+ {{ $sub.Email }}
+ {{ if ne $sub.Status "enabled" }}<span class="badge status-{{ $sub.Status }}">{{ .L.T (printf "subscribers.status.%s" $sub.Status) }}</span>{{ end }}
+ </h1>
+ </div>
+ </div>
+ <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>
+ {{ end }}
+ <button type="button" data-variant="primary" @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>
+ {{- end }}
+ </div>
+ </header>
+
+ <div role="tablist">
+ <a role="tab" href="{{ $base }}" {{ if eq $d.Tab "profile" }}aria-selected="true"{{ end }}>{{ .L.Tc "globals.terms.subscriber" 1 }}</a>
+ <a role="tab" href="{{ $base }}/lists" {{ if eq $d.Tab "lists" }}aria-selected="true"{{ end }}>{{ .L.Tc "globals.terms.lists" 2 }} ({{ len $sub.ParsedLists }})</a>
+ <a role="tab" href="{{ $base }}/activity" {{ if eq $d.Tab "activity" }}aria-selected="true"{{ end }}>{{ .L.T "subscribers.activity" }}</a>
+ {{- if $d.Can "bounces:get" }}
+ <a role="tab" href="{{ $base }}/bounces" {{ if eq $d.Tab "bounces" }}aria-selected="true"{{ end }}>{{ .L.T "globals.terms.bounces" }}</a>
+ {{- end }}
+ </div>
+
+ {{- if eq $d.Tab "profile" }}
+ {{ template "subscriber-form" dict "Root" . "Submit" "onSubmitUpdate" "Method" "post" "CanSave" ($d.Can "subscribers:manage") }}
+ {{- else if eq $d.Tab "lists" }}
+ {{ template "subscriber-lists" dict "Root" . "CanSave" ($d.Can "subscribers:manage") }}
+ {{- else if eq $d.Tab "bounces" }}
+ {{ template "subscriber-bounces" . }}
+ {{- else if eq $d.Tab "activity" }}
+ {{ template "subscriber-activity" . }}
+ {{- end }}
+</section>
+
+<script type="module" src="{{ URI "/admin/static/js/views/subscribers.js" }}?v={{ .AssetVersion }}" defer></script>
+
+{{ template "admin-footer" . -}}
+{{ end }}
diff --git a/static/admin/views/subscribers.html b/static/admin/views/subscribers.html
new file mode 100644
index 00000000..eef99fd2
--- /dev/null
+++ b/static/admin/views/subscribers.html
@@ -0,0 +1,168 @@
+{{ define "admin-subscribers" -}}
+{{ template "admin-header" . }}
+{{- $d := .Data -}}
+{{- $subStatus := $d.Page.Param "subscription_status" -}}
+{{- $base := URI "/admin/subscribers" -}}
+{{- if $d.CurrentList }}{{ $base = printf "%s/lists/%d" (URI "/admin/subscribers") $d.CurrentList.ID }}{{ end -}}
+
+<script>
+ window._lists = {{ ToJSON $d.AllLists }};
+ window._filters = {
+ listID: {{ if $d.CurrentList }}{{ $d.CurrentList.ID }}{{ else }}null{{ end }},
+ search: {{ ToJSON $d.Page.Search }},
+ query: {{ ToJSON $d.Page.Query }},
+ subStatus: {{ ToJSON $subStatus }}
+ };
+</script>
+
+<section class="subscribers" x-data="subscribersView()">
+ <header class="row page-header">
+ <div class="col-6">
+ <h1 class="page-title">
+ {{ .L.T "globals.terms.subscribers" }}
+ <span>({{ $d.Page.Total }})</span>
+ {{- if $d.CurrentList }}
+ &raquo; <a href="{{ URI "/admin/lists" }}/{{ $d.CurrentList.ID }}">{{ $d.CurrentList.Name }}</a>
+ {{- if $subStatus }}<span class="text-light text-7">({{ $subStatus }})</span>{{ end }}
+ {{- end }}
+ </h1>
+ </div>
+ <div class="col-6 col-end hstack justify-end">
+ <form action="{{ $base }}" class="search-form" :method="advanced ? 'post' : 'get'">
+ {{- $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" :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" class="" data-cy="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 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>
+ <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>
+ </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">
+ {{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}
+ </button>
+ {{- end }}
+ </div>
+ </header>
+
+ <div class="card page-content has-table">
+ <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">
+ <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()">
+ {{ 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>
+ {{- 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>
+ <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>
+ {{- end }}
+ </menu>
+ </ot-dropdown>
+ </template>
+
+ <table>
+ <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 class="align-right"></th>
+ </tr>
+ </thead>
+ <tbody>
+ {{- range $d.Subscribers }}
+ {{- $sub := . }}
+ <tr {{ if eq .Status "blocklisted" }}class="blocklisted"{{ end }}>
+ <td><input name="id" type="checkbox" value="{{ .ID }}"></td>
+ <td >
+ <a href="{{ URI "/admin/subscribers" }}/{{ .ID }}">{{ .Email }}</a>
+ {{- if ne .Status "enabled" }}<span class="badge status-{{ .Status }}">{{ $.L.T (printf "subscribers.status.%s" .Status) }}</span>{{ end }}
+ <div class="badge-list hstack gap-1">
+ {{- range .ParsedLists }}
+ <a href="{{ URI "/admin/subscribers/lists" }}/{{ .ID }}" class="badge outline">
+ {{ .Name }}
+ {{- if or (eq .Optin "double") (eq .SubscriptionStatus "unsubscribed") }}
+ <sup class="status-{{ .SubscriptionStatus }}">{{ $.L.T (printf "subscribers.status.%s" .SubscriptionStatus) }}</sup>{{ end }}
+ </a>
+ {{- end }}
+ </div>
+ </td>
+ <td><a href="{{ URI "/admin/subscribers" }}/{{ .ID }}">{{ .Name }}</a></td>
+ <td class="align-center"><a href="{{ URI "/admin/subscribers" }}/{{ .ID }}/lists">{{ len .ParsedLists }}<br /><span class="view">{{ $.L.T "globals.buttons.view" }}</span></a></td>
+ <td>{{ NiceDate .CreatedAt }}</td>
+ <td>{{ NiceDate .UpdatedAt }}</td>
+ <td class="actions align-right">
+ <ot-dropdown>
+ <button popovertarget="sub-actions-{{ .ID }}" type="button" class="ghost small icon" aria-label="{{ $.L.T "globals.buttons.more" }}">
+ {{ 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>
+ {{- 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>
+ <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>
+ {{- end }}
+ </menu>
+ </ot-dropdown>
+ </td>
+ </tr>
+ {{- else }}
+ <tr><td colspan="7" class="align-center text-light">{{ .L.T "globals.messages.emptyState" }}</td></tr>
+ {{- end }}
+ </tbody>
+ </table>
+
+ {{- template "pagination" $d.Page.Pagination }}
+ </div>
+ </div>
+
+ <dialog class="b-modal" x-ref="dialog" @close="onDialogClose">
+ {{ template "subscriber-form" dict "Root" . "Submit" "onSubmitNew" "Method" "dialog" "CanSave" ($d.Can "subscribers:manage") }}
+ </dialog>
+
+ <dialog class="b-modal" x-ref="listDialog">
+ <form @submit.prevent="onSubmitManageLists">
+ <div class="dialog-card content">
+ <header class="dialog-head"><h3 class="dialog-title">{{ .L.T "subscribers.manageLists" }}</h3></header>
+ <section class="dialog-body">
+ {{ template "manage-lists-form" dict "Root" . "Model" "bulk" "ListID" "bulk-lists" }}
+ </section>
+ <footer class="dialog-foot hstack gap-3 justify-end">
+ <button type="button" class="outline" @click="$refs.listDialog.close()">{{ .L.T "globals.buttons.close" }}</button>
+ <button type="submit" data-variant="primary" :disabled="bulk.lists.length === 0">{{ .L.T "globals.buttons.save" }}</button>
+ </footer>
+ </div>
+ </form>
+ </dialog>
+</section>
+
+<script type="module" src="{{ URI "/admin/static/js/views/subscribers.js" }}?v={{ .AssetVersion }}" defer></script>
+
+{{ template "admin-footer" . -}}
+{{ end }}