From 5785cf1c5d201e3e3f2d221cb1758dc1be5f3178 Mon Sep 17 00:00:00 2001 From: Anish Mehta Date: Wed, 18 Nov 2026 16:10:38 +0530 Subject: [PATCH 1/2] fix(tasks): keep the task status in step with its assignments Task.status was never written, so every task showed PENDING. It is now worked out from the task's assignments whenever one is assigned, started, submitted or reviewed, with the task row locked: approved once all are approved, submitted while any awaits review, rework while any was sent back, in progress once anyone started, otherwise pending. Migration task_status_backfill applies the same rule once to existing tasks. --- apps/api/src/tasks/tasks.service.spec.ts | 31 ++++++++++++++++--- apps/api/src/tasks/tasks.service.ts | 30 ++++++++++++++++++ docs/api.md | 7 +++++ .../migration.sql | 18 +++++++++++ 4 files changed, 82 insertions(+), 4 deletions(-) create mode 100644 packages/db/prisma/migrations/20261118103912_task_status_backfill/migration.sql diff --git a/apps/api/src/tasks/tasks.service.spec.ts b/apps/api/src/tasks/tasks.service.spec.ts index 20d5d4b..02b21d5 100644 --- a/apps/api/src/tasks/tasks.service.spec.ts +++ b/apps/api/src/tasks/tasks.service.spec.ts @@ -1,5 +1,5 @@ import { BadRequestException, ConflictException, ForbiddenException } from '@nestjs/common'; -import { TasksService } from './tasks.service'; +import { TasksService, taskStatusFrom } from './tasks.service'; import type { DatabaseService } from '../database.service'; import type { EventsService } from '../events/events.service'; import type { AuthorizationContext } from '../authorization/authorization.types'; @@ -12,8 +12,10 @@ type MockDb = { findMany: jest.Mock; count: jest.Mock; update: jest.Mock; + updateMany: jest.Mock; delete: jest.Mock; }; + $queryRaw: jest.Mock; taskAssignment: { create: jest.Mock; findFirst: jest.Mock; @@ -62,12 +64,14 @@ describe('TasksService WebSocket Event Emissions', () => { findMany: jest.fn(), count: jest.fn(), update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), delete: jest.fn(), }, + $queryRaw: jest.fn().mockResolvedValue([]), taskAssignment: { create: jest.fn(), findFirst: jest.fn(), - findMany: jest.fn(), + findMany: jest.fn().mockResolvedValue([]), count: jest.fn(), update: jest.fn(), updateMany: jest.fn().mockResolvedValue({ count: 1 }), @@ -290,6 +294,9 @@ describe('TasksService WebSocket Event Emissions', () => { where: { id: 'assign-1', collegeId: 'college-1', assigneeUserId: 'faculty-1', status: TaskStatus.IN_PROGRESS }, data: { status: TaskStatus.SUBMITTED, submissionContent: 'All graded', submittedAt: expect.any(Date) }, }); + // The task's status is worked out again from its assignments, with the task row locked. + expect(mockDatabase.$queryRaw).toHaveBeenCalled(); + expect(mockDatabase.task.updateMany).toHaveBeenCalledWith({ where: { id: 'task-100', collegeId: 'college-1' }, data: { status: expect.any(String) } }); // Every attempt is kept, since a resubmission replaces the stored content. expect(mockDatabase.auditLog.create).toHaveBeenCalledWith({ data: { collegeId: 'college-1', actorId: 'faculty-1', action: 'TASK_SUBMITTED', entityType: 'TaskAssignment', entityId: 'assign-1', metadata: { taskId: 'task-100', content: 'All graded' } }, @@ -425,14 +432,30 @@ describe('TasksService my assignment stats', () => { }); }); +describe('task status', () => { + it('sums up the assignments', () => { + const { PENDING, IN_PROGRESS, SUBMITTED, APPROVED, REWORK } = TaskStatus; + expect(taskStatusFrom([])).toBe(PENDING); + expect(taskStatusFrom([PENDING, PENDING])).toBe(PENDING); + expect(taskStatusFrom([PENDING, IN_PROGRESS])).toBe(IN_PROGRESS); + expect(taskStatusFrom([APPROVED, PENDING])).toBe(IN_PROGRESS); + expect(taskStatusFrom([REWORK, IN_PROGRESS])).toBe(REWORK); + expect(taskStatusFrom([SUBMITTED, REWORK, APPROVED])).toBe(SUBMITTED); + expect(taskStatusFrom([APPROVED, APPROVED])).toBe(APPROVED); + }); +}); + describe('TasksService assignment boundaries', () => { const hod: AuthorizationContext = { userId: 'hod-1', collegeId: 'college-1', roles: ['HOD'], permissions: [], departmentId: 'dept-1' }; const admin: AuthorizationContext = { userId: 'admin-1', collegeId: 'college-1', roles: ['ADMIN'], permissions: [], departmentId: null }; const database = { - task: { findFirst: jest.fn().mockResolvedValue({ id: 'task-1', title: 'Report', departmentId: 'dept-1' }) }, - taskAssignment: { create: jest.fn() }, + task: { findFirst: jest.fn().mockResolvedValue({ id: 'task-1', title: 'Report', departmentId: 'dept-1' }), updateMany: jest.fn() }, + taskAssignment: { create: jest.fn(), findMany: jest.fn().mockResolvedValue([]) }, user: { findFirst: jest.fn() }, + $queryRaw: jest.fn().mockResolvedValue([]), + $transaction: jest.fn(), }; + database.$transaction.mockImplementation((work: (tx: typeof database) => Promise) => work(database)); const events = { emitTaskAssigned: jest.fn() }; const service = new TasksService(database as unknown as DatabaseService, events as unknown as EventsService); beforeEach(() => jest.clearAllMocks()); diff --git a/apps/api/src/tasks/tasks.service.ts b/apps/api/src/tasks/tasks.service.ts index 183eeb8..62409d3 100644 --- a/apps/api/src/tasks/tasks.service.ts +++ b/apps/api/src/tasks/tasks.service.ts @@ -21,6 +21,20 @@ const denied = (): never => { const taskMissing = (): never => { throw new NotFoundException({ code: 'TASK_NOT_FOUND', message: 'Task was not found.' }); }; +/** + * A task's status sums up its assignments, so the badge on the task means something: approved once everyone's work + * is approved; submitted while any work waits for review; rework while any was sent back; in progress once anyone + * has started (or some, but not all, are approved); otherwise pending. + */ +export const taskStatusFrom = (statuses: TaskStatus[]): TaskStatus => { + if (statuses.length === 0) return TaskStatus.PENDING; + if (statuses.every((status) => status === TaskStatus.APPROVED)) return TaskStatus.APPROVED; + if (statuses.includes(TaskStatus.SUBMITTED)) return TaskStatus.SUBMITTED; + if (statuses.includes(TaskStatus.REWORK)) return TaskStatus.REWORK; + if (statuses.some((status) => status === TaskStatus.IN_PROGRESS || status === TaskStatus.APPROVED)) return TaskStatus.IN_PROGRESS; + return TaskStatus.PENDING; +}; + /** Work can be submitted while in progress, or again after it was returned for rework. */ const SUBMITTABLE: TaskStatus[] = [TaskStatus.IN_PROGRESS, TaskStatus.REWORK]; const statusChanged = (): never => { @@ -245,6 +259,7 @@ export class TasksService { } throw error; } + await this.syncTaskStatus(taskId, context.collegeId); this.events.emitTaskAssigned( this.buildPayload(task, context, `Task assigned: ${(task as { title?: string }).title ?? taskId}`, { @@ -291,6 +306,7 @@ export class TasksService { data: { status: input.status }, }); if (written.count !== 1) statusChanged(); + await this.syncTaskStatus(existing!.taskId, context.collegeId); const updated = await this.database.taskAssignment.findUniqueOrThrow({ where: { id: assignmentId }, include: assignmentInclude }); if (input.status === TaskStatus.IN_PROGRESS) { @@ -330,6 +346,7 @@ export class TasksService { data: { collegeId: context.collegeId, actorId: context.userId, action: 'TASK_SUBMITTED', entityType: 'TaskAssignment', entityId: assignmentId, metadata: { taskId: existing!.taskId, content: input.content } }, }); }); + await this.syncTaskStatus(existing!.taskId, context.collegeId); const updated = await this.database.taskAssignment.findUniqueOrThrow({ where: { id: assignmentId }, include: assignmentInclude }); this.events.emitTaskSubmitted( @@ -388,6 +405,7 @@ export class TasksService { data: { collegeId: context.collegeId, actorId: context.userId, action: 'TASK_REVIEWED', entityType: 'TaskAssignment', entityId: assignmentId, metadata: { taskId: existing!.taskId, decision: input.decision, notes: input.notes ?? null } }, }); }); + await this.syncTaskStatus(existing!.taskId, context.collegeId); const updated = await this.database.taskAssignment.findUniqueOrThrow({ where: { id: assignmentId }, include: assignmentInclude }); this.events.emitTaskReviewed( @@ -436,6 +454,18 @@ export class TasksService { return { pending, inProgress, submitted, approved, rework, total: pending + inProgress + submitted + approved + rework }; } + /** + * Works the task's status out again from its assignments after one of them changed. The task row is locked first, + * so two changes at the same moment can't leave the status computed by whichever read first. + */ + private async syncTaskStatus(taskId: string, collegeId: string): Promise { + await this.database.$transaction(async (tx) => { + await tx.$queryRaw`SELECT id FROM "Task" WHERE id = ${taskId} AND "collegeId" = ${collegeId} FOR UPDATE`; + const assignments = await tx.taskAssignment.findMany({ where: { collegeId, taskId }, select: { status: true } }); + await tx.task.updateMany({ where: { id: taskId, collegeId }, data: { status: taskStatusFrom(assignments.map((assignment) => assignment.status)) } }); + }); + } + /* ─── Event payload builder ──────────────────────────────────────────── */ private buildPayload( diff --git a/docs/api.md b/docs/api.md index 19eb640..60da9ea 100644 --- a/docs/api.md +++ b/docs/api.md @@ -197,6 +197,13 @@ FACULTY responses leave out phone and address; ADMIN and HOD receive them. HOD a - POST /api/v1/tasks/assignments/:id/submit: only from IN_PROGRESS or REWORK (409 INVALID_STATUS_TRANSITION otherwise), so approved work can't be reopened. Each submission writes a TASK_SUBMITTED audit entry with its content, since a resubmission replaces the stored content. - PUT /api/v1/tasks/assignments/:id/review: only while SUBMITTED. The reviewer's notes go in `reviewNotes`, leaving the instructions in `notes`, and each review writes a TASK_REVIEWED audit entry with the decision and notes. - Every one of these writes applies only if the assignment is still in the state it was read in. Otherwise it returns 409 TASK_STATUS_CHANGED, so two reviewers, or a review and a resubmission, can't overwrite each other. +- A task's `status` sums up its assignments, and is worked out again whenever one is assigned, started, submitted or reviewed (with the task row locked): + - APPROVED once every assignment is approved; + - SUBMITTED while any waits for review; + - REWORK while any was sent back; + - IN_PROGRESS once anyone has started, or some but not all are approved; + - otherwise PENDING. + - Migration `task_status_backfill` applies the same rule once to existing tasks. - Editing a task (PUT /api/v1/tasks/:id) sends `task:updated` to Admins, the department's HODs and everyone assigned to it (docs/websocket.md). - GET /api/v1/visitors, GET /api/v1/visitors/:id and PUT /api/v1/visitors/:id/review: an HOD only reaches visitors whose host is in their department, or, when no host is named, whose registrant is in it (404 otherwise). Only PENDING requests can be reviewed, atomically, so a second concurrent decision gets 409 VISITOR_ALREADY_REVIEWED. ADMIN reaches every visitor in the college. - GET /api/v1/timetable: HOD lists only their department's timetable; FACULTY lists only the classes they teach; STUDENT lists only their own sections. diff --git a/packages/db/prisma/migrations/20261118103912_task_status_backfill/migration.sql b/packages/db/prisma/migrations/20261118103912_task_status_backfill/migration.sql new file mode 100644 index 0000000..ea9f958 --- /dev/null +++ b/packages/db/prisma/migrations/20261118103912_task_status_backfill/migration.sql @@ -0,0 +1,18 @@ +-- Task.status was never written, so every task read PENDING. Work it out once from each task's assignments, with the +-- same rule the API now applies on every change: approved once all are approved; submitted while any awaits review; +-- rework while any was sent back; in progress once anyone started or some are approved; otherwise pending. +UPDATE "Task" AS t +SET "status" = s."status" +FROM ( + SELECT ta."taskId" AS "id", + (CASE + WHEN bool_and(ta."status" = 'APPROVED') THEN 'APPROVED' + WHEN bool_or(ta."status" = 'SUBMITTED') THEN 'SUBMITTED' + WHEN bool_or(ta."status" = 'REWORK') THEN 'REWORK' + WHEN bool_or(ta."status" IN ('IN_PROGRESS', 'APPROVED')) THEN 'IN_PROGRESS' + ELSE 'PENDING' + END)::"TaskStatus" AS "status" + FROM "TaskAssignment" AS ta + GROUP BY ta."taskId" +) AS s +WHERE t."id" = s."id"; From 8f79403dd2f6e2669cc324191b275341b3ef7b4f Mon Sep 17 00:00:00 2001 From: Anish Mehta Date: Wed, 18 Nov 2026 16:16:08 +0530 Subject: [PATCH 2/2] fix(tasks): send the recalculated task status in workflow events Assign, start, submit and review events built their payload from the task as read before the change, so they carried the old status. syncTaskStatus now returns the status it stored, and the events use it. --- apps/api/src/tasks/tasks.service.spec.ts | 3 +++ apps/api/src/tasks/tasks.service.ts | 29 +++++++++++++----------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/apps/api/src/tasks/tasks.service.spec.ts b/apps/api/src/tasks/tasks.service.spec.ts index 02b21d5..fecfb86 100644 --- a/apps/api/src/tasks/tasks.service.spec.ts +++ b/apps/api/src/tasks/tasks.service.spec.ts @@ -287,6 +287,7 @@ describe('TasksService WebSocket Event Emissions', () => { }, }; mockDatabase.taskAssignment.findFirst.mockResolvedValue({ ...existing, taskId: 'task-100' }); + mockDatabase.taskAssignment.findMany.mockResolvedValueOnce([{ status: TaskStatus.SUBMITTED }]); await service.submitTask('assign-1', { content: 'All graded' }, facultyContext); @@ -294,6 +295,8 @@ describe('TasksService WebSocket Event Emissions', () => { where: { id: 'assign-1', collegeId: 'college-1', assigneeUserId: 'faculty-1', status: TaskStatus.IN_PROGRESS }, data: { status: TaskStatus.SUBMITTED, submissionContent: 'All graded', submittedAt: expect.any(Date) }, }); + // The event carries the status just worked out, not the one read before the change. + expect(mockEventsService.emitTaskSubmitted).toHaveBeenCalledWith(expect.objectContaining({ status: TaskStatus.SUBMITTED }), 'college-1', 'dept-1'); // The task's status is worked out again from its assignments, with the task row locked. expect(mockDatabase.$queryRaw).toHaveBeenCalled(); expect(mockDatabase.task.updateMany).toHaveBeenCalledWith({ where: { id: 'task-100', collegeId: 'college-1' }, data: { status: expect.any(String) } }); diff --git a/apps/api/src/tasks/tasks.service.ts b/apps/api/src/tasks/tasks.service.ts index 62409d3..f956c11 100644 --- a/apps/api/src/tasks/tasks.service.ts +++ b/apps/api/src/tasks/tasks.service.ts @@ -259,10 +259,10 @@ export class TasksService { } throw error; } - await this.syncTaskStatus(taskId, context.collegeId); + const taskStatus = await this.syncTaskStatus(taskId, context.collegeId); this.events.emitTaskAssigned( - this.buildPayload(task, context, `Task assigned: ${(task as { title?: string }).title ?? taskId}`, { + this.buildPayload({ ...task, status: taskStatus }, context, `Task assigned: ${(task as { title?: string }).title ?? taskId}`, { assignmentId: assignment.id, assigneeUserId: input.assigneeUserId, }), @@ -306,12 +306,12 @@ export class TasksService { data: { status: input.status }, }); if (written.count !== 1) statusChanged(); - await this.syncTaskStatus(existing!.taskId, context.collegeId); + const taskStatus = await this.syncTaskStatus(existing!.taskId, context.collegeId); const updated = await this.database.taskAssignment.findUniqueOrThrow({ where: { id: assignmentId }, include: assignmentInclude }); if (input.status === TaskStatus.IN_PROGRESS) { this.events.emitTaskStarted( - this.buildPayload(existing!.task, context, `Task started: ${existing!.task.title}`, { + this.buildPayload({ ...existing!.task, status: taskStatus }, context, `Task started: ${existing!.task.title}`, { assignmentId, assigneeUserId: context.userId, }), @@ -346,11 +346,11 @@ export class TasksService { data: { collegeId: context.collegeId, actorId: context.userId, action: 'TASK_SUBMITTED', entityType: 'TaskAssignment', entityId: assignmentId, metadata: { taskId: existing!.taskId, content: input.content } }, }); }); - await this.syncTaskStatus(existing!.taskId, context.collegeId); + const taskStatus = await this.syncTaskStatus(existing!.taskId, context.collegeId); const updated = await this.database.taskAssignment.findUniqueOrThrow({ where: { id: assignmentId }, include: assignmentInclude }); this.events.emitTaskSubmitted( - this.buildPayload(existing!.task, context, `Task submitted: ${existing!.task.title}`, { + this.buildPayload({ ...existing!.task, status: taskStatus }, context, `Task submitted: ${existing!.task.title}`, { assignmentId, assigneeUserId: context.userId, }), @@ -405,11 +405,11 @@ export class TasksService { data: { collegeId: context.collegeId, actorId: context.userId, action: 'TASK_REVIEWED', entityType: 'TaskAssignment', entityId: assignmentId, metadata: { taskId: existing!.taskId, decision: input.decision, notes: input.notes ?? null } }, }); }); - await this.syncTaskStatus(existing!.taskId, context.collegeId); + const taskStatus = await this.syncTaskStatus(existing!.taskId, context.collegeId); const updated = await this.database.taskAssignment.findUniqueOrThrow({ where: { id: assignmentId }, include: assignmentInclude }); this.events.emitTaskReviewed( - this.buildPayload(existing!.task, context, `Task ${input.decision.toLowerCase()}: ${existing!.task.title}`, { + this.buildPayload({ ...existing!.task, status: taskStatus }, context, `Task ${input.decision.toLowerCase()}: ${existing!.task.title}`, { assignmentId, assigneeUserId: existing!.assigneeUserId, }), @@ -455,14 +455,17 @@ export class TasksService { } /** - * Works the task's status out again from its assignments after one of them changed. The task row is locked first, - * so two changes at the same moment can't leave the status computed by whichever read first. + * Works the task's status out again from its assignments after one of them changed, and returns it for the event. + * The task row is locked first, so two changes at the same moment can't leave the status computed by whichever + * read first. */ - private async syncTaskStatus(taskId: string, collegeId: string): Promise { - await this.database.$transaction(async (tx) => { + private async syncTaskStatus(taskId: string, collegeId: string): Promise { + return this.database.$transaction(async (tx) => { await tx.$queryRaw`SELECT id FROM "Task" WHERE id = ${taskId} AND "collegeId" = ${collegeId} FOR UPDATE`; const assignments = await tx.taskAssignment.findMany({ where: { collegeId, taskId }, select: { status: true } }); - await tx.task.updateMany({ where: { id: taskId, collegeId }, data: { status: taskStatusFrom(assignments.map((assignment) => assignment.status)) } }); + const status = taskStatusFrom(assignments.map((assignment) => assignment.status)); + await tx.task.updateMany({ where: { id: taskId, collegeId }, data: { status } }); + return status; }); }