Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import fastifyStatic from '@fastify/static';
import Fastify from 'fastify';
import { z } from 'zod';
import { ApiError } from './services/errors.js';
import { openDb, type Db } from './db/index.js';
import { checklistRoutes } from './routes/checklists.js';
import { evaluationRoutes } from './routes/evaluations.js';
Expand Down Expand Up @@ -55,6 +57,14 @@ export function buildApp(opts: AppOptions = {}) {
});
}

// App-wide on purpose: any route may throw ApiError (mapped to its status) or a ZodError (400); anything else is a
// bug and falls through to Fastify's default 500.
app.setErrorHandler((e, _req, reply) => {
if (e instanceof ApiError) return reply.code(e.status).send({ error: e.message });
if (e instanceof z.ZodError) return reply.code(400).send({ error: 'invalid input', issues: e.issues.map((i) => ({ path: i.path.join('.'), message: i.message })) });
throw e;
});

app.get('/health', async () => ({ status: 'ok', service: 'cqa-api' }));
conversationRoutes(app, db, audio);
checklistRoutes(app, db);
Expand Down
28 changes: 22 additions & 6 deletions apps/api/src/routes/evaluations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Db } from '../db/index.js';
import { createAppeal, decideAppeal, evaluationVisible, listAllAppeals, listAppeals, overrideCriterion } from '../services/appeals.js';
import { ApiError } from '../services/errors.js';
import { logEvent } from '../services/events.js';
import { blindConversationIds, shownWhenBlind, blindEvaluation } from '../services/blind.js';
import { scopeOf } from '../services/directory.js';
import { listConversationViews } from '../services/conversations.js';
import { actorOf, denied } from './actor.js';
Expand All @@ -20,7 +21,8 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner
const q = ListEvaluationsQuerySchema.safeParse(req.query);
if (!q.success) return reply.code(400).send({ error: 'invalid query' });
const actor = actorOf(req);
const list = listEvaluations(db, q.data.conversationId);
const blind = blindConversationIds(db, actor);
const list = listEvaluations(db, q.data.conversationId).map((e) => (blind.has(e.conversationId) ? blindEvaluation(db, e) : e));
if (scopeOf(db, actor) === null) return list;
const mine = new Set(listConversationViews(db, {}, actor).map((c) => c.id));
return list.filter((e) => mine.has(e.conversationId));
Expand Down Expand Up @@ -56,11 +58,20 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner
return runner.getJob(req.params.id);
});

app.get<{ Params: { id: string } }>('/api/evaluations/:id', async (req, reply) => (evaluationVisible(db, req.params.id, actorOf(req)) && getEvaluation(db, req.params.id)) || reply.code(404).send({ error: 'evaluation not found' }));
app.get<{ Params: { id: string } }>('/api/evaluations/:id', async (req, reply) => {
const actor = actorOf(req);
const e = evaluationVisible(db, req.params.id, actor) ? getEvaluation(db, req.params.id) : undefined;
if (!e) return reply.code(404).send({ error: 'evaluation not found' });
return blindConversationIds(db, actor).has(e.conversationId) ? blindEvaluation(db, e) : e;
});

app.get<{ Params: { id: string } }>('/api/evaluations/:id/appeals', async (req, reply) =>
getEvaluation(db, req.params.id) && evaluationVisible(db, req.params.id, actorOf(req)) ? listAppeals(db, req.params.id) : reply.code(404).send({ error: 'evaluation not found' }),
);
app.get<{ Params: { id: string } }>('/api/evaluations/:id/appeals', async (req, reply) => {
const actor = actorOf(req);
const e = evaluationVisible(db, req.params.id, actor) ? getEvaluation(db, req.params.id) : undefined;
if (!e) return reply.code(404).send({ error: 'evaluation not found' });
const list = listAppeals(db, req.params.id);
return blindConversationIds(db, actor).has(e.conversationId) ? list.filter(shownWhenBlind) : list;
});

