feat(backend): Voelker-Modul (Modul 3)

ColoniesModule: CRUD + Move/Split/Merge/Dissolve/History, entsprechend
Lastenheft §4.4 (Lebenszyklus eines Volkes):
- move: Standortwechsel, protokolliert in ColonyApiaryHistory.
- split: erzeugt Ableger als neues Volk, Abstammung ueber
  ColonyLineage(SPLIT, von Mutter- zu Ablegervolk).
- merge: vereinigtes Volk bleibt historisch erhalten (status MERGED,
  deactivatedAt gesetzt statt geloescht), ColonyLineage(MERGE) je
  vereinigtem Volk zum Zielvolk.
- dissolve: Volk wird deaktiviert (status DISSOLVED), Dokumentation
  bleibt erhalten.
- history: aggregiert Standort-Historie, Koeniginnen-Historie und
  Abstammungslinien (als Quelle und als Ergebnis).

Move/Split/Merge laufen transaktional (prisma.$transaction). Rollen wie
bei Apiaries: Lesen offen, Schreiben auf ADMIN/BEEKEEPER beschraenkt.

9 Unit-Tests + 6 e2e-Tests (inkl. vollstaendigem Move->Split->Merge->
Dissolve-Flow und Rollenpruefung), Lint, Typecheck und Build gruen.
This commit is contained in:
Nick Szaunig committed 2026-08-21 09:06:51 +02:00
1 parent d59153a697
commit d3f321f1b5
12 files changed
+781 -1

No files matched your search

