fix(imposition): correct imposition calculation, dual-tab print and paper cutting diagrams
Browse filesFiles changed (4)
723 unmodified lines724725726727727728729730723 unmodified lines }`} > <LayoutGrid className="w-3.5 h-3.5" /> Sơ Đồ Cắt Giấy 2D Sơ Đồ Bình Bài & Cắt Giấy </button>
<button12334556787 unmodified lines161718192021222324252627282930313233343536323337383940414243444546474849505152535455565737383940414243444546474849505152535455565758596061626364656667686970585960616263646566676869707172737475767778798081827273838485868788899091929394959697989910010110210310410510610710810911011111211311411511611775767711811912012112212312412512612712812913013113213313479808182838413513613713813914014114214314414514614714886149150899015115215392931541551561579615815998991001011601031041611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543551 unmodified line357358359112360361362363364365366367368369370371372373120374375376377'use client';
import React from 'react';import React, { useState } from 'react';import { ImpositionResult } from '@/types';import { Layers, Maximize2 } from 'lucide-react';import { Layers, Scissors, Printer, CheckCircle2, RotateCw } from 'lucide-react';
interface ImpositionVisualizerProps { imposition: ImpositionResult;7 unmodified lines productWidthMm, productHeightMm,}) => { const [activeTab, setActiveTab] = useState<'imposition' | 'paperCut'>('imposition');
const { printSheet, parentSheet, upsPerPrintSheet, cutsPerParentSheet, totalUpsPerParentSheet, gripperMarginMm, cols, rows, boxes, sheetEfficiencyPercent, isRotated, cutScheme, } = imposition;
// Kích thước SVG tờ in máy const svgWidth = printSheet.widthMm; const svgHeight = printSheet.heightMm; const printW = printSheet.widthMm; const printH = printSheet.heightMm;
// Kích thước SVG tờ giấy mẹ const parentW = cutScheme?.parentWidthMm || parentSheet.widthCm * 10; const parentH = cutScheme?.parentHeightMm || parentSheet.heightCm * 10;
// Bảng màu cho các tờ in khi xén từ tờ mẹ const blockColors = [ { bg: '#eff6ff', stroke: '#3b82f6', text: '#1d4ed8' }, // blue { bg: '#f0fdf4', stroke: '#22c55e', text: '#15803d' }, // green { bg: '#fefce8', stroke: '#eab308', text: '#a16207' }, // yellow { bg: '#faf5ff', stroke: '#a855f7', text: '#7e22ce' }, // purple { bg: '#fff7ed', stroke: '#f97316', text: '#c2410c' }, // orange { bg: '#f0fdfa', stroke: '#14b8a6', text: '#0f766e' }, // teal { bg: '#fff1f2', stroke: '#f43f5e', text: '#be123c' }, // rose { bg: '#eef2ff', stroke: '#6366f1', text: '#4338ca' }, // indigo ];
return ( <div className="space-y-3"> {/* Vùng vẽ đồ họa SVG hiển thị khổ in và các con */} <div className="relative bg-slate-900/95 rounded-xl p-4 flex items-center justify-center min-h-[220px] max-h-[260px] overflow-hidden border border-slate-800"> <svg viewBox={`0 0 ${svgWidth} ${svgHeight}`} className="w-full max-h-[220px] drop-shadow-xl border border-slate-700 rounded bg-white transition-all duration-300" style={{ aspectRatio: `${svgWidth} / ${svgHeight}` }} > {/* Lề kẹp nhíp máy in (Gripper) */} <defs> <pattern id="gripperStripe" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"> <line x1="0" y1="0" x2="0" y2="8" stroke="#fbbf24" strokeWidth="3" /> <line x1="4" y1="0" x2="4" y2="8" stroke="#f59e0b" strokeWidth="3" /> </pattern> </defs>
{/* Nền tờ in */} <rect x="0" y="0" width={svgWidth} height={svgHeight} fill="#ffffff" />
{/* Dải lề nhíp đáy */} <rect x="0" y={svgHeight - gripperMarginMm} width={svgWidth} height={gripperMarginMm} fill="url(#gripperStripe)" opacity="0.8" /> <text x={svgWidth / 2} y={svgHeight - gripperMarginMm / 2 + 3} textAnchor="middle" fill="#92400e" fontSize={Math.max(9, Math.min(14, svgWidth / 35))} fontWeight="bold" {/* Sub-tab chuyển đổi giữa Sơ đồ bình bài và Sơ đồ cắt giấy mẹ */} <div className="flex items-center justify-between gap-2 border-b border-slate-200 pb-2"> <div className="flex items-center gap-1.5 bg-slate-100 p-1 rounded-lg text-xs font-medium"> <button type="button" onClick={() => setActiveTab('imposition')} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-all ${ activeTab === 'imposition' ? 'bg-white text-blue-700 font-semibold shadow-2xs' : 'text-slate-600 hover:text-slate-900' }`} > <Printer className="w-3.5 h-3.5" /> Sơ Đồ Bình Bài (Tờ In Máy) </button>
<button type="button" onClick={() => setActiveTab('paperCut')} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-all ${ activeTab === 'paperCut' ? 'bg-white text-amber-700 font-semibold shadow-2xs' : 'text-slate-600 hover:text-slate-900' }`} > Lề kẹp nhíp ({gripperMarginMm}mm{printSheet.widthMm >= 800 ? ' • Bắt nhíp chiều 86' : ''}) </text> <Scissors className="w-3.5 h-3.5" /> Sơ Đồ Cắt Giấy Mẹ ({cutsPerParentSheet > 1 ? `Chia ${cutsPerParentSheet}` : 'Nguyên Khổ'}) </button> </div>
<span className="text-[11px] font-medium text-slate-500 hidden sm:inline-block"> {activeTab === 'imposition' ? `Khổ in: ${printW}×${printH}mm` : `Khổ mẹ: ${parentW}×${parentH}mm`} </span> </div>
{/* VÙNG 1: SƠ ĐỒ BÌNH BÀI TRÊN TỜ IN MÁY */} {activeTab === 'imposition' && ( <div className="space-y-2"> <div className="relative bg-slate-900/95 rounded-xl p-3 flex flex-col items-center justify-center min-h-[220px] max-h-[270px] overflow-hidden border border-slate-800 shadow-inner"> <svg viewBox={`0 0 ${printW} ${printH}`} className="w-full max-h-[230px] drop-shadow-xl border border-slate-700 rounded bg-white transition-all duration-300 select-none" style={{ aspectRatio: `${printW} / ${printH}` }} > <defs> {/* Hoa văn sọc vàng cho lề kẹp nhíp */} <pattern id="gripperStripe" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)" > <line x1="0" y1="0" x2="0" y2="10" stroke="#fde047" strokeWidth="3" /> <line x1="5" y1="0" x2="5" y2="10" stroke="#eab308" strokeWidth="3" /> </pattern> </defs>
{/* Các con sản phẩm */} {boxes.map((b) => ( <g key={b.index}> {/* Tờ in nền trắng */} <rect x="0" y="0" width={printW} height={printH} fill="#ffffff" />
{/* Đường biên vùng in hữu dụng (vùng an toàn) */} <rect x="4" y="4" width={printW - 8} height={printH - (gripperMarginMm + 4)} fill="none" stroke="#cbd5e1" strokeWidth="0.8" strokeDasharray="4 3" />
{/* Dải lề kẹp nhíp (Gripper margin) ở cạnh đáy */} <rect x={b.x} y={b.y} width={b.w} height={b.h} fill="#eff6ff" stroke="#3b82f6" x="0" y={printH - gripperMarginMm} width={printW} height={gripperMarginMm} fill="url(#gripperStripe)" opacity="0.9" /> <line x1="0" y1={printH - gripperMarginMm} x2={printW} y2={printH - gripperMarginMm} stroke="#ca8a04" strokeWidth="1" rx="1" /> <text x={b.x + b.w / 2} y={b.y + b.h / 2 + 4} x={printW / 2} y={printH - gripperMarginMm / 2 + 3} textAnchor="middle" fill="#1d4ed8" fontSize={Math.max(9, Math.min(13, b.w / 6))} fill="#854d0e" fontSize={Math.max(9, Math.min(13, printW / 38))} fontWeight="bold" > #{b.index} ▼ Lề kẹp nhíp: {gripperMarginMm}mm ({printW >= 800 ? 'Bắt nhíp chiều 86cm' : `Bắt nhíp chiều ${Math.round(printW / 10)}cm`}) </text> </g> ))} </svg> </div>
{/* Thông số bình trang vắn tắt */} <div className="grid grid-cols-3 gap-2 text-center text-xs"> {/* Danh sách các con sản phẩm (Ups) */} {boxes.map((b) => { const isVerySmall = b.w < 50 || b.h < 35; const fontSize = Math.max(9, Math.min(13, b.w / 5));
return ( <g key={b.index}> {/* Ô sản phẩm */} <rect x={b.x} y={b.y} width={b.w} height={b.h} fill="#eff6ff" stroke="#2563eb" strokeWidth="0.9" />
{/* Dấu xén (Crop marks) nhỏ ở góc nếu kích thước vừa */} {!isVerySmall && ( <> <line x1={b.x} y1={b.y + 4} x2={b.x} y2={b.y} stroke="#93c5fd" strokeWidth="0.8" /> <line x1={b.x} y1={b.y} x2={b.x + 4} y2={b.y} stroke="#93c5fd" strokeWidth="0.8" /> <line x1={b.x + b.w - 4} y1={b.y} x2={b.x + b.w} y2={b.y} stroke="#93c5fd" strokeWidth="0.8" /> <line x1={b.x + b.w} y1={b.y} x2={b.x + b.w} y2={b.y + 4} stroke="#93c5fd" strokeWidth="0.8" /> </> )}
{/* Số thứ tự con */} <text x={b.x + b.w / 2} y={isVerySmall ? b.y + b.h / 2 + 3 : b.y + b.h / 2 - 2} textAnchor="middle" fill="#1d4ed8" fontSize={fontSize} fontWeight="bold" > #{b.index} </text>
{/* Kích thước con (nếu con đủ lớn) */} {!isVerySmall && ( <text x={b.x + b.w / 2} y={b.y + b.h / 2 + fontSize * 0.9} textAnchor="middle" fill="#60a5fa" fontSize={Math.max(7, fontSize * 0.75)} > {Math.round(b.w)}×{Math.round(b.h)}mm </text> )} </g> ); })} </svg> </div>
<div className="flex items-center justify-between text-[11px] text-slate-500 px-1"> <span className="flex items-center gap-1"> <span className="w-2.5 h-2.5 bg-blue-500 rounded-2xs inline-block" /> Sản phẩm thành phẩm ({productWidthMm}×{productHeightMm}mm) {isRotated && ( <span className="text-amber-600 font-semibold inline-flex items-center gap-0.5 ml-1"> <RotateCw className="w-3 h-3" /> Xoay 90° </span> )} </span> <span className="flex items-center gap-1"> <span className="w-2.5 h-2.5 bg-amber-400 rounded-2xs inline-block" /> Lề kẹp nhíp ({gripperMarginMm}mm) </span> </div> </div> )}
{/* VÙNG 2: SƠ ĐỒ CẮT XẢ GIẤY MẸ */} {activeTab === 'paperCut' && ( <div className="space-y-2"> <div className="relative bg-slate-900/95 rounded-xl p-3 flex flex-col items-center justify-center min-h-[220px] max-h-[270px] overflow-hidden border border-slate-800 shadow-inner"> <svg viewBox={`0 0 ${parentW} ${parentH}`} className="w-full max-h-[230px] drop-shadow-xl border border-slate-700 rounded bg-white transition-all duration-300 select-none" style={{ aspectRatio: `${parentW} / ${parentH}` }} > {/* Tờ giấy mẹ nền ngoài */} <rect x="0" y="0" width={parentW} height={parentH} fill="#f1f5f9" stroke="#94a3b8" strokeWidth="1" />
{/* Các block tờ in con sau khi xén */} {(cutScheme?.blocks || []).map((block, idx) => { const color = blockColors[idx % blockColors.length]; const fontSize = Math.max(12, Math.min(22, block.w / 18));
return ( <g key={block.index}> <rect x={block.x} y={block.y} width={block.w} height={block.h} fill={color.bg} stroke={color.stroke} strokeWidth="1.2" />
{/* Tiêu đề tờ in con */} <text x={block.x + block.w / 2} y={block.y + block.h / 2 - fontSize * 0.4} textAnchor="middle" fill={color.text} fontSize={fontSize} fontWeight="bold" > {block.name.split('(')[0].trim() || `Tờ in #${block.index}`} </text>
{/* Kích thước khổ xén */} <text x={block.x + block.w / 2} y={block.y + block.h / 2 + fontSize * 0.8} textAnchor="middle" fill="#475569" fontSize={Math.max(10, fontSize * 0.75)} fontWeight="medium" > {Math.round(block.w)} × {Math.round(block.h)} mm ({upsPerPrintSheet} con) </text> </g> ); })}
{/* Các đường xén giấy (Cắt dao xén) màu đỏ nét đứt */} {(cutScheme?.cutLines || []).map((line, idx) => { const midX = (line.x1 + line.x2) / 2; const midY = (line.y1 + line.y2) / 2;
return ( <g key={idx}> <line x1={line.x1} y1={line.y1} x2={line.x2} y2={line.y2} stroke="#dc2626" strokeWidth="2" strokeDasharray="6 4" />
{/* Biểu tượng cây kéo & nhãn đường xén */} <g transform={`translate(${midX}, ${midY})`}> <rect x="-45" y="-10" width="90" height="20" rx="4" fill="#fee2e2" stroke="#ef4444" strokeWidth="1" /> <text x="0" y="4" textAnchor="middle" fill="#991b1b" fontSize="10" fontWeight="bold" > ✂ {line.label || 'Đường xén'} </text> </g> </g> ); })} </svg> </div>
<div className="bg-amber-50/80 border border-amber-200/80 rounded-lg p-2 flex items-center justify-between text-xs text-amber-900"> <span className="flex items-center gap-1.5 font-medium"> <Scissors className="w-3.5 h-3.5 text-amber-600 shrink-0" /> {cutScheme?.cutDescription || `Cắt xả từ tờ mẹ ${parentSheet.widthCm}×${parentSheet.heightCm}cm`} </span> <span className="font-semibold text-amber-800 shrink-0"> 1 tờ mẹ = {cutsPerParentSheet} tờ in ({totalUpsPerParentSheet} con) </span> </div> </div> )}
{/* THÔNG SỐ BÌNH TRANG VẮN TẮT */} <div className="grid grid-cols-3 sm:grid-cols-4 gap-2 text-center text-xs"> <div className="bg-slate-50 border border-slate-200/80 rounded-lg py-2 px-1"> <span className="text-[11px] text-slate-500 block">Số con / tờ in</span> <span className="text-sm font-bold text-blue-700">{upsPerPrintSheet} con</span>1 unmodified line </div>
<div className="bg-slate-50 border border-slate-200/80 rounded-lg py-2 px-1"> <span className="text-[11px] text-slate-500 block">Cắt từ tờ mẹ</span> <span className="text-[11px] text-slate-500 block">Cắt xả tờ mẹ</span> <span className="text-sm font-bold text-indigo-700">Chia {cutsPerParentSheet}</span> <span className="text-[10px] text-slate-400 block">{parentSheet.widthCm}×{parentSheet.heightCm}cm</span> </div>
<div className="bg-slate-50 border border-slate-200/80 rounded-lg py-2 px-1"> <span className="text-[11px] text-slate-500 block">Tổng con / tờ mẹ</span> <span className="text-sm font-bold text-violet-700">{totalUpsPerParentSheet} con</span> <span className="text-[10px] text-slate-400 block">{upsPerPrintSheet} × {cutsPerParentSheet}</span> </div>
<div className="bg-slate-50 border border-slate-200/80 rounded-lg py-2 px-1 col-span-3 sm:col-span-1"> <span className="text-[11px] text-slate-500 block">Tận dụng giấy</span> <span className="text-sm font-bold text-emerald-700">{sheetEfficiencyPercent}%</span> <span className="text-[10px] text-slate-400 block">{printSheet.widthMm}×{printSheet.heightMm}mm</span> <span className="text-[10px] text-slate-400 block">Khổ {printW}×{printH}mm</span> </div> </div> </div>112345 unmodified lines1011121314151617181920212223243 unmodified lines282930222324252627313233293031323334353435363738394038394041424243434445464748494748495051505152535455565758596061626364656667686954555657585960616270717273747576777879808182838467686970717273748586878889909192939495969798997778798081828384851001011021031041051061071081091108788899091929394959697111991001011021031041051121131141151161171181191201211221231241101111121131251261271281291304 unmodified lines1351361371241251261271281291301311321331341351361371381391401411421431441451461471381391401411421431441451461471481491501511521531541551561571581591601611621631641511521531541551561651661671681691701711721731611741751761771781791801811821831841851861871631641881891901911921931941951961971 unmodified line1992002011751761772022032042051791801811821831841851861871881892062072082092102112122132142152162172182192201931941951961971981992002012022032212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682092102112692702712722732742752142152162762772782792802812192202212222822832842852862872882892902912922932942952962972982992262272282293003013023033043053063074 unmodified lines3123133143153163173183193203213222442452463233243253263273287 unmodified lines336337338260339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605262606607608import { BoxCoordinate, ImpositionResult, PaperType, PrintTech } from '@/types';import { BoxCoordinate, ImpositionResult, PaperCutBlock, PaperCutLine, PaperCutScheme, PaperType, PrintTech } from '@/types';
interface ImpositionOptions { widthMm: number;5 unmodified lines gripperMarginMm?: number;}
interface EvaluationCandidate { name: string; sheetWidthMm: number; sheetHeightMm: number; cutsFromParent: number; cutScheme: PaperCutScheme; gripperMarginMm: number;}
export function calculateImposition({ widthMm, heightMm,3 unmodified lines preferredMachineSheet, gripperMarginMm = 10,}: ImpositionOptions): ImpositionResult { // Kích thước có chừa xén lề (Bleed) const itemW = widthMm + bleedMm * 2; const itemH = heightMm + bleedMm * 2;
const parentW_mm = paperType.parentWidthCm * 10; const parentH_mm = paperType.parentHeightCm * 10; const parentW = paperType.parentWidthCm * 10; const parentH = paperType.parentHeightCm * 10;
// Xác định các khổ in có thể cắt từ tờ giấy mẹ let candidatePrintSheets: { name: string; widthMm: number; heightMm: number; cutsFromParent: number; }[] = []; // 1. Sinh danh sách các phương án cắt xả giấy mẹ const candidates: EvaluationCandidate[] = [];
if (preferredMachineSheet) { // Máy in cụ thể được chọn const cuts = calculateCutsFromParent(parentW_mm, parentH_mm, preferredMachineSheet.widthMm, preferredMachineSheet.heightMm); candidatePrintSheets.push({ // Máy in cụ thể được chỉ định const cuts = calculateCutsFromParent(parentW, parentH, preferredMachineSheet.widthMm, preferredMachineSheet.heightMm); const cutScheme = determineCutScheme(parentW, parentH, preferredMachineSheet.widthMm, preferredMachineSheet.heightMm, cuts); candidates.push({ name: preferredMachineSheet.name, widthMm: preferredMachineSheet.widthMm, heightMm: preferredMachineSheet.heightMm, sheetWidthMm: preferredMachineSheet.widthMm, sheetHeightMm: preferredMachineSheet.heightMm, cutsFromParent: cuts, cutScheme, gripperMarginMm, }); } else if (printTech === 'digital') { // In nhanh kỹ thuật số thường in khổ A3+ (330x488mm) hoặc A3 (320x440mm) candidatePrintSheets = [ { name: 'Khổ A3+ (330 x 488 mm)', widthMm: 330, heightMm: 488, cutsFromParent: 4 }, { name: 'Khổ A3 chuẩn (297 x 420 mm)', widthMm: 297, heightMm: 420, cutsFromParent: 4 }, { name: 'Khổ A4 chuẩn (210 x 297 mm)', widthMm: 210, heightMm: 297, cutsFromParent: 8 }, // In nhanh KTS: các khổ in máy tiêu chuẩn A3+, A3, A4 const digitalCandidates = [ { name: 'Khổ A3+ (330 x 488 mm)', w: 488, h: 330, cuts: 4 }, { name: 'Khổ A3 chuẩn (297 x 420 mm)', w: 420, h: 297, cuts: 4 }, { name: 'Khổ A4 chuẩn (210 x 297 mm)', w: 297, h: 210, cuts: 8 }, ];
for (const dc of digitalCandidates) { const cuts = calculateCutsFromParent(parentW, parentH, dc.w, dc.h); const cutScheme = determineCutScheme(parentW, parentH, dc.w, dc.h, cuts); candidates.push({ name: dc.name, sheetWidthMm: dc.w, sheetHeightMm: dc.h, cutsFromParent: cuts, cutScheme, gripperMarginMm: 5, }); } } else { // In Offset: tính các phương án chia khổ giấy mẹ (chia 1, chia 2, chia 4, chia 8) // Trường hợp 0: Khổ nguyên 65x86cm (Bắt nhíp chiều 86) - cho ấn phẩm khổ lớn if (Math.max(parentW_mm, parentH_mm) <= 900) { const fullW = Math.max(parentW_mm, parentH_mm); // chiều 860 const fullH = Math.min(parentW_mm, parentH_mm); // chiều 650 candidatePrintSheets.push({ name: `Khổ 65x86cm (Bắt nhíp chiều 86)`, widthMm: fullW, heightMm: fullH, // In Offset: Các phương án chia khổ giấy mẹ chuẩn công nghiệp // Phương án 0: Nguyên khổ (Chia 1) - ví dụ 65x86 (860 x 650 mm) if (Math.max(parentW, parentH) <= 920) { const w1 = Math.max(parentW, parentH); const h1 = Math.min(parentW, parentH); candidates.push({ name: `Khổ nguyên ${Math.round(parentW/10)}x${Math.round(parentH/10)}cm (Bắt nhíp ${w1/10}cm)`, sheetWidthMm: w1, sheetHeightMm: h1, cutsFromParent: 1, cutScheme: buildFullCutScheme(parentW, parentH), gripperMarginMm, }); }
// Trường hợp 1: Chia 4 (vd 65x86 -> 4 tờ 325 x 430 mm; 79x109 -> 4 tờ 395 x 545 mm) const cut4_w = Math.floor(parentW_mm / 2); const cut4_h = Math.floor(parentH_mm / 2); candidatePrintSheets.push({ name: `Khổ chia 4 (${cut4_w} x ${cut4_h} mm)`, widthMm: cut4_w, heightMm: cut4_h, cutsFromParent: 4, // Phương án 1: Chia 2 (Cắt đôi) // Cắt đôi chiều dài (thường tạo ra khổ 430 x 650 mm từ 65x86) const longSide = Math.max(parentW, parentH); const shortSide = Math.min(parentW, parentH); const cut2_h = Math.floor(longSide / 2); const cut2_w = shortSide; candidates.push({ name: `Khổ chia 2 (${cut2_w} x ${cut2_h} mm)`, sheetWidthMm: Math.max(cut2_w, cut2_h), sheetHeightMm: Math.min(cut2_w, cut2_h), cutsFromParent: 2, cutScheme: buildCut2Scheme(parentW, parentH), gripperMarginMm, });
// Trường hợp 2: Chia 2 (vd 65x86 -> 2 tờ 650 x 430 mm; 79x109 -> 2 tờ 545 x 790 mm) // Cắt ngang const cut2_1_w = parentW_mm; const cut2_1_h = Math.floor(parentH_mm / 2); candidatePrintSheets.push({ name: `Khổ chia 2 (${cut2_1_w} x ${cut2_1_h} mm)`, widthMm: cut2_1_w, heightMm: cut2_1_h, cutsFromParent: 2, // Phương án 2: Chia 4 (Cắt chữ thập) const cut4_w = Math.floor(parentW / 2); const cut4_h = Math.floor(parentH / 2); candidates.push({ name: `Khổ chia 4 (${cut4_w} x ${cut4_h} mm)`, sheetWidthMm: Math.max(cut4_w, cut4_h), sheetHeightMm: Math.min(cut4_w, cut4_h), cutsFromParent: 4, cutScheme: buildCut4Scheme(parentW, parentH), gripperMarginMm, }); // Cắt dọc const cut2_2_w = Math.floor(parentW_mm / 2); const cut2_2_h = parentH_mm; if (cut2_2_w !== cut2_1_w || cut2_2_h !== cut2_1_h) { candidatePrintSheets.push({ name: `Khổ chia 2 dọc (${cut2_2_w} x ${cut2_2_h} mm)`, widthMm: cut2_2_w, heightMm: cut2_2_h, cutsFromParent: 2, }); }
// Trường hợp 3: Chia 8 (cho sp nhỏ namecard, thẻ tag) const cut8_w = Math.floor(parentW_mm / 2); const cut8_h = Math.floor(parentH_mm / 4); candidatePrintSheets.push({ name: `Khổ chia 8 (${cut8_w} x ${cut8_h} mm)`, widthMm: cut8_w, heightMm: cut8_h, // Phương án 3: Chia 8 (Cắt 8 - cho ấn phẩm nhỏ như namecard, tag...) const cut8_1 = Math.floor(shortSide / 2); const cut8_2 = Math.floor(longSide / 4); candidates.push({ name: `Khổ chia 8 (${cut8_1} x ${cut8_2} mm)`, sheetWidthMm: Math.max(cut8_1, cut8_2), sheetHeightMm: Math.min(cut8_1, cut8_2), cutsFromParent: 8, cutScheme: buildCut8Scheme(parentW, parentH), gripperMarginMm, }); }
// Đánh giá phương án nào cho tổng số con / tờ giấy mẹ cao nhất let bestResult: { printSheet: { widthMm: number; heightMm: number; name: string }; cutsFromParent: number; // 2. Đánh giá tất cả phương án để tìm phương án cho ra tổng số con trên tờ mẹ cao nhất let bestCandidateResult: { candidate: EvaluationCandidate; ups: number; cols: number; rows: number;4 unmodified lines usableH: number; } | null = null;
for (const candidate of candidatePrintSheets) { const evalResult = evaluateSheetImposition( candidate.widthMm, candidate.heightMm, itemW, itemH, gripperMarginMm );
const totalUpsPerParent = evalResult.ups * candidate.cutsFromParent;
if (!bestResult || totalUpsPerParent > (bestResult.ups * bestResult.cutsFromParent)) { bestResult = { printSheet: candidate, cutsFromParent: candidate.cutsFromParent, ups: evalResult.ups, cols: evalResult.cols, rows: evalResult.rows, isRotated: evalResult.isRotated, boxes: evalResult.boxes, efficiency: evalResult.efficiency, usableW: evalResult.usableW, usableH: evalResult.usableH, }; for (const cand of candidates) { const layout = evaluateImpositionLayout({ sheetW: cand.sheetWidthMm, sheetH: cand.sheetHeightMm, itemW: widthMm, itemH: heightMm, bleedMm, gripperMarginMm: cand.gripperMarginMm, });
const totalUps = layout.ups * cand.cutsFromParent;
if (!bestCandidateResult) { bestCandidateResult = { candidate: cand, ...layout }; } else { const currentBestTotal = bestCandidateResult.ups * bestCandidateResult.candidate.cutsFromParent; if (totalUps > currentBestTotal) { bestCandidateResult = { candidate: cand, ...layout }; } else if (totalUps === currentBestTotal) { // Nếu tổng số con bằng nhau, ưu tiên phương án tờ in nhỏ hơn (chia 4 hoặc chia 2) để tiết kiệm chi phí in máy if (cand.cutsFromParent > bestCandidateResult.candidate.cutsFromParent) { bestCandidateResult = { candidate: cand, ...layout }; } } } }
// Fallback an toàn nếu chưa tìm được if (!bestResult || bestResult.ups === 0) { const fallbackSheet = candidatePrintSheets[0]; bestResult = { printSheet: fallbackSheet, cutsFromParent: fallbackSheet.cutsFromParent, // Fallback nếu kh��ng có con nào vừa if (!bestCandidateResult || bestCandidateResult.ups === 0) { const fallbackCand = candidates[0]; bestCandidateResult = { candidate: fallbackCand, ups: 1, cols: 1, rows: 1, isRotated: false, boxes: [{ x: 10, y: gripperMarginMm + 5, w: itemW, h: itemH, index: 1 }], boxes: [ { index: 1, x: 10, y: 10, w: widthMm + bleedMm * 2, h: heightMm + bleedMm * 2, trimW: widthMm, trimH: heightMm, bleedMm, isRotated: false, }, ], efficiency: 10, usableW: fallbackSheet.widthMm, usableH: fallbackSheet.heightMm, usableW: fallbackCand.sheetWidthMm, usableH: fallbackCand.sheetHeightMm, }; }
const { candidate, ups, cols, rows, isRotated, boxes, efficiency, usableW, usableH } = bestCandidateResult;
return { parentSheet: { widthCm: paperType.parentWidthCm,1 unmodified line name: `${paperType.name} (${paperType.parentWidthCm}x${paperType.parentHeightCm}cm)`, }, printSheet: { widthMm: bestResult.printSheet.widthMm, heightMm: bestResult.printSheet.heightMm, name: bestResult.printSheet.name, widthMm: candidate.sheetWidthMm, heightMm: candidate.sheetHeightMm, name: candidate.name, }, upsPerPrintSheet: bestResult.ups, cutsPerParentSheet: bestResult.cutsFromParent, totalUpsPerParentSheet: bestResult.ups * bestResult.cutsFromParent, gripperMarginMm, usableWidthMm: bestResult.usableW, usableHeightMm: bestResult.usableH, cols: bestResult.cols, rows: bestResult.rows, isRotated: bestResult.isRotated, boxes: bestResult.boxes, sheetEfficiencyPercent: Math.round(bestResult.efficiency * 10) / 10, upsPerPrintSheet: ups, cutsPerParentSheet: candidate.cutsFromParent, totalUpsPerParentSheet: ups * candidate.cutsFromParent, gripperMarginMm: candidate.gripperMarginMm, usableWidthMm: usableW, usableHeightMm: usableH, cols, rows, isRotated, boxes, sheetEfficiencyPercent: Math.round(efficiency * 10) / 10, cutScheme: candidate.cutScheme, };}
// Tính số con tối đa trên 1 khổ in máy kèm tọa độ hiển thị trực quanfunction evaluateSheetImposition( sheetW: number, sheetH: number, itemW: number, itemH: number, gripperMarginMm: number) { // Lề máy in: 1 cạnh chừa nhíp (gripper) = 10mm, các cạnh còn lại chừa mép xén = 5mm const usableW = sheetW - 10; // lề trái 5mm, lề phải 5mm const usableH = sheetH - (gripperMarginMm + 5); // lề nhíp dưới 10mm, lề trên 5mm// -----------------------------------------------------------------------------------------// THUẬT TOÁN XẾP BÌNH BÀI CHUẨN XÉNG CÔNG NGHIỆP TRÊN TỜ IN MÁY// -----------------------------------------------------------------------------------------interface LayoutEvalParams { sheetW: number; sheetH: number; itemW: number; itemH: number; bleedMm: number; gripperMarginMm: number;}
interface LayoutResult { ups: number; cols: number; rows: number; isRotated: boolean; boxes: BoxCoordinate[]; efficiency: number; usableW: number; usableH: number;}
function evaluateImpositionLayout({ sheetW, sheetH, itemW, itemH, bleedMm, gripperMarginMm,}: LayoutEvalParams): LayoutResult { // Quy ước máy in: // Cạnh dài là cạnh bắt nhíp: width = max(sheetW, sheetH), height = min(sheetW, sheetH) const W = Math.max(sheetW, sheetH); const H = Math.min(sheetW, sheetH);
// Lề kẹp nhíp ở cạnh đáy (gripperMarginMm = 10mm) // Lề đuôi (đối diện nhíp): 4mm // Lề 2 bên biên: 4mm mỗi bên (tổng 8mm) const marginSide = 4; const marginTail = 4; const usableW = W - marginSide * 2; const usableH = H - (gripperMarginMm + marginTail);
if (usableW < itemW && usableW < itemH) { return { ups: 0, cols: 0, rows: 0, isRotated: false, boxes: [], efficiency: 0, usableW, usableH }; }
// Cách 1: Xếp thẳng (Không xoay) const cols1 = Math.floor(usableW / itemW); const rows1 = Math.floor(usableH / itemH); // --- Cách 1: Xếp Thẳng (Không xoay) --- // Chiều ngang chứa C1 cột thành phẩm, có tràn lề 2mm ở 2 mép ngoài cùng // Công thức: C1 * itemW + 2 * bleedMm <= usableW const cols1 = Math.max(0, Math.floor((usableW - 2 * bleedMm) / itemW)); const rows1 = Math.max(0, Math.floor((usableH - 2 * bleedMm) / itemH)); const ups1 = cols1 * rows1;
// Cách 2: Xếp xoay 90 độ const cols2 = Math.floor(usableW / itemH); const rows2 = Math.floor(usableH / itemW); // --- Cách 2: Xếp Xoay 90 độ --- // Chiều ngang xếp theo itemH, chiều dọc xếp theo itemW const cols2 = Math.max(0, Math.floor((usableW - 2 * bleedMm) / itemH)); const rows2 = Math.max(0, Math.floor((usableH - 2 * bleedMm) / itemW)); const ups2 = cols2 * rows2;
const isRotated = ups2 > ups1; const bestCols = isRotated ? cols2 : cols1; const bestRows = isRotated ? rows2 : rows1; const bestUps = isRotated ? ups2 : ups1; // Chọn phương án tốt nhất giữa Xếp Thẳng (ups1) và Xếp Xoay 90° (ups2) let bestUps = ups1; let bestCols = cols1; let bestRows = rows1; let isRotated = false;
if (ups2 > bestUps) { bestUps = ups2; bestCols = cols2; bestRows = rows2; isRotated = true; }
// Tạo danh sách tọa độ các hộp sản phẩm const boxes: BoxCoordinate[] = []; const boxW = isRotated ? itemH : itemW; const boxH = isRotated ? itemW : itemH;
// Tính toán tọa độ chính xác của từng con (để vẽ lên SVG / Canvas) const boxes: BoxCoordinate[] = []; const startX = 5; // lề mép trái const startY = 5; // lề mép trên (chừa nhíp ở dưới đáy) // Canh giữa cụm con trong vùng in hữu dụng const blockW = bestCols * boxW + 2 * bleedMm; const blockH = bestRows * boxH + 2 * bleedMm; const startX = marginSide + Math.max(0, Math.floor((usableW - blockW) / 2)) + bleedMm; const startY = marginTail + Math.max(0, Math.floor((usableH - blockH) / 2)) + bleedMm;
let idx = 1; for (let r = 0; r < bestRows; r++) {4 unmodified lines y: Math.round((startY + r * boxH) * 10) / 10, w: boxW, h: boxH, trimW: itemW, trimH: itemH, bleedMm, isRotated, }); } }
const itemArea = itemW * itemH * bestUps; const sheetArea = sheetW * sheetH; const efficiency = sheetArea > 0 ? (itemArea / sheetArea) * 100 : 0; const totalItemArea = itemW * itemH * bestUps; const sheetArea = W * H; const efficiency = sheetArea > 0 ? (totalItemArea / sheetArea) * 100 : 0;
return { ups: bestUps,7 unmodified lines };}
// Tính số tờ in có thể cắt ra từ tờ giấy mẹ// -----------------------------------------------------------------------------------------// SINH SƠ ĐỒ CẮT GIẤY MẸ TRỰC QUAN (PAPER CUTTING SCHEME)// -----------------------------------------------------------------------------------------
export function determineCutScheme( parentW: number, parentH: number, printW: number, printH: number, cuts: number): PaperCutScheme { const pw = Math.max(parentW, parentH); const ph = Math.min(parentW, parentH);
if (cuts <= 1) return buildFullCutScheme(pw, ph); if (cuts === 2) return buildCut2Scheme(pw, ph); if (cuts === 4) return buildCut4Scheme(pw, ph); if (cuts === 8) return buildCut8Scheme(pw, ph); return buildSimpleCutScheme(pw, ph, printW, printH, cuts);}
function buildFullCutScheme(parentW: number, parentH: number): PaperCutScheme { const pw = Math.max(parentW, parentH); const ph = Math.min(parentW, parentH);
return { parentWidthMm: pw, parentHeightMm: ph, cutType: 'chia_1', cutDescription: `In nguyên khổ ${pw} x ${ph} mm (không cần xén trước khi in)`, cutsCount: 1, cutSheetWidthMm: pw, cutSheetHeightMm: ph, wasteAreaPercent: 0, cutLines: [], blocks: [ { index: 1, x: 0, y: 0, w: pw, h: ph, name: `Tờ in #1 (${pw} x ${ph} mm)`, }, ], };}
function buildCut2Scheme(parentW: number, parentH: number): PaperCutScheme { const pw = Math.max(parentW, parentH); // ví dụ 860mm const ph = Math.min(parentW, parentH); // ví dụ 650mm const cutW = Math.floor(pw / 2); // 430mm
return { parentWidthMm: pw, parentHeightMm: ph, cutType: 'chia_2', cutDescription: `Xén đôi chiều ${pw}mm thành 2 tờ ${ph} x ${cutW} mm (Chia 2)`, cutsCount: 2, cutSheetWidthMm: ph, cutSheetHeightMm: cutW, wasteAreaPercent: 0, cutLines: [ { x1: cutW, y1: 0, x2: cutW, y2: ph, type: 'vertical', label: `Xén dọc: ${cutW}mm`, }, ], blocks: [ { index: 1, x: 0, y: 0, w: cutW, h: ph, name: `Tờ in #1 (${ph} x ${cutW} mm)`, }, { index: 2, x: cutW, y: 0, w: pw - cutW, h: ph, name: `Tờ in #2 (${ph} x ${cutW} mm)`, }, ], };}
function buildCut4Scheme(parentW: number, parentH: number): PaperCutScheme { const pw = Math.max(parentW, parentH); // ví dụ 860 hoặc 1090 const ph = Math.min(parentW, parentH); // ví dụ 650 hoặc 790 const halfW = Math.floor(pw / 2); // 430 const halfH = Math.floor(ph / 2); // 325
return { parentWidthMm: pw, parentHeightMm: ph, cutType: 'chia_4', cutDescription: `Xén chữ thập (Chia 4) thành 4 tờ ${halfW} x ${halfH} mm`, cutsCount: 4, cutSheetWidthMm: halfW, cutSheetHeightMm: halfH, wasteAreaPercent: 0, cutLines: [ { x1: halfW, y1: 0, x2: halfW, y2: ph, type: 'vertical', label: `Xén dọc: ${halfW}mm`, }, { x1: 0, y1: halfH, x2: pw, y2: halfH, type: 'horizontal', label: `Xén ngang: ${halfH}mm`, }, ], blocks: [ { index: 1, x: 0, y: 0, w: halfW, h: halfH, name: `Tờ in #1 (${halfW} x ${halfH} mm)` }, { index: 2, x: halfW, y: 0, w: pw - halfW, h: halfH, name: `Tờ in #2 (${halfW} x ${halfH} mm)` }, { index: 3, x: 0, y: halfH, w: halfW, h: ph - halfH, name: `Tờ in #3 (${halfW} x ${halfH} mm)` }, { index: 4, x: halfW, y: halfH, w: pw - halfW, h: ph - halfH, name: `Tờ in #4 (${halfW} x ${halfH} mm)` }, ], };}
function buildCut8Scheme(parentW: number, parentH: number): PaperCutScheme { const pw = Math.max(parentW, parentH); // ví dụ 860 const ph = Math.min(parentW, parentH); // ví dụ 650 const colW = Math.floor(pw / 4); // 215 const rowH = Math.floor(ph / 2); // 325
const blocks: PaperCutBlock[] = []; const cutLines: PaperCutLine[] = [ { x1: colW, y1: 0, x2: colW, y2: ph, type: 'vertical', label: `Xén: ${colW}mm` }, { x1: colW * 2, y1: 0, x2: colW * 2, y2: ph, type: 'vertical', label: `Xén: ${colW * 2}mm` }, { x1: colW * 3, y1: 0, x2: colW * 3, y2: ph, type: 'vertical', label: `Xén: ${colW * 3}mm` }, { x1: 0, y1: rowH, x2: pw, y2: rowH, type: 'horizontal', label: `Xén ngang: ${rowH}mm` }, ];
let idx = 1; for (let r = 0; r < 2; r++) { for (let c = 0; c < 4; c++) { const curW = c === 3 ? pw - colW * 3 : colW; const curH = r === 1 ? ph - rowH : rowH; blocks.push({ index: idx++, x: c * colW, y: r * rowH, w: curW, h: curH, name: `Tờ in #${idx - 1} (${rowH} x ${colW} mm)`, }); } }
return { parentWidthMm: pw, parentHeightMm: ph, cutType: 'chia_8', cutDescription: `Xén chia 8 thành 8 tờ ${rowH} x ${colW} mm`, cutsCount: 8, cutSheetWidthMm: rowH, cutSheetHeightMm: colW, wasteAreaPercent: 0, cutLines, blocks, };}
function buildSimpleCutScheme( parentW: number, parentH: number, printW: number, printH: number, cuts: number): PaperCutScheme { const pw = Math.max(parentW, parentH); const ph = Math.min(parentW, parentH);
// So sánh 2 chiều xếp trên tờ mẹ const c1 = Math.floor(pw / printW); const r1 = Math.floor(ph / printH); const tot1 = c1 * r1;
const c2 = Math.floor(pw / printH); const r2 = Math.floor(ph / printW); const tot2 = c2 * r2;
const useRotated = tot2 > tot1; const pieceW = useRotated ? printH : printW; const pieceH = useRotated ? printW : printH; const cols = useRotated ? c2 : c1; const rows = useRotated ? r2 : r1;
const actualCols = Math.max(1, cols); const actualRows = Math.max(1, rows);
const blocks: PaperCutBlock[] = []; const cutLines: PaperCutLine[] = [];
let idx = 1; for (let r = 0; r < actualRows; r++) { for (let c = 0; c < actualCols; c++) { if (idx <= cuts) { blocks.push({ index: idx++, x: c * pieceW, y: r * pieceH, w: pieceW, h: pieceH, name: `Tờ in #${idx - 1} (${pieceW} x ${pieceH} mm)`, }); } } }
// Tạo cut lines for (let c = 1; c < actualCols; c++) { cutLines.push({ x1: c * pieceW, y1: 0, x2: c * pieceW, y2: Math.min(ph, actualRows * pieceH), type: 'vertical', label: `Xén: ${c * pieceW}mm`, }); } for (let r = 1; r < actualRows; r++) { cutLines.push({ x1: 0, y1: r * pieceH, x2: Math.min(pw, actualCols * pieceW), y2: r * pieceH, type: 'horizontal', label: `Xén: ${r * pieceH}mm`, }); }
const usedArea = cuts * pieceW * pieceH; const totalArea = pw * ph; const wastePercent = totalArea > 0 ? Math.max(0, Math.round(((totalArea - usedArea) / totalArea) * 100)) : 0;
return { parentWidthMm: pw, parentHeightMm: ph, cutType: cuts === 2 ? 'chia_2' : cuts === 4 ? 'chia_4' : cuts === 8 ? 'chia_8' : 'custom', cutDescription: `Cắt ${cuts} tờ in (${pieceW} x ${pieceH} mm) từ tờ giấy mẹ ${pw} x ${ph} mm`, cutsCount: cuts, cutSheetWidthMm: pieceW, cutSheetHeightMm: pieceH, wasteAreaPercent: wastePercent, cutLines, blocks, };}
function calculateCutsFromParent(parentW: number, parentH: number, printW: number, printH: number): number { // Thử 2 hướng cắt: thẳng và xoay const cuts1 = Math.floor(parentW / printW) * Math.floor(parentH / printH); const cuts2 = Math.floor(parentW / printH) * Math.floor(parentH / printW); return Math.max(cuts1, cuts2, 1);100 unmodified lines10110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514619 unmodified lines166167168169170171172100 unmodified lines vatPercent?: number;}
export interface PaperCutLine { x1: number; y1: number; x2: number; y2: number; type: 'vertical' | 'horizontal'; label?: string;}
export interface PaperCutBlock { index: number; x: number; y: number; w: number; h: number; name: string;}
export interface PaperCutScheme { parentWidthMm: number; parentHeightMm: number; cutType: 'chia_1' | 'chia_2' | 'chia_4' | 'chia_6' | 'chia_8' | 'custom'; cutDescription: string; cutsCount: number; cutSheetWidthMm: number; cutSheetHeightMm: number; blocks: PaperCutBlock[]; wasteAreaPercent: number; cutLines?: PaperCutLine[];}
export interface BoxCoordinate { x: number; y: number; w: number; h: number; trimW?: number; trimH?: number; bleedMm?: number; isRotated?: boolean; index: number;}
19 unmodified lines isRotated: boolean; boxes: BoxCoordinate[]; sheetEfficiencyPercent: number; cutScheme?: PaperCutScheme;}
export interface FinishingCostDetail {src/app/page.tsx+1-1
src/components/ImpositionVisualizer.tsx+317-63
src/lib/engine/imposition.ts+492-149
src/types/index.ts+36