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 sections with branching, routing rules and teams
Jonas Kaninda2fbce6635e75
diff --git a/cmd/posta/server.go b/cmd/posta/server.goindex 4aa9f9e..f9a69dc 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -545,6 +545,10 @@ func startEmbeddedWorker(db *gorm.DB,)messageHandler.OnNotified(metrics.IncrementMessageNotification)messageHandler.SetRealtime(realtime.NewRedis(cfg.Redis.Client))+ messageHandler.SetRouting(repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{+ Workspaces: repositories.NewWorkspaceRepository(db),+ Teams: repositories.NewTeamRepository(db),+ })mux.HandleFunc(worker.TypeMessageProcess, messageHandler.ProcessTask)mux.HandleFunc(worker.TypeMessageReply, messageHandler.ProcessReplyTask)}@@ -621,13 +625,18 @@ func initCronManager(if cfg.MessagesEnabled {retentionJob.SetMessageRepo(repositories.NewMessageRepository(db))retentionJob.SetFormRepo(repositories.NewFormRepository(db))- manager.Register(jobs.NewMessageDigestJob(+ digest := jobs.NewMessageDigestJob(notifier,repositories.NewFormRepository(db),repositories.NewMessageRepository(db),repositories.NewWorkspaceRepository(db),cfg.AppWebURL,- ))+ )+ digest.SetRouting(repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{+ Workspaces: repositories.NewWorkspaceRepository(db),+ Teams: repositories.NewTeamRepository(db),+ })+ manager.Register(digest)}return manager}diff --git a/cmd/posta/worker.go b/cmd/posta/worker.goindex a1a0325..14819ab 100644--- a/cmd/posta/worker.go+++ b/cmd/posta/worker.go@@ -222,6 +222,10 @@ func runWorker() error {)messageHandler.OnNotified(metrics.IncrementMessageNotification)messageHandler.SetRealtime(realtime.NewRedis(cfg.Redis.Client))+ messageHandler.SetRouting(repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{+ Workspaces: repositories.NewWorkspaceRepository(db),+ Teams: repositories.NewTeamRepository(db),+ })mux.HandleFunc(worker.TypeMessageProcess, messageHandler.ProcessTask)mux.HandleFunc(worker.TypeMessageReply, messageHandler.ProcessReplyTask)}diff --git a/internal/cron/jobs/message_digest.go b/internal/cron/jobs/message_digest.goindex 9e4f9b8..497c391 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/formrules""github.com/goposta/posta/internal/services/messages""github.com/goposta/posta/internal/services/notification""github.com/goposta/posta/internal/storage/repositories"@@ -44,6 +45,8 @@ type MessageDigestJob struct {formRepo *repositories.FormRepositorymessageRepo *repositories.MessageRepositoryworkspaceRepo *repositories.WorkspaceRepository+ ruleRepo *repositories.FormRuleRepository+ directory formrules.DirectoryappURL string}@@ -63,6 +66,12 @@ func NewMessageDigestJob(}}+// SetRouting groups digests by the recipients routing rules chose, so a team+// is sent its own submissions rather than everyone everything.+func (j *MessageDigestJob) SetRouting(rules *repositories.FormRuleRepository, dir formrules.Directory) {+ j.ruleRepo, j.directory = rules, dir+}+func (j *MessageDigestJob) Name() string { return "message-digest" }func (j *MessageDigestJob) Schedule() string { return "5 * * * *" }@@ -103,7 +112,19 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labe}mask := messages.NewPIIMask(form.Fields)- items := make([]digestItem, 0, len(pending))+ var rules []models.FormRule+ if j.ruleRepo != nil {+ rules, _ = j.ruleRepo.ListByForm(form.ID)+ }+ var dir formrules.Directory+ if j.directory != nil {+ dir = &formrules.CachedDirectory{Next: j.directory}+ }++ // Each recipient gets the submissions routed to them: the form's+ // default route, or an address or member a rule added.+ groups := map[digestTarget][]digestItem{}+ var order []digestTargetids := make([]uint, 0, len(pending))for k := range pending {m := &pending[k]@@ -111,16 +132,20 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labeif m.Status == models.MessageStatusFlagged && !form.NotifyOnFlagged {continue}- if len(items) < 25 {- items = append(items, digestItem{- Sender: senderLabel(m, mask),- Subject: mask.Value(models.RoleSubject, m.Subject),- Flagged: m.Status == models.MessageStatusFlagged,- })+ item := digestItem{+ Sender: senderLabel(m, mask),+ Subject: mask.Value(models.RoleSubject, m.Subject),+ Flagged: m.Status == models.MessageStatusFlagged,+ }+ for _, target := range j.targets(form, rules, dir, m) {+ if _, seen := groups[target]; !seen {+ order = append(order, target)+ }+ groups[target] = append(groups[target], item)}}- if len(items) == 0 {+ if len(order) == 0 {_ = j.messageRepo.MarkNotified(ids, now)continue}@@ -129,26 +154,38 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labeif ws, err := j.workspaceRepo.FindByID(*form.WorkspaceID); err == nil {workspaceName = ws.Name}-- data := map[string]any{- "Period": label,- "FormName": form.Name,- "Collect": form.IsCollect(),- "Total": len(items),- "Items": items,- "InboxURL": j.inboxURL(form),- }- if workspaceName != "" {- data["WorkspaceName"] = workspaceName- }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)+ failed := false+ for _, target := range order {+ items := groups[target]+ data := map[string]any{+ "Period": label,+ "FormName": form.Name,+ "Collect": form.IsCollect(),+ "Total": len(items),+ "Items": items,+ "InboxURL": j.inboxURL(form),+ }+ if len(items) > 25 {+ data["Items"] = items[:25]+ }+ if workspaceName != "" {+ data["WorkspaceName"] = workspaceName+ }+ subject := fmt.Sprintf("%s digest: %d new %s on %s", label, len(items), noun, form.Name)+ if err := j.send(form, target, subject, data); err != nil {+ logger.Error("message-digest: failed to send", "form_id", form.ID, "error", err)+ failed = true+ }+ }+ // A failed send keeps the submissions pending for the next run; the+ // recipients that did get theirs may then get them twice, which+ // beats someone never hearing of them.+ if failed {continue}@@ -158,6 +195,56 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labereturn sent}+// digestTarget is one recipient of a digest: the form's default route, an+// address, or a member.+type digestTarget struct {+ Default bool+ Email string+ UserID uint+}++// targets is where one submission is reported. Without rules, that is the+// form's default route, as before.+func (j *MessageDigestJob) targets(form *models.Form, rules []models.FormRule, dir formrules.Directory, m *models.Message) []digestTarget {+ if len(rules) == 0 || dir == nil || !formrules.Routable(m.Status) {+ return []digestTarget{{Default: true}}+ }+ var out formrules.Outcome+ if m.RoutedAt != nil {+ out = formrules.Combine(rules, m.MatchedRules)+ } else {+ out = formrules.Evaluate(rules, formrules.FactsFor(m, form))+ }+ res, err := formrules.Resolve(form, out, dir)+ if err != nil {+ logger.Warn("message-digest: failed to resolve rule recipients", "form_id", form.ID, "error", err)+ return []digestTarget{{Default: true}}+ }+ var targets []digestTarget+ if res.Default {+ targets = append(targets, digestTarget{Default: true})+ }+ for _, e := range res.Emails {+ targets = append(targets, digestTarget{Email: e})+ }+ for _, id := range res.UserIDs {+ targets = append(targets, digestTarget{UserID: id})+ }+ return targets+}++func (j *MessageDigestJob) send(form *models.Form, target digestTarget, subject string, data map[string]any) error {+ switch {+ case target.Default:+ return j.deliver(form, subject, data)+ case target.Email != "":+ data["UserName"] = "there"+ return j.notifier.Send(target.Email, subject, notification.TemplateMessageDigest, data)+ default:+ return j.notifier.SendToUser(target.UserID, subject, notification.TemplateMessageDigest, data)+ }+}+func (j *MessageDigestJob) deliver(form *models.Form, subject string, data map[string]any) error {if len(form.NotifyEmails) > 0 {var lastErr errordiff --git a/internal/cron/jobs/message_digest_test.go b/internal/cron/jobs/message_digest_test.gonew file mode 100644index 0000000..ce705ca--- /dev/null+++ b/internal/cron/jobs/message_digest_test.go@@ -0,0 +1,87 @@+// 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 jobs++import (+ "errors"+ "reflect"+ "testing"+ "time"++ "github.com/goposta/posta/internal/models"+)++type digestDir struct{ ws uint }++func (d digestDir) Members(uint) (map[uint]models.WorkspaceRole, error) {+ return map[uint]models.WorkspaceRole{1: models.WorkspaceRoleOwner, 7: models.WorkspaceRoleEditor, 8: models.WorkspaceRoleEditor}, nil+}++func (d digestDir) Team(id uint) (*models.Team, error) {+ switch id {+ case 3:+ return &models.Team{ID: 3, WorkspaceID: &d.ws, Members: []models.TeamMember{{UserID: 7}}}, nil+ case 4:+ return &models.Team{ID: 4, WorkspaceID: &d.ws, Email: "[email protected]", Members: []models.TeamMember{{UserID: 8}}}, nil+ }+ return nil, errors.New("not found")+}++// Two rules sending to two teams give each team its own digest, and the+// default route keeps everything unless a rule suppresses it.+func TestDigestTargetsFollowRules(t *testing.T) {+ ws := uint(5)+ form := &models.Form{ID: 1, WorkspaceID: &ws, Fields: models.FieldDefs{+ {Key: "dept", Label: "Dept", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "sales"}, {Value: "billing"}}},+ }}+ sales, billing := uint(3), uint(4)+ rules := []models.FormRule{+ {UUID: "s", Enabled: true, Conditions: models.RuleConditions{{Field: "dept", Op: "eq", Value: "sales"}},+ Actions: models.RuleActions{{Type: models.ActionNotifyTeam, TeamID: &sales}, {Type: models.ActionSuppressDefault}}},+ {UUID: "b", Enabled: true, Conditions: models.RuleConditions{{Field: "dept", Op: "eq", Value: "billing"}},+ Actions: models.RuleActions{{Type: models.ActionNotifyTeam, TeamID: &billing}}},+ }+ j := &MessageDigestJob{}+ dir := digestDir{ws: ws}+ msg := func(dept string) *models.Message {+ return &models.Message{Status: models.MessageStatusReceived, Data: models.SubmissionData{"dept": dept}}+ }++ if got := j.targets(form, rules, dir, msg("sales")); !reflect.DeepEqual(got, []digestTarget{{UserID: 7}}) {+ t.Errorf("sales: %+v", got)+ }+ if got := j.targets(form, rules, dir, msg("billing")); !reflect.DeepEqual(got, []digestTarget{{Default: true}, {Email: "[email protected]"}, {UserID: 8}}) {+ t.Errorf("billing: %+v", got)+ }+ if got := j.targets(form, rules, dir, msg("other")); !reflect.DeepEqual(got, []digestTarget{{Default: true}}) {+ t.Errorf("unmatched: %+v", got)+ }++ // A routed submission replays its stored matches, not today's rules.+ routed := msg("billing")+ now := time.Now()+ routed.RoutedAt, routed.MatchedRules = &now, []string{"s"}+ if got := j.targets(form, rules, dir, routed); !reflect.DeepEqual(got, []digestTarget{{UserID: 7}}) {+ t.Errorf("routed: %+v", got)+ }+ if got := j.targets(form, nil, dir, msg("sales")); !reflect.DeepEqual(got, []digestTarget{{Default: true}}) {+ t.Errorf("no rules: %+v", got)+ }+}diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.goindex f72a0fb..9680980 100644--- a/internal/handlers/form_handler.go+++ b/internal/handlers/form_handler.go@@ -687,7 +687,7 @@ func applySchema(form *models.Form, fields *models.FieldDefs, unknownFields, errreturn err}// The honeypot, _nonce and _redirect count towards max_fields too.- if active := len(next.Active()); active+3 > form.FieldLimit() {+ if active := len(next.Active().Questions()); active+3 > form.FieldLimit() {return fmt.Errorf("the schema has %d fields but max_fields is %d; raise max_fields to at least %d", active, form.FieldLimit(), active+3)}if schemaChanged(form.Fields, next) {diff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.goindex 92c806f..b620c64 100644--- a/internal/handlers/form_ingest_handler.go+++ b/internal/handlers/form_ingest_handler.go@@ -162,6 +162,7 @@ type WidgetField struct {MaxLabel string `json:"max_label,omitempty"`Placeholder string `json:"placeholder,omitempty"`Help string `json:"help,omitempty"`+ Next string `json:"next,omitempty" doc:"Sections only: where the page leads, a section key or submit"`}func widgetFields(defs models.FieldDefs) []WidgetField {@@ -173,7 +174,7 @@ func widgetFields(defs models.FieldDefs) []WidgetField {Key: f.Key, Label: f.Label, Type: f.Type, Required: f.Required,MinLen: f.MinLen, Min: f.Min, Max: f.Max, Pattern: f.Pattern,Options: f.Options, Display: f.Display, MinLabel: f.MinLabel, MaxLabel: f.MaxLabel,- Placeholder: f.Placeholder, Help: f.Help,+ Placeholder: f.Placeholder, Help: f.Help, Next: f.Next,}switch f.Type {case models.FieldText, models.FieldTextarea, models.FieldHidden:diff --git a/internal/handlers/form_page_handler.go b/internal/handlers/form_page_handler.goindex f1156c1..3f3390c 100644--- a/internal/handlers/form_page_handler.go+++ b/internal/handlers/form_page_handler.go@@ -141,7 +141,7 @@ func prefillAttrs(form *models.Form, query url.Values) []template.HTMLAttr {}for _, f := range form.Fields.Active() {values := query[f.Key]- if f.PII || len(values) == 0 {+ if f.PII || f.IsSection() || len(values) == 0 {continue}if f.Type == models.FieldMultiSelect {diff --git a/internal/handlers/form_rule_handler.go b/internal/handlers/form_rule_handler.gonew file mode 100644index 0000000..a1c1433--- /dev/null+++ b/internal/handlers/form_rule_handler.go@@ -0,0 +1,361 @@+// 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 handlers++import (+ "fmt"+ "time"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/audit"+ "github.com/goposta/posta/internal/services/formrules"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/okapi"+)++// FormRuleHandler edits a form's routing rules. Rules are form configuration,+// so they need the admin scope like the form itself (/forms is a tenant+// admin path).+type FormRuleHandler struct {+ repo *repositories.FormRuleRepository+ formRepo *repositories.FormRepository+ messageRepo *repositories.MessageRepository+ teamRepo *repositories.TeamRepository+ workspaceRepo *repositories.WorkspaceRepository+ webhookRepo *repositories.WebhookRepository+ audit *audit.Logger+}++func NewFormRuleHandler(+ repo *repositories.FormRuleRepository,+ formRepo *repositories.FormRepository,+ messageRepo *repositories.MessageRepository,+ teamRepo *repositories.TeamRepository,+ workspaceRepo *repositories.WorkspaceRepository,+ webhookRepo *repositories.WebhookRepository,+ auditLogger *audit.Logger,+) *FormRuleHandler {+ return &FormRuleHandler{+ repo: repo, formRepo: formRepo, messageRepo: messageRepo, teamRepo: teamRepo,+ workspaceRepo: workspaceRepo, webhookRepo: webhookRepo, audit: auditLogger,+ }+}++// RuleBody is a rule as the dashboard edits it.+type RuleBody struct {+ Name string `json:"name" doc:"Shown in the rule list and on routed submissions"`+ Enabled *bool `json:"enabled" doc:"Default true"`+ Match models.RuleMatch `json:"match" enum:"all,any" doc:"Whether all conditions must hold, or any one. Default all."`+ Conditions models.RuleConditions `json:"conditions" doc:"Empty matches every submission"`+ Actions models.RuleActions `json:"actions"`+ Stop bool `json:"stop" doc:"Do not evaluate later rules when this one matches"`+}++type FormRulesRequest struct {+ ID int `param:"id"`+}++type CreateFormRuleRequest struct {+ ID int `param:"id"`+ Body RuleBody `json:"body"`+}++type UpdateFormRuleRequest struct {+ ID int `param:"id"`+ RuleID int `param:"rule_id"`+ Body RuleBody `json:"body"`+}++type FormRuleIDRequest struct {+ ID int `param:"id"`+ RuleID int `param:"rule_id"`+}++type ReorderFormRulesRequest struct {+ ID int `param:"id"`+ Body struct {+ IDs []uint `json:"ids" doc:"Every rule of the form, in the new evaluation order"`+ } `json:"body"`+}++type TestFormRulesRequest struct {+ ID int `param:"id"`+ Body struct {+ Rules []RuleBody `json:"rules" doc:"Rules to try instead of the saved ones, in order; omit to test the saved rules"`+ Limit int `json:"limit" doc:"How many recent submissions to replay, at most 200 (default 100)"`+ } `json:"body"`+}++// RuleTestResult is a dry run: what the rules would have done with recent+// submissions. Nothing is sent or changed.+type RuleTestResult struct {+ Scanned int `json:"scanned"`+ Matched int `json:"matched" doc:"Submissions at least one rule matched"`+ Rules []RuleTestCount `json:"rules"`+ Samples []RuleTestSample `json:"samples"`+}++type RuleTestCount struct {+ Index int `json:"index"`+ Name string `json:"name"`+ Matches int `json:"matches"`+}++type RuleTestSample struct {+ MessageUUID string `json:"message_uuid"`+ Sender string `json:"sender"`+ Subject string `json:"subject"`+ ReceivedAt time.Time `json:"received_at"`+ Matched []int `json:"matched" doc:"Indexes into rules"`+ Outcome formrules.Outcome `json:"outcome"`+}++func (h *FormRuleHandler) form(c *okapi.Context, id int) (*models.Form, error) {+ return h.formRepo.FindByIDForScope(getScope(c), uint(id))+}++// destinations lists what this workspace's rules may point at.+func (h *FormRuleHandler) destinations(workspaceID uint) (formrules.Destinations, error) {+ d := formrules.Destinations{Members: map[uint]bool{}, Teams: map[uint]bool{}, Webhooks: map[uint]bool{}}+ members, err := h.workspaceRepo.ListMembers(workspaceID)+ if err != nil {+ return d, err+ }+ for _, m := range members {+ d.Members[m.UserID] = true+ }+ teams, err := h.teamRepo.IDs(workspaceID)+ if err != nil {+ return d, err+ }+ for _, id := range teams {+ d.Teams[id] = true+ }+ hooks, _, err := h.webhookRepo.FindByWorkspaceID(workspaceID, 1000, 0)+ if err != nil {+ return d, err+ }+ for _, wh := range hooks {+ d.Webhooks[wh.ID] = true+ }+ return d, nil+}++func (h *FormRuleHandler) checked(c *okapi.Context, form *models.Form, b RuleBody) (*models.FormRule, error) {+ rule := &models.FormRule{+ Name: b.Name, Enabled: b.Enabled == nil || *b.Enabled, Match: b.Match,+ Conditions: b.Conditions, Actions: b.Actions, Stop: b.Stop,+ }+ if rule.Conditions == nil {+ rule.Conditions = models.RuleConditions{}+ }+ d, err := h.destinations(*form.WorkspaceID)+ if err != nil {+ return nil, c.AbortInternalServerError("failed to load workspace destinations")+ }+ if err := formrules.Check(rule, form, d); err != nil {+ return nil, c.AbortBadRequest(err.Error())+ }+ return rule, nil+}++func (h *FormRuleHandler) List(c *okapi.Context, req *FormRulesRequest) error {+ form, err := h.form(c, req.ID)+ if err != nil {+ return c.AbortNotFound("form not found")+ }+ rules, err := h.repo.ListByForm(form.ID)+ if err != nil {+ return c.AbortInternalServerError("failed to list rules")+ }+ if rules == nil {+ rules = []models.FormRule{}+ }+ return ok(c, rules)+}++func (h *FormRuleHandler) Create(c *okapi.Context, req *CreateFormRuleRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("insufficient workspace permissions", err)+ }+ form, err := h.form(c, req.ID)+ if err != nil {+ return c.AbortNotFound("form not found")+ }+ rule, err := h.checked(c, form, req.Body)+ if rule == nil {+ return err+ }+ userID := uint(c.GetInt("user_id"))+ rule.WorkspaceID, rule.FormID, rule.LastEditedByID = form.WorkspaceID, form.ID, &userID+ if err := h.repo.Create(rule); err != nil {+ return c.AbortInternalServerError("failed to create rule")+ }+ h.log(c, "form.rule_created", fmt.Sprintf("Rule %q created on form %s", rule.Name, form.Name), form, rule)+ return created(c, rule)+}++func (h *FormRuleHandler) Update(c *okapi.Context, req *UpdateFormRuleRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("insufficient workspace permissions", err)+ }+ form, err := h.form(c, req.ID)+ if err != nil {+ return c.AbortNotFound("form not found")+ }+ existing, err := h.repo.FindForForm(form.ID, uint(req.RuleID))+ if err != nil {+ return c.AbortNotFound("rule not found")+ }+ rule, err := h.checked(c, form, req.Body)+ if rule == nil {+ return err+ }+ now := time.Now()+ userID := uint(c.GetInt("user_id"))+ existing.Name, existing.Enabled, existing.Match = rule.Name, rule.Enabled, rule.Match+ existing.Conditions, existing.Actions, existing.Stop = rule.Conditions, rule.Actions, rule.Stop+ existing.LastEditedByID, existing.UpdatedAt = &userID, &now+ if err := h.repo.Update(existing); err != nil {+ return c.AbortInternalServerError("failed to update rule")+ }+ h.log(c, "form.rule_updated", fmt.Sprintf("Rule %q updated on form %s", existing.Name, form.Name), form, existing)+ return ok(c, existing)+}++func (h *FormRuleHandler) Delete(c *okapi.Context, req *FormRuleIDRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("insufficient workspace permissions", err)+ }+ form, err := h.form(c, req.ID)+ if err != nil {+ return c.AbortNotFound("form not found")+ }+ rule, err := h.repo.FindForForm(form.ID, uint(req.RuleID))+ if err != nil {+ return c.AbortNotFound("rule not found")+ }+ if err := h.repo.Delete(rule.ID); err != nil {+ return c.AbortInternalServerError("failed to delete rule")+ }+ h.log(c, "form.rule_deleted", fmt.Sprintf("Rule %q deleted from form %s", rule.Name, form.Name), form, rule)+ return noContent(c)+}++func (h *FormRuleHandler) Reorder(c *okapi.Context, req *ReorderFormRulesRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("insufficient workspace permissions", err)+ }+ form, err := h.form(c, req.ID)+ if err != nil {+ return c.AbortNotFound("form not found")+ }+ if err := h.repo.Reorder(form.ID, req.Body.IDs); err != nil {+ return c.AbortBadRequest(err.Error())+ }+ rules, err := h.repo.ListByForm(form.ID)+ if err != nil {+ return c.AbortInternalServerError("failed to list rules")+ }+ h.log(c, "form.rules_reordered", fmt.Sprintf("Rules reordered on form %s", form.Name), form, nil)+ return ok(c, rules)+}++// Test replays recent submissions through the rules without acting on them.+func (h *FormRuleHandler) Test(c *okapi.Context, req *TestFormRulesRequest) error {+ form, err := h.form(c, req.ID)+ if err != nil {+ return c.AbortNotFound("form not found")+ }+ var rules []models.FormRule+ if req.Body.Rules != nil {+ for i, b := range req.Body.Rules {+ rule, err := h.checked(c, form, b)+ if rule == nil {+ return err+ }+ rule.UUID, rule.Position = fmt.Sprintf("draft-%d", i), i+ rules = append(rules, *rule)+ }+ } else if rules, err = h.repo.ListByForm(form.ID); err != nil {+ return c.AbortInternalServerError("failed to list rules")+ }++ limit := req.Body.Limit+ if limit <= 0 {+ limit = 100+ }+ if limit > 200 {+ limit = 200+ }+ sample, _, err := h.messageRepo.FindByScopeFiltered(getScope(c),+ repositories.MessageFilterQuery{FormID: form.ID, SubmissionsOnly: true}, limit, 0)+ if err != nil {+ return c.AbortInternalServerError("failed to load submissions")+ }++ index := make(map[string]int, len(rules))+ resp := RuleTestResult{Scanned: len(sample), Rules: make([]RuleTestCount, len(rules)), Samples: []RuleTestSample{}}+ for i, r := range rules {+ index[r.UUID] = i+ resp.Rules[i] = RuleTestCount{Index: i, Name: r.Name}+ }+ for i := range sample {+ m := &sample[i]+ out := formrules.Evaluate(rules, formrules.FactsFor(m, form))+ if len(out.Matched) == 0 {+ continue+ }+ resp.Matched+++ hit := make([]int, 0, len(out.Matched))+ for _, id := range out.Matched {+ resp.Rules[index[id]].Matches+++ hit = append(hit, index[id])+ }+ if len(resp.Samples) < 20 {+ resp.Samples = append(resp.Samples, RuleTestSample{+ MessageUUID: m.UUID, Sender: senderOf(m), Subject: m.Subject,+ ReceivedAt: m.CreatedAt, Matched: hit, Outcome: out,+ })+ }+ }+ return ok(c, resp)+}++func senderOf(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+ }+ return m.SenderName+}++func (h *FormRuleHandler) log(c *okapi.Context, action, message string, form *models.Form, rule *models.FormRule) {+ if h.audit == nil {+ return+ }+ meta := map[string]any{metaFormID: form.ID}+ if rule != nil {+ meta["rule_id"], meta["rule_uuid"] = rule.ID, rule.UUID+ }+ h.audit.LogCtx(c, action, message, meta)+}diff --git a/internal/handlers/form_submission_handler.go b/internal/handlers/form_submission_handler.goindex 6dead25..75a73a0 100644--- a/internal/handlers/form_submission_handler.go+++ b/internal/handlers/form_submission_handler.go@@ -124,7 +124,7 @@ func parseFieldFilters(defs models.FieldDefs, query url.Values) (map[string]any,}var def *models.FieldDeffor i := range defs {- if defs[i].Key == key {+ if defs[i].Key == key && !defs[i].IsSection() {def = &defs[i]break}@@ -280,7 +280,7 @@ func tagsOf(m *models.Message) []string {func exportColumns(defs models.FieldDefs, showPII bool) (cols []models.FieldDef, withheld int) {for _, archived := range []bool{false, true} {for _, f := range defs {- if f.Archived != archived {+ if f.Archived != archived || f.IsSection() {continue}if f.PII && !showPII {diff --git a/internal/handlers/message_handler.go b/internal/handlers/message_handler.goindex c2a1211..7fdc621 100644--- a/internal/handlers/message_handler.go+++ b/internal/handlers/message_handler.go@@ -54,6 +54,8 @@ type MessageHandler struct {bus *eventbus.EventBusrealtime realtime.Busaudit *audit.Logger+ teamRepo *repositories.TeamRepository+ ruleRepo *repositories.FormRuleRepository}func NewMessageHandler(@@ -72,6 +74,12 @@ func (h *MessageHandler) SetEventBus(b *eventbus.EventBus) { h.bus = b }// SetRealtime configures the cross-process bus behind the live message stream.func (h *MessageHandler) SetRealtime(b realtime.Bus) { h.realtime = b }+// SetRouting lets the inbox filter by team and name the rules that routed a+// submission.+func (h *MessageHandler) SetRouting(teams *repositories.TeamRepository, rules *repositories.FormRuleRepository) {+ h.teamRepo, h.ruleRepo = teams, rules+}+type MessageListRequest struct {Page int `query:"page" default:"0"`Size int `query:"size" default:"20"`@@ -85,6 +93,15 @@ type MessageListRequest struct {Assigned int `query:"assigned_to"`Tag string `query:"tag" doc:"Only messages carrying this tag"`Priority string `query:"priority" enum:"low,normal,high,urgent"`+ TeamID int `query:"team_id" doc:"Only messages routed to this team"`+ Mine bool `query:"mine" doc:"Only messages assigned to the caller or routed to one of their teams"`+}++type UpdateMessageTeamRequest struct {+ ID string `param:"id"`+ Body struct {+ TeamID *uint `json:"team_id" doc:"A team of this workspace, or null to clear"`+ } `json:"body"`}type MessageIDRequest struct {@@ -180,6 +197,18 @@ func (h *MessageHandler) List(c *okapi.Context, req *MessageListRequest) error {return c.AbortBadRequest(err.Error())}filter.Tags = tags+ if req.TeamID > 0 {+ filter.TeamID = uint(req.TeamID)+ }+ if req.Mine {+ mine := &repositories.MineFilter{UserID: uint(c.GetInt("user_id"))}+ if scope := getScope(c); h.teamRepo != nil && scope.WorkspaceID != nil {+ mine.TeamIDs, _ = h.teamRepo.IDsForUser(*scope.WorkspaceID, mine.UserID)+ }+ filter.Mine = mine+ // Your own work includes collect-mode responses routed to you.+ filter.InboxOnly = false+ }if req.Assigned > 0 {assigned := uint(req.Assigned)filter.Assigned = &assigned@@ -208,6 +237,7 @@ func (h *MessageHandler) Get(c *okapi.Context, req *MessageIDRequest) error {return c.AbortNotFound("message not found")}hydrate(msg)+ h.nameRules(msg)if msg.ReadAt == nil {now := time.Now()@@ -398,6 +428,58 @@ func (h *MessageHandler) UpdatePriority(c *okapi.Context, req *UpdateMessagePrioreturn ok(c, msg)}+// UpdateTeam routes a message to a team by hand, or clears its team.+func (h *MessageHandler) UpdateTeam(c *okapi.Context, req *UpdateMessageTeamRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("insufficient workspace permissions", err)+ }+ scope := getScope(c)+ msg, err := h.repo.FindByUUIDForScope(scope, req.ID)+ if err != nil {+ return c.AbortNotFound("message not found")+ }+ if req.Body.TeamID != nil {+ if h.teamRepo == nil || scope.WorkspaceID == nil {+ return c.AbortBadRequest("teams are not available")+ }+ team, err := h.teamRepo.FindForWorkspace(*scope.WorkspaceID, *req.Body.TeamID)+ if err != nil {+ return c.AbortBadRequest("choose one of this workspace's teams")+ }+ msg.Team = &models.TeamRef{ID: team.ID, Name: team.Name}+ } else {+ msg.Team = nil+ }+ now := time.Now()+ msg.TeamID, msg.UpdatedAt = req.Body.TeamID, &now+ if err := h.repo.UpdateFields(msg.ID, map[string]any{"team_id": req.Body.TeamID, "updated_at": now}); err != nil {+ return c.AbortInternalServerError("failed to update message")+ }+ hydrate(msg)+ h.nameRules(msg)+ h.publish(c, messages.EventUpdated, msg)+ return ok(c, msg)+}++// nameRules fills RoutedBy from the rules that matched, so the dashboard can+// show why a submission went where it did. A deleted rule keeps its ID.+func (h *MessageHandler) nameRules(msg *models.Message) {+ if h.ruleRepo == nil || len(msg.MatchedRules) == 0 {+ return+ }+ names, err := h.ruleRepo.NamesByUUID(msg.MatchedRules)+ if err != nil {+ return+ }+ for _, id := range msg.MatchedRules {+ name := names[id]+ if name == "" {+ name = "Deleted rule"+ }+ msg.RoutedBy = append(msg.RoutedBy, models.RuleRef{UUID: id, Name: name})+ }+}+// 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)diff --git a/internal/handlers/team_handler.go b/internal/handlers/team_handler.gonew file mode 100644index 0000000..40e1e59--- /dev/null+++ b/internal/handlers/team_handler.go@@ -0,0 +1,223 @@+// 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 handlers++import (+ "fmt"+ "net/mail"+ "strings"+ "time"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/audit"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/okapi"+)++// TeamHandler manages a workspace's teams. Any member can list them (the+// inbox filters by team); changing them is tenant administration.+type TeamHandler struct {+ repo *repositories.TeamRepository+ ruleRepo *repositories.FormRuleRepository+ workspaceRepo *repositories.WorkspaceRepository+ audit *audit.Logger+}++func NewTeamHandler(repo *repositories.TeamRepository, ruleRepo *repositories.FormRuleRepository, workspaceRepo *repositories.WorkspaceRepository, auditLogger *audit.Logger) *TeamHandler {+ return &TeamHandler{repo: repo, ruleRepo: ruleRepo, workspaceRepo: workspaceRepo, audit: auditLogger}+}++type TeamBody struct {+ Name string `json:"name" required:"true"`+ Email string `json:"email" doc:"Optional shared address notified along with the members, such as [email protected]"`+ UserIDs []uint `json:"user_ids" doc:"Members; each must belong to the workspace"`+}++type CreateTeamRequest struct {+ Body TeamBody `json:"body"`+}++type UpdateTeamRequest struct {+ ID int `param:"id"`+ Body TeamBody `json:"body"`+}++type TeamIDRequest struct {+ ID int `param:"id"`+}++// requireManage allows workspace owners and admins: teams decide who is+// sent submissions.+func requireManage(c *okapi.Context) error {+ role := workspaceRole(c)+ if role != "" && !role.CanManageMembers() {+ return errForbidden+ }+ return nil+}++func (h *TeamHandler) workspace(c *okapi.Context) (uint, error) {+ scope := getScope(c)+ if scope.WorkspaceID == nil {+ return 0, c.AbortBadRequest("a workspace is required")+ }+ return *scope.WorkspaceID, nil+}++// apply validates a team body onto team and returns the member IDs.+func (h *TeamHandler) apply(c *okapi.Context, workspaceID uint, team *models.Team, b TeamBody) ([]uint, error) {+ name := strings.Join(strings.Fields(b.Name), " ")+ if name == "" || len([]rune(name)) > 80 {+ return nil, c.AbortBadRequest("a team needs a name of at most 80 characters")+ }+ if h.repo.NameTaken(workspaceID, name, team.ID) {+ return nil, c.AbortConflict("a team with that name already exists")+ }+ email := strings.ToLower(strings.TrimSpace(b.Email))+ if email != "" {+ if addr, err := mail.ParseAddress(email); err != nil || addr.Address != email {+ return nil, c.AbortBadRequest(fmt.Sprintf("%q is not an email address", b.Email))+ }+ }+ members, err := h.workspaceRepo.ListMembers(workspaceID)+ if err != nil {+ return nil, c.AbortInternalServerError("failed to load members")+ }+ inWorkspace := map[uint]bool{}+ for _, m := range members {+ inWorkspace[m.UserID] = true+ }+ seen := map[uint]bool{}+ ids := make([]uint, 0, len(b.UserIDs))+ for _, id := range b.UserIDs {+ if !inWorkspace[id] {+ return nil, c.AbortBadRequest(fmt.Sprintf("user %d is not a member of this workspace", id))+ }+ if !seen[id] {+ seen[id] = true+ ids = append(ids, id)+ }+ }+ team.Name, team.Email = name, email+ return ids, nil+}++func (h *TeamHandler) List(c *okapi.Context) error {+ ws, err := h.workspace(c)+ if ws == 0 {+ return err+ }+ teams, err := h.repo.ListByWorkspace(ws)+ if err != nil {+ return c.AbortInternalServerError("failed to list teams")+ }+ if teams == nil {+ teams = []models.Team{}+ }+ return ok(c, teams)+}++func (h *TeamHandler) Create(c *okapi.Context, req *CreateTeamRequest) error {+ if err := requireManage(c); err != nil {+ return c.AbortForbidden("only workspace owners and admins can manage teams", err)+ }+ ws, err := h.workspace(c)+ if ws == 0 {+ return err+ }+ team := &models.Team{WorkspaceID: &ws}+ ids, err := h.apply(c, ws, team, req.Body)+ if ids == nil {+ return err+ }+ if err := h.repo.Create(team); err != nil {+ return c.AbortInternalServerError("failed to create team")+ }+ if err := h.repo.SetMembers(team.ID, ids); err != nil {+ return c.AbortInternalServerError("failed to set team members")+ }+ h.log(c, ws, "team.created", fmt.Sprintf("Team %s created", team.Name), team, len(ids))+ saved, _ := h.repo.FindForWorkspace(ws, team.ID)+ return created(c, saved)+}++func (h *TeamHandler) Update(c *okapi.Context, req *UpdateTeamRequest) error {+ if err := requireManage(c); err != nil {+ return c.AbortForbidden("only workspace owners and admins can manage teams", err)+ }+ ws, err := h.workspace(c)+ if ws == 0 {+ return err+ }+ team, err := h.repo.FindForWorkspace(ws, uint(req.ID))+ if err != nil {+ return c.AbortNotFound("team not found")+ }+ ids, err := h.apply(c, ws, team, req.Body)+ if ids == nil {+ return err+ }+ now := time.Now()+ team.UpdatedAt = &now+ if err := h.repo.Update(team); err != nil {+ return c.AbortInternalServerError("failed to update team")+ }+ if err := h.repo.SetMembers(team.ID, ids); err != nil {+ return c.AbortInternalServerError("failed to set team members")+ }+ h.log(c, ws, "team.updated", fmt.Sprintf("Team %s updated", team.Name), team, len(ids))+ saved, _ := h.repo.FindForWorkspace(ws, team.ID)+ return ok(c, saved)+}++// Delete removes a team no rule points at; a rule that did would silently+// stop notifying anyone.+func (h *TeamHandler) Delete(c *okapi.Context, req *TeamIDRequest) error {+ if err := requireManage(c); err != nil {+ return c.AbortForbidden("only workspace owners and admins can manage teams", err)+ }+ ws, err := h.workspace(c)+ if ws == 0 {+ return err+ }+ team, err := h.repo.FindForWorkspace(ws, uint(req.ID))+ if err != nil {+ return c.AbortNotFound("team not found")+ }+ if names, err := h.ruleRepo.UsingTeam(ws, team.ID); err == nil && len(names) > 0 {+ return c.AbortConflict(fmt.Sprintf("routing rules use this team: %s. Change them first.", strings.Join(names, ", ")))+ }+ if err := h.repo.Delete(team.ID); err != nil {+ return c.AbortInternalServerError("failed to delete team")+ }+ h.log(c, ws, "team.deleted", fmt.Sprintf("Team %s deleted", team.Name), team, -1)+ return noContent(c)+}++func (h *TeamHandler) log(c *okapi.Context, ws uint, action, message string, team *models.Team, members int) {+ if h.audit == nil {+ return+ }+ meta := map[string]any{"team_id": team.ID, "team": team.Name}+ if members >= 0 {+ meta["members"] = members+ }+ h.audit.LogCtxScoped(c, ws, action, message, meta)+}diff --git a/internal/middlewares/message_scope_test.go b/internal/middlewares/message_scope_test.goindex 77c749f..4b097df 100644--- a/internal/middlewares/message_scope_test.go+++ b/internal/middlewares/message_scope_test.go@@ -52,6 +52,13 @@ func TestWorkspaceScopeForMessageRoutes(t *testing.T) {{http.MethodGet, "/api/v1/workspaces/current/form-submissions/export", models.ScopeRead},{http.MethodGet, "/api/v1/workspaces/current/message-filters", models.ScopeAdmin},++ // Rules and teams decide who is sent submissions: tenant administration.+ {http.MethodGet, "/api/v1/workspaces/current/forms/1/rules", models.ScopeAdmin},+ {http.MethodPost, "/api/v1/workspaces/current/forms/1/rules/test", models.ScopeAdmin},+ {http.MethodGet, "/api/v1/workspaces/current/teams", models.ScopeAdmin},+ {http.MethodPost, "/api/v1/workspaces/current/teams", models.ScopeAdmin},+ {http.MethodPut, "/api/v1/workspaces/current/messages/abc/team", models.ScopeWrite},{http.MethodPost, "/api/v1/workspaces/current/message-filters", models.ScopeAdmin},}diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.goindex 420a72a..e105361 100644--- a/internal/middlewares/middleware.go+++ b/internal/middlewares/middleware.go@@ -301,6 +301,7 @@ var tenantAdminPaths = []string{"/plan","/forms","/message-filters",+ "/teams","/gdpr/",}diff --git a/internal/models/form.go b/internal/models/form.goindex 2fd6453..ef016e4 100644--- a/internal/models/form.go+++ b/internal/models/form.go@@ -142,7 +142,7 @@ func (f *Form) Closed(now time.Time) bool {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 }+func (f *Form) HasSchema() bool { return f != nil && len(f.Fields.Active().Questions()) > 0 }// UnknownFieldsPolicy returns the policy for undeclared keys, keep by default.func (f *Form) UnknownFieldsPolicy() UnknownFieldsPolicy {diff --git a/internal/models/form_field.go b/internal/models/form_field.goindex c35f107..0d25165 100644--- a/internal/models/form_field.go+++ b/internal/models/form_field.go@@ -43,8 +43,15 @@ const (FieldScale FieldType = "scale"FieldRating FieldType = "rating"FieldHidden FieldType = "hidden"+ // FieldSection is not a question: it starts a new page of the form. The+ // questions after it, up to the next section, are that page.+ FieldSection FieldType = "section")+// GotoSubmit is a branch target that ends the form: the respondent submits+// from the page they are on.+const GotoSubmit = "submit"+// FieldRole marks the field that carries one of a message's summary values,// replacing the key-name guessing of messages.Extract.type FieldRole string@@ -83,6 +90,10 @@ const (type FieldOption struct {Value string `json:"value"`Label string `json:"label,omitempty"`+ // Goto, on a single-choice question, is where choosing this option leads+ // after its page: a later section's key, or GotoSubmit. Empty follows+ // the page's own next.+ Goto string `json:"goto,omitempty"`}// FieldDef declares one question of a form. A key, once saved, can be@@ -109,8 +120,16 @@ type FieldDef struct {Placeholder string `json:"placeholder,omitempty"`Help string `json:"help,omitempty"`Archived bool `json:"archived,omitempty"`++ // Next, on a section, is where its page leads when no answer branches: a+ // later section's key, or GotoSubmit. Empty continues to the next page.+ Next string `json:"next,omitempty"`}+// IsSection reports whether the entry starts a page rather than asking a+// question.+func (f *FieldDef) IsSection() bool { return f.Type == FieldSection }+// FieldDefs is a form's schema, stored as jsonb. Nil means the form has no// schema and accepts any fields, as before schemas existed.type FieldDefs []FieldDef@@ -142,6 +161,18 @@ func (d FieldDefs) Active() FieldDefs {return out}+// Questions returns the entries that ask something, archived ones included,+// leaving out sections.+func (d FieldDefs) Questions() FieldDefs {+ out := make(FieldDefs, 0, len(d))+ for _, f := range d {+ if !f.IsSection() {+ out = append(out, f)+ }+ }+ return out+}+// SubmissionData is a submission's typed answers keyed by field key, stored// as jsonb. Numbers, booleans and multi-select arrays keep their JSON type.type SubmissionData map[string]anydiff --git a/internal/models/form_rule.go b/internal/models/form_rule.gonew file mode 100644index 0000000..1ba3532--- /dev/null+++ b/internal/models/form_rule.go@@ -0,0 +1,171 @@+// 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 models++import (+ "database/sql/driver"+ "encoding/json"+ "time"++ "github.com/lib/pq"+ "gorm.io/gorm"+)++// RuleMatch says whether a rule needs all of its conditions or any one.+type RuleMatch string++const (+ RuleMatchAll RuleMatch = "all"+ RuleMatchAny RuleMatch = "any"+)++// RuleCondition tests one answer, or one built-in fact named with a leading+// $ ($origin, $referer, $sender_email, $spam_score, $status).+type RuleCondition struct {+ Field string `json:"field"`+ Op string `json:"op"`+ Value any `json:"value,omitempty"`+}++// Rule action types. None of them reads a destination from submission data:+// every address, member, team and webhook is chosen by an admin.+const (+ ActionNotifyEmails = "notify_emails"+ ActionNotifyMembers = "notify_members"+ ActionNotifyTeam = "notify_team"+ ActionAssignMember = "assign_member"+ ActionAssignTeam = "assign_team"+ ActionAddTags = "add_tags"+ ActionSetPriority = "set_priority"+ ActionWebhook = "webhook"+ ActionSuppressDefault = "suppress_default"+)++type RuleAction struct {+ Type string `json:"type"`+ Emails []string `json:"emails,omitempty"`+ UserIDs []uint `json:"user_ids,omitempty"`+ TeamID *uint `json:"team_id,omitempty"`+ Tags []string `json:"tags,omitempty"`+ Priority string `json:"priority,omitempty"`+ WebhookID *uint `json:"webhook_id,omitempty"`+}++type RuleConditions []RuleCondition++func (r RuleConditions) Value() (driver.Value, error) {+ if r == nil {+ return "[]", nil+ }+ return json.Marshal(r)+}++func (r *RuleConditions) Scan(value any) error {+ raw, err := jsonBytes(value)+ if err != nil || raw == nil {+ *r = nil+ return err+ }+ return json.Unmarshal(raw, r)+}++type RuleActions []RuleAction++func (r RuleActions) Value() (driver.Value, error) {+ if r == nil {+ return "[]", nil+ }+ return json.Marshal(r)+}++func (r *RuleActions) Scan(value any) error {+ raw, err := jsonBytes(value)+ if err != nil || raw == nil {+ *r = nil+ return err+ }+ return json.Unmarshal(raw, r)+}++// FormRule routes a form's submissions: when its conditions hold, its+// actions apply. Rules run in Position order and every match applies, unless+// a matching rule has Stop set.+type FormRule struct {+ ID uint `json:"id" gorm:"primaryKey"`+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index;not null"`+ FormID uint `json:"form_id" gorm:"index;not null"`+ Name string `json:"name" gorm:"not null"`+ Position int `json:"position" gorm:"not null;default:0"`+ Enabled bool `json:"enabled" gorm:"default:true;not null"`+ Match RuleMatch `json:"match" gorm:"type:varchar(8);default:'all';not null"`+ Conditions RuleConditions `json:"conditions" gorm:"type:jsonb;not null"`+ Actions RuleActions `json:"actions" gorm:"type:jsonb;not null"`+ Stop bool `json:"stop" gorm:"default:false;not null"`++ HitCount int64 `json:"hit_count" gorm:"default:0;not null"`+ LastHitAt *time.Time `json:"last_hit_at,omitempty"`+ LastEditedByID *uint `json:"last_edited_by_id,omitempty"`++ CreatedAt time.Time `json:"created_at"`+ UpdatedAt *time.Time `json:"updated_at,omitempty"`++ Form *Form `json:"-" gorm:"foreignKey:FormID;constraint:OnDelete:CASCADE"`+}++// Team is a named group of workspace members that rules can notify or+// assign submissions to, with an optional shared address.+type Team struct {+ ID uint `json:"id" gorm:"primaryKey"`+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index;not null"`+ Name string `json:"name" gorm:"not null"`+ Email string `json:"email"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt *time.Time `json:"updated_at,omitempty"`+ DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`++ Members []TeamMember `json:"members,omitempty" gorm:"foreignKey:TeamID;constraint:OnDelete:CASCADE"`+}++// TeamMember puts a workspace member on a team. Removing someone from the+// workspace removes their team memberships with it.+type TeamMember struct {+ TeamID uint `json:"team_id" gorm:"primaryKey"`+ UserID uint `json:"user_id" gorm:"primaryKey"`+ User *ActorRef `json:"user,omitempty" gorm:"->;foreignKey:UserID;references:ID;constraint:false"`+}++// TeamRef is the small view of a team embedded in a message.+type TeamRef struct {+ ID uint `json:"id"`+ Name string `json:"name"`+}++func (TeamRef) TableName() string { return "teams" }++// RuleRef names a rule that routed a submission.+type RuleRef struct {+ UUID string `json:"uuid"`+ Name string `json:"name"`+}++// RuleUUIDs is a message's matched rules.+type RuleUUIDs = pq.StringArraydiff --git a/internal/models/message.go b/internal/models/message.goindex 3d2ed9d..6fcfaa5 100644--- a/internal/models/message.go+++ b/internal/models/message.go@@ -105,10 +105,17 @@ 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 and Priority are set by operators and by routing rules.Tags pq.StringArray `json:"tags" gorm:"type:text[]"`Priority MessagePriority `json:"priority" gorm:"type:varchar(8);default:'normal';not null"`+ // TeamID is the team the submission is routed to. MatchedRules lists the+ // rules that routed it (UUIDs), for "why did this go here". RoutedAt+ // records that the rules ran, so a retried task never applies them twice.+ TeamID *uint `json:"team_id,omitempty" gorm:"index"`+ MatchedRules pq.StringArray `json:"matched_rules,omitempty" gorm:"type:text[]"`+ RoutedAt *time.Time `json:"-"`+ThreadToken string `json:"-" gorm:"uniqueIndex"`RootMessageID string `json:"-"`DedupHash string `json:"-" gorm:"index"`@@ -134,9 +141,12 @@ type Message struct {// GORM creates these foreign keys whatever the tag (only "constraint:-"// skips one), so declare the cascade the schema relies on: deleting a form// or a message must take its messages or replies with it.- Form *Form `json:"form,omitempty" gorm:"foreignKey:FormID;constraint:OnDelete:CASCADE"`- AssignedTo *ActorRef `json:"assigned_to,omitempty" gorm:"->;foreignKey:AssignedToID;references:ID;constraint:false"`- Replies []MessageReply `json:"replies,omitempty" gorm:"foreignKey:MessageID;constraint:OnDelete:CASCADE"`+ Form *Form `json:"form,omitempty" gorm:"foreignKey:FormID;constraint:OnDelete:CASCADE"`+ AssignedTo *ActorRef `json:"assigned_to,omitempty" gorm:"->;foreignKey:AssignedToID;references:ID;constraint:false"`+ Team *TeamRef `json:"team,omitempty" gorm:"->;foreignKey:TeamID;references:ID;constraint:false"`+ // RoutedBy names MatchedRules for display; filled by the handler.+ RoutedBy []RuleRef `json:"routed_by,omitempty" gorm:"-"`+ Replies []MessageReply `json:"replies,omitempty" gorm:"foreignKey:MessageID;constraint:OnDelete:CASCADE"`}func (m *Message) IsSpam() bool {diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.goindex fca8143..c3f2eae 100644--- a/internal/routes/message_routes.go+++ b/internal/routes/message_routes.go@@ -330,6 +330,18 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {okapi.DocPathParam("id", "string", "Message UUID"),},},+ {+ Method: http.MethodPut,+ Path: "/messages/{id}/team",+ Handler: okapi.H(r.h.message.UpdateTeam),+ Group: opsGroup,+ Summary: "Route a message to a team",+ Request: &handlers.UpdateMessageTeamRequest{},+ Response: &dto.Response[models.Message]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "string", "Message UUID"),+ },+ },{Method: http.MethodGet,Path: "/message-tags",@@ -432,5 +444,119 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {Request: &handlers.TestMessageFilterRequest{},Response: &dto.Response[handlers.TestMessageFilterResponse]{},},++ // Routing rules: form configuration, so admin scope like /forms.+ {+ Method: http.MethodGet,+ Path: "/forms/{id:int}/rules",+ Handler: okapi.H(r.h.formRule.List),+ Group: opsGroup,+ Summary: "List a form's routing rules",+ Response: &dto.Response[[]models.FormRule]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},+ },+ {+ Method: http.MethodPost,+ Path: "/forms/{id:int}/rules",+ Handler: okapi.H(r.h.formRule.Create),+ Group: opsGroup,+ Summary: "Create a routing rule",+ Description: "Appends a rule. Conditions test answers or built-in facts ($origin, $referer, $sender_email, $spam_score, $status); actions notify, assign, tag, prioritize or call a webhook. Every destination is one an admin chose: addresses typed here, or this workspace's members, teams and webhooks.",+ Request: &handlers.CreateFormRuleRequest{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Form ID"),+ okapi.DocResponse(201, &dto.Response[models.FormRule]{}),+ okapi.DocResponse(400, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodPut,+ Path: "/forms/{id:int}/rules/order",+ Handler: okapi.H(r.h.formRule.Reorder),+ Group: opsGroup,+ Summary: "Reorder a form's routing rules",+ Request: &handlers.ReorderFormRulesRequest{},+ Response: &dto.Response[[]models.FormRule]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},+ },+ {+ Method: http.MethodPost,+ Path: "/forms/{id:int}/rules/test",+ Handler: okapi.H(r.h.formRule.Test),+ Group: opsGroup,+ Summary: "Dry-run routing rules",+ Description: "Replays up to 200 recent submissions through the saved rules, or through draft rules sent in the body, and reports what they would have done. Nothing is sent or changed.",+ Request: &handlers.TestFormRulesRequest{},+ Response: &dto.Response[handlers.RuleTestResult]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},+ },+ {+ Method: http.MethodPut,+ Path: "/forms/{id:int}/rules/{rule_id:int}",+ Handler: okapi.H(r.h.formRule.Update),+ Group: opsGroup,+ Summary: "Update a routing rule",+ Request: &handlers.UpdateFormRuleRequest{},+ Response: &dto.Response[models.FormRule]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Form ID"),+ okapi.DocPathParam("rule_id", "integer", "Rule ID"),+ },+ },+ {+ Method: http.MethodDelete,+ Path: "/forms/{id:int}/rules/{rule_id:int}",+ Handler: okapi.H(r.h.formRule.Delete),+ Group: opsGroup,+ Summary: "Delete a routing rule",+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Form ID"),+ okapi.DocPathParam("rule_id", "integer", "Rule ID"),+ },+ },++ // Teams: tenant administration (admin scope), listed for every member.+ {+ Method: http.MethodGet,+ Path: "/teams",+ Handler: r.h.team.List,+ Group: opsGroup,+ Summary: "List teams",+ Response: &dto.Response[[]models.Team]{},+ },+ {+ Method: http.MethodPost,+ Path: "/teams",+ Handler: okapi.H(r.h.team.Create),+ Group: opsGroup,+ Summary: "Create a team",+ Request: &handlers.CreateTeamRequest{},+ Options: []okapi.RouteOption{+ okapi.DocResponse(201, &dto.Response[models.Team]{}),+ okapi.DocResponse(409, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodPut,+ Path: "/teams/{id:int}",+ Handler: okapi.H(r.h.team.Update),+ Group: opsGroup,+ Summary: "Update a team and its members",+ Request: &handlers.UpdateTeamRequest{},+ Response: &dto.Response[models.Team]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Team ID")},+ },+ {+ Method: http.MethodDelete,+ Path: "/teams/{id:int}",+ Handler: okapi.H(r.h.team.Delete),+ Group: opsGroup,+ Summary: "Delete a team",+ Description: "Refused while a routing rule notifies or assigns the team. Submissions routed to it keep no team.",+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Team ID"),+ okapi.DocResponse(409, &dto.ErrorResponseBody{}),+ },+ },}}diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 3cabe82..82e5c9f 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -139,6 +139,8 @@ type routerHandlers struct {form *handlers.FormHandlermessage *handlers.MessageHandlermessageFilter *handlers.MessageFilterHandler+ formRule *handlers.FormRuleHandler+ team *handlers.TeamHandlerformIngest *handlers.FormIngestHandler}@@ -472,6 +474,11 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cr.h.message.SetEventBus(bus)r.h.message.SetRealtime(realtime.NewRedis(redisClient))r.h.messageFilter = handlers.NewMessageFilterHandler(messageFilterRepo, messageRepo, formRepo, messageSvc.Scanner())+ ruleRepo := repositories.NewFormRuleRepository(db)+ teamRepo := repositories.NewTeamRepository(db)+ r.h.formRule = handlers.NewFormRuleHandler(ruleRepo, formRepo, messageRepo, teamRepo, workspaceRepo, webhookRepo, auditLogger)+ r.h.team = handlers.NewTeamHandler(teamRepo, ruleRepo, workspaceRepo, auditLogger)+ r.h.message.SetRouting(teamRepo, ruleRepo)r.h.formIngest = handlers.NewFormIngestHandler(messageSvc,inbound.NewIPRateLimiter(cfg.MessagesIPRateLimit, time.Duration(cfg.MessagesIPRateWindow)*time.Second),diff --git a/internal/services/formrules/check.go b/internal/services/formrules/check.gonew file mode 100644index 0000000..49b2495--- /dev/null+++ b/internal/services/formrules/check.go@@ -0,0 +1,327 @@+// 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 formrules++import (+ "fmt"+ "net/mail"+ "regexp"+ "strconv"+ "strings"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/messages"+)++const (+ maxConditions = 20+ maxActions = 20+ maxRuleEmails = 20+ maxPatternLen = 256+ maxRuleNameLen = 120+)++// Destinations is what a rule may point at: this workspace's members, teams+// and webhooks. Nothing else, and nothing from submission data.+type Destinations struct {+ Members map[uint]bool+ Teams map[uint]bool+ Webhooks map[uint]bool+}++var schemalessKey = regexp.MustCompile(`^[a-z0-9_.\-\[\]]{1,64}$`)++var orderedTypes = map[models.FieldType]bool{+ models.FieldNumber: true, models.FieldScale: true, models.FieldRating: true,+ models.FieldDate: true, models.FieldTime: true,+}++var textTypes = map[models.FieldType]bool{+ models.FieldText: true, models.FieldTextarea: true, models.FieldEmail: true,+ models.FieldPhone: true, models.FieldURL: true, models.FieldHidden: true,+}++// Check validates a rule about to be saved for form, and normalizes it:+// trimmed values, lowercased tags and addresses, actions stripped of+// settings their type does not use.+func Check(r *models.FormRule, form *models.Form, d Destinations) error {+ r.Name = strings.TrimSpace(r.Name)+ if r.Name == "" || len([]rune(r.Name)) > maxRuleNameLen {+ return fmt.Errorf("a rule needs a name of at most %d characters", maxRuleNameLen)+ }+ switch r.Match {+ case "":+ r.Match = models.RuleMatchAll+ case models.RuleMatchAll, models.RuleMatchAny:+ default:+ return fmt.Errorf("match must be all or any")+ }+ if len(r.Conditions) > maxConditions {+ return fmt.Errorf("a rule can have at most %d conditions", maxConditions)+ }+ for i := range r.Conditions {+ if err := checkCondition(&r.Conditions[i], form); err != nil {+ return fmt.Errorf("condition %d: %w", i+1, err)+ }+ }+ if len(r.Actions) == 0 || len(r.Actions) > maxActions {+ return fmt.Errorf("a rule needs between 1 and %d actions", maxActions)+ }+ for i := range r.Actions {+ clean, err := checkAction(r.Actions[i], d)+ if err != nil {+ return fmt.Errorf("action %d: %w", i+1, err)+ }+ r.Actions[i] = clean+ }+ return nil+}++func checkCondition(c *models.RuleCondition, form *models.Form) error {+ c.Field = strings.TrimSpace(c.Field)+ var def *models.FieldDef+ switch c.Field {+ case FactOrigin, FactReferer, FactSenderEmail, FactSpamScore, FactStatus:+ default:+ if form.HasSchema() {+ for i := range form.Fields {+ if form.Fields[i].Key == c.Field && !form.Fields[i].IsSection() {+ def = &form.Fields[i]+ }+ }+ if def == nil {+ return fmt.Errorf("%q is not a question on this form", c.Field)+ }+ if def.Archived {+ return fmt.Errorf("question %q is archived, so the rule would never match", c.Field)+ }+ } else {+ c.Field = strings.ToLower(c.Field)+ if !schemalessKey.MatchString(c.Field) {+ return fmt.Errorf("%q is not a field name", c.Field)+ }+ }+ }++ switch c.Op {+ case "exists", "not_exists":+ c.Value = nil+ return nil+ case "eq", "neq":+ s, err := single(c.Value)+ if err != nil {+ return err+ }+ c.Value = s+ return checkValues(c, def, []string{s})+ case "in", "not_in":+ list := wanted(c.Value)+ clean := make([]string, 0, len(list))+ for _, v := range list {+ if v = strings.TrimSpace(v); v != "" {+ clean = append(clean, v)+ }+ }+ if len(clean) == 0 {+ return fmt.Errorf("%s needs at least one value", c.Op)+ }+ c.Value = clean+ return checkValues(c, def, clean)+ case "contains", "not_contains":+ s, err := single(c.Value)+ if err != nil {+ return err+ }+ c.Value = s+ if def != nil && !textTypes[def.Type] && def.Type != models.FieldMultiSelect {+ return fmt.Errorf("contains does not apply to a %s question", def.Type)+ }+ if def != nil && def.Type == models.FieldMultiSelect {+ return checkValues(c, def, []string{s})+ }+ return nil+ case "matches":+ s, err := single(c.Value)+ if err != nil {+ return err+ }+ if len(s) > maxPatternLen {+ return fmt.Errorf("the pattern is longer than %d characters", maxPatternLen)+ }+ if _, err := regexp.Compile(s); err != nil {+ return fmt.Errorf("the pattern does not compile: %v", err)+ }+ if def != nil && !textTypes[def.Type] {+ return fmt.Errorf("matches applies to text questions, not %s", def.Type)+ }+ c.Value = s+ return nil+ case "gt", "gte", "lt", "lte":+ s, err := single(c.Value)+ if err != nil {+ return err+ }+ c.Value = s+ _, numErr := strconv.ParseFloat(s, 64)+ switch {+ case c.Field == FactSpamScore:+ case def != nil && orderedTypes[def.Type]:+ if def.Type == models.FieldDate || def.Type == models.FieldTime {+ return checkValues(c, def, []string{s})+ }+ case def == nil && strings.HasPrefix(c.Field, "$"):+ return fmt.Errorf("%s cannot be compared with %s", c.Field, c.Op)+ case def != nil:+ return fmt.Errorf("%s only compares numbers, dates and times, not a %s question", c.Op, def.Type)+ }+ if numErr != nil {+ return fmt.Errorf("%q is not a number", s)+ }+ return nil+ }+ return fmt.Errorf("unknown operator %q", c.Op)+}++func single(v any) (string, error) {+ switch v.(type) {+ case nil:+ return "", fmt.Errorf("a value is required")+ case []any, []string:+ return "", fmt.Errorf("expected one value, not a list")+ }+ s := strings.TrimSpace(toString(v))+ if s == "" {+ return "", fmt.Errorf("a value is required")+ }+ return s, nil+}++// checkValues type-checks condition values against the question.+func checkValues(c *models.RuleCondition, def *models.FieldDef, values []string) error {+ if c.Field == FactStatus {+ for _, v := range values {+ if v != string(models.MessageStatusReceived) && v != string(models.MessageStatusFlagged) {+ return fmt.Errorf("$status is received or flagged for any routed submission, not %q", v)+ }+ }+ return nil+ }+ if def == nil {+ return nil+ }+ switch def.Type {+ case models.FieldSelect, models.FieldMultiSelect:+ for _, v := range values {+ found := false+ for _, o := range def.Options {+ found = found || o.Value == v+ }+ if !found {+ return fmt.Errorf("%q is not an option of %q", v, def.Key)+ }+ }+ case models.FieldCheckbox:+ for _, v := range values {+ if _, err := strconv.ParseBool(v); err != nil {+ return fmt.Errorf("a checkbox is true or false, not %q", v)+ }+ }+ case models.FieldNumber, models.FieldScale, models.FieldRating:+ for _, v := range values {+ if _, err := strconv.ParseFloat(v, 64); err != nil {+ return fmt.Errorf("%q is not a number", v)+ }+ }+ case models.FieldDate:+ for _, v := range values {+ if len(v) != 10 || v[4] != '-' || v[7] != '-' {+ return fmt.Errorf("a date is written YYYY-MM-DD, not %q", v)+ }+ }+ case models.FieldTime:+ for _, v := range values {+ if len(v) != 5 || v[2] != ':' {+ return fmt.Errorf("a time is written HH:MM, not %q", v)+ }+ }+ }+ return nil+}++// checkAction validates one action and returns it with only the settings its+// type uses.+func checkAction(a models.RuleAction, d Destinations) (models.RuleAction, error) {+ clean := models.RuleAction{Type: a.Type}+ switch a.Type {+ case models.ActionNotifyEmails:+ if len(a.Emails) == 0 || len(a.Emails) > maxRuleEmails {+ return clean, fmt.Errorf("give between 1 and %d addresses", maxRuleEmails)+ }+ for _, e := range a.Emails {+ e = strings.ToLower(strings.TrimSpace(e))+ addr, err := mail.ParseAddress(e)+ if err != nil || addr.Address != e || !strings.Contains(e[strings.LastIndex(e, "@")+1:], ".") {+ return clean, fmt.Errorf("%q is not an email address", e)+ }+ clean.Emails = append(clean.Emails, e)+ }+ case models.ActionNotifyMembers, models.ActionAssignMember:+ if len(a.UserIDs) == 0 {+ return clean, fmt.Errorf("choose a member")+ }+ if a.Type == models.ActionAssignMember && len(a.UserIDs) != 1 {+ return clean, fmt.Errorf("a submission is assigned to one member")+ }+ for _, id := range a.UserIDs {+ if !d.Members[id] {+ return clean, fmt.Errorf("user %d is not a member of this workspace", id)+ }+ }+ clean.UserIDs = a.UserIDs+ case models.ActionNotifyTeam, models.ActionAssignTeam:+ if a.TeamID == nil || !d.Teams[*a.TeamID] {+ return clean, fmt.Errorf("choose one of this workspace's teams")+ }+ clean.TeamID = a.TeamID+ case models.ActionAddTags:+ tags, err := messages.ApplyTags(nil, a.Tags, nil)+ if err != nil {+ return clean, err+ }+ if len(tags) == 0 {+ return clean, fmt.Errorf("give at least one tag")+ }+ clean.Tags = tags+ case models.ActionSetPriority:+ if !models.ValidPriority(models.MessagePriority(a.Priority)) {+ return clean, fmt.Errorf("priority must be low, normal, high or urgent")+ }+ clean.Priority = a.Priority+ case models.ActionWebhook:+ if a.WebhookID == nil || !d.Webhooks[*a.WebhookID] {+ return clean, fmt.Errorf("choose one of this workspace's webhooks")+ }+ clean.WebhookID = a.WebhookID+ case models.ActionSuppressDefault:+ default:+ return clean, fmt.Errorf("unknown action %q", a.Type)+ }+ return clean, nil+}diff --git a/internal/services/formrules/engine.go b/internal/services/formrules/engine.gonew file mode 100644index 0000000..276fd8d--- /dev/null+++ b/internal/services/formrules/engine.go@@ -0,0 +1,486 @@+// 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 formrules decides where a form submission goes. It is pure: no I/O+// and no clock, so the worker, the digest and the dry run all agree.+package formrules++import (+ "encoding/json"+ "regexp"+ "sort"+ "strconv"+ "strings"+ "sync"++ "github.com/goposta/posta/internal/models"+)++// Built-in facts a condition can test besides the answers.+const (+ FactOrigin = "$origin"+ FactReferer = "$referer"+ FactSenderEmail = "$sender_email"+ FactSpamScore = "$spam_score"+ FactStatus = "$status"+)++// Facts is what rules can see of a submission.+type Facts struct {+ Status models.MessageStatus+ SpamScore float64+ Origin string+ Referer string+ SenderEmail string+ // Data holds typed answers (forms with questions); Fields the submitted+ // values by key, for forms without.+ Data map[string]any+ Fields map[string]string+ // Schema types the answers, so "10" > "9" compares as numbers.+ Schema map[string]*models.FieldDef+}++// FactsFor reads the facts of a stored submission.+func FactsFor(msg *models.Message, form *models.Form) Facts {+ f := Facts{+ Status: msg.Status,+ SpamScore: msg.SpamScore,+ Origin: msg.Origin,+ Referer: msg.Referer,+ SenderEmail: msg.SenderEmail,+ Data: msg.Data,+ Fields: map[string]string{},+ Schema: map[string]*models.FieldDef{},+ }+ if msg.FieldsJSON != "" {+ var fields []models.MessageField+ if json.Unmarshal([]byte(msg.FieldsJSON), &fields) == nil {+ for _, fl := range fields {+ key := strings.ToLower(strings.TrimSpace(fl.Key))+ if _, seen := f.Fields[key]; !seen {+ f.Fields[key] = fl.Value+ }+ }+ }+ }+ if form != nil {+ for i := range form.Fields {+ if !form.Fields[i].IsSection() {+ f.Schema[form.Fields[i].Key] = &form.Fields[i]+ }+ }+ }+ return f+}++// Recipient is one destination of a notification, chosen by an admin.+type Recipient struct {+ Email string `json:"email,omitempty"`+ UserID uint `json:"user_id,omitempty"`+ TeamID uint `json:"team_id,omitempty"`+}++// Outcome is what the matching rules decided.+type Outcome struct {+ Notify []Recipient `json:"notify,omitempty"`+ AssignUser *uint `json:"assign_user,omitempty"`+ AssignTeam *uint `json:"assign_team,omitempty"`+ Tags []string `json:"tags,omitempty"`+ Priority string `json:"priority,omitempty"`+ Webhooks []uint `json:"webhooks,omitempty"`+ SuppressDefault bool `json:"suppress_default,omitempty"`+ Matched []string `json:"matched,omitempty"`+}++// Routable reports whether a submission is routed at all. Spam keeps the+// old behaviour: no notification, no routing.+func Routable(status models.MessageStatus) bool {+ return status == models.MessageStatusReceived || status == models.MessageStatusFlagged+}++// Ordered returns the enabled rules in evaluation order.+func Ordered(rules []models.FormRule) []models.FormRule {+ out := make([]models.FormRule, 0, len(rules))+ for _, r := range rules {+ if r.Enabled {+ out = append(out, r)+ }+ }+ sort.SliceStable(out, func(i, j int) bool {+ if out[i].Position != out[j].Position {+ return out[i].Position < out[j].Position+ }+ return out[i].ID < out[j].ID+ })+ return out+}++// Evaluate runs the rules over a submission. Every matching rule applies, in+// Position order, until one with Stop matches.+func Evaluate(rules []models.FormRule, facts Facts) Outcome {+ if !Routable(facts.Status) {+ return Outcome{}+ }+ var matched []models.FormRule+ for _, r := range Ordered(rules) {+ if !Matches(&r, facts) {+ continue+ }+ matched = append(matched, r)+ if r.Stop {+ break+ }+ }+ return merge(matched)+}++// Combine rebuilds the outcome of rules that already matched, in their+// order, from their current actions. The worker uses it on a retry and the+// digest at send time, so neither re-evaluates against changed rules.+func Combine(rules []models.FormRule, matched []string) Outcome {+ want := make(map[string]bool, len(matched))+ for _, id := range matched {+ want[id] = true+ }+ var picked []models.FormRule+ for _, r := range Ordered(rules) {+ if want[r.UUID] {+ picked = append(picked, r)+ }+ }+ return merge(picked)+}++var priorityRank = map[string]int{"low": 1, "normal": 2, "high": 3, "urgent": 4}++// merge folds the actions of matched rules: recipients, tags and webhooks are+// a union, the first assignment wins, and the highest priority wins.+func merge(matched []models.FormRule) Outcome {+ var o Outcome+ seenRecipient := map[Recipient]bool{}+ seenTag := map[string]bool{}+ seenHook := map[uint]bool{}+ notify := func(r Recipient) {+ if !seenRecipient[r] {+ seenRecipient[r] = true+ o.Notify = append(o.Notify, r)+ }+ }+ for _, rule := range matched {+ o.Matched = append(o.Matched, rule.UUID)+ for _, a := range rule.Actions {+ switch a.Type {+ case models.ActionNotifyEmails:+ for _, e := range a.Emails {+ notify(Recipient{Email: strings.ToLower(strings.TrimSpace(e))})+ }+ case models.ActionNotifyMembers:+ for _, id := range a.UserIDs {+ notify(Recipient{UserID: id})+ }+ case models.ActionNotifyTeam:+ if a.TeamID != nil {+ notify(Recipient{TeamID: *a.TeamID})+ }+ case models.ActionAssignMember:+ if o.AssignUser == nil && len(a.UserIDs) > 0 {+ id := a.UserIDs[0]+ o.AssignUser = &id+ }+ case models.ActionAssignTeam:+ if o.AssignTeam == nil && a.TeamID != nil {+ id := *a.TeamID+ o.AssignTeam = &id+ }+ case models.ActionAddTags:+ for _, t := range a.Tags {+ if !seenTag[t] {+ seenTag[t] = true+ o.Tags = append(o.Tags, t)+ }+ }+ case models.ActionSetPriority:+ if priorityRank[a.Priority] > priorityRank[o.Priority] {+ o.Priority = a.Priority+ }+ case models.ActionWebhook:+ if a.WebhookID != nil && !seenHook[*a.WebhookID] {+ seenHook[*a.WebhookID] = true+ o.Webhooks = append(o.Webhooks, *a.WebhookID)+ }+ case models.ActionSuppressDefault:+ o.SuppressDefault = true+ }+ }+ }+ return o+}++// Matches reports whether a rule's conditions hold. A rule without+// conditions always matches.+func Matches(r *models.FormRule, facts Facts) bool {+ if len(r.Conditions) == 0 {+ return true+ }+ any := r.Match == models.RuleMatchAny+ for _, c := range r.Conditions {+ ok := test(c, facts)+ if any && ok {+ return true+ }+ if !any && !ok {+ return false+ }+ }+ return !any+}++// value is a fact as rules see it: text, a number, a boolean, or a list.+type value struct {+ present bool+ text string+ num *float64+ boolean *bool+ list []string+ exact bool // a choice value: compared as written, not case-folded+}++func lookup(field string, f Facts) value {+ switch field {+ case FactOrigin:+ return textValue(f.Origin)+ case FactReferer:+ return textValue(f.Referer)+ case FactSenderEmail:+ return textValue(f.SenderEmail)+ case FactStatus:+ v := textValue(string(f.Status))+ v.exact = true+ return v+ case FactSpamScore:+ n := f.SpamScore+ return value{present: true, num: &n, text: strconv.FormatFloat(n, 'f', -1, 64)}+ }+ def := f.Schema[field]+ if raw, ok := f.Data[field]; ok && raw != nil {+ v := typedValue(raw)+ v.exact = def != nil && (def.Type == models.FieldSelect || def.Type == models.FieldMultiSelect)+ return v+ }+ if def != nil {+ return value{}+ }+ // A form without questions: compare the submitted text.+ if s, ok := f.Fields[strings.ToLower(field)]; ok {+ return textValue(s)+ }+ return value{}+}++func textValue(s string) value {+ s = strings.TrimSpace(s)+ v := value{present: s != "", text: s}+ if n, err := strconv.ParseFloat(s, 64); err == nil {+ v.num = &n+ }+ return v+}++func typedValue(raw any) value {+ switch t := raw.(type) {+ case float64:+ return value{present: true, num: &t, text: strconv.FormatFloat(t, 'f', -1, 64)}+ case int:+ n := float64(t)+ return value{present: true, num: &n, text: strconv.Itoa(t)}+ case bool:+ text := "false"+ if t {+ text = "true"+ }+ return value{present: true, boolean: &t, text: text}+ case []any:+ list := make([]string, 0, len(t))+ for _, x := range t {+ list = append(list, toString(x))+ }+ return value{present: len(list) > 0, list: list, text: strings.Join(list, ", ")}+ case []string:+ return value{present: len(t) > 0, list: t, text: strings.Join(t, ", ")}+ case string:+ return textValue(t)+ }+ return textValue(toString(raw))+}++func toString(x any) string {+ switch t := x.(type) {+ case string:+ return t+ case float64:+ return strconv.FormatFloat(t, 'f', -1, 64)+ case bool:+ return strconv.FormatBool(t)+ }+ raw, _ := json.Marshal(x)+ return string(raw)+}++// wanted reads a condition's value as a list of strings.+func wanted(v any) []string {+ switch t := v.(type) {+ case nil:+ return nil+ case []any:+ out := make([]string, 0, len(t))+ for _, x := range t {+ out = append(out, toString(x))+ }+ return out+ case []string:+ return t+ }+ return []string{toString(v)}+}++func test(c models.RuleCondition, f Facts) bool {+ v := lookup(c.Field, f)+ switch c.Op {+ case "exists":+ return v.present+ case "not_exists":+ return !v.present+ case "eq":+ return v.present && equalAny(v, wanted(c.Value))+ case "neq":+ return !v.present || !equalAny(v, wanted(c.Value))+ case "in":+ return v.present && equalAny(v, wanted(c.Value))+ case "not_in":+ return !v.present || !equalAny(v, wanted(c.Value))+ case "contains":+ return v.present && containsAny(v, wanted(c.Value))+ case "not_contains":+ return !v.present || !containsAny(v, wanted(c.Value))+ case "matches":+ re := compiled(toString(c.Value))+ return v.present && re != nil && re.MatchString(v.text)+ case "gt", "gte", "lt", "lte":+ return v.present && compare(v, toString(c.Value), c.Op)+ }+ return false+}++func same(a, b string, exact bool) bool {+ if exact {+ return a == b+ }+ return strings.EqualFold(strings.TrimSpace(a), strings.TrimSpace(b))+}++// equalAny: for a list answer (checkboxes), any overlap; for a boolean, true+// or false; for a number, numeric equality; otherwise text.+func equalAny(v value, want []string) bool {+ for _, w := range want {+ switch {+ case v.list != nil:+ for _, item := range v.list {+ if same(item, w, v.exact) {+ return true+ }+ }+ case v.boolean != nil:+ if b, err := strconv.ParseBool(w); err == nil && b == *v.boolean {+ return true+ }+ case v.num != nil:+ if n, err := strconv.ParseFloat(strings.TrimSpace(w), 64); err == nil && n == *v.num {+ return true+ }+ if same(v.text, w, v.exact) {+ return true+ }+ default:+ if same(v.text, w, v.exact) {+ return true+ }+ }+ }+ return false+}++func containsAny(v value, want []string) bool {+ for _, w := range want {+ if v.list != nil {+ for _, item := range v.list {+ if same(item, w, v.exact) {+ return true+ }+ }+ continue+ }+ if w != "" && strings.Contains(strings.ToLower(v.text), strings.ToLower(w)) {+ return true+ }+ }+ return false+}++// compare orders numbers numerically, and dates and times as text, which+// sorts YYYY-MM-DD and HH:MM correctly.+func compare(v value, w string, op string) bool {+ var cmp int+ if n, err := strconv.ParseFloat(strings.TrimSpace(w), 64); err == nil && v.num != nil {+ switch {+ case *v.num < n:+ cmp = -1+ case *v.num > n:+ cmp = 1+ }+ } else {+ cmp = strings.Compare(v.text, strings.TrimSpace(w))+ }+ switch op {+ case "gt":+ return cmp > 0+ case "gte":+ return cmp >= 0+ case "lt":+ return cmp < 0+ }+ return cmp <= 0+}++var regexCache sync.Map // pattern → *regexp.Regexp (nil when it does not compile)++// compiled returns the case-insensitive regexp for pattern. Patterns are+// checked when a rule is saved; one that no longer compiles never matches.+func compiled(pattern string) *regexp.Regexp {+ if cached, ok := regexCache.Load(pattern); ok {+ re, _ := cached.(*regexp.Regexp)+ return re+ }+ re, err := regexp.Compile("(?i)" + pattern)+ if err != nil {+ regexCache.Store(pattern, (*regexp.Regexp)(nil))+ return nil+ }+ regexCache.Store(pattern, re)+ return re+}diff --git a/internal/services/formrules/engine_test.go b/internal/services/formrules/engine_test.gonew file mode 100644index 0000000..e34aa59--- /dev/null+++ b/internal/services/formrules/engine_test.go@@ -0,0 +1,325 @@+// 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 formrules++import (+ "reflect"+ "strings"+ "testing"++ "github.com/goposta/posta/internal/models"+)++func uintp(v uint) *uint { return &v }++func testForm() *models.Form {+ return &models.Form{Fields: models.FieldDefs{+ {Key: "email", Label: "Email", Type: models.FieldEmail},+ {Key: "dept", Label: "Department", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "sales"}, {Value: "support"}, {Value: "Billing"}}},+ {Key: "topics", Label: "Topics", Type: models.FieldMultiSelect, Options: []models.FieldOption{{Value: "api"}, {Value: "ui"}}},+ {Key: "seats", Label: "Seats", Type: models.FieldNumber},+ {Key: "nps", Label: "NPS", Type: models.FieldScale},+ {Key: "start", Label: "Start", Type: models.FieldDate},+ {Key: "vip", Label: "VIP", Type: models.FieldCheckbox},+ {Key: "notes", Label: "Notes", Type: models.FieldTextarea},+ {Key: "old", Label: "Old", Type: models.FieldText, Archived: true},+ {Key: "page2", Label: "Page 2", Type: models.FieldSection},+ }}+}++func facts(data map[string]any) Facts {+ f := FactsFor(&models.Message{Status: models.MessageStatusReceived, Origin: "https://acme.com", SenderEmail: "[email protected]", SpamScore: 2.5, Data: data}, testForm())+ return f+}++func TestConditionOperators(t *testing.T) {+ f := facts(map[string]any{+ "dept": "sales", "topics": []any{"api", "ui"}, "seats": float64(40), "nps": float64(9),+ "start": "2026-12-01", "vip": true, "notes": "Need an INVOICE copy", "email": "[email protected]",+ })+ cases := []struct {+ field, op string+ value any+ want bool+ }{+ {"dept", "eq", "sales", true},+ {"dept", "eq", "Sales", false}, // option values are exact+ {"dept", "neq", "support", true},+ {"dept", "in", []any{"support", "sales"}, true},+ {"dept", "not_in", []any{"support"}, true},+ {"topics", "in", []any{"ui"}, true}, // any overlap+ {"topics", "contains", "api", true},+ {"topics", "not_contains", "api", false},+ {"seats", "gt", "39", true},+ {"seats", "gt", "100", false},+ {"seats", "eq", "40", true},+ {"nps", "gte", "9", true},+ {"nps", "lt", "9", false},+ {"start", "gt", "2026-11-30", true},+ {"start", "lte", "2026-11-30", false},+ {"vip", "eq", "true", true},+ {"vip", "eq", "false", false},+ {"notes", "contains", "invoice", true}, // text is case-insensitive+ {"notes", "matches", `invoice\s+copy`, true},+ {"notes", "exists", nil, true},+ {"missing", "not_exists", nil, true},+ {"seats", "not_exists", nil, false},+ {FactOrigin, "eq", "HTTPS://ACME.COM", true},+ {FactSenderEmail, "contains", "@bigcorp.com", true},+ {FactSpamScore, "lt", "3", true},+ {FactStatus, "eq", "received", true},+ }+ for _, c := range cases {+ r := models.FormRule{Conditions: models.RuleConditions{{Field: c.field, Op: c.op, Value: c.value}}}+ if got := Matches(&r, f); got != c.want {+ t.Errorf("%s %s %v = %v, want %v", c.field, c.op, c.value, got, c.want)+ }+ }+}++func TestSchemalessFields(t *testing.T) {+ msg := &models.Message{Status: models.MessageStatusReceived, FieldsJSON: `[{"key":"Department","value":"Sales"},{"key":"budget","value":"5000"}]`}+ f := FactsFor(msg, &models.Form{})+ for _, c := range []models.RuleCondition{+ {Field: "department", Op: "eq", Value: "sales"},+ {Field: "budget", Op: "gte", Value: "1000"},+ } {+ r := models.FormRule{Conditions: models.RuleConditions{c}}+ if !Matches(&r, f) {+ t.Errorf("%+v did not match a schemaless submission", c)+ }+ }+}++func TestMatchAllAny(t *testing.T) {+ f := facts(map[string]any{"dept": "sales", "seats": float64(5)})+ conds := models.RuleConditions{{Field: "dept", Op: "eq", Value: "sales"}, {Field: "seats", Op: "gt", Value: "10"}}+ all := models.FormRule{Match: models.RuleMatchAll, Conditions: conds}+ anyRule := models.FormRule{Match: models.RuleMatchAny, Conditions: conds}+ if Matches(&all, f) || !Matches(&anyRule, f) {+ t.Error("all/any mixed up")+ }+ if empty := (models.FormRule{}); !Matches(&empty, f) {+ t.Error("a rule without conditions always matches")+ }+}++func rule(uuid string, pos int, conds models.RuleConditions, actions ...models.RuleAction) models.FormRule {+ return models.FormRule{UUID: uuid, Name: uuid, Position: pos, Enabled: true, Conditions: conds, Actions: actions}+}++func TestEvaluateMerges(t *testing.T) {+ sales := models.RuleConditions{{Field: "dept", Op: "eq", Value: "sales"}}+ rules := []models.FormRule{+ // Out of order on purpose: Position decides.+ rule("c", 3, nil, models.RuleAction{Type: models.ActionAssignMember, UserIDs: []uint{9}}, models.RuleAction{Type: models.ActionSetPriority, Priority: "low"}),+ rule("a", 1, sales,+ models.RuleAction{Type: models.ActionNotifyEmails, Emails: []string{"[email protected]"}},+ models.RuleAction{Type: models.ActionAssignTeam, TeamID: uintp(2)},+ models.RuleAction{Type: models.ActionAddTags, Tags: []string{"lead"}},+ models.RuleAction{Type: models.ActionSetPriority, Priority: "high"}),+ rule("b", 2, sales,+ models.RuleAction{Type: models.ActionNotifyEmails, Emails: []string{"[email protected]", "[email protected]"}},+ models.RuleAction{Type: models.ActionAssignTeam, TeamID: uintp(3)},+ models.RuleAction{Type: models.ActionAssignMember, UserIDs: []uint{7}},+ models.RuleAction{Type: models.ActionAddTags, Tags: []string{"lead", "hot"}},+ models.RuleAction{Type: models.ActionWebhook, WebhookID: uintp(4)}),+ {UUID: "off", Position: 0, Enabled: false, Actions: models.RuleActions{{Type: models.ActionSuppressDefault}}},+ }+ o := Evaluate(rules, facts(map[string]any{"dept": "sales"}))+ if !reflect.DeepEqual(o.Matched, []string{"a", "b", "c"}) {+ t.Fatalf("matched %v", o.Matched)+ }+ if want := []Recipient{{Email: "[email protected]"}, {Email: "[email protected]"}}; !reflect.DeepEqual(o.Notify, want) {+ t.Errorf("notify %+v", o.Notify)+ }+ if *o.AssignTeam != 2 || *o.AssignUser != 7 {+ t.Errorf("first assignment should win: team %d user %d", *o.AssignTeam, *o.AssignUser)+ }+ if !reflect.DeepEqual(o.Tags, []string{"lead", "hot"}) || o.Priority != "high" || !reflect.DeepEqual(o.Webhooks, []uint{4}) {+ t.Errorf("tags %v priority %q webhooks %v", o.Tags, o.Priority, o.Webhooks)+ }+ if o.SuppressDefault {+ t.Error("a disabled rule applied")+ }++ // Stop ends evaluation after its rule.+ rules[1].Stop = true+ if o := Evaluate(rules, facts(map[string]any{"dept": "sales"})); !reflect.DeepEqual(o.Matched, []string{"a"}) {+ t.Errorf("with stop, matched %v", o.Matched)+ }++ // Combine rebuilds the same outcome from the stored matches.+ rules[1].Stop = false+ if c := Combine(rules, []string{"b", "a", "c"}); !reflect.DeepEqual(c, o) {+ t.Errorf("Combine = %+v, want %+v", c, o)+ }+}++func TestSpamIsNotRouted(t *testing.T) {+ rules := []models.FormRule{rule("a", 0, nil, models.RuleAction{Type: models.ActionSuppressDefault})}+ for _, status := range []models.MessageStatus{models.MessageStatusQuarantined, models.MessageStatusRejected} {+ f := facts(nil)+ f.Status = status+ if o := Evaluate(rules, f); len(o.Matched) > 0 || o.SuppressDefault {+ t.Errorf("%s was routed", status)+ }+ }+ f := facts(nil)+ f.Status = models.MessageStatusFlagged+ if o := Evaluate(rules, f); !o.SuppressDefault {+ t.Error("a flagged submission is routed")+ }+}++func TestCheck(t *testing.T) {+ dest := Destinations{Members: map[uint]bool{7: true}, Teams: map[uint]bool{2: true}, Webhooks: map[uint]bool{4: true}}+ good := models.FormRule{+ Name: " Sales ",+ Conditions: models.RuleConditions{{Field: "dept", Op: "in", Value: []any{"sales", " Billing "}}, {Field: "seats", Op: "gte", Value: float64(10)}},+ Actions: models.RuleActions{+ {Type: models.ActionNotifyEmails, Emails: []string{" [email protected] "}, TeamID: uintp(99)},+ {Type: models.ActionAssignTeam, TeamID: uintp(2)},+ {Type: models.ActionAddTags, Tags: []string{"Lead"}},+ },+ }+ if err := Check(&good, testForm(), dest); err != nil {+ t.Fatalf("valid rule rejected: %v", err)+ }+ if good.Name != "Sales" || good.Match != models.RuleMatchAll || good.Actions[0].Emails[0] != "[email protected]" || good.Actions[0].TeamID != nil || good.Actions[2].Tags[0] != "lead" {+ t.Errorf("not normalized: %+v", good)+ }+ if v := good.Conditions[0].Value.([]string); v[1] != "Billing" {+ t.Errorf("in values not trimmed: %v", v)+ }++ bad := []struct {+ name string+ rule models.FormRule+ want string+ }{+ {"no name", models.FormRule{Actions: models.RuleActions{{Type: models.ActionSuppressDefault}}}, "name"},+ {"no actions", models.FormRule{Name: "x"}, "actions"},+ {"unknown field", ruleWith(models.RuleCondition{Field: "nope", Op: "eq", Value: "x"}), "not a question"},+ {"section as field", ruleWith(models.RuleCondition{Field: "page2", Op: "exists"}), "not a question"},+ {"archived field", ruleWith(models.RuleCondition{Field: "old", Op: "eq", Value: "x"}), "archived"},+ {"not an option", ruleWith(models.RuleCondition{Field: "dept", Op: "eq", Value: "Sales"}), "not an option"},+ {"gt on choice", ruleWith(models.RuleCondition{Field: "dept", Op: "gt", Value: "1"}), "only compares"},+ {"gt not a number", ruleWith(models.RuleCondition{Field: "seats", Op: "gt", Value: "many"}), "not a number"},+ {"bad date", ruleWith(models.RuleCondition{Field: "start", Op: "gt", Value: "12/01/2026"}), "YYYY-MM-DD"},+ {"bad regex", ruleWith(models.RuleCondition{Field: "notes", Op: "matches", Value: "("}), "compile"},+ {"in without values", ruleWith(models.RuleCondition{Field: "dept", Op: "in", Value: []any{}}), "at least one"},+ {"unknown op", ruleWith(models.RuleCondition{Field: "dept", Op: "like", Value: "x"}), "unknown operator"},+ {"checkbox value", ruleWith(models.RuleCondition{Field: "vip", Op: "eq", Value: "maybe"}), "true or false"},+ // No action can take its destination from the submission.+ {"field as address", ruleDoing(models.RuleAction{Type: models.ActionNotifyEmails, Emails: []string{"email"}}), "not an email address"},+ {"template as address", ruleDoing(models.RuleAction{Type: models.ActionNotifyEmails, Emails: []string{"{{email}}"}}), "not an email address"},+ {"display name address", ruleDoing(models.RuleAction{Type: models.ActionNotifyEmails, Emails: []string{"Eve <[email protected]>"}}), "not an email address"},+ {"other workspace member", ruleDoing(models.RuleAction{Type: models.ActionNotifyMembers, UserIDs: []uint{8}}), "not a member"},+ {"other workspace team", ruleDoing(models.RuleAction{Type: models.ActionAssignTeam, TeamID: uintp(3)}), "teams"},+ {"other workspace webhook", ruleDoing(models.RuleAction{Type: models.ActionWebhook, WebhookID: uintp(5)}), "webhooks"},+ {"assign two members", ruleDoing(models.RuleAction{Type: models.ActionAssignMember, UserIDs: []uint{7, 7}}), "one member"},+ {"bad priority", ruleDoing(models.RuleAction{Type: models.ActionSetPriority, Priority: "asap"}), "priority"},+ {"bad tag", ruleDoing(models.RuleAction{Type: models.ActionAddTags, Tags: []string{"a,b"}}), "tag"},+ {"unknown action", ruleDoing(models.RuleAction{Type: "forward_to_field"}), "unknown action"},+ }+ for _, c := range bad {+ r := c.rule+ err := Check(&r, testForm(), dest)+ if err == nil || !strings.Contains(err.Error(), c.want) {+ t.Errorf("%s: err = %v, want it to mention %q", c.name, err, c.want)+ }+ }++ // A form without questions accepts any field name, lowercased.+ free := ruleWith(models.RuleCondition{Field: "Department", Op: "eq", Value: "sales"})+ if err := Check(&free, &models.Form{}, dest); err != nil || free.Conditions[0].Field != "department" {+ t.Errorf("schemaless field: %v %q", err, free.Conditions[0].Field)+ }+}++func ruleWith(c models.RuleCondition) models.FormRule {+ return models.FormRule{Name: "r", Conditions: models.RuleConditions{c}, Actions: models.RuleActions{{Type: models.ActionSuppressDefault}}}+}++func ruleDoing(a models.RuleAction) models.FormRule {+ return models.FormRule{Name: "r", Actions: models.RuleActions{a}}+}++type fakeDir struct {+ members map[uint]models.WorkspaceRole+ teams map[uint]*models.Team+}++func (f fakeDir) Members(uint) (map[uint]models.WorkspaceRole, error) { return f.members, nil }+func (f fakeDir) Team(id uint) (*models.Team, error) {+ if t, ok := f.teams[id]; ok {+ return t, nil+ }+ return nil, errNotFound+}++type notFound struct{}++func (notFound) Error() string { return "not found" }++var errNotFound = notFound{}++func TestResolve(t *testing.T) {+ ws, other := uint(1), uint(2)+ dir := fakeDir{+ members: map[uint]models.WorkspaceRole{1: models.WorkspaceRoleOwner, 2: models.WorkspaceRoleEditor, 3: models.WorkspaceRoleViewer},+ teams: map[uint]*models.Team{+ 10: {ID: 10, WorkspaceID: &ws, Email: "[email protected]", Members: []models.TeamMember{{UserID: 1}, {UserID: 2}, {UserID: 99}}},+ 11: {ID: 11, WorkspaceID: &other, Email: "[email protected]", Members: []models.TeamMember{{UserID: 3}}},+ },+ }+ out := Outcome{Notify: []Recipient{{TeamID: 10}, {UserID: 3}, {Email: "[email protected]"}, {Email: "[email protected]"}, {TeamID: 11}}}++ // Default route to the owners and admins: the owner is not added twice,+ // and user 99 left the workspace.+ form := &models.Form{WorkspaceID: &ws}+ res, err := Resolve(form, out, dir)+ if err != nil {+ t.Fatal(err)+ }+ if !res.Default || !reflect.DeepEqual(res.UserIDs, []uint{2, 3}) || !reflect.DeepEqual(res.Emails, []string{"[email protected]", "[email protected]"}) {+ t.Errorf("got %+v", res)+ }++ // Suppressed default: the owner is notified through the team.+ out.SuppressDefault = true+ res, _ = Resolve(form, out, dir)+ if res.Default || !reflect.DeepEqual(res.UserIDs, []uint{1, 2, 3}) {+ t.Errorf("suppressed: %+v", res)+ }++ // A default address list already covering an address is not repeated.+ out.SuppressDefault = false+ form.NotifyEmails = []string{"[email protected]"}+ res, _ = Resolve(form, out, dir)+ if !reflect.DeepEqual(res.Emails, []string{"[email protected]"}) || !reflect.DeepEqual(res.UserIDs, []uint{1, 2, 3}) {+ t.Errorf("with notify_emails: %+v", res)+ }++ if res, _ := Resolve(form, Outcome{SuppressDefault: true}, dir); !res.Empty() {+ t.Errorf("suppressed with no rule recipients should notify nobody: %+v", res)+ }+}diff --git a/internal/services/formrules/recipients.go b/internal/services/formrules/recipients.gonew file mode 100644index 0000000..01a3dfd--- /dev/null+++ b/internal/services/formrules/recipients.go@@ -0,0 +1,139 @@+// 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 formrules++import (+ "strings"++ "github.com/goposta/posta/internal/models"+)++// Directory looks up the workspace data recipients expand to. The worker+// and the digest pass the repositories; tests pass a map.+type Directory interface {+ // Members maps the workspace's members to their roles.+ Members(workspaceID uint) (map[uint]models.WorkspaceRole, error)+ Team(id uint) (*models.Team, error)+}++// Resolved is where one submission's notification goes.+type Resolved struct {+ // Default is the form's own route: its notification addresses, or the+ // workspace owners and admins when it has none.+ Default bool+ Emails []string+ UserIDs []uint+}++// Empty reports whether nobody is notified.+func (r Resolved) Empty() bool { return !r.Default && len(r.Emails) == 0 && len(r.UserIDs) == 0 }++// Resolve expands an outcome's recipients for one submission: teams become+// their members plus their shared address, people who left the workspace are+// dropped, and anyone the default route already reaches is not added twice.+func Resolve(form *models.Form, out Outcome, dir Directory) (Resolved, error) {+ res := Resolved{Default: !out.SuppressDefault}+ if len(out.Notify) == 0 || form.WorkspaceID == nil {+ return res, nil+ }+ members, err := dir.Members(*form.WorkspaceID)+ if err != nil {+ return res, err+ }+ defaultEmails := map[string]bool{}+ for _, e := range form.NotifyEmails {+ defaultEmails[strings.ToLower(strings.TrimSpace(e))] = true+ }+ defaultIsAdmins := len(form.NotifyEmails) == 0++ seenEmail := map[string]bool{}+ seenUser := map[uint]bool{}+ addEmail := func(e string) {+ e = strings.ToLower(strings.TrimSpace(e))+ if e == "" || seenEmail[e] || res.Default && defaultEmails[e] {+ return+ }+ seenEmail[e] = true+ res.Emails = append(res.Emails, e)+ }+ addUser := func(id uint) {+ role, member := members[id]+ if !member || seenUser[id] || res.Default && defaultIsAdmins && role.CanManageMembers() {+ return+ }+ seenUser[id] = true+ res.UserIDs = append(res.UserIDs, id)+ }+ for _, r := range out.Notify {+ switch {+ case r.Email != "":+ addEmail(r.Email)+ case r.UserID != 0:+ addUser(r.UserID)+ case r.TeamID != 0:+ team, err := dir.Team(r.TeamID)+ if err != nil || team.WorkspaceID == nil || *team.WorkspaceID != *form.WorkspaceID {+ continue+ }+ for _, m := range team.Members {+ addUser(m.UserID)+ }+ addEmail(team.Email)+ }+ }+ return res, nil+}++// CachedDirectory remembers lookups for the life of one job run.+type CachedDirectory struct {+ Next Directory+ members map[uint]map[uint]models.WorkspaceRole+ teams map[uint]*models.Team+}++func (c *CachedDirectory) Members(workspaceID uint) (map[uint]models.WorkspaceRole, error) {+ if m, ok := c.members[workspaceID]; ok {+ return m, nil+ }+ m, err := c.Next.Members(workspaceID)+ if err != nil {+ return nil, err+ }+ if c.members == nil {+ c.members = map[uint]map[uint]models.WorkspaceRole{}+ }+ c.members[workspaceID] = m+ return m, nil+}++func (c *CachedDirectory) Team(id uint) (*models.Team, error) {+ if t, ok := c.teams[id]; ok {+ return t, nil+ }+ t, err := c.Next.Team(id)+ if err != nil {+ return nil, err+ }+ if c.teams == nil {+ c.teams = map[uint]*models.Team{}+ }+ c.teams[id] = t+ return t, nil+}diff --git a/internal/services/messages/branching.go b/internal/services/messages/branching.gonew file mode 100644index 0000000..16e1583--- /dev/null+++ b/internal/services/messages/branching.go@@ -0,0 +1,127 @@+// 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 "github.com/goposta/posta/internal/models"++// Page is one page of a form: the section that opens it (nil for the first+// page, before any section) and its active questions, in order.+type Page struct {+ Section *models.FieldDef+ Questions []*models.FieldDef+}++// Pages splits a schema's active entries into pages. A form without sections+// is one page.+func Pages(defs models.FieldDefs) []Page {+ pages := []Page{{}}+ for i := range defs {+ f := &defs[i]+ if f.Archived {+ continue+ }+ if f.IsSection() {+ pages = append(pages, Page{Section: f})+ continue+ }+ last := &pages[len(pages)-1]+ last.Questions = append(last.Questions, f)+ }+ // A form that opens with a section has no questions before it.+ if len(pages) > 1 && len(pages[0].Questions) == 0 {+ pages = pages[1:]+ }+ return pages+}++// Route walks a form the way a respondent moves through it and returns the+// keys of the questions on the pages they reached. answer gives a question's+// first submitted value. Hidden questions are always included: an embed sets+// them, they sit on no page.+//+// After each page the respondent goes where the chosen option of a branching+// question points, else where the section's Next points, else to the next+// page. Targets only ever lie ahead (CheckSchema), so the walk ends.+func Route(defs models.FieldDefs, answer func(key string) string) map[string]bool {+ pages := Pages(defs)+ index := make(map[string]int, len(pages))+ for i, p := range pages {+ if p.Section != nil {+ index[p.Section.Key] = i+ }+ }+ reached := make(map[string]bool)+ for _, f := range defs {+ if f.Type == models.FieldHidden && !f.Archived {+ reached[f.Key] = true+ }+ }+ for i := 0; i < len(pages); {+ p := pages[i]+ for _, q := range p.Questions {+ reached[q.Key] = true+ }+ target := ""+ if p.Section != nil {+ target = p.Section.Next+ }+ for _, q := range p.Questions {+ if goto_ := branchTarget(q, answer(q.Key)); goto_ != "" {+ target = goto_+ }+ }+ next := i + 1+ switch target {+ case "":+ case models.GotoSubmit:+ return reached+ default:+ if j, ok := index[target]; ok && j > i {+ next = j+ }+ }+ i = next+ }+ return reached+}++// branchTarget is where answering q with value leads, or "" when q does not+// branch on that value.+func branchTarget(q *models.FieldDef, value string) string {+ if q.Type != models.FieldSelect || value == "" {+ return ""+ }+ for _, o := range q.Options {+ if o.Value == value {+ return o.Goto+ }+ }+ return ""+}++// branches reports whether any option of q leads somewhere.+func branches(q *models.FieldDef) bool {+ for _, o := range q.Options {+ if o.Goto != "" {+ return true+ }+ }+ return false+}diff --git a/internal/services/messages/branching_test.go b/internal/services/messages/branching_test.gonew file mode 100644index 0000000..ec62f6b--- /dev/null+++ b/internal/services/messages/branching_test.go@@ -0,0 +1,174 @@+// 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 (+ "reflect"+ "sort"+ "strings"+ "testing"++ "github.com/goposta/posta/internal/models"+)++// An application form: individuals skip the company page, and anyone who+// says they are not hiring ends early.+func branchingForm() models.FieldDefs {+ return models.FieldDefs{+ {Key: "email", Label: "Email", Type: models.FieldEmail, Required: true},+ {Key: "kind", Label: "I am", Type: models.FieldSelect, Required: true, Options: []models.FieldOption{+ {Value: "company", Label: "A company"},+ {Value: "individual", Label: "An individual", Goto: "about"},+ {Value: "browsing", Label: "Just looking", Goto: models.GotoSubmit},+ }},+ {Key: "utm", Type: models.FieldHidden},+ {Key: "company", Label: "Company details", Type: models.FieldSection, Next: "wrapup"},+ {Key: "company_name", Label: "Company name", Type: models.FieldText, Required: true},+ {Key: "about", Label: "About you", Type: models.FieldSection},+ {Key: "bio", Label: "Bio", Type: models.FieldTextarea, Required: true},+ {Key: "wrapup", Label: "Last step", Type: models.FieldSection},+ {Key: "notes", Label: "Anything else?", Type: models.FieldTextarea},+ }+}++func routeKeys(defs models.FieldDefs, answers map[string]string) []string {+ var out []string+ for k := range Route(defs, func(key string) string { return answers[key] }) {+ out = append(out, k)+ }+ sort.Strings(out)+ return out+}++func TestRoute(t *testing.T) {+ defs := branchingForm()+ cases := []struct {+ kind string+ want []string+ }{+ // The company page's own next skips "about you".+ {"company", []string{"company_name", "email", "kind", "notes", "utm"}},+ {"individual", []string{"bio", "email", "kind", "notes", "utm"}},+ {"browsing", []string{"email", "kind", "utm"}},+ // No answer yet: pages follow in order, each page's next applying.+ {"", []string{"company_name", "email", "kind", "notes", "utm"}},+ }+ for _, c := range cases {+ if got := routeKeys(defs, map[string]string{"kind": c.kind}); !reflect.DeepEqual(got, c.want) {+ t.Errorf("kind=%q reached %v, want %v", c.kind, got, c.want)+ }+ }++ plain := models.FieldDefs{{Key: "a", Label: "A", Type: models.FieldText}, {Key: "b", Label: "B", Type: models.FieldText}}+ if got := routeKeys(plain, nil); !reflect.DeepEqual(got, []string{"a", "b"}) {+ t.Errorf("a form without sections reached %v", got)+ }++ // An archived section folds its questions into the page before it: "bio"+ // joins the company page.+ archived := branchingForm()+ archived[5].Archived = true+ if got := routeKeys(archived, map[string]string{"kind": "company"}); !reflect.DeepEqual(got, []string{"bio", "company_name", "email", "kind", "notes", "utm"}) {+ t.Errorf("with 'about' archived, company reached %v", got)+ }+}++func TestPages(t *testing.T) {+ pages := Pages(branchingForm())+ if len(pages) != 4 || pages[0].Section != nil || pages[1].Section.Key != "company" {+ t.Fatalf("got %d pages", len(pages))+ }+ opening := models.FieldDefs{{Key: "intro", Label: "Intro", Type: models.FieldSection}, {Key: "a", Label: "A", Type: models.FieldText}}+ if p := Pages(opening); len(p) != 1 || p[0].Section == nil || p[0].Section.Key != "intro" {+ t.Errorf("a form opening with a section should have it as its only page, got %+v", p)+ }+}++func TestValidateFollowsRoute(t *testing.T) {+ form := &models.Form{Fields: branchingForm()}++ // An individual never sees the required company name, and answers sent+ // for a skipped page are not stored.+ got, errs := Validate(form, fieldsOf("email", "[email protected]", "kind", "individual", "bio", "Hi", "company_name", "Acme"))+ if errs != nil {+ t.Fatalf("individual rejected: %+v", errs)+ }+ if _, kept := got.Data["company_name"]; kept {+ t.Error("an answer on a skipped page was stored")+ }+ for _, f := range got.Fields {+ if f.Key == "company_name" {+ t.Error("an answer on a skipped page is in the display copy")+ }+ }++ // A company must give its name, and its bio is not asked.+ _, errs = Validate(form, fieldsOf("email", "[email protected]", "kind", "company"))+ if len(errs) != 1 || errs[0].Key != "company_name" || errs[0].Code != "required" {+ t.Errorf("company without a name: %+v", errs)+ }++ if _, errs := Validate(form, fieldsOf("email", "[email protected]", "kind", "browsing")); errs != nil {+ t.Errorf("ending early rejected: %+v", errs)+ }+ // A section key sent as a field is ignored, never stored.+ got, errs = Validate(form, fieldsOf("email", "[email protected]", "kind", "browsing", "company", "x"))+ if errs != nil || got.Data["company"] != nil {+ t.Errorf("section key as a field: errs=%+v data=%v", errs, got.Data)+ }+}++func TestCheckSchemaFlow(t *testing.T) {+ if err := CheckSchema(branchingForm(), nil, "_gotcha"); err != nil {+ t.Fatalf("valid branching form rejected: %v", err)+ }+ mutate := func(fn func(d models.FieldDefs) models.FieldDefs) models.FieldDefs { return fn(branchingForm()) }+ cases := []struct {+ name string+ defs models.FieldDefs+ want string+ }{+ {"goto backwards", mutate(func(d models.FieldDefs) models.FieldDefs {+ d[6].Type, d[6].Options = models.FieldSelect, []models.FieldOption{{Value: "x", Goto: "company"}}+ return d+ }), "later section"},+ {"goto unknown", mutate(func(d models.FieldDefs) models.FieldDefs {+ d[1].Options[1].Goto = "nowhere"+ return d+ }), "later section"},+ {"next backwards", mutate(func(d models.FieldDefs) models.FieldDefs { d[7].Next = "about"; return d }), "later section"},+ {"goto on multiselect", mutate(func(d models.FieldDefs) models.FieldDefs { d[1].Type = models.FieldMultiSelect; return d }), "single-choice"},+ {"two branches on a page", mutate(func(d models.FieldDefs) models.FieldDefs {+ extra := models.FieldDef{Key: "kind2", Label: "Again", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "y", Goto: "wrapup"}}}+ return append(d[:2], append(models.FieldDefs{extra}, d[2:]...)...)+ }), "same page"},+ {"goto archived section", mutate(func(d models.FieldDefs) models.FieldDefs { d[5].Archived = true; return d }), "later section"},+ {"section with question settings", mutate(func(d models.FieldDefs) models.FieldDefs { d[3].Required = true; return d }), "only takes"},+ {"section keyed submit", mutate(func(d models.FieldDefs) models.FieldDefs { d[7].Key = "submit"; return d }), "cannot be a section key"},+ {"section without title", mutate(func(d models.FieldDefs) models.FieldDefs { d[3].Label = ""; return d }), "title"},+ {"next on a question", mutate(func(d models.FieldDefs) models.FieldDefs { d[0].Next = "about"; return d }), "only a section"},+ }+ for _, c := range cases {+ err := CheckSchema(c.defs, nil, "_gotcha")+ if err == nil || !strings.Contains(err.Error(), c.want) {+ t.Errorf("%s: err = %v, want it to mention %q", c.name, err, c.want)+ }+ }+}diff --git a/internal/services/messages/responses.go b/internal/services/messages/responses.goindex b4ca2d6..4eb0904 100644--- a/internal/services/messages/responses.go+++ b/internal/services/messages/responses.go@@ -84,7 +84,7 @@ type Summarizer struct {func NewSummarizer(defs models.FieldDefs, showPII bool) *Summarizer {s := &Summarizer{showPII: showPII}for _, f := range defs.Active() {- if f.Type == models.FieldHidden {+ if f.Type == models.FieldHidden || f.IsSection() {continue}s.fields = append(s.fields, &fieldAgg{diff --git a/internal/services/messages/schema.go b/internal/services/messages/schema.goindex bbf0dbb..6a53ecb 100644--- a/internal/services/messages/schema.go+++ b/internal/services/messages/schema.go@@ -45,7 +45,7 @@ var fieldTypes = map[models.FieldType]bool{models.FieldPhone: true, models.FieldNumber: true, models.FieldURL: true,models.FieldDate: true, models.FieldTime: true, models.FieldSelect: true,models.FieldMultiSelect: true, models.FieldCheckbox: true, models.FieldScale: true,- models.FieldRating: true, models.FieldHidden: true,+ models.FieldRating: true, models.FieldHidden: true, models.FieldSection: true,}// roleTypes lists the field types each role may sit on.@@ -84,8 +84,20 @@ func CheckSchema(defs models.FieldDefs, previous models.FieldDefs, honeypot strireturn fmt.Errorf("field %q has unknown type %q", f.Key, f.Type)}if f.Label == "" && f.Type != models.FieldHidden {+ if f.IsSection() {+ return fmt.Errorf("section %q needs a title", f.Key)+ }return fmt.Errorf("field %q needs a label", f.Key)}+ if f.IsSection() {+ if err := checkSection(f); err != nil {+ return err+ }+ continue+ }+ if f.Next != "" {+ return fmt.Errorf("field %q: only a section has a next page", f.Key)+ }if err := checkRole(f, roles); err != nil {return err}@@ -93,6 +105,9 @@ func CheckSchema(defs models.FieldDefs, previous models.FieldDefs, honeypot strireturn err}}+ if err := checkFlow(defs); err != nil {+ return err+ }for _, old := range previous {if !seen[old.Key] {return fmt.Errorf("field %q cannot be removed because submissions may use it; archive it instead", old.Key)@@ -101,6 +116,80 @@ func CheckSchema(defs models.FieldDefs, previous models.FieldDefs, honeypot strireturn nil}+// checkSection rejects question settings on a section, which only has a+// title, a description (Help) and where its page leads.+func checkSection(f *models.FieldDef) error {+ if f.Key == models.GotoSubmit {+ return fmt.Errorf("%q cannot be a section key: it means \"submit the form\"", f.Key)+ }+ if f.Required || f.Role != models.RoleNone || f.PII || len(f.Options) > 0 || f.Display != models.DisplayDefault ||+ f.MinLen != nil || f.MaxLen != nil || f.Min != nil || f.Max != nil || f.Pattern != "" {+ return fmt.Errorf("section %q only takes a title, a description and where it leads", f.Key)+ }+ return nil+}++// checkFlow checks where pages lead. A branch or a section's next must point+// to a later, active section or to submit, so every respondent moves forward+// and the form always ends. A page has at most one branching question;+// with two, which one wins would be invisible in the builder.+func checkFlow(defs models.FieldDefs) error {+ position := map[string]int{}+ page := 0+ for _, f := range defs {+ if f.Archived {+ continue+ }+ if f.IsSection() {+ page+++ position[f.Key] = page+ }+ }+ ahead := func(target string, from int) bool {+ if target == "" || target == models.GotoSubmit {+ return true+ }+ to, ok := position[target]+ return ok && to > from+ }++ page = 0+ branching := map[int]string{}+ for i := range defs {+ f := &defs[i]+ f.Next = strings.TrimSpace(f.Next)+ for j := range f.Options {+ f.Options[j].Goto = strings.TrimSpace(f.Options[j].Goto)+ }+ if f.Archived {+ continue+ }+ if f.IsSection() {+ page = position[f.Key]+ if !ahead(f.Next, page) {+ return fmt.Errorf("section %q can only lead to a later section or to submit", f.Key)+ }+ continue+ }+ if !branches(f) {+ continue+ }+ if f.Type != models.FieldSelect {+ return fmt.Errorf("field %q: only a single-choice question can lead to a section", f.Key)+ }+ for _, o := range f.Options {+ if !ahead(o.Goto, page) {+ return fmt.Errorf("field %q: option %q can only lead to a later section or to submit", f.Key, o.Value)+ }+ }+ if other, dup := branching[page]; dup {+ return fmt.Errorf("fields %q and %q are on the same page and both lead to sections; keep one", other, f.Key)+ }+ branching[page] = f.Key+ }+ return nil+}+func checkRole(f *models.FieldDef, roles map[models.FieldRole]string) error {if f.Role == models.RoleNone {return nildiff --git a/internal/services/messages/validate.go b/internal/services/messages/validate.goindex 0e8e46e..159b380 100644--- a/internal/services/messages/validate.go+++ b/internal/services/messages/validate.go@@ -117,11 +117,19 @@ func Validate(form *models.Form, fields []models.MessageField) (*Validated, []FiRoles: map[models.FieldRole]string{},}var errs []FieldError+ // On a form with sections, only the pages the answers lead through count:+ // a skipped page's questions are neither required nor stored.+ reached := Route(form.Fields, func(key string) string {+ if v := values[key]; len(v) > 0 {+ return v[0]+ }+ return ""+ })declared := make(map[string]bool, len(form.Fields))for i := range form.Fields {def := &form.Fields[i]declared[def.Key] = true- if def.Archived {+ if def.Archived || def.IsSection() || !reached[def.Key] {continue}value, display, err := coerce(def, values[def.Key])diff --git a/internal/services/webhook/dispatcher.go b/internal/services/webhook/dispatcher.goindex 7a05a5b..d9a1943 100644--- a/internal/services/webhook/dispatcher.go+++ b/internal/services/webhook/dispatcher.go@@ -229,6 +229,31 @@ func (d *Dispatcher) DispatchJSON(userID uint, workspaceID *uint, event string,}()}+// DispatchJSONTo sends body to the named webhooks of a workspace, as a routing+// rule asks. A webhook already subscribed to event is skipped: DispatchJSON+// delivers to it, and it must not get the payload twice. Runs asynchronously.+func (d *Dispatcher) DispatchJSONTo(workspaceID uint, webhookIDs []uint, event string, body []byte) {+ if len(webhookIDs) == 0 {+ return+ }+ go func() {+ for _, id := range webhookIDs {+ wh, err := d.repo.FindByID(id)+ if err != nil || wh.WorkspaceID == nil || *wh.WorkspaceID != workspaceID {+ continue+ }+ subscribed := false+ for _, e := range wh.Events {+ subscribed = subscribed || e == event+ }+ if subscribed {+ continue+ }+ d.deliverWithRetry(wh.UserID, *wh, body, event)+ }+ }()+}+// matchesFilters checks if the sender address matches the webhook's filters.func matchesFilters(filters []string, from string) bool {if len(filters) == 0 {diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.goindex 8f36923..5cb606e 100644--- a/internal/storage/migration/constraints.go+++ b/internal/storage/migration/constraints.go@@ -129,6 +129,15 @@ func runConstraints(db *gorm.DB) {EXCEPTION WHEN others THEN NULL;END $$`)+ // Routing: a form's rules in order, team names unique per workspace, and+ // the "My teams" inbox view.+ db.Exec(`DO $$ BEGIN+ CREATE INDEX IF NOT EXISTS idx_form_rules_order ON form_rules (form_id, position);+ CREATE UNIQUE INDEX IF NOT EXISTS idx_workspace_team_name ON teams (workspace_id, LOWER(name)) WHERE deleted_at IS NULL;+ CREATE INDEX IF NOT EXISTS idx_messages_team ON messages (team_id, created_at DESC) WHERE team_id IS NOT NULL AND deleted_at IS 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/migration/migration.go b/internal/storage/migration/migration.goindex 516c2bf..0dddc83 100644--- a/internal/storage/migration/migration.go+++ b/internal/storage/migration/migration.go@@ -77,6 +77,9 @@ func Run(db *gorm.DB) error {&models.Message{},&models.MessageReply{},&models.MessageFilter{},+ &models.Team{},+ &models.TeamMember{},+ &models.FormRule{},&models.Notification{},&models.Announcement{},&models.UpgradeStep{},diff --git a/internal/storage/repositories/form_rule_repo.go b/internal/storage/repositories/form_rule_repo.gonew file mode 100644index 0000000..92e7cdd--- /dev/null+++ b/internal/storage/repositories/form_rule_repo.go@@ -0,0 +1,131 @@+// 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 repositories++import (+ "fmt"+ "time"++ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+ "gorm.io/gorm/clause"+)++type FormRuleRepository struct {+ db *gorm.DB+}++func NewFormRuleRepository(db *gorm.DB) *FormRuleRepository {+ return &FormRuleRepository{db: db}+}++// ListByForm returns a form's rules in evaluation order, disabled ones too.+func (r *FormRuleRepository) ListByForm(formID uint) ([]models.FormRule, error) {+ var rules []models.FormRule+ err := r.db.Where("form_id = ?", formID).Order("position ASC, id ASC").Find(&rules).Error+ return rules, err+}++func (r *FormRuleRepository) FindForForm(formID, id uint) (*models.FormRule, error) {+ var rule models.FormRule+ if err := r.db.Where("form_id = ?", formID).First(&rule, id).Error; err != nil {+ return nil, err+ }+ return &rule, nil+}++// Create appends the rule after the form's last one.+func (r *FormRuleRepository) Create(rule *models.FormRule) error {+ return r.db.Transaction(func(tx *gorm.DB) error {+ var last struct{ Max *int }+ if err := tx.Model(&models.FormRule{}).Select("MAX(position) AS max").Where("form_id = ?", rule.FormID).Scan(&last).Error; err != nil {+ return err+ }+ rule.Position = 0+ if last.Max != nil {+ rule.Position = *last.Max + 1+ }+ return tx.Create(rule).Error+ })+}++func (r *FormRuleRepository) Update(rule *models.FormRule) error {+ return r.db.Omit(clause.Associations, "hit_count", "last_hit_at", "position").Save(rule).Error+}++func (r *FormRuleRepository) Delete(id uint) error {+ return r.db.Delete(&models.FormRule{}, id).Error+}++// Reorder sets the evaluation order to ids, which must be exactly the form's+// rules.+func (r *FormRuleRepository) Reorder(formID uint, ids []uint) error {+ return r.db.Transaction(func(tx *gorm.DB) error {+ var count int64+ if err := tx.Model(&models.FormRule{}).Where("form_id = ? AND id IN ?", formID, ids).Count(&count).Error; err != nil {+ return err+ }+ var total int64+ tx.Model(&models.FormRule{}).Where("form_id = ?", formID).Count(&total)+ if int(count) != len(ids) || count != total {+ return fmt.Errorf("the order must list each of the form's rules once")+ }+ for pos, id := range ids {+ if err := tx.Model(&models.FormRule{}).Where("id = ?", id).Update("position", pos).Error; err != nil {+ return err+ }+ }+ return nil+ })+}++// RecordHits counts a match for each rule, by UUID.+func (r *FormRuleRepository) RecordHits(uuids []string, at time.Time) error {+ if len(uuids) == 0 {+ return nil+ }+ return r.db.Model(&models.FormRule{}).Where("uuid IN ?", uuids).+ Updates(map[string]any{"hit_count": gorm.Expr("hit_count + 1"), "last_hit_at": at}).Error+}++// NamesByUUID names rules, for "Routed by" on a submission.+func (r *FormRuleRepository) NamesByUUID(uuids []string) (map[string]string, error) {+ out := map[string]string{}+ if len(uuids) == 0 {+ return out, nil+ }+ var rows []models.FormRule+ if err := r.db.Select("uuid", "name").Where("uuid IN ?", uuids).Find(&rows).Error; err != nil {+ return nil, err+ }+ for _, row := range rows {+ out[row.UUID] = row.Name+ }+ return out, nil+}++// UsingTeam names a workspace's rules that notify or assign team teamID.+func (r *FormRuleRepository) UsingTeam(workspaceID, teamID uint) ([]string, error) {+ var names []string+ err := r.db.Model(&models.FormRule{}).+ Where("workspace_id = ? AND actions @> ?::jsonb", workspaceID, fmt.Sprintf(`[{"team_id":%d}]`, teamID)).+ Pluck("name", &names).Error+ return names, err+}diff --git a/internal/storage/repositories/message_repo.go b/internal/storage/repositories/message_repo.goindex bea3793..32b14d3 100644--- a/internal/storage/repositories/message_repo.go+++ b/internal/storage/repositories/message_repo.go@@ -30,6 +30,12 @@ import ("gorm.io/gorm/clause")+// MineFilter is a member's own work: assigned to them, or to their teams.+type MineFilter struct {+ UserID uint+ TeamIDs []uint+}+type MessageFilterQuery struct {FormID uintStatus string@@ -43,6 +49,10 @@ type MessageFilterQuery struct {// Tags keeps messages carrying every listed tag; Priority one priority.Tags []stringPriority string+ // TeamID keeps one team's submissions. Mine keeps what is assigned to+ // Mine.UserID or routed to one of Mine.TeamIDs: the "My teams" view.+ TeamID uint+ Mine *MineFilter// InboxOnly leaves out collect-mode forms, whose responses are read as a// table on the form rather than worked as conversations.InboxOnly bool@@ -97,6 +107,16 @@ func applyMessageFilter(q *gorm.DB, scope ResourceScope, f MessageFilterQuery) *if f.Priority != "" {q = q.Where("priority = ?", f.Priority)}+ if f.TeamID > 0 {+ q = q.Where("team_id = ?", f.TeamID)+ }+ if f.Mine != nil {+ if len(f.Mine.TeamIDs) > 0 {+ q = q.Where("(assigned_to_id = ? OR team_id IN ?)", f.Mine.UserID, f.Mine.TeamIDs)+ } else {+ q = q.Where("assigned_to_id = ?", f.Mine.UserID)+ }+ }if f.InboxOnly {q = q.Where(notCollectForm)}@@ -215,6 +235,7 @@ func (r *MessageRepository) FindByUUIDForScope(scope ResourceScope, uuid string)err := ApplyWorkspaceScope(r.db, scope).Preload("Form").Preload("AssignedTo").+ Preload("Team").Preload("Replies", func(db *gorm.DB) *gorm.DB {return db.Order("created_at ASC").Preload("Author")}).@@ -244,6 +265,7 @@ func (r *MessageRepository) FindByScopeFiltered(scope ResourceScope, f MessageFiif err := apply(r.db).Preload("Form").Preload("AssignedTo").+ Preload("Team").Order("created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {diff --git a/internal/storage/repositories/team_repo.go b/internal/storage/repositories/team_repo.gonew file mode 100644index 0000000..cb9ed14--- /dev/null+++ b/internal/storage/repositories/team_repo.go@@ -0,0 +1,139 @@+// 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 repositories++import (+ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+ "gorm.io/gorm/clause"+)++type TeamRepository struct {+ db *gorm.DB+}++func NewTeamRepository(db *gorm.DB) *TeamRepository {+ return &TeamRepository{db: db}+}++func (r *TeamRepository) ListByWorkspace(workspaceID uint) ([]models.Team, error) {+ var teams []models.Team+ err := r.db.Preload("Members.User").Where("workspace_id = ?", workspaceID).Order("LOWER(name) ASC").Find(&teams).Error+ return teams, err+}++func (r *TeamRepository) FindForWorkspace(workspaceID, id uint) (*models.Team, error) {+ var team models.Team+ if err := r.db.Preload("Members.User").Where("workspace_id = ?", workspaceID).First(&team, id).Error; err != nil {+ return nil, err+ }+ return &team, nil+}++// FindByID loads a team with its member IDs, whatever the workspace; the+// worker checks the workspace itself.+func (r *TeamRepository) FindByID(id uint) (*models.Team, error) {+ var team models.Team+ if err := r.db.Preload("Members").First(&team, id).Error; err != nil {+ return nil, err+ }+ return &team, nil+}++func (r *TeamRepository) NameTaken(workspaceID uint, name string, exceptID uint) bool {+ var count int64+ r.db.Model(&models.Team{}).Where("workspace_id = ? AND LOWER(name) = LOWER(?) AND id <> ?", workspaceID, name, exceptID).Count(&count)+ return count > 0+}++func (r *TeamRepository) Create(team *models.Team) error {+ return r.db.Omit(clause.Associations).Create(team).Error+}++func (r *TeamRepository) Update(team *models.Team) error {+ return r.db.Omit(clause.Associations).Save(team).Error+}++// Delete removes a team and its memberships. Submissions routed to it stay+// where they are, without a team.+func (r *TeamRepository) Delete(id uint) error {+ return r.db.Transaction(func(tx *gorm.DB) error {+ if err := tx.Where("team_id = ?", id).Delete(&models.TeamMember{}).Error; err != nil {+ return err+ }+ if err := tx.Model(&models.Message{}).Where("team_id = ?", id).Update("team_id", nil).Error; err != nil {+ return err+ }+ return tx.Delete(&models.Team{}, id).Error+ })+}++// SetMembers replaces a team's members.+func (r *TeamRepository) SetMembers(teamID uint, userIDs []uint) error {+ return r.db.Transaction(func(tx *gorm.DB) error {+ if err := tx.Where("team_id = ?", teamID).Delete(&models.TeamMember{}).Error; err != nil {+ return err+ }+ for _, id := range userIDs {+ if err := tx.Create(&models.TeamMember{TeamID: teamID, UserID: id}).Error; err != nil {+ return err+ }+ }+ return nil+ })+}++// IDsForUser lists the workspace's teams the user is on.+func (r *TeamRepository) IDsForUser(workspaceID, userID uint) ([]uint, error) {+ var ids []uint+ err := r.db.Model(&models.TeamMember{}).+ Joins("JOIN teams ON teams.id = team_members.team_id AND teams.deleted_at IS NULL").+ Where("teams.workspace_id = ? AND team_members.user_id = ?", workspaceID, userID).+ Pluck("team_members.team_id", &ids).Error+ return ids, err+}++// IDs lists the workspace's team IDs, for checking rule destinations.+func (r *TeamRepository) IDs(workspaceID uint) ([]uint, error) {+ var ids []uint+ err := r.db.Model(&models.Team{}).Where("workspace_id = ?", workspaceID).Pluck("id", &ids).Error+ return ids, err+}++// RoutingDirectory answers the lookups routing rules expand recipients+// with (formrules.Directory).+type RoutingDirectory struct {+ Workspaces *WorkspaceRepository+ Teams *TeamRepository+}++func (d RoutingDirectory) Members(workspaceID uint) (map[uint]models.WorkspaceRole, error) {+ members, err := d.Workspaces.ListMembers(workspaceID)+ if err != nil {+ return nil, err+ }+ out := make(map[uint]models.WorkspaceRole, len(members))+ for _, m := range members {+ out[m.UserID] = m.Role+ }+ return out, nil+}++func (d RoutingDirectory) Team(id uint) (*models.Team, error) { return d.Teams.FindByID(id) }diff --git a/internal/storage/repositories/workspace_repo.go b/internal/storage/repositories/workspace_repo.goindex 18d7d56..7a5da09 100644--- a/internal/storage/repositories/workspace_repo.go+++ b/internal/storage/repositories/workspace_repo.go@@ -173,9 +173,17 @@ func (r *WorkspaceRepository) AddMember(member *models.WorkspaceMember) error {}// RemoveMember removes a user from a workspace.+// RemoveMember takes a user out of a workspace, and off its teams with it.func (r *WorkspaceRepository) RemoveMember(workspaceID, userID uint) error {- return r.db.Where("workspace_id = ? AND user_id = ?", workspaceID, userID).- Delete(&models.WorkspaceMember{}).Error+ return r.db.Transaction(func(tx *gorm.DB) error {+ if err := tx.Where("user_id = ? AND team_id IN (?)", userID,+ tx.Model(&models.Team{}).Select("id").Where("workspace_id = ?", workspaceID)).+ Delete(&models.TeamMember{}).Error; err != nil {+ return err+ }+ return tx.Where("workspace_id = ? AND user_id = ?", workspaceID, userID).+ Delete(&models.WorkspaceMember{}).Error+ })}// UpdateMemberRole updates a member's role in a workspace.diff --git a/internal/web/widget/posta-form.js b/internal/web/widget/posta-form.jsindex 927a3c6..080a6f5 100644--- a/internal/web/widget/posta-form.js+++ b/internal/web/widget/posta-form.js@@ -34,6 +34,9 @@error: "Your message could not be sent. Please try again.",poweredBy: "Powered by",previewOnly: "Preview only: nothing was sent.",+ next: "Next",+ back: "Back",+ page: "Page {n} of {total}",},fr: {name: "Nom",@@ -55,6 +58,9 @@error: "Votre message n'a pas pu être envoyé. Veuillez réessayer.",poweredBy: "Propulsé par",previewOnly: "Aperçu uniquement : rien n'a été envoyé.",+ next: "Suivant",+ back: "Retour",+ page: "Page {n} sur {total}",},};@@ -88,6 +94,8 @@".pf[data-theme=dark]{--t-bg:#101A37;--t-fg:#F2F4FA;--t-mut:#A9B1CC;--t-bd:#2A3A66;--t-in:#0A1124;--t-err:#FDA29B;--t-ok:#75E0A7}" +"@media (prefers-color-scheme:dark){.pf[data-theme=auto]{--t-bg:#101A37;--t-fg:#F2F4FA;--t-mut:#A9B1CC;--t-bd:#2A3A66;--t-in:#0A1124;--t-err:#FDA29B;--t-ok:#75E0A7}}" +".pf *{box-sizing:border-box}" ++ // Display rules below would otherwise beat the hidden attribute.+ ".pf [hidden]{display:none!important}" +".pf h2{margin:0 0 14px;font-size:1.2em;line-height:1.3}" +".pf .desc{margin:-10px 0 14px;color:var(--mut)}" +".pf .f{margin:0 0 12px}" +@@ -127,6 +135,13 @@".pf .st.err{color:var(--err)}" +".pf .done{margin:4px 0;color:var(--ok);font-weight:600}" +".pf button.again{margin-top:10px;background:none;color:var(--a);padding:0;min-height:0;text-decoration:underline}" ++ ".pf .sec h3{margin:0 0 4px;font-size:1.05em;line-height:1.3}" ++ ".pf .sec p{margin:0 0 12px;color:var(--mut);white-space:pre-line}" ++ ".pf .prog{margin:0 0 14px;font-size:.8em;color:var(--mut)}" ++ ".pf .bar{height:4px;margin-top:4px;border-radius:2px;background:var(--bd);overflow:hidden}" ++ ".pf .bar span{display:block;height:100%;width:0;background:var(--a);transition:width .2s}" ++ ".pf .nav{display:flex;flex-wrap:wrap;gap:8px;align-items:center}" ++ ".pf button.back{background:none;color:var(--a);border:1px solid var(--bd)}" +".pf .brand{display:flex;justify-content:flex-end;margin-top:16px;padding-top:10px;border-top:1px solid var(--bd)}" +".pf .brand a{display:inline-flex;align-items:center;gap:5px;font-size:12px;color:var(--mut);text-decoration:none}" +".pf .brand a:hover{color:var(--fg)}" +@@ -496,24 +511,148 @@var controls = {};+ // Sections split the questions into pages, shown one at a time. Hidden+ // fields sit on no page; the embed sets them. A form without sections+ // is one page and looks as it always did.+ var pages = [{ section: null, keys: [], node: h("div") }];+ var loose = h("div");fields.forEach(function (f) {+ if (f.type === "section") {+ var node = h("div");+ var head = h("div", { class: "sec" });+ head.appendChild(h("h3", null, f.label || f.key));+ if (f.help) head.appendChild(h("p", null, f.help));+ node.appendChild(head);+ pages.push({ section: f, keys: [], node: node });+ return;+ }var c = buildField(f, id + "-" + f.key);+ c.def = f;controls[f.key] = c;- form.appendChild(c.row);+ if (f.type === "hidden") {+ loose.appendChild(c.row);+ return;+ }+ var last = pages[pages.length - 1];+ last.keys.push(f.key);+ last.node.appendChild(c.row);+ });+ if (pages.length > 1 && !pages[0].keys.length) pages.shift();+ var paged = pages.length > 1;+ var sectionIndex = {};+ pages.forEach(function (p, i) {+ if (p.section) sectionIndex[p.section.key] = i;});+ var progressText = null;+ var barFill = null;+ if (paged) {+ var progress = h("div", { class: "prog" });+ progressText = h("span");+ var bar = h("div", { class: "bar", "aria-hidden": "true" });+ barFill = h("span");+ bar.appendChild(barFill);+ progress.appendChild(progressText);+ progress.appendChild(bar);+ form.appendChild(progress);+ // The widget checks one page at a time, so the browser must not+ // block submit over a required field on a page that was skipped.+ form.setAttribute("novalidate", "");+ }+ pages.forEach(function (p) { form.appendChild(p.node); });+ form.appendChild(loose);++ // nextPage mirrors the server's route (services/messages/branching.go):+ // the chosen option of a branching question, else the section's next,+ // else the following page. -1 means the form is submitted from page i.+ function nextPage(i) {+ var p = pages[i];+ var target = (p.section && p.section.next) || "";+ p.keys.forEach(function (k) {+ var f = controls[k].def;+ if (f.type !== "select") return;+ var v = controls[k].get();+ (f.options || []).forEach(function (o) {+ if (o.value === v && o.goto) target = o.goto;+ });+ });+ if (target === "submit") return -1;+ if (target && sectionIndex[target] > i) return sectionIndex[target];+ return i + 1 < pages.length ? i + 1 : -1;+ }++ var current = 0;+ var trail = []; // pages visited before the current one, in order+var hpWrap = h("div", { class: "hp", "aria-hidden": "true" });var honeypot = h("input", { type: "text", name: cfg.honeypot_field || "_gotcha", tabindex: "-1", autocomplete: "off" });hpWrap.appendChild(honeypot);form.appendChild(hpWrap);var buttonText = el.getAttribute("data-button") || t.button;+ var nav = h("div", { class: "nav" });+ var backButton = h("button", { type: "button", class: "back", hidden: true }, t.back);var button = h("button", { type: "submit" }, buttonText);- form.appendChild(button);+ nav.appendChild(backButton);+ nav.appendChild(button);+ form.appendChild(nav);var status = h("p", { class: "st", role: "status", "aria-live": "polite" });form.appendChild(status);body.appendChild(form);+ // isLast decides the button: Next while the answers lead to another+ // page, the submit text once they lead to the end.+ function isLast() { return nextPage(current) < 0; }++ function showPage(i, focus) {+ current = i;+ pages.forEach(function (p, j) { p.node.hidden = j !== i; });+ backButton.hidden = !trail.length;+ if (paged) {+ progressText.textContent = t.page.replace("{n}", i + 1).replace("{total}", pages.length);+ barFill.style.width = Math.round(((i + 1) / pages.length) * 100) + "%";+ }+ if (!button.disabled) button.textContent = isLast() ? buttonText : t.next;+ if (focus) {+ var first = pages[i].node.querySelector("input,select,textarea");+ if (first) first.focus();+ else wrap.scrollIntoView({ block: "nearest" });+ }+ }++ // pageValid checks the current page the way the browser would, plus+ // required checkbox groups, which have no native check.+ function pageValid() {+ if (preview && paged) return true;+ var keys = paged ? pages[current].keys : Object.keys(controls);+ var inputs = paged ? pages[current].node.querySelectorAll("input,select,textarea") : [];+ for (var n = 0; n < inputs.length; n++) {+ if (!inputs[n].checkValidity()) {+ inputs[n].reportValidity();+ return false;+ }+ }+ for (var k = 0; k < keys.length; k++) {+ var c = controls[keys[k]];+ if (c.requiredGroup && !c.get().length) {+ c.mark(t.required);+ c.focus();+ return false;+ }+ }+ return true;+ }++ backButton.addEventListener("click", function () {+ clearErrors();+ showPage(trail.pop(), true);+ });+ // A changed answer can change where a branching page leads.+ form.addEventListener("change", function () {+ if (!button.disabled) button.textContent = isLast() ? buttonText : t.next;+ });+ showPage(0, false);+function clearErrors() {status.textContent = "";status.className = "st";@@ -539,22 +678,22 @@form.addEventListener("submit", function (e) {e.preventDefault();clearErrors();+ if (!pageValid()) return;+ var after = nextPage(current);+ if (after >= 0) {+ trail.push(current);+ showPage(after, true);+ return;+ }+ // Only the pages the respondent went through are sent, plus hidden+ // fields; the server applies the same route.var payload = {};- var missing = null;+ var sent = trail.concat([current]);Object.keys(controls).forEach(function (k) {var c = controls[k];- payload[k] = c.get();- if (c.requiredGroup && !payload[k].length) {- c.mark(t.required);- missing = missing || c;- }+ var onRoute = c.def.type === "hidden" || sent.some(function (i) { return pages[i].keys.indexOf(k) >= 0; });+ if (onRoute) payload[k] = c.get();});- // Native validation covers single inputs; a required group of- // checkboxes has no native check.- if (missing) {- missing.focus();- return;- }if (preview) {status.textContent = t.previewOnly;return;@@ -604,7 +743,15 @@var c = controls[fe.key];if (!c) return;c.mark(fe.message || fe.code);- first = first || c;+ if (!first) {+ first = c;+ // Go back to the page that holds the first error.+ var at = sent.filter(function (i) { return pages[i].keys.indexOf(fe.key) >= 0; })[0];+ if (at !== undefined && at !== current) {+ trail = trail.slice(0, trail.indexOf(at));+ showPage(at, false);+ }+ }});var message = data.message || (res.body && res.body.error && res.body.error.message) || (res.body && res.body.message) || t.error;if (!first) fail(message);@@ -621,7 +768,7 @@).then(function () {button.disabled = false;- button.textContent = buttonText;+ button.textContent = isLast() ? buttonText : t.next;});});diff --git a/internal/worker/message_handler.go b/internal/worker/message_handler.goindex 694a686..90982e7 100644--- a/internal/worker/message_handler.go+++ b/internal/worker/message_handler.go@@ -28,6 +28,7 @@ import ("github.com/goposta/posta/internal/dto""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/formrules""github.com/goposta/posta/internal/services/messages""github.com/goposta/posta/internal/services/notification""github.com/goposta/posta/internal/services/realtime"@@ -35,6 +36,7 @@ import ("github.com/goposta/posta/internal/storage/repositories""github.com/hibiken/asynq""github.com/jkaninda/logger"+ "github.com/lib/pq")type MessageWebhookPayload struct {@@ -54,6 +56,15 @@ type MessageWebhookPayload struct {ScanReasons []string `json:"scan_reasons,omitempty"`ClientIP string `json:"client_ip,omitempty"`ReceivedAt string `json:"received_at"`++ // Typed answers and routing, for forms with questions and rules.+ Data models.SubmissionData `json:"data,omitempty"`+ SchemaVersion int `json:"schema_version,omitempty"`+ Tags []string `json:"tags"`+ Priority string `json:"priority"`+ TeamID *uint `json:"team_id,omitempty"`+ AssignedToID *uint `json:"assigned_to_id,omitempty"`+ MatchedRules []string `json:"matched_rules,omitempty"`}// messageStore is the slice of MessageRepository the worker needs; an interface@@ -71,6 +82,12 @@ type formStore interface {type jsonDispatcher interface {DispatchJSON(userID uint, workspaceID *uint, event string, body []byte, fromAddr string)+ DispatchJSONTo(workspaceID uint, webhookIDs []uint, event string, body []byte)+}++type ruleStore interface {+ ListByForm(formID uint) ([]models.FormRule, error)+ RecordHits(uuids []string, at time.Time) error}type messageNotifier interface {@@ -87,6 +104,8 @@ type MessageProcessHandler struct {dispatcher jsonDispatchernotifier messageNotifierrealtime realtime.Bus+ rules ruleStore+ directory formrules.DirectoryappURL stringonNotified func()// retryCount reports how many times Asynq has already tried this task.@@ -125,6 +144,14 @@ func NewMessageProcessHandler(func (h *MessageProcessHandler) OnNotified(fn func()) { h.onNotified = fn }+// SetRouting enables a form's routing rules.+func (h *MessageProcessHandler) SetRouting(rules *repositories.FormRuleRepository, dir formrules.Directory) {+ if rules != nil {+ h.rules = rules+ }+ h.directory = dir+}+// SetRealtime enables live dashboard events for processed messages.func (h *MessageProcessHandler) SetRealtime(b realtime.Bus) { h.realtime = b }@@ -151,8 +178,10 @@ func (h *MessageProcessHandler) ProcessTask(ctx context.Context, t *asynq.Task)return fmt.Errorf("form not found: %w", err)}+ outcome := h.route(msg, form)+if msg.WebhookDispatchedAt == nil {- h.dispatch(msg, form)+ h.dispatch(msg, form, outcome.Webhooks)now := time.Now().UTC()if err := h.messageRepo.UpdateFields(msg.ID, map[string]any{"webhook_dispatched_at": now}); err != nil {logger.Error("failed to mark message webhook dispatched", "message_id", msg.ID, "error", err)@@ -163,7 +192,7 @@ func (h *MessageProcessHandler) ProcessTask(ctx context.Context, t *asynq.Task)}if msg.NotifiedAt == nil && h.shouldNotify(msg, form) {- if err := h.notify(msg, form); err != nil {+ if err := h.notify(msg, form, outcome); err != nil {return fmt.Errorf("notify message %d: %w", msg.ID, err)}if err := h.messageRepo.MarkNotified([]uint{msg.ID}, time.Now().UTC()); err != nil {@@ -190,7 +219,99 @@ func (h *MessageProcessHandler) shouldNotify(msg *models.Message, form *models.Freturn true}-func (h *MessageProcessHandler) dispatch(msg *models.Message, form *models.Form) {+// route applies the form's rules to a submission once: assignment, team,+// tags, priority and the matched rules are stored, and the outcome is+// returned for the webhooks and notifications that follow. On a retry the+// stored matches are replayed instead of re-evaluated, so a rule edited in+// between cannot route the same submission twice.+func (h *MessageProcessHandler) route(msg *models.Message, form *models.Form) formrules.Outcome {+ if h.rules == nil || !formrules.Routable(msg.Status) {+ return formrules.Outcome{}+ }+ rules, err := h.rules.ListByForm(form.ID)+ if err != nil {+ logger.Error("failed to load routing rules", "form_id", form.ID, "error", err)+ return formrules.Outcome{}+ }+ if msg.RoutedAt != nil {+ return formrules.Combine(rules, msg.MatchedRules)+ }+ out := formrules.Evaluate(rules, formrules.FactsFor(msg, form))+ now := time.Now().UTC()+ fields := map[string]any{"routed_at": now}+ if len(out.Matched) > 0 {+ fields["matched_rules"] = pq.StringArray(out.Matched)+ msg.MatchedRules = out.Matched+ if out.AssignUser != nil && msg.AssignedToID == nil && h.isMember(form, *out.AssignUser) {+ fields["assigned_to_id"], msg.AssignedToID = *out.AssignUser, out.AssignUser+ }+ if out.AssignTeam != nil && msg.TeamID == nil && h.ownsTeam(form, *out.AssignTeam) {+ fields["team_id"], msg.TeamID = *out.AssignTeam, out.AssignTeam+ }+ if len(out.Tags) > 0 {+ tags := mergeTags(msg.Tags, out.Tags)+ fields["tags"], msg.Tags = pq.StringArray(tags), tags+ }+ if higherPriority(out.Priority, string(msg.Priority)) {+ fields["priority"], msg.Priority = out.Priority, models.MessagePriority(out.Priority)+ }+ }+ if err := h.messageRepo.UpdateFields(msg.ID, fields); err != nil {+ logger.Error("failed to store routing", "message_id", msg.ID, "error", err)+ return out+ }+ msg.RoutedAt = &now+ if err := h.rules.RecordHits(out.Matched, now); err != nil {+ logger.Warn("failed to count rule hits", "form_id", form.ID, "error", err)+ }+ return out+}++func (h *MessageProcessHandler) isMember(form *models.Form, userID uint) bool {+ if h.directory == nil || form.WorkspaceID == nil {+ return false+ }+ members, err := h.directory.Members(*form.WorkspaceID)+ _, ok := members[userID]+ return err == nil && ok+}++func (h *MessageProcessHandler) ownsTeam(form *models.Form, teamID uint) bool {+ if h.directory == nil || form.WorkspaceID == nil {+ return false+ }+ team, err := h.directory.Team(teamID)+ return err == nil && team.WorkspaceID != nil && *team.WorkspaceID == *form.WorkspaceID+}++// mergeTags adds rule tags to the submission's, keeping within MaxTags.+func mergeTags(current, add []string) []string {+ out := append([]string{}, current...)+ seen := map[string]bool{}+ for _, t := range out {+ seen[t] = true+ }+ for _, t := range add {+ if !seen[t] && len(out) < messages.MaxTags {+ seen[t] = true+ out = append(out, t)+ }+ }+ return out+}++var priorityRank = map[string]int{"low": 1, "normal": 2, "high": 3, "urgent": 4}++// higherPriority: a rule only raises priority, so it never quietens a+// submission an operator already marked urgent.+func higherPriority(candidate, current string) bool {+ if current == "" {+ current = string(models.MessagePriorityNormal)+ }+ return candidate != "" && priorityRank[candidate] > priorityRank[current]+}++func (h *MessageProcessHandler) dispatch(msg *models.Message, form *models.Form, ruleWebhooks []uint) {if h.dispatcher == nil {return}@@ -222,6 +343,20 @@ func (h *MessageProcessHandler) dispatch(msg *models.Message, form *models.Form)ScanReasons: []string(msg.ScanReasons),ClientIP: msg.ClientIP,ReceivedAt: msg.CreatedAt.UTC().Format(time.RFC3339),++ Data: msg.Data,+ SchemaVersion: msg.SchemaVersion,+ Tags: []string(msg.Tags),+ Priority: string(msg.Priority),+ TeamID: msg.TeamID,+ AssignedToID: msg.AssignedToID,+ MatchedRules: []string(msg.MatchedRules),+ }+ if body.Tags == nil {+ body.Tags = []string{}+ }+ if body.Priority == "" {+ body.Priority = string(models.MessagePriorityNormal)}encoded, err := json.Marshal(body)@@ -230,9 +365,12 @@ func (h *MessageProcessHandler) dispatch(msg *models.Message, form *models.Form)return}h.dispatcher.DispatchJSON(0, msg.WorkspaceID, event, encoded, msg.SenderEmail)+ if len(ruleWebhooks) > 0 && msg.WorkspaceID != nil {+ h.dispatcher.DispatchJSONTo(*msg.WorkspaceID, ruleWebhooks, event, encoded)+ }}-func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form) error {+func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form, outcome formrules.Outcome) error {if h.notifier == nil || !h.notifier.IsConfigured() {return nil}@@ -269,7 +407,40 @@ func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form) e"MessageURL": h.messageURL(msg.UUID),}- return h.sendToFormRecipients(msg, form, subject, data)+ return h.sendRouted(msg, form, outcome, subject, data)+}++// sendRouted notifies the form's default route, unless a rule suppressed it,+// and the recipients the rules added. It returns the last error, so a retry+// may repeat a notification that already went out; that beats one never+// arriving.+func (h *MessageProcessHandler) sendRouted(msg *models.Message, form *models.Form, outcome formrules.Outcome, subject string, data map[string]any) error {+ res := formrules.Resolved{Default: true}+ if h.directory != nil {+ resolved, err := formrules.Resolve(form, outcome, h.directory)+ if err != nil {+ return fmt.Errorf("resolve rule recipients: %w", err)+ }+ res = resolved+ }+ h.addWorkspaceName(msg, data)+ var lastErr error+ if res.Default {+ lastErr = h.sendToFormRecipients(msg, form, subject, data)+ }+ for _, to := range res.Emails {+ payload := cloneData(data)+ payload["UserName"] = "there"+ if err := h.notifier.Send(to, subject, notification.TemplateNewMessage, payload); err != nil {+ lastErr = err+ }+ }+ for _, id := range res.UserIDs {+ if err := h.notifier.SendToUser(id, subject, notification.TemplateNewMessage, cloneData(data)); err != nil {+ lastErr = err+ }+ }+ return lastErr}// sendToFormRecipients delivers to the form's explicit notification list, or@@ -277,13 +448,7 @@ func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form) e// addresses it returns the last error: a retry may then repeat a notification// to an address that already got it, which beats one never arriving.func (h *MessageProcessHandler) sendToFormRecipients(msg *models.Message, form *models.Form, subject string, data map[string]any) error {- if h.workspaceRepo != nil && msg.WorkspaceID != nil {- if _, ok := data["WorkspaceName"]; !ok {- if ws, err := h.workspaceRepo.FindByID(*msg.WorkspaceID); err == nil && ws.Name != "" {- data["WorkspaceName"] = ws.Name- }- }- }+ h.addWorkspaceName(msg, data)if len(form.NotifyEmails) > 0 {var lastErr errorfor _, to := range form.NotifyEmails {@@ -306,6 +471,17 @@ func (h *MessageProcessHandler) sendToFormRecipients(msg *models.Message, form *return h.notifier.SendToWorkspaceAdmins(*msg.WorkspaceID, subject, notification.TemplateNewMessage, data)}+func (h *MessageProcessHandler) addWorkspaceName(msg *models.Message, data map[string]any) {+ if h.workspaceRepo == nil || msg.WorkspaceID == nil {+ return+ }+ if _, ok := data["WorkspaceName"]; !ok {+ if ws, err := h.workspaceRepo.FindByID(*msg.WorkspaceID); err == nil && ws.Name != "" {+ data["WorkspaceName"] = ws.Name+ }+ }+}+func (h *MessageProcessHandler) messageURL(uuid string) string {if h.appURL == "" {return ""diff --git a/internal/worker/message_process_test.go b/internal/worker/message_process_test.goindex 09ca2f5..7a43bea 100644--- a/internal/worker/message_process_test.go+++ b/internal/worker/message_process_test.go@@ -30,6 +30,7 @@ import ("github.com/goposta/posta/internal/services/messages""github.com/goposta/posta/internal/services/realtime""github.com/hibiken/asynq"+ "github.com/lib/pq")type fakeMessageStore struct {@@ -52,6 +53,12 @@ func (f *fakeMessageStore) UpdateFields(_ uint, fields map[string]any) error {if v, ok := fields["webhook_dispatched_at"].(time.Time); ok {f.msg.WebhookDispatchedAt = &v}+ if v, ok := fields["routed_at"].(time.Time); ok {+ f.msg.RoutedAt = &v+ if m, ok := fields["matched_rules"].(pq.StringArray); ok {+ f.msg.MatchedRules = m+ }+ }return nil}@@ -72,15 +79,23 @@ type fakeFormStore struct{ form *models.Form }func (f fakeFormStore) FindByID(uint) (*models.Form, error) { return f.form, nil }-type fakeDispatcher struct{ events []string }+type fakeDispatcher struct {+ events []string+ direct []uint+}func (f *fakeDispatcher) DispatchJSON(_ uint, _ *uint, event string, _ []byte, _ string) {f.events = append(f.events, event)}+func (f *fakeDispatcher) DispatchJSONTo(_ uint, ids []uint, _ string, _ []byte) {+ f.direct = append(f.direct, ids...)+}+type fakeNotifier struct {- err error- sent []string // "to:<addr>", "user", or "admins"+ err error+ sent []string // "to:<addr>", "user", or "admins"+ users []uint}func (f *fakeNotifier) IsConfigured() bool { return true }@@ -90,6 +105,7 @@ func (f *fakeNotifier) Send(to, _, _ string, _ map[string]any) error {}func (f *fakeNotifier) SendToUser(userID uint, _, _ string, _ map[string]any) error {f.sent = append(f.sent, "user")+ f.users = append(f.users, userID)return f.err}func (f *fakeNotifier) SendToWorkspaceAdmins(uint, string, string, map[string]any) error {diff --git a/internal/worker/routing_test.go b/internal/worker/routing_test.gonew file mode 100644index 0000000..5b97bb4--- /dev/null+++ b/internal/worker/routing_test.go@@ -0,0 +1,167 @@+// 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 worker++import (+ "context"+ "errors"+ "fmt"+ "reflect"+ "testing"+ "time"++ "github.com/goposta/posta/internal/models"+)++type fakeRules struct {+ rules []models.FormRule+ hits [][]string+}++func (f *fakeRules) ListByForm(uint) ([]models.FormRule, error) { return f.rules, nil }+func (f *fakeRules) RecordHits(uuids []string, _ time.Time) error {+ f.hits = append(f.hits, uuids)+ return nil+}++type fakeDirectory struct{ ws uint }++func (f fakeDirectory) Members(uint) (map[uint]models.WorkspaceRole, error) {+ return map[uint]models.WorkspaceRole{1: models.WorkspaceRoleOwner, 7: models.WorkspaceRoleEditor, 8: models.WorkspaceRoleEditor}, nil+}++func (f fakeDirectory) Team(id uint) (*models.Team, error) {+ if id != 3 {+ return nil, errors.New("not found")+ }+ return &models.Team{ID: 3, WorkspaceID: &f.ws, Email: "[email protected]", Members: []models.TeamMember{{UserID: 8}}}, nil+}++func salesRule(suppress bool) models.FormRule {+ team, hook := uint(3), uint(9)+ actions := models.RuleActions{+ {Type: models.ActionNotifyTeam, TeamID: &team},+ {Type: models.ActionAssignTeam, TeamID: &team},+ {Type: models.ActionAssignMember, UserIDs: []uint{7}},+ {Type: models.ActionAddTags, Tags: []string{"lead"}},+ {Type: models.ActionSetPriority, Priority: "high"},+ {Type: models.ActionWebhook, WebhookID: &hook},+ }+ if suppress {+ actions = append(actions, models.RuleAction{Type: models.ActionSuppressDefault})+ }+ return models.FormRule{+ UUID: "r-sales", Name: "Sales", Enabled: true,+ Conditions: models.RuleConditions{{Field: "dept", Op: "eq", Value: "sales"}},+ Actions: actions,+ }+}++func routedFixture(suppress bool) (*MessageProcessHandler, *fakeMessageStore, *fakeDispatcher, *fakeNotifier, *fakeRules) {+ ws := uint(5)+ form := immediateForm()+ form.WorkspaceID = &ws+ form.Fields = models.FieldDefs{{Key: "dept", Label: "Dept", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "sales"}}}}+ store := &fakeMessageStore{msg: &models.Message{+ ID: 1, WorkspaceID: &ws, Status: models.MessageStatusReceived,+ Data: models.SubmissionData{"dept": "sales"}, Tags: []string{"existing"},+ }}+ h, d, n := newTestHandler(store, form)+ rules := &fakeRules{rules: []models.FormRule{salesRule(suppress)}}+ h.rules, h.directory = rules, fakeDirectory{ws: ws}+ return h, store, d, n, rules+}++func TestProcessTaskAppliesRulesOnce(t *testing.T) {+ h, store, d, n, rules := routedFixture(false)+ n.err = errors.New("smtp down")+ if err := h.ProcessTask(context.Background(), processTask(t)); err == nil {+ t.Fatal("a failed notification must fail the task")+ }++ m := store.msg+ if m.RoutedAt == nil || !reflect.DeepEqual([]string(m.MatchedRules), []string{"r-sales"}) {+ t.Fatalf("not routed: %+v", m)+ }+ routing := store.updates[0]+ if routing["team_id"] != uint(3) || routing["assigned_to_id"] != uint(7) || routing["priority"] != "high" {+ t.Errorf("routing update %+v", routing)+ }+ if tags := fmt.Sprint(routing["tags"]); tags != "[existing lead]" {+ t.Errorf("tags %s", tags)+ }+ if !reflect.DeepEqual(d.direct, []uint{9}) {+ t.Errorf("rule webhook dispatched to %v", d.direct)+ }+ // Default route (admins) plus the team: its member and its address.+ // The owner is already among the admins.+ if !reflect.DeepEqual(n.sent, []string{"admins", "to:[email protected]", "user"}) || !reflect.DeepEqual(n.users, []uint{8}) {+ t.Errorf("sent %v users %v", n.sent, n.users)+ }++ // The retry notifies the same people, without routing or counting again.+ n.err, n.sent, n.users = nil, nil, nil+ updates := len(store.updates)+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {+ t.Fatal(err)+ }+ if len(rules.hits) != 1 {+ t.Errorf("rule hits recorded %d times", len(rules.hits))+ }+ if len(store.updates) != updates || len(d.direct) != 1 {+ t.Errorf("the retry routed or dispatched again: %d updates, direct %v", len(store.updates)-updates, d.direct)+ }+ if !reflect.DeepEqual(n.sent, []string{"admins", "to:[email protected]", "user"}) {+ t.Errorf("retry sent %v", n.sent)+ }+}++func TestProcessTaskSuppressedDefault(t *testing.T) {+ h, _, _, n, _ := routedFixture(true)+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(n.sent, []string{"to:[email protected]", "user"}) {+ t.Errorf("sent %v", n.sent)+ }+}++func TestProcessTaskNoMatchKeepsDefault(t *testing.T) {+ h, store, d, n, _ := routedFixture(true)+ store.msg.Data = models.SubmissionData{"dept": "support"}+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(n.sent, []string{"admins"}) || len(d.direct) != 0 || store.msg.TeamID != nil {+ t.Errorf("unmatched submission: sent %v direct %v", n.sent, d.direct)+ }+ if store.msg.RoutedAt == nil {+ t.Error("an unmatched submission is still marked routed")+ }+}++func TestRulesNeverLowerPriority(t *testing.T) {+ if higherPriority("high", "urgent") || !higherPriority("high", "") || higherPriority("", "low") {+ t.Error("higherPriority")+ }+ if got := mergeTags([]string{"a"}, []string{"a", "b"}); !reflect.DeepEqual(got, []string{"a", "b"}) {+ t.Errorf("mergeTags = %v", got)+ }+}diff --git a/web/src/api/messages.ts b/web/src/api/messages.tsindex 17fe96d..1205f4e 100644--- a/web/src/api/messages.ts+++ b/web/src/api/messages.ts@@ -15,6 +15,11 @@ import type {SubmissionQuery,SubmissionSummary,TagCount,+ FormRule,+ FormRuleInput,+ RuleTestResult,+ Team,+ TeamInput,} from './types'const WORKSPACE_KEY = 'posta_workspace_id'@@ -73,6 +78,8 @@ export interface MessageListParams {before?: stringtag?: stringpriority?: string+ team_id?: number+ mine?: boolean}export interface FilterPayload {@@ -162,6 +169,9 @@ export const messagesApi = {tags() {return api.get<ApiResponse<TagCount[]>>('/workspaces/current/message-tags')},+ setTeam(uuid: string, teamId: number | null) {+ return api.put<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/team`, { team_id: teamId })+ },markSpam(uuid: string, payload: { create_filter?: boolean; pattern?: string; kind?: string } = {}) {return api.post<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/spam`, payload)},@@ -242,3 +252,40 @@ export const formSubmissionsApi = {return `/api/v1/workspaces/current/form-submissions/export?${params.toString()}${ws ? '&' + ws : ''}`},}++// Routing rules belong to a form and run in order.+export const formRulesApi = {+ list(formId: number) {+ return api.get<ApiResponse<FormRule[]>>(`/workspaces/current/forms/${formId}/rules`)+ },+ create(formId: number, rule: FormRuleInput) {+ return api.post<ApiResponse<FormRule>>(`/workspaces/current/forms/${formId}/rules`, rule)+ },+ update(formId: number, ruleId: number, rule: FormRuleInput) {+ return api.put<ApiResponse<FormRule>>(`/workspaces/current/forms/${formId}/rules/${ruleId}`, rule)+ },+ delete(formId: number, ruleId: number) {+ return api.delete(`/workspaces/current/forms/${formId}/rules/${ruleId}`)+ },+ reorder(formId: number, ids: number[]) {+ return api.put<ApiResponse<FormRule[]>>(`/workspaces/current/forms/${formId}/rules/order`, { ids })+ },+ test(formId: number, rules?: FormRuleInput[], limit = 100) {+ return api.post<ApiResponse<RuleTestResult>>(`/workspaces/current/forms/${formId}/rules/test`, { rules, limit })+ },+}++export const teamsApi = {+ list() {+ return api.get<ApiResponse<Team[]>>('/workspaces/current/teams')+ },+ create(team: TeamInput) {+ return api.post<ApiResponse<Team>>('/workspaces/current/teams', team)+ },+ update(id: number, team: TeamInput) {+ return api.put<ApiResponse<Team>>(`/workspaces/current/teams/${id}`, team)+ },+ delete(id: number) {+ return api.delete(`/workspaces/current/teams/${id}`)+ },+}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 006923e..07272c7 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -1291,11 +1291,15 @@ export interface Form {export interface FormFieldOption {value: stringlabel?: string+ /** Single choice only: a later section's key, or "submit". */+ goto?: string}export type FormFieldType =| 'text' | 'textarea' | 'email' | 'phone' | 'number' | 'url' | 'date' | 'time'| 'select' | 'multiselect' | 'checkbox' | 'scale' | 'rating' | 'hidden'+ /** Not a question: starts a new page. */+ | 'section'export type FormFieldRole = '' | 'sender_email' | 'sender_name' | 'sender_phone' | 'subject' | 'body'@@ -1318,6 +1322,8 @@ export interface FormField {placeholder?: stringhelp?: stringarchived?: boolean+ /** Sections only: where the page leads, a later section's key or "submit". */+ next?: string}export interface FormAppearance {@@ -1368,6 +1374,11 @@ export interface Message {scan_reasons: string[] | nulltags: string[]priority: MessagePriority+ team_id?: number | null+ team?: { id: number; name: string } | null+ matched_rules?: string[] | null+ /** The rules that routed this submission, by name. */+ routed_by?: { uuid: string; name: string }[]notified_at?: string | nullassigned_to_id?: number | nullread_at?: string | null@@ -1468,3 +1479,87 @@ export interface TagCount {tag: stringcount: number}++export type RuleOp =+ | 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'not_contains' | 'matches'+ | 'exists' | 'not_exists' | 'gt' | 'gte' | 'lt' | 'lte'++export interface RuleCondition {+ /** A question key, or a built-in: $origin, $referer, $sender_email, $spam_score, $status. */+ field: string+ op: RuleOp+ value?: string | number | boolean | string[] | null+}++export type RuleActionType =+ | 'notify_emails' | 'notify_members' | 'notify_team' | 'assign_member' | 'assign_team'+ | 'add_tags' | 'set_priority' | 'webhook' | 'suppress_default'++export interface RuleAction {+ type: RuleActionType+ emails?: string[]+ user_ids?: number[]+ team_id?: number | null+ tags?: string[]+ priority?: string+ webhook_id?: number | null+}++export interface FormRule {+ id: number+ uuid: string+ form_id: number+ name: string+ position: number+ enabled: boolean+ match: 'all' | 'any'+ conditions: RuleCondition[]+ actions: RuleAction[]+ stop: boolean+ hit_count: number+ last_hit_at?: string | null+ created_at: string+ updated_at?: string | null+}++export type FormRuleInput = Pick<FormRule, 'name' | 'enabled' | 'match' | 'conditions' | 'actions' | 'stop'>++export interface RuleOutcome {+ notify?: { email?: string; user_id?: number; team_id?: number }[]+ assign_user?: number+ assign_team?: number+ tags?: string[]+ priority?: string+ webhooks?: number[]+ suppress_default?: boolean+ matched?: string[]+}++export interface RuleTestResult {+ scanned: number+ matched: number+ rules: { index: number; name: string; matches: number }[]+ samples: {+ message_uuid: string+ sender: string+ subject: string+ received_at: string+ matched: number[]+ outcome: RuleOutcome+ }[]+}++export interface Team {+ id: number+ uuid: string+ name: string+ email: string+ members?: { team_id: number; user_id: number; user?: { id: number; name: string } | null }[]+ created_at: string+}++export interface TeamInput {+ name: string+ email?: string+ user_ids: number[]+}diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex 8f34ec6..70af8ea 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -162,6 +162,7 @@ const workspaceNavSections: NavSection[] = [icon: 'message-square',children: [{ name: 'Forms', path: '/forms', icon: 'edit-3' },+ { name: 'Teams', path: '/teams', icon: 'users' },{ name: 'Spam Filters', path: '/message-filters', icon: 'shield' },],},diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex d54e3ad..a000cda 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -63,6 +63,7 @@ const routes = [{ path: 'inbound-emails/:id', name: 'inbound-email-detail', component: () => import('../views/inbound/InboundEmailDetail.vue'), meta: { title: 'Inbound Email' } },{ path: 'messages', name: 'messages', component: () => import('../views/messages/Messages.vue'), meta: { title: 'Messages' } },{ path: 'messages/:id', name: 'message-detail', component: () => import('../views/messages/MessageDetail.vue'), meta: { title: 'Message' } },+ { path: 'teams', name: 'teams', component: () => import('../views/teams/Teams.vue'), meta: { title: 'Teams' } },{ path: 'message-filters', name: 'message-filters', component: () => import('../views/messages/MessageFilters.vue'), meta: { title: 'Spam Filters' } },{ path: 'forms', name: 'forms', component: () => import('../views/forms/Forms.vue'), meta: { title: 'Forms' } },{ path: 'forms/:id', name: 'form-detail', component: () => import('../views/forms/FormDetail.vue'), meta: { title: 'Form' } },diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vueindex 7449a97..b6227b1 100644--- a/web/src/views/forms/FormDetail.vue+++ b/web/src/views/forms/FormDetail.vue@@ -7,6 +7,7 @@ import { apiMessage } from "../../composables/apiError";import type { Form, FormSnippet } from "../../api/types";import FormFields from "./FormFields.vue";import FormResponses from "./FormResponses.vue";+import FormRules from "./FormRules.vue";const route = useRoute();const router = useRouter();@@ -21,6 +22,7 @@ const loadFailed = ref(false);const TABS = [{ key: "questions", label: "Questions" },{ key: "responses", label: "Responses" },+ { key: "routing", label: "Routing" },{ key: "setup", label: "Setup" },{ key: "settings", label: "Response settings" },{ key: "spam", label: "Spam" },@@ -173,7 +175,7 @@ function copy(text: string) {notify.success("Copied to clipboard.");}-const hasQuestions = computed(() => (form.value?.fields || []).some((f) => !f.archived));+const hasQuestions = computed(() => (form.value?.fields || []).some((f) => !f.archived && f.type !== "section"));const endpoint = computed(() => snippet.value?.endpoint || "");@@ -273,6 +275,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" :share-url="snippet?.share_url" />+ <FormRules v-if="tab === 'routing'" :form="form" /><div v-show="tab === 'setup'" class="card" style="margin-bottom: 20px"><div class="card-header"><h2>Setup</h2></div>@@ -625,7 +628,7 @@ onMounted(load);</div><!-- Questions has its own save bar and Responses saves nothing; this saves the other tabs. -->- <div v-show="tab !== 'questions' && tab !== 'responses'" class="card">+ <div v-show="!['questions', 'responses', 'routing'].includes(tab)" class="card"><div class="card-body"><button class="btn btn-primary" :disabled="saving" @click="save">{{ saving ? "Saving..." : "Save changes" }}diff --git a/web/src/views/forms/FormFields.vue b/web/src/views/forms/FormFields.vueindex 1622489..fa90c2b 100644--- a/web/src/views/forms/FormFields.vue+++ b/web/src/views/forms/FormFields.vue@@ -58,6 +58,7 @@ const ROLES: { value: FormFieldRole; label: string; types: FormFieldType[] }[] =const TEXT_TYPES: FormFieldType[] = ["text", "textarea"];const PLACEHOLDER_TYPES: FormFieldType[] = ["text", "textarea", "email", "phone", "number", "url"];const CHOICE_TYPES: FormFieldType[] = ["select", "multiselect"];+const isSection = (d: { type: FormFieldType }) => d.type === "section";let uidSeq = 0;const drafts = ref<Draft[]>([]);@@ -91,6 +92,53 @@ function reset(form: Form) {const active = computed(() => drafts.value.filter((d) => !d.archived));const archived = computed(() => drafts.value.filter((d) => d.archived));+const questionCount = computed(() => active.value.filter((d) => !isSection(d)).length);++// ─── Sections and branching ───────────────────────────────────────────────++// Where a page may lead: a later section, or submit. Mirrors checkFlow in+// services/messages/schema.go, which only allows moving forward.+function laterSections(d: Draft) {+ const list = active.value;+ return list.slice(list.indexOf(d) + 1).filter(isSection);+}++// pageNumber is the page a card's question is on, counting from 1.+function pageNumber(d: Draft) {+ const list = active.value;+ const before = list.slice(0, list.indexOf(d) + 1);+ const opensWithSection = list.length > 0 && isSection(list[0]);+ return before.filter(isSection).length + (opensWithSection ? 0 : 1);+}++const branchUids = ref(new Set<number>());+function branches(d: Draft) {+ return branchUids.value.has(d.uid) || (d.options || []).some((o) => o.goto);+}+function toggleBranch(d: Draft, on: boolean) {+ const next = new Set(branchUids.value);+ if (on) next.add(d.uid);+ else {+ next.delete(d.uid);+ (d.options || []).forEach((o) => (o.goto = undefined));+ }+ branchUids.value = next;+}++// A target that is no longer ahead (after a reorder or archive) would be+// refused on save; say so on the card instead.+function staleTarget(d: Draft, target?: string) {+ if (!target || target === "submit") return false;+ return !laterSections(d).some((s) => s.key === target);+}+function hasStaleTargets(d: Draft) {+ return isSection(d) ? staleTarget(d, d.next) : (d.options || []).some((o) => staleTarget(d, o.goto));+}++function sectionTitle(key?: string) {+ const s = drafts.value.find((d) => d.key === key);+ return s ? s.label || s.key : key;+}// ─── Keys and option values ───────────────────────────────────────────────@@ -172,7 +220,7 @@ function newDraft(type: FormFieldType, label: string, extra: Partial<Draft> = {}}async function addQuestion(type: FormFieldType = "text") {- const d = newDraft(type, "Untitled question");+ const d = newDraft(type, type === "section" ? "Untitled section" : "Untitled question");const at = openUid.value ? drafts.value.findIndex((x) => x.uid === openUid.value) + 1 : drafts.value.length;drafts.value.splice(at || drafts.value.length, 0, d);openUid.value = d.uid;@@ -202,6 +250,15 @@ function duplicate(d: Draft) {}function remove(d: Draft) {+ if (isSection(d)) {+ // Nothing may lead to a section that is gone.+ drafts.value.forEach((x) => {+ if (x.next === d.key) x.next = undefined;+ (x.options || []).forEach((o) => {+ if (o.goto === d.key) o.goto = undefined;+ });+ });+ }if (d.saved) {// Stored answers refer to the key, so it is kept, hidden from respondents.d.archived = true;@@ -262,6 +319,12 @@ function num(v: unknown): number | undefined {function serialize(): FormField[] {return drafts.value.map((d) => {const f: FormField = { key: d.key.trim(), label: d.label.trim(), type: d.type };+ if (isSection(d)) {+ if (d.help?.trim()) f.help = d.help.trim();+ if (d.next) f.next = d.next;+ if (d.archived) f.archived = true;+ return f;+ }if (d.required && d.type !== "hidden") f.required = true;if (d.role) f.role = d.role;if (d.pii) f.pii = true;@@ -283,7 +346,12 @@ function serialize(): FormField[] {if (d.max_label?.trim()) f.max_label = d.max_label.trim();}if (CHOICE_TYPES.includes(d.type)) {- f.options = (d.options || []).map((o) => (o.label?.trim() ? { value: o.value.trim(), label: o.label.trim() } : { value: o.value.trim() }));+ f.options = (d.options || []).map((o) => {+ const opt: FormFieldOption = { value: o.value.trim() };+ if (o.label?.trim()) opt.label = o.label.trim();+ if (d.type === "select" && o.goto) opt.goto = o.goto;+ return opt;+ });if (d.display) f.display = d.display;}return JSON.parse(JSON.stringify(f)); // drops undefined@@ -303,7 +371,7 @@ async function save() {} catch (e: unknown) {const message = apiMessage(e, "Failed to save questions");// Schema errors name the field: open that card so the problem is in view.- const key = /field(?: key)? "([^"]+)"/.exec(message)?.[1];+ const key = /(?:field|section)(?: key)? "([^"]+)"/.exec(message)?.[1];const target = key && drafts.value.find((d) => d.key === key);if (target) {errorKey.value = key!;@@ -410,7 +478,7 @@ onBeforeUnmount(() => {<div class="card qb-bar"><div class="card-body qb-bar-body"><div>- <strong>{{ active.length }} {{ active.length === 1 ? "question" : "questions" }}</strong>+ <strong>{{ questionCount }} {{ questionCount === 1 ? "question" : "questions" }}</strong><span v-if="form.schema_version" class="muted"> · version {{ form.schema_version }}</span><span v-if="dirty" class="badge badge-warning" style="margin-left: 8px">Unsaved</span></div>@@ -441,7 +509,7 @@ onBeforeUnmount(() => {v-for="(d, i) in active":key="d.uid"class="card qcard"- :class="{ open: openUid === d.uid, error: errorKey === d.key, dragging: dragUid === d.uid }"+ :class="{ open: openUid === d.uid, error: errorKey === d.key, dragging: dragUid === d.uid, section: isSection(d) }"@dragover.prevent@drop="onDrop(d)">@@ -457,11 +525,19 @@ onBeforeUnmount(() => {>⋮⋮</span><div class="qcard-summary"><div class="qcard-title">- {{ d.label || (d.type === "hidden" ? d.key : "Untitled question") }}+ {{ d.label || (d.type === "hidden" ? d.key : isSection(d) ? "Untitled section" : "Untitled question") }}<span v-if="d.required" class="qcard-req" title="Required">*</span></div>- <div class="qcard-meta">+ <div v-if="isSection(d)" class="qcard-meta">+ Page {{ pageNumber(d) }}+ <template v-if="d.next === 'submit'"> · then submit</template>+ <template v-else-if="d.next"> · then “{{ sectionTitle(d.next) }}”</template>+ <span v-if="hasStaleTargets(d)" class="badge badge-warning">Check where it leads</span>+ </div>+ <div v-else class="qcard-meta">{{ typeLabel(d.type) }} · <code>{{ d.key }}</code>+ <span v-if="branches(d)" class="badge badge-info">Branches</span>+ <span v-if="hasStaleTargets(d)" class="badge badge-warning">Check where it leads</span><span v-if="d.role" class="badge badge-info">{{ ROLES.find((r) => r.value === d.role)?.label }}</span><span v-if="d.pii" class="badge badge-neutral">Personal data</span></div>@@ -476,7 +552,43 @@ onBeforeUnmount(() => {</div></div>- <div v-if="openUid === d.uid" class="qcard-body">+ <div v-if="openUid === d.uid && isSection(d)" class="qcard-body">+ <div class="form-group">+ <label class="form-label" :for="`q-label-${d.uid}`">Section title</label>+ <input :id="`q-label-${d.uid}`" v-model="d.label" class="form-input" @input="onLabelInput(d)" />+ </div>+ <div class="form-group">+ <label class="form-label">Description <span class="muted">(optional)</span></label>+ <textarea v-model="d.help" class="form-input" rows="2" placeholder="Shown at the top of the page"></textarea>+ </div>+ <div class="form-group">+ <label class="form-label">After this section</label>+ <select v-model="d.next" class="form-select" style="max-width: 360px">+ <option :value="undefined">Continue to the next section</option>+ <option v-for="s in laterSections(d)" :key="s.uid" :value="s.key">Go to “{{ s.label || s.key }}”</option>+ <option value="submit">Submit the form</option>+ </select>+ <small v-if="staleTarget(d, d.next)" class="form-hint warn">+ “{{ sectionTitle(d.next) }}” is no longer after this section. Pick where this page leads again.+ </small>+ <small v-else class="form-hint">A branching question on this page takes precedence for the answers it covers.</small>+ </div>+ <div class="qcard-foot">+ <div class="qcard-key">+ <label class="form-label" style="margin: 0">Key</label>+ <input+ v-model="d.key"+ class="form-input"+ :disabled="d.saved"+ title="Branches point to sections by this key"+ spellcheck="false"+ @input="onKeyInput(d)"+ />+ </div>+ </div>+ </div>++ <div v-if="openUid === d.uid && !isSection(d)" class="qcard-body"><div class="qgrid"><div class="form-group"><label class="form-label" :for="`q-label-${d.uid}`">Question</label>@@ -509,7 +621,29 @@ onBeforeUnmount(() => {@input="o.auto = false"/><button class="btn btn-ghost btn-xs" :disabled="(d.options?.length || 0) <= 1" aria-label="Remove option" @click="removeOption(d, oi)">×</button>+ <select+ v-if="d.type === 'select' && branches(d)"+ v-model="o.goto"+ class="form-select qopt-goto"+ :class="{ stale: staleTarget(d, o.goto) }"+ :aria-label="`After choosing ${o.label || o.value}`"+ >+ <option :value="undefined">Continue</option>+ <option v-for="s in laterSections(d)" :key="s.uid" :value="s.key">Go to “{{ s.label || s.key }}”</option>+ <option value="submit">Submit the form</option>+ </select></div>+ <label+ v-if="d.type === 'select' && (laterSections(d).length || branches(d))"+ class="checkbox-label"+ style="margin-top: 8px"+ >+ <input type="checkbox" :checked="branches(d)" @change="toggleBranch(d, ($event.target as HTMLInputElement).checked)" />+ Go to a section based on the answer+ </label>+ <small v-if="d.type === 'select' && !laterSections(d).length && !branches(d)" class="form-hint">+ Add a section below this question to send respondents to different pages by their answer.+ </small><button class="btn btn-secondary btn-xs" style="margin-top: 6px" @click="addOption(d)">Add option</button><small class="form-hint">The second box is the stored value. Keep it stable once answers come in.</small></div>@@ -628,6 +762,7 @@ onBeforeUnmount(() => {<div v-if="drafts.length" class="qb-add"><button class="btn btn-secondary" @click="addQuestion()">+ Add question</button>+ <button class="btn btn-secondary" @click="addQuestion('section')">+ Add section</button></div><div v-if="archived.length" class="card">@@ -739,6 +874,13 @@ onBeforeUnmount(() => {border-left-color: var(--primary-600);}+/* A section starts a page: set it apart from the questions around it. */+.qcard.section {+ margin-top: 12px;+ background: var(--bg-secondary);+ border-top: 3px solid var(--primary-500);+}+.qcard.error {border-left-color: var(--danger, #dc2626);}@@ -826,6 +968,15 @@ onBeforeUnmount(() => {color: var(--text-muted);}+.qopt .qopt-goto {+ flex: 0 1 190px;+ min-width: 0;+}++.qopt .qopt-goto.stale {+ border-color: var(--warning-600);+}+.qopt-mark {width: 14px;height: 14px;@@ -880,6 +1031,7 @@ onBeforeUnmount(() => {.qb-add {display: flex;justify-content: center;+ gap: 8px;}.qarch {diff --git a/web/src/views/forms/FormResponses.vue b/web/src/views/forms/FormResponses.vueindex 970cf03..4dfd4ab 100644--- a/web/src/views/forms/FormResponses.vue+++ b/web/src/views/forms/FormResponses.vue@@ -38,8 +38,10 @@ 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 || []);-const activeQuestions = computed(() => (props.form.fields || []).filter((f) => !f.archived && f.type !== "hidden"));+const questions = computed(() => (props.form.fields || []).filter((f) => f.type !== "section"));+const activeQuestions = computed(() =>+ (props.form.fields || []).filter((f) => !f.archived && f.type !== "hidden" && f.type !== "section"),+);const hasSchema = computed(() => (props.form.fields || []).length > 0);const byKey = computed(() => {const out: Record<string, FormField> = {};diff --git a/web/src/views/forms/FormRules.vue b/web/src/views/forms/FormRules.vuenew file mode 100644index 0000000..08bb0f6--- /dev/null+++ b/web/src/views/forms/FormRules.vue@@ -0,0 +1,817 @@+<script setup lang="ts">+import { computed, onMounted, ref } from "vue";+import { formRulesApi, teamsApi } from "../../api/messages";+import { workspaceApi } from "../../api/workspaces";+import { webhooksApi } from "../../api/webhooks";+import { useNotificationStore } from "../../stores/notification";+import { apiMessage } from "../../composables/apiError";+import type {+ Form,+ FormField,+ FormRule,+ FormRuleInput,+ RuleAction,+ RuleActionType,+ RuleCondition,+ RuleOp,+ RuleTestResult,+ Team,+ Webhook,+ WorkspaceMember,+} from "../../api/types";++// Routing rules for one form. A rule offers only this form's questions to+// test and this workspace's members, teams and webhooks to send to: a value+// a visitor typed never becomes a destination.++const props = defineProps<{ form: Form }>();+const notify = useNotificationStore();++interface Draft extends FormRuleInput {+ uid: number;+ id?: number;+ hit_count: number;+ last_hit_at?: string | null;+ saved: string; // JSON of the last saved state, "" when new+}++let uidSeq = 0;+const loading = ref(true);+const drafts = ref<Draft[]>([]);+const openUid = ref<number | null>(null);+const busyUid = ref<number | null>(null);+const teams = ref<Team[]>([]);+const members = ref<WorkspaceMember[]>([]);+const webhooks = ref<Webhook[]>([]);+const testing = ref(false);+const test = ref<RuleTestResult | null>(null);++// ─── Fields and operators ─────────────────────────────────────────────────++const BUILTINS = [+ { key: "$sender_email", label: "Sender email" },+ { key: "$origin", label: "Website it came from" },+ { key: "$referer", label: "Page it was sent from" },+ { key: "$spam_score", label: "Spam score" },+ { key: "$status", label: "Scan result" },+];++const questions = computed(() =>+ (props.form.fields || []).filter((f) => !f.archived && f.type !== "section"),+);+const schemaless = computed(() => questions.value.length === 0);++type Kind = "choice" | "checkbox" | "number" | "date" | "time" | "status" | "text";++function fieldDef(key: string): FormField | undefined {+ return questions.value.find((f) => f.key === key);+}++function kindOf(key: string): Kind {+ if (key === "$spam_score") return "number";+ if (key === "$status") return "status";+ const f = fieldDef(key);+ switch (f?.type) {+ case "select":+ case "multiselect":+ return "choice";+ case "checkbox":+ return "checkbox";+ case "number":+ case "scale":+ case "rating":+ return "number";+ case "date":+ return "date";+ case "time":+ return "time";+ }+ return "text";+}++const ANSWERED: [RuleOp, string][] = [+ ["exists", "is answered"],+ ["not_exists", "is not answered"],+];+const OPS: Record<Kind, [RuleOp, string][]> = {+ choice: [["in", "is any of"], ["not_in", "is none of"], ...ANSWERED],+ checkbox: [["eq", "is"]],+ number: [["eq", "equals"], ["gt", "is more than"], ["gte", "is at least"], ["lt", "is less than"], ["lte", "is at most"], ...ANSWERED],+ date: [["eq", "is"], ["gt", "is after"], ["gte", "is on or after"], ["lt", "is before"], ["lte", "is on or before"], ...ANSWERED],+ time: [["eq", "is"], ["gt", "is after"], ["lt", "is before"], ...ANSWERED],+ status: [["eq", "is"]],+ text: [["eq", "is"], ["neq", "is not"], ["contains", "contains"], ["not_contains", "does not contain"], ["matches", "matches pattern"], ...ANSWERED],+};++function opsFor(c: RuleCondition) {+ return OPS[kindOf(c.field)];+}++function needsValue(c: RuleCondition) {+ return c.op !== "exists" && c.op !== "not_exists";+}++function resetCondition(c: RuleCondition) {+ const kind = kindOf(c.field);+ c.op = OPS[kind][0][0];+ c.value = kind === "choice" ? [] : kind === "checkbox" ? "true" : kind === "status" ? "flagged" : "";+}++function toggleChoice(c: RuleCondition, value: string) {+ const list = Array.isArray(c.value) ? [...c.value] : [];+ const i = list.indexOf(value);+ if (i >= 0) list.splice(i, 1);+ else list.push(value);+ c.value = list;+}++function fieldLabel(key: string) {+ return fieldDef(key)?.label || BUILTINS.find((b) => b.key === key)?.label || key;+}++// ─── Actions ──────────────────────────────────────────────────────────────++const ACTIONS: { type: RuleActionType; label: string }[] = [+ { type: "notify_team", label: "Notify a team" },+ { type: "notify_members", label: "Notify members" },+ { type: "notify_emails", label: "Notify email addresses" },+ { type: "assign_team", label: "Route to a team" },+ { type: "assign_member", label: "Assign to a member" },+ { type: "add_tags", label: "Add tags" },+ { type: "set_priority", label: "Set priority" },+ { type: "webhook", label: "Send to a webhook" },+ { type: "suppress_default", label: "Don't notify the form's usual recipients" },+];++function newAction(type: RuleActionType): RuleAction {+ switch (type) {+ case "notify_team":+ case "assign_team":+ return { type, team_id: teams.value[0]?.id ?? null };+ case "notify_members":+ return { type, user_ids: [] };+ case "assign_member":+ return { type, user_ids: members.value[0] ? [members.value[0].user_id] : [] };+ case "notify_emails":+ return { type, emails: [] };+ case "add_tags":+ return { type, tags: [] };+ case "set_priority":+ return { type, priority: "high" };+ case "webhook":+ return { type, webhook_id: webhooks.value[0]?.id ?? null };+ }+ return { type };+}++function changeActionType(d: Draft, i: number, type: RuleActionType) {+ d.actions[i] = newAction(type);+}++function listText(list?: string[]) {+ return (list || []).join(", ");+}++function setList(a: RuleAction, key: "emails" | "tags", text: string) {+ a[key] = text+ .split(/[,;\s]+/)+ .map((s) => s.trim())+ .filter(Boolean);+}++function toggleMember(a: RuleAction, id: number) {+ const ids = a.user_ids || [];+ a.user_ids = ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id];+}++const teamName = (id?: number | null) => teams.value.find((t) => t.id === id)?.name || "a team";+const memberName = (id?: number) => {+ const m = members.value.find((x) => x.user_id === id);+ return m ? m.name || m.email : "a member";+};++// summary reads a rule back in one line, for the collapsed card.+function summary(d: Draft) {+ const when = d.conditions.length+ ? d.conditions+ .map((c) => {+ const op = opsFor(c).find(([o]) => o === c.op)?.[1] || c.op;+ const value = !needsValue(c) ? "" : Array.isArray(c.value) ? ` ${c.value.join(" or ")}` : ` ${c.value ?? ""}`;+ return `${fieldLabel(c.field)} ${op}${value}`;+ })+ .join(d.match === "any" ? " or " : " and ")+ : "Every submission";+ const then = d.actions+ .map((a) => {+ switch (a.type) {+ case "notify_team":+ return `notify ${teamName(a.team_id)}`;+ case "assign_team":+ return `route to ${teamName(a.team_id)}`;+ case "notify_members":+ return `notify ${(a.user_ids || []).map(memberName).join(", ") || "members"}`;+ case "assign_member":+ return `assign to ${memberName(a.user_ids?.[0])}`;+ case "notify_emails":+ return `email ${listText(a.emails) || "addresses"}`;+ case "add_tags":+ return `tag ${listText(a.tags)}`;+ case "set_priority":+ return `priority ${a.priority}`;+ case "webhook":+ return "call a webhook";+ case "suppress_default":+ return "skip the usual recipients";+ }+ return a.type;+ })+ .join(", ");+ return `${when} → ${then || "nothing yet"}`;+}++// ─── Load and save ────────────────────────────────────────────────────────++function input(d: Draft): FormRuleInput {+ return JSON.parse(+ JSON.stringify({ name: d.name, enabled: d.enabled, match: d.match, conditions: d.conditions, actions: d.actions, stop: d.stop }),+ );+}++function toDraft(r: FormRule): Draft {+ const d: Draft = {+ uid: ++uidSeq,+ id: r.id,+ name: r.name,+ enabled: r.enabled,+ match: r.match,+ conditions: r.conditions || [],+ actions: r.actions || [],+ stop: r.stop,+ hit_count: r.hit_count,+ last_hit_at: r.last_hit_at,+ saved: "",+ };+ d.saved = JSON.stringify(input(d));+ return d;+}++const dirty = (d: Draft) => JSON.stringify(input(d)) !== d.saved;++async function load() {+ loading.value = true;+ try {+ const [ruleRes, teamRes, memberRes, hookRes] = await Promise.all([+ formRulesApi.list(props.form.id),+ teamsApi.list(),+ workspaceApi.listMembers(),+ webhooksApi.list(0, 100).catch(() => null),+ ]);+ drafts.value = ruleRes.data.data.map(toDraft);+ teams.value = teamRes.data.data;+ members.value = memberRes.data.data || [];+ webhooks.value = hookRes?.data.data || [];+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to load routing rules"));+ } finally {+ loading.value = false;+ }+}++function addRule() {+ const d: Draft = {+ uid: ++uidSeq,+ name: `Rule ${drafts.value.length + 1}`,+ enabled: true,+ match: "all",+ conditions: [],+ actions: [newAction(teams.value.length ? "notify_team" : "notify_emails")],+ stop: false,+ hit_count: 0,+ saved: "",+ };+ if (!schemaless.value) {+ const first = questions.value.find((q) => q.type === "select") || questions.value[0];+ const c: RuleCondition = { field: first.key, op: "in" };+ resetCondition(c);+ d.conditions.push(c);+ }+ drafts.value.push(d);+ openUid.value = d.uid;+}++function addCondition(d: Draft) {+ const c: RuleCondition = { field: schemaless.value ? "" : questions.value[0].key, op: "eq" };+ if (schemaless.value) c.value = "";+ else resetCondition(c);+ d.conditions.push(c);+}++async function save(d: Draft) {+ busyUid.value = d.uid;+ try {+ const res = d.id+ ? await formRulesApi.update(props.form.id, d.id, input(d))+ : await formRulesApi.create(props.form.id, input(d));+ const saved = toDraft(res.data.data);+ saved.uid = d.uid;+ drafts.value.splice(drafts.value.indexOf(d), 1, saved);+ notify.success("Rule saved.");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to save rule"));+ } finally {+ busyUid.value = null;+ }+}++async function remove(d: Draft) {+ if (d.id && !confirm(`Delete the rule "${d.name}"?`)) return;+ try {+ if (d.id) await formRulesApi.delete(props.form.id, d.id);+ drafts.value = drafts.value.filter((x) => x !== d);+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to delete rule"));+ }+}++async function move(d: Draft, step: -1 | 1) {+ const list = [...drafts.value];+ const i = list.indexOf(d);+ const j = i + step;+ if (j < 0 || j >= list.length) return;+ [list[i], list[j]] = [list[j], list[i]];+ drafts.value = list;+ const ids = list.filter((x) => x.id).map((x) => x.id!);+ if (ids.length < 2) return;+ try {+ await formRulesApi.reorder(props.form.id, ids);+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to reorder rules"));+ }+}++// Test runs the rules as they are on screen, saved or not.+async function runTest() {+ testing.value = true;+ try {+ const res = await formRulesApi.test(props.form.id, drafts.value.map(input), 200);+ test.value = res.data.data;+ } catch (e: any) {+ notify.error(apiMessage(e, "Could not test the rules"));+ } finally {+ testing.value = false;+ }+}++function testCount(i: number) {+ return test.value?.rules[i]?.matches;+}++function when(iso?: string | null) {+ return iso ? new Date(iso).toLocaleString() : "";+}++onMounted(load);+</script>++<template>+ <div class="rules">+ <div class="card" style="margin-bottom: 16px">+ <div class="card-body rules-intro">+ <div>+ <h2 style="margin: 0 0 4px">Routing</h2>+ <p class="muted" style="margin: 0">+ Rules run in order on every submission that passes the spam check. Each rule that matches applies,+ unless an earlier one says to stop. The form's usual recipients are still notified unless a rule+ turns that off.+ </p>+ </div>+ <div class="rules-intro-actions">+ <button class="btn btn-secondary" :disabled="testing || !drafts.length" @click="runTest">+ {{ testing ? "Testing…" : "Test on recent submissions" }}+ </button>+ <button class="btn btn-primary" @click="addRule">+ Add rule</button>+ </div>+ </div>+ <div v-if="test" class="card-body rules-test-head">+ <strong>{{ test.matched }} of {{ test.scanned }}</strong> recent submissions match at least one rule.+ <span class="muted">Nothing was sent or changed.</span>+ <button class="btn btn-ghost btn-xs" @click="test = null">Hide</button>+ </div>+ </div>++ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>++ <div v-else-if="!drafts.length" class="card">+ <div class="empty-state">+ <h3>No routing rules</h3>+ <p>+ Every submission goes to the form's usual recipients. Add a rule to send some of them elsewhere: for+ example, notify Sales when the department is "sales", or mark urgent requests as high priority.+ </p>+ <p v-if="!teams.length" class="muted">+ <router-link to="/teams">Create a team</router-link> first to route submissions to a group of members.+ </p>+ </div>+ </div>++ <div+ v-for="(d, i) in drafts"+ :key="d.uid"+ class="card rule-card"+ :class="{ open: openUid === d.uid, off: !d.enabled }"+ >+ <div class="rule-head" @click="openUid = openUid === d.uid ? null : d.uid">+ <span class="rule-pos">{{ i + 1 }}</span>+ <div class="rule-summary">+ <div class="rule-title">+ {{ d.name || "Untitled rule" }}+ <span v-if="!d.enabled" class="badge badge-neutral">Off</span>+ <span v-if="d.stop" class="badge badge-neutral">Stops</span>+ <span v-if="!d.id" class="badge badge-warning">Not saved</span>+ <span v-else-if="dirty(d)" class="badge badge-warning">Unsaved changes</span>+ </div>+ <div class="rule-line">{{ summary(d) }}</div>+ <div class="rule-meta muted">+ <template v-if="test && testCount(i) !== undefined">+ <strong>Would match {{ testCount(i) }} of {{ test.scanned }}</strong> ·+ </template>+ <template v-if="d.id">Matched {{ d.hit_count }} time{{ d.hit_count === 1 ? "" : "s" }}</template>+ <template v-if="d.last_hit_at">, last {{ when(d.last_hit_at) }}</template>+ </div>+ </div>+ <div class="rule-tools" @click.stop>+ <button class="btn btn-ghost btn-xs" :disabled="i === 0" aria-label="Move up" @click="move(d, -1)">↑</button>+ <button class="btn btn-ghost btn-xs" :disabled="i === drafts.length - 1" aria-label="Move down" @click="move(d, 1)">↓</button>+ </div>+ </div>++ <div v-if="openUid === d.uid" class="rule-body">+ <div class="rule-row">+ <div class="form-group" style="flex: 1 1 240px">+ <label class="form-label" :for="`rule-name-${d.uid}`">Name</label>+ <input :id="`rule-name-${d.uid}`" v-model="d.name" class="form-input" maxlength="120" />+ </div>+ <label class="checkbox-label"><input v-model="d.enabled" type="checkbox" /> On</label>+ </div>++ <h4 class="rule-section">When</h4>+ <p v-if="!d.conditions.length" class="muted rule-note">No conditions: this rule applies to every submission.</p>+ <div v-if="d.conditions.length > 1" class="form-group" style="max-width: 280px">+ <select v-model="d.match" class="form-select" aria-label="Match">+ <option value="all">All of these are true</option>+ <option value="any">Any of these is true</option>+ </select>+ </div>+ <div v-for="(c, ci) in d.conditions" :key="ci" class="cond">+ <select+ v-if="!schemaless"+ v-model="c.field"+ class="form-select cond-field"+ aria-label="Field"+ @change="resetCondition(c)"+ >+ <optgroup label="Questions">+ <option v-for="q in questions" :key="q.key" :value="q.key">{{ q.label || q.key }}</option>+ </optgroup>+ <optgroup label="About the submission">+ <option v-for="b in BUILTINS" :key="b.key" :value="b.key">{{ b.label }}</option>+ </optgroup>+ </select>+ <input+ v-else+ v-model="c.field"+ class="form-input cond-field"+ placeholder="field name, e.g. department"+ aria-label="Field"+ list="rule-builtins"+ />+ <select v-model="c.op" class="form-select cond-op" aria-label="Comparison">+ <option v-for="[op, label] in opsFor(c)" :key="op" :value="op">{{ label }}</option>+ </select>++ <template v-if="needsValue(c)">+ <div v-if="kindOf(c.field) === 'choice'" class="cond-choices">+ <label v-for="o in fieldDef(c.field)?.options || []" :key="o.value" class="chip-check">+ <input+ type="checkbox"+ :checked="Array.isArray(c.value) && c.value.includes(o.value)"+ @change="toggleChoice(c, o.value)"+ />+ {{ o.label || o.value }}+ </label>+ </div>+ <select v-else-if="kindOf(c.field) === 'checkbox'" v-model="c.value" class="form-select cond-value" aria-label="Value">+ <option value="true">Checked</option>+ <option value="false">Not checked</option>+ </select>+ <select v-else-if="kindOf(c.field) === 'status'" v-model="c.value" class="form-select cond-value" aria-label="Value">+ <option value="received">Clean</option>+ <option value="flagged">Flagged as possible spam</option>+ </select>+ <input+ v-else+ v-model="c.value"+ class="form-input cond-value"+ :type="{ number: 'number', date: 'date', time: 'time' }[kindOf(c.field) as string] || 'text'"+ :step="kindOf(c.field) === 'number' ? 'any' : undefined"+ :placeholder="c.op === 'matches' ? 'regular expression' : 'value'"+ aria-label="Value"+ />+ </template>+ <button class="btn btn-ghost btn-xs" aria-label="Remove condition" @click="d.conditions.splice(ci, 1)">×</button>+ </div>+ <datalist id="rule-builtins">+ <option v-for="b in BUILTINS" :key="b.key" :value="b.key">{{ b.label }}</option>+ </datalist>+ <button class="btn btn-secondary btn-xs" @click="addCondition(d)">+ Condition</button>++ <h4 class="rule-section">Then</h4>+ <div v-for="(a, ai) in d.actions" :key="ai" class="act">+ <select+ :value="a.type"+ class="form-select act-type"+ aria-label="Action"+ @change="changeActionType(d, ai, ($event.target as HTMLSelectElement).value as RuleActionType)"+ >+ <option v-for="t in ACTIONS" :key="t.type" :value="t.type">{{ t.label }}</option>+ </select>++ <template v-if="a.type === 'notify_team' || a.type === 'assign_team'">+ <select v-if="teams.length" v-model="a.team_id" class="form-select act-value" aria-label="Team">+ <option v-for="t in teams" :key="t.id" :value="t.id">{{ t.name }}</option>+ </select>+ <span v-else class="muted act-value"><router-link to="/teams">Create a team</router-link> first.</span>+ </template>+ <select+ v-else-if="a.type === 'assign_member'"+ :value="a.user_ids?.[0]"+ class="form-select act-value"+ aria-label="Member"+ @change="a.user_ids = [Number(($event.target as HTMLSelectElement).value)]"+ >+ <option v-for="m in members" :key="m.user_id" :value="m.user_id">{{ m.name || m.email }}</option>+ </select>+ <div v-else-if="a.type === 'notify_members'" class="cond-choices act-value">+ <label v-for="m in members" :key="m.user_id" class="chip-check">+ <input type="checkbox" :checked="(a.user_ids || []).includes(m.user_id)" @change="toggleMember(a, m.user_id)" />+ {{ m.name || m.email }}+ </label>+ </div>+ <input+ v-else-if="a.type === 'notify_emails'"+ :value="listText(a.emails)"+ class="form-input act-value"+ placeholder="[email protected], [email protected]"+ aria-label="Addresses"+ @change="setList(a, 'emails', ($event.target as HTMLInputElement).value)"+ />+ <input+ v-else-if="a.type === 'add_tags'"+ :value="listText(a.tags)"+ class="form-input act-value"+ placeholder="lead, follow up"+ aria-label="Tags"+ @change="setList(a, 'tags', ($event.target as HTMLInputElement).value)"+ />+ <select v-else-if="a.type === 'set_priority'" v-model="a.priority" class="form-select act-value" aria-label="Priority">+ <option value="urgent">Urgent</option>+ <option value="high">High</option>+ <option value="normal">Normal</option>+ <option value="low">Low</option>+ </select>+ <template v-else-if="a.type === 'webhook'">+ <select v-if="webhooks.length" v-model="a.webhook_id" class="form-select act-value" aria-label="Webhook">+ <option v-for="w in webhooks" :key="w.id" :value="w.id">{{ w.url }}</option>+ </select>+ <span v-else class="muted act-value"><router-link to="/webhooks">Add a webhook</router-link> first.</span>+ </template>+ <span v-else class="act-value"></span>+ <button class="btn btn-ghost btn-xs" :disabled="d.actions.length <= 1" aria-label="Remove action" @click="d.actions.splice(ai, 1)">×</button>+ </div>+ <button class="btn btn-secondary btn-xs" @click="d.actions.push(newAction('add_tags'))">+ Action</button>+ <p class="muted rule-note">+ Addresses are typed here by you. A rule can choose between destinations, but never sends to an address+ a visitor entered.+ </p>++ <div class="rule-foot">+ <label class="checkbox-label" title="Later rules are not checked when this one matches">+ <input v-model="d.stop" type="checkbox" /> Stop here when this rule matches+ </label>+ <div class="rule-foot-actions">+ <button class="btn btn-ghost btn-sm" @click="remove(d)">Delete</button>+ <button class="btn btn-primary btn-sm" :disabled="busyUid === d.uid || (!!d.id && !dirty(d))" @click="save(d)">+ {{ busyUid === d.uid ? "Saving…" : "Save rule" }}+ </button>+ </div>+ </div>+ </div>+ </div>++ <div v-if="test && test.samples.length" class="card">+ <div class="card-header"><h2>Recent matches</h2></div>+ <div class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Received</th>+ <th>From</th>+ <th>Rules</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="s in test.samples" :key="s.message_uuid">+ <td><router-link :to="`/messages/${s.message_uuid}`">{{ when(s.received_at) }}</router-link></td>+ <td>{{ s.sender || s.subject || "—" }}</td>+ <td>{{ s.matched.map((i) => drafts[i]?.name || `Rule ${i + 1}`).join(", ") }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ </div>+</template>++<style scoped>+.rules-intro {+ display: flex;+ gap: 16px;+ align-items: flex-start;+ justify-content: space-between;+ flex-wrap: wrap;+}++.rules-intro p {+ max-width: 640px;+}++.rules-intro-actions {+ display: flex;+ gap: 8px;+}++.rules-test-head {+ display: flex;+ gap: 8px;+ align-items: center;+ flex-wrap: wrap;+ border-top: 1px solid var(--border-secondary);+}++.rule-card {+ margin-bottom: 12px;+ border-left: 3px solid transparent;+}++.rule-card.open {+ border-left-color: var(--primary-600);+}++.rule-card.off .rule-summary {+ opacity: 0.6;+}++.rule-head {+ display: flex;+ gap: 12px;+ align-items: flex-start;+ padding: 14px 16px;+ cursor: pointer;+}++.rule-pos {+ flex: none;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ display: grid;+ place-items: center;+ font-size: 12px;+ font-weight: 600;+ background: var(--bg-tertiary);+ color: var(--text-secondary);+}++.rule-summary {+ flex: 1;+ min-width: 0;+}++.rule-title {+ display: flex;+ gap: 6px;+ align-items: center;+ flex-wrap: wrap;+ font-weight: 600;+}++.rule-line {+ margin-top: 2px;+ font-size: 13px;+ color: var(--text-secondary);+ overflow-wrap: anywhere;+}++.rule-meta {+ margin-top: 2px;+ font-size: 12px;+}++.rule-tools {+ display: flex;+ gap: 4px;+}++.rule-body {+ padding: 0 16px 16px 52px;+}++.rule-row {+ display: flex;+ gap: 16px;+ align-items: center;+ flex-wrap: wrap;+}++.rule-section {+ margin: 16px 0 8px;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--text-tertiary);+}++.rule-note {+ font-size: 13px;+ margin: 6px 0;+}++.cond,+.act {+ display: flex;+ gap: 8px;+ align-items: flex-start;+ flex-wrap: wrap;+ margin-bottom: 8px;+}++.cond-field,+.act-type {+ flex: 0 1 220px;+}++.cond-op {+ flex: 0 1 170px;+}++.cond-value,+.act-value {+ flex: 1 1 200px;+ min-width: 0;+}++.cond-choices {+ flex: 1 1 260px;+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}++.chip-check {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 5px 10px;+ border: 1px solid var(--border-primary);+ border-radius: 999px;+ font-size: 13px;+ cursor: pointer;+}++.chip-check:has(input:checked) {+ border-color: var(--primary-500);+ background: var(--primary-50);+}++.rule-foot {+ display: flex;+ gap: 12px;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ margin-top: 16px;+ padding-top: 12px;+ border-top: 1px dashed var(--border-primary);+}++.rule-foot-actions {+ display: flex;+ gap: 8px;+}++@media (max-width: 640px) {+ .rule-body {+ padding-left: 16px;+ }+}+</style>diff --git a/web/src/views/messages/MessageDetail.vue b/web/src/views/messages/MessageDetail.vueindex 04289d5..5fd9607 100644--- a/web/src/views/messages/MessageDetail.vue+++ b/web/src/views/messages/MessageDetail.vue@@ -388,6 +388,22 @@ onBeforeUnmount(() => {<td style="font-weight: 600">Client IP</td><td><code style="font-size: 12px">{{ message.client_ip }}</code></td></tr>+ <tr v-if="message.assigned_to">+ <td style="font-weight: 600">Assigned to</td>+ <td>{{ message.assigned_to.name }}</td>+ </tr>+ <tr v-if="message.routed_by && message.routed_by.length">+ <td style="font-weight: 600">Routed by</td>+ <td class="scan-reasons">+ <router-link+ v-for="r in message.routed_by"+ :key="r.uuid"+ class="badge badge-info"+ :to="message.form ? `/forms/${message.form.id}?tab=routing` : ''"+ title="The routing rule that matched this submission"+ >{{ r.name }}</router-link>+ </td>+ </tr><tr v-if="message.spam_score"><td style="font-weight: 600">Spam score</td><td>{{ message.spam_score.toFixed(1) }}</td>diff --git a/web/src/views/messages/MessageTriage.vue b/web/src/views/messages/MessageTriage.vueindex c2a31c9..bb2a418 100644--- a/web/src/views/messages/MessageTriage.vue+++ b/web/src/views/messages/MessageTriage.vue@@ -1,9 +1,9 @@<script setup lang="ts">import { onMounted, ref } from "vue";-import { messagesApi } from "../../api/messages";+import { messagesApi, teamsApi } from "../../api/messages";import { useNotificationStore } from "../../stores/notification";import { apiMessage } from "../../composables/apiError";-import type { Message, MessagePriority } from "../../api/types";+import type { Message, MessagePriority, Team } 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.@@ -14,6 +14,7 @@ const notify = useNotificationStore();const busy = ref(false);const draft = ref("");const suggestions = ref<string[]>([]);+const teams = ref<Team[]>([]);const listId = `tag-suggestions-${props.message.uuid}`;const PRIORITIES: { value: MessagePriority; label: string }[] = [@@ -30,8 +31,18 @@ onMounted(async () => {} catch {/* suggestions are a convenience */}+ try {+ teams.value = (await teamsApi.list()).data.data;+ } catch {+ /* without teams the picker stays hidden */+ }});+async function setTeam(event: Event) {+ const raw = (event.target as HTMLSelectElement).value;+ await run(() => messagesApi.setTeam(props.message.uuid, raw ? Number(raw) : null), "Failed to change the team");+}+async function run(action: () => Promise<{ data: { data: Message } }>, failure: string) {busy.value = true;try {@@ -92,6 +103,14 @@ function onKey(event: KeyboardEvent) {</select></label>+ <label v-if="teams.length || message.team" class="triage-priority">+ <span class="triage-label">Team</span>+ <select class="form-select" :value="message.team_id || ''" :disabled="busy" @change="setTeam">+ <option value="">No team</option>+ <option v-for="t in teams" :key="t.id" :value="t.id">{{ t.name }}</option>+ </select>+ </label>+<div class="triage-tags"><span class="triage-label">Tags</span><div class="tag-row">diff --git a/web/src/views/messages/Messages.vue b/web/src/views/messages/Messages.vueindex 50ec4a0..8fe3a3c 100644--- a/web/src/views/messages/Messages.vue+++ b/web/src/views/messages/Messages.vue@@ -1,10 +1,10 @@<script setup lang="ts">import { computed, onBeforeUnmount, onMounted, ref } from "vue";import { useRoute, useRouter } from "vue-router";-import { formsApi, messagesApi } from "../../api/messages";+import { formsApi, messagesApi, teamsApi } from "../../api/messages";import { useNotificationStore } from "../../stores/notification";import { apiMessage } from "../../composables/apiError";-import type { Form, Message, MessageStats } from "../../api/types";+import type { Form, Message, MessageStats, Team } from "../../api/types";import Pagination from "../../components/Pagination.vue";import { usePagination } from "../../composables/usePagination";@@ -25,6 +25,9 @@ const q = ref("");const tag = ref(String(route.query.tag || ""));const priority = ref("");const knownTags = ref<string[]>([]);+const teamId = ref<number>(Number(route.query.team_id) || 0);+const mine = ref(route.query.mine === "1");+const teams = ref<Team[]>([]);const { pageable, goToPage } = usePagination(async (page) => {loading.value = true;@@ -38,6 +41,8 @@ const { pageable, goToPage } = usePagination(async (page) => {q: q.value || undefined,tag: tag.value || undefined,priority: priority.value || undefined,+ team_id: teamId.value || undefined,+ mine: mine.value || undefined,});messages.value = res.data.data;pageable.value = res.data.pageable;@@ -55,11 +60,13 @@ const { pageable, goToPage } = usePagination(async (page) => {async function loadSidebarData() {try {- const [formsRes, statsRes, tagsRes] = await Promise.all([+ const [formsRes, statsRes, tagsRes, teamsRes] = await Promise.all([formsApi.list({ size: 100 }),messagesApi.stats(),messagesApi.tags(),+ teamsApi.list().catch(() => null),]);+ teams.value = teamsRes?.data.data || [];forms.value = formsRes.data.data;stats.value = statsRes.data.data;knownTags.value = tagsRes.data.data.map((t) => t.tag);@@ -80,6 +87,8 @@ function resetFilters() {q.value = "";tag.value = "";priority.value = "";+ teamId.value = 0;+ mine.value = false;goToPage(0);}@@ -249,6 +258,14 @@ function formatDate(date: string | null | undefined) {</select></div>+ <div v-if="teams.length || teamId" style="flex: 1 1 140px">+ <label class="form-label">Team</label>+ <select v-model.number="teamId" class="form-select" @change="applyFilters">+ <option :value="0">Any</option>+ <option v-for="t in teams" :key="t.id" :value="t.id">{{ t.name }}</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">@@ -273,6 +290,14 @@ function formatDate(date: string | null | undefined) {<input v-model="unread" type="checkbox" @change="applyFilters" />Unread only</label>+ <label+ class="form-label"+ style="display: flex; gap: 6px; align-items: center; margin: 0"+ title="Assigned to you, or routed to one of your teams"+ >+ <input v-model="mine" type="checkbox" @change="applyFilters" />+ My work+ </label><button class="btn btn-primary" @click="applyFilters">Apply</button><button class="btn btn-secondary" @click="resetFilters">Reset</button></div>@@ -339,7 +364,12 @@ function formatDate(date: string | null | undefined) {>{{ t }}</button></span></td>- <td>{{ message.form?.name || "-" }}</td>+ <td>+ {{ message.form?.name || "-" }}+ <div v-if="message.team || message.assigned_to" class="route-line">+ {{ [message.team?.name, message.assigned_to?.name].filter(Boolean).join(" · ") }}+ </div>+ </td><td><span :class="statusBadgeClass(message.status)">{{ message.status }}</span></td>@@ -359,6 +389,11 @@ function formatDate(date: string | null | undefined) {</template><style scoped>+.route-line {+ font-size: 12px;+ color: var(--text-tertiary);+}+.collect-note {margin: 0;padding: 0 20px 14px;diff --git a/web/src/views/teams/Teams.vue b/web/src/views/teams/Teams.vuenew file mode 100644index 0000000..4096ddc--- /dev/null+++ b/web/src/views/teams/Teams.vue@@ -0,0 +1,196 @@+<script setup lang="ts">+import { computed, onMounted, ref } from "vue";+import { teamsApi } from "../../api/messages";+import { workspaceApi } from "../../api/workspaces";+import { useNotificationStore } from "../../stores/notification";+import { apiMessage } from "../../composables/apiError";+import type { Team, WorkspaceMember } from "../../api/types";++// Teams group workspace members so routing rules can notify or assign them+// together. Any member can see them; owners and admins change them.++const notify = useNotificationStore();+const loading = ref(true);+const teams = ref<Team[]>([]);+const members = ref<WorkspaceMember[]>([]);++const editing = ref<Team | null>(null);+const showEditor = ref(false);+const saving = ref(false);+const draft = ref({ name: "", email: "", user_ids: [] as number[] });++const memberName = computed(() => {+ const out: Record<number, string> = {};+ members.value.forEach((m) => (out[m.user_id] = m.name || m.email));+ return out;+});++async function load() {+ loading.value = true;+ try {+ const [teamRes, memberRes] = await Promise.all([teamsApi.list(), workspaceApi.listMembers()]);+ teams.value = teamRes.data.data;+ members.value = memberRes.data.data || [];+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to load teams"));+ } finally {+ loading.value = false;+ }+}++function openEditor(team: Team | null) {+ editing.value = team;+ draft.value = {+ name: team?.name || "",+ email: team?.email || "",+ user_ids: (team?.members || []).map((m) => m.user_id),+ };+ showEditor.value = true;+}++function toggleMember(id: number) {+ const ids = draft.value.user_ids;+ draft.value.user_ids = ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id];+}++async function save() {+ saving.value = true;+ try {+ const payload = { name: draft.value.name.trim(), email: draft.value.email.trim(), user_ids: draft.value.user_ids };+ if (editing.value) await teamsApi.update(editing.value.id, payload);+ else await teamsApi.create(payload);+ showEditor.value = false;+ notify.success(editing.value ? "Team saved." : "Team created.");+ await load();+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to save team"));+ } finally {+ saving.value = false;+ }+}++async function remove(team: Team) {+ if (!confirm(`Delete the team "${team.name}"? Submissions routed to it keep no team.`)) return;+ try {+ await teamsApi.delete(team.id);+ notify.success("Team deleted.");+ await load();+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to delete team"));+ }+}++function memberList(team: Team) {+ const names = (team.members || []).map((m) => memberName.value[m.user_id] || m.user?.name || `User ${m.user_id}`);+ return names.length ? names.join(", ") : "No members";+}++onMounted(load);+</script>++<template>+ <div>+ <div class="page-header">+ <h1>Teams</h1>+ <button class="btn btn-primary" @click="openEditor(null)">New team</button>+ </div>++ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>++ <div v-else class="card">+ <div v-if="!teams.length" class="empty-state">+ <h3>No teams yet</h3>+ <p>+ A team is a group of members, like Sales or Billing. Form routing rules can notify a team or assign+ submissions to it, and everyone on it sees them under "My work" in Messages.+ </p>+ <button class="btn btn-primary" @click="openEditor(null)">Create a team</button>+ </div>+ <div v-else class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Team</th>+ <th>Members</th>+ <th>Shared address</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="team in teams" :key="team.id">+ <td><strong>{{ team.name }}</strong></td>+ <td class="team-members">{{ memberList(team) }}</td>+ <td>{{ team.email || "—" }}</td>+ <td class="team-actions">+ <router-link class="btn btn-ghost btn-sm" :to="`/messages?team_id=${team.id}`">Messages</router-link>+ <button class="btn btn-secondary btn-sm" @click="openEditor(team)">Edit</button>+ <button class="btn btn-ghost btn-sm" @click="remove(team)">Delete</button>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>++ <div v-if="showEditor" class="modal-overlay" @click.self="showEditor = false">+ <div class="modal">+ <div class="modal-header">+ <h3>{{ editing ? `Edit ${editing.name}` : "New team" }}</h3>+ </div>+ <div class="modal-body">+ <div class="form-group">+ <label class="form-label" for="team-name">Name</label>+ <input id="team-name" v-model="draft.name" class="form-input" placeholder="Sales" maxlength="80" />+ </div>+ <div class="form-group">+ <label class="form-label" for="team-email">Shared address <span class="muted">(optional)</span></label>+ <input id="team-email" v-model="draft.email" type="email" class="form-input" placeholder="[email protected]" />+ <small class="muted">Notified along with the members when a rule notifies this team.</small>+ </div>+ <fieldset class="form-group team-pick">+ <legend class="form-label">Members</legend>+ <label v-for="m in members" :key="m.user_id" class="checkbox-label">+ <input type="checkbox" :checked="draft.user_ids.includes(m.user_id)" @change="toggleMember(m.user_id)" />+ {{ m.name || m.email }} <span class="muted">{{ m.email }}</span>+ </label>+ </fieldset>+ </div>+ <div class="modal-footer">+ <button class="btn btn-secondary" @click="showEditor = false">Cancel</button>+ <button class="btn btn-primary" :disabled="saving || !draft.name.trim()" @click="save">+ {{ saving ? "Saving…" : editing ? "Save team" : "Create team" }}+ </button>+ </div>+ </div>+ </div>+ </div>+</template>++<style scoped>+.team-members {+ color: var(--text-secondary);+ max-width: 420px;+}++.team-actions {+ display: flex;+ gap: 6px;+ justify-content: flex-end;+ white-space: nowrap;+}++.team-pick {+ border: 0;+ padding: 0;+ margin-inline: 0;+ display: grid;+ gap: 6px;+ max-height: 260px;+ overflow-y: auto;+}++.team-pick legend {+ padding: 0;+ margin-bottom: 6px;+}+</style>