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(forms): add collect mode, message tags and priority, hide PII in emails
Jonas Kaninda34b4f6e3b637
diff --git a/internal/cron/jobs/message_digest.go b/internal/cron/jobs/message_digest.goindex 7de8259..9e4f9b8 100644--- a/internal/cron/jobs/message_digest.go+++ b/internal/cron/jobs/message_digest.go@@ -26,6 +26,7 @@ import ("time""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/messages""github.com/goposta/posta/internal/services/notification""github.com/goposta/posta/internal/storage/repositories""github.com/hibiken/asynq"@@ -101,6 +102,7 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labecontinue}+ mask := messages.NewPIIMask(form.Fields)items := make([]digestItem, 0, len(pending))ids := make([]uint, 0, len(pending))for k := range pending {@@ -111,8 +113,8 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labe}if len(items) < 25 {items = append(items, digestItem{- Sender: senderLabel(m),- Subject: m.Subject,+ Sender: senderLabel(m, mask),+ Subject: mask.Value(models.RoleSubject, m.Subject),Flagged: m.Status == models.MessageStatusFlagged,})}@@ -131,14 +133,19 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labedata := map[string]any{"Period": label,"FormName": form.Name,+ "Collect": form.IsCollect(),"Total": len(items),"Items": items,- "InboxURL": j.inboxURL(form.UUID),+ "InboxURL": j.inboxURL(form),}if workspaceName != "" {data["WorkspaceName"] = workspaceName}- subject := fmt.Sprintf("%s digest: %d new message(s) on %s", label, len(items), form.Name)+ noun := "message(s)"+ if form.IsCollect() {+ noun = "response(s)"+ }+ subject := fmt.Sprintf("%s digest: %d new %s on %s", label, len(items), noun, form.Name)if err := j.deliver(form, subject, data); err != nil {logger.Error("message-digest: failed to send", "form_id", form.ID, "error", err)@@ -173,22 +180,21 @@ func (j *MessageDigestJob) deliver(form *models.Form, subject string, data map[sreturn j.notifier.SendToWorkspaceAdmins(*form.WorkspaceID, subject, notification.TemplateMessageDigest, data)}-func (j *MessageDigestJob) inboxURL(formUUID string) string {+// inboxURL opens the form's responses for a collect form and the inbox,+// filtered to the form, otherwise.+func (j *MessageDigestJob) inboxURL(form *models.Form) string {if j.appURL == "" {return ""}- return fmt.Sprintf("%s/messages?form=%s", j.appURL, formUUID)+ if form.IsCollect() {+ return fmt.Sprintf("%s/forms/%d?tab=responses", j.appURL, form.ID)+ }+ return fmt.Sprintf("%s/messages?form_id=%d", j.appURL, form.ID)}-func senderLabel(m *models.Message) string {- switch {- case m.SenderName != "" && m.SenderEmail != "":- return fmt.Sprintf("%s <%s>", m.SenderName, m.SenderEmail)- case m.SenderEmail != "":- return m.SenderEmail- case m.SenderName != "":- return m.SenderName- default:- return "unknown"+func senderLabel(m *models.Message, mask messages.PIIMask) string {+ if label := mask.Sender(m.SenderName, m.SenderEmail); label != "" {+ return label}+ return "unknown"}diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.goindex dd16085..f72a0fb 100644--- a/internal/handlers/form_handler.go+++ b/internal/handlers/form_handler.go@@ -91,6 +91,7 @@ type CreateFormRequest struct {Name string `json:"name" required:"true"`Slug string `json:"slug"`Description string `json:"description"`+ Mode string `json:"mode" enum:"inbox,collect" doc:"inbox (default): submissions are conversations to answer. collect: responses read as a table, kept out of the inbox."`AllowedOrigins []string `json:"allowed_origins"`StrictOrigin bool `json:"strict_origin"`RedirectURL string `json:"redirect_url"`@@ -121,6 +122,7 @@ type UpdateFormRequest struct {Slug string `json:"slug"`Description string `json:"description"`Status string `json:"status" enum:"active,paused,archived"`+ Mode *string `json:"mode" doc:"inbox or collect"`AllowedOrigins *[]string `json:"allowed_origins"`StrictOrigin *bool `json:"strict_origin"`RedirectURL *string `json:"redirect_url"`@@ -210,6 +212,16 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {}}+ mode, valid := parseFormMode(req.Body.Mode)+ if !valid {+ return c.AbortBadRequest("mode must be inbox or collect")+ }+ notifyMode := normalizeNotifyMode(req.Body.NotifyMode)+ if mode == models.FormModeCollect && strings.TrimSpace(req.Body.NotifyMode) == "" {+ // A survey's responses are rarely urgent: one email a day, not one each.+ notifyMode = models.NotifyModeDaily+ }+key, err := generatePublicKey()if err != nil {return c.AbortInternalServerError("failed to generate form key")@@ -223,6 +235,7 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {Description: strings.TrimSpace(req.Body.Description),PublicKey: key,Status: models.FormStatusActive,+ Mode: mode,AllowedOrigins: origins,StrictOrigin: req.Body.StrictOrigin,RedirectURL: strings.TrimSpace(req.Body.RedirectURL),@@ -238,7 +251,7 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {RejectThreshold: 10,NotifyEnabled: true,NotifyEmails: notify,- NotifyMode: normalizeNotifyMode(req.Body.NotifyMode),+ NotifyMode: notifyMode,NotifyOnFlagged: true,ReplyFrom: replyFrom,ReplyFromName: strings.TrimSpace(req.Body.ReplyFromName),@@ -320,6 +333,13 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {}form.Status = status}+ if b.Mode != nil {+ mode, valid := parseFormMode(*b.Mode)+ if !valid {+ return c.AbortBadRequest("mode must be inbox or collect")+ }+ form.Mode = mode+ }if b.AllowedOrigins != nil {origins, err := normalizeOrigins(*b.AllowedOrigins)if err != nil {@@ -598,6 +618,17 @@ func parseNotifyMode(v string) (models.NotifyMode, bool) {}}+// parseFormMode reads a form mode; empty means inbox.+func parseFormMode(v string) (models.FormMode, bool) {+ switch models.FormMode(strings.ToLower(strings.TrimSpace(v))) {+ case "", models.FormModeInbox:+ return models.FormModeInbox, true+ case models.FormModeCollect:+ return models.FormModeCollect, true+ }+ return models.FormModeInbox, false+}+func normalizeNotifyMode(v string) models.NotifyMode {if strings.TrimSpace(v) == "" {return models.NotifyModeImmediatediff --git a/internal/handlers/form_submission_handler.go b/internal/handlers/form_submission_handler.goindex fca22a3..6dead25 100644--- a/internal/handlers/form_submission_handler.go+++ b/internal/handlers/form_submission_handler.go@@ -56,14 +56,16 @@ const (// field.<key>[lte]=n for ranges on number, scale, rating, date and time// questions.type SubmissionQueryRequest struct {- FormID int `query:"form_id" doc:"The form whose submissions to read (required)"`- Page int `query:"page" default:"0"`- Size int `query:"size" default:"20"`- Status string `query:"status" enum:"received,flagged,quarantined,rejected" doc:"Defaults to received and flagged: spam is not a response"`- Q string `query:"q" doc:"Free-text search over the submission"`- After string `query:"after" doc:"RFC 3339 lower bound on received time"`- Before string `query:"before" doc:"RFC 3339 upper bound on received time"`- Format string `query:"format" enum:"csv,json" default:"csv" doc:"Export only"`+ FormID int `query:"form_id" doc:"The form whose submissions to read (required)"`+ Page int `query:"page" default:"0"`+ Size int `query:"size" default:"20"`+ Status string `query:"status" enum:"received,flagged,quarantined,rejected" doc:"Defaults to received and flagged: spam is not a response"`+ Q string `query:"q" doc:"Free-text search over the submission"`+ After string `query:"after" doc:"RFC 3339 lower bound on received time"`+ Before string `query:"before" doc:"RFC 3339 upper bound on received time"`+ Tag string `query:"tag" doc:"Only submissions carrying this tag"`+ Priority string `query:"priority" enum:"low,normal,high,urgent"`+ Format string `query:"format" enum:"csv,json" default:"csv" doc:"Export only"`}// submissionQuery resolves the form and the filter a request names. It writes@@ -80,10 +82,16 @@ func (h *MessageHandler) submissionQuery(c *okapi.Context, req *SubmissionQueryRif err != nil {return nil, nil, c.AbortBadRequest(err.Error())}+ tags, err := tagFilter(req.Tag)+ if err != nil {+ return nil, nil, c.AbortBadRequest(err.Error())+ }filter := &repositories.MessageFilterQuery{FormID: form.ID,Status: req.Status,Query: strings.TrimSpace(req.Q),+ Tags: tags,+ Priority: req.Priority,SubmissionsOnly: true,DataEquals: equals,DataRanges: ranges,@@ -255,6 +263,20 @@ func answersOf(m *models.Message) models.SubmissionData {// exportColumns are the questions an export carries, active ones first, then// archived ones, so old answers are not lost. Personal-data questions are// left out unless the caller may see them.+func priorityOf(m *models.Message) models.MessagePriority {+ if m.Priority == "" {+ return models.MessagePriorityNormal+ }+ return m.Priority+}++func tagsOf(m *models.Message) []string {+ if m.Tags == nil {+ return []string{}+ }+ return m.Tags+}+func exportColumns(defs models.FieldDefs, showPII bool) (cols []models.FieldDef, withheld int) {for _, archived := range []bool{false, true} {for _, f := range defs {@@ -327,7 +349,7 @@ func (h *MessageHandler) ExportSubmissions(c *okapi.Context, req *SubmissionQuer// The byte-order mark makes Excel read the file as UTF-8._, _ = out.WriteString("\ufeff")w := csv.NewWriter(out)- header := []string{"Submitted at", "ID", "Status"}+ header := []string{"Submitted at", "ID", "Status", "Priority", "Tags"}if len(form.Fields) == 0 {header = append(header, "Email", "Name", "Phone", "Subject", "Message", "Fields")}@@ -348,7 +370,8 @@ func (h *MessageHandler) ExportSubmissions(c *okapi.Context, req *SubmissionQuerreturn nil}write = func(m *models.Message) error {- record := []string{m.CreatedAt.UTC().Format(time.RFC3339), m.UUID, string(m.Status)}+ record := []string{m.CreatedAt.UTC().Format(time.RFC3339), m.UUID, string(m.Status),+ string(priorityOf(m)), csvSafe(strings.Join(m.Tags, "; "))}if len(form.Fields) == 0 {hydrate(m)raw, _ := json.Marshal(m.Fields)@@ -381,6 +404,8 @@ func (h *MessageHandler) ExportSubmissions(c *okapi.Context, req *SubmissionQuer"id": m.UUID,"submitted_at": m.CreatedAt.UTC().Format(time.RFC3339),"status": m.Status,+ "priority": priorityOf(m),+ "tags": tagsOf(m),}if len(form.Fields) == 0 {hydrate(m)diff --git a/internal/handlers/message_handler.go b/internal/handlers/message_handler.goindex ebbcc75..c2a1211 100644--- a/internal/handlers/message_handler.go+++ b/internal/handlers/message_handler.go@@ -36,6 +36,7 @@ import ("github.com/goposta/posta/internal/storage/repositories""github.com/jkaninda/logger""github.com/jkaninda/okapi"+ "github.com/lib/pq")const (@@ -82,6 +83,8 @@ type MessageListRequest struct {After string `query:"after" doc:"RFC 3339 lower bound on received time"`Before string `query:"before" doc:"RFC 3339 upper bound on received time"`Assigned int `query:"assigned_to"`+ Tag string `query:"tag" doc:"Only messages carrying this tag"`+ Priority string `query:"priority" enum:"low,normal,high,urgent"`}type MessageIDRequest struct {@@ -117,6 +120,21 @@ type AssignMessageRequest struct {} `json:"body"`}+type UpdateMessageTagsRequest struct {+ ID string `param:"id"`+ Body struct {+ Add []string `json:"add" doc:"Tags to add. Tags are lowercased; at most 20 per message, 32 characters each."`+ Remove []string `json:"remove" doc:"Tags to remove"`+ } `json:"body"`+}++type UpdateMessagePriorityRequest struct {+ ID string `param:"id"`+ Body struct {+ Priority string `json:"priority" required:"true" enum:"low,normal,high,urgent"`+ } `json:"body"`+}+type MarkSpamRequest struct {ID string `param:"id"`Body struct {@@ -147,12 +165,21 @@ func (h *MessageHandler) List(c *okapi.Context, req *MessageListRequest) error {page, size, offset := normalizePageParams(req.Page, req.Size)filter := repositories.MessageFilterQuery{- FormID: uint(req.FormID),- Status: req.Status,- State: req.State,- Unread: req.Unread,- Query: strings.TrimSpace(req.Q),+ FormID: uint(req.FormID),+ Status: req.Status,+ State: req.State,+ Unread: req.Unread,+ Query: strings.TrimSpace(req.Q),+ Priority: req.Priority,+ // Collect-mode responses show in the inbox only when their form is+ // picked: the inbox is for conversations.+ InboxOnly: req.FormID == 0,+ }+ tags, err := tagFilter(req.Tag)+ if err != nil {+ return c.AbortBadRequest(err.Error())}+ filter.Tags = tagsif req.Assigned > 0 {assigned := uint(req.Assigned)filter.Assigned = &assigned@@ -323,6 +350,66 @@ func (h *MessageHandler) Assign(c *okapi.Context, req *AssignMessageRequest) errreturn ok(c, msg)}+// UpdateTags adds and removes tags on a message.+func (h *MessageHandler) UpdateTags(c *okapi.Context, req *UpdateMessageTagsRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("insufficient workspace permissions", err)+ }+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)+ if err != nil {+ return c.AbortNotFound("message not found")+ }+ tags, err := messages.ApplyTags(msg.Tags, req.Body.Add, req.Body.Remove)+ if err != nil {+ return c.AbortBadRequest(err.Error())+ }+ now := time.Now()+ msg.Tags = tags+ msg.UpdatedAt = &now+ if err := h.repo.UpdateFields(msg.ID, map[string]any{"tags": pq.StringArray(tags), "updated_at": now}); err != nil {+ return c.AbortInternalServerError("failed to update message")+ }+ hydrate(msg)+ h.publish(c, messages.EventUpdated, msg)+ return ok(c, msg)+}++// UpdatePriority sets a message's priority.+func (h *MessageHandler) UpdatePriority(c *okapi.Context, req *UpdateMessagePriorityRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("insufficient workspace permissions", err)+ }+ priority := models.MessagePriority(strings.ToLower(strings.TrimSpace(req.Body.Priority)))+ if !models.ValidPriority(priority) {+ return c.AbortBadRequest("priority must be one of: low, normal, high, urgent")+ }+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)+ if err != nil {+ return c.AbortNotFound("message not found")+ }+ now := time.Now()+ msg.Priority = priority+ msg.UpdatedAt = &now+ if err := h.repo.UpdateFields(msg.ID, map[string]any{"priority": priority, "updated_at": now}); err != nil {+ return c.AbortInternalServerError("failed to update message")+ }+ hydrate(msg)+ h.publish(c, messages.EventUpdated, msg)+ return ok(c, msg)+}++// Tags lists the tags in use on recent messages, most used first.+func (h *MessageHandler) Tags(c *okapi.Context) error {+ tags, err := h.repo.RecentTags(getScope(c), 5000, 100)+ if err != nil {+ return c.AbortInternalServerError("failed to list tags")+ }+ if tags == nil {+ tags = []repositories.TagCount{}+ }+ return ok(c, tags)+}+func (h *MessageHandler) MarkSpam(c *okapi.Context, req *MarkSpamRequest) error {if err := requireEdit(c); err != nil {return c.AbortForbidden("insufficient workspace permissions", err)@@ -531,7 +618,25 @@ func (h *MessageHandler) publish(c *okapi.Context, eventType string, msg *modelsmap[string]any{metaMessageID: msg.UUID, metaFormID: msg.FormID})}+// tagFilter turns a tag query parameter into a filter, nil when empty.+func tagFilter(raw string) ([]string, error) {+ if strings.TrimSpace(raw) == "" {+ return nil, nil+ }+ tag, err := messages.NormalizeTag(raw)+ if err != nil {+ return nil, err+ }+ return []string{tag}, nil+}+func hydrate(msg *models.Message) {+ if msg.Tags == nil {+ msg.Tags = pq.StringArray{}+ }+ if msg.Priority == "" {+ msg.Priority = models.MessagePriorityNormal+ }if msg.FieldsJSON != "" {var fields []models.MessageFieldif err := json.Unmarshal([]byte(msg.FieldsJSON), &fields); err == nil {diff --git a/internal/middlewares/message_scope_test.go b/internal/middlewares/message_scope_test.goindex d0eb218..77c749f 100644--- a/internal/middlewares/message_scope_test.go+++ b/internal/middlewares/message_scope_test.go@@ -36,6 +36,9 @@ func TestWorkspaceScopeForMessageRoutes(t *testing.T) {{http.MethodGet, "/api/v1/workspaces/current/messages/abc", models.ScopeRead},{http.MethodPost, "/api/v1/workspaces/current/messages/abc/reply", models.ScopeWrite},{http.MethodDelete, "/api/v1/workspaces/current/messages/abc", models.ScopeWrite},+ {http.MethodPut, "/api/v1/workspaces/current/messages/abc/tags", models.ScopeWrite},+ {http.MethodPut, "/api/v1/workspaces/current/messages/abc/priority", models.ScopeWrite},+ {http.MethodGet, "/api/v1/workspaces/current/message-tags", models.ScopeRead},{http.MethodGet, "/api/v1/workspaces/current/forms", models.ScopeAdmin},{http.MethodPost, "/api/v1/workspaces/current/forms", models.ScopeAdmin},diff --git a/internal/models/form.go b/internal/models/form.goindex 2cd48da..2fd6453 100644--- a/internal/models/form.go+++ b/internal/models/form.go@@ -43,6 +43,16 @@ const (NotifyModeOff NotifyMode = "off")+// FormMode decides what the dashboard makes of submissions. An inbox form's+// submissions are conversations to answer; a collect form's are responses to+// read as a table (surveys, signups, RSVPs). Both share ingest and storage.+type FormMode string++const (+ FormModeInbox FormMode = "inbox"+ FormModeCollect FormMode = "collect"+)+const (DefaultHoneypotField = "_gotcha"DefaultMaxBodyBytes = 65536@@ -58,6 +68,7 @@ type Form struct {Description string `json:"description"`PublicKey string `json:"public_key" gorm:"uniqueIndex;not null"`Status FormStatus `json:"status" gorm:"type:varchar(20);default:'active';index;not null"`+ Mode FormMode `json:"mode" gorm:"type:varchar(16);default:'inbox';not null"`AllowedOrigins pq.StringArray `json:"allowed_origins" gorm:"type:text[]"`StrictOrigin bool `json:"strict_origin" gorm:"default:false;not null"`@@ -126,6 +137,10 @@ func (f *Form) Closed(now time.Time) bool {return f.MaxResponses > 0 && f.MessageCount-f.SpamCount >= int64(f.MaxResponses)}+// IsCollect reports whether submissions are responses to read, not+// conversations: they stay out of the inbox and cannot be replied to.+func (f *Form) IsCollect() bool { return f != nil && f.Mode == FormModeCollect }+// HasSchema reports whether submissions are validated against Fields.func (f *Form) HasSchema() bool { return f != nil && len(f.Fields.Active()) > 0 }diff --git a/internal/models/message.go b/internal/models/message.goindex 39556d3..3d2ed9d 100644--- a/internal/models/message.go+++ b/internal/models/message.go@@ -45,6 +45,25 @@ const (MessageStateSpam MessageState = "spam")+// MessagePriority orders submissions for triage. Normal is the default.+type MessagePriority string++const (+ MessagePriorityLow MessagePriority = "low"+ MessagePriorityNormal MessagePriority = "normal"+ MessagePriorityHigh MessagePriority = "high"+ MessagePriorityUrgent MessagePriority = "urgent"+)++// ValidPriority reports whether p is one of the four priorities.+func ValidPriority(p MessagePriority) bool {+ switch p {+ case MessagePriorityLow, MessagePriorityNormal, MessagePriorityHigh, MessagePriorityUrgent:+ return true+ }+ return false+}+type MessageReplyKind stringconst (@@ -86,6 +105,10 @@ type Message struct {SpamScore float64 `json:"spam_score" gorm:"default:0;not null"`ScanReasons pq.StringArray `json:"scan_reasons" gorm:"type:text[]"`+ // Tags and Priority are set by operators (and later by routing rules).+ Tags pq.StringArray `json:"tags" gorm:"type:text[]"`+ Priority MessagePriority `json:"priority" gorm:"type:varchar(8);default:'normal';not null"`+ThreadToken string `json:"-" gorm:"uniqueIndex"`RootMessageID string `json:"-"`DedupHash string `json:"-" gorm:"index"`diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.goindex ca909fe..fca8143 100644--- a/internal/routes/message_routes.go+++ b/internal/routes/message_routes.go@@ -26,6 +26,7 @@ import ("github.com/goposta/posta/internal/handlers""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/messages"+ "github.com/goposta/posta/internal/storage/repositories""github.com/jkaninda/okapi")@@ -303,6 +304,41 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {okapi.DocPathParam("id", "string", "Message UUID"),},},+ {+ Method: http.MethodPut,+ Path: "/messages/{id}/tags",+ Handler: okapi.H(r.h.message.UpdateTags),+ Group: opsGroup,+ Summary: "Add or remove message tags",+ Description: "Tags are lowercased and deduplicated. A tag in both add and remove is removed.",+ Request: &handlers.UpdateMessageTagsRequest{},+ Response: &dto.Response[models.Message]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "string", "Message UUID"),+ okapi.DocResponse(400, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodPut,+ Path: "/messages/{id}/priority",+ Handler: okapi.H(r.h.message.UpdatePriority),+ Group: opsGroup,+ Summary: "Set message priority",+ Request: &handlers.UpdateMessagePriorityRequest{},+ Response: &dto.Response[models.Message]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "string", "Message UUID"),+ },+ },+ {+ Method: http.MethodGet,+ Path: "/message-tags",+ Handler: r.h.message.Tags,+ Group: opsGroup,+ Summary: "List message tags in use",+ Description: "Tags on the workspace's recent messages, most used first, for suggestions and filters.",+ Response: &dto.Response[[]repositories.TagCount]{},+ },{Method: http.MethodPost,Path: "/messages/{id}/spam",diff --git a/internal/services/messages/pii.go b/internal/services/messages/pii.gonew file mode 100644index 0000000..d491bfe--- /dev/null+++ b/internal/services/messages/pii.go@@ -0,0 +1,89 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package messages++import (+ "fmt"++ "github.com/goposta/posta/internal/models"+)++// HiddenValue stands in for a personal-data answer in notification emails.+// Members read the real value on the submission page.+const HiddenValue = "•••• (hidden, view in Posta)"++// PIIMask says which of a submission's values a notification email must+// hide: the answers to questions marked personal data, and the summary values+// (sender email, name, phone, subject, body) those questions fill. A form+// without a schema hides nothing.+type PIIMask struct {+ keys map[string]bool+ roles map[models.FieldRole]bool+}++// NewPIIMask reads the mask from a form schema. Archived questions count:+// older submissions still carry their answers.+func NewPIIMask(defs models.FieldDefs) PIIMask {+ m := PIIMask{keys: map[string]bool{}, roles: map[models.FieldRole]bool{}}+ for _, f := range defs {+ if !f.PII {+ continue+ }+ m.keys[f.Key] = true+ if f.Role != models.RoleNone {+ m.roles[f.Role] = true+ }+ }+ return m+}++// Key reports whether the answer submitted under key is hidden.+func (m PIIMask) Key(key string) bool { return m.keys[key] }++// Value returns v, or HiddenValue when the question filling role is personal+// data. An empty value stays empty, so nothing is shown as hidden that was+// never given.+func (m PIIMask) Value(role models.FieldRole, v string) string {+ if v == "" || !m.roles[role] {+ return v+ }+ return HiddenValue+}++// Sender labels who submitted, leaving out what is hidden. It returns "" when+// neither a name nor an email was given.+func (m PIIMask) Sender(name, email string) string {+ nameHidden := name != "" && m.roles[models.RoleSenderName]+ emailHidden := email != "" && m.roles[models.RoleSenderEmail]+ switch {+ case name == "" && email == "":+ return ""+ case (nameHidden || name == "") && (emailHidden || email == ""):+ return HiddenValue+ case emailHidden:+ return name + " (email hidden)"+ case nameHidden || name == "":+ return email+ case email == "":+ return name+ default:+ return fmt.Sprintf("%s <%s>", name, email)+ }+}diff --git a/internal/services/messages/pii_test.go b/internal/services/messages/pii_test.gonew file mode 100644index 0000000..2e292a3--- /dev/null+++ b/internal/services/messages/pii_test.go@@ -0,0 +1,75 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package messages++import (+ "testing"++ "github.com/goposta/posta/internal/models"+)++func TestPIIMask(t *testing.T) {+ mask := NewPIIMask(models.FieldDefs{+ {Key: "email", Type: models.FieldEmail, Role: models.RoleSenderEmail, PII: true},+ {Key: "name", Type: models.FieldText, Role: models.RoleSenderName},+ {Key: "ssn", Type: models.FieldText, PII: true, Archived: true},+ {Key: "dept", Type: models.FieldText},+ })++ if !mask.Key("email") || !mask.Key("ssn") || mask.Key("dept") || mask.Key("name") {+ t.Error("Key does not follow the pii flags (archived questions included)")+ }+ if got := mask.Value(models.RoleSenderEmail, "[email protected]"); got != HiddenValue {+ t.Errorf("hidden role value = %q", got)+ }+ if got := mask.Value(models.RoleSenderEmail, ""); got != "" {+ t.Errorf("an empty value became %q", got)+ }+ if got := mask.Value(models.RoleSenderName, "Ada"); got != "Ada" {+ t.Errorf("a visible role value became %q", got)+ }++ cases := []struct{ name, email, want string }{+ {"Ada", "[email protected]", "Ada (email hidden)"},+ {"", "[email protected]", HiddenValue},+ {"Ada", "", "Ada"},+ {"", "", ""},+ }+ for _, c := range cases {+ if got := mask.Sender(c.name, c.email); got != c.want {+ t.Errorf("Sender(%q, %q) = %q, want %q", c.name, c.email, got, c.want)+ }+ }++ none := NewPIIMask(nil)+ if got := none.Sender("Ada", "[email protected]"); got != "Ada <[email protected]>" {+ t.Errorf("schemaless Sender = %q", got)+ }+ both := NewPIIMask(models.FieldDefs{+ {Key: "e", Role: models.RoleSenderEmail, PII: true},+ {Key: "n", Role: models.RoleSenderName, PII: true},+ })+ if got := both.Sender("Ada", "[email protected]"); got != HiddenValue {+ t.Errorf("all-hidden Sender = %q", got)+ }+ if got := both.Sender("", "[email protected]"); got != HiddenValue {+ t.Errorf("hidden email alone = %q", got)+ }+}diff --git a/internal/services/messages/tags.go b/internal/services/messages/tags.gonew file mode 100644index 0000000..9bae77e--- /dev/null+++ b/internal/services/messages/tags.go@@ -0,0 +1,89 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package messages++import (+ "fmt"+ "strings"+ "unicode"+ "unicode/utf8"+)++const (+ // MaxTags is how many tags one message may carry.+ MaxTags = 20+ // MaxTagLen is the longest tag, in characters.+ MaxTagLen = 32+)++// NormalizeTag lowercases a tag and collapses its whitespace, so "VIP " and+// "vip" are one tag. It rejects empty tags, control characters, and commas,+// which would split the tag in a CSV export.+func NormalizeTag(raw string) (string, error) {+ tag := strings.ToLower(strings.Join(strings.Fields(raw), " "))+ if tag == "" {+ return "", fmt.Errorf("a tag cannot be empty")+ }+ if utf8.RuneCountInString(tag) > MaxTagLen {+ return "", fmt.Errorf("tag %q is longer than %d characters", tag, MaxTagLen)+ }+ for _, r := range tag {+ if unicode.IsControl(r) || r == ',' || r == ';' {+ return "", fmt.Errorf("tag %q contains a character tags cannot use", tag)+ }+ }+ return tag, nil+}++// ApplyTags returns current with add appended and remove taken out, in a+// stable order: existing tags keep their place, new ones follow in the order+// given. Removing wins over adding the same tag.+func ApplyTags(current, add, remove []string) ([]string, error) {+ drop := map[string]bool{}+ for _, raw := range remove {+ tag, err := NormalizeTag(raw)+ if err != nil {+ return nil, err+ }+ drop[tag] = true+ }+ seen := map[string]bool{}+ out := make([]string, 0, len(current)+len(add))+ keep := func(tag string) {+ if !drop[tag] && !seen[tag] {+ seen[tag] = true+ out = append(out, tag)+ }+ }+ for _, tag := range current {+ keep(tag)+ }+ for _, raw := range add {+ tag, err := NormalizeTag(raw)+ if err != nil {+ return nil, err+ }+ keep(tag)+ }+ if len(out) > MaxTags {+ return nil, fmt.Errorf("a message can carry at most %d tags", MaxTags)+ }+ return out, nil+}diff --git a/internal/services/messages/tags_test.go b/internal/services/messages/tags_test.gonew file mode 100644index 0000000..3e0a990--- /dev/null+++ b/internal/services/messages/tags_test.go@@ -0,0 +1,71 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package messages++import (+ "fmt"+ "reflect"+ "strings"+ "testing"+)++func TestNormalizeTag(t *testing.T) {+ cases := map[string]string{+ "VIP": "vip",+ " follow up ": "follow up",+ "Ünïcode": "ünïcode",+ }+ for in, want := range cases {+ got, err := NormalizeTag(in)+ if err != nil || got != want {+ t.Errorf("NormalizeTag(%q) = %q, %v; want %q", in, got, err, want)+ }+ }+ for _, bad := range []string{"", " ", "a,b", "a;b", "tab\x00", strings.Repeat("x", MaxTagLen+1)} {+ if _, err := NormalizeTag(bad); err == nil {+ t.Errorf("NormalizeTag(%q) accepted", bad)+ }+ }+}++func TestApplyTags(t *testing.T) {+ got, err := ApplyTags([]string{"vip", "lead"}, []string{"Hot", "VIP", "later"}, []string{"lead", "LATER"})+ if err != nil {+ t.Fatal(err)+ }+ if want := []string{"vip", "hot"}; !reflect.DeepEqual(got, want) {+ t.Errorf("got %v, want %v", got, want)+ }++ if got, _ := ApplyTags(nil, nil, []string{"absent"}); len(got) != 0 {+ t.Errorf("removing from nothing gave %v", got)+ }+ if _, err := ApplyTags(nil, []string{"ok", ","}, nil); err == nil {+ t.Error("a bad tag in add was accepted")+ }++ many := make([]string, MaxTags+1)+ for i := range many {+ many[i] = fmt.Sprintf("t%d", i)+ }+ if _, err := ApplyTags(nil, many, nil); err == nil {+ t.Errorf("%d tags accepted", len(many))+ }+}diff --git a/internal/services/notification/message_templates_test.go b/internal/services/notification/message_templates_test.goindex d846467..e21fea2 100644--- a/internal/services/notification/message_templates_test.go+++ b/internal/services/notification/message_templates_test.go@@ -154,3 +154,29 @@ func TestNewMessageTemplateOmitsPhoneWhenAbsent(t *testing.T) {t.Fatal("no phone row should render when no phone was submitted")}}++func TestCollectFormTemplatesSayResponse(t *testing.T) {+ out := renderedText(t, TemplateNewMessage, map[string]any{+ "UserName": "Ada", "FormName": "Survey", "Collect": true,+ "Fields": []models.MessageField{{Key: "From", Value: "•••• (hidden, view in Posta)"}},+ "MessageURL": "https://posta.test/messages/abc",+ })+ for _, want := range []string{"New response on Survey", "Open response", "hidden, view in Posta"} {+ if !strings.Contains(out, want) {+ t.Fatalf("collect notification is missing %q", want)+ }+ }+ if strings.Contains(out, "Open and reply") || strings.Contains(out, "before replying") {+ t.Fatal("a collect-mode notification must not offer to reply")+ }++ digest := renderedText(t, TemplateMessageDigest, map[string]any{+ "UserName": "Ada", "Period": "Daily", "FormName": "Survey", "Collect": true,+ "Total": 2, "InboxURL": "https://posta.test/forms/1?tab=responses",+ })+ for _, want := range []string{"Daily response digest", "2</strong> new responses", "Open responses"} {+ if !strings.Contains(digest, want) {+ t.Fatalf("collect digest is missing %q", want)+ }+ }+}diff --git a/internal/services/notification/templates/message_digest.tmpl b/internal/services/notification/templates/message_digest.tmplindex ba7ecc4..965a7a9 100644--- a/internal/services/notification/templates/message_digest.tmpl+++ b/internal/services/notification/templates/message_digest.tmpl@@ -1,8 +1,8 @@{{ define "content" }}-<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">{{ .Period }} message digest</h2>+<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">{{ .Period }} {{ if .Collect }}response{{ else }}message{{ end }} digest</h2><p style="margin: 0 0 16px;">Hi {{ .UserName }},</p>-<p style="margin: 0 0 16px;">{{ if .WorkspaceName }}<strong>{{ .WorkspaceName }}</strong> received{{ else }}You received{{ end }} <strong>{{ .Total }}</strong> new message{{ if ne .Total 1 }}s{{ end }} on <strong>{{ .FormName }}</strong>.</p>+<p style="margin: 0 0 16px;">{{ if .WorkspaceName }}<strong>{{ .WorkspaceName }}</strong> received{{ else }}You received{{ end }} <strong>{{ .Total }}</strong> new {{ if .Collect }}response{{ else }}message{{ end }}{{ if ne .Total 1 }}s{{ end }} on <strong>{{ .FormName }}</strong>.</p><table class="stats-table" role="presentation" style="width: 100%; border-collapse: separate; border-spacing: 0; margin: 20px 0; border: 1px solid #eceef2; border-radius: 10px; overflow: hidden;"><tr>@@ -20,7 +20,7 @@{{ if .InboxURL }}<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin: 28px auto;"><tr><td align="center" bgcolor="#7c3aed" style="border-radius: 8px;">- <a href="{{ .InboxURL }}" class="btn" style="display: inline-block; padding: 13px 30px; background-color: #7c3aed; color: #ffffff !important; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 15px; line-height: 1;">Open inbox</a>+ <a href="{{ .InboxURL }}" class="btn" style="display: inline-block; padding: 13px 30px; background-color: #7c3aed; color: #ffffff !important; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 15px; line-height: 1;">{{ if .Collect }}Open responses{{ else }}Open inbox{{ end }}</a></td></tr></table>{{ end }}diff --git a/internal/services/notification/templates/new_message.tmpl b/internal/services/notification/templates/new_message.tmplindex 405ebac..2844f64 100644--- a/internal/services/notification/templates/new_message.tmpl+++ b/internal/services/notification/templates/new_message.tmpl@@ -1,5 +1,5 @@{{ define "content" }}-<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">{{ if .Reply }}New reply on {{ .FormName }}{{ else }}New message on {{ .FormName }}{{ end }}</h2>+<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">{{ if .Reply }}New reply on {{ .FormName }}{{ else if .Collect }}New response on {{ .FormName }}{{ else }}New message on {{ .FormName }}{{ end }}</h2><p style="margin: 0 0 16px;">Hi {{ .UserName }},</p>{{ if .Reply }}@@ -10,12 +10,12 @@</div>{{ end }}{{ else }}-<p style="margin: 0 0 16px;">{{ if .WorkspaceName }}<strong>{{ .WorkspaceName }}</strong> received{{ else }}You received{{ end }} a new message through the <strong>{{ .FormName }}</strong> form.</p>+<p style="margin: 0 0 16px;">{{ if .WorkspaceName }}<strong>{{ .WorkspaceName }}</strong> received{{ else }}You received{{ end }} a new {{ if .Collect }}response{{ else }}message{{ end }} through the <strong>{{ .FormName }}</strong> form.</p>{{ end }}{{ if .Flagged }}<div class="alert-box alert-warning" style="padding: 14px 16px; border-radius: 10px; margin: 20px 0; font-size: 14px; line-height: 1.55; background-color: #fffbeb; border: 1px solid #fde68a; color: #92400e;">- This message was flagged by spam scanning (score {{ .SpamScore }}). Review it before replying.+ This {{ if .Collect }}response{{ else }}message{{ end }} was flagged by spam scanning (score {{ .SpamScore }}).{{ if not .Collect }} Review it before replying.{{ end }}</div>{{ end }}@@ -44,7 +44,7 @@{{ if .MessageURL }}<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin: 28px auto;"><tr><td align="center" bgcolor="#7c3aed" style="border-radius: 8px;">- <a href="{{ .MessageURL }}" class="btn" style="display: inline-block; padding: 13px 30px; background-color: #7c3aed; color: #ffffff !important; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 15px; line-height: 1;">Open and reply</a>+ <a href="{{ .MessageURL }}" class="btn" style="display: inline-block; padding: 13px 30px; background-color: #7c3aed; color: #ffffff !important; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 15px; line-height: 1;">{{ if .Collect }}Open response{{ else }}Open and reply{{ end }}</a></td></tr></table>{{ end }}diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.goindex 44b6bc4..8f36923 100644--- a/internal/storage/migration/constraints.go+++ b/internal/storage/migration/constraints.go@@ -123,6 +123,12 @@ func runConstraints(db *gorm.DB) {EXCEPTION WHEN others THEN NULL;END $$`)+ // Tag filters are array containment (tags @> '{vip}').+ db.Exec(`DO $$ BEGIN+ CREATE INDEX IF NOT EXISTS idx_messages_tags ON messages USING GIN (tags) WHERE tags IS NOT NULL;+ EXCEPTION WHEN others THEN NULL;+ END $$`)+// One thread reply per inbound email, so a retried parse task cannot attach// the same answer twice. Its own block: a failure must not skip the others.db.Exec(`DO $$ BEGINdiff --git a/internal/storage/repositories/message_repo.go b/internal/storage/repositories/message_repo.goindex 9c0e5b6..bea3793 100644--- a/internal/storage/repositories/message_repo.go+++ b/internal/storage/repositories/message_repo.go@@ -25,6 +25,7 @@ import ("time""github.com/goposta/posta/internal/models"+ "github.com/lib/pq""gorm.io/gorm""gorm.io/gorm/clause")@@ -39,6 +40,13 @@ type MessageFilterQuery struct {From *time.TimeTo *time.Time+ // Tags keeps messages carrying every listed tag; Priority one priority.+ Tags []string+ Priority string+ // InboxOnly leaves out collect-mode forms, whose responses are read as a+ // table on the form rather than worked as conversations.+ InboxOnly bool+// SubmissionsOnly leaves out quarantined and rejected messages unless// Status asks for one: spam is not a response.SubmissionsOnly bool@@ -83,6 +91,15 @@ func applyMessageFilter(q *gorm.DB, scope ResourceScope, f MessageFilterQuery) *if f.Unread {q = q.Where("read_at IS NULL")}+ if len(f.Tags) > 0 {+ q = q.Where("tags @> ?", pq.StringArray(f.Tags))+ }+ if f.Priority != "" {+ q = q.Where("priority = ?", f.Priority)+ }+ if f.InboxOnly {+ q = q.Where(notCollectForm)+ }if f.Query != "" {like := "%" + strings.ToLower(f.Query) + "%"q = q.Where(@@ -292,16 +309,40 @@ func (r *MessageRepository) Delete(id uint) error {return r.db.Delete(&models.Message{}, id).Error}+// notCollectForm keeps messages whose form is in inbox mode.+const notCollectForm = "NOT EXISTS (SELECT 1 FROM forms WHERE forms.id = messages.form_id AND forms.mode = 'collect')"++// CountByScope counts the inbox: total and unread leave out collect-mode+// forms, as the inbox list does; spam counts every form.func (r *MessageRepository) CountByScope(scope ResourceScope) (total, unread, spam int64) {ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).- Where("status <> ?", models.MessageStatusRejected).Count(&total)+ Where("status <> ?", models.MessageStatusRejected).Where(notCollectForm).Count(&total)ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).- Where("read_at IS NULL AND status IN ?", []models.MessageStatus{models.MessageStatusReceived, models.MessageStatusFlagged}).Count(&unread)+ Where("read_at IS NULL AND status IN ?", []models.MessageStatus{models.MessageStatusReceived, models.MessageStatusFlagged}).+ Where(notCollectForm).Count(&unread)ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).Where("status IN ?", []models.MessageStatus{models.MessageStatusQuarantined, models.MessageStatusRejected}).Count(&spam)return}+// TagCount is one tag in use and how many messages carry it.+type TagCount struct {+ Tag string `json:"tag"`+ Count int64 `json:"count"`+}++// RecentTags lists the tags on the newest tagged messages, most used first,+// for suggestions. It reads a bounded window so a large workspace stays cheap.+func (r *MessageRepository) RecentTags(scope ResourceScope, window, limit int) ([]TagCount, error) {+ recent := ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).+ Select("tags").Where("tags IS NOT NULL AND cardinality(tags) > 0").+ Order("id DESC").Limit(window)+ var out []TagCount+ err := r.db.Raw("SELECT t.tag, COUNT(*) AS count FROM (?) AS recent, unnest(recent.tags) AS t(tag) GROUP BY t.tag ORDER BY count DESC, t.tag ASC LIMIT ?",+ recent, limit).Scan(&out).Error+ return out, err+}+func (r *MessageRepository) CountBySenderSince(formID uint, email string, since time.Time) int64 {var count int64r.db.Model(&models.Message{}).diff --git a/internal/worker/message_handler.go b/internal/worker/message_handler.goindex aea2a1b..694a686 100644--- a/internal/worker/message_handler.go+++ b/internal/worker/message_handler.go@@ -242,16 +242,28 @@ func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form) e_ = json.Unmarshal([]byte(msg.FieldsJSON), &fields)}- subject := fmt.Sprintf("New message on %s", form.Name)+ noun := "message"+ if form.IsCollect() {+ noun = "response"+ }+ subject := fmt.Sprintf("New %s on %s", noun, form.Name)if msg.Status == models.MessageStatusFlagged {- subject = fmt.Sprintf("Flagged message on %s", form.Name)+ subject = fmt.Sprintf("Flagged %s on %s", noun, form.Name)}+ // Answers to personal-data questions stay out of email: inboxes are+ // forwarded, synced and searched far beyond the workspace.+ mask := messages.NewPIIMask(form.Fields)+ phone := msg.SenderPhone+ if mask.Value(models.RoleSenderPhone, phone) != phone {+ phone = "" // the Phone row in Fields shows it as hidden+ }data := map[string]any{"FormName": form.Name,- "SenderPhone": msg.SenderPhone,- "Fields": notifiableFields(msg, fields),- "Body": msg.Body,+ "Collect": form.IsCollect(),+ "SenderPhone": phone,+ "Fields": notifiableFields(msg, fields, mask),+ "Body": mask.Value(models.RoleBody, msg.Body),"Flagged": msg.Status == models.MessageStatusFlagged,"SpamScore": fmt.Sprintf("%.1f", msg.SpamScore),"MessageURL": h.messageURL(msg.UUID),@@ -309,14 +321,16 @@ var summarizedFieldKeys = func() map[string]bool {return set}()-func notifiableFields(msg *models.Message, fields []models.MessageField) []models.MessageField {- out := []models.MessageField{- {Key: "From", Value: displaySender(msg)},+func notifiableFields(msg *models.Message, fields []models.MessageField, mask messages.PIIMask) []models.MessageField {+ from := mask.Sender(msg.SenderName, msg.SenderEmail)+ if from == "" {+ from = "unknown sender"}+ out := []models.MessageField{{Key: "From", Value: from}}if msg.SenderPhone != "" {- out = append(out, models.MessageField{Key: "Phone", Value: msg.SenderPhone})+ out = append(out, models.MessageField{Key: "Phone", Value: mask.Value(models.RoleSenderPhone, msg.SenderPhone)})}- out = append(out, models.MessageField{Key: "Subject", Value: msg.Subject})+ out = append(out, models.MessageField{Key: "Subject", Value: mask.Value(models.RoleSubject, msg.Subject)})for _, f := range fields {if summarizedFieldKeys[strings.ToLower(strings.TrimSpace(f.Key))] {@@ -325,24 +339,14 @@ func notifiableFields(msg *models.Message, fields []models.MessageField) []modelif len(out) >= 12 {break}+ if mask.Key(f.Key) && f.Value != "" {+ f.Value = messages.HiddenValue+ }out = append(out, f)}return out}-func displaySender(msg *models.Message) string {- switch {- case msg.SenderName != "" && msg.SenderEmail != "":- return fmt.Sprintf("%s <%s>", msg.SenderName, msg.SenderEmail)- case msg.SenderEmail != "":- return msg.SenderEmail- case msg.SenderName != "":- return msg.SenderName- default:- return "unknown sender"- }-}-func cloneData(in map[string]any) map[string]any {out := make(map[string]any, len(in))for k, v := range in {@@ -444,7 +448,7 @@ func (h *MessageProcessHandler) notifyReply(msg *models.Message, form *models.Fo"Reply": true,"SenderMismatch": reply.SenderMismatch,"Fields": []models.MessageField{- {Key: "From", Value: reply.FromAddr},+ {Key: "From", Value: messages.NewPIIMask(form.Fields).Value(models.RoleSenderEmail, reply.FromAddr)},{Key: "Subject", Value: reply.Subject},},"Body": reply.TextBody,diff --git a/internal/worker/message_handler_test.go b/internal/worker/message_handler_test.goindex 5f028e7..8f1913f 100644--- a/internal/worker/message_handler_test.go+++ b/internal/worker/message_handler_test.go@@ -20,9 +20,11 @@package workerimport (+ "strings""testing""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/messages")func TestShouldNotify(t *testing.T) {@@ -76,7 +78,7 @@ func TestShouldNotify(t *testing.T) {}}-func TestDisplaySender(t *testing.T) {+func TestNotifiableFieldsSender(t *testing.T) {cases := []struct {msg models.Messagewant string@@ -88,12 +90,43 @@ func TestDisplaySender(t *testing.T) {}for _, tc := range cases {msg := tc.msg- if got := displaySender(&msg); got != tc.want {- t.Fatalf("displaySender(%+v) = %q, want %q", tc.msg, got, tc.want)+ if got := notifiableFields(&msg, nil, messages.NewPIIMask(nil))[0].Value; got != tc.want {+ t.Fatalf("From for %+v = %q, want %q", tc.msg, got, tc.want)}}}+// Answers to personal-data questions never reach a notification email, and+// neither do the summary values they fill.+func TestNotifiableFieldsHidesPII(t *testing.T) {+ mask := messages.NewPIIMask(models.FieldDefs{+ {Key: "work_email", Type: models.FieldEmail, Role: models.RoleSenderEmail, PII: true},+ {Key: "mobile", Type: models.FieldPhone, Role: models.RoleSenderPhone, PII: true},+ {Key: "salary", Type: models.FieldNumber, PII: true},+ {Key: "dept", Type: models.FieldText},+ })+ msg := &models.Message{SenderName: "Ada", SenderEmail: "[email protected]", SenderPhone: "+1 555 010 9999", Subject: "Hi"}+ fields := []models.MessageField{+ {Key: "work_email", Value: "[email protected]"},+ {Key: "mobile", Value: "+1 555 010 9999"},+ {Key: "salary", Value: "90000"},+ {Key: "dept", Value: "sales"},+ }+ got := map[string]string{}+ for _, f := range notifiableFields(msg, fields, mask) {+ got[f.Key] = f.Value+ if strings.Contains(f.Value, "[email protected]") || strings.Contains(f.Value, "555") || f.Value == "90000" {+ t.Errorf("%s leaks %q", f.Key, f.Value)+ }+ }+ if got["From"] != "Ada (email hidden)" || got["salary"] != messages.HiddenValue || got["Phone"] != messages.HiddenValue {+ t.Errorf("unexpected masking: %+v", got)+ }+ if got["dept"] != "sales" || got["Subject"] != "Hi" {+ t.Errorf("visible answers were hidden: %+v", got)+ }+}+func TestNotifiableFieldsDropsBodyAndCaps(t *testing.T) {msg := &models.Message{SenderEmail: "[email protected]", Subject: "Hi"}fields := []models.MessageField{{Key: "message", Value: "long body"}, {Key: "company", Value: "Acme"}}@@ -101,7 +134,7 @@ func TestNotifiableFieldsDropsBodyAndCaps(t *testing.T) {fields = append(fields, models.MessageField{Key: "extra", Value: "x"})}- got := notifiableFields(msg, fields)+ got := notifiableFields(msg, fields, messages.NewPIIMask(nil))if len(got) > 12 {t.Fatalf("got %d fields, want at most 12", len(got))}@@ -146,7 +179,7 @@ func TestNotifiableFieldsIncludesPhoneAndDropsSummarizedAliases(t *testing.T) {{Key: "company", Value: "Acme"},}- got := notifiableFields(msg, fields)+ got := notifiableFields(msg, fields, messages.NewPIIMask(nil))keys := make([]string, 0, len(got))for _, f := range got {@@ -168,7 +201,7 @@ func TestNotifiableFieldsIncludesPhoneAndDropsSummarizedAliases(t *testing.T) {func TestNotifiableFieldsOmitsPhoneRowWhenAbsent(t *testing.T) {msg := &models.Message{SenderEmail: "[email protected]", Subject: "Hi"}- for _, f := range notifiableFields(msg, nil) {+ for _, f := range notifiableFields(msg, nil, messages.NewPIIMask(nil)) {if f.Key == "Phone" {t.Fatal("a Phone row should not appear when no phone was submitted")}diff --git a/web/src/api/messages.ts b/web/src/api/messages.tsindex 1f0a366..17fe96d 100644--- a/web/src/api/messages.ts+++ b/web/src/api/messages.ts@@ -5,13 +5,16 @@ import type {Form,FormAppearance,FormField,+ FormMode,FormSnippet,Message,MessageFilterRule,+ MessagePriority,MessageReply,MessageStats,SubmissionQuery,SubmissionSummary,+ TagCount,} from './types'const WORKSPACE_KEY = 'posta_workspace_id'@@ -26,6 +29,7 @@ export interface FormPayload {slug?: stringdescription?: stringstatus?: string+ mode?: FormModeallowed_origins?: string[]strict_origin?: booleanredirect_url?: string@@ -67,6 +71,8 @@ export interface MessageListParams {q?: stringafter?: stringbefore?: string+ tag?: string+ priority?: string}export interface FilterPayload {@@ -147,6 +153,15 @@ export const messagesApi = {user_id: userId,})},+ updateTags(uuid: string, payload: { add?: string[]; remove?: string[] }) {+ return api.put<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/tags`, payload)+ },+ setPriority(uuid: string, priority: MessagePriority) {+ return api.put<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/priority`, { priority })+ },+ tags() {+ return api.get<ApiResponse<TagCount[]>>('/workspaces/current/message-tags')+ },markSpam(uuid: string, payload: { create_filter?: boolean; pattern?: string; kind?: string } = {}) {return api.post<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/spam`, payload)},@@ -195,7 +210,7 @@ export const messageFiltersApi = {// equality, field.<key>[gte]=n and field.<key>[lte]=n for ranges.function submissionParams(formId: number, query: SubmissionQuery): Record<string, string | number> {const params: Record<string, string | number> = { form_id: formId }- for (const k of ['page', 'size', 'status', 'q', 'after', 'before'] as const) {+ for (const k of ['page', 'size', 'status', 'q', 'after', 'before', 'tag', 'priority'] as const) {const v = query[k]if (v !== undefined && v !== '') params[k] = v}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex ad88443..006923e 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -1231,6 +1231,9 @@ export interface CampaignAnalyticsData {}export type FormStatus = 'active' | 'paused' | 'archived'+/** inbox: submissions are conversations. collect: responses read as a table. */+export type FormMode = 'inbox' | 'collect'+export type MessagePriority = 'low' | 'normal' | 'high' | 'urgent'export type NotifyMode = 'immediate' | 'hourly' | 'daily' | 'off'export type MessageStatus = 'received' | 'flagged' | 'quarantined' | 'rejected'export type MessageState = 'new' | 'open' | 'replied' | 'closed' | 'spam'@@ -1247,6 +1250,7 @@ export interface Form {description: stringpublic_key: stringstatus: FormStatus+ mode: FormModeallowed_origins: string[]strict_origin: booleanredirect_url: string@@ -1362,6 +1366,8 @@ export interface Message {state: MessageStatespam_score: numberscan_reasons: string[] | null+ tags: string[]+ priority: MessagePrioritynotified_at?: string | nullassigned_to_id?: number | nullread_at?: string | null@@ -1453,5 +1459,12 @@ export interface SubmissionQuery {q?: stringafter?: stringbefore?: string+ tag?: string+ priority?: stringfilters?: SubmissionFieldFilter[]}++export interface TagCount {+ tag: string+ count: number+}diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vueindex a440cfd..7449a97 100644--- a/web/src/views/forms/FormDetail.vue+++ b/web/src/views/forms/FormDetail.vue@@ -28,7 +28,9 @@ const TABS = [{ key: "embed", label: "Share & embed" },] as const;type Tab = (typeof TABS)[number]["key"];-const tab = ref<Tab>("questions");+// ?tab=responses opens a tab directly (digest emails and the inbox link here).+const queryTab = TABS.find((t) => t.key === route.query.tab)?.key;+const tab = ref<Tab>(queryTab ?? "questions");const originsText = ref("");// close_at is edited in the browser's local time and stored as UTC.@@ -66,6 +68,8 @@ async function load() {originsText.value = (formRes.data.data.allowed_origins || []).join(", ");syncResponseFields(formRes.data.data);notifyText.value = (formRes.data.data.notify_emails || []).join(", ");+ // A collect form is mostly read, so it opens on its responses.+ if (!queryTab && formRes.data.data.mode === "collect") tab.value = "responses";} catch (e: any) {loadFailed.value = true;notify.error(apiMessage(e, "Failed to load form"));@@ -89,6 +93,7 @@ async function save() {name: form.value.name,description: form.value.description,status: form.value.status,+ mode: form.value.mode,allowed_origins: splitList(originsText.value),strict_origin: form.value.strict_origin,redirect_url: form.value.redirect_url,@@ -229,7 +234,7 @@ onMounted(load);<h1>{{ form?.name || "Form" }}</h1><div style="display: flex; gap: 8px"><router-link- v-if="form"+ v-if="form && form.mode !== 'collect'":to="`/messages?form_id=${form.id}`"class="btn btn-secondary">View messages</router-link>@@ -267,7 +272,7 @@ onMounted(load);<FormFields v-show="tab === 'questions'" :form="form" @saved="onFieldsSaved" /><!-- Mounted on demand: it loads responses, and has no edits to keep. -->- <FormResponses v-if="tab === 'responses'" :form="form" />+ <FormResponses v-if="tab === 'responses'" :form="form" :share-url="snippet?.share_url" /><div v-show="tab === 'setup'" class="card" style="margin-bottom: 20px"><div class="card-header"><h2>Setup</h2></div>@@ -280,6 +285,29 @@ onMounted(load);<label class="form-label">Description</label><input v-model="form.description" class="form-input" /></div>+ <fieldset class="form-group mode-choice">+ <legend class="form-label">What submissions are</legend>+ <label class="mode-option" :class="{ selected: form.mode !== 'collect' }">+ <input v-model="form.mode" type="radio" value="inbox" />+ <span>+ <strong>Messages to answer</strong>+ <small class="muted">+ Contact and support forms. Submissions arrive in the inbox, where you reply,+ assign and close them.+ </small>+ </span>+ </label>+ <label class="mode-option" :class="{ selected: form.mode === 'collect' }">+ <input v-model="form.mode" type="radio" value="collect" />+ <span>+ <strong>Responses to collect</strong>+ <small class="muted">+ Surveys, signups and RSVPs. Responses stay out of the inbox and are read on the+ Responses tab, as a summary or a table.+ </small>+ </span>+ </label>+ </fieldset><div class="form-group"><label class="form-label">Status</label><select v-model="form.status" class="form-select">@@ -326,12 +354,12 @@ onMounted(load);Accept file attachments</label></div>- <div class="form-group">+ <div v-if="form.mode !== 'collect'" class="form-group"><label class="form-label">Reply sender</label><input v-model="form.reply_from" class="form-input" placeholder="[email protected]" /><small class="muted">Must be on a verified domain in this workspace.</small></div>- <div class="form-group">+ <div v-if="form.mode !== 'collect'" class="form-group"><label class="form-label">Reply sender name</label><input v-model="form.reply_from_name" class="form-input" placeholder="Acme Support" /></div>@@ -607,3 +635,44 @@ onMounted(load);</template></div></template>++<style scoped>+.mode-choice {+ border: 0;+ padding: 0;+ margin-inline: 0;+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: 10px;+}++.mode-choice legend {+ padding: 0;+ margin-bottom: 6px;+}++.mode-option {+ display: flex;+ gap: 10px;+ align-items: flex-start;+ padding: 12px 14px;+ border: 1px solid var(--border-primary);+ border-radius: 8px;+ cursor: pointer;+}++.mode-option.selected {+ border-color: var(--primary-500);+ background: var(--primary-50);+}++.mode-option input {+ margin-top: 3px;+}++.mode-option span {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+</style>diff --git a/web/src/views/forms/FormResponses.vue b/web/src/views/forms/FormResponses.vueindex 3c6123e..970cf03 100644--- a/web/src/views/forms/FormResponses.vue+++ b/web/src/views/forms/FormResponses.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { computed, onMounted, ref, watch } from "vue";-import { formSubmissionsApi } from "../../api/messages";+import { formSubmissionsApi, messagesApi } from "../../api/messages";import { apiMessage } from "../../composables/apiError";import { useNotificationStore } from "../../stores/notification";import Pagination from "../../components/Pagination.vue";@@ -18,7 +18,7 @@ import type {// A form's responses: a per-question summary and a table, over one set of// filters, with CSV and JSON export of exactly what is shown.-const props = defineProps<{ form: Form }>();+const props = defineProps<{ form: Form; shareUrl?: string }>();const notify = useNotificationStore();const view = ref<"summary" | "table">("summary");@@ -33,6 +33,9 @@ const search = ref("");const after = ref("");const before = ref("");const fieldFilters = ref<SubmissionFieldFilter[]>([]);+const tag = ref("");+const priority = ref("");+const knownTags = ref<string[]>([]);// Archived and hidden questions can still be filtered on: old answers keep them.const questions = computed(() => props.form.fields || []);@@ -50,6 +53,8 @@ function query(): SubmissionQuery {return {status: status.value,q: search.value.trim(),+ tag: tag.value,+ priority: priority.value,// Dates are picked in local time; the day bounds are inclusive.after: after.value ? new Date(`${after.value}T00:00:00`).toISOString() : "",before: before.value ? new Date(`${before.value}T23:59:59`).toISOString() : "",@@ -80,7 +85,7 @@ watch(search, () => {clearTimeout(searchTimer);searchTimer = setTimeout(reload, 300);});-watch([status, after, before, fieldFilters], reload, { deep: true });+watch([status, after, before, tag, priority, fieldFilters], reload, { deep: true });function reload() {page.value = 0;@@ -121,11 +126,22 @@ function clearFilters() {search.value = "";after.value = "";before.value = "";+ tag.value = "";+ priority.value = "";fieldFilters.value = [];}const filtered = computed(- () => !!(status.value || search.value.trim() || after.value || before.value || fieldFilters.value.some((f) => f.value !== "")),+ () =>+ !!(+ status.value ||+ search.value.trim() ||+ after.value ||+ before.value ||+ tag.value ||+ priority.value ||+ fieldFilters.value.some((f) => f.value !== "")+ ),);function exportUrl(format: "csv" | "json") {@@ -177,7 +193,16 @@ function scaleTop(s: SubmissionFieldSummary) {return opts.length ? opts[opts.length - 1].value : "";}-onMounted(load);+const PRIORITY_LABELS: Record<string, string> = { low: "Low", high: "High", urgent: "Urgent" };++onMounted(async () => {+ load();+ try {+ knownTags.value = (await messagesApi.tags()).data.data.map((t) => t.tag);+ } catch {+ /* the tag filter just stays hidden */+ }+});</script><template>@@ -208,6 +233,17 @@ onMounted(load);<option value="flagged">Flagged only</option><option value="quarantined">Quarantined (spam)</option></select>+ <select v-model="priority" class="form-select rf-status" aria-label="Priority">+ <option value="">Any priority</option>+ <option value="urgent">Urgent</option>+ <option value="high">High</option>+ <option value="normal">Normal</option>+ <option value="low">Low</option>+ </select>+ <select v-if="knownTags.length" v-model="tag" class="form-select rf-status" aria-label="Tag">+ <option value="">Any tag</option>+ <option v-for="t in knownTags" :key="t" :value="t">{{ t }}</option>+ </select><div class="rf-export"><a class="btn btn-secondary btn-sm" :href="exportUrl('csv')" download>Download CSV</a><a class="btn btn-ghost btn-sm" :href="exportUrl('json')" download>JSON</a>@@ -264,7 +300,12 @@ onMounted(load);<div v-else-if="summary && summary.total === 0" class="card"><div class="empty-state"><h3>{{ filtered ? "No responses match these filters" : "No responses yet" }}</h3>- <p v-if="!filtered">Share the form's link or embed it on your site from the Share & embed tab.</p>+ <template v-if="!filtered">+ <p>Share this link, or embed the form on your site from the Share & embed tab.</p>+ <p v-if="props.shareUrl" class="share-line">+ <a :href="props.shareUrl" target="_blank" rel="noopener">{{ props.shareUrl }}</a>+ </p>+ </template><button v-else class="btn btn-secondary" @click="clearFilters">Clear filters</button></div></div>@@ -372,6 +413,8 @@ onMounted(load);<th>Subject</th><th>Message</th></template>+ <th>Priority</th>+ <th>Tags</th></tr></thead><tbody>@@ -391,6 +434,8 @@ onMounted(load);<td>{{ m.subject }}</td><td class="rt-long">{{ m.body }}</td></template>+ <td>{{ PRIORITY_LABELS[m.priority] || "" }}</td>+ <td class="rt-tags">{{ (m.tags || []).join(", ") }}</td></tr></tbody></table>@@ -695,6 +740,14 @@ onMounted(load);text-overflow: ellipsis;}+.share-line {+ overflow-wrap: anywhere;+}++.rt-tags {+ color: var(--text-secondary);+}+.rt-when {white-space: nowrap;}diff --git a/web/src/views/forms/Forms.vue b/web/src/views/forms/Forms.vueindex 87f630c..dbbe466 100644--- a/web/src/views/forms/Forms.vue+++ b/web/src/views/forms/Forms.vue@@ -4,7 +4,7 @@ import { useRouter } from "vue-router";import { formsApi } from "../../api/messages";import { useNotificationStore } from "../../stores/notification";import { apiMessage } from "../../composables/apiError";-import type { Form } from "../../api/types";+import type { Form, FormMode } from "../../api/types";import Pagination from "../../components/Pagination.vue";import { usePagination } from "../../composables/usePagination";@@ -19,6 +19,7 @@ const creating = ref(false);const newName = ref("");const newOrigins = ref("");const newNotify = ref("");+const newMode = ref<FormMode>("inbox");const { pageable, goToPage } = usePagination(async (page) => {loading.value = true;@@ -42,6 +43,7 @@ function openCreate() {newName.value = "";newOrigins.value = "";newNotify.value = "";+ newMode.value = "inbox";showCreate.value = true;}@@ -51,6 +53,7 @@ async function createForm() {try {const res = await formsApi.create({name: newName.value.trim(),+ mode: newMode.value,allowed_origins: splitList(newOrigins.value),notify_emails: splitList(newNotify.value),});@@ -126,9 +129,10 @@ function formatDate(date: string | null | undefined) {<th>Name</th><th>Public key</th><th>Status</th>- <th>Messages</th>+ <th>Kind</th>+ <th>Submissions</th><th>Spam</th>- <th>Last message</th>+ <th>Last submission</th></tr></thead><tbody>@@ -141,6 +145,7 @@ function formatDate(date: string | null | undefined) {<td>{{ form.name }}</td><td><code style="font-size: 12px">{{ form.public_key }}</code></td><td><span :class="statusBadgeClass(form.status)">{{ form.status }}</span></td>+ <td>{{ form.mode === "collect" ? "Responses" : "Messages" }}</td><td>{{ form.message_count }}</td><td>{{ form.spam_count }}</td><td>{{ formatDate(form.last_message_at) }}</td>@@ -162,6 +167,16 @@ function formatDate(date: string | null | undefined) {<label class="form-label">Name</label><input v-model="newName" class="form-input" placeholder="Contact form" /></div>+ <div class="form-group">+ <label class="form-label">Submissions are</label>+ <select v-model="newMode" class="form-select">+ <option value="inbox">Messages to answer (contact, support)</option>+ <option value="collect">Responses to collect (surveys, signups, RSVPs)</option>+ </select>+ <small v-if="newMode === 'collect'" class="muted">+ Responses stay out of the inbox, and notifications default to a daily digest.+ </small>+ </div><div class="form-group"><label class="form-label">Allowed origins</label><inputdiff --git a/web/src/views/messages/MessageDetail.vue b/web/src/views/messages/MessageDetail.vueindex 27fcb4c..04289d5 100644--- a/web/src/views/messages/MessageDetail.vue+++ b/web/src/views/messages/MessageDetail.vue@@ -5,6 +5,7 @@ import { messagesApi } from "../../api/messages";import { useNotificationStore } from "../../stores/notification";import { apiMessage } from "../../composables/apiError";import type { Message } from "../../api/types";+import MessageTriage from "./MessageTriage.vue";const route = useRoute();const router = useRouter();@@ -141,7 +142,7 @@ async function remove() {busy.value = true;try {await messagesApi.delete(uuid);- router.push("/messages");+ router.push(backTo.value);} catch (e: any) {notify.error(apiMessage(e, "Failed to delete message"));busy.value = false;@@ -248,6 +249,15 @@ async function copyValue(value: string) {}}+// A collect-mode form's submissions are responses to read, not conversations:+// no reply composer and no state to work through.+const collect = computed(() => message.value?.form?.mode === "collect");+const backTo = computed(() =>+ collect.value && message.value?.form+ ? `/forms/${message.value.form.id}?tab=responses`+ : "/messages"+);+const canReply = computed(() => !!message.value?.sender_email && message.value?.status !== "rejected");@@ -294,9 +304,14 @@ onBeforeUnmount(() => {<template><div><div class="page-header">- <h1>Message</h1>+ <h1>{{ collect ? "Response" : "Message" }}</h1><div style="display: flex; gap: 8px">- <button v-if="message" class="btn btn-secondary" :disabled="busy" @click="setState('closed')">+ <button+ v-if="message && !collect"+ class="btn btn-secondary"+ :disabled="busy"+ @click="setState('closed')"+ >Close</button><button@@ -316,7 +331,7 @@ onBeforeUnmount(() => {Not spam</button><button class="btn btn-danger" :disabled="busy" @click="remove">Delete</button>- <button class="btn btn-secondary" @click="router.push('/messages')">Back</button>+ <button class="btn btn-secondary" @click="router.push(backTo)">Back</button></div></div>@@ -338,7 +353,7 @@ onBeforeUnmount(() => {<h2>{{ message.subject || "(no subject)" }}</h2><div style="display: flex; gap: 8px"><span :class="statusBadgeClass(message.status)">{{ message.status }}</span>- <span class="badge badge-secondary">{{ message.state }}</span>+ <span v-if="!collect" class="badge badge-secondary">{{ message.state }}</span></div></div><div class="card-body">@@ -390,6 +405,9 @@ onBeforeUnmount(() => {</tr></tbody></table>+ <div class="triage-block">+ <MessageTriage :message="message" @updated="message = $event" />+ </div></div></div>@@ -513,7 +531,7 @@ onBeforeUnmount(() => {</div></div>- <div class="card">+ <div v-if="!collect" class="card"><div class="card-header"><h2>Reply</h2></div><div class="card-body"><div v-if="!canReply" class="empty-state">@@ -558,6 +576,12 @@ onBeforeUnmount(() => {</template><style scoped>+.triage-block {+ margin-top: 16px;+ padding-top: 16px;+ border-top: 1px solid var(--border-secondary);+}+.submission-actions {display: flex;align-items: center;diff --git a/web/src/views/messages/MessageTriage.vue b/web/src/views/messages/MessageTriage.vuenew file mode 100644index 0000000..c2a31c9--- /dev/null+++ b/web/src/views/messages/MessageTriage.vue@@ -0,0 +1,196 @@+<script setup lang="ts">+import { onMounted, ref } from "vue";+import { messagesApi } from "../../api/messages";+import { useNotificationStore } from "../../stores/notification";+import { apiMessage } from "../../composables/apiError";+import type { Message, MessagePriority } from "../../api/types";++// Tags and priority on one message. Each change saves at once and hands the+// updated message back, so the page never holds unsaved triage.+const props = defineProps<{ message: Message }>();+const emit = defineEmits<{ updated: [message: Message] }>();++const notify = useNotificationStore();+const busy = ref(false);+const draft = ref("");+const suggestions = ref<string[]>([]);+const listId = `tag-suggestions-${props.message.uuid}`;++const PRIORITIES: { value: MessagePriority; label: string }[] = [+ { value: "low", label: "Low" },+ { value: "normal", label: "Normal" },+ { value: "high", label: "High" },+ { value: "urgent", label: "Urgent" },+];++onMounted(async () => {+ try {+ const res = await messagesApi.tags();+ suggestions.value = res.data.data.map((t) => t.tag);+ } catch {+ /* suggestions are a convenience */+ }+});++async function run(action: () => Promise<{ data: { data: Message } }>, failure: string) {+ busy.value = true;+ try {+ const res = await action();+ emit("updated", res.data.data);+ return true;+ } catch (e: any) {+ notify.error(apiMessage(e, failure));+ return false;+ } finally {+ busy.value = false;+ }+}++async function setPriority(event: Event) {+ const priority = (event.target as HTMLSelectElement).value as MessagePriority;+ await run(() => messagesApi.setPriority(props.message.uuid, priority), "Failed to set priority");+}++async function addTags() {+ const tags = draft.value+ .split(/[,;]/)+ .map((t) => t.trim())+ .filter(Boolean);+ if (!tags.length) return;+ if (await run(() => messagesApi.updateTags(props.message.uuid, { add: tags }), "Failed to add tag")) {+ draft.value = "";+ for (const t of tags) {+ const tag = t.toLowerCase();+ if (!suggestions.value.includes(tag)) suggestions.value.push(tag);+ }+ }+}++function removeTag(tag: string) {+ run(() => messagesApi.updateTags(props.message.uuid, { remove: [tag] }), "Failed to remove tag");+}++function onKey(event: KeyboardEvent) {+ if (event.key === "Enter" || event.key === ",") {+ event.preventDefault();+ addTags();+ }+}+</script>++<template>+ <div class="triage">+ <label class="triage-priority">+ <span class="triage-label">Priority</span>+ <select+ class="form-select"+ :value="message.priority || 'normal'"+ :disabled="busy"+ @change="setPriority"+ >+ <option v-for="p in PRIORITIES" :key="p.value" :value="p.value">{{ p.label }}</option>+ </select>+ </label>++ <div class="triage-tags">+ <span class="triage-label">Tags</span>+ <div class="tag-row">+ <span v-for="tag in message.tags" :key="tag" class="tag-chip">+ {{ tag }}+ <button+ type="button"+ class="tag-remove"+ :disabled="busy"+ :aria-label="`Remove tag ${tag}`"+ @click="removeTag(tag)"+ >×</button>+ </span>+ <input+ v-model="draft"+ class="form-input tag-input"+ :list="listId"+ maxlength="32"+ placeholder="Add a tag…"+ :disabled="busy"+ aria-label="Add a tag"+ @keydown="onKey"+ @blur="addTags"+ />+ <datalist :id="listId">+ <option v-for="s in suggestions.filter((s) => !message.tags.includes(s))" :key="s" :value="s" />+ </datalist>+ </div>+ </div>+ </div>+</template>++<style scoped>+.triage {+ display: flex;+ flex-wrap: wrap;+ gap: 16px 24px;+ align-items: flex-start;+}++.triage-label {+ display: block;+ margin-bottom: 6px;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ font-weight: 600;+ color: var(--text-tertiary);+}++.triage-priority .form-select {+ width: 140px;+}++.triage-tags {+ flex: 1 1 280px;+ min-width: 0;+}++.tag-row {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ align-items: center;+}++.tag-chip {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 3px 4px 3px 10px;+ border-radius: 999px;+ background: var(--bg-tertiary);+ color: var(--text-secondary);+ font-size: 13px;+ line-height: 1.4;+}++.tag-remove {+ border: 0;+ background: none;+ width: 20px;+ height: 20px;+ border-radius: 50%;+ color: var(--text-muted);+ font-size: 15px;+ line-height: 1;+ cursor: pointer;+}++.tag-remove:hover,+.tag-remove:focus-visible {+ background: var(--bg-secondary);+ color: var(--text-primary);+}++.tag-input {+ flex: 1 1 140px;+ min-width: 120px;+ max-width: 220px;+}+</style>diff --git a/web/src/views/messages/Messages.vue b/web/src/views/messages/Messages.vueindex 098a82c..50ec4a0 100644--- a/web/src/views/messages/Messages.vue+++ b/web/src/views/messages/Messages.vue@@ -22,6 +22,9 @@ const status = ref("");const state = ref("");const unread = ref(false);const q = ref("");+const tag = ref(String(route.query.tag || ""));+const priority = ref("");+const knownTags = ref<string[]>([]);const { pageable, goToPage } = usePagination(async (page) => {loading.value = true;@@ -33,6 +36,8 @@ const { pageable, goToPage } = usePagination(async (page) => {state: state.value || undefined,unread: unread.value || undefined,q: q.value || undefined,+ tag: tag.value || undefined,+ priority: priority.value || undefined,});messages.value = res.data.data;pageable.value = res.data.pageable;@@ -50,12 +55,14 @@ const { pageable, goToPage } = usePagination(async (page) => {async function loadSidebarData() {try {- const [formsRes, statsRes] = await Promise.all([+ const [formsRes, statsRes, tagsRes] = await Promise.all([formsApi.list({ size: 100 }),messagesApi.stats(),+ messagesApi.tags(),]);forms.value = formsRes.data.data;stats.value = statsRes.data.data;+ knownTags.value = tagsRes.data.data.map((t) => t.tag);} catch {/* the list view already reports a disabled feature */}@@ -71,6 +78,8 @@ function resetFilters() {state.value = "";unread.value = false;q.value = "";+ tag.value = "";+ priority.value = "";goToPage(0);}@@ -98,6 +107,18 @@ onBeforeUnmount(() => {});const hasForms = computed(() => forms.value.length > 0);+const collectForms = computed(() => forms.value.filter((f) => f.mode === "collect"));++function filterByTag(value: string) {+ tag.value = value;+ applyFilters();+}++const PRIORITY_BADGES: Record<string, { label: string; cls: string }> = {+ urgent: { label: "Urgent", cls: "badge badge-danger" },+ high: { label: "High", cls: "badge badge-warning" },+ low: { label: "Low", cls: "badge badge-neutral" },+};function statusBadgeClass(value: string) {switch (value) {@@ -217,6 +238,26 @@ function formatDate(date: string | null | undefined) {</select></div>+ <div style="flex: 1 1 120px">+ <label class="form-label">Priority</label>+ <select v-model="priority" class="form-select" @change="applyFilters">+ <option value="">Any</option>+ <option value="urgent">Urgent</option>+ <option value="high">High</option>+ <option value="normal">Normal</option>+ <option value="low">Low</option>+ </select>+ </div>++ <div v-if="knownTags.length || tag" style="flex: 1 1 140px">+ <label class="form-label">Tag</label>+ <select v-model="tag" class="form-select" @change="applyFilters">+ <option value="">Any</option>+ <option v-if="tag && !knownTags.includes(tag)" :value="tag">{{ tag }}</option>+ <option v-for="t in knownTags" :key="t" :value="t">{{ t }}</option>+ </select>+ </div>+<div style="flex: 2 1 200px"><label class="form-label">Search</label><input@@ -237,6 +278,16 @@ function formatDate(date: string | null | undefined) {</div></div>+ <p v-if="!formId && collectForms.length" class="collect-note">+ Responses to+ <template v-for="(f, i) in collectForms.slice(0, 3)" :key="f.id">+ <router-link :to="`/forms/${f.id}?tab=responses`">{{ f.name }}</router-link+ >{{ i < Math.min(collectForms.length, 3) - 1 ? ", " : "" }}+ </template>+ <template v-if="collectForms.length > 3"> and {{ collectForms.length - 3 }} more</template>+ are collected on {{ collectForms.length === 1 ? "its form" : "their forms" }}, not in this inbox.+ </p>+<div v-if="messages.length === 0" class="empty-state"><h3>No messages yet</h3><p v-if="hasForms">@@ -271,7 +322,23 @@ function formatDate(date: string | null | undefined) {<td :style="{ fontWeight: message.read_at ? '400' : '600' }">{{ senderLabel(message) }}</td>- <td>{{ message.subject || "(no subject)" }}</td>+ <td>+ <span class="subject-cell">+ <span+ v-if="PRIORITY_BADGES[message.priority]"+ :class="PRIORITY_BADGES[message.priority].cls"+ >{{ PRIORITY_BADGES[message.priority].label }}</span>+ <span>{{ message.subject || "(no subject)" }}</span>+ <button+ v-for="t in message.tags"+ :key="t"+ type="button"+ class="tag-chip"+ :title="`Show messages tagged ${t}`"+ @click.stop="filterByTag(t)"+ >{{ t }}</button>+ </span>+ </td><td>{{ message.form?.name || "-" }}</td><td><span :class="statusBadgeClass(message.status)">{{ message.status }}</span>@@ -290,3 +357,36 @@ function formatDate(date: string | null | undefined) {</template></div></template>++<style scoped>+.collect-note {+ margin: 0;+ padding: 0 20px 14px;+ font-size: 13px;+ color: var(--text-tertiary);+}++.subject-cell {+ display: inline-flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+}++.tag-chip {+ border: 0;+ padding: 1px 8px;+ border-radius: 999px;+ background: var(--bg-tertiary);+ color: var(--text-secondary);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+}++.tag-chip:hover,+.tag-chip:focus-visible {+ color: var(--text-primary);+ text-decoration: underline;+}+</style>