Files
support_backend/tests/integration/support-org-hierarchy.test.ts
T
saqib mirandClaude Sonnet 5 a0c1a9aa33 feat: implement support organization (006) — teams, agents, hierarchy, capability lookup
Phase 6 of the roadmap. Populates the identity/teams and
orchestration/hierarchy module directories (previously empty or
near-empty scaffold stubs) and replaces identity/agents' pre-existing
placeholder, which queried a generic User/UserRole model unrelated to
this system's real architecture (nothing since 002-saas-integration's
CustomerReference has used it).

Teams and agents: active/inactive CRUD, never hard deletion; team
deactivation never cascades to its agents. Skills: compound-unique
upsert on (agentId, skillTag), never duplicates. Availability: a single
current record per agent, deliberately last-write-wins rather than
optimistic-locked — operational telemetry, not a durable business
record. The dynamic hierarchy: a nestable, orderable HierarchyNode tree
with every field (scope, assignment strategy reference, entry/exit
conditions) stored as opaque admin-set data; cycle detection runs only
on reparenting edits (a new node can't form a cycle); every
create/edit/activate/deactivate is audited via AuditLog, reusing
002's existing writer pattern. A capability-eligibility read path
composes hierarchy scope with caller-supplied skills for the future
orchestration/assignment phase (Phase 7) to call, deliberately
excluding availability per doc 05's own capability-before-availability
ordering.

Found and fixed a real bug before it reached tests: the initial
availability upsert reset currentLoad to 0 on every update, not just
creation.

Adds 11 unit tests (cycle detection, capability matching) and 4
integration test files covering all four user stories. Full regression
(every pre-existing 002-005 integration test plus all new ones) run
against real Postgres/Redis/MinIO: 107 passed, 9 skipped (005's
AI-key-gated tests, unrelated), 0 failed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 18:12:26 +05:30

162 lines
5.6 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { buildApp } from '@/app';
import { prismaClient } from '@/infrastructure/database';
import { FastifyInstance } from 'fastify';
/** Covers specs/006-support-organization/quickstart.md Scenario 3 against a real Postgres. */
describe('Support organization — dynamic hierarchy (User Story 3)', () => {
let app: FastifyInstance;
const rootName = `Test Root ${Date.now()}`;
let rootId: string;
let childId: string;
beforeAll(async () => {
app = await buildApp();
});
afterAll(async () => {
await prismaClient.hierarchyNode.deleteMany({
where: { name: { startsWith: 'Test' }, id: { in: [rootId, childId].filter(Boolean) } },
});
await prismaClient.auditLog.deleteMany({
where: { entityType: 'HierarchyNode', entityId: { in: [rootId, childId].filter(Boolean) } },
});
await app.close();
});
it('Scenario 3: parent/child creation, order, nonexistent parent rejected, cycle rejected, deactivation does not cascade', async () => {
const createRoot = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
payload: { name: rootName, order: 0, assignmentStrategy: 'ROUND_ROBIN' },
});
expect(createRoot.statusCode).toBe(201);
rootId = createRoot.json().data.id;
const createChild = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
payload: {
name: `${rootName} Child`,
parentId: rootId,
order: 0,
assignmentStrategy: 'ROUND_ROBIN',
},
});
expect(createChild.statusCode).toBe(201);
childId = createChild.json().data.id;
const children = await app.inject({
method: 'GET',
url: `/admin/hierarchy-nodes/${rootId}/children`,
});
expect(children.json().data.map((n: { id: string }) => n.id)).toContain(childId);
const badParent = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
payload: {
name: 'Orphan',
parentId: 'nonexistent-node-id',
order: 0,
assignmentStrategy: 'ROUND_ROBIN',
},
});
expect(badParent.statusCode).toBe(404);
const selfCycle = await app.inject({
method: 'PUT',
url: `/admin/hierarchy-nodes/${childId}`,
payload: {
name: `${rootName} Child`,
parentId: childId,
order: 0,
assignmentStrategy: 'ROUND_ROBIN',
},
});
expect(selfCycle.statusCode).toBe(400);
expect(selfCycle.json().error.code).toBe('CYCLE_DETECTED');
const transitiveCycle = await app.inject({
method: 'PUT',
url: `/admin/hierarchy-nodes/${rootId}`,
payload: { name: rootName, parentId: childId, order: 0, assignmentStrategy: 'ROUND_ROBIN' },
});
expect(transitiveCycle.statusCode).toBe(400);
expect(transitiveCycle.json().error.code).toBe('CYCLE_DETECTED');
await app.inject({ method: 'PATCH', url: `/admin/hierarchy-nodes/${rootId}/deactivate` });
const activeTree = await app.inject({
method: 'GET',
url: '/admin/hierarchy-nodes?active=true',
});
const activeIds = activeTree.json().data.map((n: { id: string }) => n.id);
expect(activeIds).not.toContain(rootId);
const childAfterParentDeactivation = await app.inject({
method: 'GET',
url: `/admin/hierarchy-nodes/${childId}`,
});
expect(childAfterParentDeactivation.json().data.active).toBe(true);
});
it('preserves sibling order under the same parent', async () => {
const parent = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
payload: { name: `${rootName} Order Parent`, order: 0, assignmentStrategy: 'ROUND_ROBIN' },
});
const parentId = parent.json().data.id;
const second = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
payload: { name: 'Second', parentId, order: 2, assignmentStrategy: 'ROUND_ROBIN' },
});
const first = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
payload: { name: 'First', parentId, order: 1, assignmentStrategy: 'ROUND_ROBIN' },
});
const children = await app.inject({
method: 'GET',
url: `/admin/hierarchy-nodes/${parentId}/children`,
});
const orderedIds = children.json().data.map((n: { id: string }) => n.id);
expect(orderedIds).toEqual([first.json().data.id, second.json().data.id]);
await prismaClient.hierarchyNode.deleteMany({
where: { id: { in: [parentId, first.json().data.id, second.json().data.id] } },
});
await prismaClient.auditLog.deleteMany({
where: {
entityType: 'HierarchyNode',
entityId: { in: [parentId, first.json().data.id, second.json().data.id] },
},
});
});
it('every create/edit/activate/deactivate writes exactly one audit log row', async () => {
const created = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
payload: { name: `${rootName} Audited`, order: 0, assignmentStrategy: 'ROUND_ROBIN' },
});
const nodeId = created.json().data.id;
await app.inject({ method: 'PATCH', url: `/admin/hierarchy-nodes/${nodeId}/deactivate` });
await app.inject({ method: 'PATCH', url: `/admin/hierarchy-nodes/${nodeId}/activate` });
const auditRows = await prismaClient.auditLog.findMany({
where: { entityType: 'HierarchyNode', entityId: nodeId },
});
expect(auditRows).toHaveLength(3); // created, deactivated, activated
await prismaClient.hierarchyNode.deleteMany({ where: { id: nodeId } });
await prismaClient.auditLog.deleteMany({
where: { entityType: 'HierarchyNode', entityId: nodeId },
});
});
});