Complete feature list, actor journeys, state flows, business rules, edge cases, and diagrams for the Catalog module.
Use this page for the catalog domain: what it does for users, admins, workers and systems, and how each flow behaves from start to finish.
| Source Type | Files or Docs | What Was Extracted |
|---|
| Technical design | catalog-slug.service.ts, catalog-search.service.ts, catalog.constants.ts, workers/catalog-job-state.ts | Slug ownership, search form, job state machine, advisory lock |
| API | admin/{category,brand,brand-series,job}/*.controller.ts, customer/**/*.controller.ts, bulk controllers | Route surface, permissions, rate limits |
| Backend | catalog-category-{write,admin,bulk,tree}.service.ts, catalog-brand*.service.ts, catalog-import-*.ts, catalog-export.service.ts | Business rules, transactions, side effects |
| Schema | packages/db/src/schema/catalog/*.ts | Constraints, partial indexes, slug tables |
| Jobs | packages/jobs/src/index.ts | Queue contracts, payloads |
| Field | Value |
|---|
| Module | catalog |
| Submodule | category (tree), brand, brand series, tag (newer), jobs (import/export) |
| Primary user value | The store's taxonomy — categories, brands and brand series — with permanent, honest URLs and a unified search |
| Actors | Guest, admin, worker/system |
| Main entry points | /api/admin/catalog/{categories,brands,brand-series,jobs}, /api/mobile/catalog/{categories,brands,series,search}, /api/admin/catalog/tags |
| Main outputs | Tree/list/detail responses, per-item bulk results, CSV imports/exports, activity records, cache invalidations |
| Related docs | API, Backend |
| Actor | Can Do | Cannot Do | Auth Requirement | Notes |
|---|
| Guest | Browse categories (root list, detail, breadcrumbs), brands, series, search, suggestions, tags | Admin mutations, see hidden/deleted entities | None (@Public()) | Hidden/deleted → 404 on detail routes; rate limits PUBLIC_READ 60/min, PUBLIC_SEARCH 60/min, PUBLIC_SUGGEST 300/min |
| Admin | Full CRUD + bulk + reorder + tree ops + import/export jobs for all three entities, tag CRUD | Delete a category with active children, delete a brand with active series, delete a category, brand or series that live products still use, permanently delete anything | Admin JWT + Categories_* / Brands_* / BrandSeries_* / Catalog_* / Tags_* | Every mutation writes activity + invalidates cache; category tree mutations serialise on an advisory lock |
| Worker/system | Run import/export jobs, sweep stalled jobs | — | BullMQ worker | Lease-based claim; cooperative cancellation |
| Capability | Surface | Actor | Route/Trigger | State Read | State Written | Linked API Section |
|---|
| List siblings | Admin | Admin | GET /api/admin/catalog/categories | One tree level | — | API §3 |
| Full tree | Admin | Admin | GET /api/admin/catalog/categories/tree | Non-deleted rows | — | API §3 |
| Category detail/breadcrumbs | Admin | Admin | GET /:publicId(/:breadcrumbs) | Row + ancestors | — | API §3 |
| Create/update/move/visibility/delete/restore category | Admin | Admin | POST/PATCH/DELETE on /api/admin/catalog/categories | Row + parent | Category rows, slug rows | API §3 |
| Bulk category ops + reorder | Admin | Admin | POST /bulk/*, PATCH /reorder | Rows | Rows + display_order | API §3.6–3.7 |
| Brand CRUD + bulk + reorder | Admin | Admin | /api/admin/catalog/brands | Rows | Rows, slugs | API §4 |
| Series CRUD + bulk + reorder | Admin | Admin | /api/admin/catalog/brand-series | Rows + brand | Rows, slugs | API §5 |
| Import/export jobs | Admin/worker | Admin → system | /api/admin/catalog/jobs | Job rows | Job rows, CSV | API §6 |
| Category/brand/series browsing | Storefront | Guest | /api/mobile/catalog/{categories,brands,series} | Visible rows | — | API §7–9 |
| Search + suggestions | Storefront | Guest | /api/mobile/catalog/search | Visible rows | — | API §10 |
| Tag CRUD + listing | Admin/guest | Both | /api/admin/catalog/tags, /api/mobile/catalog/tags | Tag rows | Tag rows | Products API §4 |
A guest opens the storefront. The frontend fetches root categories, then drills into a category detail by slug and renders breadcrumbs. Category visibility is inherited: a visible category under a hidden or deleted ancestor is unreachable.
| Branch | Condition | Behavior | Error/Result |
|---|
| Retired slug | Slug owned by the entity, not current | 200 + canonicalSlug — frontend redirects | No 3xx from the API |
| Hidden/deleted entity | Not visible on storefront | 404 on both slug branches | CATEGORY_NOT_FOUND-style |
| Parent hidden | Visible child under hidden parent | Child unreachable everywhere | 404 / excluded |
| Tag filter resolves empty | Unknown tag slugs | Empty result, never the whole catalogue | Empty data |
Search covers category, brand and brand series with pg_trgm: the % operator bounds candidates in WHERE (index-accelerated), similarity() ranks in ORDER BY — never in WHERE, which would force a full scan. A term under 2 characters is "no search" → unfiltered visible list. Category visibility is enforced inside the SQL (hidden/deleted ancestors block); series visibility requires a visible brand.
Permission Categories_CREATE, ADMIN_WRITE 10/min. Inside the transaction: advisory tree lock first, parent resolve + depth check (max 6), slug generation against the ownership table, insert + claim slug.
The only parent-mutating route: PATCH /:publicId/move. Guards: cycle prevention (cannot move under own descendant), depth cap for the whole subtree, parent liveness. parent_id and depth are rewritten in one statement.
Delete requires no active children (409 CATEGORY_HAS_ACTIVE_CHILDREN) and no live products (409 CATEGORY_HAS_ACTIVE_PRODUCTS; BRAND_HAS_ACTIVE_PRODUCTS and BRAND_SERIES_HAS_ACTIVE_PRODUCTS for brands and series). A delete that cannot take its locks within CATALOG_DELETE_LOCK_TIMEOUT_MS answers 409 CATALOG_RESOURCE_BUSY. Bulk delete processes deepest-first so parents and children can go together, and reports a blocked id in failures. Restore requires a live parent (409 CATEGORY_PARENT_DELETED); a series restore requires a live brand (409 BRAND_SERIES_BRAND_DELETED). Slugs are never released by delete, so restore never fails on a taken slug.
CSV/XLSX import (25 MB, 50,000 rows) validates every row before writing anything; a category file's internal parent graph must be acyclic. Export caps at 50,000 matching rows. Import submit re-checks the entity-specific create permission (Categories_CREATE / Brands_CREATE / BrandSeries_CREATE) beyond route-level Catalog_CREATE.
The declared entity is checked against the file header before any row is built — validateImportHeaderForEntity in catalog-import-row.ts. The three entity column lists overlap almost completely (category and brand_series differ by exactly one column, parentSlug against brandSlug), so a file uploaded under the wrong entity parses into shape-valid rows and a job that reports success. The guard rejects a header on either of two conditions: the declared entity's discriminating column is absent (parentSlug for category, logoUrl for brand, brandSlug for brand_series), or the header carries a column that belongs to another catalog entity and not to this one. Both are needed — the category / brand_series pair differs by one column in each direction, so a single check misses one direction. Columns owned by no catalog entity are ignored, as the row builders already do.
A rejection fails the whole job with one error at row: 0 under CATALOG_IMPORT_HEADER_MISMATCH. row: 0 means the file itself, not a 1-based data row; the message names both the expected column list and the file's own header. Product and inventory imports have no equivalent guard. Each accepts a single entity, so there is no wrong-entity hazard of this shape, but a wrong file there still produces N per-row errors rather than one file-level message.
CSV parsing goes through the shared record reader common/utils/csv-records.util.ts, used by all three importers — catalog, products and inventory. It streams logical records rather than physical lines, so a quoted field may contain embedded newlines, commas and escaped quotes; row numbers and the 50,000-row cap both count logical records, not lines. Row counts consequently changed for any file with multi-line fields: a product file that previously parsed as 149 rows, 84 of them fragments of a description, now parses as the 65 records it actually holds. An unterminated quote at end of file rejects the upload and names the row the quote opened in (CATALOG_IMPORT_FILE_INVALID, and the product and inventory equivalents).
| Entity | From | Event/Action | To | Guard Condition | Side Effects |
|---|
category_slug | current | rename | retired | Demote BEFORE promote (partial unique index non-deferrable) | retired_at stamped; re-adoption restores original URL |
any *_slug | any | soft delete | (unchanged) | Slugs never released on delete | Restore can never fail on a slug |
| Entity | From | Event/Action | To | Guard Condition | Side Effects |
|---|
catalog_job | queued | claim | processing | status = 'queued' OR processing past TTL | started_at stamped |
catalog_job | processing | complete | completed | Terminal write matches zero rows → throws CATALOG_JOB_NOT_PROCESSING | finished_at in same UPDATE |
catalog_job | queued/processing | cancel | cancelled | Not terminal | Cooperative abort for running imports |
| Flow | DB Writes | Cache Effects | Jobs | Realtime | Analytics | Notifications |
|---|
| Category create/move/delete/restore | Category + slug rows | catalog_category + search | — | — | — | — |
| Brand/series writes | Rows + slugs | catalog_brand / catalog_series + search | — | — | — | — |
| Reorder | display_order | owning domain | — | — | — | — |
| Import | Entity rows + catalog_job | owning domain | catalog.import_entities | — | — | — |
| Export | catalog_job + CSV | — | catalog.export_entities | — | — | — |
| All mutations | Row + activity record | domain tags + Redis patterns | — | — | — | — |
| Scenario | Trigger | User/System Experience | Recovery | Source |
|---|
| Concurrent tree moves | Two moves cross | Both validate against a snapshot | Advisory lock serialises — second waits | catalog.constants.ts |
| Import validation failure | Any row invalid / cycle | Job failed, nothing written | Fix file, resubmit | catalog-import.service.ts |
| Import under the wrong entity | File header does not match the declared entity | Job failed with one row: 0 error naming both column sets, nothing written | Resubmit under the correct entity | catalog-import-row.ts |
| Unterminated quoted field | A quote is never closed before end of file | Upload rejected, no rows parsed | Fix the file's quoting | csv-records.util.ts |
| Import cancelled mid-run | Admin cancels | Cooperative abort, rollback | Resubmit | catalog-job-state.ts |
| Worker died mid-run | Crash | Job stuck processing | Sweep fails it after 15 min TTL | catalog-job-sweep.* |
| Slug generation exhausted | 100 attempts taken | 409 CATALOG_SLUG_GENERATION_FAILED | Rename source | catalog-slug.service.ts |
- Actor capability diagram — §3/§4.
- High-level module flow — §6.1/§6.2 admin flows.
- Sequence diagram per major flow — §5.1.
- State machine diagram — §7.2 (jobs), §7.1 (slugs).
- Data side-effect diagram — §9.
- Error branch diagram — §10.
| Feature | Minor Behavior | Actor | Trigger | User/System Result | Backend Side Effect | Source |
|---|
| Category list | Sibling listing with deletedOnly | Admin | GET /categories?deletedOnly=true | Restore workflow | Partial index idx_category_parent_order | catalog-category-admin.service.ts |
| Tree | 2,000-node cap | Admin | GET /tree | 400 CATALOG_TREE_TOO_LARGE | In-app bound, not truncation | |
| Move | Re-root (parentId: null) | Admin | PATCH /move | Moves to root | One-statement subtree rewrite | catalog-category-tree.service.ts |
| Rename | Undo | Admin | Rename back | Original URL restored | Re-adoption of owned slug | catalog-slug.service.ts |
| Bulk delete | Deepest-first ordering | Admin | POST /bulk/delete | Parent+child batch works | Sorted by depth desc | catalog-category-bulk.service.ts |
| Bulk restore | Shallowest-first | Admin | POST /bulk/restore | Parent-first ordering | Sorted by depth asc | |
| Reorder | Exact sibling set | Admin | PATCH /reorder | 409 on mismatch | Set equality check | |
| Import | Slug-based parents | Admin | POST /jobs/import | Nothing written on any error | All-or-nothing | catalog-import.service.ts |
| Export | Formula-injection escape | Admin | Export download | ' prefix on = + - @ cells | CSV escaping | catalog-export.service.ts |
| Search | Term < 2 chars | Guest | ?search=ab | Unfiltered list | "No search" | catalog-search.service.ts |
| Search | Cursor stability | Guest | Any page | Stable order | ORDER BY ... id tiebreak | |
| Slug routes | Retired slug | Guest | Old URL | 200 + canonicalSlug | Ownership table lookup | catalog-slug.service.ts |
| Rule | Business Reason | Actor Impact | Enforced In | API Impact | Backend Impact | Tests |
|---|
| Slug never re-hands to a different entity | Old links must stay honest | Guest URLs never repoint | One UNIQUE over current+retired | Storefront resolves any owned slug | Slug ownership tables | catalog-slug.service.spec.ts |
| Depth capped at 6 | Tree stays navigable | Admin gets 409 on deep create/move | DB CHECK + service | Create/move/restore | CHECK chk_category_depth_within_cap | probe |
| Delete blocked while active children | No orphaned visibility | Admin must delete children first | Service + RESTRICT | Delete/bulk delete | ON DELETE RESTRICT | probe |
| Hard delete unsupported | Delete is always recoverable | Nothing permanently removed | RESTRICT FKs | No hard-delete route | FK 23503 | probe |
| Visibility inherited | Hidden parent hides subtree | Guest cannot reach hidden subtree | Service + SQL | Storefront 404 | computeAncestorChainVisible | spec |
| One error code per status | Clients branch on status | Deterministic errors | Review fix | PAGINATION_LIMIT_TOO_LARGE = 400 everywhere | BadRequestException | — |
| Import requires entity-specific create | Route-level superset token must not mass-create | 403 without entity permission | Service | Import submit | assertCanCreateEntity | spec |
| Product Decision | User Benefit | Engineering Benefit | Alternative | Tradeoff | Risk |
|---|
| Slugs in ownership tables | Permanent URLs | Unrepresentable re-pointing | Slug column + history table | More tables | — |
| Advisory lock on tree writes | Consistent tree | Serialised rare writes | Application-level checks | Throughput on writes | Accepted (rare) |
| Soft delete + RESTRICT everywhere | Recoverable deletes | No cascade surprises | Hard delete | Storage grows | Retention policy |
Trigram % in WHERE | Fast fuzzy search | Index-accelerated candidates | similarity() in WHERE | Full scan if misused | Documented rule |
| Flow | Edge Case | Trigger | Expected Behavior | User/System Feedback | Source |
|---|
| Create | Slug collision | Name already used | Auto-suffix (-2, …) up to 100 attempts | 409 after exhaustion | catalog-slug.service.ts |
| Rename | Slug owned by self | Rename back | Re-adopt, original URL | 200 | |
| Move | Cycle | Move under descendant | 409 CATEGORY_CIRCULAR_HIERARCHY | | |
| Move | Concurrent | Two cross moves | Serialised; second sees committed state | 200/409 | advisory lock |
| Bulk | Duplicate ids | [X, X, Y] | Counted once | 409 only if > 100 unique | dedupeAndCapBulkIds |
| Reorder | Partial set | Missing sibling | 409 CATALOG_REORDER_INVALID_ITEM | | |
| Import | File-internal cycle | parentSlug graph cyclic | Job fails, nothing written | CATALOG_IMPORT_CYCLE_DETECTED | Kahn's algorithm |
| Import | Wrong entity declared | brand_series file submitted as entity=category | Header check fails the job before any row is built; zero rows written | CATALOG_IMPORT_HEADER_MISMATCH at row: 0 | validateImportHeaderForEntity |
| Import | Quoted field spans lines | A description containing newlines | One logical record, not one per physical line | Row counts and the row cap count records | csv-records.util.ts |
| Import | Retry | Worker error before final attempt | Released to queued | Real retry | lease claim |
| Export | Zero rows | Empty match | Header-only CSV, completed | Success | |
| Slug resolve | No current slug | Corrupt state | Not found | 404 | service invariant |
| Flow | Reads | Writes | Cache | Jobs/Events | Response Fields |
|---|
| Category list/tree | category, category_slug | — | catalog_category | — | ResponseDto + tree nodes |
| Category write | Row + parent + slug ownership | category, category_slug | invalidate | activity | ResponseDto |
| Search | category/brand/brand_series + slugs | — | catalog:search | — | items + pagination |
| Import | Rows, slug ownership | Entity + slug + catalog_job | invalidate | outbox → catalog.import_entities | job |
| Export | Entity rows | catalog_job + CSV | — | outbox → catalog.export_entities | job |