From 6678fd263c64cec266347a57ad2376db900fe877 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:27:51 +0200 Subject: [PATCH] feat(store): Unterlagen merge into the document store One document view (decided 2026-10-20): the tenant's own documents that staff kept as Unterlagen become internal documents of the store (0023, same ids and product links); BreakPilot's deliveries stay without an area and are listed last in the store. The store lists published documents only, and serves a delivery's original like any other. The tenant's document list returns every document again, so Werkmeister keeps reading a product's own documents, including internal ones uploaded in the workspace. Marking a document as the tenant's own moves it into the internal area and back. Co-Authored-By: Claude Opus 5.5 --- internal/server/document_store.go | 3 +- internal/server/document_store_db_test.go | 25 +++++++-- internal/server/document_store_test.go | 22 +++++--- internal/server/documents.go | 4 ++ internal/server/projects_test.go | 9 +++- internal/store/memory_document_store.go | 8 +-- internal/store/memory_documents.go | 8 ++- internal/store/postgres_document_store.go | 4 +- internal/store/postgres_documents.go | 12 +++-- internal/store/store.go | 7 +-- internal/store/types.go | 3 +- .../0023_store_takes_own_documents.down.sql | 4 ++ .../0023_store_takes_own_documents.up.sql | 5 ++ migrations/migrations_test.go | 51 +++++++++++++++++++ openapi.yaml | 1 + 15 files changed, 139 insertions(+), 27 deletions(-) create mode 100644 migrations/0023_store_takes_own_documents.down.sql create mode 100644 migrations/0023_store_takes_own_documents.up.sql diff --git a/internal/server/document_store.go b/internal/server/document_store.go index c977de3..9f43775 100644 --- a/internal/server/document_store.go +++ b/internal/server/document_store.go @@ -114,7 +114,8 @@ func (s *Server) storeDocument(ctx context.Context, w http.ResponseWriter, r *ht return nil, false } d, err := s.Store.GetDocument(ctx, r.PathValue("doc")) - if err == nil && (d.TenantID != t.ID || d.Area == "") { + // Drafts (staff uploads before publishing) are not shown yet. + if err == nil && (d.TenantID != t.ID || d.Status != store.DocumentPublished) { err = store.ErrNotFound } if err != nil { diff --git a/internal/server/document_store_db_test.go b/internal/server/document_store_db_test.go index 6af311b..d71b92a 100644 --- a/internal/server/document_store_db_test.go +++ b/internal/server/document_store_db_test.go @@ -37,10 +37,13 @@ func TestDocumentStoreContract(t *testing.T) { if _, err := mk(ids[3], "Richtlinie", store.AreaInternal, "", ""); err != nil { t.Fatal(err) } - // Unterlagen (no area) stay apart. + // A BreakPilot delivery (no area) shows last; a draft not at all. if _, err := h.store.CreateDocument(ctx, store.Document{ID: ids[4], TenantID: tid, Title: "Report", ObjectKey: "k/r", Status: store.DocumentPublished}); err != nil { t.Fatal(err) } + if _, err := h.store.CreateDocument(ctx, store.Document{ID: "10000000-0000-0000-0000-000000000006", TenantID: tid, Title: "Entwurf", ObjectKey: "k/e", Status: store.DocumentDraft}); err != nil { + t.Fatal(err) + } for name, bad := range map[string]store.Document{ "legal without folder": {Area: store.AreaLegalWeb}, "folder outside legal": {Area: store.AreaInternal, LegalKind: "agb"}, @@ -62,11 +65,25 @@ func TestDocumentStoreContract(t *testing.T) { for _, d := range docs { order = append(order, d.Title) } - if strings.Join(order, ",") != "Impressum,Widerruf,Datenblatt,Richtlinie" { + if strings.Join(order, ",") != "Impressum,Widerruf,Datenblatt,Richtlinie,Report" { t.Errorf("order: %v", order) } - if u, _ := h.store.ListDocuments(ctx, tid, false); len(u) != 1 || u[0].Title != "Report" { - t.Errorf("Unterlagen: %+v", u) + // Every document, for Werkmeister and staff. + if u, _ := h.store.ListDocuments(ctx, tid, false); len(u) != 6 { + t.Errorf("all documents: %d", len(u)) + } + if u, _ := h.store.ListDocuments(ctx, tid, true); len(u) != 5 { + t.Errorf("published documents: %d", len(u)) + } + // Marking a delivery as the tenant's own moves it into the internal area, and back. + if d, err := h.store.SetDocumentOwn(ctx, ids[4], true); err != nil || d.Area != store.AreaInternal { + t.Errorf("own: %+v %v", d, err) + } + if d, err := h.store.SetDocumentOwn(ctx, ids[4], false); err != nil || d.Area != "" { + t.Errorf("not own: %+v %v", d, err) + } + if d, err := h.store.SetDocumentOwn(ctx, ids[0], false); err != nil || d.Area != store.AreaProductPublic { + t.Errorf("a public document keeps its area: %+v %v", d, err) } if d, err := h.store.GetDocumentByExternalID(ctx, tid, "wsdoc-b"); err != nil || d.ID != ids[1] { t.Errorf("by external id: %v %v", d, err) diff --git a/internal/server/document_store_test.go b/internal/server/document_store_test.go index dfabed6..d9c591c 100644 --- a/internal/server/document_store_test.go +++ b/internal/server/document_store_test.go @@ -123,7 +123,7 @@ func TestStoreUploadRules(t *testing.T) { t.Errorf("processing: internal sent %q, public %q", d3.ProcessingStatus, d4.ProcessingStatus) } - // The store lists them by area and folder; "Unterlagen" does not. + // The store lists them by area and folder; the tenant's document list (Werkmeister's) has them too. code, _, raw := f.call(t, "GET", "/v1/tenants/"+f.tenant.ID+"/store", "", nil) var list storeListResp _ = json.Unmarshal([]byte(raw), &list) @@ -131,8 +131,8 @@ func TestStoreUploadRules(t *testing.T) { t.Fatalf("store list: %d %s", code, raw) } docs, _ := f.s.Store.ListDocuments(ctx, f.tenant.ID, false) - if len(docs) != 0 { - t.Errorf("store documents appear under Unterlagen: %d", len(docs)) + if len(docs) != 4 { + t.Errorf("tenant documents: %d", len(docs)) } if ev := f.audit(t, "store.uploaded"); len(ev) != 4 || ev[0].Metadata["area"] == nil { t.Errorf("audit: %+v", ev) @@ -187,11 +187,19 @@ func TestStoreIsTenantScoped(t *testing.T) { t.Errorf("%s: %d", p, rr.Code) } } - // A BreakPilot delivery is not reachable through the store routes. + // A published BreakPilot delivery is served like any store document; a draft is not. ctx := context.Background() - _, _ = f.s.Store.CreateDocument(ctx, store.Document{ID: "11111111-1111-1111-1111-111111111111", TenantID: f.tenant.ID, Title: "Report", ObjectKey: "k", Status: store.DocumentPublished}) - if rr := f.raw(t, "GET", base+"/store/documents/11111111-1111-1111-1111-111111111111/original", "", nil, nil); rr.Code != 404 { - t.Errorf("Unterlagen via store: %d", rr.Code) + report := []byte("%PDF-1.7 synthetic report") + sum := sha256.Sum256(report) + _ = f.objects.Put(ctx, "k/report", bytes.NewReader(report), int64(len(report)), "application/pdf") + _, _ = f.s.Store.CreateDocument(ctx, store.Document{ID: "11111111-1111-1111-1111-111111111111", TenantID: f.tenant.ID, Title: "Report", Filename: "report.pdf", + ContentType: "application/pdf", SHA256: hex.EncodeToString(sum[:]), ObjectKey: "k/report", Status: store.DocumentPublished}) + _, _ = f.s.Store.CreateDocument(ctx, store.Document{ID: "22222222-2222-2222-2222-222222222222", TenantID: f.tenant.ID, Title: "Draft", ObjectKey: "k/draft", Status: store.DocumentDraft}) + if rr := f.raw(t, "GET", base+"/store/documents/11111111-1111-1111-1111-111111111111/original", "", nil, nil); rr.Code != 200 || rr.Body.String() != string(report) { + t.Errorf("delivery via store: %d", rr.Code) + } + if rr := f.raw(t, "GET", base+"/store/documents/22222222-2222-2222-2222-222222222222/original", "", nil, nil); rr.Code != 404 { + t.Errorf("draft via store: %d", rr.Code) } } diff --git a/internal/server/documents.go b/internal/server/documents.go index addb1d0..17c59f4 100644 --- a/internal/server/documents.go +++ b/internal/server/documents.go @@ -202,6 +202,10 @@ func (s *Server) adminUploadDocument(w http.ResponseWriter, r *http.Request) { } doc.Title, doc.Description = title, description doc.OwnDocument, doc.ProjectIDs = own, projectIDs + if own { + // The tenant's own document belongs to the store's internal area. + doc.Area = store.AreaInternal + } if sub, email, ok := s.staffActor(r); ok { doc.UploadedBy = firstNonEmpty(email, sub) } diff --git a/internal/server/projects_test.go b/internal/server/projects_test.go index f47ff37..f499044 100644 --- a/internal/server/projects_test.go +++ b/internal/server/projects_test.go @@ -152,9 +152,16 @@ func TestProjects_documents(t *testing.T) { t.Fatalf("patch: %d %s", resp.StatusCode, raw) } _ = json.Unmarshal(raw, &d) - if len(d.ProjectIDs) != 1 || d.ProjectIDs[0] != cra.ID || !d.OwnDocument { + if len(d.ProjectIDs) != 1 || d.ProjectIDs[0] != cra.ID || !d.OwnDocument || d.Area != store.AreaInternal { t.Fatalf("patched: %+v", d) } + // an own document uploaded by staff goes to the store's internal area + resp, raw = uploadWith(t, h, h.tenant.ID, [][2]string{{"own_document", "on"}, {"project_ids", vx.ID}}, "richtlinie.pdf") + var own store.Document + _ = json.Unmarshal(raw, &own) + if resp.StatusCode != 201 || own.Area != store.AreaInternal || !own.OwnDocument { + t.Fatalf("own upload: %d %s", resp.StatusCode, raw) + } if resp, raw := h.do("PATCH", "/v1/admin/documents/"+d.ID, map[string]any{"project_ids": []string{gp.ID}}); resp.StatusCode != 400 || !strings.Contains(string(raw), "invalid_projects") { t.Fatalf("foreign project on patch: %d %s", resp.StatusCode, raw) } diff --git a/internal/store/memory_document_store.go b/internal/store/memory_document_store.go index c454dec..68918d3 100644 --- a/internal/store/memory_document_store.go +++ b/internal/store/memory_document_store.go @@ -6,10 +6,10 @@ import ( "time" ) -// storeOrder sorts the tenant's own documents: by area, legal folder (in the -// folders' order), title, then id. +// storeOrder sorts the store: by area (BreakPilot's deliveries last), legal +// folder (in the folders' order), title, then id. func storeOrder(out []Document) { - area := map[string]int{AreaLegalWeb: 0, AreaProductPublic: 1, AreaInternal: 2} + area := map[string]int{AreaLegalWeb: 0, AreaProductPublic: 1, AreaInternal: 2, "": 3} kind := map[string]int{} for i, k := range LegalKinds { kind[k] = i @@ -34,7 +34,7 @@ func (m *Memory) ListStoreDocuments(_ context.Context, tenantID string) ([]Docum defer m.mu.RUnlock() out := []Document{} for _, d := range m.documents { - if d.TenantID == tenantID && d.Area != "" { + if d.TenantID == tenantID && d.Status == DocumentPublished { out = append(out, *d.copy()) } } diff --git a/internal/store/memory_documents.go b/internal/store/memory_documents.go index 1776f1d..cf7db36 100644 --- a/internal/store/memory_documents.go +++ b/internal/store/memory_documents.go @@ -86,6 +86,12 @@ func (m *Memory) SetDocumentOwn(_ context.Context, docID string, own bool) (*Doc return nil, ErrNotFound } d.OwnDocument, d.UpdatedAt = own, time.Now().UTC() + switch { + case own && d.Area == "": + d.Area = AreaInternal + case !own && d.Area == AreaInternal: + d.Area = "" + } return d.copy(), nil } @@ -104,7 +110,7 @@ func (m *Memory) ListDocuments(_ context.Context, tenantID string, publishedOnly defer m.mu.RUnlock() out := []Document{} for _, d := range m.documents { - if d.TenantID != tenantID || d.Area != "" || (publishedOnly && d.Status != DocumentPublished) { + if d.TenantID != tenantID || (publishedOnly && d.Status != DocumentPublished) { continue } out = append(out, *d.copy()) diff --git a/internal/store/postgres_document_store.go b/internal/store/postgres_document_store.go index c4af86f..df97351 100644 --- a/internal/store/postgres_document_store.go +++ b/internal/store/postgres_document_store.go @@ -9,8 +9,8 @@ import ( func (p *Postgres) ListStoreDocuments(ctx context.Context, tenantID string) ([]Document, error) { rows, err := p.pool.Query(ctx, documentSelect+` - WHERE tenant_id = $1::uuid AND area IS NOT NULL - ORDER BY array_position(ARRAY['legal_web','product_public','internal'], area), + WHERE tenant_id = $1::uuid AND status = 'published' + ORDER BY array_position(ARRAY['legal_web','product_public','internal'], area) NULLS LAST, array_position($2::text[], legal_kind) NULLS FIRST, title, id`, tenantID, LegalKinds) if isInvalidUUID(err) { return []Document{}, nil diff --git a/internal/store/postgres_documents.go b/internal/store/postgres_documents.go index 5e2fae1..1f60966 100644 --- a/internal/store/postgres_documents.go +++ b/internal/store/postgres_documents.go @@ -80,8 +80,9 @@ func (p *Postgres) GetDocument(ctx context.Context, id string) (*Document, error } func (p *Postgres) ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error) { - // BreakPilot's deliveries only; the tenant's own documents are the store's. - q := documentSelect + `WHERE tenant_id = $1::uuid AND area IS NULL` + // Every document of the tenant: BreakPilot's deliveries (area NULL) and the + // store's; Werkmeister reads a product's own documents from this list. + q := documentSelect + `WHERE tenant_id = $1::uuid` if publishedOnly { q += ` AND status = 'published'` } @@ -176,7 +177,12 @@ func (p *Postgres) SetDocumentProjects(ctx context.Context, docID string, projec } func (p *Postgres) SetDocumentOwn(ctx context.Context, docID string, own bool) (*Document, error) { - tag, err := p.pool.Exec(ctx, `UPDATE documents SET own_document = $2, updated_at = now() WHERE id = $1::uuid`, docID, own) + tag, err := p.pool.Exec(ctx, `UPDATE documents SET own_document = $2, + -- an own document lives in the store's internal area, a delivery outside it + area = CASE WHEN $2 AND area IS NULL THEN 'internal' + WHEN NOT $2 AND area = 'internal' THEN NULL ELSE area END, + updated_at = now() + WHERE id = $1::uuid`, docID, own) if isInvalidUUID(err) { return nil, ErrNotFound } diff --git a/internal/store/store.go b/internal/store/store.go index c9303b2..ded6ea2 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -176,9 +176,10 @@ type Store interface { SetDocumentProjects(ctx context.Context, docID string, projectIDs []string) (*Document, error) SetDocumentOwn(ctx context.Context, docID string, own bool) (*Document, error) - // Dokumentenablage (0022). ListDocuments returns only BreakPilot's - // deliveries (no area); ListStoreDocuments the tenant's own documents - // (with an area), by area, legal folder and title. GetDocumentByExternalID + // Dokumentenablage (0022, 0023). ListDocuments returns every document of + // the tenant; ListStoreDocuments the published ones as the store shows + // them: by area (BreakPilot's deliveries, no area, last), legal folder and + // title. GetDocumentByExternalID // finds a document by the Factory's id (ErrNotFound when none). ListStoreDocuments(ctx context.Context, tenantID string) ([]Document, error) GetDocumentByExternalID(ctx context.Context, tenantID, externalID string) (*Document, error) diff --git a/internal/store/types.go b/internal/store/types.go index 62d1617..6abe03e 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -292,7 +292,8 @@ type Document struct { // ProjectIDs are the tenant projects the document belongs to (0010). ProjectIDs []string `json:"project_ids"` // Dokumentenablage (0022): the tenant's own documents carry an area - // (empty = a BreakPilot delivery, "Unterlagen"), legal documents their + // (empty = a BreakPilot delivery, "Von BreakPilot"; own documents are + // internal, 0023), legal documents their // folder; ProcessingStatus says whether the prepared version is there. Area string `json:"area,omitempty"` LegalKind string `json:"legal_kind,omitempty"` diff --git a/migrations/0023_store_takes_own_documents.down.sql b/migrations/0023_store_takes_own_documents.down.sql new file mode 100644 index 0000000..019f2e4 --- /dev/null +++ b/migrations/0023_store_takes_own_documents.down.sql @@ -0,0 +1,4 @@ +-- Back to Unterlagen: internal documents not sent for preparation and not +-- imported (which is what an own document of Unterlagen was). +UPDATE documents SET area = NULL +WHERE area = 'internal' AND own_document AND processing_status = 'none' AND external_id = ''; diff --git a/migrations/0023_store_takes_own_documents.up.sql b/migrations/0023_store_takes_own_documents.up.sql new file mode 100644 index 0000000..3e62f71 --- /dev/null +++ b/migrations/0023_store_takes_own_documents.up.sql @@ -0,0 +1,5 @@ +-- One document view (decided 2026-10-20): "Unterlagen" merges into the +-- Dokumentenablage. The tenant's own documents that staff kept as Unterlagen +-- become internal documents of the store, with their ids and product links; +-- BreakPilot's deliveries stay area NULL and show as "Von BreakPilot". +UPDATE documents SET area = 'internal' WHERE area IS NULL AND own_document; diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 42882c7..c9ef465 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -431,3 +431,54 @@ func TestMigrate_0019AlignsTrialEntitlements(t *testing.T) { t.Errorf("audit rows: %d", audited) } } + +func TestMigrate_0023MovesOwnDocumentsIntoTheStore(t *testing.T) { + if testing.Short() { + t.Skip("skipping integration test under -short") + } + dsn, stop := startPostgres(t) + defer stop() + m := newMigrator(t, dsn) + if err := m.Migrate(22); err != nil { + t.Fatalf("up to 22: %v", err) + } + db, err := sql.Open("pgx", dsn) + if err != nil { + t.Fatal(err) + } + defer func() { _ = db.Close() }() + var tid string + if err := db.QueryRow(`INSERT INTO tenants (slug, name) VALUES ('muster', 'Muster Modellbau GmbH') RETURNING id`).Scan(&tid); err != nil { + t.Fatal(err) + } + doc := func(title string, own bool, area any) string { + var id string + if err := db.QueryRow(`INSERT INTO documents (tenant_id, title, filename, content_type, size_bytes, sha256, object_key, status, own_document, area) + VALUES ($1, $2, $2 || '.pdf', 'application/pdf', 1, 'x', 'k/' || $2, 'published', $3, $4) RETURNING id`, tid, title, own, area).Scan(&id); err != nil { + t.Fatal(err) + } + return id + } + own := doc("Datenblatt Lok 100", true, nil) // own document of Unterlagen: moves + delivery := doc("Prüfbericht", false, nil) // BreakPilot's delivery: stays + public := doc("Handbuch", true, "product_public") // already in the store: stays + areaOf := func(id string) string { + var a sql.NullString + if err := db.QueryRow(`SELECT area FROM documents WHERE id = $1`, id).Scan(&a); err != nil { + t.Fatal(err) + } + return a.String + } + if err := m.Migrate(23); err != nil { + t.Fatalf("up to 23: %v", err) + } + if got := [3]string{areaOf(own), areaOf(delivery), areaOf(public)}; got != [3]string{"internal", "", "product_public"} { + t.Errorf("after up: %v", got) + } + if err := m.Migrate(22); err != nil { + t.Fatalf("down to 22: %v", err) + } + if got := [3]string{areaOf(own), areaOf(delivery), areaOf(public)}; got != [3]string{"", "", "product_public"} { + t.Errorf("after down: %v", got) + } +} diff --git a/openapi.yaml b/openapi.yaml index 15d1af8..e0552d4 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -337,6 +337,7 @@ paths: get: summary: The tenant's document store (Dokumentenablage), by area and legal folder. description: | + Published documents only; BreakPilot's deliveries (no area) come last. Served by the `{id}/{sub}` route; user tokens reach their own tenant only. Each item carries its processing status and, once delivered, a summary of its prepared version. -- 2.54.1