feat(store): keep each tenant's filled AVV (migration 0027)

tenant_contract_documents records a workspace's own filled contract
document (for now the AVV): master version, PDF SHA-256, bucket key,
digest of the filled-in values and the staff member's Keycloak sub.
Rows are insert-only (an UPDATE trigger refuses changes); the newest per
tenant and kind is current. Memory and Postgres stores, purge with the
tenant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-09 12:55:06 +01:00
1 parent 8faf3fe2a7
commit 82a5a6ca80
8 files changed
+244 -5

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
package store
import (
"regexp"
"time"
)
// ContractDocument is a workspace's own filled contract document (0027): a
// PDF in the document bucket, made by staff from the released master and
// the workspace's details. Rows are never changed; a corrected document is a
// new row, and the newest per tenant and kind is the current one.
type ContractDocument struct {
ID int64 `json:"id"`
TenantID string `json:"tenant_id"`
Kind string `json:"doc_kind"` // avv
Version string `json:"version"` // version of the master it was filled from
SHA256 string `json:"sha256"`
ObjectKey string `json:"-"`
// ValuesSHA256 is the digest of the details filled in; the values
// themselves are not kept here.
ValuesSHA256 string `json:"values_sha256"`
CreatedBy string `json:"created_by"` // Keycloak sub of the staff member
CreatedAt time.Time `json:"created_at"`
}
// ContractDocumentAVV is the only kind a workspace has its own copy of.
const ContractDocumentAVV = "avv"
var (
contractVersionRe = regexp.MustCompile(`^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$`)
hexDigestRe = regexp.MustCompile(`^[0-9a-f]{64}$`)
)
// validContractDocument mirrors the CHECK constraints of 0027.
func validContractDocument(d ContractDocument) bool {
return d.Kind == ContractDocumentAVV && contractVersionRe.MatchString(d.Version) &&
hexDigestRe.MatchString(d.SHA256) && hexDigestRe.MatchString(d.ValuesSHA256) &&
d.ObjectKey != "" && len(d.ObjectKey) <= 512 && d.CreatedBy != "" && len(d.CreatedBy) <= 200
}
+10
View File
@@ -47,6 +47,9 @@ type Memory struct {
mailID int64
prodSets map[string]*TenantProductSettings // tenant_id + "/" + product (0025)
contractDocs []ContractDocument // every row, oldest first (0027)
contractDocID int64
}
type apiKeyWithHash struct {
@@ -597,6 +600,13 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error {
delete(m.prodSets, k)
}
}
kept := m.contractDocs[:0]
for _, d := range m.contractDocs {
if d.TenantID != id {
kept = append(kept, d)
}
}
m.contractDocs = kept
for kid, k := range m.apiKeys {
if k.TenantID == id {
delete(m.apiKeys, kid)
@@ -0,0 +1,49 @@
package store
import (
"context"
"time"
)
func (m *Memory) CreateContractDocument(_ context.Context, d ContractDocument) (*ContractDocument, error) {
if !validContractDocument(d) {
return nil, ErrInvalidInput
}
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[d.TenantID]; !ok {
return nil, ErrNotFound
}
m.contractDocID++
d.ID = m.contractDocID
if d.CreatedAt.IsZero() {
d.CreatedAt = time.Now()
}
d.CreatedAt = d.CreatedAt.UTC()
m.contractDocs = append(m.contractDocs, d)
cp := d
return &cp, nil
}
func (m *Memory) CurrentContractDocument(_ context.Context, tenantID, kind string) (*ContractDocument, error) {
m.mu.RLock()
defer m.mu.RUnlock()
for i := len(m.contractDocs) - 1; i >= 0; i-- {
if d := m.contractDocs[i]; d.TenantID == tenantID && d.Kind == kind {
return &d, nil
}
}
return nil, ErrNotFound
}
func (m *Memory) ListContractDocuments(_ context.Context, tenantID string) ([]ContractDocument, error) {
m.mu.RLock()
defer m.mu.RUnlock()
out := []ContractDocument{}
for _, d := range m.contractDocs {
if d.TenantID == tenantID {
out = append(out, d)
}
}
return out, nil
}
@@ -0,0 +1,77 @@
package store
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
)
const contractDocumentCols = `id, tenant_id::text, doc_kind, version, sha256, object_key, values_sha256, created_by, created_at`
func scanContractDocument(row pgx.Row) (*ContractDocument, error) {
var d ContractDocument
if err := row.Scan(&d.ID, &d.TenantID, &d.Kind, &d.Version, &d.SHA256, &d.ObjectKey, &d.ValuesSHA256, &d.CreatedBy, &d.CreatedAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
return &d, nil
}
func (p *Postgres) CreateContractDocument(ctx context.Context, d ContractDocument) (*ContractDocument, error) {
if !validContractDocument(d) {
return nil, ErrInvalidInput
}
saved, err := scanContractDocument(p.pool.QueryRow(ctx, `
INSERT INTO tenant_contract_documents (tenant_id, doc_kind, version, sha256, object_key, values_sha256, created_by)
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7)
RETURNING `+contractDocumentCols,
d.TenantID, d.Kind, d.Version, d.SHA256, d.ObjectKey, d.ValuesSHA256, d.CreatedBy))
switch {
case err == nil:
return saved, nil
case isFKViolation(err), isInvalidUUID(err):
return nil, ErrNotFound
case isCheckViolation(err):
return nil, ErrInvalidInput
}
return nil, err
}
func (p *Postgres) CurrentContractDocument(ctx context.Context, tenantID, kind string) (*ContractDocument, error) {
d, err := scanContractDocument(p.pool.QueryRow(ctx, `
SELECT `+contractDocumentCols+` FROM tenant_contract_documents
WHERE tenant_id = $1::uuid AND doc_kind = $2
ORDER BY id DESC LIMIT 1`, tenantID, kind))
if isInvalidUUID(err) {
return nil, ErrNotFound
}
return d, err
}
func (p *Postgres) ListContractDocuments(ctx context.Context, tenantID string) ([]ContractDocument, error) {
rows, err := p.pool.Query(ctx, `
SELECT `+contractDocumentCols+` FROM tenant_contract_documents
WHERE tenant_id = $1::uuid ORDER BY id`, tenantID)
if isInvalidUUID(err) {
return []ContractDocument{}, nil
}
if err != nil {
return nil, err
}
defer rows.Close()
out := []ContractDocument{}
for rows.Next() {
d, err := scanContractDocument(rows)
if err != nil {
return nil, err
}
out = append(out, *d)
}
if isInvalidUUID(rows.Err()) {
return []ContractDocument{}, nil
}
return out, rows.Err()
}
+10
View File
@@ -257,6 +257,16 @@ type Store interface {
GetTenantProductSettings(ctx context.Context, tenantID, product string) (*TenantProductSettings, error)
PutTenantProductSettings(ctx context.Context, ps TenantProductSettings) (*TenantProductSettings, error)
// Contract documents of a tenant (0027): its own filled copies, for now
// the AVV. Rows are never changed; the newest per tenant and kind is the
// current one. CreateContractDocument returns ErrNotFound for an unknown
// tenant and ErrInvalidInput for a malformed row; CurrentContractDocument
// is ErrNotFound when the tenant has none of that kind;
// ListContractDocuments returns every row, oldest first.
CreateContractDocument(ctx context.Context, d ContractDocument) (*ContractDocument, error)
CurrentContractDocument(ctx context.Context, tenantID, kind string) (*ContractDocument, error)
ListContractDocuments(ctx context.Context, tenantID string) ([]ContractDocument, error)
// Managed services (0012, portal#77), listed by created_at. One row per
// (tenant, kind, url): ErrConflict otherwise.
ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error)
@@ -0,0 +1,3 @@
DROP TRIGGER IF EXISTS tenant_contract_documents_immutable ON tenant_contract_documents;
DROP FUNCTION IF EXISTS tenant_contract_documents_immutable();
DROP TABLE IF EXISTS tenant_contract_documents;
@@ -0,0 +1,29 @@
-- A workspace's own filled contract documents: for now the AVV, which staff
-- fill in from the released master with the company's details (name,
-- address, management, who gives instructions) and upload as a PDF to the
-- document bucket. The row records which master version it was made from,
-- the PDF's SHA-256 (checked before every download), the digest of the
-- details filled in (the details themselves are not stored here) and the
-- staff member who made it. Rows are never changed: a corrected document is a
-- new row, and the newest per tenant and kind is the current one.
CREATE TABLE tenant_contract_documents (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
doc_kind TEXT NOT NULL CHECK (doc_kind IN ('avv')),
version TEXT NOT NULL CHECK (version ~ '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'),
sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
object_key TEXT NOT NULL CHECK (char_length(object_key) BETWEEN 1 AND 512),
values_sha256 TEXT NOT NULL CHECK (values_sha256 ~ '^[0-9a-f]{64}$'),
created_by TEXT NOT NULL CHECK (char_length(created_by) BETWEEN 1 AND 200),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX tenant_contract_documents_current ON tenant_contract_documents (tenant_id, doc_kind, id DESC);
CREATE FUNCTION tenant_contract_documents_immutable() RETURNS trigger AS $$
BEGIN
RAISE EXCEPTION 'tenant_contract_documents: rows are never changed; insert a new one';
END $$ LANGUAGE plpgsql;
CREATE TRIGGER tenant_contract_documents_immutable
BEFORE UPDATE ON tenant_contract_documents
FOR EACH ROW EXECUTE FUNCTION tenant_contract_documents_immutable();
+27 -5
View File
@@ -107,6 +107,7 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
"role_datasets",
"role_dataset_revisions",
"tenant_product_settings",
"tenant_contract_documents",
}
for _, table := range wantTables {
var exists bool
@@ -122,8 +123,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
}
}
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings).
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}} {
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents).
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}} {
var exists bool
err := db.QueryRow(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",
@@ -315,15 +316,36 @@ func TestSeed_canInsertAndQuery(t *testing.T) {
t.Error("settings that are not an object were stored")
}
// 0027: filled contract documents, insert-only.
insDoc := `INSERT INTO tenant_contract_documents (tenant_id, doc_kind, version, sha256, object_key, values_sha256, created_by)
VALUES ($1, $2, $3, $4, 'tenants/x/contracts/avv/a.pdf', $4, 'staff-sub')`
digest := strings.Repeat("ab", 32)
if _, err := db.ExecContext(ctx, insDoc, tid, "avv", "1.0.0", digest); err != nil {
t.Fatalf("insert contract document: %v", err)
}
for name, args := range map[string][]any{
"unknown kind": {tid, "nda", "1.0.0", digest},
"bad version": {tid, "avv", "1.0", digest},
"upper-case sha": {tid, "avv", "1.0.0", strings.ToUpper(digest)},
} {
if _, err := db.ExecContext(ctx, insDoc, args...); err == nil {
t.Errorf("contract document with %s was stored", name)
}
}
if _, err := db.ExecContext(ctx, `UPDATE tenant_contract_documents SET version = '1.0.1' WHERE tenant_id = $1`, tid); err == nil {
t.Error("a contract document row was changed")
}
// FK cascade — delete tenant, projects/products/keys/audit_log handling.
if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, tid); err != nil {
t.Fatalf("delete tenant: %v", err)
}
var nServices, nSettings int
var nServices, nSettings, nContractDocs int
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM managed_services WHERE tenant_id = $1`, tid).Scan(&nServices)
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_product_settings WHERE tenant_id = $1`, tid).Scan(&nSettings)
if nServices != 0 || nSettings != 0 {
t.Errorf("FK cascade incomplete: managed_services=%d tenant_product_settings=%d", nServices, nSettings)
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_contract_documents WHERE tenant_id = $1`, tid).Scan(&nContractDocs)
if nServices != 0 || nSettings != 0 || nContractDocs != 0 {
t.Errorf("FK cascade incomplete: managed_services=%d tenant_product_settings=%d tenant_contract_documents=%d", nServices, nSettings, nContractDocs)
}
var nProjects, nProducts, nKeys int
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_projects WHERE tenant_id = $1`, tid).Scan(&nProjects)