Data-integrity fixes found in a systematic review of ApiCore: - Bottling booked the honey batch amount from a value read outside the transaction and wrote an absolute result back, so two concurrent bottlings (double tap, two devices) could both pass the check and one deduction was lost. Bookings now use a conditional UPDATE inside the transaction; corrections and deletions give amounts back atomically. - Outgoing stock movements could drive stock below zero; the removal is now a conditional decrement that refuses when stock is insufficient. - Weak, conspicuous and queenless colonies were treated as "not active" and could not be moved, split or merged - uniting a queenless colony is the textbook merge. Only terminal statuses lock a colony now; merging a colony into itself and dissolving twice are rejected. - Moving a queen to another colony failed on the unique currentQueenId because the old colony kept pointing at her. The old colony now releases her (and becomes QUEENLESS); a queenless colony receiving a queen becomes ACTIVE; dissolved colonies cannot receive a queen. - Completing a task twice moved completedAt and re-sent the webhook; reopening a task kept completedAt. Recurring templates created tasks without a due date and caught up missed weeks one stale task at a time. - Automation rules created a new task and warning on every trigger (every stock removal below minimum). Tasks now record their source trigger and at most one open task per rule and object exists. The varroa threshold (mites per day) is only compared with natural-mite-fall rates, not with sample-based counts in another unit. - New opt-in Idempotency-Key support for record-creating endpoints, so the offline queue can retry after a lost response without duplicates. - Permission catalog sync crashed replicas booting concurrently on a fresh database (unique violation); it now uses createMany/skipDuplicates. - Server-side validation for inspection rating scales (1-5), unique colony/harvest lists and net weight <= gross weight. - Stale e2e expectations updated (permission count, trigger list, real PNG fixture for the file-signature check). Migration is additive only (nullable Task column, new table). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
133 lines
4.0 KiB
TypeScript
133 lines
4.0 KiB
TypeScript
import { Injectable, NotFoundException } from '@nestjs/common';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { AuditLogService } from '../audit/audit-log.service';
|
|
import { WebhooksService } from '../webhooks/webhooks.service';
|
|
import { TaskTemplatesService } from '../task-templates/task-templates.service';
|
|
import { CalendarSyncService } from '../calendar-sync/calendar-sync.service';
|
|
import { Task, TaskPriority, TaskStatus } from '../../generated/prisma';
|
|
import { CreateTaskDto } from './dto/create-task.dto';
|
|
import { UpdateTaskDto } from './dto/update-task.dto';
|
|
|
|
/**
|
|
* Keeps completedAt in step with status when the status is edited directly:
|
|
* set when a task becomes DONE, cleared when it is reopened or cancelled -
|
|
* a reopened task must not keep claiming it was finished.
|
|
*/
|
|
function completedAtForStatusChange(
|
|
before: Task,
|
|
nextStatus: TaskStatus | undefined,
|
|
): Date | null | undefined {
|
|
if (nextStatus === undefined || nextStatus === before.status) {
|
|
return undefined;
|
|
}
|
|
return nextStatus === 'DONE' ? new Date() : null;
|
|
}
|
|
|
|
export interface TaskFilter {
|
|
status?: TaskStatus;
|
|
priority?: TaskPriority;
|
|
}
|
|
|
|
@Injectable()
|
|
export class TasksService {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly auditLog: AuditLogService,
|
|
private readonly webhooks: WebhooksService,
|
|
private readonly taskTemplates: TaskTemplatesService,
|
|
private readonly calendarSync: CalendarSyncService,
|
|
) {}
|
|
|
|
async findAll(filter: TaskFilter): Promise<Task[]> {
|
|
await this.taskTemplates.generateDueTasks();
|
|
return this.prisma.task.findMany({
|
|
where: filter,
|
|
orderBy: [{ dueDate: 'asc' }, { createdAt: 'desc' }],
|
|
});
|
|
}
|
|
|
|
async findById(id: string): Promise<Task> {
|
|
const task = await this.prisma.task.findUnique({ where: { id } });
|
|
if (!task) {
|
|
throw new NotFoundException('Task not found');
|
|
}
|
|
return task;
|
|
}
|
|
|
|
async create(dto: CreateTaskDto, actingUserId: string): Promise<Task> {
|
|
const task = await this.prisma.task.create({
|
|
data: {
|
|
...dto,
|
|
dueDate: dto.dueDate ? new Date(dto.dueDate) : undefined,
|
|
createdByUserId: actingUserId,
|
|
},
|
|
});
|
|
await this.auditLog.record({
|
|
entityType: 'Task',
|
|
entityId: task.id,
|
|
action: 'CREATE',
|
|
userId: actingUserId,
|
|
afterData: task,
|
|
});
|
|
await this.webhooks.dispatch('task.created', task);
|
|
if (task.dueDate) {
|
|
await this.calendarSync.enqueue('TASK', task.id);
|
|
}
|
|
return task;
|
|
}
|
|
|
|
async update(
|
|
id: string,
|
|
dto: UpdateTaskDto,
|
|
actingUserId: string,
|
|
): Promise<Task> {
|
|
const before = await this.findById(id);
|
|
const task = await this.prisma.task.update({
|
|
where: { id },
|
|
data: {
|
|
...dto,
|
|
dueDate: dto.dueDate ? new Date(dto.dueDate) : undefined,
|
|
completedAt: completedAtForStatusChange(before, dto.status),
|
|
},
|
|
});
|
|
await this.auditLog.record({
|
|
entityType: 'Task',
|
|
entityId: id,
|
|
action: 'UPDATE',
|
|
userId: actingUserId,
|
|
beforeData: before,
|
|
afterData: task,
|
|
});
|
|
if (task.dueDate) {
|
|
await this.calendarSync.enqueue('TASK', task.id);
|
|
} else {
|
|
await this.calendarSync.cancel('TASK', task.id);
|
|
}
|
|
return task;
|
|
}
|
|
|
|
async complete(id: string, actingUserId: string): Promise<Task> {
|
|
const before = await this.findById(id);
|
|
// A second tap on "Erledigt" (or a retried request) must not move the
|
|
// completion time or announce the completion a second time.
|
|
if (before.status === 'DONE') {
|
|
return before;
|
|
}
|
|
const task = await this.prisma.task.update({
|
|
where: { id },
|
|
data: { status: 'DONE', completedAt: new Date() },
|
|
});
|
|
await this.auditLog.record({
|
|
entityType: 'Task',
|
|
entityId: id,
|
|
action: 'UPDATE',
|
|
userId: actingUserId,
|
|
beforeData: before,
|
|
afterData: task,
|
|
});
|
|
await this.webhooks.dispatch('task.completed', task);
|
|
await this.calendarSync.cancel('TASK', task.id);
|
|
return task;
|
|
}
|
|
}
|