Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/ency07/B2B-import/llms.txt

Use this file to discover all available pages before exploring further.

B2B Import ERP ships with a dedicated TypeScript test script for every functional module. Each script is invoked via ts-node and connects to Supabase using the pg client or the Supabase JS client directly — no testing framework is required. The scripts validate SQL migrations syntactically (table definitions, triggers, RLS policies) when environment credentials are absent, and execute full live integration tests — including CRUD operations, state machine transitions, trigger behavior, and cross-tenant RLS isolation — when credentials are provided.

Prerequisites for Testing

Before running any test script, ensure the following are in place:

Migrations Applied

All Supabase migrations have been executed against your development database, including the seed_master_data migration that creates demo companies, roles, and users.

Environment Credentials

.env.local contains valid NEXT_PUBLIC_SUPABASE_URL (or SUPABASE_URL) and SUPABASE_SERVICE_ROLE_KEY. Scripts fall back to static SQL validation if these are absent.

Dev Server Not Required

Test scripts run as standalone Node.js processes via ts-node. You do not need npm run dev to be running when executing scripts.
Test scripts insert, mutate, and delete real data. Always run them against a dedicated development or staging database. Never point test scripts at a production Supabase project — they create and clean up temporary tenants and users, but failures mid-run can leave partial data behind.

Available Test Scripts

Every module has a corresponding npm script that maps to a ts-node invocation of its script file under scripts/.
ModuleCommandWhat It Tests
Multi-tenancynpm run test:multitenantRLS isolation between tenants — verifies that data inserted for Tenant A is invisible to Tenant B queries
Clientsnpm run test:clientsClient CRUD, auto-generated client_code sequence, tax_id uniqueness per tenant, contact primary-swap trigger, soft deletes, and business_events emission
Requirementsnpm run test:requirementsRequirement creation and full state machine transitions (BORRADOR → NUEVO → EN_REVISION → DIAGNOSTICO → COTIZACION → APROBACION → OT_GENERADA)
Quotesnpm run test:quotesQuote creation, line-item auto-calculation, header total rollup triggers, versioning (previous version set to VENCIDA), rejection/cancellation traceability, and integration with requirements state machine
Approvalsnpm run test:approvalsApproval workflow creation, multi-level escalation, resolution (approve/reject), and audit trail
Jobsnpm run test:jobsWork order lifecycle from creation through scheduling, start, pause, completion, and closure, including evidence attachment
Inventorynpm run test:inventoryStock movements (entrada, salida, transferencia, ajuste), purchase order creation, and stock balance queries
Invoicesnpm run test:invoicesInvoice generation from approved quotes/jobs, tax application, PDF generation flags, status transitions, and voiding
Warrantiesnpm run test:warrantiesWarranty creation from closed jobs, approval workflow, intervention records, and warranty closure
Websitenpm run test:websiteCMS content records, public product catalog entries, and UTM tracking metadata
Wizardnpm run test:wizardEnd-to-end wizard form submission, automatic lead creation in CRM, and email notification queue
CRMnpm run test:crmLead scoring rules, pipeline stage transitions, opportunity creation, win/loss recording
Marketingnpm run test:marketingCampaign creation, contact list segmentation, send-queue population, and analytics event recording
Dashboardsnpm run test:dashboardsKPI view queries, aggregation correctness, and per-tenant data scoping on summary tables
Costsnpm run test:costosJob cost line entry, labor vs. material split, actual vs. budgeted variance calculations
Profitabilitynpm run test:rentabilidadMargin calculations per job, per client, and per period — validates computed columns and reporting views
Documentsnpm run test:documentosDocument uploads (DIAGNOSTIC, QUOTE, APPROVAL types), storage path recording, checksum storage, soft delete, and retrieval by entity
Notificationsnpm run test:notificacionesNotification queue insertion, delivery status transitions, and per-user preference filtering
Security & Auditnpm run test:security-auditAudit log completeness, RLS policy enforcement across all core tables, and privilege escalation prevention
Performancenpm run test:hardeningQuery execution times on large datasets, index coverage for common filter patterns, and connection pooler behavior
UATnpm run test:uatFull user acceptance test suite covering all modules in sequence with representative demo data
Go-Livenpm run test:go-liveProduction readiness checklist — verifies migrations, RLS, seed isolation, auth config, and performance thresholds
Settingsnpm run test:settingsTenant-level configuration persistence, white-label settings CRUD, and configuration inheritance
White Labelnpm run test:white-labelPer-tenant branding record creation, CSS variable injection for primary/secondary colors, logo URL storage
Integrationsnpm run test:integrationsExternal provider connectivity checks (payment gateway sandbox, email provider, storage)
Advanced Adminnpm run test:advanced-adminRole creation, custom permission overrides per tenant, and super-admin privilege boundaries

Utility Scripts

