Brings the ERPNext sales catalogue in line with the frozen Leistungsbeschreibungen 1.0.0. This PR changes code and tests only. No ERP was called; the live run is yours, using the erpsetup CLI. ## Dry run first (with the flag; only this path prints `field old → new`) ```sh ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… ERP_WEBHOOK_SECRET=… \ go run ./cmd/erpsetup -webhook-url https://registry.breakpilot.com/v1/internal/erp/webhook -sync-catalog -dry-run ``` (`ERP_LEAD_DOCTYPE` is optional, as before.) Leave out `-dry-run` for the real run. ## What a run does with and without `-sync-catalog` | | without the flag (as today) | with `-sync-catalog` | |---|---|---| | New items, unit "Prüftag", their list prices | created | created | | Item **description** | **updated (this already happens on every run today)** | updated | | Item `item_name`, `disabled` | untouched | updated when they differ | | Standard Selling `price_list_rate` (rows without a customer) | set once, never changed | updated when it differs | | Customer-specific Item Prices | untouched | untouched | | Quote print format (Mehrverbrauch row) | updated | updated | **A plain run is not inert.** It creates the 5 new items, the new unit and 5 new prices, rewrites every changed description, and updates the quote template. Only names, the disabled flags and price changes wait for the flag. Nothing is ever deleted. Only the doctypes Item, Item Price and UOM are touched beyond what erpsetup already manages. ## Catalogue changes | Code | Status | Price old → new (EUR) | |---|---|---| | PLT-CORE-CLD-STD/BUS/ENT | keep (name "Breakpilot …", new text) | 290 / 790 / 1990 (unchanged) | | PLT-BNDL-CLD-STD | **new** Starter-Modulpaket | 990 | | PLT-BNDL-CLD-ADD | **new** Weiteres Modul | 499 | | CRA-CSA-CLD-STD | keep | **1490 → 490** | | CRA-CSA-CLD-BUS | keep | **3990 → 1290** | | CRA-CSA-CLD-ENT | keep | **9900 → 0** (Preis nach Vereinbarung: a quote shows 0,00 € unless the rate is entered by hand) | | CRA-CSA-CLD-TGT | **new** extra Prüfobjekt / Monat | 5.99 | | CRA-CSA-CLD-DAY | **new** Prüftag (unit Prüftag) | 9.99 | | CRA-CSA-CLD-SCAN | **disable** | 12 (unchanged) | | CRA-WBK-CLD-STD/BUS/ENT | **disable** | unchanged | | DEV-WP-CLD-STD | keep ("Werkpilot Cloud") | 59 | | DEV-WP-CLD-BUS/ENT | **disable** | unchanged | | DEV-WP-OPR-*, DEV-FWK-OPR-*, INF-GIT-OPR-*, INF-CI-OPR-* | keep, new texts | unchanged | | DEV-FWK-CLD-STD | keep ("Firmwerk Cloud") | 89 | | DEV-FWK-CLD-BUS/ENT | **disable** | unchanged | | INF-GIT-CLD-STD/BUS/ENT | keep, new texts | 190 / 390 / 790 | | INF-GIT-CLD-USR | **new** extra user | 19 | | INF-CI-CLD-STD/BUS/ENT | keep, new texts | 149 / 290 / 590 | The item group stays "BreakPilot Abonnements". Correction to the spec, applied here: PLT-CORE-CLD-STD no longer mentions "Rechnungen", because LB Plattform §2(3) says the portal provides no invoices. The text is now "Arbeitsbereich mit Anmeldung und Team für bis 25 Nutzer, Standard-Support. Module werden einzeln gebucht." No other item text mentions invoices, and a test now checks that none does. ## Other changes - `sku.Disabled` is sent to ERPNext as the Item field `disabled: 1`. Disabled items stay in ERPNext so old documents keep working. Since the disabled items already exist on prod, their flag only changes with `-sync-catalog`. - **Quote, Mehrverbrauch row:** "Zusätzliche Prüfobjekte werden mit {TGT} netto je Monat berechnet, Prüftage nach verbrauchtem Monatskontingent mit {DAY} netto (Leistungsbeschreibung Prüfwerk, Abschnitt 7)." If a rate is missing, the text says "gemäß der jeweils gültigen Preisliste" instead, per rate. If both are missing, one combined sentence is printed. Quotes with INF-GIT-CLD-STD/BUS/ENT or PLT-BNDL-* add the sentence on extra users (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4). The Jinja was parsed and rendered locally with jinja2 against mocks for eight item mixes. - **Migration 0026** adds CRA-CSA-CLD-TGT and -DAY to the `pruefwerk` product. SCAN stays so old orders still map. The up is guarded so it can run twice; the down removes the two SKUs. `DefaultProducts` and the ERP mock's SKU list follow. **Run `migrate-up` with the deploy.** Without it, TGT/DAY lines on an order log "sales order item without catalog product". - **0 € module lines:** nothing needed fixing. Neither the webhook path nor reconcile reads the rate: the webhook template sends only `item_code` and `qty`, and `SubscriptionPlan` has no rate. A new test covers both paths: a bundle order with modules at rate 0 and qty 15 gives an active tenant, plan standard, and seats 15 per module. ## Decisions the spec did not cover 1. **No Prüfwerk Mehrverbrauch sentence on Enterprise quotes.** CRA-CSA-CLD-ENT is "ohne Begrenzung". Edge case: a quote with both -STD and -ENT also prints no Prüfwerk sentence. The extra-users sentence is not affected. 2. The run without the flag still writes descriptions, as `Run` has done until now (see the table). 3. `-sync-catalog` only changes Item Price rows without a `customer`. If there are several such rows for an item, the run reports "not synced". If there are none, it creates the list price. 4. The quote template's Item Price lookup still has no customer filter (unchanged from before). 5. INF-GIT-OPR texts: STD uses the spec text exactly, so "kein Quellcode verlässt das Haus" is gone. BUS keeps "für mittelgroße Teams" and loses "schnellerer Patch-Rhythmus", like CI. ENT says "für große Entwicklungsorganisationen". 6. INF-CI-OPR texts differ only by size ("mindestens 2 vCPU / 4 GB" etc.); "für größere/umfangreiche Builds" was dropped. 7. DEV-WP-OPR and DEV-FWK-OPR texts: the tier phrase sits after "im eigenen Netz", e.g. "Werkpilot im eigenen Netz für mittlere Teams, mit einem vom Kunden betriebenen KI-Modell; …". 8. TGT/DAY quantities on an order or subscription count toward Prüfwerk `seats`, exactly as SCAN already does. Not changed here. 9. Bundle revenue goes to cost center Plattform (PLT-*). Module lines at 0 € book nothing on Prüfwerk, Firmwerk or Werkpilot. Whether to allocate it is an accounting decision for you. 10. The dry run prints texts in full (no truncation), so the wording can be read before it goes live. 11. `TestEverySKUHasAListPrice` now allows exactly one item at 0: CRA-CSA-CLD-ENT. 12. The ERP mock's `DefaultSKUs` now also lists PLT-BNDL-* and CRA-CSA-CLD-TGT/DAY. ## Tests `go build ./... && go vet ./... && go test ./...` all pass. The Postgres testcontainers suites ran (podman socket) with no skips: server 463 s, migrations 32 s. New tests: - catalogue consistency: unique codes, units, disabled set, prices including 5.99/9.99, brand spelling - `TestSyncCatalog`: the dry run writes nothing and names every change; the run updates name, description, disabled and price and keeps the customer price; a second run makes no updates; without the flag only the description changes - quote template phrases - `TestMigrate_productsSeedMatchesDefaults`: seed equals `DefaultProducts`, 0026 applied twice, down - `TestErp_zeroRateModuleLinesEntitle`: webhook and reconcile, memory and Postgres 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Reviewed-on: #115
568 lines
20 KiB
Go
568 lines
20 KiB
Go
package migrations
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/golang-migrate/migrate/v4"
|
|
"github.com/golang-migrate/migrate/v4/database/postgres"
|
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
|
_ "github.com/jackc/pgx/v5/stdlib" // pgx stdlib driver for database/sql
|
|
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// startPostgres spins a fresh postgres:16-alpine container and returns its
|
|
// DSN + a cleanup func. Skips the test if Docker is unreachable.
|
|
func startPostgres(t *testing.T) (string, func()) {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
|
defer cancel()
|
|
|
|
pgc, err := tcpostgres.Run(ctx,
|
|
"postgres:16-alpine",
|
|
tcpostgres.WithDatabase("tenant_registry_test"),
|
|
tcpostgres.WithUsername("test"),
|
|
tcpostgres.WithPassword("test"),
|
|
tcpostgres.BasicWaitStrategies(),
|
|
)
|
|
if err != nil {
|
|
t.Skipf("skipping: docker unreachable (%v)", err)
|
|
}
|
|
|
|
dsn, err := pgc.ConnectionString(ctx, "sslmode=disable")
|
|
if err != nil {
|
|
_ = pgc.Terminate(context.Background())
|
|
t.Fatalf("dsn: %v", err)
|
|
}
|
|
cleanup := func() {
|
|
c, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
_ = pgc.Terminate(c)
|
|
}
|
|
return dsn, cleanup
|
|
}
|
|
|
|
func newMigrator(t *testing.T, dsn string) *migrate.Migrate {
|
|
t.Helper()
|
|
src, err := iofs.New(FS, ".")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
driver, err := postgres.WithInstance(db, &postgres.Config{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
m, err := migrate.NewWithInstance("iofs", src, "postgres", driver)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() {
|
|
_, _ = m.Close()
|
|
_ = db.Close()
|
|
})
|
|
return m
|
|
}
|
|
|
|
func TestMigrate_upDownRoundTrip(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.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
t.Fatalf("up: %v", err)
|
|
}
|
|
|
|
// Schema assertions — every table the spec requires must exist.
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
|
|
wantTables := []string{
|
|
"tenants",
|
|
"tenant_projects",
|
|
"tenant_products",
|
|
"tenant_idp_config",
|
|
"api_keys",
|
|
"audit_log",
|
|
"products",
|
|
"managed_services",
|
|
"role_datasets",
|
|
"role_dataset_revisions",
|
|
"tenant_product_settings",
|
|
}
|
|
for _, table := range wantTables {
|
|
var exists bool
|
|
err := db.QueryRow(
|
|
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema='public' AND table_name=$1)",
|
|
table,
|
|
).Scan(&exists)
|
|
if err != nil {
|
|
t.Fatalf("query for table %s: %v", table, err)
|
|
}
|
|
if !exists {
|
|
t.Errorf("table %s missing after migrate up", table)
|
|
}
|
|
}
|
|
|
|
// 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"}} {
|
|
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)",
|
|
c[0], c[1],
|
|
).Scan(&exists)
|
|
if err != nil {
|
|
t.Fatalf("query for column %s.%s: %v", c[0], c[1], err)
|
|
}
|
|
if !exists {
|
|
t.Errorf("column %s.%s missing after migrate up", c[0], c[1])
|
|
}
|
|
}
|
|
|
|
// 0011: the offer snapshot cannot change, the state can.
|
|
var offerID string
|
|
if err := db.QueryRow(`INSERT INTO trial_offers (company_name, street, postcode, city, country, first_name, last_name, email,
|
|
terms_document_id, terms_version, terms_sha256, notice_version, flow_version, terms_accepted, offered_at,
|
|
verify_token_hash, verify_expires_at)
|
|
VALUES ('Firma', 'Str. 1', '78224', 'Singen', 'DE', 'A', 'B', 'a@b.de', 'trial-terms', '1.0', $1,
|
|
'246c-2026-10-01', 'trial-flow-1', true, now(), 'h1', now() + interval '72 hours') RETURNING id::text`,
|
|
"f7b2635fc26f58acc2686ed1e3d96d4aef878fe2cd313bc3dc233c86d8d79906").Scan(&offerID); err != nil {
|
|
t.Fatalf("insert offer: %v", err)
|
|
}
|
|
if _, err := db.Exec(`UPDATE trial_offers SET email = 'x@y.de' WHERE id = $1::uuid`, offerID); err == nil {
|
|
t.Error("changing the offer snapshot was allowed")
|
|
}
|
|
if _, err := db.Exec(`UPDATE trial_offers SET terms_sha256 = $2 WHERE id = $1::uuid`, offerID, strings.Repeat("0", 64)); err == nil {
|
|
t.Error("changing the accepted terms was allowed")
|
|
}
|
|
if _, err := db.Exec(`UPDATE trial_offers SET state = 'verified', verified_at = now() WHERE id = $1::uuid`, offerID); err != nil {
|
|
t.Errorf("state update refused: %v", err)
|
|
}
|
|
if _, err := db.Exec(`INSERT INTO trial_offers (company_name, street, postcode, city, country, first_name, last_name, email,
|
|
terms_document_id, terms_version, terms_sha256, notice_version, flow_version, terms_accepted, offered_at,
|
|
verify_token_hash, verify_expires_at)
|
|
VALUES ('F', 'S', '1', 'C', 'DE', 'A', 'B', 'c@d.de', 'trial-terms', '1.0', $1, 'n', 'f', false, now(), 'h2', now())`,
|
|
strings.Repeat("a", 64)); err == nil {
|
|
t.Error("an offer without accepted terms was stored")
|
|
}
|
|
|
|
// Enum assertions.
|
|
wantEnums := map[string][]string{
|
|
// 0002 appends the ladder values; enum values are never removed (down is a no-op).
|
|
"tenant_status": {"demo", "trial", "active", "frozen", "archived", "warning", "restricted", "halted"},
|
|
"tenant_kind": {"customer", "demo"},
|
|
"idp_kind": {"oidc", "saml"},
|
|
"tenant_project_status": {"active", "archived"},
|
|
}
|
|
for enum, values := range wantEnums {
|
|
rows, err := db.Query(
|
|
"SELECT e.enumlabel FROM pg_type t JOIN pg_enum e ON t.oid = e.enumtypid WHERE t.typname = $1 ORDER BY e.enumsortorder",
|
|
enum,
|
|
)
|
|
if err != nil {
|
|
t.Fatalf("query enum %s: %v", enum, err)
|
|
}
|
|
var got []string
|
|
for rows.Next() {
|
|
var v string
|
|
if err := rows.Scan(&v); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got = append(got, v)
|
|
}
|
|
_ = rows.Close()
|
|
if fmt.Sprint(got) != fmt.Sprint(values) {
|
|
t.Errorf("enum %s = %v, want %v", enum, got, values)
|
|
}
|
|
}
|
|
|
|
// Round-trip: down all, then up again — must succeed without leftover state.
|
|
if err := m.Down(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
t.Fatalf("down: %v", err)
|
|
}
|
|
var afterDown int
|
|
err = db.QueryRow(
|
|
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name = ANY($1)",
|
|
wantTables,
|
|
).Scan(&afterDown)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if afterDown != 0 {
|
|
t.Errorf("after down: %d tables still present, want 0", afterDown)
|
|
}
|
|
|
|
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
t.Fatalf("up after down: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestSeed_canInsertAndQuery is the lightweight happy-path: insert a tenant,
|
|
// give it a project + a product + an api_key + an audit record, query back.
|
|
// Catches schema-level mistakes (NOT NULL, FK direction, enum cast) that
|
|
// table-existence checks miss.
|
|
func TestSeed_canInsertAndQuery(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.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
t.Fatalf("up: %v", err)
|
|
}
|
|
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
ctx := context.Background()
|
|
|
|
var tid string
|
|
err = db.QueryRowContext(ctx,
|
|
`INSERT INTO tenants (slug, name, plan, status, kind)
|
|
VALUES ($1, $2, 'professional', 'active', 'customer')
|
|
RETURNING id`,
|
|
"acme", "Acme Inc.").Scan(&tid)
|
|
if err != nil {
|
|
t.Fatalf("insert tenant: %v", err)
|
|
}
|
|
|
|
if _, err := db.ExecContext(ctx,
|
|
`INSERT INTO tenant_projects (tenant_id, name, slug) VALUES ($1, $2, $3)`,
|
|
tid, "Production", "prod"); err != nil {
|
|
t.Fatalf("insert project: %v", err)
|
|
}
|
|
if _, err := db.ExecContext(ctx,
|
|
`INSERT INTO tenant_products (tenant_id, product, config) VALUES ($1, 'certifai', '{"max_seats":10}'::jsonb)`,
|
|
tid); err != nil {
|
|
t.Fatalf("insert product: %v", err)
|
|
}
|
|
if _, err := db.ExecContext(ctx,
|
|
`INSERT INTO api_keys (tenant_id, name, hash, prefix, scopes)
|
|
VALUES ($1, 'ci-bot', 'argon2-hash', 'bp_12345', ARRAY['certifai:read'])`,
|
|
tid); err != nil {
|
|
t.Fatalf("insert api_key: %v", err)
|
|
}
|
|
if _, err := db.ExecContext(ctx,
|
|
`INSERT INTO audit_log (tenant_id, action, actor_id, actor_name, metadata)
|
|
VALUES ($1, 'tenant.created', 'sys', 'system', '{"source":"test"}'::jsonb)`,
|
|
tid); err != nil {
|
|
t.Fatalf("insert audit: %v", err)
|
|
}
|
|
|
|
// Round-trip read.
|
|
var slug, status string
|
|
err = db.QueryRowContext(ctx, `SELECT slug, status::text FROM tenants WHERE id = $1`, tid).Scan(&slug, &status)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if slug != "acme" || status != "active" {
|
|
t.Errorf("tenant readback: slug=%q status=%q", slug, status)
|
|
}
|
|
|
|
// 0012: one row per (tenant, kind, url); kind and status are checked.
|
|
insMS := `INSERT INTO managed_services (tenant_id, kind, name, url, sku, status) VALUES ($1, $2, 'Git', $3, 'INF-GIT-CLD-STD', $4)`
|
|
if _, err := db.ExecContext(ctx, insMS, tid, "git", "https://git.k-00001.example", "active"); err != nil {
|
|
t.Fatalf("insert managed service: %v", err)
|
|
}
|
|
if _, err := db.ExecContext(ctx, insMS, tid, "git", "https://git.k-00001.example", "active"); err == nil {
|
|
t.Error("duplicate (tenant, kind, url) was stored")
|
|
}
|
|
if _, err := db.ExecContext(ctx, insMS, tid, "svn", "https://svn.k-00001.example", "active"); err == nil {
|
|
t.Error("unknown kind was stored")
|
|
}
|
|
if _, err := db.ExecContext(ctx, insMS, tid, "git", "https://git2.k-00001.example", "paused"); err == nil {
|
|
t.Error("unknown status was stored")
|
|
}
|
|
// 0013: kind ci-runner; several runners may serve one Git instance.
|
|
insRunner := `INSERT INTO managed_services (tenant_id, kind, name, url, sku) VALUES ($1, 'ci-runner', 'Runner', $2, 'INF-CI-CLD-STD')`
|
|
for i := 0; i < 2; i++ {
|
|
if _, err := db.ExecContext(ctx, insRunner, tid, "https://git.k-00001.example"); err != nil {
|
|
t.Fatalf("insert runner %d: %v", i+1, err)
|
|
}
|
|
}
|
|
|
|
// 0025: one settings object per (tenant, product).
|
|
insSet := `INSERT INTO tenant_product_settings (tenant_id, product, settings) VALUES ($1, 'pruefwerk', $2::jsonb)`
|
|
if _, err := db.ExecContext(ctx, insSet, tid, `{"prueftag_cap":null}`); err != nil {
|
|
t.Fatalf("insert product settings: %v", err)
|
|
}
|
|
if _, err := db.ExecContext(ctx, insSet, tid, `{"prueftag_cap":5}`); err == nil {
|
|
t.Error("second settings row for the same product was stored")
|
|
}
|
|
if _, err := db.ExecContext(ctx, `INSERT INTO tenant_product_settings (tenant_id, product, settings) VALUES ($1, 'firmwerk', '[1]'::jsonb)`, tid); err == nil {
|
|
t.Error("settings that are not an object were stored")
|
|
}
|
|
|
|
// 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
|
|
_ = 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)
|
|
}
|
|
var nProjects, nProducts, nKeys int
|
|
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_projects WHERE tenant_id = $1`, tid).Scan(&nProjects)
|
|
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_products WHERE tenant_id = $1`, tid).Scan(&nProducts)
|
|
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM api_keys WHERE tenant_id = $1`, tid).Scan(&nKeys)
|
|
if nProjects != 0 || nProducts != 0 || nKeys != 0 {
|
|
t.Errorf("FK cascade incomplete: projects=%d products=%d keys=%d", nProjects, nProducts, nKeys)
|
|
}
|
|
|
|
// audit_log uses ON DELETE SET NULL — tenant_id becomes NULL but row stays
|
|
var nAudit, nAuditNullTenant int
|
|
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM audit_log`).Scan(&nAudit)
|
|
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM audit_log WHERE tenant_id IS NULL`).Scan(&nAuditNullTenant)
|
|
if nAudit != 1 || nAuditNullTenant != 1 {
|
|
t.Errorf("audit_log SET NULL: total=%d null=%d, want 1/1", nAudit, nAuditNullTenant)
|
|
}
|
|
}
|
|
|
|
func TestSlugConstraint(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.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
t.Fatalf("up: %v", err)
|
|
}
|
|
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
|
|
cases := []struct {
|
|
slug string
|
|
wantErr bool
|
|
}{
|
|
{"acme", false},
|
|
{"a-c-m-e", false},
|
|
{"a1b2c3", false},
|
|
{"a", true}, // too short
|
|
{"-acme", true}, // leading dash
|
|
{"acme-", true}, // trailing dash
|
|
{"AcMe", true}, // uppercase
|
|
{"a_b", true}, // underscore
|
|
}
|
|
for _, c := range cases {
|
|
_, err := db.Exec(`INSERT INTO tenants (slug, name) VALUES ($1, 'X')`, c.slug)
|
|
gotErr := err != nil
|
|
if gotErr != c.wantErr {
|
|
t.Errorf("slug %q: gotErr=%v wantErr=%v (err=%v)", c.slug, gotErr, c.wantErr, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// 0019 ends the product trials of workspaces on trial with that trial, and
|
|
// leaves everything else alone.
|
|
func TestMigrate_0019AlignsTrialEntitlements(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(18); err != nil {
|
|
t.Fatalf("up to 18: %v", err)
|
|
}
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
|
|
tenant := func(slug, status, trialEnd string) string {
|
|
var id string
|
|
if err := db.QueryRow(`INSERT INTO tenants (slug, name, status, trial_ends_at)
|
|
VALUES ($1, 'X', $2, NOW() + $3::interval) RETURNING id`, slug, status, trialEnd).Scan(&id); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return id
|
|
}
|
|
product := func(tenantID, key, source, expires string) {
|
|
if _, err := db.Exec(`INSERT INTO tenant_products (tenant_id, product, enabled, config, expires_at)
|
|
VALUES ($1, $2, FALSE, jsonb_build_object('source', $3::text), NOW() + $4::interval)`, tenantID, key, source, expires); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
short := tenant("trial-short", "trial", "14 days")
|
|
product(short, "pruefwerk", "trial", "-1 hour") // expired before the trial: aligned
|
|
product(short, "firmwerk", "erp", "-1 hour") // booked: untouched
|
|
longer := tenant("trial-longer", "trial", "3 days")
|
|
product(longer, "pruefwerk", "trial", "10 days") // ends later: untouched
|
|
paying := tenant("paying", "active", "14 days")
|
|
product(paying, "pruefwerk", "trial", "-1 hour") // not on trial: untouched
|
|
|
|
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
t.Fatalf("up: %v", err)
|
|
}
|
|
aligned := func(tenantID, key string) bool {
|
|
var ok bool
|
|
if err := db.QueryRow(`SELECT tp.enabled AND tp.expires_at = t.trial_ends_at
|
|
FROM tenant_products tp JOIN tenants t ON t.id = tp.tenant_id
|
|
WHERE tp.tenant_id = $1 AND tp.product = $2`, tenantID, key).Scan(&ok); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return ok
|
|
}
|
|
if !aligned(short, "pruefwerk") {
|
|
t.Error("the trial product of a workspace on trial was not aligned")
|
|
}
|
|
for _, c := range []struct{ id, key string }{{short, "firmwerk"}, {longer, "pruefwerk"}, {paying, "pruefwerk"}} {
|
|
if aligned(c.id, c.key) {
|
|
t.Errorf("%s/%s changed", c.id, c.key)
|
|
}
|
|
}
|
|
var audited int
|
|
if err := db.QueryRow(`SELECT COUNT(*) FROM audit_log WHERE action = 'entitlement.trial_aligned' AND tenant_id = $1`, short).Scan(&audited); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if audited != 1 {
|
|
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)
|
|
}
|
|
}
|
|
|
|
// The seeded products match store.DefaultProducts (the Memory store's copy),
|
|
// and 0026 adds the Prüfwerk SKUs TGT and DAY once, keeping SCAN; its down
|
|
// takes them out again.
|
|
func TestMigrate_productsSeedMatchesDefaults(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.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
t.Fatalf("up: %v", err)
|
|
}
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
|
|
seeded := func(key string) ([]string, []store.ProductAddon) {
|
|
t.Helper()
|
|
var skus, addons []byte
|
|
if err := db.QueryRow(`SELECT skus, addons FROM products WHERE key = $1`, key).Scan(&skus, &addons); err != nil {
|
|
t.Fatalf("product %s: %v", key, err)
|
|
}
|
|
var s []string
|
|
var a []store.ProductAddon
|
|
if err := json.Unmarshal(skus, &s); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := json.Unmarshal(addons, &a); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return s, a
|
|
}
|
|
for _, p := range store.DefaultProducts() {
|
|
skus, addons := seeded(p.Key)
|
|
if fmt.Sprint(skus) != fmt.Sprint(p.SKUs) {
|
|
t.Errorf("%s: seeded SKUs %v, DefaultProducts %v", p.Key, skus, p.SKUs)
|
|
}
|
|
if fmt.Sprint(addons) != fmt.Sprint(p.Addons) {
|
|
t.Errorf("%s: seeded add-ons %v, DefaultProducts %v", p.Key, addons, p.Addons)
|
|
}
|
|
}
|
|
|
|
// Applied again (e.g. after a manual fix), 0026 adds nothing twice.
|
|
up, err := FS.ReadFile("0026_pruefwerk_tgt_day_skus.up.sql")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := db.Exec(string(up)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if skus, _ := seeded("pruefwerk"); fmt.Sprint(skus) != "[CRA-CSA-CLD-STD CRA-CSA-CLD-BUS CRA-CSA-CLD-ENT CRA-CSA-CLD-SCAN CRA-CSA-CLD-TGT CRA-CSA-CLD-DAY]" {
|
|
t.Errorf("0026 twice: %v", skus)
|
|
}
|
|
if err := m.Migrate(25); err != nil {
|
|
t.Fatalf("down to 25: %v", err)
|
|
}
|
|
if skus, _ := seeded("pruefwerk"); fmt.Sprint(skus) != "[CRA-CSA-CLD-STD CRA-CSA-CLD-BUS CRA-CSA-CLD-ENT CRA-CSA-CLD-SCAN]" {
|
|
t.Errorf("after down: %v", skus)
|
|
}
|
|
}
|