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_audittrail 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_usersandpermissiontables. bb reuses them;bb_roleonly marks whichrolerows 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.
| Piece | File |
|---|---|
| Root module | bb.module.ts |
| Admin aggregate | admin/bb-admin-aggregate.module.ts |
| Role controller / service | admin/role/bb-role-admin.controller.ts, bb-role-admin.service.ts |
| Role permission-code check | admin/role/bb-role-permission-codes.ts |
| Staff controller / service | admin/staff/bb-staff-admin.controller.ts, bb-staff-admin.service.ts |
| Permission catalog controller / service | admin/permission/bb-permission-admin.controller.ts, bb-permission-admin.service.ts |
| Customer controller / service | admin/customer/bb-customer-admin.controller.ts, bb-customer-admin.service.ts |
| Customer phone normaliser | admin/customer/bb-customer-phone.ts |
| Customer DB error mapping | admin/customer/bb-customer-db-errors.ts |
| Audit controller / service (read) | admin/audit/bb-audit-admin.controller.ts, bb-audit-admin.service.ts |
| Audit writer | shared/bb-audit.service.ts |
| Audit value allowlist and diffing | shared/bb-audit-redaction.ts |
| bb/retail lookups | shared/bb-scope.service.ts |
| Actor and IP snapshot | shared/bb-request-context.ts |
| Retail-side filter helpers | apps/api/src/common/authorization/bb-role-scope.ts |
| Permission catalog (bb modules) | packages/db/src/authorization/permission-catalog.ts |
| Schema | packages/db/src/schema/bb/ (bb-role.ts, bb-audit.ts, bb-customer.ts) |
| Migration | packages/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.
| Column | Notes |
|---|---|
role_id | Primary key, FK to role.id, ON DELETE cascade |
created_at | timestamptz, default now() |
created_by_admin_id | FK 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
| Column | Notes |
|---|---|
id, public_id | Serial key and unique UUID. Only public_id leaves the API |
name, phone, email, company_name, address, pan_vat_number, notes | All nullable text |
status | active or disabled, default active |
password_hash, email_verified_at, phone_verified_at, last_login_at | Reserved columns. No phase 1 endpoint reads or writes them |
created_at, updated_at, deleted_at | deleted_at set means soft-deleted |
created_by_admin_id | FK to admin_users.id, ON DELETE set null |
Constraints, all CHECKs unless noted:
chk_bb_customers_has_identity: at least one ofname,phone,company_namechk_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 columnbb_customers_phone_live_uniqueandbb_customers_email_live_unique: unique indexes over live rows only (deleted_at IS NULL)
bb_audit
| Column | Notes |
|---|---|
id | bigserial, the cursor key |
public_id | Unique UUID |
created_at | timestamptz, default now() |
actor_admin_id | FK to admin_users.id, ON DELETE restrict |
actor_name, actor_role | Snapshot at write time |
action | Matches ^bb\.[a-z_]+\.[a-z_]+$ |
entity_type | role, staff or customer; must equal the middle segment of action |
entity_public_id | UUID of the changed entity |
summary | At most 500 characters |
changes | JSON array, default [] |
ip | Never 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 surface | Behavior |
|---|---|
Team list and get (team.service.ts) | Filtered with notBbRole |
| Team update, ban, unban | 404 TEAM_USER_NOT_FOUND for bb staff (assertNotBbStaffMutation) |
| Team create with a bb role | 400 TEAM_ROLE_NOT_FOUND |
Role list (role.service.ts) | Filtered with notBbRole; permission lists drop BB_* codes |
| Role get, update, delete on a bb role | 404 ROLE_NOT_FOUND |
| Role-permissions write on a bb role | 404 ROLE_NOT_FOUND |
Role-permissions write containing a BB_* code | 400 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
| Item | Where | Value |
|---|---|---|
| Read throttle | RATE_LIMITS.ADMIN_READ | 30 per 60 s per IP |
| Write throttle | RATE_LIMITS.ADMIN_WRITE | 10 per 60 s per IP |
| Role list cap | BB_ROLE_LIST_MAX in bb-role-admin.service.ts | 100 |
| Customer and staff page size | DTO | default 20, max 100 |
| Phone default region | DEFAULT_REGION in bb-customer-phone.ts | NP |
No new environment variable is introduced.
6. Security and Operational Controls
ipand the integer ids never leave the API. Audit DTOs are mapped field by field.- Customer list endpoints reject
?pagination=falsewith 400 so a page never holds more thansizerows. - 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 takeSHARE ROW EXCLUSIVEonroleandadmin_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.sqlrefuses 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 400BB_PERMISSION_NOT_ASSIGNABLEwithreason: "not_synced".
7. Error Contract
| Code | HTTP | Raised by |
|---|---|---|
BB_ROLE_NOT_FOUND | 404 route, 400 body | BbScopeService.assertBbRole |
BB_STAFF_NOT_FOUND | 404 | BbScopeService.assertBbStaff |
BB_PERMISSION_NOT_ASSIGNABLE | 400 | assertAssignablePermissionIds |
BB_AUDIT_NOT_FOUND | 404 | BbAuditAdminService.findOne |
BB_AUDIT_RANGE_INVALID | 400 | from later than to |
BB_CUSTOMER_NOT_FOUND | 404 | Customer service (missing, or deleted where a live row is required) |
BB_CUSTOMER_IDENTITY_REQUIRED | 400 | No name, phone or company |
BB_CUSTOMER_PHONE_INVALID | 400 | Normaliser or phone CHECK |
BB_CUSTOMER_EMAIL_INVALID | 400 | Email CHECK |
BB_CUSTOMER_FIELD_INVALID | 400 | Any other chk_bb_customers_* CHECK |
BB_CUSTOMER_PHONE_TAKEN / BB_CUSTOMER_EMAIL_TAKEN | 409 | Live-unique index; create, update, restore |
ROLE_PERMISSION_BB_CODE_NOT_ALLOWED | 400 | Retail 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.sqlSee Also
B2B Second Inventory Feature Overview
Phase 1 of the bb (B2B second inventory) area — a separate staff, role and customer surface with its own permissions and audit trail, kept apart from the retail admin.
B2B Second Inventory API Reference
Endpoint reference for the bb phase 1 admin API — roles, permissions, staff, customers and audit — with contracts and error codes.