From a6f79d0fed92672f40f3e45f056102d33777739a Mon Sep 17 00:00:00 2001 From: Denis Andreyev Date: Sun, 8 Nov 2026 11:40:53 +0500 Subject: [PATCH] Fix review findings in the team workflow: picker, notifications, blind cross-checks, comments, scoping, UX (#79) --- apps/api/src/app.ts | 10 ++ apps/api/src/routes/evaluations.ts | 28 +++-- apps/api/src/routes/team.ts | 9 +- apps/api/src/services/appeals.ts | 4 +- apps/api/src/services/blind.ts | 26 +++++ apps/api/src/services/conversations.ts | 12 ++- apps/api/src/services/directory.ts | 11 +- apps/api/src/services/notifications.ts | 13 ++- apps/api/src/services/review.ts | 6 +- apps/api/src/services/work.ts | 22 +++- apps/api/test/team.test.ts | 121 +++++++++++++++++++++- apps/web/src/App.tsx | 62 +++++++++-- apps/web/src/features/AnalyticsPage.tsx | 23 ++-- apps/web/src/features/Appeals.tsx | 6 +- apps/web/src/features/AppealsPage.tsx | 10 +- apps/web/src/features/AuditPage.tsx | 4 +- apps/web/src/features/CrosscheckPage.tsx | 47 +++++++-- apps/web/src/features/DialogNotes.tsx | 20 ++-- apps/web/src/features/DialogsPage.tsx | 4 +- apps/web/src/features/EvaluationPanel.tsx | 2 +- apps/web/src/features/ReviewControl.tsx | 4 +- apps/web/src/features/RolePicker.tsx | 31 ++++-- apps/web/src/features/Sidebar.tsx | 9 +- apps/web/src/features/TasksPage.tsx | 2 +- apps/web/src/features/TeamPage.tsx | 36 ++++++- apps/web/src/index.css | 4 + apps/web/src/lib/analytics.ts | 28 ++--- apps/web/src/lib/errors.ts | 3 + apps/web/test/analytics.test.ts | 10 ++ apps/web/test/errors.test.ts | 3 + apps/web/test/review-fixes.test.tsx | 52 ++++++++++ docs/ARCHITECTURE.md | 4 +- 32 files changed, 516 insertions(+), 110 deletions(-) create mode 100644 apps/api/src/services/blind.ts create mode 100644 apps/web/test/review-fixes.test.tsx diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 499ace9..1bc93b5 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -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'; @@ -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); diff --git a/apps/api/src/routes/evaluations.ts b/apps/api/src/routes/evaluations.ts index 3430de5..29b0713 100644 --- a/apps/api/src/routes/evaluations.ts +++ b/apps/api/src/routes/evaluations.ts @@ -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'; @@ -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)); @@ -42,11 +44,20 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner app.get<{ Params: { id: string } }>('/api/jobs/:id', async (req, reply) => runner.getJob(req.params.id) ?? reply.code(404).send({ error: 'job not found' })); - 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; @@ -75,7 +86,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) => { diff --git a/apps/api/src/routes/team.ts b/apps/api/src/routes/team.ts index de86859..1de0257 100644 --- a/apps/api/src/routes/team.ts +++ b/apps/api/src/routes/team.ts @@ -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 { @@ -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; diff --git a/apps/api/src/services/appeals.ts b/apps/api/src/services/appeals.ts index 1069972..6c1c387 100644 --- a/apps/api/src/services/appeals.ts +++ b/apps/api/src/services/appeals.ts @@ -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'; @@ -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 }; } diff --git a/apps/api/src/services/blind.ts b/apps/api/src/services/blind.ts new file mode 100644 index 0000000..13070bb --- /dev/null +++ b/apps/api/src/services/blind.ts @@ -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 { + 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'; diff --git a/apps/api/src/services/conversations.ts b/apps/api/src/services/conversations.ts index bcdf149..9500d08 100644 --- a/apps/api/src/services/conversations.ts +++ b/apps/api/src/services/conversations.ts @@ -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; @@ -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; } diff --git a/apps/api/src/services/directory.ts b/apps/api/src/services/directory.ts index 1ca8efc..7b72da1 100644 --- a/apps/api/src/services/directory.ts +++ b/apps/api/src/services/directory.ts @@ -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({ @@ -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 }; }); diff --git a/apps/api/src/services/notifications.ts b/apps/api/src/services/notifications.ts index e0e9930..e87c669 100644 --- a/apps/api/src/services/notifications.ts +++ b/apps/api/src/services/notifications.ts @@ -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 }); } diff --git a/apps/api/src/services/review.ts b/apps/api/src/services/review.ts index 34c0429..e162f5f 100644 --- a/apps/api/src/services/review.ts +++ b/apps/api/src/services/review.ts @@ -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 } }); } }); } diff --git a/apps/api/src/services/work.ts b/apps/api/src/services/work.ts index b8d2b98..729bb73 100644 --- a/apps/api/src/services/work.ts +++ b/apps/api/src/services/work.ts @@ -88,6 +88,11 @@ export function addTag(db: Db, input: AddTagInput, actor?: Actor): Tag { if (!ev) throw new ApiError('evaluation not found', 404); requireVisible(db, ev.conversationId, actor); return db.transaction((tx) => { + // `label` is the category. Free text only while no taxonomy is defined; then it must be one of its items. + if (input.label !== undefined) { + const labels = tx.select({ label: taxonomy.label }).from(taxonomy).all().map((t) => t.label); + if (labels.length && !labels.includes(input.label)) throw new ApiError('tag is not in the taxonomy', 400); + } const row = { id: `tag-${randomUUID()}`, evaluationId: ev.id, conversationId: ev.conversationId, criterionId: input.criterionId ?? null, origin: input.origin, label: input.label ?? null, by: actor?.name || 'система', at: new Date().toISOString() }; tx.insert(tags).values(row).run(); logEvent(tx, actor, { type: 'tag.added', conversationId: ev.conversationId, summary: `Причина ошибки: ${input.label ?? input.origin}`, data: { criterionId: input.criterionId, origin: input.origin, label: input.label } }); @@ -132,9 +137,14 @@ export function createTasks(db: Db, input: CreateTasksInput, actor?: Actor): Tas if (input.assigneeId && !assignable.has(input.assigneeId)) throw new ApiError('the assignee must be a QA person or a top manager', 400); return db.transaction((tx) => { const created: Task[] = []; + const skipped: string[] = []; for (const conversationId of [...new Set(input.conversationIds)]) { if (!conversationExists(db, conversationId)) throw new ApiError(`conversation ${conversationId} not found`, 404); - if (tx.select().from(tasks).where(and(eq(tasks.conversationId, conversationId), eq(tasks.kind, input.kind), eq(tasks.status, 'open'))).get()) continue; // already waiting for someone + // Already waiting for someone: skipped, so a batch over a mixed selection still hands out the rest. + if (tx.select().from(tasks).where(and(eq(tasks.conversationId, conversationId), eq(tasks.kind, input.kind), eq(tasks.status, 'open'))).get()) { + skipped.push(conversationId); + continue; + } const review = tx.select().from(reviews).where(eq(reviews.conversationId, conversationId)).get(); if (input.kind === 'crosscheck' && review?.status !== 'reviewed') throw new ApiError(`dialog ${conversationId} must be reviewed before a cross-check`, 409); const first = input.kind === 'crosscheck' ? review?.byId ?? undefined : undefined; @@ -147,6 +157,8 @@ export function createTasks(db: Db, input: CreateTasksInput, actor?: Actor): Tas notify(tx, [assigneeId], { kind: 'task', title: input.kind === 'crosscheck' ? `Контрольная проверка: ${conversationId}` : `Новая задача: ${conversationId}`, body: 'Вам назначена проверка диалога.', conversationId }); created.push(toTask(row)); } + // Nothing new at all is a conflict, not a silent success. The web matches 'already has an open task'. + if (!created.length && skipped.length) throw new ApiError(`${skipped.length === 1 ? `dialog ${skipped[0]}` : `each of the ${skipped.length} dialogs`} already has an open task of this kind`, 409); return created; }); } @@ -173,10 +185,14 @@ export function sampleCrosschecks(db: Db, percent: number, actor?: Actor): Task[ const toCrosscheck = (r: typeof crosschecks.$inferSelect): Crosscheck => CrosscheckSchema.parse({ ...r, reviewerId: r.reviewerId ?? undefined }); -/** A QA person sees only their own cross-checks (blind: not each other's); top managers and admins see all. */ +/** + * A QA person sees only their own cross-checks (blind: not each other's); a manager those on their team's dialogs; + * top managers and admins see all. + */ export function listCrosschecks(db: Db, actor: Actor | undefined): Crosscheck[] { const rows = db.select().from(crosschecks).orderBy(asc(crosschecks.submittedAt)).all(); - return rows.filter((r) => !actor || can(actor, 'task') || can(actor, 'audit') || r.reviewerId === actor.id).map(toCrosscheck); + const scope = actor?.role === 'manager' ? scopeOf(db, actor) : undefined; + return rows.filter((r) => !actor || can(actor, 'task') || can(actor, 'audit') || r.reviewerId === actor.id || (scope !== undefined && canSee(scope, { operatorId: operatorOf(db, r.conversationId) }))).map(toCrosscheck); } export function submitCrosscheck(db: Db, input: SubmitCrosscheckInput, actor?: Actor): Crosscheck { diff --git a/apps/api/test/team.test.ts b/apps/api/test/team.test.ts index 8f3fd4e..6371ae3 100644 --- a/apps/api/test/team.test.ts +++ b/apps/api/test/team.test.ts @@ -120,7 +120,9 @@ describe('tasks, cross-checks and QA-of-QA', () => { expect((await post(app, '/api/tasks', lead, { conversationIds: ['d3'], kind: 'crosscheck' })).statusCode).toBe(409); // not reviewed yet const cc = (await post(app, '/api/tasks', lead, { conversationIds: ['d1'], kind: 'crosscheck' })).json(); expect(cc[0]).toMatchObject({ assigneeId: 'qa-2', firstReviewerId: 'qa-1' }); - expect((await post(app, '/api/tasks', lead, { conversationIds: ['d1'], kind: 'crosscheck', assigneeId: 'qa-1' })).json()).toEqual([]); // one open cross-check per dialog + const again = await post(app, '/api/tasks', lead, { conversationIds: ['d1'], kind: 'crosscheck', assigneeId: 'qa-1' }); // one open cross-check per dialog + expect(again.statusCode).toBe(409); + expect(again.json().error).toContain('already has an open task'); }); it('a cross-check is a blind re-grade by someone else; the first reviewer cannot do it, QA only see their own, leads see all', async () => { @@ -197,3 +199,120 @@ describe('directory', () => { expect((await get(app, '/api/conversations', admin))[0].operatorId).toMatch(/^op-/); }); }); + +describe('review fixes: alerts, task conflicts, audit of auto-closed tasks', () => { + it('a reviewer correction that newly raises a critical flag alerts the manager and the top managers once', async () => { + const { app } = world(); + expect(await get(app, '/api/notifications', mgr)).toEqual([]); + expect((await post(app, '/api/evaluations/e-d1/overrides', qa1, { criterionId: '08', reason: 'Раскрыты данные', value: true })).statusCode).toBe(201); + expect((await get(app, '/api/notifications', mgr)).filter((n: { kind: string }) => n.kind === 'critical')).toHaveLength(1); + expect((await get(app, '/api/notifications', lead)).filter((n: { kind: string }) => n.kind === 'critical')).toHaveLength(1); + // Still raised after another change: not "newly" raised, no second alert. + await post(app, '/api/evaluations/e-d1/overrides', qa1, { criterionId: '04', reason: 'Уточнение', value: 20 }); + expect((await get(app, '/api/notifications', mgr)).filter((n: { kind: string }) => n.kind === 'critical')).toHaveLength(1); + }); + + it('an appeal decision that raises a critical flag alerts too', async () => { + const { app } = world(); + const appeal = (await post(app, '/api/evaluations/e-d1/appeals', o1, { criterionId: '08', comment: 'x' })).json(); + expect((await post(app, `/api/appeals/${appeal.id}/decision`, qa1, { action: 'override', reason: 'Нарушение есть', value: true })).statusCode).toBe(200); + expect((await get(app, '/api/notifications', mgr)).filter((n: { kind: string }) => n.kind === 'critical')).toHaveLength(1); + }); + + it('seeding the demo organisation backfills critical alerts of already evaluated dialogs to the right people', async () => { + const db = openDb(':memory:'); + const app = buildApp({ db }); + const at = new Date().toISOString(); + for (const id of ['x1', 'x2']) db.insert(conversations).values({ id, datasetGroupId: 'g', language: 'RU', channel: 'agent chat', audioUrl: null, transcript: conv.transcript, importedAt: at }).run(); + const raised = base.finalResults.map((r) => (r.criterionId === '08' ? { ...r, value: true } : r)); + insertEvaluation(db, { ...base, id: 'e-x1', conversationId: 'x1', seriousViolation: true, finalResults: raised } as Evaluation); // op-1, team A + insertEvaluation(db, { ...base, id: 'e-x2', conversationId: 'x2' } as Evaluation); // clean + expect((await post(app, '/api/demo/org', who('admin', 'admin-1'))).statusCode).toBe(201); + const crit = async (id: string, role = 'manager') => (await get(app, '/api/notifications', who(role, id))).filter((n: { kind: string }) => n.kind === 'critical'); + expect(await crit('mgr-a')).toEqual([expect.objectContaining({ conversationId: 'x1' })]); + expect(await crit('mgr-b')).toEqual([]); + expect(await crit('lead-1', 'lead')).toHaveLength(1); + }); + + it('re-assigning only dialogs that already have an open task is a 409; a mixed batch creates the rest', async () => { + const { app } = world(); + expect((await post(app, '/api/tasks', lead, { conversationIds: ['d3'], kind: 'review' })).statusCode).toBe(201); + const again = await post(app, '/api/tasks', lead, { conversationIds: ['d3'], kind: 'review' }); + expect(again.statusCode).toBe(409); + expect(again.json().error).toContain('already has an open task'); + const mixed = await post(app, '/api/tasks', lead, { conversationIds: ['d3', 'd2'], kind: 'review' }); + expect(mixed.statusCode).toBe(201); + expect(mixed.json().map((t: { conversationId: string }) => t.conversationId)).toEqual(['d2']); + }); + + it('closing the review task by finishing the check is in the audit log', async () => { + const { app } = world(); + const [task] = (await post(app, '/api/tasks', lead, { conversationIds: ['d1'], kind: 'review', assigneeId: 'qa-1' })).json(); + await review(app, 'd1', qa1); + expect(await get(app, '/api/events?type=task.done', lead)).toEqual([expect.objectContaining({ conversationId: 'd1', actorId: 'qa-1', data: expect.objectContaining({ taskId: task.id }) })]); + }); +}); + +describe('review fixes: cross-check visibility', () => { + const results = base.finalResults.map((r) => ({ criterionId: r.criterionId, value: r.value, isNA: r.isNA })); + + it('a manager sees the cross-checks on their team\'s dialogs only', async () => { + const { app } = world(); + for (const d of ['d1', 'd3']) { + await review(app, d, qa1); + const [task] = (await post(app, '/api/tasks', lead, { conversationIds: [d], kind: 'crosscheck' })).json(); + expect((await post(app, '/api/crosschecks', qa2, { taskId: task.id, results })).statusCode).toBe(201); + } + expect((await get(app, '/api/crosschecks', mgr)).map((c: { conversationId: string }) => c.conversationId)).toEqual(['d1']); + }); + + it('is blind: the second reviewer sees the AI results, not the first review, until they submit', async () => { + const { app } = world(); + const ai04 = base.finalResults.find((r) => r.criterionId === '04')!.value; + await post(app, '/api/evaluations/e-d1/overrides', qa1, { criterionId: '04', reason: 'Иначе', value: 20 }); + await review(app, 'd1', qa1); + const [task] = (await post(app, '/api/tasks', lead, { conversationIds: ['d1'], kind: 'crosscheck' })).json(); + expect(task.assigneeId).toBe('qa-2'); + const v04 = (e: { finalResults: { criterionId: string; value: unknown }[] }) => e.finalResults.find((r) => r.criterionId === '04')!.value; + + const blindEv = await get(app, '/api/evaluations/e-d1', qa2); + expect(v04(blindEv)).toBe(ai04); + expect(blindEv.finalTotal).toBe(blindEv.originalTotal); + expect(v04((await get(app, '/api/evaluations?conversationId=d1', qa2))[0])).toBe(ai04); + expect(await get(app, '/api/evaluations/e-d1/appeals', qa2)).toEqual([]); + expect((await get(app, '/api/appeals', qa2)).filter((a: { evaluationId: string }) => a.evaluationId === 'e-d1')).toEqual([]); + expect((await get(app, '/api/conversations/d1', qa2)).review).toBeUndefined(); + expect((await get(app, '/api/conversations', qa2)).find((c: { id: string }) => c.id === 'd1').review).toBeUndefined(); + + // Everyone else still sees the first review. + expect(v04(await get(app, '/api/evaluations/e-d1', qa1))).toBe(20); + expect(v04(await get(app, '/api/evaluations/e-d1', lead))).toBe(20); + expect((await get(app, '/api/conversations/d1', lead)).review).toMatchObject({ status: 'reviewed' }); + expect(await get(app, '/api/evaluations/e-d1/appeals', lead)).toHaveLength(1); + + expect((await post(app, '/api/crosschecks', qa2, { taskId: task.id, results })).statusCode).toBe(201); + expect(v04(await get(app, '/api/evaluations/e-d1', qa2))).toBe(20); + expect((await get(app, '/api/conversations/d1', qa2)).review).toMatchObject({ status: 'reviewed' }); + }); + + it('a top manager doing a QA-of-QA check is not blinded', async () => { + const { app } = world(); + await post(app, '/api/evaluations/e-d1/overrides', qa1, { criterionId: '04', reason: 'Иначе', value: 20 }); + await review(app, 'd1', qa1); + await post(app, '/api/tasks', lead, { conversationIds: ['d1'], kind: 'crosscheck', assigneeId: 'lead-1' }); + expect((await get(app, '/api/evaluations/e-d1', lead)).finalResults.find((r: { criterionId: string }) => r.criterionId === '04').value).toBe(20); + }); +}); + +describe('review fixes: tags follow the taxonomy', () => { + it('accepts any category while the taxonomy is empty, then only its items', async () => { + const { app } = world(); + expect((await post(app, '/api/tags', qa1, { evaluationId: 'e-d1', origin: 'rule', label: 'Что угодно' })).statusCode).toBe(201); + await post(app, '/api/taxonomy', lead, { label: 'Неполный ответ' }); + const bad = await post(app, '/api/tags', qa1, { evaluationId: 'e-d1', origin: 'rule', label: 'Что угодно' }); + expect(bad.statusCode).toBe(400); + expect(bad.json().error).toBe('tag is not in the taxonomy'); + expect((await post(app, '/api/tags', qa1, { evaluationId: 'e-d1', origin: 'rule', label: 'Неполный ответ' })).statusCode).toBe(201); + expect((await post(app, '/api/tags', qa1, { evaluationId: 'e-d1', origin: 'process' })).statusCode).toBe(201); // origin only + }); +}); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 7765188..86a83ec 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,4 +1,4 @@ -import { can, type Comment, type Directory, type ErrorOrigin, type Notification, type SaveTimelineEventInput, type Tag as ErrorTag, type Task, type TaxonomyItem, type TimelineEvent, type Appeal, type ChecklistVersion, type Conversation, type DecideAppealInput, type Evaluation, type SaveChecklistInput } from '@cqa/contracts'; +import { can, ROLE_LABELS, type Comment, type Crosscheck, type Directory, type ErrorOrigin, type Notification, type SaveTimelineEventInput, type Tag as ErrorTag, type Task, type TaxonomyItem, type TimelineEvent, type Appeal, type ChecklistVersion, type Conversation, type DecideAppealInput, type Evaluation, type SaveChecklistInput } from '@cqa/contracts'; import { AlertTriangle, ArrowLeft, ChevronLeft, ChevronRight, PanelLeftOpen } from 'lucide-react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { MockCqaApi } from './api'; @@ -92,6 +92,8 @@ export function App() { const [starting, setStarting] = useState(false); const [startError, setStartError] = useState(null); const [searchFocus, setSearchFocus] = useState(0); + const [notice, setNotice] = useState(null); + const [submittedCc, setSubmittedCc] = useState(null); const [onlyFlagged, setOnlyFlagged] = useState(false); const fits = useWide(); /** The queue rail is optional: a reviewer can collapse it (remembered per browser; storage may be unavailable). */ @@ -186,6 +188,32 @@ export function App() { }; }, [fetchAll]); + /** The inbox refreshes every 45 s and when the window regains focus, so a new comment or task shows without a reload. */ + const ready = load.status === 'ready'; + useEffect(() => { + if (!ready) return; + let live = true; + const refresh = () => { + if (document.hidden) return; + api.listNotifications().then((notifications) => live && setLoad((l) => (l.status === 'ready' ? { status: 'ready', data: { ...l.data, notifications } } : l)), () => {}); + }; + const timer = window.setInterval(refresh, 45_000); + window.addEventListener('focus', refresh); + return () => { + live = false; + window.clearInterval(timer); + window.removeEventListener('focus', refresh); + }; + }, [api, ready, identity.role, identity.id]); + + /** The first-visit identity names nobody; once the directory exists it becomes the directory's first person of that role, so the bell and the tasks belong to a real account. */ + const directoryPeople = load.status === 'ready' ? load.data.directory.people : null; + useEffect(() => { + if (!directoryPeople || identity.id) return; + const first = directoryPeople.find((p) => p.role === identity.role); + if (first && identity.name === ROLE_LABELS[identity.role]) setIdentity({ role: first.role, name: first.name, id: first.id }); + }, [directoryPeople, identity]); + /** Evaluations per conversation, oldest first (the API lists them in creation order). */ const byConversation = useMemo(() => { const m = new Map(); @@ -371,19 +399,33 @@ export function App() { const setReview = async (status: 'new' | 'in_review' | 'reviewed') => { if (!conversation) return; await api.setReview(conversation.id, { status }); + if (status === 'reviewed') await readRelated(conversation.id, ['task']); await reload(); if (status !== 'reviewed') return; + const flash = (text: string) => { + setNotice(text); + window.setTimeout(() => setNotice((cur) => (cur === text ? null : cur)), 4000); + }; const from = Math.max(queue.indexOf(conversation.id), 0); for (let k = 1; k < queue.length; k++) { const id = queue[(from + k) % queue.length]!; const c = data.conversations.find((x) => x.id === id); - if (c && reviewOf(c, latest.get(id)).state === 'new') return go({ name: 'dialog', id }); + if (c && reviewOf(c, latest.get(id)).state === 'new') { + flash('Отмечено проверенным · следующий диалог'); + return go({ name: 'dialog', id }); + } } + flash('Отмечено проверенным'); }; const act = async (f: () => Promise) => { await f(); await reload(); }; + /** Notifications about a dialog are read once the thing they announce is dealt with (comment acknowledged, task opened or done). */ + const readRelated = async (conversationId: string, kinds: Notification['kind'][]) => { + const ids = data.notifications.filter((n) => !n.readAt && n.conversationId === conversationId && kinds.includes(n.kind)).map((n) => n.id); + if (ids.length) await api.markNotificationsRead(ids); + }; const openNotification = (n: Notification) => { void api.markNotificationsRead([n.id]).then(reload); if (n.conversationId) go({ name: 'dialog', id: n.conversationId, ...(n.criterionId ? { criterion: n.criterionId } : {}) }); @@ -429,7 +471,7 @@ export function App() {

{conversation.id}

-

{conversation.language} · {conversation.channel === 'voice call' ? 'звонок' : 'чат'} · {conversation.transcript.length} сообщений{staff && conversation.operatorId ? ` · оператор ${conversation.operatorId}` : ''}

+

{conversation.language} · {conversation.channel === 'voice call' ? 'звонок' : 'чат'} · {conversation.transcript.length} сообщений{staff && conversation.operatorId ? ` · оператор ${data.directory.people.find((p) => p.id === conversation.operatorId)?.name ?? conversation.operatorId}` : ''}

{!wide && (
@@ -465,10 +507,11 @@ export function App() { sections={SECTIONS[identity.role]} active={sectionOf(route)} pendingAppeals={data.appeals.filter((a) => a.status === 'pending').length} - openTasks={data.tasks.filter((t) => t.status === 'open' && (can(identity, 'task') || t.assigneeId === identity.id)).length} + openTasks={data.tasks.filter((t) => t.status === 'open' && t.assigneeId === identity.id).length} notifications={data.notifications} onNotification={openNotification} onReadNotifications={() => void api.markNotificationsRead().then(reload)} + onSeedDemo={() => act(() => api.seedDemoOrg())} onNavigate={(to) => go(to === 'dialogs' ? { name: 'list' } : { name: to })} theme={theme} onToggleTheme={toggleTheme} @@ -481,7 +524,7 @@ export function App() { ) : route.name === 'tasks' ? (
- go({ name: 'dialog', id })} onOpenCrosscheck={(id) => go({ name: 'crosscheck', id })} + { void readRelated(id, ['task']).then(reload); go({ name: 'dialog', id }); }} onOpenCrosscheck={(id) => { const t = data.tasks.find((x) => x.id === id); if (t) void readRelated(t.conversationId, ['crosscheck', 'task']).then(reload); go({ name: 'crosscheck', id }); }} onSample={async (percent) => { const made = await api.sampleCrosschecks(percent); await reload(); return made.length; }} onCancel={(id) => act(() => api.cancelTask(id))} />
) : route.name === 'analytics' ? ( @@ -504,8 +547,8 @@ export function App() { const evals = byConversation.get(task?.conversationId ?? ''); const evl = evals?.[evals.length - 1]; const cl = data.checklists.find((c) => c.id === evl?.checklistVersionId); - return task && conv && evl && cl && task.status === 'open' ? ( - go({ name: 'tasks' })} onSubmit={(results) => act(() => api.submitCrosscheck({ taskId: task.id, results }))} /> + return task && conv && evl && cl && (task.status === 'open' || submittedCc?.taskId === task.id) ? ( + go({ name: 'tasks' })} onSubmit={async (results) => { setSubmittedCc(await api.submitCrosscheck({ taskId: task.id, results })); await reload(); }} /> ) : (

Эта проверка недоступна или уже выполнена.

); @@ -516,7 +559,7 @@ export function App() { ) : route.name === 'appeals' ? (
- go({ name: 'dialog', id, criterion })} identity={identity} /> + go({ name: 'dialog', id, criterion })} identity={identity} people={data.directory.people} />
) : route.name === 'list' ? (
@@ -567,7 +610,7 @@ export function App() { tags={data.tags.filter((t) => t.evaluationId === evaluationId)} taxonomy={data.taxonomy} onAddComment={(body) => act(() => api.addComment({ conversationId: conversation.id, body }))} - onAckComment={(id) => act(() => api.acknowledgeComment(id))} + onAckComment={(id) => act(async () => { const c = await api.acknowledgeComment(id); await readRelated(c.conversationId, ['comment']); })} onAddTag={(cid, origin: ErrorOrigin, label) => act(() => api.addTag({ evaluationId: evaluation!.id, criterionId: cid, origin, ...(label ? { label } : {}) }))} key={conversation.id} conversation={conversation} @@ -611,6 +654,7 @@ export function App() { )}
+
{notice}
{route.name === 'dialog' && conversation && evaluation?.status === 'completed' && x.evaluationId === evaluation.id)} />} ); diff --git a/apps/web/src/features/AnalyticsPage.tsx b/apps/web/src/features/AnalyticsPage.tsx index f183c5b..4befc69 100644 --- a/apps/web/src/features/AnalyticsPage.tsx +++ b/apps/web/src/features/AnalyticsPage.tsx @@ -43,16 +43,16 @@ const Card = ({ title, hint, children }: { title: string; hint?: string; childre function RankTable({ rows, label }: { rows: RankRow[]; label: string }) { return (
- +
- + {rows.map((r) => ( - - - - + + + + @@ -219,15 +219,18 @@ export function AnalyticsPage(p: Props) {
{[['Очередь', `${qa.queueLength}`, 'оценённых диалогов без проверки'], ['Самый старый', qa.backlogAgeDays === null ? '—' : `${num(qa.backlogAgeDays)} дн.`, 'ждёт проверки'], ['Медиана проверки', qa.medianMinutes === null ? '—' : `${num(qa.medianMinutes)} мин`, 'от «в работе» до «проверено»'], ['За 7 дней', `${qa.reviewedLast7Days}`, `в среднем ${num(qa.perDay)} в день`]].map(([k, v, h]) =>
{k}
{v}

{h}

)}
-
{label}
№{label}ОцененоСредний итогНарушений
№{label}ОцененоСредний итогНарушений
{r.rank ?? '—'}{r.name}{r.teamName && {r.teamName}}{!r.rankable && мало данных}{r.n} из {r.dialogs}{num(r.average)}{r.rank ?? '—'}{r.name}{r.teamName && {r.teamName}}{!r.rankable && мало данных}{r.n} из {r.dialogs}{num(r.average)} {r.violations}
{qa.rows.map((r) => )}
Проверяющие
ПроверяющийПровереноС замеромМедиана, минОткрытых задач
{r.reviewer}{r.reviewed}{r.timed}{num(r.medianMinutes)}{r.openTasks}
+ {qa.rows.map((r) => )}
Проверяющие
ПроверяющийПровереноС замеромМедиана, минОткрытых задач
{r.reviewer}{r.reviewed}{r.timed}{num(r.medianMinutes)}{r.openTasks}
)} - {agree.rows.length === 0 ? Контрольных проверок пока нет: топ-менеджер назначает их на странице «Задачи». : ( + {agree.rows.length === 0 ? {p.identity.role === 'manager' ? 'Контрольных проверок по вашей группе пока нет' : 'Контрольных проверок пока нет: топ-менеджер назначает их на странице «Задачи».'} : ( <> - {agree.rows.map((r) => )}
Согласованность
Кто проверялПроверокС первой проверкойС ИИ
{r.reviewer}{r.role === 'lead' && контроль QA}{r.checks}{pct(r.agreeFirst / r.results)}{pct(r.agreeAi / r.results)}
-

Меньше всего согласия: {agree.byCriterion.slice(0, 3).map((c) => `${c.criterionId} ${critTitle(c.criterionId)} (${pct(c.agreeFirst / c.results)})`).join('; ')}.

+ {agree.rows.map((r) => )}
Согласованность
Кто проверялПроверокС первой проверкойС ИИ
{r.reviewer}{r.role === 'lead' && контроль QA}{r.checks}{r.results >= MIN_N ? pct(r.agreeFirst / r.results) : —}{r.results >= MIN_N ? pct(r.agreeAi / r.results) : —}
+ {(() => { + const enough = agree.byCriterion.filter((c) => c.results >= MIN_N).slice(0, 3); + return

{enough.length ? `Меньше всего согласия: ${enough.map((c) => `${c.criterionId} ${critTitle(c.criterionId)} (${pct(c.agreeFirst / c.results)})`).join('; ')}.` : `Процент согласия показывается от ${MIN_N} результатов; пока проверок мало для вывода.`}

; + })()} )}
diff --git a/apps/web/src/features/Appeals.tsx b/apps/web/src/features/Appeals.tsx index f9ecc7f..41db5b8 100644 --- a/apps/web/src/features/Appeals.tsx +++ b/apps/web/src/features/Appeals.tsx @@ -55,7 +55,7 @@ function AnswerPicker({ name, opts, current, picked, onPick }: { name: string; o const now = isCurrent(o, current); return ( @@ -186,8 +186,8 @@ export function ReviewBox({ identity, evaluation, checklist, criterionId, criter

Подана {fmt(pending.createdAt)}{pending.createdBy ? ` · ${pending.createdBy}` : ''}

- - + +
{action === 'override' && ( <> diff --git a/apps/web/src/features/AppealsPage.tsx b/apps/web/src/features/AppealsPage.tsx index 56fa3da..3015476 100644 --- a/apps/web/src/features/AppealsPage.tsx +++ b/apps/web/src/features/AppealsPage.tsx @@ -1,4 +1,4 @@ -import type { Actor, Appeal, ChecklistVersion, Conversation, Evaluation } from '@cqa/contracts'; +import type { Actor, Appeal, ChecklistVersion, Conversation, Evaluation, Person } from '@cqa/contracts'; import { useMemo, useState } from 'react'; import { Badge } from '@/components/ui/badge'; import { cn } from '@/lib/utils'; @@ -11,6 +11,7 @@ type Props = { conversations: Conversation[]; onOpen: (conversationId: string, criterionId: string) => void; identity: Actor; + people?: Person[]; }; type Filter = 'pending' | 'decided' | 'all'; @@ -22,11 +23,12 @@ const STATUS = { pending: { label: 'На рассмотрении', tone: 'warn' * Appeals by role. A reviewer or lead gets the approver's queue (across all dialogs; opening one lands on the criterion with * the decision form). An operator gets their own appeals and what was decided; the server already limits the list to them. */ -export function AppealsPage({ appeals: all, evaluations, checklists, conversations, onOpen, identity }: Props) { +export function AppealsPage({ appeals: all, evaluations, checklists, conversations, onOpen, identity, people = [] }: Props) { const mine = identity.role === 'operator'; const [filter, setFilter] = useState('pending'); // Direct corrections by a reviewer are audit history of a dialog, not disputes: they never enter this queue. const appeals = useMemo(() => all.filter((a) => a.kind !== 'correction'), [all]); + const nameOf = (id: string | null | undefined) => (id ? people.find((p) => p.id === id)?.name ?? id : undefined); const pending = appeals.filter((a) => a.status === 'pending').length; const rows = useMemo(() => { @@ -86,7 +88,7 @@ export function AppealsPage({ appeals: all, evaluations, checklists, conversatio conv && onOpen(conv.id, a.criterionId)} className={cn('align-top', conv && 'cursor-pointer hover:bg-brand-soft/60')}> {conv ? ( - e.stopPropagation()} className="inline-flex min-h-6 items-center text-base font-medium text-accent underline-offset-2 hover:underline">{conv.id} + e.stopPropagation()} className="inline-flex min-h-6 items-center whitespace-nowrap text-base font-medium text-accent underline-offset-2 hover:underline">{conv.id} ) : ( Диалог не найден )} @@ -100,7 +102,7 @@ export function AppealsPage({ appeals: all, evaluations, checklists, conversatio {changed && final &&
Итог: {grade(criterion, final).label}
} {fmt(a.createdAt)} - {!mine && {a.createdBy ?? conv?.operatorId ?? —}} + {!mine && {nameOf(a.createdBy ?? conv?.operatorId) ?? —}} {STATUS[a.status].label} {a.status !== 'pending' && (a.reviewerReason || a.decidedBy) &&

{a.decidedBy ? `${a.decidedBy}: ` : ''}{a.reviewerReason}

} diff --git a/apps/web/src/features/AuditPage.tsx b/apps/web/src/features/AuditPage.tsx index a0c19e7..49931cb 100644 --- a/apps/web/src/features/AuditPage.tsx +++ b/apps/web/src/features/AuditPage.tsx @@ -1,4 +1,4 @@ -import type { AuditEvent } from '@cqa/contracts'; +import { ROLE_LABELS, type AuditEvent } from '@cqa/contracts'; import { ShieldAlert } from 'lucide-react'; import { useEffect, useMemo, useState } from 'react'; import { useApi } from '@/ApiContext'; @@ -62,7 +62,7 @@ export function AuditPage({ onOpenDialog }: { onOpenDialog: (id: string) => void
- {rows.slice(0, 500).map((e) => )} + {rows.slice(0, 500).map((e) => )}
Журнал действий
КогдаКтоЧтоДиалог
{fmt(e.at)}{e.actorName}{e.actorRole && {e.actorRole}}{TYPE_LABEL[e.type] ?? e.type}{e.summary}{e.conversationId && }
{fmt(e.at)}{e.actorName}{e.actorRole && {ROLE_LABELS[e.actorRole]}}{TYPE_LABEL[e.type] ?? e.type}{e.summary}{e.conversationId && }
{rows.length === 0 &&

Записей нет.

}
diff --git a/apps/web/src/features/CrosscheckPage.tsx b/apps/web/src/features/CrosscheckPage.tsx index f270a6d..a465a2d 100644 --- a/apps/web/src/features/CrosscheckPage.tsx +++ b/apps/web/src/features/CrosscheckPage.tsx @@ -1,10 +1,10 @@ -import type { ChecklistVersion, Conversation, CriterionResult, CriterionValue, Evaluation, Task } from '@cqa/contracts'; +import type { ChecklistVersion, Conversation, Crosscheck, CriterionResult, CriterionValue, Evaluation, Task } from '@cqa/contracts'; import { ArrowLeft } from 'lucide-react'; import { useState } from 'react'; import { Button } from '@/components/ui/button'; import { ErrorNote } from '@/components/ui/error-note'; import { PlayerProvider } from '@/lib/player'; -import { outcome } from '@/lib/present'; +import { grade } from '@/lib/present'; import { Transcript } from './Transcript'; type Props = { @@ -13,6 +13,8 @@ type Props = { evaluation: Evaluation; checklist: ChecklistVersion; onSubmit: (results: { criterionId: string; value: CriterionValue | null; isNA: boolean }[]) => Promise; + /** Set after the answer was sent: the page then shows how it compares with the first review. */ + submitted?: Crosscheck; onBack: () => void; }; @@ -20,9 +22,9 @@ const probe = (criterionId: string, value: CriterionValue | null, isNA: boolean) /** * Blind re-grade: the transcript and the criteria, nothing about what the AI or the first reviewer answered. The - * answer is the checker's own; agreement is computed afterwards in the analytics, never shown here. + * answer is the checker's own. Only after sending is the comparison with the first review shown. */ -export function CrosscheckPage({ task, conversation, evaluation, checklist, onSubmit, onBack }: Props) { +export function CrosscheckPage({ task, conversation, evaluation, checklist, onSubmit, submitted, onBack }: Props) { const [picked, setPicked] = useState>({}); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); @@ -37,13 +39,20 @@ export function CrosscheckPage({ task, conversation, evaluation, checklist, onSu const k = picked[c!.id]!; return k === 'na' ? { criterionId: c!.id, value: null, isNA: true } : { criterionId: c!.id, value: c!.allowedValues[Number(k)]!, isNA: false }; })); - onBack(); } catch (e) { setError(e); } finally { setBusy(false); } }; + const answerText = (c: (typeof criteria)[number], r: { value: CriterionValue | null; isNA: boolean } | undefined) => (r ? grade(c, { criterionId: c!.id, value: r.value, isNA: r.isNA, explanation: '', evidence: [] }).label : '—'); + const same = (a: { value: unknown; isNA: boolean } | undefined, b: { value: unknown; isNA: boolean } | undefined) => !!a && !!b && a.isNA === b.isNA && a.value === b.value; + const compared = submitted ? criteria.map((c) => { + const mine = submitted.results.find((r) => r.criterionId === c!.id); + const first = evaluation.finalResults.find((r) => r.criterionId === c!.id); + return { c, mine, first, agree: same(mine, first) }; + }) : []; + const agreed = compared.filter((x) => x.agree).length; return (
@@ -53,14 +62,35 @@ export function CrosscheckPage({ task, conversation, evaluation, checklist, onSu

Ваша оценка

-

Вслепую: ответы ИИ и первого проверяющего скрыты. Оцените каждый критерий сами по транскрипту.

+

{submitted ? 'Теперь видно, как ваш ответ соотносится с первой проверкой.' : 'Вслепую: ответы ИИ и первого проверяющего скрыты. Оцените каждый критерий сами по транскрипту.'}

+ {submitted ? ( +
+

Проверка отправлена. Совпало с первой проверкой: {agreed} из {compared.length}{compared.length > 0 && ({Math.round((agreed / compared.length) * 100)}%)}

+
+ + + + + {compared.map(({ c, mine, first, agree }) => ( + + + + + + + ))} + +
Сравнение с первой проверкой
КритерийВаш ответПервая проверкаИтог
{c!.id}{c!.title}{answerText(c, mine)}{answerText(c, first)}{agree ? 'Совпало' : 'Расходится'}
+
+
+ ) : (
{criteria.map((c) => (
{c!.id}{c!.title}
Как оценивается

{c!.instructions}

- {[...c!.allowedValues.map((v, i) => ({ key: String(i), label: outcome(c, probe(c!.id, v, false)).label })), ...(c!.allowNA ? [{ key: 'na', label: 'N/A' }] : [])].map((o) => ( + {[...c!.allowedValues.map((v, i) => ({ key: String(i), label: grade(c, probe(c!.id, v, false)).label })), ...(c!.allowNA ? [{ key: 'na', label: 'N/A' }] : [])].map((o) => ( @@ -68,9 +98,10 @@ export function CrosscheckPage({ task, conversation, evaluation, checklist, onSu
))}
+ )}
- + {submitted ? : }
diff --git a/apps/web/src/features/DialogNotes.tsx b/apps/web/src/features/DialogNotes.tsx index 6c34652..81cfcc9 100644 --- a/apps/web/src/features/DialogNotes.tsx +++ b/apps/web/src/features/DialogNotes.tsx @@ -1,4 +1,4 @@ -import { can, ERROR_ORIGIN_LABELS, ErrorOriginSchema, type Actor, type Comment, type ErrorOrigin, type Tag, type TaxonomyItem } from '@cqa/contracts'; +import { can, ERROR_ORIGIN_LABELS, ErrorOriginSchema, type Actor, type ChecklistVersion, type Comment, type ErrorOrigin, type Tag, type TaxonomyItem } from '@cqa/contracts'; import { Check } from 'lucide-react'; import { useId, useState } from 'react'; import { Badge } from '@/components/ui/badge'; @@ -25,8 +25,11 @@ export function CriterionTags({ identity, criterionId, tags, taxonomy, onAdd }: {canTag && (
{ e.preventDefault(); setError(null); onAdd(origin, label.trim() || undefined).then(() => setLabel(''), setError); }}> - setLabel(e.target.value)} placeholder="Категория (необязательно)" title="Категория (необязательно)" className="h-8 min-w-56 flex-1 rounded-full border border-transparent bg-fill px-3 text-sm placeholder:text-muted" /> - {options.map((t) => + {taxonomy.length > 0 ? ( + options.length > 0 && + ) : ( + setLabel(e.target.value)} placeholder="Категория (необязательно)" title="Категория (необязательно)" className="h-8 min-w-56 flex-1 rounded-full border border-transparent bg-fill px-3 text-sm placeholder:text-muted" /> + )}
)} @@ -36,20 +39,23 @@ export function CriterionTags({ identity, criterionId, tags, taxonomy, onAdd }: } /** Coaching comments on the dialog: written by QA or managers, read and acknowledged by the operator. */ -export function DialogComments({ identity, conversationId, comments, onAdd, onAck }: { identity: Actor; conversationId: string; comments: Comment[]; onAdd: (body: string) => Promise; onAck: (id: string) => Promise }) { +export function DialogComments({ identity, conversationId, comments, checklist, onAdd, onAck }: { identity: Actor; conversationId: string; comments: Comment[]; checklist?: ChecklistVersion; onAdd: (body: string) => Promise; onAck: (id: string) => Promise }) { const [text, setText] = useState(''); const [error, setError] = useState(null); - const mine = comments.filter((c) => c.conversationId === conversationId && !c.criterionId); + const mine = comments.filter((c) => c.conversationId === conversationId); const canWrite = can(identity, 'comment'); if (mine.length === 0 && !canWrite) return null; return ( -
+

Комментарии к работе

{mine.length === 0 &&

Комментариев пока нет.

}