Files
saqib mirandClaude Sonnet 5 3bd068b031 feat(012-admin-list-views): SLA-run, escalation-event, and product-catalog list endpoints
Adds GET /admin/sla-runs (filterable by status), GET /admin/escalation-
events (capped, most-recent-first), and GET /admin/products (with
integration status joined in, never the full ProductIntegration row).
None of these existed as a single query before - only per-ticket or
per-integration-id lookups did.

Discovered while planning supporthub-web's 001-agent-admin-ui User
Stories 6-7 (SLA/escalation monitoring, product catalog), the same way
011-agent-ticket-queue was discovered for User Story 1.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 16:31:20 +05:30

249 lines
8.4 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { buildApp } from '@/app';
import { prismaClient } from '@/infrastructure/database';
import { FastifyInstance } from 'fastify';
import { loginAs, authHeader } from '../helpers/auth';
import {
encryptCredential,
generateCredentialSecret,
issueIntegrationToken,
} from '@/modules/catalog/products';
/**
* Covers specs/012-admin-list-views/quickstart.md Scenarios 1-3 against a real Postgres/Redis
* — SLA runs, escalation events, and the product catalog, all listed across multiple
* tickets/products in one request.
*/
describe('Admin list views (User Stories 1-3)', () => {
let app: FastifyInstance;
let adminToken: string;
let agentToken: string;
const suffix = Date.now();
const externalProductId = `TEST_ALV_PROD_${suffix}`;
const skillTag = `alv_skill_${suffix}`;
let productId: string;
let teamId: string;
let agentAId: string;
let secret: string;
let nodeAId: string;
let nodeBId: string;
let globalPolicyId: string;
const createdTicketIds: string[] = [];
async function createTicket(): Promise<string> {
const token = issueIntegrationToken(secret, {
externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
});
const created = await app.inject({
method: 'POST',
url: '/v1/support/requests',
headers: { authorization: `Bearer ${token}` },
payload: {
productId: externalProductId,
tenantId: 'tenant-1',
userId: 'user-1',
source: 'test',
problem: `Needs a human ${Date.now()}-${Math.random()}`,
},
});
const ticketId = created.json().data.ticketId as string;
createdTicketIds.push(ticketId);
return ticketId;
}
async function escalate(ticketId: string): Promise<void> {
const ticket = await prismaClient.ticket.findUniqueOrThrow({ where: { id: ticketId } });
await app.inject({
method: 'PATCH',
url: `/tickets/${ticketId}/status`,
headers: authHeader(adminToken),
payload: { status: 'HUMAN_ESCALATION', expectedVersion: ticket.version },
});
}
beforeAll(async () => {
app = await buildApp();
adminToken = await loginAs(app, 'ADMIN');
agentToken = await loginAs(app, 'AGENT');
const product = await prismaClient.product.create({
data: { externalProductId, name: 'Admin List Views Test Product', status: 'active' },
});
productId = product.id;
secret = generateCredentialSecret();
await prismaClient.productIntegration.create({
data: {
productId,
credentialRef: encryptCredential(secret),
authMechanism: 'signed_token',
allowedScope: { tenantIds: ['tenant-1'] },
status: 'active',
rateLimitPerMinute: 1000,
rateLimitPerUserPerMinute: 1000,
},
});
const team = await app.inject({
method: 'POST',
url: '/admin/teams',
headers: authHeader(adminToken),
payload: { name: `ALV Team ${suffix}` },
});
teamId = team.json().data.id;
const agentA = await app.inject({
method: 'POST',
url: `/admin/teams/${teamId}/agents`,
headers: authHeader(adminToken),
payload: { name: 'ALV Agent A' },
});
agentAId = agentA.json().data.id;
await app.inject({
method: 'PUT',
url: `/admin/agents/${agentAId}/skills/${skillTag}`,
headers: authHeader(adminToken),
payload: { level: 3 },
});
const nodeA = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
headers: authHeader(adminToken),
payload: {
name: 'ALV Node A',
order: 0,
productScope: [externalProductId],
skills: [skillTag],
assignmentStrategy: 'ROUND_ROBIN',
},
});
nodeAId = nodeA.json().data.id;
const nodeB = await app.inject({
method: 'POST',
url: '/admin/hierarchy-nodes',
headers: authHeader(adminToken),
payload: {
name: 'ALV Node B',
order: 1,
productScope: [externalProductId],
skills: [skillTag],
assignmentStrategy: 'ROUND_ROBIN',
},
});
nodeBId = nodeB.json().data.id;
const policy = await app.inject({
method: 'POST',
url: '/admin/sla-policies',
headers: authHeader(adminToken),
payload: {
name: `ALV Policy ${suffix}`,
productId,
firstResponseMinutes: 30,
resolutionMinutes: 60,
},
});
globalPolicyId = policy.json().data.id;
});
afterAll(async () => {
const ticketFilter = { ticketId: { in: createdTicketIds } };
await prismaClient.escalationEvent.deleteMany({ where: ticketFilter });
await prismaClient.sLARun.deleteMany({ where: ticketFilter });
await prismaClient.sLARun.deleteMany({ where: { policyId: globalPolicyId } });
await prismaClient.sLAPolicy.deleteMany({ where: { id: globalPolicyId } });
await prismaClient.assignmentHistory.deleteMany({ where: ticketFilter });
await prismaClient.assignment.deleteMany({ where: ticketFilter });
await prismaClient.hierarchyNode.deleteMany({ where: { id: { in: [nodeAId, nodeBId] } } });
await prismaClient.agentSkill.deleteMany({ where: { agentId: agentAId } });
await prismaClient.ticketMessage.deleteMany({ where: ticketFilter });
await prismaClient.ticket.deleteMany({ where: { id: { in: createdTicketIds } } });
await prismaClient.problem.deleteMany({ where: { productId } });
await prismaClient.agent.deleteMany({ where: { teamId } });
await prismaClient.team.deleteMany({ where: { id: teamId } });
await prismaClient.productIntegration.deleteMany({ where: { productId } });
await prismaClient.product.deleteMany({ where: { id: productId } });
await app.close();
});
it('US1: SLA runs are listed across tickets, filterable by status, and reject an invalid status', async () => {
const ticket1 = await createTicket();
await escalate(ticket1);
const unfiltered = await app.inject({
method: 'GET',
url: '/admin/sla-runs',
headers: authHeader(agentToken),
});
expect(unfiltered.statusCode).toBe(200);
const ours = unfiltered.json().data.filter((r: { ticketId: string }) => r.ticketId === ticket1);
expect(ours).toHaveLength(1);
expect(ours[0].ticketCode).toBeTruthy();
const filtered = await app.inject({
method: 'GET',
url: '/admin/sla-runs?status=running',
headers: authHeader(agentToken),
});
expect(filtered.statusCode).toBe(200);
expect(filtered.json().data.every((r: { status: string }) => r.status === 'running')).toBe(
true,
);
const invalid = await app.inject({
method: 'GET',
url: '/admin/sla-runs?status=not-a-real-status',
headers: authHeader(agentToken),
});
expect(invalid.statusCode).toBe(400);
});
it('US2: recent escalation events are listed across tickets, most-recent-first', async () => {
const ticket2 = await createTicket();
await escalate(ticket2);
await new Promise((resolve) => setTimeout(resolve, 10));
const manual = await app.inject({
method: 'POST',
url: `/tickets/${ticket2}/escalate`,
headers: authHeader(agentToken),
payload: { targetNodeId: nodeBId, reason: 'test manual escalation' },
});
expect(manual.statusCode).toBe(201);
const events = await app.inject({
method: 'GET',
url: '/admin/escalation-events',
headers: authHeader(agentToken),
});
expect(events.statusCode).toBe(200);
const ours = events.json().data.filter((e: { ticketId: string }) => e.ticketId === ticket2);
expect(ours.length).toBeGreaterThanOrEqual(1);
const manualEvent = ours.find((e: { ruleId: string | null }) => e.ruleId === null);
expect(manualEvent).toBeDefined();
expect(manualEvent.triggeredBy).toBeTruthy();
expect(manualEvent.toNodeId).toBe(nodeBId);
});
it('US3: the product catalog shows integration status, and is admin-only', async () => {
const asAdmin = await app.inject({
method: 'GET',
url: '/admin/products',
headers: authHeader(adminToken),
});
expect(asAdmin.statusCode).toBe(200);
const ours = asAdmin.json().data.find((p: { id: string }) => p.id === productId);
expect(ours.integrationStatus).toBe('active');
expect(ours.credentialRef).toBeUndefined();
const asAgent = await app.inject({
method: 'GET',
url: '/admin/products',
headers: authHeader(agentToken),
});
expect(asAgent.statusCode).toBe(403);
});
});