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(area, ''), COALESCE(legal_kind, ''), processing_status, processing_error, external_id, 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.Area, &d.LegalKind, &d.ProcessingStatus, &d.ProcessingError, &d.ExternalID, &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 } if d.ProcessingStatus == "" { d.ProcessingStatus = ProcessingNone } if !validStoreFields(d) { return nil, ErrInvalidInput } _, 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, area, legal_kind, processing_status, external_id) VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NULLIF($13, ''), NULLIF($14, ''), $15, $16)`, d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy, d.OwnDocument, d.Area, d.LegalKind, d.ProcessingStatus, d.ExternalID) 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) { // BreakPilot's deliveries only; the tenant's own documents are the store's. q := documentSelect + `WHERE tenant_id = $1::uuid AND area IS NULL` 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 }