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 a Responses tab with summary, filters and export
Jonas Kanindaa65680d1bd72
diff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.goindex a81f291..92c806f 100644--- a/internal/handlers/form_ingest_handler.go+++ b/internal/handlers/form_ingest_handler.go@@ -614,9 +614,7 @@ func stringify(v any) string {}return "false"case float64:- if t == float64(int64(t)) {- return strings.TrimSuffix(strings.TrimRight(strings.TrimRight(formatFloat(t), "0"), "."), ".")- }+ // The shortest exact form: 30 stays "30", 2.50 becomes "2.5".return formatFloat(t)case []any:parts := make([]string, 0, len(t))diff --git a/internal/handlers/form_submission_handler.go b/internal/handlers/form_submission_handler.gonew file mode 100644index 0000000..fca22a3--- /dev/null+++ b/internal/handlers/form_submission_handler.go@@ -0,0 +1,464 @@+// 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 (+ "bufio"+ "encoding/csv"+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "strconv"+ "strings"+ "time"++ "github.com/goposta/posta/internal/middlewares"+ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/messages"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/logger"+ "github.com/jkaninda/okapi"+)++// Form submissions are a form's messages read as responses: typed answers,+// field filters, a summary and an export. They live outside /forms on+// purpose: /forms is tenant administration (admin scope), while reading+// responses is reading content (read scope).++const (+ // maxSummarySubmissions bounds how many of the newest submissions a+ // summary reads; the result says when it stopped short.+ maxSummarySubmissions = 50000+ // maxSubmissionExport bounds one export.+ maxSubmissionExport = 100000+)++// SubmissionQueryRequest selects a form's submissions. Field filters are read+// from the raw query: field.<key>=value for equality, field.<key>[gte]=n and+// field.<key>[lte]=n for ranges on number, scale, rating, date and time+// questions.+type SubmissionQueryRequest struct {+ FormID int `query:"form_id" doc:"The form whose submissions to read (required)"`+ Page int `query:"page" default:"0"`+ Size int `query:"size" default:"20"`+ Status string `query:"status" enum:"received,flagged,quarantined,rejected" doc:"Defaults to received and flagged: spam is not a response"`+ Q string `query:"q" doc:"Free-text search over the submission"`+ After string `query:"after" doc:"RFC 3339 lower bound on received time"`+ Before string `query:"before" doc:"RFC 3339 upper bound on received time"`+ Format string `query:"format" enum:"csv,json" default:"csv" doc:"Export only"`+}++// submissionQuery resolves the form and the filter a request names. It writes+// the error response itself and returns nil when the request is invalid.+func (h *MessageHandler) submissionQuery(c *okapi.Context, req *SubmissionQueryRequest) (*models.Form, *repositories.MessageFilterQuery, error) {+ if req.FormID <= 0 {+ return nil, nil, c.AbortBadRequest("form_id is required")+ }+ form, err := h.formRepo.FindByIDForScope(getScope(c), uint(req.FormID))+ if err != nil {+ return nil, nil, c.AbortNotFound("form not found")+ }+ equals, ranges, err := parseFieldFilters(form.Fields, c.Request().URL.Query())+ if err != nil {+ return nil, nil, c.AbortBadRequest(err.Error())+ }+ filter := &repositories.MessageFilterQuery{+ FormID: form.ID,+ Status: req.Status,+ Query: strings.TrimSpace(req.Q),+ SubmissionsOnly: true,+ DataEquals: equals,+ DataRanges: ranges,+ }+ if t, err := time.Parse(time.RFC3339, req.After); err == nil {+ filter.From = &t+ }+ if t, err := time.Parse(time.RFC3339, req.Before); err == nil {+ filter.To = &t+ }+ return form, filter, nil+}++// parseFieldFilters turns field.<key>[op]=value query parameters into typed+// filters. Every key must be a question of the form, so nothing a caller+// sends reaches SQL except as a bound value.+func parseFieldFilters(defs models.FieldDefs, query url.Values) (map[string]any, []repositories.DataRange, error) {+ var equals map[string]any+ var ranges []repositories.DataRange+ for param, values := range query {+ if !strings.HasPrefix(param, "field.") || len(values) == 0 {+ continue+ }+ key, op := strings.TrimPrefix(param, "field."), ""+ if i := strings.IndexByte(key, '['); i >= 0 && strings.HasSuffix(key, "]") {+ key, op = key[:i], key[i+1:len(key)-1]+ }+ if len(defs) == 0 {+ return nil, nil, fmt.Errorf("this form has no questions to filter by")+ }+ var def *models.FieldDef+ for i := range defs {+ if defs[i].Key == key {+ def = &defs[i]+ break+ }+ }+ if def == nil {+ return nil, nil, fmt.Errorf("unknown field %q", key)+ }+ raw := strings.TrimSpace(values[0])+ numeric := def.Type == models.FieldNumber || def.Type == models.FieldScale || def.Type == models.FieldRating++ switch op {+ case "":+ v, err := equalityValue(def, raw)+ if err != nil {+ return nil, nil, err+ }+ if equals == nil {+ equals = map[string]any{}+ }+ equals[key] = v+ case "gte", "lte":+ r := repositories.DataRange{Key: key, Op: op, Numeric: numeric}+ switch {+ case numeric:+ n, err := strconv.ParseFloat(raw, 64)+ if err != nil {+ return nil, nil, fmt.Errorf("field %q: %q is not a number", key, raw)+ }+ r.Value = n+ case def.Type == models.FieldDate || def.Type == models.FieldTime:+ r.Value = raw+ default:+ return nil, nil, fmt.Errorf("field %q cannot be filtered by range", key)+ }+ ranges = append(ranges, r)+ default:+ return nil, nil, fmt.Errorf("field %q: unknown operator %q (use gte or lte)", key, op)+ }+ }+ return equals, ranges, nil+}++// equalityValue types a filter value the way submissions store it, so the+// containment match is exact.+func equalityValue(def *models.FieldDef, raw string) (any, error) {+ switch def.Type {+ case models.FieldNumber, models.FieldScale, models.FieldRating:+ n, err := strconv.ParseFloat(raw, 64)+ if err != nil {+ return nil, fmt.Errorf("field %q: %q is not a number", def.Key, raw)+ }+ return n, nil+ case models.FieldCheckbox:+ switch strings.ToLower(raw) {+ case "true", "yes", "1", "on":+ return true, nil+ case "false", "no", "0", "off":+ return false, nil+ }+ return nil, fmt.Errorf("field %q: %q is not true or false", def.Key, raw)+ case models.FieldMultiSelect:+ return []any{raw}, nil+ }+ return raw, nil+}++// canSeePII reports whether the caller may read personal-data answers in+// bulk: a workspace owner or admin, or an API key with the admin scope. A+// workspace-bound key resolves as owner, so its scopes decide, not its role.+func canSeePII(c *okapi.Context) bool {+ if c.GetString(middlewares.CtxAuthMethod) == middlewares.AuthMethodAPIKey {+ for _, s := range middlewares.APIKeyScopes(c) {+ if s == models.ScopeAdmin || s == models.ScopeAll {+ return true+ }+ }+ return false+ }+ return workspaceRole(c).CanManageMembers()+}++// ListSubmissions pages through a form's submissions, newest first.+func (h *MessageHandler) ListSubmissions(c *okapi.Context, req *SubmissionQueryRequest) error {+ _, filter, err := h.submissionQuery(c, req)+ if filter == nil {+ return err+ }+ page, size, offset := normalizePageParams(req.Page, req.Size)+ items, total, err := h.repo.FindByScopeFiltered(getScope(c), *filter, size, offset)+ if err != nil {+ return c.AbortInternalServerError("failed to list submissions")+ }+ for i := range items {+ hydrate(&items[i])+ items[i].Body = truncateBody(items[i].Body, 400)+ items[i].Form = nil+ }+ return paginated(c, items, total, page, size)+}++// SubmissionSummary reduces a form's submissions to per-question figures.+func (h *MessageHandler) SubmissionSummary(c *okapi.Context, req *SubmissionQueryRequest) error {+ form, filter, err := h.submissionQuery(c, req)+ if filter == nil {+ return err+ }+ s := messages.NewSummarizer(form.Fields, canSeePII(c))+ truncated, err := h.repo.EachMessage(getScope(c), *filter, 1000, maxSummarySubmissions, func(batch []models.Message) error {+ for i := range batch {+ s.Add(answersOf(&batch[i]))+ }+ return nil+ })+ if err != nil {+ return c.AbortInternalServerError("failed to summarize submissions")+ }+ return ok(c, s.Result(truncated))+}++// answersOf returns a submission's answers by key. Submissions stored before+// the form had a schema have no typed data, so their raw fields stand in.+func answersOf(m *models.Message) models.SubmissionData {+ if m.Data != nil {+ return m.Data+ }+ hydrate(m)+ out := make(models.SubmissionData, len(m.Fields))+ for _, f := range m.Fields {+ if _, seen := out[f.Key]; !seen {+ out[f.Key] = f.Value+ }+ }+ return out+}++// exportColumns are the questions an export carries, active ones first, then+// archived ones, so old answers are not lost. Personal-data questions are+// left out unless the caller may see them.+func 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 {+ continue+ }+ if f.PII && !showPII {+ withheld+++ continue+ }+ cols = append(cols, f)+ }+ }+ return cols, withheld+}++// csvSafe keeps a cell from being read as a formula by a spreadsheet:+// submissions are written by the public.+func csvSafe(v string) string {+ if v != "" && strings.ContainsRune("=+-@\t\r", rune(v[0])) {+ return "'" + v+ }+ return v+}++// ExportSubmissions streams a form's submissions as CSV or JSON.+func (h *MessageHandler) ExportSubmissions(c *okapi.Context, req *SubmissionQueryRequest) error {+ form, filter, err := h.submissionQuery(c, req)+ if filter == nil {+ return err+ }+ format := req.Format+ if format != "json" {+ format = "csv"+ }+ showPII := canSeePII(c)+ cols, withheld := exportColumns(form.Fields, showPII)+ known := map[string]bool{form.Honeypot(): true}+ for _, f := range form.Fields {+ known[f.Key] = true+ }++ slug := form.Slug+ if slug == "" {+ slug = "form"+ }+ filename := fmt.Sprintf("%s-responses-%s.%s", slug, time.Now().UTC().Format("20060102"), format)+ hdr := c.ResponseWriter().Header()+ if format == "csv" {+ hdr.Set("Content-Type", "text/csv; charset=utf-8")+ } else {+ hdr.Set("Content-Type", "application/json; charset=utf-8")+ }+ hdr.Set("Content-Disposition", contentDisposition(filename))+ hdr.Set("Cache-Control", "no-store")+ hdr.Set("X-Content-Type-Options", "nosniff")+ if withheld > 0 {+ hdr.Set("X-Posta-Withheld-Fields", strconv.Itoa(withheld))+ }+ c.ResponseWriter().WriteHeader(http.StatusOK)++ out := bufio.NewWriter(c.ResponseWriter())+ defer func() { _ = out.Flush() }()++ rows := 0+ var write func(m *models.Message) error+ var finish func() error++ if format == "csv" {+ // The byte-order mark makes Excel read the file as UTF-8.+ _, _ = out.WriteString("\ufeff")+ w := csv.NewWriter(out)+ header := []string{"Submitted at", "ID", "Status"}+ if len(form.Fields) == 0 {+ header = append(header, "Email", "Name", "Phone", "Subject", "Message", "Fields")+ }+ for _, f := range cols {+ label := f.Label+ if label == "" {+ label = f.Key+ }+ if f.Archived {+ label += " (archived)"+ }+ header = append(header, label)+ }+ if len(form.Fields) > 0 {+ header = append(header, "Other fields")+ }+ if err := w.Write(header); err != nil {+ return nil+ }+ write = func(m *models.Message) error {+ record := []string{m.CreatedAt.UTC().Format(time.RFC3339), m.UUID, string(m.Status)}+ if len(form.Fields) == 0 {+ hydrate(m)+ raw, _ := json.Marshal(m.Fields)+ record = append(record, csvSafe(m.SenderEmail), csvSafe(m.SenderName), csvSafe(m.SenderPhone),+ csvSafe(m.Subject), csvSafe(m.Body), csvSafe(string(raw)))+ }+ answers := answersOf(m)+ for i := range cols {+ cell := messages.ExportValue(&cols[i], answers[cols[i].Key])+ switch cols[i].Type {+ case models.FieldNumber, models.FieldScale, models.FieldRating:+ default:+ cell = csvSafe(cell)+ }+ record = append(record, cell)+ }+ if len(form.Fields) > 0 {+ record = append(record, csvSafe(otherFields(m, known)))+ }+ return w.Write(record)+ }+ finish = func() error {+ w.Flush()+ return w.Error()+ }+ } else {+ _, _ = out.WriteString("[")+ write = func(m *models.Message) error {+ item := map[string]any{+ "id": m.UUID,+ "submitted_at": m.CreatedAt.UTC().Format(time.RFC3339),+ "status": m.Status,+ }+ if len(form.Fields) == 0 {+ hydrate(m)+ item["sender_email"], item["sender_name"], item["subject"], item["body"] = m.SenderEmail, m.SenderName, m.Subject, m.Body+ item["fields"] = m.Fields+ } else {+ answers := answersOf(m)+ data := make(map[string]any, len(cols))+ for _, f := range cols {+ if v, ok := answers[f.Key]; ok {+ data[f.Key] = v+ }+ }+ item["data"] = data+ if other := otherFields(m, known); other != "" {+ item["other_fields"] = json.RawMessage(other)+ }+ }+ raw, err := json.Marshal(item)+ if err != nil {+ return err+ }+ if rows > 0 {+ _, _ = out.WriteString(",")+ }+ _, err = out.Write(raw)+ return err+ }+ finish = func() error {+ _, err := out.WriteString("]\n")+ return err+ }+ }++ truncated, err := h.repo.EachMessage(getScope(c), *filter, 500, maxSubmissionExport, func(batch []models.Message) error {+ for i := range batch {+ if err := write(&batch[i]); err != nil {+ return err+ }+ rows+++ }+ return nil+ })+ if err == nil {+ err = finish()+ }+ if err != nil {+ // The status is already sent; the file ends short.+ logger.Warn("form submission export failed", "form_id", form.ID, "rows", rows, "error", err)+ }++ if h.audit != nil {+ if scope := getScope(c); scope.WorkspaceID != nil {+ piiIncluded := false+ for _, f := range cols {+ piiIncluded = piiIncluded || f.PII+ }+ h.audit.LogCtxScoped(c, *scope.WorkspaceID, "form.submissions_exported",+ fmt.Sprintf("Exported %d responses of form %q as %s", rows, form.Name, strings.ToUpper(format)),+ map[string]any{"form_id": form.ID, "format": format, "rows": rows, "pii": piiIncluded, "withheld_fields": withheld, "truncated": truncated})+ }+ }+ return nil+}++// otherFields returns, as a JSON object, the submitted fields the schema does+// not declare (kept under the "keep" policy), or "" when there are none.+func otherFields(m *models.Message, known map[string]bool) string {+ hydrate(m)+ extra := map[string]string{}+ for _, f := range m.Fields {+ if !known[f.Key] && !strings.HasPrefix(f.Key, "_") {+ extra[f.Key] = f.Value+ }+ }+ if len(extra) == 0 {+ return ""+ }+ raw, _ := json.Marshal(extra)+ return string(raw)+}diff --git a/internal/handlers/form_submission_test.go b/internal/handlers/form_submission_test.gonew file mode 100644index 0000000..f0d6b5b--- /dev/null+++ b/internal/handlers/form_submission_test.go@@ -0,0 +1,168 @@+// 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 (+ "net/url"+ "reflect"+ "strings"+ "testing"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/storage/repositories"+)++func submissionSchema() models.FieldDefs {+ return models.FieldDefs{+ {Key: "email", Label: "Email", Type: models.FieldEmail, PII: true},+ {Key: "dept", Label: "Department", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "sales"}}},+ {Key: "topics", Label: "Topics", Type: models.FieldMultiSelect, Options: []models.FieldOption{{Value: "api"}}},+ {Key: "nps", Label: "NPS", Type: models.FieldScale},+ {Key: "agree", Label: "Agree", Type: models.FieldCheckbox},+ {Key: "day", Label: "Day", Type: models.FieldDate},+ {Key: "old", Label: "Old", Type: models.FieldText, Archived: true},+ }+}++func TestParseFieldFiltersTypesValues(t *testing.T) {+ q := url.Values{+ "field.dept": {"sales"},+ "field.topics": {"api"},+ "field.nps": {"9"},+ "field.agree": {"yes"},+ "field.nps[gte]": {"7"},+ "field.day[lte]": {"2026-12-31"},+ "field.old": {"x"}, // archived questions still filter old answers+ "page": {"2"},+ }+ equals, ranges, err := parseFieldFilters(submissionSchema(), q)+ if err != nil {+ t.Fatal(err)+ }+ want := map[string]any{"dept": "sales", "topics": []any{"api"}, "nps": 9.0, "agree": true, "old": "x"}+ if !reflect.DeepEqual(equals, want) {+ t.Errorf("equals = %#v, want %#v", equals, want)+ }+ if len(ranges) != 2 {+ t.Fatalf("ranges = %+v", ranges)+ }+ byKey := map[string]repositories.DataRange{}+ for _, r := range ranges {+ byKey[r.Key] = r+ }+ if r := byKey["nps"]; !r.Numeric || r.Op != "gte" || r.Value != 7.0 {+ t.Errorf("nps range = %+v", r)+ }+ if r := byKey["day"]; r.Numeric || r.Op != "lte" || r.Value != "2026-12-31" {+ t.Errorf("day range = %+v", r)+ }+}++func TestParseFieldFiltersRejects(t *testing.T) {+ cases := map[string]url.Values{+ "unknown field": {"field.nope": {"1"}},+ "hostile key": {"field.dept') OR 1=1 --": {"x"}},+ "not a number": {"field.nps": {"high"}},+ "not true or false": {"field.agree": {"maybe"}},+ "cannot be filtered by range": {"field.dept[gte]": {"a"}},+ "unknown operator": {"field.nps[ne]": {"1"}},+ }+ for want, q := range cases {+ _, _, err := parseFieldFilters(submissionSchema(), q)+ if err == nil {+ t.Errorf("%v: accepted", q)+ continue+ }+ if want != "hostile key" && !strings.Contains(err.Error(), want) {+ t.Errorf("%v: error %q, want it to mention %q", q, err, want)+ }+ }+ if _, _, err := parseFieldFilters(nil, url.Values{"field.a": {"b"}}); err == nil || !strings.Contains(err.Error(), "no questions") {+ t.Errorf("schemaless form: %v", err)+ }+ if eq, r, err := parseFieldFilters(nil, url.Values{"q": {"x"}}); err != nil || eq != nil || r != nil {+ t.Errorf("no field filters: %v %v %v", eq, r, err)+ }+}++func TestCSVSafe(t *testing.T) {+ for in, want := range map[string]string{+ "=HYPERLINK(\"x\")": "'=HYPERLINK(\"x\")",+ "+1 555": "'+1 555",+ "-2": "'-2",+ "@SUM(A1)": "'@SUM(A1)",+ "\tcmd": "'\tcmd",+ "plain": "plain",+ "": "",+ } {+ if got := csvSafe(in); got != want {+ t.Errorf("csvSafe(%q) = %q, want %q", in, got, want)+ }+ }+}++func TestExportColumnsOrderAndPII(t *testing.T) {+ keys := func(cols []models.FieldDef) []string {+ out := []string{}+ for _, c := range cols {+ out = append(out, c.Key)+ }+ return out+ }+ cols, withheld := exportColumns(submissionSchema(), false)+ if withheld != 1 || !reflect.DeepEqual(keys(cols), []string{"dept", "topics", "nps", "agree", "day", "old"}) {+ t.Errorf("without PII: %v, withheld %d", keys(cols), withheld)+ }+ cols, withheld = exportColumns(submissionSchema(), true)+ if withheld != 0 || keys(cols)[0] != "email" || keys(cols)[len(cols)-1] != "old" {+ t.Errorf("with PII: %v, withheld %d", keys(cols), withheld)+ }+}++func TestOtherFieldsSkipsSchemaAndReserved(t *testing.T) {+ m := &models.Message{FieldsJSON: `[{"key":"dept","value":"sales"},{"key":"utm","value":"ad"},{"key":"_nonce","value":"n"},{"key":"_gotcha","value":""}]`}+ got := otherFields(m, map[string]bool{"dept": true, "_gotcha": true})+ if got != `{"utm":"ad"}` {+ t.Errorf("otherFields = %s", got)+ }+}++// JSON submissions carry numbers as numbers; they must reach Data and the+// display copy unchanged. Trimming zeros once turned 30 into 3.+func TestStringifyKeepsNumbers(t *testing.T) {+ for in, want := range map[float64]string{+ 30: "30",+ 100: "100",+ 10: "10",+ 0: "0",+ -20: "-20",+ 2.5: "2.5",+ 0.1: "0.1",+ 1e21: "1000000000000000000000",+ 1234.0: "1234",+ } {+ if got := stringify(in); got != want {+ t.Errorf("stringify(%v) = %q, want %q", in, got, want)+ }+ }+ if got := stringify([]any{10.0, "a", true}); got != "10, a, true" {+ t.Errorf("stringify(list) = %q", got)+ }+}diff --git a/internal/middlewares/message_scope_test.go b/internal/middlewares/message_scope_test.goindex 787bfbd..d0eb218 100644--- a/internal/middlewares/message_scope_test.go+++ b/internal/middlewares/message_scope_test.go@@ -42,6 +42,12 @@ func TestWorkspaceScopeForMessageRoutes(t *testing.T) {{http.MethodPut, "/api/v1/workspaces/current/forms/1", models.ScopeAdmin},{http.MethodPost, "/api/v1/workspaces/current/forms/1/rotate-key", models.ScopeAdmin},+ // Responses are content, not configuration: reading them needs only read,+ // even though the form they belong to is admin-only.+ {http.MethodGet, "/api/v1/workspaces/current/form-submissions", models.ScopeRead},+ {http.MethodGet, "/api/v1/workspaces/current/form-submissions/summary", models.ScopeRead},+ {http.MethodGet, "/api/v1/workspaces/current/form-submissions/export", models.ScopeRead},+{http.MethodGet, "/api/v1/workspaces/current/message-filters", models.ScopeAdmin},{http.MethodPost, "/api/v1/workspaces/current/message-filters", models.ScopeAdmin},}diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.goindex eee770c..ca909fe 100644--- a/internal/routes/message_routes.go+++ b/internal/routes/message_routes.go@@ -194,6 +194,35 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {Request: &handlers.MessageListRequest{},Response: &dto.PageableResponse[models.Message]{},},+ {+ Method: http.MethodGet,+ Path: "/form-submissions",+ Handler: okapi.H(r.h.message.ListSubmissions),+ Group: opsGroup,+ Summary: "List a form's submissions",+ Description: "Pages through a form's responses, newest first. Filter answers with field.<key>=value, or field.<key>[gte]=n and field.<key>[lte]=n on number, scale, rating, date and time questions. Spam is left out unless status asks for it.",+ Request: &handlers.SubmissionQueryRequest{},+ Response: &dto.PageableResponse[models.Message]{},+ },+ {+ Method: http.MethodGet,+ Path: "/form-submissions/summary",+ Handler: okapi.H(r.h.message.SubmissionSummary),+ Group: opsGroup,+ Summary: "Summarize a form's submissions",+ Description: "Per-question figures over the same filters: option counts, scale and rating histograms with means, number ranges, and the latest text answers. Personal-data answers are quoted only for workspace admins or admin-scoped keys.",+ Request: &handlers.SubmissionQueryRequest{},+ Response: &dto.Response[messages.SubmissionSummary]{},+ },+ {+ Method: http.MethodGet,+ Path: "/form-submissions/export",+ Handler: okapi.H(r.h.message.ExportSubmissions),+ Group: streamGroup,+ Summary: "Export a form's submissions",+ Description: "Streams the filtered responses as CSV (one column per question, choices by label) or JSON (typed answers). Personal-data questions are included only for workspace admins or admin-scoped keys; X-Posta-Withheld-Fields counts the ones left out. Each export is audit-logged.",+ Request: &handlers.SubmissionQueryRequest{},+ },{Method: http.MethodGet,Path: "/messages/stats",diff --git a/internal/services/messages/responses.go b/internal/services/messages/responses.gonew file mode 100644index 0000000..b4ca2d6--- /dev/null+++ b/internal/services/messages/responses.go@@ -0,0 +1,277 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package messages++import (+ "fmt"+ "strconv"+ "strings"++ "github.com/goposta/posta/internal/models"+)++// summarySamples is how many recent text answers a question's summary shows.+const summarySamples = 20++// OptionCount is how many responses chose one value.+type OptionCount struct {+ Value string `json:"value"`+ Label string `json:"label"`+ Count int `json:"count"`+}++// FieldSummary aggregates the answers to one question.+type FieldSummary struct {+ Key string `json:"key"`+ Label string `json:"label"`+ Type models.FieldType `json:"type"`+ PII bool `json:"pii,omitempty"`+ Answered int `json:"answered"`+ // Options counts each value of a choice, checkbox, scale or rating+ // question, in the schema's order, then any value the schema no longer has.+ Options []OptionCount `json:"options,omitempty"`+ Mean *float64 `json:"mean,omitempty"`+ Min *float64 `json:"min,omitempty"`+ Max *float64 `json:"max,omitempty"`+ // Samples are the latest text answers, newest first. SamplesHidden says+ // they were withheld because the question is personal data.+ Samples []string `json:"samples,omitempty"`+ SamplesHidden bool `json:"samples_hidden,omitempty"`+}++// SubmissionSummary is a form's responses reduced to per-question figures.+type SubmissionSummary struct {+ Total int `json:"total"`+ Truncated bool `json:"truncated"`+ Fields []FieldSummary `json:"fields"`+}++type fieldAgg struct {+ def models.FieldDef+ sum FieldSummary+ counts map[string]int+ extra []string // values seen that the schema does not list, in first-seen order+ total float64+ nums int+}++// Summarizer builds a SubmissionSummary from submissions fed newest first.+type Summarizer struct {+ fields []*fieldAgg+ total int+ showPII bool+}++// NewSummarizer summarizes the active questions of defs. Without showPII, the+// text answers of personal-data questions are counted but not quoted.+func NewSummarizer(defs models.FieldDefs, showPII bool) *Summarizer {+ s := &Summarizer{showPII: showPII}+ for _, f := range defs.Active() {+ if f.Type == models.FieldHidden {+ continue+ }+ s.fields = append(s.fields, &fieldAgg{+ def: f,+ sum: FieldSummary{Key: f.Key, Label: f.Label, Type: f.Type, PII: f.PII},+ counts: map[string]int{},+ })+ }+ return s+}++// Add counts one submission's answers.+func (s *Summarizer) Add(data models.SubmissionData) {+ s.total+++ for _, a := range s.fields {+ v, ok := data[a.def.Key]+ if !ok || isEmptyAnswer(v) {+ continue+ }+ a.sum.Answered+++ switch a.def.Type {+ case models.FieldSelect, models.FieldMultiSelect:+ for _, item := range answerList(v) {+ a.count(item)+ }+ case models.FieldCheckbox:+ if b, isBool := v.(bool); isBool && b {+ a.count("true")+ } else {+ a.count("false")+ }+ case models.FieldScale, models.FieldRating, models.FieldNumber:+ n, isNum := v.(float64)+ if !isNum {+ continue+ }+ a.total += n+ a.nums+++ if a.sum.Min == nil || n < *a.sum.Min {+ a.sum.Min = ptr(n)+ }+ if a.sum.Max == nil || n > *a.sum.Max {+ a.sum.Max = ptr(n)+ }+ if a.def.Type != models.FieldNumber {+ a.count(strconv.FormatFloat(n, 'f', -1, 64))+ }+ default:+ if len(a.sum.Samples) < summarySamples && (!a.def.PII || s.showPII) {+ a.sum.Samples = append(a.sum.Samples, fmt.Sprint(v))+ }+ }+ }+}++func (a *fieldAgg) count(value string) {+ if _, seen := a.counts[value]; !seen && !a.known(value) {+ a.extra = append(a.extra, value)+ }+ a.counts[value]+++}++func (a *fieldAgg) known(value string) bool {+ for _, o := range a.choices() {+ if o.Value == value {+ return true+ }+ }+ return false+}++// choices lists the values a question offers, in display order.+func (a *fieldAgg) choices() []OptionCount {+ f := &a.def+ switch f.Type {+ case models.FieldSelect, models.FieldMultiSelect:+ out := make([]OptionCount, 0, len(f.Options))+ for _, o := range f.Options {+ label := o.Label+ if label == "" {+ label = o.Value+ }+ out = append(out, OptionCount{Value: o.Value, Label: label})+ }+ return out+ case models.FieldCheckbox:+ return []OptionCount{{Value: "true", Label: "Yes"}, {Value: "false", Label: "No"}}+ case models.FieldScale, models.FieldRating:+ lo, hi := ScaleRange(f)+ if f.Type == models.FieldRating {+ lo, hi = 1, RatingStars(f)+ }+ out := make([]OptionCount, 0, hi-lo+1)+ for n := lo; n <= hi; n++ {+ v := strconv.Itoa(n)+ out = append(out, OptionCount{Value: v, Label: v})+ }+ return out+ }+ return nil+}++// Result returns the summary. truncated reports that only the newest+// submissions were read.+func (s *Summarizer) Result(truncated bool) SubmissionSummary {+ out := SubmissionSummary{Total: s.total, Truncated: truncated, Fields: make([]FieldSummary, 0, len(s.fields))}+ for _, a := range s.fields {+ sum := a.sum+ if choices := a.choices(); choices != nil {+ for _, c := range choices {+ c.Count = a.counts[c.Value]+ sum.Options = append(sum.Options, c)+ }+ for _, v := range a.extra {+ sum.Options = append(sum.Options, OptionCount{Value: v, Label: v, Count: a.counts[v]})+ }+ }+ if a.nums > 0 {+ sum.Mean = ptr(a.total / float64(a.nums))+ }+ if a.def.PII && !s.showPII && sum.Answered > 0 && sum.Options == nil && sum.Mean == nil {+ sum.SamplesHidden = true+ }+ out.Fields = append(out.Fields, sum)+ }+ return out+}++// ExportValue renders an answer for a spreadsheet cell: choices by their+// labels, booleans as yes or no, several values joined with "; ".+func ExportValue(f *models.FieldDef, v any) string {+ if v == nil {+ return ""+ }+ switch val := v.(type) {+ case bool:+ if val {+ return "yes"+ }+ return "no"+ case float64:+ return strconv.FormatFloat(val, 'f', -1, 64)+ case string:+ return exportLabel(f, val)+ case []any:+ parts := make([]string, 0, len(val))+ for _, item := range val {+ parts = append(parts, exportLabel(f, fmt.Sprint(item)))+ }+ return strings.Join(parts, "; ")+ }+ return fmt.Sprint(v)+}++func exportLabel(f *models.FieldDef, value string) string {+ if f == nil {+ return value+ }+ for _, o := range f.Options {+ if o.Value == value && o.Label != "" {+ return o.Label+ }+ }+ return value+}++func answerList(v any) []string {+ if list, ok := v.([]any); ok {+ out := make([]string, 0, len(list))+ for _, item := range list {+ out = append(out, fmt.Sprint(item))+ }+ return out+ }+ return []string{fmt.Sprint(v)}+}++func isEmptyAnswer(v any) bool {+ switch val := v.(type) {+ case nil:+ return true+ case string:+ return strings.TrimSpace(val) == ""+ case []any:+ return len(val) == 0+ }+ return false+}++func ptr[T any](v T) *T { return &v }diff --git a/internal/services/messages/responses_test.go b/internal/services/messages/responses_test.gonew file mode 100644index 0000000..608c4b8--- /dev/null+++ b/internal/services/messages/responses_test.go@@ -0,0 +1,162 @@+// 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"+ "testing"++ "github.com/goposta/posta/internal/models"+)++func surveySchema() models.FieldDefs {+ return models.FieldDefs{+ {Key: "email", Label: "Email", Type: models.FieldEmail, PII: true},+ {Key: "dept", Label: "Department", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "sales", Label: "Sales"}, {Value: "support"}}},+ {Key: "topics", Label: "Topics", Type: models.FieldMultiSelect, Options: []models.FieldOption{{Value: "api"}, {Value: "ui", Label: "Dashboard"}}},+ {Key: "nps", Label: "Recommend", Type: models.FieldScale, Min: ptrF(0), Max: ptrF(3)},+ {Key: "stars", Label: "Stars", Type: models.FieldRating, Max: ptrF(3)},+ {Key: "agree", Label: "Agree", Type: models.FieldCheckbox},+ {Key: "seats", Label: "Seats", Type: models.FieldNumber},+ {Key: "notes", Label: "Notes", Type: models.FieldTextarea},+ {Key: "old", Label: "Old", Type: models.FieldText, Archived: true},+ {Key: "src", Type: models.FieldHidden},+ }+}++func counts(fs FieldSummary) map[string]int {+ out := map[string]int{}+ for _, o := range fs.Options {+ out[o.Value] = o.Count+ }+ return out+}++func TestSummarizerCountsEveryQuestionType(t *testing.T) {+ s := NewSummarizer(surveySchema(), false)+ s.Add(models.SubmissionData{"email": "[email protected]", "dept": "sales", "topics": []any{"api", "ui"}, "nps": 3.0, "stars": 2.0, "agree": true, "seats": 10.0, "notes": "newest"})+ s.Add(models.SubmissionData{"email": "[email protected]", "dept": "legacy", "topics": []any{"api"}, "nps": 0.0, "agree": false, "seats": 4.0, "notes": " "})+ s.Add(models.SubmissionData{"dept": "sales", "old": "kept", "src": "ad"})+ got := s.Result(false)++ if got.Total != 3 {+ t.Fatalf("total = %d, want 3", got.Total)+ }+ keys := []string{}+ byKey := map[string]FieldSummary{}+ for _, f := range got.Fields {+ keys = append(keys, f.Key)+ byKey[f.Key] = f+ }+ // Archived and hidden questions are not summarized.+ if want := []string{"email", "dept", "topics", "nps", "stars", "agree", "seats", "notes"}; !reflect.DeepEqual(keys, want) {+ t.Fatalf("fields = %v, want %v", keys, want)+ }++ dept := byKey["dept"]+ if dept.Answered != 3 || !reflect.DeepEqual(counts(dept), map[string]int{"sales": 2, "support": 0, "legacy": 1}) {+ t.Errorf("dept = %+v", dept)+ }+ // Schema order first, then values the schema no longer lists.+ if order := []string{dept.Options[0].Value, dept.Options[1].Value, dept.Options[2].Value}; !reflect.DeepEqual(order, []string{"sales", "support", "legacy"}) {+ t.Errorf("dept order = %v", order)+ }+ if dept.Options[1].Label != "support" || dept.Options[0].Label != "Sales" {+ t.Errorf("dept labels = %+v", dept.Options)+ }+ if c := counts(byKey["topics"]); c["api"] != 2 || c["ui"] != 1 || byKey["topics"].Answered != 2 {+ t.Errorf("topics = %+v", byKey["topics"])+ }+ nps := byKey["nps"]+ if !reflect.DeepEqual(counts(nps), map[string]int{"0": 1, "1": 0, "2": 0, "3": 1}) || nps.Mean == nil || *nps.Mean != 1.5 {+ t.Errorf("nps = %+v", nps)+ }+ if c := counts(byKey["stars"]); len(byKey["stars"].Options) != 3 || c["2"] != 1 {+ t.Errorf("stars = %+v", byKey["stars"])+ }+ if c := counts(byKey["agree"]); c["true"] != 1 || c["false"] != 1 {+ t.Errorf("agree = %+v", byKey["agree"])+ }+ seats := byKey["seats"]+ if seats.Options != nil || *seats.Mean != 7 || *seats.Min != 4 || *seats.Max != 10 {+ t.Errorf("seats = %+v", seats)+ }+ // Blank answers are not answers.+ if notes := byKey["notes"]; notes.Answered != 1 || !reflect.DeepEqual(notes.Samples, []string{"newest"}) {+ t.Errorf("notes = %+v", notes)+ }+}++func TestSummarizerWithholdsPersonalDataSamples(t *testing.T) {+ data := models.SubmissionData{"email": "[email protected]"}++ hidden := NewSummarizer(surveySchema(), false)+ hidden.Add(data)+ email := hidden.Result(false).Fields[0]+ if email.Samples != nil || !email.SamplesHidden || email.Answered != 1 {+ t.Errorf("without PII access: %+v", email)+ }++ shown := NewSummarizer(surveySchema(), true)+ shown.Add(data)+ email = shown.Result(true).Fields[0]+ if !reflect.DeepEqual(email.Samples, []string{"[email protected]"}) || email.SamplesHidden {+ t.Errorf("with PII access: %+v", email)+ }+ if !shown.Result(true).Truncated {+ t.Error("truncated flag lost")+ }+}++func TestSummarizerKeepsTheLatestSamples(t *testing.T) {+ s := NewSummarizer(models.FieldDefs{{Key: "q", Label: "Q", Type: models.FieldText}}, false)+ for i := 0; i < summarySamples+5; i++ {+ s.Add(models.SubmissionData{"q": string(rune('a' + i))})+ }+ q := s.Result(false).Fields[0]+ if q.Answered != summarySamples+5 || len(q.Samples) != summarySamples || q.Samples[0] != "a" {+ t.Errorf("samples = %d (first %q), answered %d", len(q.Samples), q.Samples[0], q.Answered)+ }+}++func TestExportValue(t *testing.T) {+ dept := &models.FieldDef{Type: models.FieldSelect, Options: []models.FieldOption{{Value: "sales", Label: "Sales"}, {Value: "support"}}}+ cases := []struct {+ field *models.FieldDef+ in any+ want string+ }{+ {dept, "sales", "Sales"},+ {dept, "support", "support"},+ {dept, "gone", "gone"},+ {dept, []any{"sales", "support"}, "Sales; support"},+ {nil, true, "yes"},+ {nil, false, "no"},+ {nil, 2.5, "2.5"},+ {nil, 10.0, "10"},+ {nil, nil, ""},+ {nil, "plain", "plain"},+ }+ for _, c := range cases {+ if got := ExportValue(c.field, c.in); got != c.want {+ t.Errorf("ExportValue(%v) = %q, want %q", c.in, got, c.want)+ }+ }+}diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.goindex d721517..44b6bc4 100644--- a/internal/storage/migration/constraints.go+++ b/internal/storage/migration/constraints.go@@ -116,6 +116,13 @@ func runConstraints(db *gorm.DB) {EXCEPTION WHEN others THEN NULL;END $$`)+ // Field filters on form submissions are containment queries+ // (data @> '{"department":"sales"}'), which jsonb_path_ops serves.+ db.Exec(`DO $$ BEGIN+ CREATE INDEX IF NOT EXISTS idx_messages_data ON messages USING GIN (data jsonb_path_ops) WHERE data IS NOT NULL;+ EXCEPTION WHEN others THEN NULL;+ END $$`)+// One thread reply per inbound email, so a retried parse task cannot attach// the same answer twice. Its own block: a failure must not skip the others.db.Exec(`DO $$ BEGINdiff --git a/internal/storage/repositories/message_repo.go b/internal/storage/repositories/message_repo.goindex d06bc8f..9c0e5b6 100644--- a/internal/storage/repositories/message_repo.go+++ b/internal/storage/repositories/message_repo.go@@ -20,6 +20,7 @@package repositoriesimport (+ "encoding/json""strings""time"@@ -37,6 +38,80 @@ type MessageFilterQuery struct {Query stringFrom *time.TimeTo *time.Time++ // SubmissionsOnly leaves out quarantined and rejected messages unless+ // Status asks for one: spam is not a response.+ SubmissionsOnly bool+ // DataEquals matches typed answers by containment (data @> ...), so it is+ // served by the GIN index. A multiselect value is a one-element array.+ DataEquals map[string]any+ // DataRanges bound answers from below or above. Keys are checked against+ // the form schema by the caller and always bound as parameters.+ DataRanges []DataRange+}++// DataRange is one bound on a typed answer. Numeric compares numbers and+// skips answers that are not numbers; otherwise the text is compared, which+// orders YYYY-MM-DD dates and HH:MM times correctly.+type DataRange struct {+ Key string+ Op string // gte | lte+ Value any+ Numeric bool+}++// applyMessageFilter narrows q to the messages f selects.+func applyMessageFilter(q *gorm.DB, scope ResourceScope, f MessageFilterQuery) *gorm.DB {+ q = ApplyWorkspaceScope(q, scope)+ if f.FormID > 0 {+ q = q.Where("form_id = ?", f.FormID)+ }+ switch {+ case f.Status != "":+ q = q.Where("status = ?", f.Status)+ case f.SubmissionsOnly:+ q = q.Where("status IN ?", []models.MessageStatus{models.MessageStatusReceived, models.MessageStatusFlagged})+ default:+ q = q.Where("status <> ?", models.MessageStatusRejected)+ }+ if f.State != "" {+ q = q.Where("state = ?", f.State)+ }+ if f.Assigned != nil {+ q = q.Where("assigned_to_id = ?", *f.Assigned)+ }+ if f.Unread {+ q = q.Where("read_at IS NULL")+ }+ if f.Query != "" {+ like := "%" + strings.ToLower(f.Query) + "%"+ q = q.Where(+ "LOWER(subject) LIKE ? OR LOWER(body) LIKE ? OR LOWER(sender_email) LIKE ? OR LOWER(sender_name) LIKE ? OR sender_phone LIKE ? OR LOWER(COALESCE(data::text, '')) LIKE ?",+ like, like, like, like, like, like)+ }+ if f.From != nil {+ q = q.Where("created_at >= ?", *f.From)+ }+ if f.To != nil {+ q = q.Where("created_at <= ?", *f.To)+ }+ if len(f.DataEquals) > 0 {+ if raw, err := json.Marshal(f.DataEquals); err == nil {+ q = q.Where("data @> ?::jsonb", string(raw))+ }+ }+ for _, r := range f.DataRanges {+ op := ">="+ if r.Op == "lte" {+ op = "<="+ }+ if r.Numeric {+ q = q.Where("(CASE WHEN jsonb_typeof(data -> ?) = 'number' THEN (data ->> ?)::numeric END) "+op+" ?", r.Key, r.Key, r.Value)+ } else {+ q = q.Where("(data ->> ?) "+op+" ?", r.Key, r.Value)+ }+ }+ return q}type MessageRepository struct {@@ -145,39 +220,7 @@ func (r *MessageRepository) FindByScopeFiltered(scope ResourceScope, f MessageFivar items []models.Messagevar total int64- apply := func(q *gorm.DB) *gorm.DB {- q = ApplyWorkspaceScope(q, scope)- if f.FormID > 0 {- q = q.Where("form_id = ?", f.FormID)- }- if f.Status != "" {- q = q.Where("status = ?", f.Status)- } else {- q = q.Where("status <> ?", models.MessageStatusRejected)- }- if f.State != "" {- q = q.Where("state = ?", f.State)- }- if f.Assigned != nil {- q = q.Where("assigned_to_id = ?", *f.Assigned)- }- if f.Unread {- q = q.Where("read_at IS NULL")- }- if f.Query != "" {- like := "%" + strings.ToLower(f.Query) + "%"- q = q.Where(- "LOWER(subject) LIKE ? OR LOWER(body) LIKE ? OR LOWER(sender_email) LIKE ? OR LOWER(sender_name) LIKE ? OR sender_phone LIKE ?",- like, like, like, like, like)- }- if f.From != nil {- q = q.Where("created_at >= ?", *f.From)- }- if f.To != nil {- q = q.Where("created_at <= ?", *f.To)- }- return q- }+ apply := func(q *gorm.DB) *gorm.DB { return applyMessageFilter(q, scope, f) }apply(r.db.Model(&models.Message{})).Count(&total)@@ -192,6 +235,49 @@ func (r *MessageRepository) FindByScopeFiltered(scope ResourceScope, f MessageFireturn items, total, nil}+// EachMessage walks the messages f selects, newest first, handing them to fn+// in batches. It pages by id rather than offset, so submissions arriving+// during an export neither repeat nor shift rows. It stops after max messages+// (0 means no limit) and reports whether it stopped early.+func (r *MessageRepository) EachMessage(scope ResourceScope, f MessageFilterQuery, batch, max int, fn func([]models.Message) error) (bool, error) {+ if batch <= 0 {+ batch = 500+ }+ var lastID uint+ seen := 0+ for {+ size := batch+ if max > 0 && max-seen < size {+ size = max - seen+ }+ q := applyMessageFilter(r.db.Model(&models.Message{}), scope, f)+ if lastID > 0 {+ q = q.Where("id < ?", lastID)+ }+ var items []models.Message+ if err := q.Order("id DESC").Limit(size + 1).Find(&items).Error; err != nil {+ return false, err+ }+ more := len(items) > size+ if more {+ items = items[:size]+ }+ if len(items) > 0 {+ if err := fn(items); err != nil {+ return false, err+ }+ seen += len(items)+ lastID = items[len(items)-1].ID+ }+ if !more {+ return false, nil+ }+ if max > 0 && seen >= max {+ return true, nil+ }+ }+}+func (r *MessageRepository) FindRecentDuplicate(formID uint, hash string, since time.Time) (*models.Message, error) {var m models.Messageerr := r.db.Where("form_id = ? AND dedup_hash = ? AND created_at >= ?", formID, hash, since).diff --git a/web/src/api/messages.ts b/web/src/api/messages.tsindex 68e27ad..1f0a366 100644--- a/web/src/api/messages.ts+++ b/web/src/api/messages.ts@@ -10,6 +10,8 @@ import type {MessageFilterRule,MessageReply,MessageStats,+ SubmissionQuery,+ SubmissionSummary,} from './types'const WORKSPACE_KEY = 'posta_workspace_id'@@ -188,3 +190,40 @@ export const messageFiltersApi = {return api.post<ApiResponse<FilterTestResult>>('/workspaces/current/message-filters/test', payload)},}++// Submission filters become flat query parameters: field.<key>=v for+// equality, field.<key>[gte]=n and field.<key>[lte]=n for ranges.+function submissionParams(formId: number, query: SubmissionQuery): Record<string, string | number> {+ const params: Record<string, string | number> = { form_id: formId }+ for (const k of ['page', 'size', 'status', 'q', 'after', 'before'] as const) {+ const v = query[k]+ if (v !== undefined && v !== '') params[k] = v+ }+ for (const f of query.filters || []) {+ params[f.op === 'eq' ? `field.${f.key}` : `field.${f.key}[${f.op}]`] = f.value+ }+ return params+}++export const formSubmissionsApi = {+ list(formId: number, query: SubmissionQuery = {}) {+ return api.get<PaginatedResponse<Message>>('/workspaces/current/form-submissions', {+ params: submissionParams(formId, { page: 0, size: 25, ...query }),+ })+ },+ summary(formId: number, query: SubmissionQuery = {}) {+ return api.get<ApiResponse<SubmissionSummary>>('/workspaces/current/form-submissions/summary', {+ params: submissionParams(formId, query),+ })+ },+ // A browser download cannot send the workspace header, so the workspace+ // travels as a query parameter (WorkspaceFromQueryOrHeader).+ exportUrl(formId: number, format: 'csv' | 'json', query: SubmissionQuery = {}) {+ const { page: _page, size: _size, ...rest } = query+ const params = new URLSearchParams()+ for (const [k, v] of Object.entries(submissionParams(formId, rest))) params.set(k, String(v))+ params.set('format', format)+ const ws = workspaceParam()+ return `/api/v1/workspaces/current/form-submissions/export?${params.toString()}${ws ? '&' + ws : ''}`+ },+}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex a3fbf7c..ad88443 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -1370,6 +1370,9 @@ export interface Message {created_at: stringupdated_at?: string | nullfields?: MessageField[]+ /** Typed answers, for forms with questions. */+ data?: Record<string, unknown> | null+ schema_version?: numberattachments?: InboundAttachmentMeta[]form?: Form | nullassigned_to?: { id: number; name: string; email: string } | null@@ -1409,3 +1412,46 @@ export interface FormSnippet {widget: stringshare_url: string}++export interface SubmissionOptionCount {+ value: string+ label: string+ count: number+}++export interface SubmissionFieldSummary {+ key: string+ label: string+ type: FormFieldType+ pii?: boolean+ answered: number+ options?: SubmissionOptionCount[]+ mean?: number+ min?: number+ max?: number+ samples?: string[]+ samples_hidden?: boolean+}++export interface SubmissionSummary {+ total: number+ truncated: boolean+ fields: SubmissionFieldSummary[]+}++/** One answer filter: equality, or a bound on number, scale, rating, date and time questions. */+export interface SubmissionFieldFilter {+ key: string+ op: 'eq' | 'gte' | 'lte'+ value: string+}++export interface SubmissionQuery {+ page?: number+ size?: number+ status?: string+ q?: string+ after?: string+ before?: string+ filters?: SubmissionFieldFilter[]+}diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vueindex c8c3319..a440cfd 100644--- a/web/src/views/forms/FormDetail.vue+++ b/web/src/views/forms/FormDetail.vue@@ -6,6 +6,7 @@ import { useNotificationStore } from "../../stores/notification";import { apiMessage } from "../../composables/apiError";import type { Form, FormSnippet } from "../../api/types";import FormFields from "./FormFields.vue";+import FormResponses from "./FormResponses.vue";const route = useRoute();const router = useRouter();@@ -17,7 +18,17 @@ const saving = ref(false);const form = ref<Form | null>(null);const snippet = ref<FormSnippet | null>(null);const loadFailed = ref(false);-const tab = ref<"questions" | "setup" | "responses" | "spam" | "notifications" | "embed">("questions");+const TABS = [+ { key: "questions", label: "Questions" },+ { key: "responses", label: "Responses" },+ { key: "setup", label: "Setup" },+ { key: "settings", label: "Response settings" },+ { key: "spam", label: "Spam" },+ { key: "notifications", label: "Notifications" },+ { key: "embed", label: "Share & embed" },+] as const;+type Tab = (typeof TABS)[number]["key"];+const tab = ref<Tab>("questions");const originsText = ref("");// close_at is edited in the browser's local time and stored as UTC.@@ -243,18 +254,20 @@ onMounted(load);<div class="card" style="margin-bottom: 20px"><div class="card-body" style="display: flex; gap: 8px; flex-wrap: wrap"><button- v-for="t in (['questions', 'setup', 'responses', 'spam', 'notifications', 'embed'] as const)"- :key="t"+ v-for="t in TABS"+ :key="t.key"class="btn"- :class="tab === t ? 'btn-primary' : 'btn-secondary'"- @click="tab = t"+ :class="tab === t.key ? 'btn-primary' : 'btn-secondary'"+ @click="tab = t.key">- {{ t }}+ {{ t.label }}</button></div></div><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" /><div v-show="tab === 'setup'" class="card" style="margin-bottom: 20px"><div class="card-header"><h2>Setup</h2></div>@@ -365,7 +378,7 @@ onMounted(load);</div></div>- <div v-show="tab === 'responses'" class="card" style="margin-bottom: 20px">+ <div v-show="tab === 'settings'" class="card" style="margin-bottom: 20px"><div class="card-header"><h2>Responses</h2></div><div class="card-body"><div class="form-group">@@ -583,8 +596,8 @@ onMounted(load);</div></div>- <!-- The Questions tab has its own save bar; this one saves the other tabs. -->- <div v-show="tab !== 'questions'" class="card">+ <!-- 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 class="card-body"><button class="btn btn-primary" :disabled="saving" @click="save">{{ saving ? "Saving..." : "Save changes" }}diff --git a/web/src/views/forms/FormResponses.vue b/web/src/views/forms/FormResponses.vuenew file mode 100644index 0000000..3c6123e--- /dev/null+++ b/web/src/views/forms/FormResponses.vue@@ -0,0 +1,709 @@+<script setup lang="ts">+import { computed, onMounted, ref, watch } from "vue";+import { formSubmissionsApi } from "../../api/messages";+import { apiMessage } from "../../composables/apiError";+import { useNotificationStore } from "../../stores/notification";+import Pagination from "../../components/Pagination.vue";+import type {+ Form,+ FormField,+ Message,+ Pageable,+ SubmissionFieldFilter,+ SubmissionFieldSummary,+ SubmissionQuery,+ SubmissionSummary,+} from "../../api/types";++// A form's responses: a per-question summary and a table, over one set of+// filters, with CSV and JSON export of exactly what is shown.++const props = defineProps<{ form: Form }>();+const notify = useNotificationStore();++const view = ref<"summary" | "table">("summary");+const loading = ref(false);+const summary = ref<SubmissionSummary | null>(null);+const rows = ref<Message[]>([]);+const pageable = ref<Pageable | null>(null);+const page = ref(0);++const status = ref("");+const search = ref("");+const after = ref("");+const before = ref("");+const fieldFilters = ref<SubmissionFieldFilter[]>([]);++// 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 hasSchema = computed(() => (props.form.fields || []).length > 0);+const byKey = computed(() => {+ const out: Record<string, FormField> = {};+ (props.form.fields || []).forEach((f) => (out[f.key] = f));+ return out;+});++const RANGE_TYPES = ["number", "scale", "rating", "date", "time"];++function query(): SubmissionQuery {+ return {+ status: status.value,+ q: search.value.trim(),+ // Dates are picked in local time; the day bounds are inclusive.+ after: after.value ? new Date(`${after.value}T00:00:00`).toISOString() : "",+ before: before.value ? new Date(`${before.value}T23:59:59`).toISOString() : "",+ filters: fieldFilters.value.filter((f) => f.key && f.value !== ""),+ };+}++async function load() {+ loading.value = true;+ try {+ const q = query();+ const [sumRes, listRes] = await Promise.all([+ formSubmissionsApi.summary(props.form.id, q),+ formSubmissionsApi.list(props.form.id, { ...q, page: page.value, size: 25 }),+ ]);+ summary.value = sumRes.data.data;+ rows.value = listRes.data.data;+ pageable.value = listRes.data.pageable;+ } catch (e: unknown) {+ notify.error(apiMessage(e, "Failed to load responses"));+ } finally {+ loading.value = false;+ }+}++let searchTimer: ReturnType<typeof setTimeout> | undefined;+watch(search, () => {+ clearTimeout(searchTimer);+ searchTimer = setTimeout(reload, 300);+});+watch([status, after, before, fieldFilters], reload, { deep: true });++function reload() {+ page.value = 0;+ load();+}++function goPage(p: number) {+ page.value = p;+ load();+}++// ─── Field filters ────────────────────────────────────────────────────────++function addFilter() {+ const first = activeQuestions.value[0];+ if (!first) return;+ fieldFilters.value.push({ key: first.key, op: "eq", value: "" });+}++function filterField(f: SubmissionFieldFilter) {+ return byKey.value[f.key];+}++function onFilterKey(f: SubmissionFieldFilter) {+ f.value = "";+ if (!RANGE_TYPES.includes(filterField(f)?.type || "")) f.op = "eq";+}++function inputType(f: SubmissionFieldFilter): string {+ const t = filterField(f)?.type;+ if (t === "number" || t === "scale" || t === "rating") return "number";+ if (t === "date" || t === "time") return t;+ return "text";+}++function clearFilters() {+ status.value = "";+ search.value = "";+ after.value = "";+ before.value = "";+ fieldFilters.value = [];+}++const filtered = computed(+ () => !!(status.value || search.value.trim() || after.value || before.value || fieldFilters.value.some((f) => f.value !== "")),+);++function exportUrl(format: "csv" | "json") {+ return formSubmissionsApi.exportUrl(props.form.id, format, query());+}++// ─── Display ──────────────────────────────────────────────────────────────++function labelOf(field: FormField | undefined, value: unknown): string {+ if (value === null || value === undefined) return "";+ if (typeof value === "boolean") return value ? "Yes" : "No";+ if (Array.isArray(value)) return value.map((v) => labelOf(field, v)).join(", ");+ const s = String(value);+ return field?.options?.find((o) => o.value === s)?.label || s;+}++function answer(m: Message, key: string): string {+ if (m.data && key in m.data) return labelOf(byKey.value[key], m.data[key]);+ // Submissions from before the form had questions keep only their raw fields.+ return m.fields?.find((f) => f.key === key)?.value || "";+}++function when(iso: string) {+ return new Date(iso).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });+}++function pct(n: number, of: number) {+ return of ? Math.round((n / of) * 100) : 0;+}++function fmt(n?: number) {+ return n === undefined ? "–" : Number.isInteger(n) ? String(n) : n.toFixed(1);+}++function isChoice(s: SubmissionFieldSummary) {+ return s.type === "select" || s.type === "multiselect" || s.type === "checkbox";+}++function isHistogram(s: SubmissionFieldSummary) {+ return s.type === "scale" || s.type === "rating";+}++function maxCount(s: SubmissionFieldSummary) {+ return Math.max(1, ...(s.options || []).map((o) => o.count));+}++function scaleTop(s: SubmissionFieldSummary) {+ const opts = s.options || [];+ return opts.length ? opts[opts.length - 1].value : "";+}++onMounted(load);+</script>++<template>+ <div>+ <!-- Filters: one row above the views, applied to summary, table and export alike. -->+ <div class="card" style="margin-bottom: 16px">+ <div class="card-body">+ <div class="rf-row">+ <div class="rf-views" role="tablist">+ <button+ v-for="v in (['summary', 'table'] as const)"+ :key="v"+ class="btn btn-sm"+ :class="view === v ? 'btn-primary' : 'btn-secondary'"+ role="tab"+ :aria-selected="view === v"+ @click="view = v"+ >+ {{ v === "summary" ? "Summary" : "Table" }}+ </button>+ </div>+ <input v-model="search" class="form-input rf-search" placeholder="Search answers" />+ <input v-model="after" type="date" class="form-input rf-date" aria-label="From" />+ <span class="muted">–</span>+ <input v-model="before" type="date" class="form-input rf-date" aria-label="To" />+ <select v-model="status" class="form-select rf-status" aria-label="Status">+ <option value="">Responses</option>+ <option value="flagged">Flagged only</option>+ <option value="quarantined">Quarantined (spam)</option>+ </select>+ <div class="rf-export">+ <a class="btn btn-secondary btn-sm" :href="exportUrl('csv')" download>Download CSV</a>+ <a class="btn btn-ghost btn-sm" :href="exportUrl('json')" download>JSON</a>+ </div>+ </div>++ <div v-if="hasSchema" class="rf-fields">+ <div v-for="(f, i) in fieldFilters" :key="i" class="rf-field">+ <select v-model="f.key" class="form-select" aria-label="Question" @change="onFilterKey(f)">+ <option v-for="q in questions" :key="q.key" :value="q.key">+ {{ q.label || q.key }}{{ q.archived ? " (archived)" : "" }}+ </option>+ </select>+ <select v-if="RANGE_TYPES.includes(filterField(f)?.type || '')" v-model="f.op" class="form-select rf-op" aria-label="Comparison">+ <option value="eq">is</option>+ <option value="gte">at least</option>+ <option value="lte">at most</option>+ </select>+ <span v-else class="muted rf-is">is</span>+ <select+ v-if="filterField(f)?.options?.length"+ v-model="f.value"+ class="form-select"+ aria-label="Value"+ >+ <option value="">Any</option>+ <option v-for="o in filterField(f)!.options" :key="o.value" :value="o.value">{{ o.label || o.value }}</option>+ </select>+ <select v-else-if="filterField(f)?.type === 'checkbox'" v-model="f.value" class="form-select" aria-label="Value">+ <option value="">Any</option>+ <option value="true">Checked</option>+ <option value="false">Not checked</option>+ </select>+ <input+ v-else+ v-model.lazy="f.value"+ class="form-input"+ aria-label="Value"+ :type="inputType(f)"+ />+ <button class="btn btn-ghost btn-xs" aria-label="Remove filter" @click="fieldFilters.splice(i, 1)">×</button>+ </div>+ <button class="btn btn-ghost btn-sm" :disabled="!activeQuestions.length" @click="addFilter">+ Filter by answer</button>+ <button v-if="filtered" class="btn btn-ghost btn-sm" @click="clearFilters">Clear filters</button>+ </div>+ <small class="muted">+ Downloads include exactly what is filtered here. Questions marked as personal data are exported only for workspace admins.+ </small>+ </div>+ </div>++ <div v-if="loading && !summary" class="loading-page"><div class="spinner"></div></div>++ <div v-else-if="summary && summary.total === 0" class="card">+ <div class="empty-state">+ <h3>{{ filtered ? "No responses match these filters" : "No responses yet" }}</h3>+ <p v-if="!filtered">Share the form's link or embed it on your site from the Share & embed tab.</p>+ <button v-else class="btn btn-secondary" @click="clearFilters">Clear filters</button>+ </div>+ </div>++ <!-- ─── Summary ─── -->+ <template v-else-if="summary && view === 'summary'">+ <div class="rs-head">+ <div class="rs-total">{{ summary.total.toLocaleString() }}</div>+ <div class="muted">{{ summary.total === 1 ? "response" : "responses" }}{{ filtered ? " match" : "" }}</div>+ </div>+ <p v-if="summary.truncated" class="muted" style="font-size: 13px">+ Summarized from the newest {{ summary.total.toLocaleString() }} responses. Narrow the dates to cover older ones.+ </p>+ <div v-if="!hasSchema" class="card">+ <div class="card-body muted">+ This form has no questions, so there is nothing to chart. Add questions on the Questions tab, or use the Table view.+ </div>+ </div>++ <div v-for="s in summary.fields" :key="s.key" class="card rs-card">+ <div class="card-body">+ <div class="rs-title">{{ s.label || s.key }}</div>+ <div class="rs-sub">+ {{ s.answered.toLocaleString() }} {{ s.answered === 1 ? "response" : "responses" }}+ <span v-if="s.answered < summary.total"> · {{ summary.total - s.answered }} skipped</span>+ </div>++ <!-- Choices: horizontal bars, labelled with count and share. -->+ <div v-if="isChoice(s) && s.options" class="rs-bars">+ <div+ v-for="o in s.options"+ :key="o.value"+ class="rs-bar-row"+ :title="`${o.label}: ${o.count} (${pct(o.count, s.answered)}%)`"+ >+ <div class="rs-bar-label">{{ o.label }}</div>+ <div class="rs-bar-track">+ <div class="rs-bar" :style="{ width: `${(o.count / maxCount(s)) * 100}%` }"></div>+ </div>+ <div class="rs-bar-value">+ {{ o.count }} <span class="muted">({{ pct(o.count, s.answered) }}%)</span>+ </div>+ </div>+ <p v-if="s.type === 'multiselect'" class="rs-note">Respondents could pick more than one, so shares add up past 100%.</p>+ </div>++ <!-- Scale and rating: a histogram anchored to the baseline, plus the mean. -->+ <div v-else-if="isHistogram(s) && s.options" class="rs-hist-wrap">+ <div class="rs-mean">+ <span class="rs-mean-value">{{ fmt(s.mean) }}</span>+ <span class="muted"> average{{ s.type === "rating" ? ` of ${scaleTop(s)} stars` : ` on ${s.options[0].value}–${scaleTop(s)}` }}</span>+ </div>+ <div class="rs-hist" role="img" :aria-label="s.options.map((o) => `${o.label}: ${o.count}`).join(', ')">+ <div+ v-for="o in s.options"+ :key="o.value"+ class="rs-col"+ :title="`${s.type === 'rating' ? o.label + ' ★' : o.label}: ${o.count} (${pct(o.count, s.answered)}%)`"+ >+ <div class="rs-col-count">{{ o.count || "" }}</div>+ <div class="rs-col-plot">+ <div class="rs-col-bar" :style="{ height: `${(o.count / maxCount(s)) * 100}%` }"></div>+ </div>+ <div class="rs-col-label">{{ o.label }}{{ s.type === "rating" ? "★" : "" }}</div>+ </div>+ </div>+ </div>++ <!-- Numbers: the figures themselves, no chart. -->+ <div v-else-if="s.type === 'number'" class="rs-stats">+ <div><span class="rs-stat">{{ fmt(s.mean) }}</span><span class="muted">average</span></div>+ <div><span class="rs-stat">{{ fmt(s.min) }}</span><span class="muted">lowest</span></div>+ <div><span class="rs-stat">{{ fmt(s.max) }}</span><span class="muted">highest</span></div>+ </div>++ <!-- Text: the latest answers. -->+ <template v-else>+ <p v-if="s.samples_hidden" class="rs-note">+ Personal data: answers are shown to workspace admins only. Open a response to see it.+ </p>+ <ul v-else-if="s.samples?.length" class="rs-samples">+ <li v-for="(a, i) in s.samples" :key="i">{{ a }}</li>+ </ul>+ <p v-if="(s.samples?.length || 0) < s.answered && !s.samples_hidden" class="rs-note">+ Latest {{ s.samples?.length }} of {{ s.answered }}. See all in the Table view.+ </p>+ </template>+ </div>+ </div>+ </template>++ <!-- ─── Table ─── -->+ <div v-else-if="summary && view === 'table'" class="card rt-card">+ <div class="rt-scroll">+ <table class="rt">+ <thead>+ <tr>+ <th>Submitted</th>+ <template v-if="hasSchema">+ <th v-for="q in activeQuestions" :key="q.key">{{ q.label || q.key }}</th>+ </template>+ <template v-else>+ <th>Email</th>+ <th>Name</th>+ <th>Subject</th>+ <th>Message</th>+ </template>+ </tr>+ </thead>+ <tbody>+ <tr v-for="m in rows" :key="m.uuid">+ <td class="rt-when">+ <router-link :to="`/messages/${m.uuid}`">{{ when(m.created_at) }}</router-link>+ <span v-if="m.status !== 'received'" class="badge badge-warning" style="margin-left: 6px">{{ m.status }}</span>+ </td>+ <template v-if="hasSchema">+ <td v-for="q in activeQuestions" :key="q.key" :class="{ 'rt-num': ['number', 'scale', 'rating'].includes(q.type) }">+ {{ answer(m, q.key) }}+ </td>+ </template>+ <template v-else>+ <td>{{ m.sender_email }}</td>+ <td>{{ m.sender_name }}</td>+ <td>{{ m.subject }}</td>+ <td class="rt-long">{{ m.body }}</td>+ </template>+ </tr>+ </tbody>+ </table>+ </div>+ <div v-if="pageable && pageable.total_pages > 1" class="card-body">+ <Pagination :pageable="pageable" @page="goPage" />+ </div>+ </div>+ </div>+</template>++<style scoped>+/* Single-series charts: one brand hue, validated against both surfaces+ (#9333EA on light, #A855F7 on dark). Text stays in text tokens. */+.rs-card,+.rt-scroll {+ --rs-mark: #9333ea;+}++:global([data-theme="dark"]) .rs-card {+ --rs-mark: #a855f7;+}++.rf-row {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++.rf-views {+ display: flex;+ gap: 4px;+ margin-right: 8px;+}++.rf-search {+ flex: 1 1 180px;+ min-width: 140px;+}++.rf-date {+ width: 150px;+}++.rf-status {+ width: 190px;+}++.rf-export {+ display: flex;+ gap: 4px;+ margin-left: auto;+}++.rf-fields {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px;+ margin: 12px 0 8px;+}++.rf-field {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 6px;+ border: 1px solid var(--border-primary);+ border-radius: 8px;+}++.rf-field .form-select,+.rf-field .form-input {+ width: auto;+ max-width: 200px;+ padding-top: 4px;+ padding-bottom: 4px;+}++.rf-op {+ width: 100px;+}++.rf-is {+ font-size: 13px;+}++.rs-head {+ display: flex;+ align-items: baseline;+ gap: 8px;+ margin: 4px 0 12px;+}++.rs-total {+ font-size: 32px;+ font-weight: 700;+ line-height: 1;+ color: var(--text-primary);+}++.rs-card {+ margin-bottom: 16px;+}++.rs-title {+ font-weight: 600;+ font-size: 15px;+ color: var(--text-primary);+}++.rs-sub {+ font-size: 12px;+ color: var(--text-muted);+ margin: 2px 0 14px;+}++.rs-bars {+ display: grid;+ gap: 6px;+}++.rs-bar-row {+ display: grid;+ grid-template-columns: minmax(80px, 200px) minmax(0, 1fr) 90px;+ align-items: center;+ gap: 10px;+ font-size: 13px;+ padding: 2px 0;+ border-radius: 4px;+}++.rs-bar-row:hover {+ background: var(--bg-hover, rgba(0, 0, 0, 0.03));+}++.rs-bar-label {+ color: var(--text-secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.rs-bar-track {+ height: 12px;+}++.rs-bar {+ height: 100%;+ min-width: 2px;+ background: var(--rs-mark);+ border-radius: 0 4px 4px 0;+}++.rs-bar-value {+ color: var(--text-primary);+ font-variant-numeric: tabular-nums;+}++.rs-hist-wrap {+ display: grid;+ gap: 10px;+}++.rs-mean-value {+ font-size: 24px;+ font-weight: 700;+ color: var(--text-primary);+}++.rs-hist {+ display: flex;+ align-items: flex-end;+ gap: 2px;+ max-width: 560px;+}++.rs-col {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ min-width: 24px;+ max-width: 64px;+ border-radius: 4px;+}++.rs-col:hover {+ background: var(--bg-hover, rgba(0, 0, 0, 0.03));+}++.rs-col-count {+ font-size: 12px;+ color: var(--text-secondary);+ height: 18px;+ font-variant-numeric: tabular-nums;+}++.rs-col-plot {+ width: 100%;+ height: 120px;+ display: flex;+ align-items: flex-end;+ justify-content: center;+ border-bottom: 1px solid var(--border-primary);+}++.rs-col-bar {+ width: 70%;+ min-height: 0;+ background: var(--rs-mark);+ border-radius: 4px 4px 0 0;+}++.rs-col-label {+ font-size: 12px;+ color: var(--text-muted);+ margin-top: 4px;+}++.rs-stats {+ display: flex;+ gap: 32px;+}++.rs-stats > div {+ display: flex;+ flex-direction: column;+}++.rs-stat {+ font-size: 22px;+ font-weight: 700;+ color: var(--text-primary);+ font-variant-numeric: tabular-nums;+}++.rs-samples {+ list-style: none;+ margin: 0;+ padding: 0;+ max-height: 260px;+ overflow: auto;+}++.rs-samples li {+ padding: 8px 10px;+ font-size: 13px;+ color: var(--text-primary);+ background: var(--bg-secondary);+ border-radius: 6px;+ margin-bottom: 4px;+ white-space: pre-wrap;+ word-break: break-word;+}++.rs-note {+ margin: 8px 0 0;+ font-size: 12px;+ color: var(--text-muted);+}++/* A wide table scrolls inside its card instead of widening the page:+ inline-size containment keeps the content from sizing the card. */+.rt-card {+ contain: inline-size;+}++.rt-scroll {+ overflow-x: auto;+}++.rt {+ width: 100%;+ border-collapse: collapse;+ font-size: 13px;+}++.rt th,+.rt td {+ padding: 10px 12px;+ text-align: left;+ border-bottom: 1px solid var(--border-primary);+ vertical-align: top;+ max-width: 280px;+}++.rt th {+ font-size: 12px;+ font-weight: 600;+ color: var(--text-muted);+ white-space: nowrap;+ position: sticky;+ top: 0;+ background: var(--bg-primary);+}++.rt td {+ color: var(--text-primary);+ overflow: hidden;+ text-overflow: ellipsis;+}++.rt-when {+ white-space: nowrap;+}++.rt-num {+ font-variant-numeric: tabular-nums;+}++.rt-long {+ white-space: nowrap;+}+</style>