Nano Store - Ecommerce Docs
Developer Resourcesb2b-second-inventory

B2B Second Inventory Backend Architecture

Internal architecture of the bb phase 1 modules — composition, data model, separation invariants, audit, error contract and file map.

B2B Second Inventory (bb) — Backend Documentation

1. Module Scope

The bb module owns, in phase 1:

  • bb roles, bb staff and the assignable bb permission catalog
  • bb customers (separate from retail customers)
  • The bb_audit trail and its single writer
  • The separation filters that hide bb data from retail endpoints (these live in the retail modules but call bb helpers)

It does not own:

  • The role, admin_users and permission tables. bb reuses them; bb_role only marks which role rows are bb
  • Retail team, role and permission endpoints. They are filtered, not replaced
  • bb orders or pricing (later phases). Stock is phase 3: see the stock backend page
  • Any customer-facing or storefront endpoint

2. Composition

All bb files are under apps/api/src/modules/bb/. BbModule is registered in apps/api/src/app.module.ts.

PieceFile
Root modulebb.module.ts
Admin aggregateadmin/bb-admin-aggregate.module.ts
Role controller / serviceadmin/role/bb-role-admin.controller.ts, bb-role-admin.service.ts
Role permission-code checkadmin/role/bb-role-permission-codes.ts
Staff controller / serviceadmin/staff/bb-staff-admin.controller.ts, bb-staff-admin.service.ts
Permission catalog controller / serviceadmin/permission/bb-permission-admin.controller.ts, bb-permission-admin.service.ts
Customer controller / serviceadmin/customer/bb-customer-admin.controller.ts, bb-customer-admin.service.ts
Customer phone normaliseradmin/customer/bb-customer-phone.ts
Customer DB error mappingadmin/customer/bb-customer-db-errors.ts
Audit controller / service (read)admin/audit/bb-audit-admin.controller.ts, bb-audit-admin.service.ts
Audit writershared/bb-audit.service.ts
Audit value allowlist and diffingshared/bb-audit-redaction.ts
bb/retail lookupsshared/bb-scope.service.ts
Actor and IP snapshotshared/bb-request-context.ts
Retail-side filter helpersapps/api/src/common/authorization/bb-role-scope.ts
Permission catalog (bb modules)packages/db/src/authorization/permission-catalog.ts
Schemapackages/db/src/schema/bb/ (bb-role.ts, bb-audit.ts, bb-customer.ts)
Migrationpackages/db/src/migrations/0060_bb_foundation.sql

Every controller applies JwtAuthGuard and RoleGuard, then IpThrottlerGuard per route and @Permissions(...). The three create routes also apply IdempotentCreate with IdempotencyInterceptor; scopes are bb.role.create, bb.staff.create and bb.customer.create.


3. Data Model

Migration 0060_bb_foundation.sql adds three tables and alters none.

bb_role

Registry of which role rows are bb roles.

ColumnNotes
role_idPrimary key, FK to role.id, ON DELETE cascade
created_attimestamptz, default now()
created_by_admin_idFK to admin_users.id, ON DELETE set null

A bb role is a normal role row plus a bb_role row. A bb staff member is a normal admin_users row whose role_id is in bb_role. Role permissions use the existing role_permission rows.

bb_customers

ColumnNotes
id, public_idSerial key and unique UUID. Only public_id leaves the API
name, phone, email, company_name, address, pan_vat_number, notesAll nullable text
statusactive or disabled, default active
password_hash, email_verified_at, phone_verified_at, last_login_atReserved columns. No phase 1 endpoint reads or writes them
created_at, updated_at, deleted_atdeleted_at set means soft-deleted
created_by_admin_idFK to admin_users.id, ON DELETE set null

Constraints, all CHECKs unless noted:

  • chk_bb_customers_has_identity: at least one of name, phone, company_name
  • chk_bb_customers_phone_e164: ^\+[1-9][0-9]{6,14}$
  • chk_bb_customers_email: lower-cased, trimmed, 3 to 254 characters, contains @
  • chk_bb_customers_status, plus length and trim checks per text column
  • bb_customers_phone_live_unique and bb_customers_email_live_unique: unique indexes over live rows only (deleted_at IS NULL)

bb_audit

