fix: keep quantities, colony/queen states and tasks consistent under retries

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]>
This commit is contained in:
Nick SzaunigandClaude Opus 5.5 committed 2026-09-27 05:27:45 +02:00
1 parent 786d929df9
commit 5d11756a87
37 files changed
+1420 -164

No files matched your search

@@ -7,7 +7,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { WebhooksService } from '../webhooks/webhooks.service';
import { AutomationService } from '../automation/automation.service';
import { BottlingBatch } from '../../generated/prisma';
import { BottlingBatch, Prisma } from '../../generated/prisma';
import { CreateBottlingBatchDto } from './dto/create-bottling-batch.dto';
import { UpdateBottlingBatchDto } from './dto/update-bottling-batch.dto';
@@ -29,6 +29,74 @@ function roundKg(amount: number): number {
return Math.round(amount * 1000) / 1000;
}
const INSUFFICIENT_AMOUNT_MESSAGE =
'Abfüllmenge übersteigt die verfügbare Menge der Honigcharge';
type Tx = Prisma.TransactionClient;
/**
* Deducts `amount` kg from a honey batch in one conditional UPDATE, so the
* database - not a value read earlier - decides whether enough is left.
* A batch without a recorded amount (null) is not tracked and stays null.
*/
async function takeFromHoneyBatch(
tx: Tx,
honeyBatchId: string,
amount: number,
): Promise<void> {
const current = await tx.honeyBatch.findUnique({
where: { id: honeyBatchId },
select: { amount: true },
});
if (!current) {
throw new NotFoundException('Honey batch not found');
}
if (current.amount === null) {
await tx.honeyBatch.update({
where: { id: honeyBatchId },
data: { status: 'BOTTLED' },
});
return;
}
// Tolerance of half a gram absorbs float noise from earlier writes.
const booked = await tx.honeyBatch.updateMany({
where: { id: honeyBatchId, amount: { gte: amount - 0.0005 } },
data: { amount: { decrement: amount }, status: 'BOTTLED' },
});
if (booked.count === 0) {
throw new BadRequestException(INSUFFICIENT_AMOUNT_MESSAGE);
}
await normalizeAmount(tx, honeyBatchId);
}
async function giveBackToHoneyBatch(
tx: Tx,
honeyBatchId: string,
amount: number,
): Promise<void> {
await tx.honeyBatch.updateMany({
where: { id: honeyBatchId, amount: { not: null } },
data: { amount: { increment: amount } },
});
await normalizeAmount(tx, honeyBatchId);
}
/** Keeps gram precision and clamps float noise below zero to exactly 0. */
async function normalizeAmount(tx: Tx, honeyBatchId: string): Promise<void> {
const row = await tx.honeyBatch.findUnique({
where: { id: honeyBatchId },
select: { amount: true },
});
if (row?.amount == null) return;
const normalized = Math.max(0, roundKg(row.amount));
if (normalized !== row.amount) {
await tx.honeyBatch.update({
where: { id: honeyBatchId },
data: { amount: normalized },
});
}
}
@Injectable()
export class BottlingService {
constructor(
@@ -73,11 +141,9 @@ export class BottlingService {
}
}
const totalAmount = (dto.jarSize * dto.jarCount) / 1000;
const totalAmount = roundKg((dto.jarSize * dto.jarCount) / 1000);
if (honeyBatch.amount !== null && totalAmount > honeyBatch.amount) {
throw new BadRequestException(
'Abfüllmenge übersteigt die verfügbare Menge der Honigcharge',
);
throw new BadRequestException(INSUFFICIENT_AMOUNT_MESSAGE);
}
const lotNumber =
@@ -91,7 +157,12 @@ export class BottlingService {
const bottlingBatch: BottlingBatch = await this.prisma.$transaction(
async (tx) => {
const created = await tx.bottlingBatch.create({
// Booked against the stored amount inside the transaction, never
// against the value read above: two bottlings submitted at the same
// time (double tap, two devices) must not both pass the check and
// overwrite each other's deduction.
await takeFromHoneyBatch(tx, dto.honeyBatchId, totalAmount);
return tx.bottlingBatch.create({
data: {
honeyBatchId: dto.honeyBatchId,
productId: dto.productId,
@@ -104,17 +175,6 @@ export class BottlingService {
userId: actingUserId,
},
});
await tx.honeyBatch.update({
where: { id: dto.honeyBatchId },
data: {
amount:
honeyBatch.amount !== null
? honeyBatch.amount - totalAmount
: null,
status: 'BOTTLED',
},
});
return created;
},
);
@@ -163,8 +223,8 @@ export class BottlingService {
throw new NotFoundException('Honey batch not found');
}
// Capacity on the target batch, with this bottling batch's current amount
// released first when it already sits on that same batch.
// Early, friendly check against the amounts read above. The booking
// itself happens atomically inside the transaction below.
const availableOnTarget =
targetHoneyBatch.amount === null
? null
@@ -173,14 +233,26 @@ export class BottlingService {
(movedToOtherHoneyBatch ? 0 : before.totalAmount),
);
if (availableOnTarget !== null && totalAmount > availableOnTarget) {
throw new BadRequestException(
'Abfüllmenge übersteigt die verfügbare Menge der Honigcharge',
);
throw new BadRequestException(INSUFFICIENT_AMOUNT_MESSAGE);
}
// A duplicate lotNumber surfaces as Prisma P2002 and is turned into a
// 409 with a field-specific message by AllExceptionsFilter.
await this.prisma.$transaction(async (tx) => {
const amountChanged =
movedToOtherHoneyBatch || totalAmount !== before.totalAmount;
if (amountChanged) {
// Give the previous amount back first, then take the corrected one -
// a correction never double-charges the source batch.
await giveBackToHoneyBatch(tx, before.honeyBatchId, before.totalAmount);
await takeFromHoneyBatch(tx, honeyBatchId, totalAmount);
}
if (movedToOtherHoneyBatch) {
await tx.honeyBatch.update({
where: { id: honeyBatchId },
data: { status: 'BOTTLED' },
});
}
await tx.bottlingBatch.update({
where: { id },
data: {
@@ -196,38 +268,6 @@ export class BottlingService {
lotNumber: dto.lotNumber,
},
});
if (movedToOtherHoneyBatch) {
await tx.honeyBatch.update({
where: { id: before.honeyBatchId },
data: {
amount:
before.honeyBatch.amount === null
? null
: roundKg(before.honeyBatch.amount + before.totalAmount),
},
});
await tx.honeyBatch.update({
where: { id: honeyBatchId },
data: {
amount:
availableOnTarget === null
? null
: roundKg(availableOnTarget - totalAmount),
status: 'BOTTLED',
},
});
} else if (totalAmount !== before.totalAmount) {
await tx.honeyBatch.update({
where: { id: honeyBatchId },
data: {
amount:
availableOnTarget === null
? null
: roundKg(availableOnTarget - totalAmount),
},
});
}
});
const bottlingBatch = await this.findById(id);
@@ -257,14 +297,7 @@ export class BottlingService {
await this.prisma.$transaction(async (tx) => {
await tx.bottlingBatch.delete({ where: { id } });
if (before.honeyBatch.amount !== null) {
await tx.honeyBatch.update({
where: { id: before.honeyBatchId },
data: {
amount: roundKg(before.honeyBatch.amount + before.totalAmount),
},
});
}
await giveBackToHoneyBatch(tx, before.honeyBatchId, before.totalAmount);
});
await this.auditLog.record({