# Taxonomy — Prompt 3, Step A

The backend manages categories, tags, topics and entities as soft-deleted,
ULID-addressed resources. All names are JSON translations with a required Nepali
name and optional English translation. Categories use an adjacency list; parent
references in requests and responses are ULIDs. Numeric primary/foreign keys are
never exposed. Dates use the existing Kathmandu ISO/BS formatter.

## CMS endpoints

All routes use Sanctum, the CMS token ability, active-account and required-2FA
middleware, and the CMS rate limiter. Taxonomy is part of core news, rather than
an optional module.

| Method | Path under `/api/v1/cms` | Permission |
| --- | --- | --- |
| GET, POST | `categories`, `tags`, `topics`, `entities` | `taxonomy.{resource}.manage` |
| GET, PATCH, DELETE | `{resource}/{term ULID}` | `taxonomy.{resource}.manage` |
| GET | `categories/tree` | `taxonomy.categories.manage` |
| PUT | `categories/reorder` | `taxonomy.categories.manage` |
| POST | `tags/{source ULID}/merge` | `taxonomy.tags.manage` |

Lists use `page` (default 1), `per_page` (1–100, default 25), `sort`
(`slug`, `sort_order`, `created_at`, `uid`, optional `-` prefix), and explicit
Spatie query-builder filters. Common filters: `filter[slug]`,
`filter[is_active]` (`0`, `1`, `true`, `false`). Category filters also include
`filter[parent]` (parent ULID or `root`) and `filter[show_in_menu]`; entity
filters include `filter[type]` (`person`, `organisation`, `place`). Unsupported
filters/sorts return the standard translated 422 envelope.

Create example:

```json
{
  "name": {"ne": "स्थानीय समाचार", "en": "Local news"},
  "slug": "local-news",
  "parent": null,
  "color": "#123abc",
  "icon": "newspaper",
  "layout_key": "standard",
  "show_in_menu": true,
  "seo": {"title": {"ne": "स्थानीय समाचार"}}
}
```

Common fields are `name`, `slug`, `seo`, `is_active`, `sort_order`.
Category-only fields are `parent`, `color`, `icon`, `layout_key`, `show_in_menu`.
Entities require `type`. SEO accepts translated `title`, `description`,
`keywords`. PATCH changes only supplied fields. Slugs remain reserved after
soft deletion. Legacy IDs/slugs are migration inputs, not editable CMS fields.

The hierarchy endpoint returns a flat ordered array containing `parent` ULIDs,
so clients can build a tree without recursive queries. Category lists, hierarchy
reads and item mutations enforce category scope. Scoped managers can edit
assigned categories, but administrators create new categories and grant their
scope. Changing a parent also requires access to that parent. Scope checks and
`Category::visibleTo()` share the existing `ScopeService` rules; category and
content-type scope keys now resolve by slug or UID and serialize as public UIDs.

Reorder body: `{"parent": "<parent ULID or null>", "categories": ["<UID>", "<UID>"]}`.
Supply the complete sibling group exactly once. Every sibling and the parent
must be authorized. Move categories by PATCHing `parent`; self and descendant
cycles are rejected. Tree mutations and merges serialize through the Redis lock
`lock:taxonomy:write` (DB 4, 60 seconds) and database transactions.

Merge body: `{"target": "<destination tag ULID>"}`. Merging transfers
`story_tags` associations when the Step B pivot exists, deduplicates overlaps,
flattens earlier aliases, and soft-deletes/deactivates the source while preserving
its slug and canonical `merged_into_id`. Self merges and deleted destinations
are rejected. Canonical tags with aliases cannot be deleted. The pivot transfer
contract is tested independently with an isolated SQLite database.

Deletion refuses terms with references, including child categories, category
scopes, legacy mappings and story relationships (when Step B tables exist).

## Audit, events and cache

`AuditService` records `taxonomy_created`, `taxonomy_updated`,
`taxonomy_deleted`, `categories_reordered` (per changed category) and
`tags_merged`. Updates include field changes; merge records include the
destination UID and transferred story count. Default seed insertions are audited
with no authenticated actor and an explicit seed reason.

`TaxonomyChanged` dispatches after commit. `InvalidateTaxonomyCache` immediately
purges the category catalogue, using `CacheService`, tag `taxonomy:categories`
and key `taxonomy:categories:catalogue` (TTL one hour). CMS paginated queries
always apply current scope; cached hierarchy data is filtered before output.
Hierarchy mutations read locked fresh rows, never cached rows.

No new settings or external packages are required. The new permission
`taxonomy.entities.manage` is added to the catalogue. Existing roles retain
administrator edits on reseeding; grant the new permission explicitly to
existing system administrators if needed. Newly seeded system administrators
receive it through the existing `taxonomy.*` role definition.

## Seeders and required client input

`ReferenceDataSeeder` calls `CategoriesSeeder` and `ContentTypesSeeder`.
Both add missing rows by slug, preserve existing names/settings/deletions and
record a seed version. The supplied prompt defines 28 design categories
(economy subcategories are nested under economy) and 14 content types.
The category seed version is explicitly `2026.11.design.1`.

**Pending: `__CONFIRM_WITH_CLIENT__` — Appendix E is absent from the supplied
48-page SRS.** `database/seeders/data/legacy-categories.php` records that pending
input. No legacy IDs, legacy slugs, old-site subcategories or category mappings
have been invented. `legacy_category_map` is ready for the approved mapping.
The pending manifest is documentation of the input contract; importing its
approved rows must be implemented once that source is supplied.

Step A cannot be accepted as complete until the full old-site category list
(Nepali names, legacy IDs and slugs, destination categories and parent hierarchy)
is supplied and seeded. Steps B–D (stories, revisions, media and their endpoints)
remain subsequent work, following `CLAUDE.md`'s one-step-at-a-time instruction.

The workspace has an empty, read-only `.git` directory, so no P3A commit can be
created in this session.

## Verification

Feature coverage includes CRUD, authentication/permissions, category scope,
validation, cycles, sibling ordering, soft-delete/reference protection, merge
aliases, audits, seed idempotency, cache invalidation and constant list query
counts. The existing CMS route security check also covers these endpoints.
See `docs/openapi.json` for the generated request and response contracts.

Verified in this session on PHP 8.2:

- Full regression suite: 180 tests, 1,334 assertions passed.
- After final index/listener/scope changes: 25 targeted tests, 621 assertions passed.
- Larastan level 8: passed (sequential `--debug` mode avoids sandbox socket restrictions).
- Pint: passed.
- PHP 8.4 syntax: 389 PHP files passed, including the new migration. Full PHP 8.4
  tests cannot run on this machine because DOM/mbstring/XML extensions are absent.
- OpenAPI export: all 23 taxonomy operations and all create/update schemas
  verified. Nine existing `JR001` diagnostics remain in unrelated resources.

Tests applied the migration only to `ePaschim_test`; the default application
database was not migrated or seeded in this session.