ColumnNotes
idbigserial, the cursor key
public_idUnique UUID
created_attimestamptz, default now()
actor_admin_idFK to admin_users.id, ON DELETE restrict
actor_name, actor_roleSnapshot at write time
actionMatches ^bb\.[a-z_]+\.[a-z_]+$
entity_typerole, staff or customer; must equal the middle segment of action
entity_public_idUUID of the changed entity
summaryAt most 500 characters
changesJSON array, default []
ipNever returned by the API

Actions written: bb.role.create, bb.role.update, bb.role.set_permissions, bb.role.delete, bb.staff.create, bb.staff.update, bb.staff.ban, bb.staff.unban, bb.customer.create, bb.customer.update, bb.customer.delete, bb.customer.restore.


4. Runtime Rules and Domain Invariants

The audit row commits with the write

BbAuditService.record takes the business transaction's executor, so an audit failure rolls the write back and a write cannot commit without its row. It also rejects an entity type that does not match the action, a summary over 500 characters, and an update or set_permissions action with no changes.

bb_audit is append-only

The trigger bb_audit_no_mutation (function bb_audit_reject_mutation()) raises on every row UPDATE and DELETE. TRUNCATE is not covered.

Audit values are an allowlist

BB_AUDIT_VALUE_FIELDS lists the only fields whose values are stored: customer status; role name, description; staff name, banned. Any other changed field is recorded as { "field": "...", "changed": true } with no before or after. Permission changes are recorded as permissionCodes with before.removed and after.added. A role change on staff is recorded by role name.

bb lookups are inner joins on bb_role

BbScopeService.assertBbRole and assertBbStaff inner-join bb_role, so a retail role or retail admin is indistinguishable from a missing one. A missing bb role is 404 BB_ROLE_NOT_FOUND when it is in the route and 400 when it is in the request body.

Retail endpoints cannot see or change bb

Retail surfaceBehavior
Team list and get (team.service.ts)Filtered with notBbRole
Team update, ban, unban404 TEAM_USER_NOT_FOUND for bb staff (assertNotBbStaffMutation)
Team create with a bb role400 TEAM_ROLE_NOT_FOUND
Role list (role.service.ts)Filtered with notBbRole; permission lists drop BB_* codes
Role get, update, delete on a bb role404 ROLE_NOT_FOUND
Role-permissions write on a bb role404 ROLE_NOT_FOUND
Role-permissions write containing a BB_* code400 ROLE_PERMISSION_BB_CODE_NOT_ALLOWED
Permissions list (permissions.service.ts)Excludes modules with the BB_ prefix

notBbRole is an uncorrelated NOT IN (SELECT "bb_role"."role_id" FROM "bb_role") on purpose; a correlated subquery binds to the wrong column in drizzle and empties the list.

Assignable permissions

The prefix test is isBbPermissionCode (BB_). The bb modules are BB_Roles, BB_Staff, BB_Audit, BB_Customers, each with actions CREATE, READ, UPDATE, DELETE, RESTORE. A bb role may hold only BB_Audit and BB_Customers codes (BB_ASSIGNABLE_MODULES). Any other code, or a code not yet synced to the permission table, is 400 BB_PERMISSION_NOT_ASSIGNABLE with details.codes. Unsynced codes add details.reason: "not_synced".

scripts/sync-permissions.ts grants superadmin every non-BB_ code; superadmin reaches bb routes through the guard bypass, not through role rows.

Self-targeting is blocked

Role update, permission replacement and delete refuse the actor's own role (403 ROLE_SELF_TARGET_FORBIDDEN). Staff update runs assertMayUpdateTeamMember (403 TEAM_SELF_ROLE_CHANGE_FORBIDDEN on a self role change). Staff ban refuses self (403 TEAM_SELF_BAN_FORBIDDEN) and superadmin (403 TEAM_SUPERADMIN_PROTECTED).

Role deletion needs zero holders

remove locks the role row and refuses with 409 ROLE_IN_USE while any admin_users row holds it, banned included.

Customer constraint errors are mapped

The service validates first, then maps Postgres errors from bb-customer-db-errors.ts: 23514 on chk_bb_customers_has_identity, _phone_e164, _email or any other chk_bb_customers_* becomes the matching 400 code; 23505 on the live-unique indexes becomes 409 with details { field, conflictingPublicId }.

Phone normalisation

