# Task G - Document Template Management 404 Hotfix - 2026-07-02

## Summary

- Investigated `GET /api/crm/settings/document-templates/versions/:id/management` returning `404`.
- Confirmed the route exists at `src/app/api/crm/settings/document-templates/versions/[id]/management/route.ts`.
- Confirmed the reported version id `e7e89bf2-f107-4f90-b03d-4a7533883d84` still exists in `crm_document_template_versions` for organization `ALLA Demo`.
- Root cause was the template-version settings UI keeping a stale selected tab value after template versions were reseeded or refetched.

## Root Cause

`TemplateDetailCard` in `src/features/foundation/document-template/components/template-settings.tsx` used Radix `Tabs` with `defaultValue={template.versions[0]?.id ?? 'empty'}`.

That made the version selection uncontrolled:

- when the template detail query refetched after version changes, the tab state could continue pointing at an old version id
- the management panel then kept querying `/api/crm/settings/document-templates/versions/:oldId/management`
- if that old id no longer existed in the latest template-version set, the server correctly returned `404 Document template version not found`

## Fix

Changed template-version selection to controlled state:

- added `selectedVersionId` state
- synchronized it with the latest `template.versions`
- reset it to the first available version when the previous selection no longer exists

This keeps the management panel aligned with the current server dataset and prevents stale version management requests after reseed/refetch/mutation flows.

## Verification

- `npm run typecheck`
- Database spot-check confirmed the reported version id still exists, so the failing `404` was not caused by a missing route or missing DB row.