app.post<{ Params: { id: string } }>('/api/evaluations/:id/appeals', async (req, reply) => {
if (denied(req, reply, 'appeal')) return;
Expand Down Expand Up @@ -89,7 +100,12 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner
app.get('/api/appeals', async (req, reply) => {
const q = ListAppealsQuerySchema.omit({ evaluationId: true }).safeParse(req.query);
if (!q.success) return reply.code(400).send({ error: 'status must be pending, upheld or overridden' });
return listAllAppeals(db, q.data.status, actorOf(req));
const actor = actorOf(req);
const list = listAllAppeals(db, q.data.status, actor);
const blind = blindConversationIds(db, actor);
if (!blind.size) return list;
const hidden = new Set(listEvaluations(db).filter((e) => blind.has(e.conversationId)).map((e) => e.id));
return list.filter((a) => !hidden.has(a.evaluationId) || shownWhenBlind(a));
});

app.post<{ Params: { id: string } }>('/api/appeals/:id/decision', async (req, reply) => {
Expand Down
9 changes: 1 addition & 8 deletions apps/api/src/routes/team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import type { FastifyInstance, FastifyReply } from 'fastify';
import { z } from 'zod';
import type { Db } from '../db/index.js';
import { getDirectory, savePerson, saveTeam, seedDemoOrg } from '../services/directory.js';
import { ApiError } from '../services/errors.js';
import { listEvents } from '../services/events.js';
import { listNotifications, markRead } from '../services/notifications.js';
import {
Expand All @@ -19,13 +18,7 @@ const bad = (reply: FastifyReply, what: string) => reply.code(400).send({ error:

/** People, teams, audit log, notifications, comments, tags, tasks, cross-checks and the timeline. Roles are enforced here; scoping in the services. */
export function teamRoutes(app: FastifyInstance, db: Db) {
// Every handler maps ApiError to its status; anything else is a bug and surfaces as 500.
app.setErrorHandler((e, _req, reply) => {
if (e instanceof ApiError) return reply.code(e.status).send({ error: e.message });
if (e instanceof z.ZodError) return reply.code(400).send({ error: 'invalid input', issues: e.issues.map((i) => ({ path: i.path.join('.'), message: i.message })) });
throw e;
});

// Handlers here throw ApiError / ZodError and rely on the app-wide error handler in app.ts.
app.get('/api/directory', async () => getDirectory(db));
app.post('/api/people', async (req, reply) => {
if (denied(req, reply, 'manageTeams')) return;
Expand Down
4 changes: 3 additions & 1 deletion apps/api/src/services/appeals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getChecklist } from './checklists.js';
import { scopeOf } from './directory.js';
import { ApiError } from './errors.js';
import { logEvent } from './events.js';
import { notify } from './notifications.js';
import { notify, notifyCritical } from './notifications.js';
import { responsibleFor } from './directory.js';
import { toEvaluation } from './evaluations.js';
import { noteReviewActivity } from './review.js';
Expand Down Expand Up @@ -101,6 +101,8 @@ function applyOverride(db: Db, tx: Tx, evaluationId: string, criterionId: string
throw e;
}
tx.update(evaluations).set({ finalResults: next, finalTotal: scored.total, seriousViolation: scored.seriousViolation }).where(eq(evaluations.id, ev.id)).run();
// A human decision that newly raises a critical flag alerts the same people as an AI result would.
if (!ev.seriousViolation && scored.seriousViolation) notifyCritical(db, { ...ev, finalResults: next, finalTotal: scored.total, seriousViolation: true }, { tx });
return { value, isNA, before: { value: before.value, isNA: before.isNA }, conversationId: ev.conversationId };
}

Expand Down
26 changes: 26 additions & 0 deletions apps/api/src/services/blind.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { deriveSeriousViolation, type Actor, type Appeal, type Evaluation } from '@cqa/contracts';
import { and, eq } from 'drizzle-orm';
import type { Db } from '../db/index.js';
import { tasks } from '../db/schema.js';
import { getChecklist } from './checklists.js';

/**
* Blind cross-check: while a person has an OPEN cross-check task on a dialog, the read endpoints show them the AI's
* initial results only, never the first reviewer's state, corrections or name. Output-only masking: nothing stored
* changes, and the source conversation (hashed by the evaluation reuse cache) is not involved. A top manager is
* exempt (they see everything anyway, and checking the QA team is their audit). See docs/ARCHITECTURE.md.
*/
export function blindConversationIds(db: Db, actor: Actor | undefined): ReadonlySet<string> {
if (!actor?.id || actor.role === 'lead') return new Set();
const rows = db.select({ c: tasks.conversationId }).from(tasks).where(and(eq(tasks.assigneeId, actor.id), eq(tasks.kind, 'crosscheck'), eq(tasks.status, 'open'))).all();
return new Set(rows.map((r) => r.c));
}

/** The evaluation as the AI left it: final = original, flag derived from the original results. */
export function blindEvaluation(db: Db, e: Evaluation): Evaluation {
const checklist = getChecklist(db, e.checklistVersionId);
return { ...e, finalResults: e.originalResults, finalTotal: e.originalTotal, seriousViolation: checklist ? deriveSeriousViolation(checklist.criteria, e.originalResults) : e.seriousViolation };
}

/** Pending appeals are the operator's; corrections and decisions carry the reviewer's values and name. */
export const shownWhenBlind = (a: Appeal): boolean => a.kind !== 'correction' && a.status === 'pending';
12 changes: 9 additions & 3 deletions apps/api/src/services/conversations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ConversationSchema, canSee, type Actor, type Conversation, type ListCon
import { and, asc, eq } from 'drizzle-orm';
import type { Db } from '../db/index.js';
import { conversations, operatorAssignments, reviews } from '../db/schema.js';
import { blindConversationIds } from './blind.js';
import { scopeOf } from './directory.js';

type Row = typeof conversations.$inferSelect;
Expand All @@ -28,25 +29,30 @@ function enrich(row: Row, operator: string | undefined, review: typeof reviews.$
});
}

/** What the UI sees: the source plus import time, assigned operator and review. Scoped to what the actor may see. */
/**
* What the UI sees: the source plus import time, assigned operator and review. Scoped to what the actor may see; the
* review is hidden from a person with an open blind cross-check on the dialog (services/blind.ts).
*/
export function listConversationViews(db: Db, q: ListConversationsQuery = {}, actor?: Actor): Conversation[] {
const where = and(q.language ? eq(conversations.language, q.language) : undefined, q.channel ? eq(conversations.channel, q.channel) : undefined);
const ops = new Map(db.select().from(operatorAssignments).all().map((a) => [a.conversationId, a.operator]));
const revs = new Map(db.select().from(reviews).all().map((r) => [r.conversationId, r]));
const scope = scopeOf(db, actor);
const blind = blindConversationIds(db, actor);
return db
.select()
.from(conversations)
.where(where)
.orderBy(asc(conversations.id))
.all()
.map((row) => enrich(row, ops.get(row.id), revs.get(row.id)))
.map((row) => enrich(row, ops.get(row.id), blind.has(row.id) ? undefined : revs.get(row.id)))
.filter((c) => canSee(scope, c));
}

export function getConversationView(db: Db, id: string, actor?: Actor): Conversation | undefined {
const row = db.select().from(conversations).where(eq(conversations.id, id)).get();
if (!row) return undefined;
const view = enrich(row, db.select().from(operatorAssignments).where(eq(operatorAssignments.conversationId, id)).get()?.operator, db.select().from(reviews).where(eq(reviews.conversationId, id)).get());
const review = blindConversationIds(db, actor).has(id) ? undefined : db.select().from(reviews).where(eq(reviews.conversationId, id)).get();
const view = enrich(row, db.select().from(operatorAssignments).where(eq(operatorAssignments.conversationId, id)).get()?.operator, review);
return canSee(scopeOf(db, actor), view) ? view : undefined;
}
11 changes: 9 additions & 2 deletions apps/api/src/services/directory.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { DirectorySchema, PersonSchema, TeamSchema, operatorScope, type Actor, type Directory, type Person, type Scope, type Team } from '@cqa/contracts';
import { eq } from 'drizzle-orm';
import { desc, eq } from 'drizzle-orm';
import type { Db } from '../db/index.js';
import { conversations, operatorAssignments, people, teams } from '../db/schema.js';
import { conversations, evaluations, operatorAssignments, people, teams } from '../db/schema.js';
import { ApiError } from './errors.js';
import { toEvaluation } from './evaluations.js';
import { logEvent } from './events.js';
import { notifyCritical } from './notifications.js';

export function getDirectory(db: Db): Directory {
return DirectorySchema.parse({
Expand Down Expand Up @@ -75,6 +77,11 @@ export function seedDemoOrg(db: Db, actor?: Actor): { people: number; assigned:
const free = tx.select({ id: conversations.id }).from(conversations).all().map((c) => c.id).filter((id) => !tx.select().from(operatorAssignments).where(eq(operatorAssignments.conversationId, id)).get());
const at = new Date().toISOString();
free.forEach((conversationId, i) => tx.insert(operatorAssignments).values({ conversationId, operator: ops[i % ops.length]!.id, assignedBy: 'демо', assignedAt: at }).run());
// Dialogs evaluated before anyone was responsible for them: their critical alerts reach the new managers now.
for (const { id } of tx.select({ id: conversations.id }).from(conversations).all()) {
const latest = tx.select().from(evaluations).where(eq(evaluations.conversationId, id)).orderBy(desc(evaluations.createdAt), desc(evaluations.id)).get();
if (latest) notifyCritical(db, toEvaluation(latest), { tx, once: true });
}
logEvent(tx, actor, { type: 'directory.changed', summary: `Создана демонстрационная команда (вымышленные сотрудники), диалогов распределено: ${free.length}`, data: { demo: true } });
return { people: 4 + 4 + ops.length, assigned: free.length };
});
Expand Down
13 changes: 9 additions & 4 deletions apps/api/src/services/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,18 @@ export function markRead(db: Db, actor: Actor | undefined, ids?: string[]): void
/**
* A serious violation on a finished evaluation tells the manager of the operator's team and the top managers. The
* trigger is the checklist's own critical flag, never a criterion id, so it follows whatever the checklist defines.
* Called when an evaluation is stored, when a correction or appeal decision newly raises a flag, and as a backfill
* when the demo organisation is seeded (the dialogs had no manager before).
*/
export function notifyCritical(db: Db, e: Evaluation): void {
export function notifyCritical(db: Db, e: Evaluation, opts: { tx?: Tx; once?: boolean } = {}): void {
if (e.status !== 'completed' || !e.seriousViolation) return;
const w = opts.tx ?? db;
const checklist = getChecklist(db, e.checklistVersionId);
const raised = e.finalResults.filter((r) => r.value === true && checklist?.criteria.find((c) => c.id === r.criterionId)?.criticalFlag).map((r) => checklist?.criteria.find((c) => c.id === r.criterionId)?.title ?? r.criterionId);
const { managerId } = responsibleFor(db, e.conversationId);
const leads = db.select({ id: people.id }).from(people).where(eq(people.role, 'lead')).all().map((p) => p.id);
const to = [...(managerId ? [managerId] : []), ...leads];
if (to.length) notify(db, to, { kind: 'critical', title: `Грубое нарушение: ${e.conversationId}`, body: raised.length ? raised.join('; ') : 'Выявлено грубое нарушение.', conversationId: e.conversationId });
const leads = w.select({ id: people.id }).from(people).where(eq(people.role, 'lead')).all().map((p) => p.id);
let to = [...(managerId ? [managerId] : []), ...leads];
// `once`: a backfill must not repeat an alert the person already has for this dialog.
if (opts.once) to = to.filter((id) => !w.select({ id: notifications.id }).from(notifications).where(and(eq(notifications.recipientId, id), eq(notifications.kind, 'critical'), eq(notifications.conversationId, e.conversationId))).get());
if (to.length) notify(w, to, { kind: 'critical', title: `Грубое нарушение: ${e.conversationId}`, body: raised.length ? raised.join('; ') : 'Выявлено грубое нарушение.', conversationId: e.conversationId });
}
6 changes: 5 additions & 1 deletion apps/api/src/services/review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ export function setReview(db: Db, conversationId: string, input: SetReviewInput,
logEvent(tx, actor, { type: 'review.set', conversationId, summary: input.status === 'reviewed' ? 'Диалог отмечен проверенным' : 'Диалог взят в работу', data: { status: input.status, evaluationId } });
// A finished check closes the review task handed to this person.
if (input.status === 'reviewed' && actor?.id) {
tx.update(tasks).set({ status: 'done', doneAt: at }).where(and(eq(tasks.conversationId, conversationId), eq(tasks.kind, 'review'), eq(tasks.assigneeId, actor.id), eq(tasks.status, 'open'))).run();
const open = and(eq(tasks.conversationId, conversationId), eq(tasks.kind, 'review'), eq(tasks.assigneeId, actor.id), eq(tasks.status, 'open'));
const ids = tx.select({ id: tasks.id }).from(tasks).where(open).all().map((t) => t.id);
if (!ids.length) return;
tx.update(tasks).set({ status: 'done', doneAt: at }).where(inArray(tasks.id, ids)).run();
for (const taskId of ids) logEvent(tx, actor, { type: 'task.done', conversationId, summary: 'Задача на проверку выполнена', data: { taskId } });
}
});
}
Expand Down
Loading
Loading