bb-customer-phone.ts accepts only digits, spaces, ( ) . - and one leading +, parses with default region NP through libphonenumber-js, and rejects anything invalid with 400. A rejected input is never repaired.

Customer reads never load credentials

Reads select a fixed column set and map field by field in toBbCustomerDto. The integer id, password_hash, verification timestamps and created_by_admin_id are never returned.

Audit reads are cursor-paginated

GET /admin/bb/audit orders by id descending. before_seq is the cursor and nextCursor is the last returned id as a string, or null on the last page. The ids are bigint; the comparison casts in SQL.


5. Configuration

ItemWhereValue
Read throttleRATE_LIMITS.ADMIN_READ30 per 60 s per IP
Write throttleRATE_LIMITS.ADMIN_WRITE10 per 60 s per IP
Role list capBB_ROLE_LIST_MAX in bb-role-admin.service.ts100
Customer and staff page sizeDTOdefault 20, max 100
Phone default regionDEFAULT_REGION in bb-customer-phone.tsNP

No new environment variable is introduced.


6. Security and Operational Controls

  • ip and the integer ids never leave the API. Audit DTOs are mapped field by field.
  • Customer list endpoints reject ?pagination=false with 400 so a page never holds more than size rows.
  • Unsupported query keys on staff, customer and audit lists are 400 (global forbidNonWhitelisted).
  • Deploy in a quiet window. The migration sets lock_timeout = '5s' and its new foreign keys take SHARE ROW EXCLUSIVE on role and admin_users, blocking writes to them until the migrate batch commits. A timeout aborts the batch with nothing applied; re-run it.
  • Rollback. packages/db/src/migrations/down/0060_bb_foundation.down.sql refuses while any bb table holds a row, so 0060 is forward-fix only after first use.
  • Run the permission sync after deploy so the BB_* rows exist; until then, assigning a code is 400 BB_PERMISSION_NOT_ASSIGNABLE with reason: "not_synced".

7. Error Contract

CodeHTTPRaised by
BB_ROLE_NOT_FOUND404 route, 400 bodyBbScopeService.assertBbRole
BB_STAFF_NOT_FOUND404BbScopeService.assertBbStaff
BB_PERMISSION_NOT_ASSIGNABLE400assertAssignablePermissionIds
BB_AUDIT_NOT_FOUND404BbAuditAdminService.findOne
BB_AUDIT_RANGE_INVALID400from later than to
BB_CUSTOMER_NOT_FOUND404Customer service (missing, or deleted where a live row is required)
BB_CUSTOMER_IDENTITY_REQUIRED400No name, phone or company
BB_CUSTOMER_PHONE_INVALID400Normaliser or phone CHECK
BB_CUSTOMER_EMAIL_INVALID400Email CHECK
BB_CUSTOMER_FIELD_INVALID400Any other chk_bb_customers_* CHECK
BB_CUSTOMER_PHONE_TAKEN / BB_CUSTOMER_EMAIL_TAKEN409Live-unique index; create, update, restore
ROLE_PERMISSION_BB_CODE_NOT_ALLOWED400Retail role-permissions write

All are defined in apps/api/src/common/types/error-codes.ts (lines 1638 to 1658). The bb routes also reuse ROLE_* and TEAM_* codes; see the API Reference.

Precedence on staff create: bb role lookup (400), assignment authority, email in use (409), phone in use (409), then the transaction, where the same checks re-run through constraint mapping. On audit list: query validation (400), pagination (422), then range (400).


8. File Map

apps/api/src/modules/bb/
  bb.module.ts
  admin/
    bb-admin-aggregate.module.ts
    role/        controller, service, bb-role-permission-codes.ts, dto/
    staff/       controller, service, bb-staff-availability.ts, dto/
    permission/  controller, service, dto/
    customer/    controller, service, bb-customer-phone.ts, bb-customer-db-errors.ts, dto/
    audit/       controller, service, dto/
  shared/
    bb-audit.service.ts  bb-audit-redaction.ts  bb-audit.types.ts
    bb-scope.service.ts  bb-request-context.ts  bb-pg-error.ts  bb-shared.module.ts
apps/api/src/common/authorization/bb-role-scope.ts
packages/db/src/schema/bb/
packages/db/src/migrations/0060_bb_foundation.sql
packages/db/src/migrations/down/0060_bb_foundation.down.sql

See Also