feat: make the parent relation of every record correctable after entry

An inspection, treatment, feeding, varroa measurement or swarm control check
filed against the wrong colony could not be repaired: the colony was frozen at
creation time, and with no delete endpoint either, the only remedy was leaving
a wrong record in the colony's history. The same held for a harvest booked
against the wrong apiary or with a colony forgotten, for an extraction linked
to the wrong harvests, and for a honey batch whose number or source extraction
was mistyped.

Backend:
- The five colony-scoped update DTOs now cover the full create DTO, colonyId
  included.
- Harvest update accepts apiaryId and colonyIds, extraction update accepts
  harvestIds. Both validate the ids first and replace the whole join-row set
  inside the existing transaction; the join rows carry no data of their own,
  so replacing beats diffing.
- Honey batch update accepts batchNumber, extractionId and status. Status was
  previously only ever set to BOTTLED by the bottling module, so SOLD and
  CONSUMED were unreachable through the API.
- Colony and storage container codes, and a task's relatedType/relatedId, are
  editable.
- apiaryId on a colony and storageContainerId on a honey batch stay out of
  PATCH on purpose: both have dedicated endpoints that also write the history
  entry (ColonyApiaryHistory, HoneyBatchRelocation) the traceability chain
  depends on.
- AllExceptionsFilter now also translates Prisma P2003 to a 400 and P2025 to a
  404. Services write straight against the foreign keys with no application
  level existence check, so before this a stale or mistyped relation id came
  back as a bare 500 and filled the log with fake server errors.

Frontend:
- New shared fields: ColonySelectField (used by all five colony-scoped edit
  dialogs), HarvestSelectField (both extraction dialogs) and TaskRelatedField.
- Re-filing a record invalidates the lists of both the colony it left and the
  one it joined, otherwise one of the two stays stale.
- The harvest dialog gained an apiary select and a colony checklist that keeps
  already-linked colonies visible even when they moved or were dissolved; the
  honey batch dialog gained batch number, source extraction and status.
- Extraction and harvest forms refuse to submit an empty relation set instead
  of letting the backend reject it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Nick SzaunigandClaude Opus 5 committed 2026-09-19 08:01:05 +02:00
1 parent 2b15795a60
commit bee2199647
44 files changed
+958 -156

No files matched your search

@@ -1,13 +1,9 @@
import { PartialType, PickType } from '@nestjs/swagger';
import { PartialType } from '@nestjs/swagger';
import { CreateExtractionDto } from './create-extraction.dto';
export class UpdateExtractionDto extends PartialType(
PickType(CreateExtractionDto, [
'date',
'amount',
'room',
'waterContent',
'temperature',
'notes',
] as const),
) {}
/**
* Every field stays correctable, the set of harvests included: a Schleuderung
* linked to the wrong Ernte is a data-entry error, and re-pointing it is the
* only way to repair the traceability chain without deleting the record.
*/
export class UpdateExtractionDto extends PartialType(CreateExtractionDto) {}
@@ -12,16 +12,19 @@ describe('ExtractionsService', () => {
};
let auditLog: { record: jest.Mock };
let tx: {
extraction: { create: jest.Mock };
extractionHarvest: { createMany: jest.Mock };
extraction: { create: jest.Mock; update: jest.Mock };
extractionHarvest: { createMany: jest.Mock; deleteMany: jest.Mock };
};
const extraction = { id: 'extraction-1', date: new Date() };
beforeEach(() => {
tx = {
extraction: { create: jest.fn().mockResolvedValue(extraction) },
extractionHarvest: { createMany: jest.fn() },
extraction: {
create: jest.fn().mockResolvedValue(extraction),
update: jest.fn(),
},
extractionHarvest: { createMany: jest.fn(), deleteMany: jest.fn() },
};
prisma = {
extraction: { findUnique: jest.fn(), update: jest.fn() },
@@ -82,7 +85,6 @@ describe('ExtractionsService', () => {
prisma.extraction.findUnique
.mockResolvedValueOnce(extraction)
.mockResolvedValueOnce(updated);
prisma.extraction.update.mockResolvedValue(updated);
const result = await service.update(
'extraction-1',
@@ -100,5 +102,41 @@ describe('ExtractionsService', () => {
afterData: updated,
}),
);
expect(tx.extractionHarvest.deleteMany).not.toHaveBeenCalled();
});
it('update replaces the whole harvest set when harvestIds is given', async () => {
prisma.extraction.findUnique.mockResolvedValue(extraction);
await service.update(
'extraction-1',
{ harvestIds: ['harvest-1', 'harvest-2'] },
'user-1',
);
expect(tx.extractionHarvest.deleteMany).toHaveBeenCalledWith({
where: { extractionId: 'extraction-1' },
});
const [[createArg]] = tx.extractionHarvest.createMany.mock.calls as [
[{ data: { extractionId: string; harvestId: string }[] }],
];
expect(createArg.data).toEqual([
{ extractionId: 'extraction-1', harvestId: 'harvest-1' },
{ extractionId: 'extraction-1', harvestId: 'harvest-2' },
]);
});
it('update rejects an unknown harvest id before touching the database', async () => {
prisma.extraction.findUnique.mockResolvedValue(extraction);
prisma.harvest.findMany.mockResolvedValue([{ id: 'harvest-1' }]);
await expect(
service.update(
'extraction-1',
{ harvestIds: ['harvest-1', 'missing-harvest'] },
'user-1',
),
).rejects.toBeInstanceOf(BadRequestException);
expect(prisma.$transaction).not.toHaveBeenCalled();
});
});
@@ -89,10 +89,32 @@ export class ExtractionsService {
async update(id: string, dto: UpdateExtractionDto, actingUserId: string) {
const before = await this.findById(id);
await this.prisma.extraction.update({
where: { id },
data: { ...dto, date: dto.date ? new Date(dto.date) : undefined },
const { harvestIds, ...scalarFields } = dto;
if (harvestIds) {
await this.assertHarvestsExist(harvestIds);
}
await this.prisma.$transaction(async (tx) => {
await tx.extraction.update({
where: { id },
data: {
...scalarFields,
date: dto.date ? new Date(dto.date) : undefined,
},
});
// The join rows carry no data of their own, so replacing the whole set
// is both simpler and safer than diffing it.
if (harvestIds) {
await tx.extractionHarvest.deleteMany({ where: { extractionId: id } });
await tx.extractionHarvest.createMany({
data: harvestIds.map((harvestId) => ({
extractionId: id,
harvestId,
})),
});
}
});
const extraction = await this.findById(id);
await this.auditLog.record({
entityType: 'Extraction',