@@ -0,0 +1,89 @@
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Role } from '../../generated/prisma';
import { Roles } from '../auth/decorators/roles.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { CreateColonyDto } from './dto/create-colony.dto';
import { UpdateColonyDto } from './dto/update-colony.dto';
import { MoveColonyDto } from './dto/move-colony.dto';
import { SplitColonyDto } from './dto/split-colony.dto';
import { MergeColonyDto } from './dto/merge-colony.dto';
import { ColoniesService } from './colonies.service';
@ApiTags('colonies')
@ApiBearerAuth()
@Controller('colonies')
export class ColoniesController {
constructor(private readonly coloniesService: ColoniesService) {}
@Get()
findAll() {
return this.coloniesService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.coloniesService.findById(id);
}
@Get(':id/history')
getHistory(@Param('id') id: string) {
return this.coloniesService.getHistory(id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post()
create(
@Body() dto: CreateColonyDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.coloniesService.create(dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateColonyDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.coloniesService.update(id, dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post(':id/move')
move(
@Param('id') id: string,
@Body() dto: MoveColonyDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.coloniesService.move(id, dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post(':id/split')
split(
@Param('id') id: string,
@Body() dto: SplitColonyDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.coloniesService.split(id, dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post(':id/merge')
merge(
@Param('id') id: string,
@Body() dto: MergeColonyDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.coloniesService.merge(id, dto, actor.id);
}
@Roles(Role.ADMIN, Role.BEEKEEPER)
@Post(':id/dissolve')
dissolve(@Param('id') id: string, @CurrentUser() actor: AuthenticatedUser) {
return this.coloniesService.dissolve(id, actor.id);
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { ColoniesController } from './colonies.controller';
import { ColoniesService } from './colonies.service';
@Module({
controllers: [ColoniesController],
providers: [ColoniesService],
exports: [ColoniesService],
})
export class ColoniesModule {}
@@ -0,0 +1,160 @@
import { NotFoundException } from '@nestjs/common';
import { ColoniesService } from './colonies.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('ColoniesService', () => {
let service: ColoniesService;
let tx: {
colony: { create: jest.Mock; update: jest.Mock; findUnique: jest.Mock };
colonyApiaryHistory: { create: jest.Mock };
colonyLineage: { create: jest.Mock };
};
let prisma: {
colony: {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
colonyApiaryHistory: { findMany: jest.Mock };
queenColonyHistory: { findMany: jest.Mock };
colonyLineage: { findMany: jest.Mock };
$transaction: jest.Mock;
};
let auditLog: { record: jest.Mock };
const parentColony = {
id: 'colony-1',
code: 'V-001',
apiaryId: 'apiary-1',
status: 'ACTIVE',
deactivatedAt: null,
};
beforeEach(() => {
tx = {
colony: { create: jest.fn(), update: jest.fn(), findUnique: jest.fn() },
colonyApiaryHistory: { create: jest.fn() },
colonyLineage: { create: jest.fn() },
};
prisma = {
colony: {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
colonyApiaryHistory: { findMany: jest.fn() },
queenColonyHistory: { findMany: jest.fn() },
colonyLineage: { findMany: jest.fn() },
$transaction: jest.fn((callback: (txArg: typeof tx) => unknown) =>
callback(tx),
),
};
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
service = new ColoniesService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('findById throws NotFoundException when missing', async () => {
prisma.colony.findUnique.mockResolvedValue(null);
await expect(service.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('move updates the apiary and records apiary history', async () => {
prisma.colony.findUnique.mockResolvedValue(parentColony);
tx.colony.update.mockResolvedValue({
...parentColony,
apiaryId: 'apiary-2',
});
tx.colonyApiaryHistory.create.mockResolvedValue({});
const result = await service.move(
'colony-1',
{ apiaryId: 'apiary-2' },
'user-1',
);
expect(result.apiaryId).toBe('apiary-2');
const [[historyArg]] = tx.colonyApiaryHistory.create.mock.calls as [
[{ data: { colonyId: string; apiaryId: string } }],
];
expect(historyArg.data.colonyId).toBe('colony-1');
expect(historyArg.data.apiaryId).toBe('apiary-2');
});
it('split creates a new colony and a SPLIT lineage entry', async () => {
prisma.colony.findUnique.mockResolvedValue(parentColony);
const child = { id: 'colony-2', code: 'V-001-A', apiaryId: 'apiary-1' };
tx.colony.create.mockResolvedValue(child);
tx.colonyLineage.create.mockResolvedValue({});
const result = await service.split(
'colony-1',
{ code: 'V-001-A', colonyType: 'NUCLEUS_COLONY' },
'user-1',
);
expect(result).toEqual(child);
const [[lineageArg]] = tx.colonyLineage.create.mock.calls as [
[{ data: { type: string; fromColonyId: string; toColonyId: string } }],
];
expect(lineageArg.data.type).toBe('SPLIT');
expect(lineageArg.data.fromColonyId).toBe('colony-1');
expect(lineageArg.data.toColonyId).toBe('colony-2');
});
it('merge marks the merged colony as MERGED and records a MERGE lineage entry', async () => {
prisma.colony.findUnique
.mockResolvedValueOnce(parentColony)
.mockResolvedValueOnce({
...parentColony,
id: 'colony-1',
});
tx.colony.findUnique.mockResolvedValue({
id: 'colony-3',
status: 'ACTIVE',
});
tx.colony.update.mockResolvedValue({});
tx.colonyLineage.create.mockResolvedValue({});
await service.merge(
'colony-1',
{ mergedColonyIds: ['colony-3'] },
'user-1',
);
const [[updateArg]] = tx.colony.update.mock.calls as [
[{ where: { id: string }; data: { status: string } }],
];
expect(updateArg.where.id).toBe('colony-3');
expect(updateArg.data.status).toBe('MERGED');
const [[lineageArg]] = tx.colonyLineage.create.mock.calls as [
[{ data: { type: string; fromColonyId: string; toColonyId: string } }],
];
expect(lineageArg.data.type).toBe('MERGE');
expect(lineageArg.data.fromColonyId).toBe('colony-3');
expect(lineageArg.data.toColonyId).toBe('colony-1');
});
it('dissolve sets status DISSOLVED and records DEACTIVATE', async () => {
prisma.colony.findUnique.mockResolvedValue(parentColony);
prisma.colony.update.mockResolvedValue({
...parentColony,
status: 'DISSOLVED',
});
const result = await service.dissolve('colony-1', 'user-1');
expect(result.status).toBe('DISSOLVED');
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({ action: 'DEACTIVATE' }),
);
});
});
@@ -0,0 +1,205 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { Colony } from '../../generated/prisma';
import { CreateColonyDto } from './dto/create-colony.dto';
import { UpdateColonyDto } from './dto/update-colony.dto';
import { MoveColonyDto } from './dto/move-colony.dto';
import { SplitColonyDto } from './dto/split-colony.dto';
import { MergeColonyDto } from './dto/merge-colony.dto';
@Injectable()
export class ColoniesService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
) {}
async findAll(): Promise<Colony[]> {
return this.prisma.colony.findMany({ orderBy: { code: 'asc' } });
}
async findById(id: string): Promise<Colony> {
const colony = await this.prisma.colony.findUnique({ where: { id } });
if (!colony) {
throw new NotFoundException('Colony not found');
}
return colony;
}
async create(dto: CreateColonyDto, actingUserId: string): Promise<Colony> {
const colony = await this.prisma.colony.create({ data: { ...dto } });
await this.auditLog.record({
entityType: 'Colony',
entityId: colony.id,
action: 'CREATE',
userId: actingUserId,
afterData: colony,
});
return colony;
}
async update(
id: string,
dto: UpdateColonyDto,
actingUserId: string,
): Promise<Colony> {
const before = await this.findById(id);
const colony = await this.prisma.colony.update({
where: { id },
data: { ...dto },
});
await this.auditLog.record({
entityType: 'Colony',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: colony,
});
return colony;
}
async move(
id: string,
dto: MoveColonyDto,
actingUserId: string,
): Promise<Colony> {
const before = await this.findById(id);
const colony = await this.prisma.$transaction(async (tx) => {
const updated = await tx.colony.update({
where: { id },
data: { apiaryId: dto.apiaryId },
});
await tx.colonyApiaryHistory.create({
data: {
colonyId: id,
apiaryId: dto.apiaryId,
movedByUserId: actingUserId,
notes: dto.notes,
},
});
return updated;
});
await this.auditLog.record({
entityType: 'Colony',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: colony,
});
return colony;
}
async split(
id: string,
dto: SplitColonyDto,
actingUserId: string,
): Promise<Colony> {
const parent = await this.findById(id);
const child = await this.prisma.$transaction(async (tx) => {
const created = await tx.colony.create({
data: {
code: dto.code,
apiaryId: parent.apiaryId,
colonyType: dto.colonyType,
notes: dto.notes,
},
});
await tx.colonyLineage.create({
data: {
type: 'SPLIT',
fromColonyId: parent.id,
toColonyId: created.id,
date: new Date(),
notes: dto.notes,
},
});
return created;
});
await this.auditLog.record({
entityType: 'Colony',
entityId: child.id,
action: 'CREATE',
userId: actingUserId,
afterData: { ...child, splitFromColonyId: parent.id },
});
return child;
}
async merge(
id: string,
dto: MergeColonyDto,
actingUserId: string,
): Promise<Colony> {
const survivor = await this.findById(id);
await this.prisma.$transaction(async (tx) => {
for (const mergedColonyId of dto.mergedColonyIds) {
const merged = await tx.colony.findUnique({
where: { id: mergedColonyId },
});
if (!merged) {
throw new NotFoundException(`Colony ${mergedColonyId} not found`);
}
await tx.colony.update({
where: { id: mergedColonyId },
data: { status: 'MERGED', deactivatedAt: new Date() },
});
await tx.colonyLineage.create({
data: {
type: 'MERGE',
fromColonyId: mergedColonyId,
toColonyId: survivor.id,
date: new Date(),
notes: dto.notes,
},
});
}
});
await this.auditLog.record({
entityType: 'Colony',
entityId: survivor.id,
action: 'UPDATE',
userId: actingUserId,
beforeData: survivor,
afterData: { ...survivor, mergedColonyIds: dto.mergedColonyIds },
});
return this.findById(survivor.id);
}
async dissolve(id: string, actingUserId: string): Promise<Colony> {
const before = await this.findById(id);
const colony = await this.prisma.colony.update({
where: { id },
data: { status: 'DISSOLVED', deactivatedAt: new Date() },
});
await this.auditLog.record({
entityType: 'Colony',
entityId: id,
action: 'DEACTIVATE',
userId: actingUserId,
beforeData: before,
afterData: colony,
});
return colony;
}
async getHistory(id: string) {
await this.findById(id);
const [apiaryHistory, queenHistory, lineageAsSource, lineageAsResult] =
await Promise.all([
this.prisma.colonyApiaryHistory.findMany({
where: { colonyId: id },
orderBy: { movedAt: 'desc' },
}),
this.prisma.queenColonyHistory.findMany({
where: { colonyId: id },
orderBy: { startDate: 'desc' },
}),
this.prisma.colonyLineage.findMany({ where: { fromColonyId: id } }),
this.prisma.colonyLineage.findMany({ where: { toColonyId: id } }),
]);
return { apiaryHistory, queenHistory, lineageAsSource, lineageAsResult };
}
}
@@ -0,0 +1,52 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsInt, IsOptional, IsString } from 'class-validator';
import { ColonyType } from '../../../generated/prisma';
export class CreateColonyDto {
@ApiProperty()
@IsString()
code!: string;
@ApiProperty()
@IsString()
apiaryId!: string;
@ApiProperty({ enum: ColonyType })
@IsEnum(ColonyType)
colonyType!: ColonyType;
@ApiPropertyOptional()
@IsOptional()
@IsString()
hiveType?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
originText?: string;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
strength?: number;
@ApiPropertyOptional()
@IsOptional()
@IsString()
broodStatus?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
feedStatus?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
healthStatus?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
notes?: string;
}
@@ -0,0 +1,15 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ArrayMinSize, IsArray, IsOptional, IsString } from 'class-validator';
export class MergeColonyDto {
@ApiProperty({ type: [String] })
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
mergedColonyIds!: string[];
@ApiPropertyOptional()
@IsOptional()
@IsString()
notes?: string;
}
@@ -0,0 +1,13 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';
export class MoveColonyDto {
@ApiProperty()
@IsString()
apiaryId!: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
notes?: string;
}
@@ -0,0 +1,18 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional, IsString } from 'class-validator';
import { ColonyType } from '../../../generated/prisma';
export class SplitColonyDto {
@ApiProperty()
@IsString()
code!: string;
@ApiProperty({ enum: ColonyType })
@IsEnum(ColonyType)
colonyType!: ColonyType;
@ApiPropertyOptional()
@IsOptional()
@IsString()
notes?: string;
}
@@ -0,0 +1,24 @@
import { ApiPropertyOptional, PartialType, PickType } from '@nestjs/swagger';
import { IsEnum, IsOptional } from 'class-validator';
import { ColonyStatus } from '../../../generated/prisma';
import { CreateColonyDto } from './create-colony.dto';
class UpdatableColonyFieldsDto extends PartialType(
PickType(CreateColonyDto, [
'hiveType',
'originText',
'colonyType',
'strength',
'broodStatus',
'feedStatus',
'healthStatus',
'notes',
] as const),
) {}
export class UpdateColonyDto extends UpdatableColonyFieldsDto {
@ApiPropertyOptional({ enum: ColonyStatus })
@IsOptional()
@IsEnum(ColonyStatus)
status?: ColonyStatus;
}