Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6941a797f | ||
|
|
9659b8d266 |
No files matched your search
+9
@@ -0,0 +1,9 @@
|
||||
-- Explicit A4 sheet layout per LabelTemplate: columns/rows (nullable, null =
|
||||
-- auto-fit) plus configurable page margins and gaps, so a template can be
|
||||
-- made to match a specific physical label sheet's exact printed grid.
|
||||
ALTER TABLE "LabelTemplate" ADD COLUMN "columns" INTEGER;
|
||||
ALTER TABLE "LabelTemplate" ADD COLUMN "rows" INTEGER;
|
||||
ALTER TABLE "LabelTemplate" ADD COLUMN "marginTopMm" DOUBLE PRECISION NOT NULL DEFAULT 5;
|
||||
ALTER TABLE "LabelTemplate" ADD COLUMN "marginLeftMm" DOUBLE PRECISION NOT NULL DEFAULT 5;
|
||||
ALTER TABLE "LabelTemplate" ADD COLUMN "gapXMm" DOUBLE PRECISION NOT NULL DEFAULT 2;
|
||||
ALTER TABLE "LabelTemplate" ADD COLUMN "gapYMm" DOUBLE PRECISION NOT NULL DEFAULT 2;
|
||||
@@ -864,6 +864,17 @@ model LabelTemplate {
|
||||
elements Json @default("[]")
|
||||
widthMm Float @default(90)
|
||||
heightMm Float @default(35)
|
||||
// A4 sheet layout. columns/rows are nullable: null means "auto-fit as many
|
||||
// as fit" (the original behaviour); a real label sheet product (e.g. a
|
||||
// specific Avery SKU) publishes an exact columns/rows/margin/gap grid, so
|
||||
// setting these lets a template's printed positions match the physical,
|
||||
// pre-die-cut sheet instead of just whatever the naive fit computes.
|
||||
columns Int?
|
||||
rows Int?
|
||||
marginTopMm Float @default(5)
|
||||
marginLeftMm Float @default(5)
|
||||
gapXMm Float @default(2)
|
||||
gapYMm Float @default(2)
|
||||
isDefault Boolean @default(false)
|
||||
active Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ArrayMaxSize,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsInt,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
@@ -36,6 +37,47 @@ export class CreateLabelTemplateDto {
|
||||
@Min(10)
|
||||
heightMm?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'Spalten pro A4-Bogen. Leer = automatisch so viele wie passen.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
columns?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Zeilen pro A4-Bogen. Leer = automatisch so viele wie passen.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
rows?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
marginTopMm?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
marginLeftMm?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
gapXMm?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
gapYMm?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
|
||||
@@ -4,8 +4,10 @@ import {
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
@@ -65,11 +67,14 @@ export class LabelTemplatesController {
|
||||
async print(
|
||||
@Param('id') id: string,
|
||||
@Param('bottlingBatchId') bottlingBatchId: string,
|
||||
@Query('startPosition', new ParseIntPipe({ optional: true }))
|
||||
startPosition: number | undefined,
|
||||
@Res() res: Response,
|
||||
): Promise<void> {
|
||||
const pdf = await this.labelTemplatesService.renderLabelsPdf(
|
||||
id,
|
||||
bottlingBatchId,
|
||||
startPosition,
|
||||
);
|
||||
res.setHeader('Content-Type', 'application/pdf');
|
||||
res.setHeader(
|
||||
|
||||
@@ -64,6 +64,12 @@ describe('LabelTemplatesService', () => {
|
||||
elements,
|
||||
widthMm: 90,
|
||||
heightMm: 35,
|
||||
columns: null,
|
||||
rows: null,
|
||||
marginTopMm: 5,
|
||||
marginLeftMm: 5,
|
||||
gapXMm: 2,
|
||||
gapYMm: 2,
|
||||
isDefault: false,
|
||||
active: true,
|
||||
};
|
||||
@@ -213,5 +219,56 @@ describe('LabelTemplatesService', () => {
|
||||
// A PDF with an embedded raster image contains an XObject /Image entry.
|
||||
expect(pdf.toString('latin1')).toContain('/Image');
|
||||
});
|
||||
|
||||
function countPages(pdf: Buffer): number {
|
||||
const matches = pdf.toString('latin1').match(/\/Type\s*\/Page[^s]/g);
|
||||
return matches ? matches.length : 0;
|
||||
}
|
||||
|
||||
it('uses an explicit columns/rows override instead of auto-fitting', async () => {
|
||||
prisma.labelTemplate.findUnique.mockResolvedValue({
|
||||
...template,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
});
|
||||
prisma.bottlingBatch.findUnique.mockResolvedValue({
|
||||
id: 'batch-1',
|
||||
jarSize: 500,
|
||||
jarCount: 3,
|
||||
lotNumber: 'L-001',
|
||||
date: new Date('2026-06-01T00:00:00.000Z'),
|
||||
bestBeforeDate: new Date('2028-06-01T00:00:00.000Z'),
|
||||
honeyBatch: { batchNumber: 'HB-001', honeyType: 'Bluetenhonig' },
|
||||
product: { name: 'Glas 500g' },
|
||||
});
|
||||
|
||||
const pdf = await service.renderLabelsPdf('template-1', 'batch-1');
|
||||
|
||||
expect(countPages(pdf)).toBe(3);
|
||||
});
|
||||
|
||||
it('skips already-used slots on the first sheet via startPosition, but not later sheets', async () => {
|
||||
prisma.labelTemplate.findUnique.mockResolvedValue({
|
||||
...template,
|
||||
columns: 2,
|
||||
rows: 1,
|
||||
});
|
||||
prisma.bottlingBatch.findUnique.mockResolvedValue({
|
||||
id: 'batch-1',
|
||||
jarSize: 500,
|
||||
jarCount: 3,
|
||||
lotNumber: 'L-001',
|
||||
date: new Date('2026-06-01T00:00:00.000Z'),
|
||||
bestBeforeDate: new Date('2028-06-01T00:00:00.000Z'),
|
||||
honeyBatch: { batchNumber: 'HB-001', honeyType: 'Bluetenhonig' },
|
||||
product: { name: 'Glas 500g' },
|
||||
});
|
||||
|
||||
const pdf = await service.renderLabelsPdf('template-1', 'batch-1', 2);
|
||||
|
||||
// perPage=2, skip=1: label 1 fills the remaining slot on page 1,
|
||||
// labels 2-3 fill both slots of page 2.
|
||||
expect(countPages(pdf)).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -13,12 +13,21 @@ import {
|
||||
} from './label-element.types';
|
||||
|
||||
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_SOURCE_SIZE_PX = 400;
|
||||
|
||||
interface SheetLayout {
|
||||
widthMm: number;
|
||||
heightMm: number;
|
||||
columns: number | null;
|
||||
rows: number | null;
|
||||
marginTopMm: number;
|
||||
marginLeftMm: number;
|
||||
gapXMm: number;
|
||||
gapYMm: number;
|
||||
}
|
||||
|
||||
function formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('de-DE');
|
||||
}
|
||||
@@ -151,6 +160,7 @@ export class LabelTemplatesService {
|
||||
async renderLabelsPdf(
|
||||
templateId: string,
|
||||
bottlingBatchId: string,
|
||||
startPosition = 1,
|
||||
): Promise<Buffer> {
|
||||
const template = await this.findById(templateId);
|
||||
const bottlingBatch = await this.prisma.bottlingBatch.findUnique({
|
||||
@@ -193,19 +203,28 @@ export class LabelTemplatesService {
|
||||
|
||||
return this.renderPdf(
|
||||
elements,
|
||||
template.widthMm,
|
||||
template.heightMm,
|
||||
{
|
||||
widthMm: template.widthMm,
|
||||
heightMm: template.heightMm,
|
||||
columns: template.columns,
|
||||
rows: template.rows,
|
||||
marginTopMm: template.marginTopMm,
|
||||
marginLeftMm: template.marginLeftMm,
|
||||
gapXMm: template.gapXMm,
|
||||
gapYMm: template.gapYMm,
|
||||
},
|
||||
bottlingBatch.jarCount,
|
||||
qrCodeBuffer,
|
||||
startPosition,
|
||||
);
|
||||
}
|
||||
|
||||
private renderPdf(
|
||||
elements: LabelElement[],
|
||||
widthMm: number,
|
||||
heightMm: number,
|
||||
layout: SheetLayout,
|
||||
copies: number,
|
||||
qrCodeBuffer: Buffer | null,
|
||||
startPosition: number,
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const doc = new PDFDocument({ size: 'A4', margin: 0 });
|
||||
@@ -214,27 +233,34 @@ export class LabelTemplatesService {
|
||||
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 { widthMm, heightMm, marginTopMm, marginLeftMm, gapXMm, gapYMm } =
|
||||
layout;
|
||||
const usableWidthMm = A4_WIDTH_MM - 2 * marginLeftMm;
|
||||
const usableHeightMm = A4_HEIGHT_MM - 2 * marginTopMm;
|
||||
const columns =
|
||||
layout.columns ??
|
||||
Math.max(1, Math.floor((usableWidthMm + gapXMm) / (widthMm + gapXMm)));
|
||||
const rows =
|
||||
layout.rows ??
|
||||
Math.max(
|
||||
1,
|
||||
Math.floor((usableHeightMm + gapYMm) / (heightMm + gapYMm)),
|
||||
);
|
||||
const perPage = columns * rows;
|
||||
// startPosition only skips ahead on the first sheet (partially-used
|
||||
// physical sheet, e.g. a few labels already peeled off) - every sheet
|
||||
// after that always starts fresh at the top-left slot.
|
||||
const skip = Math.min(Math.max(0, startPosition - 1), perPage - 1);
|
||||
|
||||
for (let index = 0; index < copies; index += 1) {
|
||||
const onPage = index % perPage;
|
||||
if (index > 0 && onPage === 0) {
|
||||
const slotOnPage = (skip + index) % perPage;
|
||||
if (index > 0 && slotOnPage === 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 column = slotOnPage % columns;
|
||||
const row = Math.floor(slotOnPage / columns);
|
||||
const xMm = marginLeftMm + column * (widthMm + gapXMm);
|
||||
const yMm = marginTopMm + row * (heightMm + gapYMm);
|
||||
const originX = xMm * MM_TO_PT;
|
||||
const originY = yMm * MM_TO_PT;
|
||||
const w = widthMm * MM_TO_PT;
|
||||
|
||||
@@ -7,6 +7,8 @@ import { toast } from "sonner";
|
||||
import { fetchLabelTemplates, printLabels } from "@/lib/label-templates/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -17,6 +19,7 @@ import {
|
||||
|
||||
export function PrintLabelsCard({ bottlingBatchId }: { bottlingBatchId: string }) {
|
||||
const [templateId, setTemplateId] = useState("");
|
||||
const [startPosition, setStartPosition] = useState(1);
|
||||
const { data: templates } = useQuery({
|
||||
queryKey: ["label-templates"],
|
||||
queryFn: fetchLabelTemplates,
|
||||
@@ -28,9 +31,13 @@ export function PrintLabelsCard({ bottlingBatchId }: { bottlingBatchId: string }
|
||||
const selectedTemplate = activeTemplates.find(
|
||||
(template) => template.id === effectiveTemplateId,
|
||||
);
|
||||
const slotsPerSheet =
|
||||
selectedTemplate?.columns && selectedTemplate?.rows
|
||||
? selectedTemplate.columns * selectedTemplate.rows
|
||||
: undefined;
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => printLabels(effectiveTemplateId, bottlingBatchId),
|
||||
mutationFn: () => printLabels(effectiveTemplateId, bottlingBatchId, startPosition),
|
||||
onError: () => toast.error("Etiketten konnten nicht erstellt werden"),
|
||||
});
|
||||
|
||||
@@ -65,6 +72,23 @@ export function PrintLabelsCard({ bottlingBatchId }: { bottlingBatchId: string }
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="print-start-position">
|
||||
Startposition auf dem Bogen (1 = oben links)
|
||||
</Label>
|
||||
<Input
|
||||
id="print-start-position"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
max={slotsPerSheet}
|
||||
value={startPosition}
|
||||
onChange={(event) => setStartPosition(Math.max(1, Number(event.target.value)))}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Für bereits angebrochene Bögen: Position der ersten noch freien Etikette.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={!effectiveTemplateId || mutation.isPending}
|
||||
|
||||
@@ -40,6 +40,12 @@ export default function EditLabelTemplatePage() {
|
||||
elements: template.elements,
|
||||
widthMm: template.widthMm,
|
||||
heightMm: template.heightMm,
|
||||
columns: template.columns,
|
||||
rows: template.rows,
|
||||
marginTopMm: template.marginTopMm,
|
||||
marginLeftMm: template.marginLeftMm,
|
||||
gapXMm: template.gapXMm,
|
||||
gapYMm: template.gapYMm,
|
||||
isDefault: template.isDefault,
|
||||
}}
|
||||
onSubmit={handleSubmit}
|
||||
|
||||
+34
-4
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Bold, Italic, Trash2 } from "lucide-react";
|
||||
import { Bold, Copy, Italic, Trash2 } from "lucide-react";
|
||||
import {
|
||||
LabelElement,
|
||||
LabelFontFamily,
|
||||
@@ -36,12 +36,14 @@ interface ElementPropertiesPanelProps {
|
||||
element: LabelElement;
|
||||
onChange: (patch: Partial<LabelElement>) => void;
|
||||
onDelete: () => void;
|
||||
onDuplicate: () => void;
|
||||
}
|
||||
|
||||
export function ElementPropertiesPanel({
|
||||
element,
|
||||
onChange,
|
||||
onDelete,
|
||||
onDuplicate,
|
||||
}: ElementPropertiesPanelProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
@@ -49,9 +51,37 @@ export function ElementPropertiesPanel({
|
||||
<p className="text-sm font-medium text-muted-foreground">
|
||||
{element.type === "text" ? "Text" : element.type === "qrCode" ? "QR-Code" : element.type === "image" ? "Bild" : "Linie"}
|
||||
</p>
|
||||
<Button type="button" variant="ghost" size="icon-sm" onClick={onDelete}>
|
||||
<Trash2 className="size-3.5 text-destructive" />
|
||||
</Button>
|
||||
<div className="flex gap-1">
|
||||
<Button type="button" variant="ghost" size="icon-sm" onClick={onDuplicate} title="Duplizieren">
|
||||
<Copy className="size-3.5" />
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" size="icon-sm" onClick={onDelete} title="Löschen">
|
||||
<Trash2 className="size-3.5 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="element-x">X (mm)</Label>
|
||||
<Input
|
||||
id="element-x"
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={element.x}
|
||||
onChange={(event) => onChange({ x: Number(event.target.value) })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="element-y">Y (mm)</Label>
|
||||
<Input
|
||||
id="element-y"
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={element.y}
|
||||
onChange={(event) => onChange({ y: Number(event.target.value) })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{element.type === "text" ? <TextFields element={element} onChange={onChange} /> : null}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "@/lib/label-templates/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const CANVAS_SCALE = 4; // px per mm
|
||||
export const BASE_SCALE = 4; // px per mm at 100% zoom
|
||||
const PT_TO_MM = 25.4 / 72;
|
||||
const MIN_SIZE_MM = 5;
|
||||
|
||||
@@ -27,6 +27,7 @@ interface LabelCanvasProps {
|
||||
heightMm: number;
|
||||
elements: LabelElement[];
|
||||
selectedId: string | null;
|
||||
zoom?: number;
|
||||
onSelect: (id: string | null) => void;
|
||||
onChangeElement: (id: string, patch: Partial<LabelElement>) => void;
|
||||
}
|
||||
@@ -36,9 +37,12 @@ export function LabelCanvas({
|
||||
heightMm,
|
||||
elements,
|
||||
selectedId,
|
||||
zoom = 1,
|
||||
onSelect,
|
||||
onChangeElement,
|
||||
}: LabelCanvasProps) {
|
||||
const scale = BASE_SCALE * zoom;
|
||||
|
||||
function startDrag(
|
||||
event: ReactPointerEvent,
|
||||
element: LabelElement,
|
||||
@@ -52,8 +56,8 @@ export function LabelCanvas({
|
||||
const origin = element;
|
||||
|
||||
function onMove(moveEvent: PointerEvent) {
|
||||
const dxMm = (moveEvent.clientX - startX) / CANVAS_SCALE;
|
||||
const dyMm = (moveEvent.clientY - startY) / CANVAS_SCALE;
|
||||
const dxMm = (moveEvent.clientX - startX) / scale;
|
||||
const dyMm = (moveEvent.clientY - startY) / scale;
|
||||
|
||||
if (mode === "move") {
|
||||
onChangeElement(origin.id, {
|
||||
@@ -92,13 +96,14 @@ export function LabelCanvas({
|
||||
return (
|
||||
<div
|
||||
className="relative overflow-hidden rounded-lg border border-dashed border-border bg-white shadow-sm"
|
||||
style={{ width: widthMm * CANVAS_SCALE, height: heightMm * CANVAS_SCALE }}
|
||||
style={{ width: widthMm * scale, height: heightMm * scale }}
|
||||
onPointerDown={() => onSelect(null)}
|
||||
>
|
||||
{elements.map((element) => (
|
||||
<ElementBox
|
||||
key={element.id}
|
||||
element={element}
|
||||
scale={scale}
|
||||
selected={element.id === selectedId}
|
||||
onStartMove={(event) => startDrag(event, element, "move")}
|
||||
onStartResize={(event) => startDrag(event, element, "resize")}
|
||||
@@ -110,16 +115,18 @@ export function LabelCanvas({
|
||||
|
||||
function ElementBox({
|
||||
element,
|
||||
scale,
|
||||
selected,
|
||||
onStartMove,
|
||||
onStartResize,
|
||||
}: {
|
||||
element: LabelElement;
|
||||
scale: number;
|
||||
selected: boolean;
|
||||
onStartMove: (event: ReactPointerEvent) => void;
|
||||
onStartResize: (event: ReactPointerEvent) => void;
|
||||
}) {
|
||||
const box = boxFor(element);
|
||||
const box = boxFor(element, scale);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -135,7 +142,7 @@ function ElementBox({
|
||||
}}
|
||||
onPointerDown={onStartMove}
|
||||
>
|
||||
{renderContent(element)}
|
||||
{renderContent(element, scale)}
|
||||
{selected ? (
|
||||
<div
|
||||
className="absolute right-0 bottom-0 size-3 translate-x-1/2 translate-y-1/2 cursor-nwse-resize rounded-full border-2 border-primary bg-background"
|
||||
@@ -149,27 +156,30 @@ function ElementBox({
|
||||
);
|
||||
}
|
||||
|
||||
function boxFor(element: LabelElement): {
|
||||
function boxFor(
|
||||
element: LabelElement,
|
||||
scale: number,
|
||||
): {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
} {
|
||||
const left = element.x * CANVAS_SCALE;
|
||||
const top = element.y * CANVAS_SCALE;
|
||||
const left = element.x * scale;
|
||||
const top = element.y * scale;
|
||||
if (element.type === "qrCode") {
|
||||
return { left, top, width: element.size * CANVAS_SCALE, height: element.size * CANVAS_SCALE };
|
||||
return { left, top, width: element.size * scale, height: element.size * scale };
|
||||
}
|
||||
if (element.type === "line") {
|
||||
const thicknessPx = Math.max(2, element.thickness * PT_TO_MM * CANVAS_SCALE);
|
||||
const thicknessPx = Math.max(2, element.thickness * PT_TO_MM * scale);
|
||||
return element.orientation === "horizontal"
|
||||
? { left, top: top - thicknessPx / 2, width: element.length * CANVAS_SCALE, height: thicknessPx }
|
||||
: { left: left - thicknessPx / 2, top, width: thicknessPx, height: element.length * CANVAS_SCALE };
|
||||
? { left, top: top - thicknessPx / 2, width: element.length * scale, height: thicknessPx }
|
||||
: { left: left - thicknessPx / 2, top, width: thicknessPx, height: element.length * scale };
|
||||
}
|
||||
return { left, top, width: element.width * CANVAS_SCALE, height: element.height * CANVAS_SCALE };
|
||||
return { left, top, width: element.width * scale, height: element.height * scale };
|
||||
}
|
||||
|
||||
function renderContent(element: LabelElement) {
|
||||
function renderContent(element: LabelElement, scale: number) {
|
||||
switch (element.type) {
|
||||
case "text": {
|
||||
const display = element.placeholderKey
|
||||
@@ -180,7 +190,7 @@ function renderContent(element: LabelElement) {
|
||||
className="size-full overflow-hidden whitespace-pre-wrap"
|
||||
style={{
|
||||
fontFamily: FONT_CSS[element.fontFamily],
|
||||
fontSize: element.fontSize * PT_TO_MM * CANVAS_SCALE,
|
||||
fontSize: element.fontSize * PT_TO_MM * scale,
|
||||
fontWeight: element.bold ? 700 : 400,
|
||||
fontStyle: element.italic ? "italic" : "normal",
|
||||
color: element.color,
|
||||
|
||||
+300
-9
@@ -1,8 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { ChangeEvent, useState } from "react";
|
||||
import { ChangeEvent, useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Image as ImageIcon, Minus, QrCode, Type } from "lucide-react";
|
||||
import {
|
||||
Download,
|
||||
Image as ImageIcon,
|
||||
Minus,
|
||||
QrCode,
|
||||
Type,
|
||||
Upload,
|
||||
ZoomIn,
|
||||
ZoomOut,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
LabelElement,
|
||||
@@ -25,6 +34,17 @@ import {
|
||||
import { LabelCanvas } from "./label-canvas";
|
||||
import { ElementPropertiesPanel } from "./element-properties-panel";
|
||||
|
||||
const ELEMENT_TYPES = ["text", "qrCode", "image", "line"] as const;
|
||||
const ZOOM_STEPS: number[] = [0.5, 0.75, 1, 1.25, 1.5, 2];
|
||||
const ZOOM_MIN = ZOOM_STEPS[0];
|
||||
const ZOOM_MAX = ZOOM_STEPS[ZOOM_STEPS.length - 1];
|
||||
|
||||
function nextZoomStep(current: number, direction: 1 | -1): number {
|
||||
const index = ZOOM_STEPS.indexOf(current);
|
||||
const nextIndex = Math.min(Math.max(index + direction, 0), ZOOM_STEPS.length - 1);
|
||||
return ZOOM_STEPS[nextIndex];
|
||||
}
|
||||
|
||||
function newId(): string {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
@@ -54,9 +74,44 @@ export interface LabelDesignerValue {
|
||||
elements: LabelElement[];
|
||||
widthMm: number;
|
||||
heightMm: number;
|
||||
columns: number | null;
|
||||
rows: number | null;
|
||||
marginTopMm: number;
|
||||
marginLeftMm: number;
|
||||
gapXMm: number;
|
||||
gapYMm: number;
|
||||
isDefault: boolean;
|
||||
}
|
||||
|
||||
// Loose runtime check for imported JSON (own export, or hand/AI-authored) -
|
||||
// only verifies the shape is plausible enough to load into the canvas;
|
||||
// the backend's own DTO validation is still the real boundary check on save.
|
||||
function isLabelElementArray(value: unknown): value is LabelElement[] {
|
||||
return (
|
||||
Array.isArray(value) &&
|
||||
value.every(
|
||||
(item) =>
|
||||
typeof item === "object" &&
|
||||
item !== null &&
|
||||
"id" in item &&
|
||||
"type" in item &&
|
||||
"x" in item &&
|
||||
"y" in item &&
|
||||
ELEMENT_TYPES.includes((item as { type: unknown }).type as (typeof ELEMENT_TYPES)[number]),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function slugify(name: string): string {
|
||||
return (
|
||||
name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/(^-|-$)/g, "") || "etikett"
|
||||
);
|
||||
}
|
||||
|
||||
interface LabelDesignerProps {
|
||||
initial?: LabelDesignerValue;
|
||||
onSubmit: (value: LabelDesignerValue) => Promise<void>;
|
||||
@@ -68,10 +123,17 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
const [widthMm, setWidthMm] = useState(initial?.widthMm ?? 90);
|
||||
const [heightMm, setHeightMm] = useState(initial?.heightMm ?? 35);
|
||||
const [columns, setColumns] = useState<number | null>(initial?.columns ?? null);
|
||||
const [rows, setRows] = useState<number | null>(initial?.rows ?? null);
|
||||
const [marginTopMm, setMarginTopMm] = useState(initial?.marginTopMm ?? 5);
|
||||
const [marginLeftMm, setMarginLeftMm] = useState(initial?.marginLeftMm ?? 5);
|
||||
const [gapXMm, setGapXMm] = useState(initial?.gapXMm ?? 2);
|
||||
const [gapYMm, setGapYMm] = useState(initial?.gapYMm ?? 2);
|
||||
const [isDefault, setIsDefault] = useState(initial?.isDefault ?? false);
|
||||
const [elements, setElements] = useState<LabelElement[]>(initial?.elements ?? []);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [zoom, setZoom] = useState(1);
|
||||
|
||||
const selectedElement = elements.find((element) => element.id === selectedId) ?? null;
|
||||
|
||||
@@ -88,12 +150,34 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
|
||||
);
|
||||
}
|
||||
|
||||
function deleteSelected() {
|
||||
if (!selectedId) return;
|
||||
setElements((current) => current.filter((element) => element.id !== selectedId));
|
||||
setSelectedId(null);
|
||||
function deleteElement(id: string) {
|
||||
setElements((current) => current.filter((element) => element.id !== id));
|
||||
setSelectedId((current) => (current === id ? null : current));
|
||||
}
|
||||
|
||||
function duplicateElement(id: string) {
|
||||
const source = elements.find((element) => element.id === id);
|
||||
if (!source) return;
|
||||
const copy = { ...source, id: newId(), x: source.x + 4, y: source.y + 4 };
|
||||
addElement(copy);
|
||||
}
|
||||
|
||||
// Delete/Backspace removes the selected element, but never while the user
|
||||
// is typing in a text field - only when focus is on the canvas itself.
|
||||
useEffect(() => {
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key !== "Delete" && event.key !== "Backspace") return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target && ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)) return;
|
||||
if (selectedId) {
|
||||
event.preventDefault();
|
||||
deleteElement(selectedId);
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [selectedId, elements]);
|
||||
|
||||
function handlePlaceholderInsert(key: PlaceholderKey) {
|
||||
addElement(newTextElement({ placeholderKey: key, text: "" }));
|
||||
}
|
||||
@@ -117,6 +201,66 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function handleExport() {
|
||||
const payload: LabelDesignerValue = {
|
||||
name,
|
||||
elements,
|
||||
widthMm,
|
||||
heightMm,
|
||||
columns,
|
||||
rows,
|
||||
marginTopMm,
|
||||
marginLeftMm,
|
||||
gapXMm,
|
||||
gapYMm,
|
||||
isDefault,
|
||||
};
|
||||
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = `${slugify(name)}.json`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function handleImportFile(event: ChangeEvent<HTMLInputElement>) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = "";
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(String(reader.result));
|
||||
const importedElements = Array.isArray(parsed)
|
||||
? parsed
|
||||
: (parsed as { elements?: unknown })?.elements;
|
||||
if (!isLabelElementArray(importedElements)) {
|
||||
toast.error("Datei enthält keine gültige Etikettenvorlage.");
|
||||
return;
|
||||
}
|
||||
setElements(importedElements.map((element) => ({ ...element, id: newId() })));
|
||||
if (!Array.isArray(parsed)) {
|
||||
const value = parsed as Partial<LabelDesignerValue>;
|
||||
if (typeof value.name === "string" && value.name && !name) setName(value.name);
|
||||
if (typeof value.widthMm === "number") setWidthMm(value.widthMm);
|
||||
if (typeof value.heightMm === "number") setHeightMm(value.heightMm);
|
||||
if (typeof value.columns === "number" || value.columns === null) setColumns(value.columns);
|
||||
if (typeof value.rows === "number" || value.rows === null) setRows(value.rows);
|
||||
if (typeof value.marginTopMm === "number") setMarginTopMm(value.marginTopMm);
|
||||
if (typeof value.marginLeftMm === "number") setMarginLeftMm(value.marginLeftMm);
|
||||
if (typeof value.gapXMm === "number") setGapXMm(value.gapXMm);
|
||||
if (typeof value.gapYMm === "number") setGapYMm(value.gapYMm);
|
||||
}
|
||||
setSelectedId(null);
|
||||
toast.success("Vorlage importiert.");
|
||||
} catch {
|
||||
toast.error("Datei konnte nicht gelesen werden - ist es gültiges JSON?");
|
||||
}
|
||||
};
|
||||
reader.readAsText(file);
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!name.trim()) {
|
||||
toast.error("Bitte einen Namen für die Vorlage angeben.");
|
||||
@@ -124,7 +268,19 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await onSubmit({ name, elements, widthMm, heightMm, isDefault });
|
||||
await onSubmit({
|
||||
name,
|
||||
elements,
|
||||
widthMm,
|
||||
heightMm,
|
||||
columns,
|
||||
rows,
|
||||
marginTopMm,
|
||||
marginLeftMm,
|
||||
gapXMm,
|
||||
gapYMm,
|
||||
isDefault,
|
||||
});
|
||||
router.push("/settings/label-templates");
|
||||
} catch {
|
||||
toast.error("Vorlage konnte nicht gespeichert werden.");
|
||||
@@ -186,7 +342,115 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Seiten-Layout (A4)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Spalten/Zeilen leer lassen, um automatisch so viele einzuplanen wie passen. Feste
|
||||
Werte eintragen, um exakt zum vorgedruckten Raster eines Etikettenbogens (z.B.
|
||||
Avery-Vorlage) zu passen.
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="designer-columns">Spalten</Label>
|
||||
<Input
|
||||
id="designer-columns"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
placeholder="Auto"
|
||||
value={columns ?? ""}
|
||||
onChange={(event) =>
|
||||
setColumns(event.target.value === "" ? null : Number(event.target.value))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="designer-rows">Zeilen</Label>
|
||||
<Input
|
||||
id="designer-rows"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
placeholder="Auto"
|
||||
value={rows ?? ""}
|
||||
onChange={(event) =>
|
||||
setRows(event.target.value === "" ? null : Number(event.target.value))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="designer-margin-top">Rand oben (mm)</Label>
|
||||
<Input
|
||||
id="designer-margin-top"
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={marginTopMm}
|
||||
onChange={(event) => setMarginTopMm(Number(event.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="designer-margin-left">Rand links (mm)</Label>
|
||||
<Input
|
||||
id="designer-margin-left"
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={marginLeftMm}
|
||||
onChange={(event) => setMarginLeftMm(Number(event.target.value))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="designer-gap-x">Abstand horizontal (mm)</Label>
|
||||
<Input
|
||||
id="designer-gap-x"
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={gapXMm}
|
||||
onChange={(event) => setGapXMm(Number(event.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="designer-gap-y">Abstand vertikal (mm)</Label>
|
||||
<Input
|
||||
id="designer-gap-y"
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={gapYMm}
|
||||
onChange={(event) => setGapYMm(Number(event.target.value))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-2">
|
||||
<CardTitle className="text-base">Elemente</CardTitle>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
render={
|
||||
<label className="cursor-pointer">
|
||||
<Upload className="size-4" />
|
||||
Importieren
|
||||
<input
|
||||
type="file"
|
||||
accept="application/json"
|
||||
className="hidden"
|
||||
onChange={handleImportFile}
|
||||
/>
|
||||
</label>
|
||||
}
|
||||
/>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={handleExport}>
|
||||
<Download className="size-4" />
|
||||
Exportieren
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
@@ -251,12 +515,37 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
disabled={zoom <= ZOOM_MIN}
|
||||
onClick={() => setZoom((current) => nextZoomStep(current, -1))}
|
||||
>
|
||||
<ZoomOut className="size-3.5" />
|
||||
</Button>
|
||||
<span className="w-12 text-center text-sm text-muted-foreground">
|
||||
{Math.round(zoom * 100)}%
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
disabled={zoom >= ZOOM_MAX}
|
||||
onClick={() => setZoom((current) => nextZoomStep(current, 1))}
|
||||
>
|
||||
<ZoomIn className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="overflow-auto rounded-lg bg-muted/30 p-6">
|
||||
<LabelCanvas
|
||||
widthMm={widthMm}
|
||||
heightMm={heightMm}
|
||||
elements={elements}
|
||||
selectedId={selectedId}
|
||||
zoom={zoom}
|
||||
onSelect={setSelectedId}
|
||||
onChangeElement={changeElement}
|
||||
/>
|
||||
@@ -276,11 +565,13 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
|
||||
<ElementPropertiesPanel
|
||||
element={selectedElement}
|
||||
onChange={(patch) => changeElement(selectedElement.id, patch)}
|
||||
onDelete={deleteSelected}
|
||||
onDelete={() => deleteElement(selectedElement.id)}
|
||||
onDuplicate={() => duplicateElement(selectedElement.id)}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Element im Etikett anklicken, um es zu bearbeiten.
|
||||
Element im Etikett anklicken, um es zu bearbeiten. Entf/Backspace löscht das
|
||||
ausgewählte Element.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
@@ -27,9 +27,14 @@ export function deactivateLabelTemplate(id: string): Promise<LabelTemplate> {
|
||||
return apiFetch<LabelTemplate>(`/label-templates/${id}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function printLabels(templateId: string, bottlingBatchId: string): Promise<void> {
|
||||
export async function printLabels(
|
||||
templateId: string,
|
||||
bottlingBatchId: string,
|
||||
startPosition?: number,
|
||||
): Promise<void> {
|
||||
const query = startPosition && startPosition > 1 ? `?startPosition=${startPosition}` : "";
|
||||
const { blob, filename } = await apiFetchBlob(
|
||||
`/label-templates/${templateId}/print/${bottlingBatchId}`,
|
||||
`/label-templates/${templateId}/print/${bottlingBatchId}${query}`,
|
||||
"etiketten.pdf",
|
||||
);
|
||||
downloadBlob(blob, filename);
|
||||
|
||||
@@ -75,6 +75,12 @@ export interface LabelTemplate {
|
||||
elements: LabelElement[];
|
||||
widthMm: number;
|
||||
heightMm: number;
|
||||
columns: number | null;
|
||||
rows: number | null;
|
||||
marginTopMm: number;
|
||||
marginLeftMm: number;
|
||||
gapXMm: number;
|
||||
gapYMm: number;
|
||||
isDefault: boolean;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
@@ -86,6 +92,12 @@ export interface CreateLabelTemplateInput {
|
||||
elements: LabelElement[];
|
||||
widthMm?: number;
|
||||
heightMm?: number;
|
||||
columns?: number | null;
|
||||
rows?: number | null;
|
||||
marginTopMm?: number;
|
||||
marginLeftMm?: number;
|
||||
gapXMm?: number;
|
||||
gapYMm?: number;
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
@@ -94,5 +106,11 @@ export interface UpdateLabelTemplateInput {
|
||||
elements?: LabelElement[];
|
||||
widthMm?: number;
|
||||
heightMm?: number;
|
||||
columns?: number | null;
|
||||
rows?: number | null;
|
||||
marginTopMm?: number;
|
||||
marginLeftMm?: number;
|
||||
gapXMm?: number;
|
||||
gapYMm?: number;
|
||||
isDefault?: boolean;
|
||||
}
|
||||
Reference in new issue
Block a user