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
34 changes: 30 additions & 4 deletions apps/api/src/tasks/tasks.service.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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;
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -283,13 +287,19 @@ 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);

expect(mockDatabase.taskAssignment.updateMany).toHaveBeenCalledWith({
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) } });
// 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' } },
Expand Down Expand Up @@ -425,14 +435,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<unknown>) => work(database));
const events = { emitTaskAssigned: jest.fn() };
const service = new TasksService(database as unknown as DatabaseService, events as unknown as EventsService);
beforeEach(() => jest.clearAllMocks());
Expand Down
41 changes: 37 additions & 4 deletions apps/api/src/tasks/tasks.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down Expand Up @@ -245,9 +259,10 @@ export class TasksService {
}
throw error;
}
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,
}),
Expand Down Expand Up @@ -291,11 +306,12 @@ export class TasksService {
data: { status: input.status },
});
if (written.count !== 1) statusChanged();
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,
}),
Expand Down Expand Up @@ -330,10 +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 } },
});
});
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,
}),
Expand Down Expand Up @@ -388,10 +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 } },
});
});
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,
}),
Expand Down Expand Up @@ -436,6 +454,21 @@ 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, 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<TaskStatus> {
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 } });
const status = taskStatusFrom(assignments.map((assignment) => assignment.status));
await tx.task.updateMany({ where: { id: taskId, collegeId }, data: { status } });
return status;
});
}

/* ─── Event payload builder ──────────────────────────────────────────── */

private buildPayload(
Expand Down
7 changes: 7 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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";