Tenant Management Domain Sandbox Tenant Seeding and Tenant Aware Demo Data

Overview

This sandbox flow creates a reusable tenant-scoped dataset for local development and validation. The seeding script provisions a tenant, a tenant-bound API client, three deterministic credit profiles, region-specific consent fixtures, and region-specific evidence snapshots so the same sandbox identity can be replayed across runs.

The main value is repeatability: the same tenant name, client ID, applicant IDs, profile IDs, and evidence references are reused, while decisions are recalculated from fixed profile inputs. That makes the exported JSON and CSV artifacts useful for checking tenant isolation across US and JP surfaces, comparing profile outcomes, and reviewing evidence snapshots without querying the database directly.

Architecture Overview

flowchart TB
    Operator[Operator]

    subgraph Seeding [Sandbox seeding]
        SeedScript[seed sandbox dummy data script]
        PrismaClient[Prisma Client]
        Postgres[(PostgreSQL)]
        ArtifactDir[workspace artifacts]
    end

    subgraph Validation [Local API validation]
        CheckLocal[check local API script]
        CheckApi[check api script]
        Smoke[check all api paths script]
        API[Fastify API]
        Docker[Docker Compose]
    end

    Operator --> SeedScript
    SeedScript --> PrismaClient
    PrismaClient --> Postgres
    SeedScript --> ArtifactDir

    Operator --> CheckLocal
    CheckLocal --> Docker
    CheckLocal --> CheckApi
    CheckLocal --> Smoke
    CheckApi --> API
    Smoke --> API

Sandbox Tenant Seeding Script

[!IMPORTANT] The sandbox seed is designed to be rerun safely with the same identifiers. Tenant lookup, API client upsert, profile upsert, decision replacement, and evidence snapshot upsert all preserve a stable sandbox namespace rather than generating a fresh one on each run.

scripts/seed-sandbox-dummy-data.sh

This script is the canonical sandbox bootstrap for tenant-aware demo data. It loads environment overrides, generates the Prisma client, runs an inline Node.js seed program, and writes reusable artifacts to the workspace output directory.

Inputs and defaults

Variable Default Purpose
TENANT_NAME sandbox-tenant Stable tenant name reused across seed runs
API_KEY sandbox-key Stable API client identifier used for the sandbox client
CLIENT_NAME sandbox-client Human-readable API client name
OUTPUT_FORMAT both Controls JSON, CSV, or both artifact outputs
OUTPUT_DIR ./workspace/artifacts Destination directory for exported files
DATABASE_URL postgresql://postgres:postgres@localhost:5432/lita-api Prisma connection target when .env does not override it

The script also loads .env when present, so local overrides flow into both Prisma and artifact generation.

Helper functions

Function Description
computeScore(input) Produces a deterministic integer score from profile income, debt-to-income, balance, NSF count, and currency
scoreToOutcome(score) Maps the score into approved, manual_review, or declined
reasonCodesFor(outcome) Returns the reason-code array for the outcome band
plusDays(days) Returns a date offset from the script start time
escapeCsvValue(value) Escapes values for CSV output, including commas, quotes, and newlines
toCsvRows(payload) Serializes the exported payload into grouped CSV sections
upsertUsFixtures() Reuses or creates the US consent and evidence fixtures
upsertJpFixtures() Reuses or creates the JP consent and evidence fixtures

Seeded tenant-scoped records

Record type Key fields Behavior
Tenant name Looked up by name and created only if missing
API client clientId, tenantId, name, clientSecretHash, scopes Upserted by clientId and attached to the sandbox tenant
Credit profile tenantId, externalUserId, dataJson Upserted per tenant and external user ID
Decision tenantId, creditProfileId, outcome, reasonCodesJson, scoreJson Existing decisions for the profile are deleted before creating the fresh decision
US consent tenantId, applicantId, status, purpose, dataCategories, refreshPermissionsJson, disclosureVersion, expiresAt Reused by applicant and tenant, with one active consent selected by revokedAt: null
JP consent tenantId, applicantId, status, purpose, dataCategories, refreshPermissionsJson, disclosureVersion, appiProvisionJson, expiresAt Same reuse pattern as US, with JP-specific provision metadata
US evidence snapshot evidenceRef, tenantId, consentId, featureSet, featuresJson Upserted by stable evidence reference
JP evidence snapshot evidenceRef, tenantId, consentId, featureSet, featuresJson Upserted by stable evidence reference

Deterministic demo profiles

The script seeds three fixed profiles and derives their decision outcomes from the same scoring function on every run.

externalUserId Region Currency Employment status Monthly income Debt-to-income 90d average balance 180d NSF count Computed score Outcome
sandbox-us-prime-001 US USD full_time 8200 0.22 5400 0 676 manual_review
sandbox-us-thin-002 US USD contract 4700 0.44 1400 1 537 declined
sandbox-jp-stable-003 JP JPY full_time 680000 0.29 510000 0 647 manual_review

Reason-code bands

