Files
ApiCore/ApiCore-Backend/test/calendar.e2e-spec.ts
T
Nick SzaunigandClaude Opus 5.5 ef33e5549b feat: T4 wave 5 - colony end cleanup, withdrawal chain, next steps, inspection takeover UI
- Colony end releases the queen in the same transaction; open
  suggestions become obsolete and a CLEANUP suggestion lists open
  tasks and the queen; apply-cleanup validates evidence and blocks
  reactivated colonies
- Withdrawal chain: plausibility warnings on harvest and bottling,
  conflict notifications also when a treatment is entered or corrected
  after the harvest (naming bottled lots), withdrawal spans in the
  calendar and M365 sync, Berlin-day end events
- Next 3 steps per colony and the "Heute" endpoint with ranking and an
  explicit merge table by intent
- Inspection-triggered rule suggestions follow the colony's latest
  inspection (resolve when the finding is gone, refresh when it stays)
- Frontend: colony card takeover in the inspection form, feed status as
  condition, occupied frames 0-40; legacy offline entries keep syncing
- Notifications and preferences are deleted with their user

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 16:28:07 +02:00

222 lines
7.3 KiB
TypeScript

import { INestApplication } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import request from 'supertest';
import { App } from 'supertest/types';
import { PrismaService } from '../src/prisma/prisma.service';
import { createTestApp } from './utils/create-test-app';
import { login } from './utils/api';
interface CalendarEventBody {
id: string;
type: string;
title: string;
date: string;
endDate?: string;
relatedType: string;
relatedId: string;
}
describe('Calendar (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const beekeeperEmail = `calendar-e2e-beekeeper-${Date.now()}@example.com`;
const password = 'SuperSecret123!';
let beekeeperId: string;
let beekeeperToken: string;
let apiaryId: string;
let colonyId: string;
let taskId: string;
let treatmentId: string;
let colonyCode: string;
let calendarOnlyRoleId: string;
let calendarOnlyId: string;
let calendarOnlyToken: string;
beforeAll(async () => {
app = await createTestApp();
prisma = app.get(PrismaService);
const passwordHash = await bcrypt.hash(password, 12);
const beekeeper = await prisma.user.create({
data: {
email: beekeeperEmail,
passwordHash,
name: 'Beekeeper',
role: { connect: { key: 'BEEKEEPER' } },
},
});
beekeeperId = beekeeper.id;
beekeeperToken = (await login(app, beekeeperEmail, password)).accessToken;
const apiary = await prisma.apiary.create({
data: { name: `Stand ${Date.now()}` },
});
apiaryId = apiary.id;
const colony = await prisma.colony.create({
data: {
code: `V-${Date.now()}`,
apiaryId,
colonyType: 'PRODUCTION_COLONY',
},
});
colonyId = colony.id;
colonyCode = colony.code;
// 2027-06-10 + 10 days: harvestable again from 2027-06-20.
const treatment = await prisma.treatment.create({
data: {
colonyId,
userId: beekeeperId,
date: new Date('2027-06-10T00:00:00.000Z'),
product: 'Oxuvar',
withdrawalPeriodDays: 10,
},
});
treatmentId = treatment.id;
const calendarOnlyRole = await prisma.role.create({
data: {
key: `CAL_ONLY_${Date.now()}`,
name: 'Nur Kalender',
permissions: {
create: [{ permission: { connect: { key: 'calendar:read' } } }],
},
},
});
calendarOnlyRoleId = calendarOnlyRole.id;
const calendarOnly = await prisma.user.create({
data: {
email: `calendar-e2e-only-${Date.now()}@example.com`,
passwordHash,
name: 'Calendar only',
roleId: calendarOnlyRoleId,
},
});
calendarOnlyId = calendarOnly.id;
calendarOnlyToken = (await login(app, calendarOnly.email, password))
.accessToken;
const task = await prisma.task.create({
data: {
title: `Kalendertest ${Date.now()}`,
dueDate: new Date('2027-06-15'),
createdByUserId: beekeeperId,
},
});
taskId = task.id;
});
afterAll(async () => {
await prisma.task.deleteMany({ where: { id: taskId } });
await prisma.treatment.deleteMany({ where: { id: treatmentId } });
await prisma.colony.deleteMany({ where: { id: colonyId } });
await prisma.apiary.deleteMany({ where: { id: apiaryId } });
const userIds = [beekeeperId, calendarOnlyId];
await prisma.refreshToken.deleteMany({
where: { userId: { in: userIds } },
});
await prisma.auditLog.deleteMany({ where: { userId: { in: userIds } } });
await prisma.user.deleteMany({ where: { id: { in: userIds } } });
await prisma.role.deleteMany({ where: { id: calendarOnlyRoleId } });
await app.close();
});
it('rejects the request when from/to are missing', () => {
return request(app.getHttpServer())
.get('/api/v1/calendar')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(400);
});
it('returns events for a task due within the queried range', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/calendar?from=2027-06-01&to=2027-06-30')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(200);
const events = response.body as CalendarEventBody[];
expect(
events.some(
(event) =>
event.type === 'TASK' && event.title.includes('Kalendertest'),
),
).toBe(true);
});
it('lists WITHDRAWAL as a span with endDate for users with treatments:read', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/calendar?from=2027-06-01&to=2027-06-30')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(200);
const events = response.body as CalendarEventBody[];
const span = events.find(
(event) =>
event.type === 'WITHDRAWAL' && event.id === `withdrawal:${treatmentId}`,
);
expect(span).toMatchObject({
title: `Wartezeit ${colonyCode} · Oxuvar`,
relatedType: 'Colony',
relatedId: colonyId,
});
expect(span?.date.slice(0, 10)).toBe('2027-06-10');
// The last covered day, inclusive; 2027-06-20 is harvestable again.
expect(span?.endDate?.slice(0, 10)).toBe('2027-06-19');
});
it('shows the span in a range that only touches the end of the window', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/calendar?from=2027-06-19&to=2027-06-25')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(200);
const events = response.body as CalendarEventBody[];
expect(
events.some((event) => event.id === `withdrawal:${treatmentId}`),
).toBe(true);
const later = await request(app.getHttpServer())
.get('/api/v1/calendar?from=2027-06-20&to=2027-06-25')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(200);
expect(
(later.body as CalendarEventBody[]).some(
(event) => event.id === `withdrawal:${treatmentId}`,
),
).toBe(false);
});
it('hides WITHDRAWAL from users without treatments:read', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/calendar?from=2027-06-01&to=2027-06-30')
.set('Authorization', `Bearer ${calendarOnlyToken}`)
.expect(200);
expect(
(response.body as CalendarEventBody[]).filter(
(event) => event.type === 'WITHDRAWAL',
),
).toEqual([]);
});
it('lists TREATMENT events only for users with treatments:read', async () => {
const asBeekeeper = await request(app.getHttpServer())
.get('/api/v1/calendar?from=2027-06-01&to=2027-06-30')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(200);
const asCalendarOnly = await request(app.getHttpServer())
.get('/api/v1/calendar?from=2027-06-01&to=2027-06-30')
.set('Authorization', `Bearer ${calendarOnlyToken}`)
.expect(200);
const treatmentEvent = (body: unknown) =>
(body as CalendarEventBody[]).filter(
(event) => event.type === 'TREATMENT' && event.id === treatmentId,
);
expect(treatmentEvent(asBeekeeper.body)).toHaveLength(1);
expect(treatmentEvent(asCalendarOnly.body)).toEqual([]);
});
it('rejects an invalid date range', () => {
return request(app.getHttpServer())
.get('/api/v1/calendar?from=nonsense&to=2027-06-30')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(400);
});
});