Files
TradarrV2/backend/internal/api/reports_ticket14_postgres_test.go
Blomios 989996fbd6 feat(ai): add personal summary models and retire Q&A
Add an admin-managed provider model catalog with per-user summary selection, migration backfill, and generation snapshots. Retire report creation and messaging while preserving owner-scoped history.

Refs #15 #16

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-21 20:45:21 +01:00

124 lines
6.7 KiB
Go

package api_test
import (
"bytes"
"database/sql"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
)
const (
ticket14OwnerA = "00000000-0000-0000-0000-000000000241"
ticket14OwnerB = "00000000-0000-0000-0000-000000000242"
ticket14SummaryA = "00000000-0000-0000-0000-000000000251"
ticket14ReportA = "00000000-0000-0000-0000-000000000261"
ticket14ReportB = "00000000-0000-0000-0000-000000000262"
ticket14MessageA = "00000000-0000-0000-0000-000000000271"
ticket14MessageB = "00000000-0000-0000-0000-000000000272"
)
func TestReportWritesAreGoneWhileHistoricalReadsAndDeletesRemainOwnerScopedPostgres(t *testing.T) {
db := ticket14DB(t)
for _, q := range []string{
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
`INSERT INTO users(id,email) VALUES('` + ticket14OwnerA + `','a@example.test'),('` + ticket14OwnerB + `','b@example.test')`,
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID NOT NULL,content TEXT NOT NULL,ai_provider_id UUID,generated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`INSERT INTO summaries(id,user_id,content) VALUES('` + ticket14SummaryA + `','` + ticket14OwnerA + `','Historical summary excerpt.')`,
`CREATE TABLE reports(id UUID PRIMARY KEY DEFAULT gen_random_uuid(),user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,summary_id UUID REFERENCES summaries(id) ON DELETE SET NULL,context_excerpt TEXT NOT NULL,question TEXT NOT NULL,answer TEXT NOT NULL DEFAULT '',status VARCHAR(20) NOT NULL DEFAULT 'done',error_msg TEXT NOT NULL DEFAULT '',created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE report_messages(id UUID PRIMARY KEY DEFAULT gen_random_uuid(),report_id UUID NOT NULL REFERENCES reports(id) ON DELETE CASCADE,role VARCHAR(10) NOT NULL,content TEXT NOT NULL,status VARCHAR(10) NOT NULL DEFAULT 'done',created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`INSERT INTO reports(id,user_id,summary_id,context_excerpt,question,answer,status) VALUES('` + ticket14ReportA + `','` + ticket14OwnerA + `','` + ticket14SummaryA + `','Historical summary excerpt.','Old question','Old answer','done'),('` + ticket14ReportB + `','` + ticket14OwnerB + `',NULL,'B private excerpt','B question','B answer','done')`,
`INSERT INTO report_messages(id,report_id,role,content,status) VALUES('` + ticket14MessageA + `','` + ticket14ReportA + `','assistant','Historical message','done'),('` + ticket14MessageB + `','` + ticket14ReportB + `','assistant','B private message','done')`,
} {
if _, err := db.Exec(q); err != nil {
t.Fatal(err)
}
}
const secret = "ticket14-reports-secret"
ownerA, err := auth.GenerateToken(ticket14OwnerA, "a@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
ownerB, err := auth.GenerateToken(ticket14OwnerB, "b@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
invoke := func(method, path, token, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
res := httptest.NewRecorder()
router.ServeHTTP(res, req)
return res
}
before := ticket14ReportsSnapshot(t, db)
for _, tc := range []struct{ name, path, body string }{
{"create report", "/api/reports", `{"summary_id":"` + ticket14SummaryA + `","excerpts":["Historical summary excerpt."],"question":"New question"}`},
{"create report message", "/api/reports/" + ticket14ReportA + "/messages", `{"content":"New message"}`},
} {
res := invoke(http.MethodPost, tc.path, ownerA, tc.body)
if res.Code != http.StatusGone {
t.Errorf("POST %s status=%d body=%s, want 410", tc.path, res.Code, res.Body.String())
}
}
if after := ticket14ReportsSnapshot(t, db); after != before {
t.Errorf("410 report endpoints wrote historical or new data\nbefore: %s\nafter: %s", before, after)
}
list := invoke(http.MethodGet, "/api/reports", ownerA, "")
if list.Code != http.StatusOK {
t.Fatalf("GET owned historical reports status=%d body=%s", list.Code, list.Body.String())
}
if !strings.Contains(list.Body.String(), ticket14ReportA) || strings.Contains(list.Body.String(), ticket14ReportB) {
t.Errorf("GET /reports not owner scoped: %s", list.Body.String())
}
messages := invoke(http.MethodGet, "/api/reports/"+ticket14ReportA+"/messages", ownerA, "")
if messages.Code != http.StatusOK || !strings.Contains(messages.Body.String(), ticket14MessageA) {
t.Errorf("GET owned historical messages status=%d body=%s", messages.Code, messages.Body.String())
}
foreign := invoke(http.MethodGet, "/api/reports/"+ticket14ReportA+"/messages", ownerB, "")
if foreign.Code != http.StatusNotFound {
t.Errorf("GET foreign historical messages status=%d, want 404", foreign.Code)
}
deleteForeign := invoke(http.MethodDelete, "/api/reports/"+ticket14ReportA, ownerB, "")
if deleteForeign.Code != http.StatusNotFound {
t.Errorf("DELETE foreign historical report status=%d, want 404", deleteForeign.Code)
}
var stillOwnerA, stillOwnerB int
if err := db.QueryRow(`SELECT count(*) FILTER(WHERE id=$1),count(*) FILTER(WHERE id=$2) FROM reports`, ticket14ReportA, ticket14ReportB).Scan(&stillOwnerA, &stillOwnerB); err != nil {
t.Fatal(err)
}
if stillOwnerA != 1 || stillOwnerB != 1 {
t.Fatalf("foreign delete changed history: ownerA=%d ownerB=%d", stillOwnerA, stillOwnerB)
}
deleteOwned := invoke(http.MethodDelete, "/api/reports/"+ticket14ReportA, ownerA, "")
if deleteOwned.Code != http.StatusNoContent {
t.Errorf("DELETE owned historical report status=%d, want 204", deleteOwned.Code)
}
if err := db.QueryRow(`SELECT count(*) FROM reports WHERE id=$1`, ticket14ReportA).Scan(&stillOwnerA); err != nil || stillOwnerA != 0 {
t.Errorf("owned historical report remains count=%d err=%v", stillOwnerA, err)
}
if err := db.QueryRow(`SELECT count(*) FROM reports WHERE id=$1`, ticket14ReportB).Scan(&stillOwnerB); err != nil || stillOwnerB != 1 {
t.Errorf("other user's report changed count=%d err=%v", stillOwnerB, err)
}
}
func ticket14ReportsSnapshot(t *testing.T, db *sql.DB) string {
t.Helper()
var value string
err := db.QueryRow(`SELECT jsonb_build_object('reports',(SELECT jsonb_agg(to_jsonb(r) ORDER BY id) FROM reports r),'messages',(SELECT jsonb_agg(to_jsonb(m) ORDER BY id) FROM report_messages m))::text`).Scan(&value)
if err != nil {
t.Fatal(err)
}
return value
}