Outcome Reason codes
approved INCOME_VERIFIED, LOW_UTILIZATION, STRONG_CASH_BUFFER
manual_review THIN_FILE, MODERATE_UTILIZATION, REVIEW_REQUIRED
declined HIGH_UTILIZATION, ELEVATED_OVERDRAFT_RISK, INSUFFICIENT_AFFORDABILITY

US and JP fixture behavior

The region-specific fixture helpers both reuse stable applicant IDs and stable evidence references.

Helper Consent lookup key Evidence reference Evidence feature set Snapshot feature fields
upsertUsFixtures() sandbox-applicant-us us-sandbox-stable-v2 cashflow_v2 avg_balance_90d, nsf_count_180d, monthly_income_estimate, debt_to_income
upsertJpFixtures() sandbox-applicant-jp jp-sandbox-stable-v2 cashflow_v2 avg_balance_90d, nsf_count_180d, monthly_income_estimate, debt_to_income

The US consent is created with purpose: "GENERAL_PERSONAL_FINANCE", the five data categories used by the sandbox flows, refresh permissions for accounts, balances, transactions, and income, and an expiration set 30 days ahead. The JP consent uses the same core data categories and refresh permissions, plus appiProvisionJson with article23: true and crossBorderTransfer: false.

Export payload shape

The JSON export is assembled as a single object containing tenant identity, API client identity, profile outcomes, consent details, and evidence snapshots.

Property Shape
generatedAt ISO timestamp string
tenant.id Tenant ID
tenant.name Tenant name
apiClient.clientId API client ID
apiClient.name API client name
profiles Array of seeded profile summaries
consents.us US consent export fields
consents.jp JP consent export fields
evidenceSnapshots.us US evidence export fields or null
evidenceSnapshots.jp JP evidence export fields or null

Console output contract

The script prints machine-readable key/value lines for downstream automation.

Output line Meaning
sandbox_tenant_id=... Tenant identifier created or reused by the script
sandbox_api_key=... Sandbox API client identifier
credit_profiles_seeded=... Number of profiles written into the tenant
us_consent_id=... Current US consent identifier
jp_consent_id=... Current JP consent identifier
dummy_data_json=... JSON artifact path, when JSON output is enabled
dummy_data_csv=... CSV artifact path, when CSV output is enabled

After the summary lines, the script emits a seeded_profiles= section containing one bullet per seeded profile with externalUserId, region, outcome, score, and decision_id.

Workspace Artifact Output Conventions

scripts/seed-sandbox-dummy-data.sh writes to workspace/artifacts by default.

Artifact files

File Format Contents When written
workspace/artifacts/sandbox-dummy-data.json JSON Full export payload with tenant, client, profiles, consents, and evidence snapshots OUTPUT_FORMAT=json or OUTPUT_FORMAT=both
workspace/artifacts/sandbox-dummy-data.csv CSV Flattened profile rows plus consent and evidence sections OUTPUT_FORMAT=csv or OUTPUT_FORMAT=both

CSV section layout

The CSV output is grouped into three sections separated by blank rows.

Section Header row Rows
Profiles external_user_id,region,outcome,score,decision_id One row per seeded profile
Consents consent_region,consent_id,applicant_id,status,expires_at US and JP consent rows
Evidence snapshots evidence_region,evidence_ref,feature_set,features_json US and JP evidence rows

Output validation rules

Condition Result
OUTPUT_FORMAT=json Only the JSON artifact is written
OUTPUT_FORMAT=csv Only the CSV artifact is written
OUTPUT_FORMAT=both Both artifacts are written
Any other value The script throws Unsupported OUTPUT_FORMAT=... and exits

These exported artifacts are the primary review surface for checking that a single sandbox tenant carries both regional profiles and both regional evidence snapshots without mixing identifiers across tenants.

Local API Validation Script

scripts/check-local-api.sh

This script validates a local API installation before the broader smoke tests run. It resolves runtime ports from the active Docker Compose stack, pushes the Prisma schema, seeds the development API client, and then executes the API checks.

Inputs and runtime resolution

Variable Default Purpose
PORT 4000 Local API port used to build BASE_URL
BASE_URL http://localhost:${PORT} API base URL for smoke checks
API_KEY dev-key API key used by the dev auth seed and downstream checks
AUTO_SEED_AUTH 1 Enables automatic dev auth seeding
DATABASE_URL inherited Used as the runtime Prisma target if present
REDIS_URL inherited Used as the runtime Redis target if present

The script also loads .env when present and resolves the published Postgres and Redis ports from docker-compose or docker compose.

Helper functions

Function Description
need() Fails fast if a required command is missing
dc() Wraps docker-compose or docker compose
published_port() Resolves the host port mapped to a container port

Validation flow

Step Action
1 Compute runtime database and Redis URLs from published container ports
2 Run pnpm -C packages/db prisma db push
3 Run ./scripts/seed-dev-auth.sh with the runtime database URL and API key
4 Run ./scripts/check-api.sh
5 Run ./scripts/check-all-api-paths.sh
6 Print ✅ Local API full check completed successfully.

Dependents