Beyond the npm run test:* scripts, two standalone utility scripts help with development and database management. They are invoked directly with ts-node and do not have package.json shortcuts.
ScriptLocationPurpose
check-catalog.tsRepo rootQueries product_categories, product_subcategories, and products tables via supabaseAdmin and prints a live summary. Useful for quickly verifying that the product catalog seed was applied correctly.
combine-migrations.tsscripts/Reads every .sql file in supabase/migrations/ in chronological order, concatenates them into a single supabase_combined_migrations.sql file at the project root, and prepends a generated header. Use this to produce a full-database snapshot for auditing or external review.
Run them directly:
# Verify product catalog contents against the live database
ts-node check-catalog.ts

# Combine all migration files into a single SQL snapshot
ts-node scripts/combine-migrations.ts
Both scripts require SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY (or the hardcoded values inside the scripts) to connect to Supabase.

Running a Test

Each script is invoked with a single npm command. For example, to run the clients test:
npm run test:clients
# Executes: ts-node scripts/test-clients.ts
If SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are present in .env.local, the script connects to the live database and runs full integration assertions. If credentials are absent, it falls back to static validation of the SQL migration file — confirming table definitions, trigger names, and RLS declarations are present.
# Example output (live database mode)
--------------------------------------------------
INICIANDO VALIDACIÓN SINTÁCTICA DEL MODELO CLIENTES Y SEDES...
--------------------------------------------------
 Tenants creados: A (uuid-a), B (uuid-b)
 TC-CLI-01: Códigos autogenerados: CLI-000001, CLI-000002
 TC-CLI-02: Código tras intento de alteración: CLI-000001
 TC-CLI-03: Bloqueo de TAX_ID duplicado en mismo Tenant: Bloqueado Correctamente
 TC-CLI-04: Mismo TAX_ID permitido en tenants cruzados.
 TC-CON-01: Reemplazo automático de contacto principal.
 TC-CON-02: Soft delete ejecutado.
 TC-STE-01: Registro de sede comercial exitoso.
 TC-EVT-01, 02: Eventos semánticos generados y auditados correctamente.

[ÉXITO] Estructura sintáctica, triggers y modelo RLS validados correctamente.
Run scripts in the order below to respect cross-module dependencies. Each layer depends on data created by the one before it.
  1. Foundationnpm run test:multitenant
    Confirm RLS isolation is working before any other module can be trusted.
  2. Core commerce pipelinenpm run test:clientsnpm run test:requirementsnpm run test:quotesnpm run test:approvals
    Clients must exist before requirements; requirements before quotes; quotes before approvals.
  3. Operations pipelinenpm run test:jobsnpm run test:inventorynpm run test:invoices
    Jobs depend on approved quotes; inventory movements reference job records; invoices close the billing loop.
  4. Lead generationnpm run test:wizardnpm run test:crm
    The wizard creates leads that the CRM pipeline then processes.
  5. Governancenpm run test:security-auditnpm run test:hardening
    Run after all data-creating tests so the audit log and performance tests have realistic data to evaluate.
  6. Sign-offnpm run test:uatnpm run test:go-live
    UAT sweeps all modules end-to-end; go-live is the final production readiness gate.

Demo Users

The seed migration creates 106 demo user accounts distributed across both demo tenant companies, covering every role in the system:
RoleCount
Super Admin1
Admin Empresa2
Gerentes5
Directores5
Jefes10
Comerciales10
Ingenieros10
Técnicos15
Almacén5
Cartera5
Auditores3
Clientes (portal)25
Proveedores10
Total106
All 106 demo accounts are created with email_confirmed_at already set — no email verification step is needed when signing in as a demo user during development testing.
Before running any test scripts, the seed migration must have provisioned the full demo dataset: 25 demo companies, 106 users, all roles, all site records, all permission assignments, the approvals structure, a functional client portal, and a payment gateway sandbox connection. See the pre-test checklist in docs/10_pruebas/Antes de iniciar pruebas.txt for the complete bootstrap requirement list.

Manual UAT Coverage

The master test plan (docs/10_pruebas/13 PLAN MAESTRO DE PRUEBAS OPERATIVAS.txt) requires manual validation in addition to the automated scripts. Every UI surface must be verified by a human tester:
  • All buttons, icons, and links render and respond correctly
  • All filters, modals, and search inputs return accurate results
  • All exports (PDF, Excel) and imports produce valid files
  • All widgets, KPI cards, and reports display correct aggregated data
The UAT dataset targets 25 demo companies (across Manufactura, Minería, HVAC, Data Center, and Logística sectors) with 250 contacts, 500 leads, 300 quotes, 200 jobs, 200 invoices, 300 inventory movements, and 100 warranties. A module is not considered passing until both the automated script and a manual tester sign off with screenshot evidence, result, user, date, and observations recorded.
The npm run test:go-live script is the final production readiness gate. It runs a comprehensive checklist covering all modules, verifying migration completeness, RLS policy coverage, auth configuration, performance thresholds, and seed data isolation. A clean exit from this script is the recommended minimum bar before cutting a production release.

Build docs developers (and LLMs) love