Files
tenant-registry/internal/store/postgres_documents.go
T
Sharang ParnerkarandClaude Opus 5.5 e25320297a
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Successful in 24m19s
ci / image (pull_request) Skipped
feat(projects): Projekte for documents and product objects
A tenant groups its documents and product objects by one of its own
products (kind product) or a topic such as the CRA (kind topic). Purely
organisational.

- migration 0010: projects (unique name per tenant, ignoring case),
  document_projects, documents.own_document
- GET/POST /v1/tenants/{id}/projects, PATCH/DELETE .../{pid}: the portal
  writes for staff and tenant admins; products read with tenants.read
- GET /v1/tenants/{id}/projects/{pid}/targets: the project's Prüfwerk
  objects from Prüfwerk's platform API (service token), with dashboard links;
  empty and available=false when Prüfwerk cannot answer
- documents: upload with project_ids and own_document, PATCH
  /v1/admin/documents/{doc} to reassign; own documents are published
  without a notification mail
- audit: project.created/updated/deleted, document.updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-29 14:24:12 +02:00

195 lines
5.6 KiB
Go

package store
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
)
const documentSelect = `
SELECT id::text, tenant_id::text, title, description, filename, content_type, size_bytes, sha256,
object_key, status, uploaded_by, COALESCE(published_by, ''), published_at, created_at, updated_at,
own_document,
COALESCE((SELECT array_agg(dp.project_id::text ORDER BY dp.project_id) FROM document_projects dp
WHERE dp.document_id = documents.id), '{}')
FROM documents `
func scanDocument(row pgx.Row) (*Document, error) {
var d Document
if err := row.Scan(&d.ID, &d.TenantID, &d.Title, &d.Description, &d.Filename, &d.ContentType, &d.SizeBytes, &d.SHA256,
&d.ObjectKey, &d.Status, &d.UploadedBy, &d.PublishedBy, &d.PublishedAt, &d.CreatedAt, &d.UpdatedAt,
&d.OwnDocument, &d.ProjectIDs); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
return &d, nil
}
func (p *Postgres) CreateDocument(ctx context.Context, d Document) (*Document, error) {
if d.ID == "" || d.ObjectKey == "" || d.Title == "" {
return nil, ErrInvalidInput
}
if d.Status == "" {
d.Status = DocumentDraft
}
_, err := p.pool.Exec(ctx, `
INSERT INTO documents (id, tenant_id, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by, own_document)
VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy, d.OwnDocument)
switch {
case err == nil:
if len(d.ProjectIDs) > 0 {
out, perr := p.SetDocumentProjects(ctx, d.ID, d.ProjectIDs)
if perr != nil {
// No half-created document: without its projects it goes again.
_, _ = p.pool.Exec(context.WithoutCancel(ctx), `DELETE FROM documents WHERE id = $1::uuid`, d.ID)
return nil, perr
}
return out, nil
}
return p.GetDocument(ctx, d.ID)
case isFKViolation(err), isInvalidUUID(err):
return nil, ErrNotFound
case isUniqueViolation(err):
return nil, ErrConflict
case isCheckViolation(err):
return nil, ErrInvalidInput
default:
return nil, err
}
}
func (p *Postgres) GetDocument(ctx context.Context, id string) (*Document, error) {
d, err := scanDocument(p.pool.QueryRow(ctx, documentSelect+`WHERE id = $1::uuid`, id))
if isInvalidUUID(err) {
return nil, ErrNotFound
}
return d, err
}
func (p *Postgres) ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error) {
q := documentSelect + `WHERE tenant_id = $1::uuid`
if publishedOnly {
q += ` AND status = 'published'`
}
rows, err := p.pool.Query(ctx, q+` ORDER BY created_at DESC, id DESC`, tenantID)
if isInvalidUUID(err) {
return []Document{}, nil
}
if err != nil {
return nil, err
}
defer rows.Close()
out := []Document{}
for rows.Next() {
d, err := scanDocument(rows)
if err != nil {
return nil, err
}
out = append(out, *d)
}
return out, rows.Err()
}
func (p *Postgres) PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error) {
// An already published document is returned unchanged.
_, err := p.pool.Exec(ctx, `
UPDATE documents SET status = 'published', published_by = $2, published_at = $3, updated_at = $3
WHERE id = $1::uuid AND status <> 'published'`, id, by, at.UTC())
if isInvalidUUID(err) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return p.GetDocument(ctx, id)
}
func (p *Postgres) DeleteDocument(ctx context.Context, id string) error {
tag, err := p.pool.Exec(ctx, `DELETE FROM documents WHERE id = $1::uuid`, id)
if isInvalidUUID(err) {
return ErrNotFound
}
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) SetDocumentProjects(ctx context.Context, docID string, projectIDs []string) (*Document, error) {
d, err := p.GetDocument(ctx, docID)
if err != nil {
return nil, err
}
ids := dedupe(projectIDs)
tx, err := p.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback(ctx) }()
if len(ids) > 0 {
// Every project must exist and belong to the document's tenant.
var n int
err := tx.QueryRow(ctx, `SELECT count(*) FROM projects WHERE id = ANY($1::uuid[]) AND tenant_id = $2::uuid`, ids, d.TenantID).Scan(&n)
if isInvalidUUID(err) {
return nil, ErrInvalidInput
}
if err != nil {
return nil, err
}
if n != len(ids) {
return nil, ErrInvalidInput
}
}
if _, err := tx.Exec(ctx, `DELETE FROM document_projects WHERE document_id = $1::uuid`, docID); err != nil {
return nil, err
}
if len(ids) > 0 {
if _, err := tx.Exec(ctx, `INSERT INTO document_projects (document_id, project_id)
SELECT $1::uuid, unnest($2::uuid[])`, docID, ids); err != nil {
return nil, err
}
}
if _, err := tx.Exec(ctx, `UPDATE documents SET updated_at = now() WHERE id = $1::uuid`, docID); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return p.GetDocument(ctx, docID)
}
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)
if isInvalidUUID(err) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
if tag.RowsAffected() == 0 {
return nil, ErrNotFound
}
return p.GetDocument(ctx, docID)
}
// dedupe keeps the first occurrence of every id.
func dedupe(ids []string) []string {
seen := map[string]bool{}
out := []string{}
for _, id := range ids {
if id != "" && !seen[id] {
seen[id] = true
out = append(out, id)
}
}
return out
}