Script Role
scripts/seed-dev-auth.sh Creates the reusable dev tenant and API client used by local smoke checks
scripts/check-api.sh Performs the local API health and readiness validation step
scripts/check-all-api-paths.sh Exercises the regional smoke-test surface after auth seeding

README Sandbox Instructions

The root README sandbox instructions align with the same bootstrap contract used by the seed script. The documented entry point is pnpm seed:sandbox, and the operational knobs map directly to the script defaults.

README-aligned bootstrap contract

Concern README-facing value Backing script variable
Sandbox tenant name Stable reusable sandbox tenant TENANT_NAME
Sandbox API key Stable sandbox client key API_KEY
Sandbox client name Human-readable sandbox client CLIENT_NAME
Artifact format JSON, CSV, or both OUTPUT_FORMAT
Artifact destination Workspace artifact directory OUTPUT_DIR
Database target Local PostgreSQL instance or override DATABASE_URL

The README instruction set exists to make the sandbox setup repeatable for operators who need the same tenant, the same profiles, and the same evidence snapshots on every run.

Tenant Aware Demo Data Shape

Profile-to-decision relationship

The seed script does not create random demo data. Each profile is built from a fixed input object, converted into a normalized dataJson, scored deterministically, and then paired with a fresh decision record for that profile.

Field family Values used
Region US, JP
Currency USD, JPY
Employment status full_time, contract
Income metric monthlyIncome
Risk metric debtToIncome
Stability metric avgBalance90d
Negative signal nsfCount180d

Evidence snapshot alignment

Both regional evidence snapshots are aligned to the same feature family so reviewers can compare the export with decision outcomes.

Snapshot Feature family Fields
US cashflow_v2 90-day average balance, 180-day NSF count, monthly income estimate, debt-to-income
JP cashflow_v2 90-day average balance, 180-day NSF count, monthly income estimate, debt-to-income

This alignment makes the exported dataset suitable for validating tenant isolation across profiles, decisions, and evidence snapshots. It also keeps US and JP sandbox records comparable while still preserving regional identity and regional consent history.

Local Smoke Test Surface

scripts/check-all-api-paths.sh and scripts/test-use-cases.sh drive the broader validation surface.

These scripts confirm that the sandbox tenant and dev auth setup can reach the expected local API flows using the seeded key and request headers. They use curl, jq, Authorization or authorization, content-type: application/json when sending bodies, and x-request-id on each call.

Validation characteristics

Check What it proves
Public endpoints The local service is reachable and responds to basic health and readiness checks
Regional auth flows The seeded API key can initiate regional consent and token flows
Profile access flows The tenant-scoped demo identity can drive data access and feature generation flows
Evidence fetch Feature generation produces a stable evidence reference that can be read back
Decision replay The seeded evidence can be replayed through the decision path

Error Handling

Script Failure behavior
scripts/seed-sandbox-dummy-data.sh Exits on unsupported OUTPUT_FORMAT; shell settings stop on unset variables and failed commands
scripts/check-local-api.sh Stops immediately on any failed Prisma, auth-seeding, or API-check step
scripts/test-use-cases.sh Validates REGION before running and exits on missing curl or jq
scripts/check-all-api-paths.sh Uses curl -fsS, so non-2xx responses fail the smoke run

Dependencies

Dependency Role
Bash Entry point for both seeding and local validation scripts
Node.js Runs the inline Prisma-backed seed program
pnpm Invokes Prisma generation, db push, and repo scripts
Prisma Client Reads and writes tenant, client, profile, consent, decision, and evidence records
PostgreSQL Persistence layer for sandbox data
Redis Runtime dependency resolved by check-local-api.sh
curl HTTP smoke checks
jq Response inspection in the smoke scripts
Docker Compose or Docker Compose v2 Port discovery for local Postgres and Redis containers

Testing Considerations

Scenario What to verify
Repeated seeding The same tenant name reuses the same tenant record
API client reuse The same clientId updates the same client record
Profile stability The three demo profiles keep the same IDs and inputs on rerun
Decision refresh Previous profile decisions are removed before the new decision is created
US and JP separation Each region gets its own consent, evidence snapshot, and profile summary
Artifact correctness JSON and CSV outputs reflect the same tenant, client, and profile set
Local smoke coverage check-local-api.sh successfully reaches the validation script chain after auth seeding

Key Classes Reference

Class Location Responsibility
seed-sandbox-dummy-data.sh scripts/seed-sandbox-dummy-data.sh Seeds a reusable sandbox tenant, deterministic profiles, regional consent fixtures, and evidence snapshots
check-local-api.sh scripts/check-local-api.sh Prepares the local database and runs the local API validation chain
check-all-api-paths.sh scripts/check-all-api-paths.sh Executes the broader regional smoke-test checks against the local API
seed-dev-auth.sh scripts/seed-dev-auth.sh Seeds the development tenant and API client used by local validation
workspace/README.md workspace/README.md Defines the workspace memory update rule that accompanies meaningful sandbox changes
workspace/MEMORIES.md workspace/MEMORIES.md Records the sandbox seeding and artifact export decision for future edits