feat: Profilseite, Etikettendruck mit QR-Code, mehr Automatisierungen und Entra-ID-SSO
- Profilseite mit MFA-Einrichtung, Passwort/E-Mail/Name aendern, Konto deaktivieren - Bearbeiten-Buttons fuer Bienenstaende/Voelker/Koeniginnen/Aufgaben-Datensaetze - Restliche englische Enum-Werte durch deutsche Labels ersetzt (SelectValue-Fix) - Sidebar-Eintraege fuer Ernten/Schleuderungen ergaenzt - Automatisierungen von 3 auf 6 Regeln erweitert (Schwarmstimmung, kritischer Gesundheitsstatus, Lagerbestand) - Responsive Grid-Layout fuer Volk-/Koeniginnen-/Honigchargen-/Bienenstand-Detailseiten - Etikettenvorlagen mit Platzhaltern inkl. QR-Code (verweist auf Herkunftsseite) und PDF-Druck - Entra-ID-SSO (Authorization Code + PKCE, kein Auto-Provisioning, Secrets nur ueber Environment-Variablen)
This commit is contained in:
1 parent
0a52b29c57
commit
8432313fa9
83 files changed
+2684
-289
No files matched your search
@@ -0,0 +1,236 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import PDFDocument from 'pdfkit';
|
||||
import * as QRCode from 'qrcode';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditLogService } from '../audit/audit-log.service';
|
||||
import { LabelTemplate } from '../../generated/prisma';
|
||||
import { CreateLabelTemplateDto } from './dto/create-label-template.dto';
|
||||
import { UpdateLabelTemplateDto } from './dto/update-label-template.dto';
|
||||
|
||||
const MM_TO_PT = 72 / 25.4;
|
||||
const PAGE_MARGIN_MM = 5;
|
||||
const LABEL_GAP_MM = 2;
|
||||
const A4_WIDTH_MM = 210;
|
||||
const A4_HEIGHT_MM = 297;
|
||||
const QR_CODE_PLACEHOLDER = '{{qrCode}}';
|
||||
|
||||
function formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('de-DE');
|
||||
}
|
||||
|
||||
function fillPlaceholders(
|
||||
content: string,
|
||||
values: Record<string, string>,
|
||||
): string {
|
||||
return content.replace(/\{\{(\w+)\}\}/g, (match, key: string) =>
|
||||
key in values ? values[key] : match,
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class LabelTemplatesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly auditLog: AuditLogService,
|
||||
) {}
|
||||
|
||||
async findAll(): Promise<LabelTemplate[]> {
|
||||
return this.prisma.labelTemplate.findMany({ orderBy: { name: 'asc' } });
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<LabelTemplate> {
|
||||
const template = await this.prisma.labelTemplate.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!template) {
|
||||
throw new NotFoundException('Label template not found');
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
async create(
|
||||
dto: CreateLabelTemplateDto,
|
||||
actingUserId: string,
|
||||
): Promise<LabelTemplate> {
|
||||
const template = await this.prisma.$transaction(async (tx) => {
|
||||
if (dto.isDefault) {
|
||||
await tx.labelTemplate.updateMany({
|
||||
where: {},
|
||||
data: { isDefault: false },
|
||||
});
|
||||
}
|
||||
return tx.labelTemplate.create({ data: { ...dto } });
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'LabelTemplate',
|
||||
entityId: template.id,
|
||||
action: 'CREATE',
|
||||
userId: actingUserId,
|
||||
afterData: template,
|
||||
});
|
||||
return template;
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
dto: UpdateLabelTemplateDto,
|
||||
actingUserId: string,
|
||||
): Promise<LabelTemplate> {
|
||||
const before = await this.findById(id);
|
||||
const template = await this.prisma.$transaction(async (tx) => {
|
||||
if (dto.isDefault) {
|
||||
await tx.labelTemplate.updateMany({
|
||||
where: { id: { not: id } },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
}
|
||||
return tx.labelTemplate.update({ where: { id }, data: { ...dto } });
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'LabelTemplate',
|
||||
entityId: id,
|
||||
action: 'UPDATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: template,
|
||||
});
|
||||
return template;
|
||||
}
|
||||
|
||||
async deactivate(id: string, actingUserId: string): Promise<LabelTemplate> {
|
||||
const before = await this.findById(id);
|
||||
const template = await this.prisma.labelTemplate.update({
|
||||
where: { id },
|
||||
data: { active: false, isDefault: false },
|
||||
});
|
||||
await this.auditLog.record({
|
||||
entityType: 'LabelTemplate',
|
||||
entityId: id,
|
||||
action: 'DEACTIVATE',
|
||||
userId: actingUserId,
|
||||
beforeData: before,
|
||||
afterData: template,
|
||||
});
|
||||
return template;
|
||||
}
|
||||
|
||||
async renderLabelsPdf(
|
||||
templateId: string,
|
||||
bottlingBatchId: string,
|
||||
): Promise<Buffer> {
|
||||
const template = await this.findById(templateId);
|
||||
const bottlingBatch = await this.prisma.bottlingBatch.findUnique({
|
||||
where: { id: bottlingBatchId },
|
||||
include: { honeyBatch: true, product: true },
|
||||
});
|
||||
if (!bottlingBatch) {
|
||||
throw new NotFoundException('Bottling batch not found');
|
||||
}
|
||||
|
||||
const values: Record<string, string> = {
|
||||
batchNumber: bottlingBatch.honeyBatch.batchNumber,
|
||||
honeyType: bottlingBatch.honeyBatch.honeyType ?? '',
|
||||
lotNumber: bottlingBatch.lotNumber,
|
||||
bottlingDate: formatDate(bottlingBatch.date),
|
||||
bestBeforeDate: formatDate(bottlingBatch.bestBeforeDate),
|
||||
jarSize: `${bottlingBatch.jarSize} ml`,
|
||||
productName: bottlingBatch.product?.name ?? '',
|
||||
};
|
||||
const labelText = fillPlaceholders(template.content, values);
|
||||
|
||||
// The QR code is generated once (not per copy) - it always points at the
|
||||
// public Herkunft/traceability page for this batch, which already shows
|
||||
// honey type, dates, and origin, so the label itself only needs to
|
||||
// reference it rather than duplicate that information.
|
||||
let qrCodeBuffer: Buffer | null = null;
|
||||
if (labelText.includes(QR_CODE_PLACEHOLDER)) {
|
||||
const frontendOrigin =
|
||||
process.env.FRONTEND_ORIGIN ?? 'http://localhost:3000';
|
||||
const herkunftUrl = `${frontendOrigin}/herkunft/${encodeURIComponent(bottlingBatch.lotNumber)}`;
|
||||
qrCodeBuffer = await QRCode.toBuffer(herkunftUrl, {
|
||||
margin: 1,
|
||||
width: 300,
|
||||
});
|
||||
}
|
||||
|
||||
return this.renderPdf(
|
||||
labelText,
|
||||
template.widthMm,
|
||||
template.heightMm,
|
||||
bottlingBatch.jarCount,
|
||||
qrCodeBuffer,
|
||||
);
|
||||
}
|
||||
|
||||
private renderPdf(
|
||||
labelText: string,
|
||||
widthMm: number,
|
||||
heightMm: number,
|
||||
copies: number,
|
||||
qrCodeBuffer: Buffer | null,
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const doc = new PDFDocument({ size: 'A4', margin: 0 });
|
||||
const chunks: Buffer[] = [];
|
||||
doc.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', (error: Error) => reject(error));
|
||||
|
||||
const usableWidthMm = A4_WIDTH_MM - 2 * PAGE_MARGIN_MM;
|
||||
const usableHeightMm = A4_HEIGHT_MM - 2 * PAGE_MARGIN_MM;
|
||||
const columns = Math.max(
|
||||
1,
|
||||
Math.floor((usableWidthMm + LABEL_GAP_MM) / (widthMm + LABEL_GAP_MM)),
|
||||
);
|
||||
const rows = Math.max(
|
||||
1,
|
||||
Math.floor((usableHeightMm + LABEL_GAP_MM) / (heightMm + LABEL_GAP_MM)),
|
||||
);
|
||||
const perPage = columns * rows;
|
||||
|
||||
for (let index = 0; index < copies; index += 1) {
|
||||
const onPage = index % perPage;
|
||||
if (index > 0 && onPage === 0) {
|
||||
doc.addPage({ size: 'A4', margin: 0 });
|
||||
}
|
||||
const column = onPage % columns;
|
||||
const row = Math.floor(onPage / columns);
|
||||
const xMm = PAGE_MARGIN_MM + column * (widthMm + LABEL_GAP_MM);
|
||||
const yMm = PAGE_MARGIN_MM + row * (heightMm + LABEL_GAP_MM);
|
||||
const x = xMm * MM_TO_PT;
|
||||
const y = yMm * MM_TO_PT;
|
||||
const w = widthMm * MM_TO_PT;
|
||||
const h = heightMm * MM_TO_PT;
|
||||
|
||||
doc.rect(x, y, w, h).dash(2, { space: 2 }).stroke('#999999').undash();
|
||||
|
||||
if (qrCodeBuffer) {
|
||||
const qrSide = Math.min(w, h) - 8;
|
||||
const qrX = x + w - qrSide - 4;
|
||||
const qrY = y + (h - qrSide) / 2;
|
||||
doc.image(qrCodeBuffer, qrX, qrY, { width: qrSide, height: qrSide });
|
||||
const textWidth = qrX - 4 - (x + 4);
|
||||
doc
|
||||
.fontSize(9)
|
||||
.fillColor('#000000')
|
||||
.text(
|
||||
labelText.replace(QR_CODE_PLACEHOLDER, '').trim(),
|
||||
x + 4,
|
||||
y + 4,
|
||||
{
|
||||
width: Math.max(textWidth, 0),
|
||||
height: h - 8,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
doc
|
||||
.fontSize(9)
|
||||
.fillColor('#000000')
|
||||
.text(labelText, x + 4, y + 4, { width: w - 8, height: h - 8 });
|
||||
}
|
||||
}
|
||||
|
||||
doc.end();
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user