feat(backend): Benachrichtigungssystem (Modul 26)

NotificationsModule: Notification-Modell mit Prioritaeten INFO/
HINWEIS/WARNUNG/KRITISCH, GET /notifications (eigene + Broadcast),
POST /notifications/:id/read. record() als interne API fuer
kuenftige Automatisierungsregeln (Modul 30) vorgesehen.
This commit is contained in:
Nick Szaunig committed 2026-08-22 22:43:38 +02:00
1 parent 9b078022ff
commit a57cde1f9a
9 files changed
+299 -1

No files matched your search

@@ -0,0 +1,25 @@
-- CreateEnum
CREATE TYPE "NotificationPriority" AS ENUM ('INFO', 'HINWEIS', 'WARNUNG', 'KRITISCH');
-- CreateTable
CREATE TABLE "Notification" (
"id" TEXT NOT NULL,
"userId" TEXT,
"priority" "NotificationPriority" NOT NULL,
"message" TEXT NOT NULL,
"relatedType" TEXT,
"relatedId" TEXT,
"read" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Notification_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "Notification_userId_read_idx" ON "Notification"("userId", "read");
-- CreateIndex
CREATE INDEX "Notification_priority_idx" ON "Notification"("priority");
-- AddForeignKey
ALTER TABLE "Notification" ADD CONSTRAINT "Notification_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+27
View File
@@ -50,6 +50,7 @@ model User {
colonyMoves ColonyApiaryHistory[] colonyMoves ColonyApiaryHistory[]
auditLogs AuditLog[] auditLogs AuditLog[]
bottlingBatches BottlingBatch[] bottlingBatches BottlingBatch[]
notifications Notification[]
@@index([role]) @@index([role])
} }
@@ -698,3 +699,29 @@ model Equipment {
@@index([condition]) @@index([condition])
} }
// ---------------------------------------------------------------------------
// Benachrichtigungssystem (Abschnitt 24) – v1.x Modul 26
// ---------------------------------------------------------------------------
enum NotificationPriority {
INFO
HINWEIS
WARNUNG
KRITISCH
}
model Notification {
id String @id @default(cuid())
userId String?
user User? @relation(fields: [userId], references: [id])
priority NotificationPriority
message String
relatedType String?
relatedId String?
read Boolean @default(false)
createdAt DateTime @default(now())
@@index([userId, read])
@@index([priority])
}
+2
View File
@@ -26,6 +26,7 @@ import { ProductsModule } from './products/products.module';
import { BottlingModule } from './bottling/bottling.module'; import { BottlingModule } from './bottling/bottling.module';
import { EquipmentModule } from './equipment/equipment.module'; import { EquipmentModule } from './equipment/equipment.module';
import { CalendarModule } from './calendar/calendar.module'; import { CalendarModule } from './calendar/calendar.module';
import { NotificationsModule } from './notifications/notifications.module';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
import { RolesGuard } from './auth/guards/roles.guard'; import { RolesGuard } from './auth/guards/roles.guard';
@@ -57,6 +58,7 @@ import { RolesGuard } from './auth/guards/roles.guard';
BottlingModule, BottlingModule,
EquipmentModule, EquipmentModule,
CalendarModule, CalendarModule,
NotificationsModule,
], ],
controllers: [], controllers: [],
providers: [ providers: [
@@ -0,0 +1,28 @@
import { Controller, Get, Param, Post, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { NotificationsService } from './notifications.service';
@ApiTags('notifications')
@ApiBearerAuth()
@Controller('notifications')
export class NotificationsController {
constructor(private readonly notificationsService: NotificationsService) {}
@Get()
findAll(
@CurrentUser() actor: AuthenticatedUser,
@Query('unreadOnly') unreadOnly?: string,
) {
return this.notificationsService.findAll({
userId: actor.id,
unreadOnly: unreadOnly === 'true',
});
}
@Post(':id/read')
markRead(@Param('id') id: string) {
return this.notificationsService.markRead(id);
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { NotificationsController } from './notifications.controller';
import { NotificationsService } from './notifications.service';
@Module({
controllers: [NotificationsController],
providers: [NotificationsService],
exports: [NotificationsService],
})
export class NotificationsModule {}
@@ -0,0 +1,74 @@
import { NotFoundException } from '@nestjs/common';
import { NotificationsService } from './notifications.service';
import { PrismaService } from '../prisma/prisma.service';
describe('NotificationsService', () => {
let service: NotificationsService;
let prisma: {
notification: {
create: jest.Mock;
findMany: jest.Mock;
findUnique: jest.Mock;
update: jest.Mock;
};
};
beforeEach(() => {
prisma = {
notification: {
create: jest.fn(),
findMany: jest.fn(),
findUnique: jest.fn(),
update: jest.fn(),
},
};
service = new NotificationsService(prisma as unknown as PrismaService);
});
it('records a notification with the given priority and message', async () => {
const created = {
id: 'n1',
priority: 'KRITISCH',
message: 'Keine Königin gesehen',
};
prisma.notification.create.mockResolvedValueOnce(created);
const result = await service.record({
priority: 'KRITISCH',
message: 'Keine Königin gesehen',
});
expect(result).toEqual(created);
expect(prisma.notification.create).toHaveBeenCalledWith({
data: { priority: 'KRITISCH', message: 'Keine Königin gesehen' },
});
});
it('lists notifications for a user including broadcast notifications', async () => {
await service.findAll({ userId: 'user-1' });
const [[queryArg]] = prisma.notification.findMany.mock.calls as [
[{ where: { OR?: { userId: string | null }[] } }],
];
expect(queryArg.where.OR).toEqual([{ userId: 'user-1' }, { userId: null }]);
});
it('throws NotFoundException when marking an unknown notification as read', async () => {
prisma.notification.findUnique.mockResolvedValueOnce(null);
await expect(service.markRead('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('marks a notification as read', async () => {
prisma.notification.findUnique.mockResolvedValueOnce({
id: 'n1',
read: false,
});
prisma.notification.update.mockResolvedValueOnce({ id: 'n1', read: true });
const result = await service.markRead('n1');
expect(result.read).toBe(true);
});
});
@@ -0,0 +1,51 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Notification, NotificationPriority } from '../../generated/prisma';
export interface CreateNotificationInput {
userId?: string;
priority: NotificationPriority;
message: string;
relatedType?: string;
relatedId?: string;
}
export interface NotificationFilter {
userId?: string;
unreadOnly?: boolean;
}
@Injectable()
export class NotificationsService {
constructor(private readonly prisma: PrismaService) {}
async record(input: CreateNotificationInput): Promise<Notification> {
return this.prisma.notification.create({ data: { ...input } });
}
async findAll(filter: NotificationFilter = {}): Promise<Notification[]> {
return this.prisma.notification.findMany({
where: {
OR: filter.userId
? [{ userId: filter.userId }, { userId: null }]
: undefined,
read: filter.unreadOnly ? false : undefined,
},
orderBy: { createdAt: 'desc' },
take: 100,
});
}
async markRead(id: string): Promise<Notification> {
const notification = await this.prisma.notification.findUnique({
where: { id },
});
if (!notification) {
throw new NotFoundException('Notification not found');
}
return this.prisma.notification.update({
where: { id },
data: { read: true },
});
}
}
@@ -0,0 +1,81 @@
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 NotificationBody {
id: string;
priority: string;
read: boolean;
}
describe('Notifications (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const beekeeperEmail = `notifications-e2e-beekeeper-${Date.now()}@example.com`;
const password = 'SuperSecret123!';
let beekeeperId: string;
let beekeeperToken: string;
let notificationId: 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: 'BEEKEEPER',
},
});
beekeeperId = beekeeper.id;
beekeeperToken = (await login(app, beekeeperEmail, password)).accessToken;
const notification = await prisma.notification.create({
data: {
userId: beekeeperId,
priority: 'KRITISCH',
message: `Kritischer Testalarm ${Date.now()}`,
},
});
notificationId = notification.id;
});
afterAll(async () => {
await prisma.notification.deleteMany({ where: { id: notificationId } });
await prisma.refreshToken.deleteMany({ where: { userId: beekeeperId } });
await prisma.auditLog.deleteMany({ where: { userId: beekeeperId } });
await prisma.user.deleteMany({ where: { id: beekeeperId } });
await app.close();
});
it('lists notifications for the authenticated user', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/notifications')
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(200);
const notifications = response.body as NotificationBody[];
expect(
notifications.some(
(notification) =>
notification.id === notificationId &&
notification.priority === 'KRITISCH',
),
).toBe(true);
});
it('marks a notification as read', async () => {
const response = await request(app.getHttpServer())
.post(`/api/v1/notifications/${notificationId}/read`)
.set('Authorization', `Bearer ${beekeeperToken}`)
.expect(201);
const notification = response.body as NotificationBody;
expect(notification.read).toBe(true);
});
});
+1 -1
View File
@@ -211,7 +211,7 @@ Reihenfolge = Bau-Reihenfolge. Gleiche Haken-Regel wie MVP: erst setzen, wenn Li
- Backend: `NotificationsModule` (`Notification`: Priorität INFO/HINWEIS/WARNUNG/KRITISCH, Nachricht, verknüpftes Objekt, gelesen); erzeugt aus Automatisierungen/Schwellenwerten - Backend: `NotificationsModule` (`Notification`: Priorität INFO/HINWEIS/WARNUNG/KRITISCH, Nachricht, verknüpftes Objekt, gelesen); erzeugt aus Automatisierungen/Schwellenwerten
- Endpunkte: `GET /api/v1/notifications`, `POST /api/v1/notifications/:id/read` - Endpunkte: `GET /api/v1/notifications`, `POST /api/v1/notifications/:id/read`
- Frontend: Glocken-Icon in der Navigation mit Liste/Badge für ungelesene Einträge - Frontend: Glocken-Icon in der Navigation mit Liste/Badge für ungelesene Einträge
- [ ] Backend-Modul fertig, getestet, grün, committet - [x] Backend-Modul fertig, getestet, grün, committet
- [ ] Frontend-Views fertig, getestet, grün, committet - [ ] Frontend-Views fertig, getestet, grün, committet
### 27. Statistik und Reporting ### 27. Statistik und Reporting