Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(emails): add search, filtering and sorting to email log
Mike Kosulin43985c0f8867
diff --git a/docs/docs/analytics/dashboard.md b/docs/docs/analytics/dashboard.mdindex 1e8d23d..7b57a7b 100644--- a/docs/docs/analytics/dashboard.md+++ b/docs/docs/analytics/dashboard.md@@ -65,6 +65,9 @@ View sent emails for the workspace with pagination:GET /api/v1/workspaces/current/emails?page=1&size=20```+The same endpoint also supports search, filtering, and sorting — see+[Email Log](/docs/email-sending/email-log).+## Email DetailsGet full details for a specific email:diff --git a/docs/docs/email-sending/email-log.md b/docs/docs/email-sending/email-log.mdnew file mode 100644index 0000000..6943a0a--- /dev/null+++ b/docs/docs/email-sending/email-log.md@@ -0,0 +1,127 @@+---+sidebar_position: 7+title: Email Log+description: List, search, and filter a workspace's sent email+---++# Email Log++Browse the emails a workspace has sent. This workspace-scoped endpoint backs the+**Emails** page in the dashboard and supports pagination plus an operator-based+search string. All routes require a JWT and the workspace header:++```+Authorization: Bearer <jwt>+X-Posta-Workspace-Id: 1+```++:::tip+For the full request/response schema, see the interactive [API Reference](https://app.goposta.dev/docs).+:::++## List Emails++```+GET /api/v1/workspaces/current/emails+```++Returns a paginated list scoped to the current workspace, newest first.++Query parameters:++| Param | Type | Description |+|-------|------|-------------|+| `page` | int | Zero-based page index (default `0`). |+| `size` | int | Page size, 1–100 (default `20`). |+| `q` | string | Search string with optional operators (see below). |+| `sort` | string | Sort key (see [Sorting](#sorting)); default is newest first. |++```bash+curl "http://localhost:9000/api/v1/workspaces/current/emails?page=0&size=20" \+ -H "Authorization: Bearer <jwt>" \+ -H "X-Posta-Workspace-Id: 1"+```++## Search operators++The `q` parameter is a single search string that accepts operators. Words+without an operator match the **subject** — the body is not searched (it may be+stored as a blob or redacted).++| Operator | Matches | Example |+|----------|---------|---------|+| _(bare text)_ | Subject | `invoice reminder` |+| `subject:` | Subject | `subject:"weekly report"` |+| `from:` | Sender address | `from:[email protected]` |+| `to:` | Any recipient | `to:[email protected]` |+| `template:` | Template name | `template:welcome` |+| `has:attachment` | Emails that have attachments | `has:attachment` |+| `status:` | One or more statuses (comma-separated) | `status:failed,suppressed` |+| `after:` | Created on/after a date | `after:2026-07-01` |+| `before:` | Created on/before a date (inclusive) | `before:2026-07-20` |++**Matching rules**++- Text operators (`from:`, `to:`, `subject:`, `template:`) and bare words use+ **case-insensitive substring** matching.+- Use `*` as a wildcard: `to:*@example.com` matches addresses ending in+ `@example.com`; `subject:invoice*` matches subjects that start with "invoice".+- Wrap multi-word values in quotes: `subject:"payment failed"`.+- `status:` accepts a comma-separated list; an email matches if it is in **any**+ of the listed statuses. See [Email Status](/docs/email-sending/email-status)+ for the status values.+- Dates bound `created_at`. A `YYYY-MM-DD` value is treated as a whole day, so+ `before:` is inclusive of that day; a full RFC3339 timestamp is used as the+ exact instant.+- Operators combine with **AND**. Any bare words are merged into the subject search.++## Sorting++The `sort` parameter orders the results. Prefix a field with `-` for descending.+Any unknown value falls back to the default (`-created_at`, newest first), so the+default ordering is always safe.++| Sort key | Orders by |+|----------|-----------|+| `created_at` / `-created_at` | Creation time (default: `-created_at`) |+| `sent_at` / `-sent_at` | Delivery time |+| `subject` / `-subject` | Subject |+| `sender` / `-sender` | Sender address |+| `template` / `-template` | Template name |+| `status` / `-status` | Status |++```bash+curl "http://localhost:9000/api/v1/workspaces/current/emails?sort=-sent_at" \+ -H "Authorization: Bearer <jwt>" \+ -H "X-Posta-Workspace-Id: 1"+```++Example — failed or suppressed invoices that carry an attachment, from July 2026:++```bash+curl -G http://localhost:9000/api/v1/workspaces/current/emails \+ -H "Authorization: Bearer <jwt>" \+ -H "X-Posta-Workspace-Id: 1" \+ --data-urlencode "q=invoice has:attachment status:failed,suppressed after:2026-07-01 before:2026-07-31"+```++## In the dashboard++The **Emails** page exposes the same capability: a search box that accepts every+operator above, plus quick filters for status (multi-select), a date range, and+an attachments toggle. Clicking a column header sorts by it (click again to+reverse, once more to clear). The active query and sort are stored in the page+URL, so a view can be bookmarked or shared, and it survives reloads and+pagination. Times are shown in your browser's local timezone with a short label+(e.g. `GMT+3`).++## Email details++Fetch the full record for one email by its UUID:++```+GET /api/v1/workspaces/current/emails/{id}+```++Email content may be redacted depending on the administrator's privacy settings.+To retry a failed send, see [Email Status](/docs/email-sending/email-status).diff --git a/docs/sidebars.ts b/docs/sidebars.tsindex c9dd850..d54620f 100644--- a/docs/sidebars.ts+++ b/docs/sidebars.ts@@ -23,6 +23,7 @@ const sidebars: SidebarsConfig = {'email-sending/scheduled-email','email-sending/attachments','email-sending/email-status',+ 'email-sending/email-log','email-sending/email-verification',],},diff --git a/internal/handlers/email_handler.go b/internal/handlers/email_handler.goindex d83f216..541c4f5 100644--- a/internal/handlers/email_handler.go+++ b/internal/handlers/email_handler.go@@ -51,8 +51,10 @@ type SendBatchEmailRequest struct {Body email.BatchRequest `json:"body"`}type ListRequest struct {- Page int `query:"page" default:"0"`- Size int `query:"size" default:"20"`+ Page int `query:"page" default:"0"`+ Size int `query:"size" default:"20"`+ Q string `query:"q" doc:"Search with operators: from: to: subject: template: has:attachment after: before: status:"`+ Sort string `query:"sort" doc:"Sort key: created_at|sent_at|subject|sender|template|status, prefix '-' for descending (default: -created_at)"`}type GetByIDRequest struct {ID int `param:"id"`@@ -296,7 +298,8 @@ func normalizePageParams(page, size int) (int, int, int) {func (h *EmailHandler) List(c *okapi.Context, req *ListRequest) error {page, size, offset := normalizePageParams(req.Page, req.Size)- emails, total, err := h.emailRepo.FindByScope(getScope(c), size, offset)+ filter := repositories.ParseSearchQuery(req.Q)+ emails, total, err := h.emailRepo.FindByScopeFiltered(getScope(c), filter, req.Sort, size, offset)if err != nil {return c.AbortInternalServerError("failed to list emails")}diff --git a/internal/storage/repositories/email_repo.go b/internal/storage/repositories/email_repo.goindex a235854..c1d77ec 100644--- a/internal/storage/repositories/email_repo.go+++ b/internal/storage/repositories/email_repo.go@@ -109,6 +109,54 @@ func (r *EmailRepository) FindByScope(scope ResourceScope, limit, offset int) ([return items, total, nil}+// FindByScopeFiltered returns scoped emails narrowed by the given search filter.+// sort is an optional sort key (e.g. "subject", "-sent_at"); empty/unknown keeps+// the default newest-first order.+func (r *EmailRepository) FindByScopeFiltered(scope ResourceScope, f EmailFilter, sort string, limit, offset int) ([]models.Email, int64, error) {+ var items []models.Email+ var total int64++ apply := func(q *gorm.DB) *gorm.DB {+ q = ApplyScope(q, scope)+ if f.Sender != "" {+ q = q.Where("LOWER(sender) LIKE ?", likePattern(f.Sender))+ }+ if f.Recipient != "" {+ q = q.Where("EXISTS (SELECT 1 FROM unnest(recipients) AS r WHERE LOWER(r) LIKE ?)",+ likePattern(f.Recipient))+ }+ if f.Subject != "" {+ q = q.Where("LOWER(subject) LIKE ?", likePattern(f.Subject))+ }+ if f.Template != "" {+ q = q.Where("LOWER(template_name) LIKE ?", likePattern(f.Template))+ }+ if len(f.Statuses) > 0 {+ q = q.Where("status IN ?", f.Statuses)+ }+ if f.HasAttachment {+ q = q.Where("attachments_json <> '' AND attachments_json <> '[]'")+ }+ if f.After != nil {+ q = q.Where("created_at >= ?", *f.After)+ }+ if f.Before != nil {+ q = q.Where("created_at < ?", *f.Before)+ }+ return q+ }++ apply(r.db.Model(&models.Email{})).Count(&total)++ if err := apply(r.db).+ Order(orderClause(sort)).+ Limit(limit).Offset(offset).+ Find(&items).Error; err != nil {+ return nil, 0, err+ }+ return items, total, nil+}+// FindFailedForRetry returns failed emails with retry_count < maxRetries for a given user.func (r *EmailRepository) FindFailedForRetry(userID uint, maxRetries int) ([]models.Email, error) {var emails []models.Emaildiff --git a/internal/storage/repositories/email_search.go b/internal/storage/repositories/email_search.gonew file mode 100644index 0000000..427532c--- /dev/null+++ b/internal/storage/repositories/email_search.go@@ -0,0 +1,233 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package repositories++import (+ "strings"+ "time"+)++// Search operator keys and the DB columns they map to. Kept as constants so the+// same literals aren't scattered across the parser and the sort whitelist.+const (+ opFrom = "from"+ opTo = "to"+ opSubject = "subject"+ opTemplate = "template"+ opStatus = "status"+ opHas = "has"+ opAfter = "after"+ opBefore = "before"++ colCreatedAt = "created_at"+ colSentAt = "sent_at"+ colSender = "sender"+ colTemplateName = "template_name"+)++// EmailFilter captures optional list filters for outbound email queries.+type EmailFilter struct {+ Sender string+ Recipient string+ Subject string+ Template string+ Statuses []string+ HasAttachment bool+ After *time.Time+ Before *time.Time+}++// maxSearchQueryLen bounds the raw search string before parsing so a single+// request cannot build pathologically large predicates (huge status lists, many+// wildcards, or very long LIKE terms) against the unindexed email columns.+const maxSearchQueryLen = 512++// ParseSearchQuery turns a Twitter-style search string into an EmailFilter.+// Supported operators: from: to: subject: template: status: has:attachment after: before:+// Bare words (no known prefix) accumulate into Subject as a free-text search.+//+// Example:+//+// from:[email protected] to:bob subject:"weekly report" has:attachment after:2026-01-01 status:sent invoice+func ParseSearchQuery(q string) EmailFilter {+ if len(q) > maxSearchQueryLen {+ q = q[:maxSearchQueryLen]+ }++ var f EmailFilter+ var free []string++ for _, tok := range tokenizeSearch(q) {+ key, val, ok := strings.Cut(tok, ":")+ if !ok {+ free = append(free, tok)+ continue+ }+ switch strings.ToLower(key) {+ case opFrom:+ f.Sender = val+ case opTo:+ f.Recipient = val+ case opSubject:+ f.appendSubject(val)+ case opTemplate:+ f.Template = val+ case opStatus:+ // Accept a comma-separated list, e.g. status:sent,failed.+ for _, s := range strings.Split(val, ",") {+ if s = strings.ToLower(strings.TrimSpace(s)); s != "" {+ f.Statuses = append(f.Statuses, s)+ }+ }+ case opHas:+ if v := strings.ToLower(val); v == "attachment" || v == "attachments" {+ f.HasAttachment = true+ }+ case opAfter:+ if t, _, ok := parseSearchDate(val); ok {+ f.After = &t+ }+ case opBefore:+ if t, dateOnly, ok := parseSearchDate(val); ok {+ // A date-only bound covers the whole day (created_at < next+ // midnight). An explicit RFC3339 instant is used as given.+ if dateOnly {+ t = t.Add(24 * time.Hour)+ }+ f.Before = &t+ }+ default:+ // Unknown prefix: treat the whole token as free text.+ free = append(free, tok)+ }+ }++ if len(free) > 0 {+ f.appendSubject(strings.Join(free, " "))+ }+ return f+}++func (f *EmailFilter) appendSubject(s string) {+ s = strings.TrimSpace(s)+ if s == "" {+ return+ }+ if f.Subject == "" {+ f.Subject = s+ return+ }+ f.Subject += " " + s+}++// likePattern builds a case-insensitive SQL LIKE pattern from a user term.+// A `*` acts as a wildcard (mapped to `%`); without one the term matches as a+// substring. Any real LIKE metacharacters in the input are escaped so they stay+// literal (Postgres LIKE uses `\` as the default escape).+func likePattern(term string) string {+ s := strings.ToLower(strings.TrimSpace(term))+ s = strings.ReplaceAll(s, "\\", "\\\\")+ s = strings.ReplaceAll(s, "%", "\\%")+ s = strings.ReplaceAll(s, "_", "\\_")+ if strings.Contains(s, "*") {+ return strings.ReplaceAll(s, "*", "%")+ }+ return "%" + s + "%"+}++// sortColumns whitelists the user-facing sort keys to real, safe column names.+// ORDER BY is built only from these constants — user input never reaches SQL.+var sortColumns = map[string]string{+ colCreatedAt: colCreatedAt,+ colSentAt: colSentAt,+ opSubject: opSubject,+ colSender: colSender,+ opTemplate: colTemplateName,+ opStatus: opStatus,+}++// orderClause maps an optional sort key to a safe "column DIR" ORDER BY clause.+// A leading "-" means descending. Empty or unknown input falls back to the+// default (newest first), so the current behaviour is preserved.+func orderClause(sort string) string {+ const def = "created_at DESC"+ sort = strings.TrimSpace(sort)+ if sort == "" {+ return def+ }+ desc := false+ if strings.HasPrefix(sort, "-") {+ desc = true+ sort = sort[1:]+ }+ col, ok := sortColumns[strings.ToLower(strings.TrimSpace(sort))]+ if !ok {+ return def+ }+ // NULLS LAST keeps rows with a null sort value (e.g. unsent emails when+ // sorting by sent_at) at the bottom regardless of direction.+ if desc {+ return col + " DESC NULLS LAST"+ }+ return col + " ASC NULLS LAST"+}++// tokenizeSearch splits a query on whitespace while keeping double-quoted+// values together (quotes may follow an operator prefix, e.g. subject:"a b").+func tokenizeSearch(q string) []string {+ var tokens []string+ var b strings.Builder+ inQuote := false++ flush := func() {+ if b.Len() > 0 {+ tokens = append(tokens, b.String())+ b.Reset()+ }+ }++ for _, r := range q {+ switch {+ case r == '"':+ inQuote = !inQuote+ case (r == ' ' || r == '\t' || r == '\n') && !inQuote:+ flush()+ default:+ b.WriteRune(r)+ }+ }+ flush()+ return tokens+}++// parseSearchDate accepts a date-only (YYYY-MM-DD) or RFC3339 timestamp. It+// reports dateOnly=true when the value carried no time component, so callers can+// apply whole-day rounding only in that case (never to an explicit instant).+func parseSearchDate(s string) (t time.Time, dateOnly bool, ok bool) {+ s = strings.TrimSpace(s)+ if s == "" {+ return time.Time{}, false, false+ }+ if t, err := time.Parse("2006-01-02", s); err == nil {+ return t, true, true+ }+ if t, err := time.Parse(time.RFC3339, s); err == nil {+ return t, false, true+ }+ return time.Time{}, false, false+}diff --git a/internal/storage/repositories/email_search_test.go b/internal/storage/repositories/email_search_test.gonew file mode 100644index 0000000..1c9f154--- /dev/null+++ b/internal/storage/repositories/email_search_test.go@@ -0,0 +1,226 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package repositories++import (+ "strings"+ "testing"+ "time"+)++func TestParseSearchQuery(t *testing.T) {+ date := func(s string) *time.Time {+ tt, err := time.Parse("2006-01-02", s)+ if err != nil {+ t.Fatalf("bad test date %q: %v", s, err)+ }+ return &tt+ }+ rfc := func(s string) *time.Time {+ tt, err := time.Parse(time.RFC3339, s)+ if err != nil {+ t.Fatalf("bad test timestamp %q: %v", s, err)+ }+ return &tt+ }++ tests := []struct {+ name string+ q string+ want EmailFilter+ }{+ {+ name: "empty",+ q: "",+ want: EmailFilter{},+ },+ {+ name: "bare words become subject",+ q: "weekly invoice",+ want: EmailFilter{Subject: "weekly invoice"},+ },+ {+ name: "from and to operators",+ q: "from:[email protected] to:[email protected]",+ want: EmailFilter{Sender: "[email protected]", Recipient: "[email protected]"},+ },+ {+ name: "quoted subject keeps spaces",+ q: `subject:"weekly report"`,+ want: EmailFilter{Subject: "weekly report"},+ },+ {+ name: "has attachment flag (singular and plural)",+ q: "has:attachments",+ want: EmailFilter{HasAttachment: true},+ },+ {+ name: "status is lowercased",+ q: "status:Sent",+ want: EmailFilter{Statuses: []string{"sent"}},+ },+ {+ name: "status accepts a comma-separated list",+ q: "status:sent,failed",+ want: EmailFilter{Statuses: []string{"sent", "failed"}},+ },+ {+ name: "after is parsed as start of day",+ q: "after:2026-07-01",+ want: EmailFilter{After: date("2026-07-01")},+ },+ {+ name: "before is inclusive (next day) for date-only",+ q: "before:2026-07-20",+ want: EmailFilter{Before: date("2026-07-21")},+ },+ {+ name: "before with RFC3339 instant is used as-is (no day rounding)",+ q: "before:2026-07-20T12:00:00Z",+ want: EmailFilter{Before: rfc("2026-07-20T12:00:00Z")},+ },+ {+ name: "after with RFC3339 instant is used as-is",+ q: "after:2026-07-01T08:30:00Z",+ want: EmailFilter{After: rfc("2026-07-01T08:30:00Z")},+ },+ {+ name: "invalid date is ignored",+ q: "after:not-a-date",+ want: EmailFilter{},+ },+ {+ name: "operators mixed with free text",+ q: `from:alice subject:report has:attachment status:failed after:2026-01-01 urgent`,+ want: EmailFilter{+ Sender: "alice",+ Subject: "report urgent",+ Statuses: []string{"failed"},+ HasAttachment: true,+ After: date("2026-01-01"),+ },+ },+ {+ name: "template operator",+ q: "template:welcome-email",+ want: EmailFilter{Template: "welcome-email"},+ },+ {+ name: "unknown prefix falls back to free text",+ q: "cc:someone",+ want: EmailFilter{Subject: "cc:someone"},+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := ParseSearchQuery(tc.q)+ if got.Sender != tc.want.Sender {+ t.Errorf("Sender = %q, want %q", got.Sender, tc.want.Sender)+ }+ if got.Recipient != tc.want.Recipient {+ t.Errorf("Recipient = %q, want %q", got.Recipient, tc.want.Recipient)+ }+ if got.Subject != tc.want.Subject {+ t.Errorf("Subject = %q, want %q", got.Subject, tc.want.Subject)+ }+ if got.Template != tc.want.Template {+ t.Errorf("Template = %q, want %q", got.Template, tc.want.Template)+ }+ if strings.Join(got.Statuses, ",") != strings.Join(tc.want.Statuses, ",") {+ t.Errorf("Statuses = %v, want %v", got.Statuses, tc.want.Statuses)+ }+ if got.HasAttachment != tc.want.HasAttachment {+ t.Errorf("HasAttachment = %v, want %v", got.HasAttachment, tc.want.HasAttachment)+ }+ if !timeEq(got.After, tc.want.After) {+ t.Errorf("After = %v, want %v", got.After, tc.want.After)+ }+ if !timeEq(got.Before, tc.want.Before) {+ t.Errorf("Before = %v, want %v", got.Before, tc.want.Before)+ }+ })+ }+}++func TestParseSearchQueryLengthCap(t *testing.T) {+ // A very long term must not build an unbounded predicate value.+ f := ParseSearchQuery("subject:" + strings.Repeat("a", 4000))+ if len(f.Subject) > maxSearchQueryLen {+ t.Errorf("subject not capped: len=%d, want <= %d", len(f.Subject), maxSearchQueryLen)+ }+ // A huge comma-separated status list must be bounded too.+ f = ParseSearchQuery("status:" + strings.Repeat("sent,", 4000))+ if len(f.Statuses) > maxSearchQueryLen {+ t.Errorf("statuses not capped: len=%d", len(f.Statuses))+ }+}++func TestOrderClause(t *testing.T) {+ tests := []struct{ in, want string }{+ {"", "created_at DESC"}, // default preserved (unchanged)+ {"created_at", "created_at ASC NULLS LAST"}, // explicit asc+ {"-created_at", "created_at DESC NULLS LAST"}, // explicit desc+ {"sent_at", "sent_at ASC NULLS LAST"},+ {"-sent_at", "sent_at DESC NULLS LAST"},+ {"subject", "subject ASC NULLS LAST"},+ {"sender", "sender ASC NULLS LAST"},+ {"template", "template_name ASC NULLS LAST"}, // mapped column name+ {"-template", "template_name DESC NULLS LAST"},+ {"status", "status ASC NULLS LAST"},+ {"STATUS", "status ASC NULLS LAST"}, // case-insensitive key+ {"bogus", "created_at DESC"}, // unknown -> default+ {"-", "created_at DESC"}, // lone dash -> default+ {"created_at; DROP TABLE emails", "created_at DESC"}, // injection -> default+ {"sender) --", "created_at DESC"}, // injection -> default+ }+ for _, tc := range tests {+ if got := orderClause(tc.in); got != tc.want {+ t.Errorf("orderClause(%q) = %q, want %q", tc.in, got, tc.want)+ }+ }+}++func TestLikePattern(t *testing.T) {+ tests := []struct {+ name string+ in string+ want string+ }{+ {"substring by default", "example.com", "%example.com%"},+ {"leading wildcard", "*@example.com", "%@example.com"},+ {"trailing wildcard", "john*", "john%"},+ {"case folded", "[email protected]", "%[email protected]%"},+ {"escapes percent", "50%", "%50\\%%"},+ {"escapes underscore", "a_b", "%a\\_b%"},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := likePattern(tc.in); got != tc.want {+ t.Errorf("likePattern(%q) = %q, want %q", tc.in, got, tc.want)+ }+ })+ }+}++func timeEq(a, b *time.Time) bool {+ if a == nil || b == nil {+ return a == b+ }+ return a.Equal(*b)+}diff --git a/web/src/api/emails.ts b/web/src/api/emails.tsindex 0d6c8ae..a479e64 100644--- a/web/src/api/emails.ts+++ b/web/src/api/emails.ts@@ -19,8 +19,10 @@ export interface EmailPreviewResponse {}export const emailsApi = {- list(page = 0, size = 20) {- return api.get<PaginatedResponse<Email>>('/workspaces/current/emails', { params: { page, size } })+ list(page = 0, size = 20, q = '', sort = '') {+ return api.get<PaginatedResponse<Email>>('/workspaces/current/emails', {+ params: { page, size, q: q || undefined, sort: sort || undefined },+ })},get(uuid: string) {return api.get<ApiResponse<Email>>(`/workspaces/current/emails/${uuid}`)diff --git a/web/src/composables/searchTokens.ts b/web/src/composables/searchTokens.tsnew file mode 100644index 0000000..305dbb2--- /dev/null+++ b/web/src/composables/searchTokens.ts@@ -0,0 +1,84 @@+// Lightweight helpers to read/write operator tokens inside a single search+// string (e.g. `from:alice subject:"weekly report" has:attachment after:2026-01-01`).+// The string stays the single source of truth — the backend does the real+// parsing — so UI controls only nudge tokens in and out of it.++function tokenize(q: string): string[] {+ const tokens: string[] = []+ let cur = ''+ let inQuote = false+ for (const ch of q) {+ if (ch === '"') {+ inQuote = !inQuote+ continue+ }+ if (/\s/.test(ch) && !inQuote) {+ if (cur) {+ tokens.push(cur)+ cur = ''+ }+ continue+ }+ cur += ch+ }+ if (cur) tokens.push(cur)+ return tokens+}++function serialize(tokens: string[]): string {+ return tokens+ .map((t) => {+ const i = t.indexOf(':')+ if (i > 0) {+ const key = t.slice(0, i)+ const val = t.slice(i + 1)+ return /\s/.test(val) ? `${key}:"${val}"` : t+ }+ return /\s/.test(t) ? `"${t}"` : t+ })+ .join(' ')+}++/** Returns the value of the first `key:value` token, or '' when absent. */+export function getToken(q: string, key: string): string {+ const k = key.toLowerCase()+ for (const t of tokenize(q)) {+ const i = t.indexOf(':')+ if (i > 0 && t.slice(0, i).toLowerCase() === k) return t.slice(i + 1)+ }+ return ''+}++/** Sets/replaces a `key:value` token; an empty value removes it. */+export function setToken(q: string, key: string, value: string): string {+ const k = key.toLowerCase()+ const out: string[] = []+ let done = false+ for (const t of tokenize(q)) {+ const i = t.indexOf(':')+ if (i > 0 && t.slice(0, i).toLowerCase() === k) {+ if (!done && value) {+ out.push(`${key}:${value}`)+ done = true+ }+ continue+ }+ out.push(t)+ }+ if (!done && value) out.push(`${key}:${value}`)+ return serialize(out)+}++/** True when the exact flag token (e.g. `has:attachment`) is present. */+export function hasFlag(q: string, flag: string): boolean {+ const f = flag.toLowerCase()+ return tokenize(q).some((t) => t.toLowerCase() === f)+}++/** Adds or removes a standalone flag token. */+export function toggleFlag(q: string, flag: string, on: boolean): string {+ const f = flag.toLowerCase()+ const tokens = tokenize(q).filter((t) => t.toLowerCase() !== f)+ if (on) tokens.push(flag)+ return serialize(tokens)+}diff --git a/web/src/views/emails/Emails.vue b/web/src/views/emails/Emails.vueindex 0bc6e9d..d7c04be 100644--- a/web/src/views/emails/Emails.vue+++ b/web/src/views/emails/Emails.vue@@ -1,22 +1,30 @@<script setup lang="ts">-import { ref } from 'vue'-import { useRouter } from 'vue-router'+import { computed, onBeforeUnmount, onMounted, ref } from 'vue'+import { useRoute, useRouter } from 'vue-router'import { emailsApi } from '../../api/emails'import { useNotificationStore } from '../../stores/notification'import type { Email } from '../../api/types'import Pagination from '../../components/Pagination.vue'import { usePagination } from '../../composables/usePagination'+import { getToken, hasFlag, setToken, toggleFlag } from '../../composables/searchTokens'+const route = useRoute()const router = useRouter()const notify = useNotificationStore()const loading = ref(true)const emails = ref<Email[]>([])const retryingId = ref<string | null>(null)+const showFilters = ref(false)-const { pageable, goToPage } = usePagination(async (page) => {+// The search string is the single source of truth, mirrored to the URL (?q=).+const queryText = ref<string>(typeof route.query.q === 'string' ? route.query.q : '')+// Optional sort key (e.g. 'subject', '-sent_at'); empty keeps the default order.+const sortValue = ref<string>(typeof route.query.sort === 'string' ? route.query.sort : '')++const load = async (page: number) => {loading.value = truetry {- const res = await emailsApi.list(page)+ const res = await emailsApi.list(page, pageable.value.size, queryText.value, sortValue.value)emails.value = res.data.datapageable.value = res.data.pageable} catch (e) {@@ -24,7 +32,150 @@ const { pageable, goToPage } = usePagination(async (page) => {} finally {loading.value = false}+}++const { pageable, goToPage } = usePagination(load)++let searchTimeout: ReturnType<typeof setTimeout> | null = null+function clearSearchTimeout() {+ if (searchTimeout) {+ clearTimeout(searchTimeout)+ searchTimeout = null+ }+}++function applySearch() {+ // Drop any pending debounce so an immediate apply (Enter / a quick filter)+ // doesn't get followed by a duplicate fire.+ clearSearchTimeout()+ router.replace({ query: { ...route.query, q: queryText.value || undefined, page: undefined } })+ load(0)+}++// Debounce free-text typing; discrete controls call applySearch directly.+function onSearchInput() {+ clearSearchTimeout()+ searchTimeout = setTimeout(applySearch, 300)+}++function resetSearch() {+ queryText.value = ''+ applySearch()+}++// Column sorting — mirrored to the URL (?sort=). Clicking a column cycles+// ascending -> descending -> default (newest first).+const sortField = computed(() => sortValue.value.replace(/^-/, ''))+const sortDesc = computed(() => sortValue.value.startsWith('-'))+function toggleSort(field: string) {+ let next: string+ if (sortField.value !== field) next = field+ else if (!sortDesc.value) next = '-' + field+ else next = ''+ sortValue.value = next+ router.replace({ query: { ...route.query, sort: next || undefined, page: undefined } })+ load(0)+}+function sortIcon(field: string) {+ if (sortField.value !== field) return 'mdi-unfold-more-horizontal th-sort__arrow--idle'+ return sortDesc.value ? 'mdi-arrow-down' : 'mdi-arrow-up'+}++// Surfaced quick filters — each just nudges a token in `queryText`.+const hasAttachment = computed({+ get: () => hasFlag(queryText.value, 'has:attachment') || hasFlag(queryText.value, 'has:attachments'),+ set: (on: boolean) => {+ let s = toggleFlag(queryText.value, 'has:attachments', false)+ s = toggleFlag(s, 'has:attachment', on)+ queryText.value = s+ applySearch()+ },+})+const afterDate = computed({+ get: () => getToken(queryText.value, 'after'),+ set: (v: string) => {+ queryText.value = setToken(queryText.value, 'after', v)+ applySearch()+ },})+const beforeDate = computed({+ get: () => getToken(queryText.value, 'before'),+ set: (v: string) => {+ queryText.value = setToken(queryText.value, 'before', v)+ applySearch()+ },+})+const STATUS_OPTIONS = [+ { value: 'sent', label: 'Sent' },+ { value: 'queued', label: 'Queued' },+ { value: 'pending', label: 'Pending' },+ { value: 'processing', label: 'Processing' },+ { value: 'scheduled', label: 'Scheduled' },+ { value: 'failed', label: 'Failed' },+ { value: 'suppressed', label: 'Suppressed' },+]+const statusLabel = (v: string) => STATUS_OPTIONS.find((o) => o.value === v)?.label ?? v++// Status is a multi-select — stored as a comma-separated `status:` token.+const statuses = computed<string[]>({+ get: () => {+ const raw = getToken(queryText.value, 'status')+ return raw ? raw.split(',').map((s) => s.trim()).filter(Boolean) : []+ },+ set: (vals: string[]) => {+ queryText.value = setToken(queryText.value, 'status', vals.join(','))+ applySearch()+ },+})+function toggleStatus(value: string) {+ const cur = statuses.value+ statuses.value = cur.includes(value) ? cur.filter((s) => s !== value) : [...cur, value]+}+const statusSummary = computed(() => {+ const n = statuses.value.length+ if (n === 0) return 'Any status'+ if (n === 1) return statusLabel(statuses.value[0])+ return `${n} statuses`+})++// Close the status dropdown on an outside click.+const statusOpen = ref(false)+const statusRef = ref<HTMLElement | null>(null)+function onDocClick(e: MouseEvent) {+ if (statusOpen.value && statusRef.value && !statusRef.value.contains(e.target as Node)) {+ statusOpen.value = false+ }+}+onMounted(() => document.addEventListener('click', onDocClick))+onBeforeUnmount(() => {+ document.removeEventListener('click', onDocClick)+ clearSearchTimeout()+})++// Compact summary of the structured quick-filters that are active — shown as+// removable chips so the selection stays visible even when the panel is closed.+const activeChips = computed(() => {+ const chips: { key: string; label: string }[] = []+ for (const s of statuses.value) chips.push({ key: `status:${s}`, label: `Status: ${statusLabel(s)}` })+ if (afterDate.value) chips.push({ key: 'after', label: `After: ${afterDate.value}` })+ if (beforeDate.value) chips.push({ key: 'before', label: `Before: ${beforeDate.value}` })+ if (hasAttachment.value) chips.push({ key: 'attachment', label: 'Has attachments' })+ return chips+})++function removeChip(key: string) {+ if (key.startsWith('status:')) {+ const v = key.slice('status:'.length)+ statuses.value = statuses.value.filter((s) => s !== v)+ } else if (key === 'attachment') hasAttachment.value = false+ else if (key === 'after') afterDate.value = ''+ else if (key === 'before') beforeDate.value = ''+}++function hasAttachments(email: Email): boolean {+ const a = email.attachments_json+ return !!a && a !== '' && a !== '[]'+}async function retryEmail(e: Event, em: Email) {e.stopPropagation()@@ -58,7 +209,9 @@ function statusBadgeClass(status: string) {function formatDate(date: string | null) {if (!date) return '-'- return new Date(date).toLocaleString()+ // Rendered in the viewer's local timezone; the short tz label (e.g. GMT+3)+ // keeps the time unambiguous.+ return new Date(date).toLocaleString(undefined, { timeZoneName: 'short' })}</script>@@ -69,58 +222,457 @@ function formatDate(date: string | null) {<button class="btn btn-secondary" @click="router.push('/templates/preview')">Preview Template</button></div>- <div v-if="loading" class="loading-page">- <div class="spinner"></div>- </div>+ <div class="card">+ <div class="card-body filters">+ <div class="filters__bar">+ <div class="filters__search">+ <span class="mdi mdi-magnify filters__search-icon"></span>+ <input+ v-model="queryText"+ class="form-input filters__search-input"+ placeholder="Search — from: to: subject: template: has:attachment after: before: status:"+ @input="onSearchInput"+ @keyup.enter="applySearch"+ />+ </div>+ <button+ class="btn btn-secondary filters__toggle"+ :class="{ 'filters__toggle--active': showFilters }"+ @click="showFilters = !showFilters"+ >+ <span class="mdi mdi-tune-variant"></span>+ <span class="filters__toggle-label">Filters</span>+ <span v-if="activeChips.length" class="filters__badge">{{ activeChips.length }}</span>+ </button>+ </div>++ <div v-if="activeChips.length" class="filters__chips">+ <button+ v-for="c in activeChips"+ :key="c.key"+ class="filters__chip"+ @click="removeChip(c.key)"+ >+ {{ c.label }}+ <span class="mdi mdi-close"></span>+ </button>+ <button class="filters__chip filters__chip--clear" @click="resetSearch">Clear all</button>+ </div>++ <div v-show="showFilters" class="filters__panel">+ <div ref="statusRef" class="filters__field">+ <label class="form-label">Status</label>+ <div class="msel">+ <button+ type="button"+ class="msel__button"+ :class="{ 'msel__button--empty': !statuses.length, 'msel__button--open': statusOpen }"+ @click="statusOpen = !statusOpen"+ >+ <span>{{ statusSummary }}</span>+ <span class="mdi mdi-chevron-down msel__chevron"></span>+ </button>+ <div v-if="statusOpen" class="msel__menu">+ <label v-for="o in STATUS_OPTIONS" :key="o.value" class="msel__option">+ <input+ type="checkbox"+ :checked="statuses.includes(o.value)"+ @change="toggleStatus(o.value)"+ />+ <span>{{ o.label }}</span>+ </label>+ </div>+ </div>+ </div>++ <div class="filters__field">+ <label class="form-label">After</label>+ <input v-model="afterDate" type="date" class="form-input" />+ </div>++ <div class="filters__field">+ <label class="form-label">Before</label>+ <input v-model="beforeDate" type="date" class="form-input" />+ </div>++ <label class="filters__check">+ <input v-model="hasAttachment" type="checkbox" />+ <span>Has attachments</span>+ </label>- <div v-else class="card">- <div v-if="emails.length === 0" class="empty-state">- <h3>No emails found</h3>- <p>Emails sent through the API will appear here.</p>+ <button class="btn btn-secondary filters__reset" @click="resetSearch">Reset</button>+ </div>+ </div>++ <div v-if="loading" class="loading-page">+ <div class="spinner"></div></div>+<template v-else>- <div class="table-wrapper">- <table>- <thead>- <tr>- <th>Subject</th>- <th>From</th>- <th>Recipients</th>- <th>Template</th>- <th>Status</th>- <th>Sent At</th>- <th></th>- </tr>- </thead>- <tbody>- <tr- v-for="email in emails"- :key="email.uuid"- style="cursor: pointer"- @click="router.push(`/emails/${email.uuid}`)"- >- <td>{{ email.subject }}</td>- <td>{{ email.sender }}</td>- <td>{{ email.recipients.join(', ') }}</td>- <td>{{ email.template_name || 'N/A' }}</td>- <td><span :class="statusBadgeClass(email.status)">{{ email.status }}</span></td>- <td>{{ formatDate(email.sent_at) }}</td>- <td>- <button- v-if="email.status === 'failed'"- class="btn btn-secondary btn-sm"- :disabled="retryingId === email.uuid"- @click="retryEmail($event, email)"- >- {{ retryingId === email.uuid ? 'Retrying...' : 'Retry' }}- </button>- </td>- </tr>- </tbody>- </table>+ <div v-if="emails.length === 0" class="empty-state">+ <h3>No emails found</h3>+ <p v-if="queryText">No emails match your search. Try adjusting the filters.</p>+ <p v-else>Emails sent through the API will appear here.</p></div>- <Pagination :pageable="pageable" @page="goToPage" />+ <template v-else>+ <div class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th class="th-sort" :class="{ 'th-sort--active': sortField === 'subject' }" @click="toggleSort('subject')">+ <span class="th-sort__inner">Subject<span class="mdi th-sort__arrow" :class="sortIcon('subject')"></span></span>+ </th>+ <th class="th-sort" :class="{ 'th-sort--active': sortField === 'sender' }" @click="toggleSort('sender')">+ <span class="th-sort__inner">From<span class="mdi th-sort__arrow" :class="sortIcon('sender')"></span></span>+ </th>+ <th>Recipients</th>+ <th class="th-sort" :class="{ 'th-sort--active': sortField === 'template' }" @click="toggleSort('template')">+ <span class="th-sort__inner">Template<span class="mdi th-sort__arrow" :class="sortIcon('template')"></span></span>+ </th>+ <th class="th-sort" :class="{ 'th-sort--active': sortField === 'status' }" @click="toggleSort('status')">+ <span class="th-sort__inner">Status<span class="mdi th-sort__arrow" :class="sortIcon('status')"></span></span>+ </th>+ <th class="th-sort" :class="{ 'th-sort--active': sortField === 'sent_at' }" @click="toggleSort('sent_at')">+ <span class="th-sort__inner">Sent At<span class="mdi th-sort__arrow" :class="sortIcon('sent_at')"></span></span>+ </th>+ <th class="col-actions"></th>+ </tr>+ </thead>+ <tbody>+ <tr+ v-for="email in emails"+ :key="email.uuid"+ style="cursor: pointer"+ @click="router.push(`/emails/${email.uuid}`)"+ >+ <td>+ <span class="subject-cell">+ <span class="subject-cell__clip">+ <span+ v-if="hasAttachments(email)"+ class="mdi mdi-paperclip"+ title="Has attachments"+ ></span>+ </span>+ <span>{{ email.subject }}</span>+ </span>+ </td>+ <td>{{ email.sender }}</td>+ <td>{{ email.recipients.join(', ') }}</td>+ <td>{{ email.template_name || 'N/A' }}</td>+ <td><span :class="statusBadgeClass(email.status)">{{ email.status }}</span></td>+ <td>{{ formatDate(email.sent_at) }}</td>+ <td class="col-actions">+ <button+ v-if="email.status === 'failed'"+ class="btn btn-secondary btn-sm"+ :disabled="retryingId === email.uuid"+ @click="retryEmail($event, email)"+ >+ {{ retryingId === email.uuid ? 'Retrying...' : 'Retry' }}+ </button>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ <Pagination :pageable="pageable" @page="goToPage" />+ </template></template></div></div></template>++<style scoped>+/* Reserve a fixed gutter for the attachment clip so subjects always align,+ whether or not a row has an attachment. */+.subject-cell {+ display: inline-flex;+ align-items: center;+ gap: 6px;+}++.subject-cell__clip {+ flex: 0 0 16px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: var(--text-muted, var(--text-tertiary));+}++/* Sortable column headers */+.th-sort {+ cursor: pointer;+ user-select: none;+ white-space: nowrap;+}++.th-sort__inner {+ display: inline-flex;+ align-items: center;+ gap: 4px;+}++.th-sort__arrow {+ font-size: 15px;+ line-height: 1;+}++.th-sort__arrow--idle {+ opacity: 0;+ transition: opacity var(--transition);+}++.th-sort:hover .th-sort__arrow--idle {+ opacity: 0.45;+}++.th-sort--active {+ color: var(--text-primary);+}++/* Reserve a stable width for the action column so the table doesn't shift+ between pages/searches depending on whether a row has a Retry button. */+.col-actions {+ width: 96px;+ text-align: right;+}++.filters {+ display: flex;+ flex-direction: column;+ gap: 14px;+}++.filters__bar {+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+ align-items: center;+}++.filters__search {+ position: relative;+ flex: 1 1 240px;+ min-width: 200px;+}++.filters__search-icon {+ position: absolute;+ left: 12px;+ top: 50%;+ transform: translateY(-50%);+ font-size: 18px;+ color: var(--text-muted, var(--text-tertiary));+ pointer-events: none;+}++.filters__search-input {+ height: 44px;+ padding-left: 38px;+}++.filters__toggle {+ flex: 0 0 auto;+ height: 44px;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ white-space: nowrap;+}++.filters__toggle .mdi {+ font-size: 18px;+}++.filters__toggle--active {+ border-color: var(--primary-600);+ color: var(--primary-600);+}++.filters__badge {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-width: 18px;+ height: 18px;+ padding: 0 5px;+ border-radius: 999px;+ background: var(--primary-600);+ color: #fff;+ font-size: 11px;+ font-weight: 600;+ line-height: 1;+}++.filters__chips {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}++.filters__chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ font-size: 13px;+ border-radius: 999px;+ border: 1px solid var(--border-primary);+ background: var(--bg-tertiary);+ color: var(--text-secondary);+ cursor: pointer;+ transition: background var(--transition), border-color var(--transition);+}++.filters__chip:hover {+ background: var(--bg-hover);+}++.filters__chip .mdi {+ font-size: 14px;+ color: var(--text-tertiary);+}++.filters__chip--clear {+ border-style: dashed;+ background: transparent;+}++.filters__panel {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: 14px 16px;+ padding-top: 2px;+}++.filters__field {+ display: flex;+ flex-direction: column;+ gap: 6px;+ flex: 1 1 150px;+ min-width: 140px;+ max-width: 220px;+}++.filters__field .form-label {+ margin: 0;+}++.filters__field .form-input,+.filters__field .form-select {+ height: 44px;+}++.msel {+ position: relative;+}++.msel__button {+ width: 100%;+ height: 44px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 0 12px 0 14px;+ border: 1px solid var(--border-input);+ border-radius: var(--radius);+ background: var(--bg-input);+ color: var(--text-primary);+ font-size: 14px;+ font-family: inherit;+ cursor: pointer;+ text-align: left;+ transition: border-color var(--transition), box-shadow var(--transition);+}++.msel__button--open {+ border-color: var(--primary-600);+ box-shadow: var(--shadow-focus);+}++.msel__button--empty {+ color: var(--text-tertiary);+}++.msel__chevron {+ font-size: 18px;+ color: var(--text-tertiary);+ transition: transform var(--transition);+}++.msel__button--open .msel__chevron {+ transform: rotate(180deg);+}++.msel__menu {+ position: absolute;+ z-index: 20;+ top: calc(100% + 4px);+ left: 0;+ min-width: 100%;+ padding: 6px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ background: var(--bg-secondary);+ border: 1px solid var(--border-input);+ border-radius: var(--radius);+ box-shadow: var(--shadow-lg);+}++.msel__option {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 7px 8px;+ border-radius: var(--radius-sm);+ font-size: 14px;+ color: var(--text-secondary);+ white-space: nowrap;+ cursor: pointer;+}++.msel__option:hover {+ background: var(--bg-hover);+}++.msel__option input {+ width: 15px;+ height: 15px;+ cursor: pointer;+}++.filters__check {+ display: flex;+ align-items: center;+ gap: 8px;+ height: 44px;+ white-space: nowrap;+ cursor: pointer;+ user-select: none;+ color: var(--text-secondary);+ font-size: 14px;+}++.filters__check input {+ width: 16px;+ height: 16px;+ cursor: pointer;+}++.filters__reset {+ height: 44px;+ align-self: flex-end;+ margin-left: auto;+}++@media (max-width: 640px) {+ .filters__toggle {+ flex: 1 1 auto;+ justify-content: center;+ }+}+</style>