feat: PrintCal - Smart offset and digital print pricing calculator with ERP management
Browse filesFiles changed (32)
- .dockerignoreAdded+8
- .gitignore+6
- DockerfileAdded+29
- README.md+57-23
- data/printcal.dbAdded
- package-lock.json+78-2
- package.json+3-2
- src/app/api/calculate/route.tsAdded+117
- src/app/api/customers/route.tsAdded+48
- src/app/api/finishing/route.tsAdded+99
- src/app/api/machines/route.tsAdded+90
- src/app/api/orders/route.tsAdded+216
- src/app/api/papers/route.tsAdded+99
- src/app/api/settings/route.tsAdded+57
- src/app/layout.tsx+4-4
- src/app/page.tsx+839-63
- src/components/BreakEvenChart.tsxAdded+156
- src/components/CostBreakdownCard.tsxAdded+211
- src/components/CustomerManager.tsxAdded+227
- src/components/FinishingManager.tsxAdded+308
- src/components/ImpositionVisualizer.tsxAdded+187
- src/components/MachineManager.tsxAdded+326
- src/components/Navbar.tsxAdded+131
- src/components/OrdersManager.tsxAdded+263
- src/components/PaperManager.tsxAdded+296
- src/components/QuotePrintModal.tsxAdded+417
- src/components/SettingsManager.tsxAdded+202
- src/lib/db.tsAdded+287
- src/lib/engine/costCalculator.tsAdded+413
- src/lib/engine/imposition.tsAdded+242
- src/types/index.tsAdded+246
- src/types/sqlite.d.tsAdded+14
12345678node_modules.next.git.gitignore*.logdata/*.db-waldata/*.db-shmdata/*.db-journal38 unmodified lines39404138 unmodified lines# typescript*.tsbuildinfonext-env.d.ts38 unmodified lines39404142434445464738 unmodified lines# typescript*.tsbuildinfonext-env.d.ts# sqlite tempdata/*.db-waldata/*.db-shmdata/*.db-journal
1234567891011121314151617181920212223242526272829FROM node:24-alpine
WORKDIR /app
ENV NODE_ENV=productionENV NEXT_TELEMETRY_DISABLED=1ENV PORT=3000ENV HOSTNAME="0.0.0.0"
# User UID 1000 for Hugging Face Spaces compatibilityRUN addgroup --system --gid 1001 nodejs && \ adduser --system --uid 1000 nextjs
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# Setup data directory permissionsRUN mkdir -p /app/data && chown -R nextjs:nodejs /app
USER nextjs
EXPOSE 3000
CMD ["npm", "run", "start"]123456789101112131415161718192021222324252627282930313233343536This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).## Getting StartedFirst, run the development server:```bashnpm run dev# oryarn dev# orpnpm dev# orbun dev```Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.## Learn MoreTo learn more about Next.js, take a look at the following resources:- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!## Deploy on VercelThe easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970---title: PrintCalemoji: 🖨️colorFrom: bluecolorTo: indigosdk: dockerapp_port: 3000pinned: falselicense: mitshort_description: Công cụ tính giá in Offset & In Nhanh thông minh, quản lý đơn hàng---# 🖨️ PrintCal - Công Cụ Tính Giá In Offset & In Nhanh Thông Minh**PrintCal** là hệ thống phần mềm chuyên nghiệp phục vụ tính toán chi phí in ấn (Offset & In Nhanh Kỹ Thuật Số), tích hợp thuật toán bình trang cắt giấy 2D, phân tích điểm hòa vốn, cùng cơ sở dữ liệu SQLite quản lý đơn hàng, kho giá giấy, bảng giá in và gia công sau in.---## 🌟 Tính Năng Cốt Lõi### 1. ⚡ Máy Tính Giá In Thông Minh (Smart Calculator)- **Mẫu ấn phẩm 1-click (Presets)**: Tờ rơi A4, A5, Namecard, Brochure gấp 3, Hộp mỹ phẩm, Túi giấy Kraft, Decal tem nhãn...- **Thuật toán bình trang & Cắt giấy 2D (`imposition.ts`)**: Tự động tính số con (ups) tối ưu trên tờ in máy, tự động tìm cách chia từ các khổ giấy mẹ (65x86, 79x109, 60x84...).- **Bản vẽ 2D trực quan bằng SVG**: Hiển thị rõ vùng kẹp nhíp (10mm), đường xén thành phẩm, đánh số thứ tự từng con `#1, #2...`, và tỷ lệ tận dụng diện tích giấy.- **Bù hao thông minh**: Tự động cộng bù hao canh màu kẽm Offset (80–120 tờ), bù hao in nhanh (3–5 tờ), và bù hao lũy tiến theo từng khâu gia công.- **Quy đổi định lượng**: Tự động tính số tờ in, số tờ giấy mẹ, quy đổi ra **Số Ram (500 tờ)** hoặc **Số Kg** theo định lượng GSM.### 2. 📊 Phân Tích Hòa Vốn & So Sánh Công Nghệ In (Break-even Engine)- Tự động so sánh chi phí giữa **In Nhanh KTS (Click)** và **In Offset (Kẽm + Công Máy)** theo các mốc số lượng thực tế.- Biểu đồ trực quan chỉ rõ điểm hòa vốn (Break-even crossover) và đưa ra lời khuyên công nghệ in nào tiết kiệm chi phí nhất theo đơn hàng.### 3. 💾 Cơ Sở Dữ Liệu SQLite Native Quản Lý Đơn Hàng & Giá Cả- Lưu trữ bền vững tại file `data/printcal.db` (dễ dàng sao lưu, không cần cài đặt SQL Server phức tạp).- **Kho Giá Giấy**: Đã nạp sẵn bảng giá chuẩn ngành in Việt Nam (Couche C100-C300, Ivory, Bristol, Ford, Kraft, Decal...).- **Bảng Giá Máy In**: Quản lý giá xuất kẽm CTP, phí mở máy in, giá lũy tiến /1.000 lượt ép, đơn giá click in nhanh A4/A3.- **Bảng Giá Gia Công Sau In**: 17+ công đoạn (cán màng bóng/mờ/metalize, cấn, bế demi/đứt, ép kim, dập nổi 3D, phủ UV, đóng ghim, dán gáy sách, dán hộp...).- **Quản Lý Đơn Hàng & Báo Giá**: Tự động sinh mã đơn `PC-YYYYMM-XXX`, theo dõi tiến độ sản xuất 6 bước (Báo giá ➔ Duyệt ➔ In máy ➔ Gia công ➔ Hoàn thành ➔ Giao hàng).### 4. 📄 Xuất Bản & In Ấn Chuẩn A4- **Phiếu Báo Giá Khách Hàng**: Đầy đủ thông tin nhà in, quy cách ấn phẩm, bảng giá, thuế VAT, số tài khoản thanh toán và điều khoản giao nhận.- **Lệnh Sản Xuất Xưởng In**: Phiếu kỹ thuật dành riêng cho xưởng in ghi rõ khổ cắt giấy mẹ, số ram, số kẽm CTP, số lượt ép và danh mục gia công kèm chữ ký bàn giao thợ máy.- **Nút Copy Báo Giá Zalo**: Tự động định dạng văn bản báo giá ngắn gọn, chuyên nghiệp để gửi trực tiếp cho khách qua Zalo/Messenger.---## 🚀 Khởi Chạy Ứng Dụng### 1. Cài đặt và chạy cục bộ (Local Development)Yêu cầu Node.js 22 trở lên:```bashgit clone https://github.com/phucsd1/PrintCal.gitcd PrintCalnpm installnpm run dev```Truy cập: `http://localhost:3000`### 2. Chạy với Docker```bashdocker build -t printcal .docker run -p 3000:3000 printcal```---## 🛠️ Công Nghệ Sử Dụng- **Frontend / Backend**: Next.js 16 (App Router), React 19, TypeScript- **Styling**: Tailwind CSS v4, Lucide Icons- **Database**: Native `node:sqlite` (SQLite 3 không cần cài đặt ngoài)- **Deployment**: Docker, Hugging Face Spaces, GitHub
123456789101112131614 unmodified lines1628162916301631163216333522 unmodified lines515651575158515951605161{"name": "temp-app","version": "0.1.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "temp-app","version": "0.1.0","dependencies": {"next": "16.3.4","react": "19.2.8","react-dom": "19.2.8"1614 unmodified lines"node": ">=14.0.0"}},"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {"version": "4.3.3","resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",3522 unmodified lines"yallist": "^3.0.2"}},"node_modules/magic-string": {"version": "0.30.21","resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",12345678910111213141614 unmodified lines1629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917003522 unmodified lines522352245225522652275228522952305231523252335234523552365237{"name": "printcal","version": "0.1.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "printcal","version": "0.1.0","dependencies": {"lucide-react": "^1.43.0","next": "16.3.4","react": "19.2.8","react-dom": "19.2.8"1614 unmodified lines"node": ">=14.0.0"}},"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {"version": "1.11.1","dev": true,"inBundle": true,"license": "MIT","optional": true,"dependencies": {"@emnapi/wasi-threads": "1.2.2","tslib": "^2.4.0"}},"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {"version": "1.11.1","dev": true,"inBundle": true,"license": "MIT","optional": true,"dependencies": {"tslib": "^2.4.0"}},"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {"version": "1.2.2","dev": true,"inBundle": true,"license": "MIT","optional": true,"dependencies": {"tslib": "^2.4.0"}},"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {"version": "1.1.4","dev": true,"inBundle": true,"license": "MIT","optional": true,"dependencies": {"@tybys/wasm-util": "^0.10.1"},"funding": {"type": "github","url": "https://github.com/sponsors/Brooooooklyn"},"peerDependencies": {"@emnapi/core": "^1.7.1","@emnapi/runtime": "^1.7.1"}},"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {"version": "0.10.2","dev": true,"inBundle": true,"license": "MIT","optional": true,"dependencies": {"tslib": "^2.4.0"}},"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {"version": "2.8.1","dev": true,"inBundle": true,"license": "0BSD","optional": true},"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {"version": "4.3.3","resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",3522 unmodified lines"yallist": "^3.0.2"}},"node_modules/lucide-react": {"version": "1.43.0","resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.43.0.tgz","integrity": "sha512-ubtnda1fVK5ky0PNEpOmB0wiwhpZUyJiol4K14KCm+QKvuCkfUu54Et/rIjyupJpwiJ5Hg+BLQE86/GEsS+IgQ==","license": "ISC","peerDependencies": {"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},"node_modules/magic-string": {"version": "0.30.21","resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
1234567891011121314{"name": "temp-app","version": "0.1.0","private": true,"scripts": {"dev": "next dev","build": "next build","start": "next start","lint": "eslint"},"dependencies": {"next": "16.3.4","react": "19.2.8","react-dom": "19.2.8"123456789101112131415{"name": "printcal","version": "0.1.0","private": true,"scripts": {"dev": "next dev","build": "next build","start": "next start -H 0.0.0.0 -p 3000","lint": "eslint"},"dependencies": {"lucide-react": "^1.43.0","next": "16.3.4","react": "19.2.8","react-dom": "19.2.8"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { calculatePrintCost } from '@/lib/engine/costCalculator';import { CalculationInput, DigitalMachine, FinishingService, OffsetMachine, PaperType } from '@/types';
export async function POST(req: NextRequest) { try { const input = (await req.json()) as CalculationInput; const db = getDb();
// Lấy thông tin giấy const paperRow = db.prepare('SELECT * FROM paper_types WHERE id = ?').get(input.paperTypeId) as Record<string, unknown> | undefined; if (!paperRow) { return NextResponse.json({ error: 'Không tìm thấy loại giấy yêu cầu' }, { status: 400 }); }
const paperType: PaperType = { id: paperRow.id as number, code: paperRow.code as string, name: paperRow.name as string, gsm: paperRow.gsm as number, parentWidthCm: paperRow.parent_width_cm as number, parentHeightCm: paperRow.parent_height_cm as number, pricePerRam: paperRow.price_per_ram as number, pricePerKg: paperRow.price_per_kg as number, unit: paperRow.unit as 'ram' | 'kg', description: paperRow.description as string, isActive: Boolean(paperRow.is_active), };
// Lấy thông số máy in offset let offsetMachine: OffsetMachine | undefined; if (input.offsetMachineId) { const row = db.prepare('SELECT * FROM offset_machines WHERE id = ?').get(input.offsetMachineId) as Record<string, unknown> | undefined; if (row) { offsetMachine = mapOffsetMachine(row); } } if (!offsetMachine) { const row = db.prepare('SELECT * FROM offset_machines ORDER BY id ASC LIMIT 1').get() as Record<string, unknown> | undefined; if (row) offsetMachine = mapOffsetMachine(row); }
// Lấy thông số máy in nhanh let digitalMachine: DigitalMachine | undefined; if (input.digitalMachineId) { const row = db.prepare('SELECT * FROM digital_machines WHERE id = ?').get(input.digitalMachineId) as Record<string, unknown> | undefined; if (row) { digitalMachine = mapDigitalMachine(row); } } if (!digitalMachine) { const row = db.prepare('SELECT * FROM digital_machines ORDER BY id ASC LIMIT 1').get() as Record<string, unknown> | undefined; if (row) digitalMachine = mapDigitalMachine(row); }
// Lấy danh mục dịch vụ gia công const finishingRows = db.prepare('SELECT * FROM finishing_services WHERE is_active = 1').all() as Record<string, unknown>[]; const allFinishingServices: FinishingService[] = finishingRows.map((r) => ({ id: r.id as number, code: r.code as string, name: r.name as string, category: r.category as FinishingService['category'], calcType: r.calc_type as FinishingService['calcType'], unitPrice: r.unit_price as number, minPrice: r.min_price as number, setupFee: r.setup_fee as number, wastePercent: r.waste_percent as number, wasteSheets: r.waste_sheets as number, isActive: Boolean(r.is_active), }));
const result = calculatePrintCost({ input, paperType, offsetMachine, digitalMachine, allFinishingServices, });
return NextResponse.json(result); } catch (err: unknown) { console.error('Calculate error:', err); return NextResponse.json({ error: (err as Error).message || 'Lỗi tính toán chi phí' }, { status: 500 }); }}
function mapOffsetMachine(r: Record<string, unknown>): OffsetMachine { return { id: r.id as number, name: r.name as string, maxWidthMm: r.max_width_mm as number, maxHeightMm: r.max_height_mm as number, minWidthMm: r.min_width_mm as number, minHeightMm: r.min_height_mm as number, platePrice: r.plate_price as number, setupCost: r.setup_cost as number, stepCost: r.step_cost as number, defaultWasteSheets: r.default_waste_sheets as number, gripperMarginMm: (r.gripper_margin_mm as number) || 10, };}
function mapDigitalMachine(r: Record<string, unknown>): DigitalMachine { return { id: r.id as number, name: r.name as string, maxWidthMm: r.max_width_mm as number, maxHeightMm: r.max_height_mm as number, clickA41Side: r.click_a4_1side as number, clickA42Side: r.click_a4_2side as number, clickA31Side: r.click_a3_1side as number, clickA32Side: r.click_a3_2side as number, defaultWasteSheets: (r.default_waste_sheets as number) || 3, minCharge: (r.min_charge as number) || 20000, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { Customer } from '@/types';
export async function GET() { try { const db = getDb(); const rows = db.prepare('SELECT * FROM customers ORDER BY id DESC').all() as Record<string, unknown>[]; const customers: Customer[] = rows.map((r) => ({ id: r.id as number, name: r.name as string, phone: r.phone as string, email: (r.email as string) || '', company: (r.company as string) || '', address: (r.address as string) || '', notes: (r.notes as string) || '', createdAt: r.created_at as string, })); return NextResponse.json(customers); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function POST(req: NextRequest) { try { const body = await req.json(); const db = getDb();
const stmt = db.prepare(` INSERT INTO customers (name, phone, email, company, address, notes) VALUES (?, ?, ?, ?, ?, ?) `);
const result = stmt.run( body.name, body.phone, body.email || '', body.company || '', body.address || '', body.notes || '' );
return NextResponse.json({ success: true, id: Number(result.lastInsertRowid) }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { FinishingService } from '@/types';
export async function GET() { try { const db = getDb(); const rows = db.prepare('SELECT * FROM finishing_services ORDER BY category ASC, id ASC').all() as Record<string, unknown>[]; const services: FinishingService[] = rows.map((r) => ({ id: r.id as number, code: r.code as string, name: r.name as string, category: r.category as FinishingService['category'], calcType: r.calc_type as FinishingService['calcType'], unitPrice: r.unit_price as number, minPrice: r.min_price as number, setupFee: r.setup_fee as number, wastePercent: r.waste_percent as number, wasteSheets: r.waste_sheets as number, isActive: Boolean(r.is_active), })); return NextResponse.json(services); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function POST(req: NextRequest) { try { const body = await req.json(); const db = getDb();
const stmt = db.prepare(` INSERT INTO finishing_services (code, name, category, calc_type, unit_price, min_price, setup_fee, waste_percent, waste_sheets, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `);
const result = stmt.run( body.code, body.name, body.category, body.calcType, body.unitPrice, body.minPrice || 0, body.setupFee || 0, body.wastePercent || 0, body.wasteSheets || 0, body.isActive !== false ? 1 : 0 );
return NextResponse.json({ success: true, id: Number(result.lastInsertRowid) }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function PUT(req: NextRequest) { try { const body = await req.json(); const db = getDb();
const stmt = db.prepare(` UPDATE finishing_services SET name = ?, category = ?, calc_type = ?, unit_price = ?, min_price = ?, setup_fee = ?, waste_percent = ?, waste_sheets = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? `);
stmt.run( body.name, body.category, body.calcType, body.unitPrice, body.minPrice || 0, body.setupFee || 0, body.wastePercent || 0, body.wasteSheets || 0, body.isActive ? 1 : 0, body.id );
return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function DELETE(req: NextRequest) { try { const { searchParams } = new URL(req.url); const id = searchParams.get('id'); if (!id) return NextResponse.json({ error: 'Thiếu ID dịch vụ' }, { status: 400 });
const db = getDb(); db.prepare('DELETE FROM finishing_services WHERE id = ?').run(Number(id)); return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { DigitalMachine, OffsetMachine } from '@/types';
export async function GET() { try { const db = getDb(); const offsetRows = db.prepare('SELECT * FROM offset_machines ORDER BY id ASC').all() as Record<string, unknown>[]; const digitalRows = db.prepare('SELECT * FROM digital_machines ORDER BY id ASC').all() as Record<string, unknown>[];
const offsetMachines: OffsetMachine[] = offsetRows.map((r) => ({ id: r.id as number, name: r.name as string, maxWidthMm: r.max_width_mm as number, maxHeightMm: r.max_height_mm as number, minWidthMm: r.min_width_mm as number, minHeightMm: r.min_height_mm as number, platePrice: r.plate_price as number, setupCost: r.setup_cost as number, stepCost: r.step_cost as number, defaultWasteSheets: r.default_waste_sheets as number, gripperMarginMm: (r.gripper_margin_mm as number) || 10, }));
const digitalMachines: DigitalMachine[] = digitalRows.map((r) => ({ id: r.id as number, name: r.name as string, maxWidthMm: r.max_width_mm as number, maxHeightMm: r.max_height_mm as number, clickA41Side: r.click_a4_1side as number, clickA42Side: r.click_a4_2side as number, clickA31Side: r.click_a3_1side as number, clickA32Side: r.click_a3_2side as number, defaultWasteSheets: r.default_waste_sheets as number, minCharge: r.min_charge as number, }));
return NextResponse.json({ offsetMachines, digitalMachines }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function PUT(req: NextRequest) { try { const body = await req.json(); const db = getDb();
if (body.type === 'offset') { const stmt = db.prepare(` UPDATE offset_machines SET name = ?, max_width_mm = ?, max_height_mm = ?, plate_price = ?, setup_cost = ?, step_cost = ?, default_waste_sheets = ?, gripper_margin_mm = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? `); stmt.run( body.name, body.maxWidthMm, body.maxHeightMm, body.platePrice, body.setupCost, body.stepCost, body.defaultWasteSheets, body.gripperMarginMm || 10, body.id ); } else if (body.type === 'digital') { const stmt = db.prepare(` UPDATE digital_machines SET name = ?, max_width_mm = ?, max_height_mm = ?, click_a4_1side = ?, click_a4_2side = ?, click_a3_1side = ?, click_a3_2side = ?, default_waste_sheets = ?, min_charge = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? `); stmt.run( body.name, body.maxWidthMm, body.maxHeightMm, body.clickA41Side, body.clickA42Side, body.clickA31Side, body.clickA32Side, body.defaultWasteSheets, body.minCharge, body.id ); }
return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { OrderStatus, ProductType, QuoteOrder } from '@/types';
export async function GET(req: NextRequest) { try { const db = getDb(); const { searchParams } = new URL(req.url); const status = searchParams.get('status'); const search = searchParams.get('search');
let query = 'SELECT * FROM quotes_orders WHERE 1=1'; const params: unknown[] = [];
if (status && status !== 'all') { query += ' AND status = ?'; params.push(status); }
if (search) { query += ' AND (code LIKE ? OR customer_name LIKE ? OR customer_phone LIKE ? OR job_name LIKE ?)'; const term = `%${search}%`; params.push(term, term, term, term); }
query += ' ORDER BY id DESC';
const rows = db.prepare(query).all(...params) as Record<string, unknown>[]; const orders: QuoteOrder[] = rows.map((r) => mapOrder(r));
return NextResponse.json(orders); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function POST(req: NextRequest) { try { const body = await req.json(); const db = getDb();
// Sinh mã đơn hàng tự động: PC-YYYYMM-XXX const now = new Date(); const yearMonth = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}`; const countRow = db.prepare('SELECT COUNT(*) as count FROM quotes_orders WHERE code LIKE ?').get(`PC-${yearMonth}-%`) as { count: number }; const nextNum = String(countRow.count + 1).padStart(3, '0'); const code = body.code || `PC-${yearMonth}-${nextNum}`;
// Tự động thêm hoặc cập nhật khách hàng let customerId = body.customerId; if (!customerId && body.customerPhone) { const existingCust = db.prepare('SELECT id FROM customers WHERE phone = ?').get(body.customerPhone) as { id: number } | undefined; if (existingCust) { customerId = existingCust.id; } else if (body.customerName) { const custResult = db.prepare(` INSERT INTO customers (name, phone, email, company) VALUES (?, ?, ?, ?) `).run(body.customerName, body.customerPhone, body.customerEmail || '', body.customerCompany || ''); customerId = Number(custResult.lastInsertRowid); } }
const stmt = db.prepare(` INSERT INTO quotes_orders ( code, customer_id, customer_name, customer_phone, customer_email, customer_company, job_name, product_type, print_tech, quantity, width_mm, height_mm, pages, paper_name, paper_gsm, parent_size, print_size, ups_per_sheet, total_print_sheets, total_parent_sheets, paper_cost, print_cost, finishing_cost, total_cost, profit_margin_percent, profit_amount, discount_amount, vat_percent, vat_amount, final_price, unit_price, status, notes, spec_json ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) `);
const result = stmt.run( code, customerId || null, body.customerName || 'Khách vãng lai', body.customerPhone || '', body.customerEmail || '', body.customerCompany || '', body.jobName || 'In ấn phẩm', body.productType || 'to_roi', body.printTech || 'offset', body.quantity, body.widthMm, body.heightMm, body.pages || 2, body.paperName, body.paperGsm, body.parentSize || '', body.printSize || '', body.upsPerSheet || 1, body.totalPrintSheets || 0, body.totalParentSheets || 0, body.paperCost || 0, body.printCost || 0, body.finishingCost || 0, body.totalCost || 0, body.profitMarginPercent || 25, body.profitAmount || 0, body.discountAmount || 0, body.vatPercent || 0, body.vatAmount || 0, body.finalPrice || 0, body.unitPrice || 0, body.status || 'quote', body.notes || '', body.specJson ? JSON.stringify(body.specJson) : null );
return NextResponse.json({ success: true, id: Number(result.lastInsertRowid), code }); } catch (err: unknown) { console.error('Order save error:', err); return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function PUT(req: NextRequest) { try { const body = await req.json(); const db = getDb();
if (body.action === 'status') { db.prepare(` UPDATE quotes_orders SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? `).run(body.status, body.id); } else { db.prepare(` UPDATE quotes_orders SET customer_name = ?, customer_phone = ?, customer_email = ?, customer_company = ?, job_name = ?, status = ?, notes = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? `).run( body.customerName, body.customerPhone, body.customerEmail || '', body.customerCompany || '', body.jobName, body.status, body.notes || '', body.id ); }
return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function DELETE(req: NextRequest) { try { const { searchParams } = new URL(req.url); const id = searchParams.get('id'); if (!id) return NextResponse.json({ error: 'Thiếu ID đơn hàng' }, { status: 400 });
const db = getDb(); db.prepare('DELETE FROM quotes_orders WHERE id = ?').run(Number(id)); return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
function mapOrder(r: Record<string, unknown>): QuoteOrder { return { id: r.id as number, code: r.code as string, customerId: r.customer_id as number | undefined, customerName: r.customer_name as string, customerPhone: r.customer_phone as string, customerEmail: (r.customer_email as string) || '', customerCompany: (r.customer_company as string) || '', jobName: r.job_name as string, productType: r.product_type as ProductType, printTech: r.print_tech as 'offset' | 'digital', quantity: r.quantity as number, widthMm: r.width_mm as number, heightMm: r.height_mm as number, pages: r.pages as number, paperName: r.paper_name as string, paperGsm: r.paper_gsm as number, parentSize: r.parent_size as string, printSize: r.print_size as string, upsPerSheet: r.ups_per_sheet as number, totalPrintSheets: r.total_print_sheets as number, totalParentSheets: r.total_parent_sheets as number, paperCost: r.paper_cost as number, printCost: r.print_cost as number, finishingCost: r.finishing_cost as number, totalCost: r.total_cost as number, profitMarginPercent: r.profit_margin_percent as number, profitAmount: r.profit_amount as number, discountAmount: r.discount_amount as number, vatPercent: r.vat_percent as number, vatAmount: r.vat_amount as number, finalPrice: r.final_price as number, unitPrice: r.unit_price as number, status: r.status as OrderStatus, notes: (r.notes as string) || '', specJson: (r.spec_json as string) || '', createdAt: r.created_at as string, updatedAt: r.updated_at as string, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { PaperType } from '@/types';
export async function GET() { try { const db = getDb(); const rows = db.prepare('SELECT * FROM paper_types ORDER BY is_active DESC, name ASC, gsm ASC').all() as Record<string, unknown>[]; const papers: PaperType[] = rows.map((r) => ({ id: r.id as number, code: r.code as string, name: r.name as string, gsm: r.gsm as number, parentWidthCm: r.parent_width_cm as number, parentHeightCm: r.parent_height_cm as number, pricePerRam: r.price_per_ram as number, pricePerKg: r.price_per_kg as number, unit: r.unit as 'ram' | 'kg', description: (r.description as string) || '', isActive: Boolean(r.is_active), })); return NextResponse.json(papers); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function POST(req: NextRequest) { try { const body = await req.json(); const db = getDb();
const stmt = db.prepare(` INSERT INTO paper_types (code, name, gsm, parent_width_cm, parent_height_cm, price_per_ram, price_per_kg, unit, description, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `);
const result = stmt.run( body.code, body.name, body.gsm, body.parentWidthCm, body.parentHeightCm, body.pricePerRam, body.pricePerKg || 0, body.unit || 'ram', body.description || '', body.isActive !== false ? 1 : 0 );
return NextResponse.json({ success: true, id: Number(result.lastInsertRowid) }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function PUT(req: NextRequest) { try { const body = await req.json(); const db = getDb();
const stmt = db.prepare(` UPDATE paper_types SET name = ?, gsm = ?, parent_width_cm = ?, parent_height_cm = ?, price_per_ram = ?, price_per_kg = ?, unit = ?, description = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? `);
stmt.run( body.name, body.gsm, body.parentWidthCm, body.parentHeightCm, body.pricePerRam, body.pricePerKg || 0, body.unit || 'ram', body.description || '', body.isActive ? 1 : 0, body.id );
return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function DELETE(req: NextRequest) { try { const { searchParams } = new URL(req.url); const id = searchParams.get('id'); if (!id) return NextResponse.json({ error: 'Thiếu ID giấy' }, { status: 400 });
const db = getDb(); db.prepare('DELETE FROM paper_types WHERE id = ?').run(Number(id)); return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { SystemSetting } from '@/types';
export async function GET() { try { const db = getDb(); const rows = db.prepare('SELECT key, value FROM system_settings').all() as { key: string; value: string }[]; const map: Record<string, string> = {}; for (const r of rows) { map[r.key] = r.value; }
const settings: SystemSetting = { companyName: map.companyName || 'XƯỞNG IN ẤN PRINTCAL', companyAddress: map.companyAddress || '', companyPhone: map.companyPhone || '', companyEmail: map.companyEmail || '', bankAccount: map.bankAccount || '', bankName: map.bankName || '', quoteFooterNote: map.quoteFooterNote || '', defaultProfitMargin: Number(map.defaultProfitMargin) || 25, defaultVatPercent: Number(map.defaultVatPercent) || 8, };
return NextResponse.json(settings); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}
export async function PUT(req: NextRequest) { try { const body = (await req.json()) as Partial<SystemSetting>; const db = getDb();
const upsert = db.prepare(` INSERT INTO system_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value `);
if (body.companyName !== undefined) upsert.run('companyName', body.companyName); if (body.companyAddress !== undefined) upsert.run('companyAddress', body.companyAddress); if (body.companyPhone !== undefined) upsert.run('companyPhone', body.companyPhone); if (body.companyEmail !== undefined) upsert.run('companyEmail', body.companyEmail); if (body.bankAccount !== undefined) upsert.run('bankAccount', body.bankAccount); if (body.bankName !== undefined) upsert.run('bankName', body.bankName); if (body.quoteFooterNote !== undefined) upsert.run('quoteFooterNote', body.quoteFooterNote); if (body.defaultProfitMargin !== undefined) upsert.run('defaultProfitMargin', String(body.defaultProfitMargin)); if (body.defaultVatPercent !== undefined) upsert.run('defaultVatPercent', String(body.defaultVatPercent));
return NextResponse.json({ success: true }); } catch (err: unknown) { return NextResponse.json({ error: (err as Error).message }, { status: 500 }); }}12 unmodified lines131415161718192021222324252612 unmodified lines});export const metadata: Metadata = {title: "Create Next App",description: "Generated by create next app",};export default function RootLayout({ children }: LayoutProps<"/">) {return (<htmllang="en"className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}><body className="min-h-full flex flex-col">{children}</body>12 unmodified lines131415161718192021222324252612 unmodified lines});export const metadata: Metadata = {title: "PrintCal - Công Cụ Tính Giá In Offset & In Nhanh Thông Minh",description: "Phần mềm tính giá in ấn, quản lý kho giá giấy, máy in, gia công thành phẩm và đơn hàng",};export default function RootLayout({ children }: { children: React.ReactNode }) {return (<htmllang="vi"className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}><body className="min-h-full flex flex-col">{children}</body>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import Image from "next/image";export default function Home() {return (<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black"><main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start"><ImageclassName="dark:invert h-5 w-[100px]"src="/next.svg"alt="Next.js logo"width={100}height={20}priority/><div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left"><h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">To get started, edit the{" "}<code className="rounded bg-black/[.06] px-1.5 py-0.5 font-mono text-[0.9em] dark:bg-white/[.08]">page.tsx</code>{" "}file.</h1><p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">Looking for a starting point or more instructions? Head over to{" "}<ahref="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"className="font-medium text-zinc-950 dark:text-zinc-50">Templates</a>{" "}or the{" "}<ahref="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"className="font-medium text-zinc-950 dark:text-zinc-50">Learning</a>{" "}center.</p></div><div className="flex flex-col gap-4 text-base font-medium sm:flex-row"><aclassName="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"target="_blank"rel="noopener noreferrer"><ImageclassName="dark:invert h-[14px] w-4"src="/vercel.svg"alt="Vercel logomark"width={16}height={14}/>Deploy Now</a><aclassName="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"target="_blank"rel="noopener noreferrer">Documentation</a></div></main></div>);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845'use client';import React, { useState, useEffect, useMemo, useCallback } from 'react';import { Navbar, ActiveTab } from '@/components/Navbar';import { ImpositionVisualizer } from '@/components/ImpositionVisualizer';import { BreakEvenChart } from '@/components/BreakEvenChart';import { CostBreakdownCard } from '@/components/CostBreakdownCard';import { QuotePrintModal } from '@/components/QuotePrintModal';import { OrdersManager } from '@/components/OrdersManager';import { PaperManager } from '@/components/PaperManager';import { MachineManager } from '@/components/MachineManager';import { FinishingManager } from '@/components/FinishingManager';import { CustomerManager } from '@/components/CustomerManager';import { SettingsManager } from '@/components/SettingsManager';import {CalculationInput,CalculationResult,DigitalMachine,FinishingService,OffsetMachine,PaperType,ProductType,PrintTech,OffsetWorkType,SystemSetting,} from '@/types';import {Calculator,Layers,Sparkles,Zap,Scissors,Check,ChevronRight,RefreshCw,Sliders,DollarSign,FileSpreadsheet,} from 'lucide-react';export default function HomePage() {const [activeTab, setActiveTab] = useState<ActiveTab>('calculator');// Master Dataconst [papers, setPapers] = useState<PaperType[]>([]);const [offsetMachines, setOffsetMachines] = useState<OffsetMachine[]>([]);const [digitalMachines, setDigitalMachines] = useState<DigitalMachine[]>([]);const [finishingServices, setFinishingServices] = useState<FinishingService[]>([]);const [settings, setSettings] = useState<SystemSetting | undefined>();const [orderCount, setOrderCount] = useState(0);// Form Inputsconst [jobName, setJobName] = useState('In Tờ Rơi A4 Quảng Cáo');const [productType, setProductType] = useState<ProductType>('to_roi');const [printTech, setPrintTech] = useState<PrintTech>('auto');const [quantity, setQuantity] = useState(1000);const [widthMm, setWidthMm] = useState(210);const [heightMm, setHeightMm] = useState(297);const [bleedMm, setBleedMm] = useState(2);const [paperTypeId, setPaperTypeId] = useState<number>(0);const [printSides, setPrintSides] = useState<'1_side' | '2_side'>('2_side');const [colorsFront, setColorsFront] = useState(4);const [colorsBack, setColorsBack] = useState(4);const [offsetWorkType, setOffsetWorkType] = useState<OffsetWorkType>('self_turn');const [selectedFinishing, setSelectedFinishing] = useState<{ serviceId: number; sides?: number }[]>([{ serviceId: 1, sides: 2 }, // Cán màng mờ 2 mặt mặc định]);const [profitMarginPercent, setProfitMarginPercent] = useState(25);const [discountAmount, setDiscountAmount] = useState(0);const [vatPercent, setVatPercent] = useState(8);// Customer Info for Order / Quoteconst [customerName, setCustomerName] = useState('Công ty Khách Hàng');const [customerPhone, setCustomerPhone] = useState('0912345678');// Calculation Resultconst [result, setResult] = useState<CalculationResult | null>(null);const [calculating, setCalculating] = useState(false);const [isSavingOrder, setIsSavingOrder] = useState(false);const [isPrintModalOpen, setIsPrintModalOpen] = useState(false);const [currentQuoteCode, setCurrentQuoteCode] = useState(`BG-${Date.now().toString().slice(-6)}`);// Tải dữ liệu ban đầuconst loadMasterData = async () => {try {const [pRes, mRes, fRes, sRes, oRes] = await Promise.all([fetch('/api/papers').then((r) => r.json()),fetch('/api/machines').then((r) => r.json()),fetch('/api/finishing').then((r) => r.json()),fetch('/api/settings').then((r) => r.json()),fetch('/api/orders').then((r) => r.json()),]);if (Array.isArray(pRes)) {setPapers(pRes);if (pRes.length > 0 && paperTypeId === 0) {// Mặc định chọn Couche 150gsmconst defaultPaper = pRes.find((p) => p.code.includes('C150')) || pRes[0];setPaperTypeId(defaultPaper.id);}}if (mRes.offsetMachines) setOffsetMachines(mRes.offsetMachines);if (mRes.digitalMachines) setDigitalMachines(mRes.digitalMachines);if (Array.isArray(fRes)) setFinishingServices(fRes);if (sRes.companyName) {setSettings(sRes);if (sRes.defaultProfitMargin) setProfitMarginPercent(sRes.defaultProfitMargin);if (sRes.defaultVatPercent) setVatPercent(sRes.defaultVatPercent);}if (Array.isArray(oRes)) setOrderCount(oRes.length);} catch (err) {console.error('Failed to load initial data:', err);}};useEffect(() => {loadMasterData();}, []);// Tính toán chi phí mỗi khi tham số thay đổiconst triggerCalculation = useCallback(async () => {if (!paperTypeId || paperTypeId === 0) return;try {setCalculating(true);const payload: CalculationInput = {jobName,productType,printTech,quantity: Number(quantity) || 1,widthMm: Number(widthMm) || 210,heightMm: Number(heightMm) || 297,bleedMm: Number(bleedMm) || 2,paperTypeId,printSides,colorsFront: Number(colorsFront) || 4,colorsBack: printSides === '2_side' ? (Number(colorsBack) || 4) : 0,offsetWorkType,selectedFinishing,profitMarginPercent: Number(profitMarginPercent) || 0,discountAmount: Number(discountAmount) || 0,vatPercent: Number(vatPercent) || 0,};const res = await fetch('/api/calculate', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(payload),});if (res.ok) {const data = await res.json();setResult(data);}} catch (err) {console.error('Calculation error:', err);} finally {setCalculating(false);}}, [jobName,productType,printTech,quantity,widthMm,heightMm,bleedMm,paperTypeId,printSides,colorsFront,colorsBack,offsetWorkType,selectedFinishing,profitMarginPercent,discountAmount,vatPercent,]);useEffect(() => {if (paperTypeId > 0) {triggerCalculation();}}, [triggerCalculation, paperTypeId]);// Áp dụng Preset mẫu ấn phẩm phổ biếnconst applyPreset = (type: string) => {switch (type) {case 'a4_flyer':setJobName('Tờ Rơi A4 Quảng Cáo');setProductType('to_roi');setWidthMm(210);setHeightMm(297);setQuantity(1000);setPrintSides('2_side');setSelectedFinishing([]);const c150 = papers.find((p) => p.code.includes('C150'));if (c150) setPaperTypeId(c150.id);break;case 'a5_flyer':setJobName('Tờ Rơi A5 Sự Kiện');setProductType('to_roi');setWidthMm(148);setHeightMm(210);setQuantity(2000);setPrintSides('2_side');setSelectedFinishing([]);const c150_a5 = papers.find((p) => p.code.includes('C150'));if (c150_a5) setPaperTypeId(c150_a5.id);break;case 'namecard':setJobName('Danh Thiếp / Namecard 2 Mặt');setProductType('namecard');setWidthMm(90);setHeightMm(54);setQuantity(500);setPrintSides('2_side');const c300 = papers.find((p) => p.code.includes('C300') || p.code.includes('B300'));if (c300) setPaperTypeId(c300.id);const lamination = finishingServices.find((f) => f.category === 'can_mang');if (lamination) setSelectedFinishing([{ serviceId: lamination.id, sides: 2 }]);break;case 'cosmetic_box':setJobName('Hộp Mỹ Phẩm Cao Cấp');setProductType('hop_giay');setWidthMm(240);setHeightMm(320); // Khổ trải mở phẳng hộpsetQuantity(1000);setPrintSides('1_side');const ivory = papers.find((p) => p.code.includes('I350') || p.code.includes('I300'));if (ivory) setPaperTypeId(ivory.id);const dieCut = finishingServices.find((f) => f.calcType === 'die_cut');const lam = finishingServices.find((f) => f.category === 'can_mang');const glue = finishingServices.find((f) => f.category === 'dan');const boxFinishing = [];if (lam) boxFinishing.push({ serviceId: lam.id, sides: 1 });if (dieCut) boxFinishing.push({ serviceId: dieCut.id });if (glue) boxFinishing.push({ serviceId: glue.id });setSelectedFinishing(boxFinishing);break;case 'paper_bag':setJobName('Túi Giấy Kraft Shop');setProductType('tui_giay');setWidthMm(420);setHeightMm(310);setQuantity(1000);setPrintSides('1_side');const kraft = papers.find((p) => p.code.includes('K250') || p.code.includes('K170'));if (kraft) setPaperTypeId(kraft.id);const bagDie = finishingServices.find((f) => f.calcType === 'die_cut');const bagGlue = finishingServices.find((f) => f.code.includes('DAN_DAY_TUI'));const bagFinishing = [];if (bagDie) bagFinishing.push({ serviceId: bagDie.id });if (bagGlue) bagFinishing.push({ serviceId: bagGlue.id });setSelectedFinishing(bagFinishing);break;case 'sticker':setJobName('Decal Tem Nhãn Tròn Dán Ly');setProductType('decal');setWidthMm(50);setHeightMm(50);setQuantity(2000);setPrintSides('1_side');const decal = papers.find((p) => p.code.includes('DECAL'));if (decal) setPaperTypeId(decal.id);const demi = finishingServices.find((f) => f.code.includes('BE_DEMI'));if (demi) setSelectedFinishing([{ serviceId: demi.id }]);break;case 'brochure':setJobName('Brochure Gấp 3 Giới Thiệu');setProductType('to_roi');setWidthMm(297);setHeightMm(210);setQuantity(1500);setPrintSides('2_side');const c200 = papers.find((p) => p.code.includes('C200'));if (c200) setPaperTypeId(c200.id);const crease = finishingServices.find((f) => f.code.includes('CAN_GAP_2_DUONG'));const mờ = finishingServices.find((f) => f.category === 'can_mang');const broFin = [];if (mờ) broFin.push({ serviceId: mờ.id, sides: 2 });if (crease) broFin.push({ serviceId: crease.id });setSelectedFinishing(broFin);break;}};// Toggle dịch vụ gia côngconst toggleFinishing = (serviceId: number) => {setSelectedFinishing((prev) => {const exists = prev.find((f) => f.serviceId === serviceId);if (exists) {return prev.filter((f) => f.serviceId !== serviceId);} else {return [...prev, { serviceId, sides: 1 }];}});};const updateFinishingSides = (serviceId: number, sides: number) => {setSelectedFinishing((prev) =>prev.map((f) => (f.serviceId === serviceId ? { ...f, sides } : f)));};// Lưu đơn hàng vào CSDLconst handleSaveOrder = async () => {if (!result) return;try {setIsSavingOrder(true);const selectedPaper = papers.find((p) => p.id === paperTypeId);const orderPayload = {customerName: customerName || 'Khách vãng lai',customerPhone: customerPhone || '',jobName,productType,printTech: result.chosenTech,quantity: result.quantities.productQty,widthMm,heightMm,pages: printSides === '2_side' ? 2 : 1,paperName: selectedPaper?.name || 'Giấy in',paperGsm: selectedPaper?.gsm || 150,parentSize: result.imposition.parentSheet.name,printSize: result.imposition.printSheet.name,upsPerSheet: result.imposition.upsPerPrintSheet,totalPrintSheets: result.quantities.totalPrintSheets,totalParentSheets: result.quantities.parentSheetsNeeded,paperCost: result.costs.paperCost,printCost: result.costs.totalPrintCost,finishingCost: result.costs.finishingCost,totalCost: result.costs.totalBaseCost,profitMarginPercent,profitAmount: result.costs.profitAmount,discountAmount,vatPercent,vatAmount: result.costs.vatAmount,finalPrice: result.costs.finalPrice,unitPrice: result.costs.unitPrice,status: 'quote',notes: `Tận dụng giấy: ${result.imposition.sheetEfficiencyPercent}%. Số tờ bù hao: ${result.quantities.printWasteSheets + result.quantities.finishingWasteSheets}`,};const res = await fetch('/api/orders', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(orderPayload),});if (res.ok) {const data = await res.json();setCurrentQuoteCode(data.code);setOrderCount((prev) => prev + 1);alert(`Đã lưu đơn hàng thành công! Mã đơn: ${data.code}`);}} catch (err) {console.error('Save order error:', err);} finally {setIsSavingOrder(false);}};const selectedPaper = useMemo(() => {return papers.find((p) => p.id === paperTypeId) || papers[0];}, [papers, paperTypeId]);return (<div className="min-h-screen bg-slate-100 flex flex-col font-sans">{/* Navbar điều hướng */}<Navbar activeTab={activeTab} setActiveTab={setActiveTab} orderCount={orderCount} />{/* Main Container */}<main className="flex-1 max-w-7xl w-full mx-auto p-4 sm:p-6 space-y-6">{/* PHÂN HỆ 1: MÁY TÍNH GIÁ THÔNG MINH */}{activeTab === 'calculator' && (<div className="space-y-5">{/* Thanh Presets Mẫu Ấn Phẩm */}<div className="bg-white p-3.5 rounded-xl border border-slate-200 shadow-xs flex items-center justify-between gap-2 overflow-x-auto no-scrollbar"><span className="text-xs font-bold text-slate-700 uppercase tracking-wider shrink-0 flex items-center gap-1.5 pl-1"><Sparkles className="w-3.5 h-3.5 text-blue-600" /> Mẫu Nhanh:</span><div className="flex items-center gap-2 text-xs"><buttononClick={() => applyPreset('a4_flyer')}className="px-3 py-1.5 rounded-lg border border-slate-200 hover:border-blue-500 hover:bg-blue-50/60 font-medium text-slate-700 transition-colors whitespace-nowrap">📄 Tờ Rơi A4</button><buttononClick={() => applyPreset('a5_flyer')}className="px-3 py-1.5 rounded-lg border border-slate-200 hover:border-blue-500 hover:bg-blue-50/60 font-medium text-slate-700 transition-colors whitespace-nowrap">📄 Tờ Rơi A5</button><buttononClick={() => applyPreset('namecard')}className="px-3 py-1.5 rounded-lg border border-slate-200 hover:border-blue-500 hover:bg-blue-50/60 font-medium text-slate-700 transition-colors whitespace-nowrap">💳 Namecard</button><buttononClick={() => applyPreset('brochure')}className="px-3 py-1.5 rounded-lg border border-slate-200 hover:border-blue-500 hover:bg-blue-50/60 font-medium text-slate-700 transition-colors whitespace-nowrap">📖 Brochure Gấp 3</button><buttononClick={() => applyPreset('cosmetic_box')}className="px-3 py-1.5 rounded-lg border border-slate-200 hover:border-blue-500 hover:bg-blue-50/60 font-medium text-slate-700 transition-colors whitespace-nowrap">📦 Hộp Mỹ Phẩm</button><buttononClick={() => applyPreset('paper_bag')}className="px-3 py-1.5 rounded-lg border border-slate-200 hover:border-blue-500 hover:bg-blue-50/60 font-medium text-slate-700 transition-colors whitespace-nowrap">🛍️ Túi Giấy Kraft</button><buttononClick={() => applyPreset('sticker')}className="px-3 py-1.5 rounded-lg border border-slate-200 hover:border-blue-500 hover:bg-blue-50/60 font-medium text-slate-700 transition-colors whitespace-nowrap">🏷️ Decal Tem Nhãn</button></div></div>{/* Khung Tính Giá 3 Cột: Form Nhập -> Kết Quả Trực Quan 2D & Chart -> Tóm Tắt Giá Bán */}<div className="grid grid-cols-1 lg:grid-cols-12 gap-5 items-start">{/* CỘT 1: FORM THÔNG SỐ SẢN PHẨM & CẤU HÌNH (4 CỘT) */}<div className="lg:col-span-5 bg-white rounded-2xl border border-slate-200 shadow-xs p-5 space-y-4"><div className="flex items-center justify-between pb-3 border-b border-slate-100"><div className="flex items-center gap-2"><div className="p-1.5 bg-blue-50 text-blue-600 rounded-lg"><Calculator className="w-5 h-5" /></div><div><h2 className="font-bold text-slate-900 text-sm md:text-base">Thông Số Ấn Phẩm</h2><p className="text-[11px] text-slate-500">Nhập quy cách sản phẩm để tính toán tức thì</p></div></div><buttononClick={triggerCalculation}className="p-1.5 text-slate-400 hover:text-blue-600 rounded-lg hover:bg-slate-100"title="Tính lại"><RefreshCw className={`w-4 h-4 ${calculating ? 'animate-spin text-blue-600' : ''}`} /></button></div>{/* Tên bài in & Phân loại */}<div className="space-y-3 text-xs"><div><label className="block text-slate-700 font-semibold mb-1">Tên Ấn Phẩm / Bài In</label><inputtype="text"value={jobName}onChange={(e) => setJobName(e.target.value)}className="w-full border border-slate-300 rounded-lg p-2 font-medium focus:ring-2 focus:ring-blue-500 focus:border-blue-500"/></div><div className="grid grid-cols-2 gap-3"><div><label className="block text-slate-700 font-semibold mb-1">Phân Loại Ấn Phẩm</label><selectvalue={productType}onChange={(e) => setProductType(e.target.value as ProductType)}className="w-full border border-slate-300 rounded-lg p-2 bg-white"><option value="to_roi">Tờ Rơi / Flyer</option><option value="namecard">Danh Thiếp / Card</option><option value="hop_giay">Hộp Giấy Bao Bì</option><option value="tui_giay">Túi Giấy Xách</option><option value="decal">Decal / Tem Nhãn</option><option value="catalogue">Catalogue / Sách</option><option value="khac">Khác</option></select></div><div><label className="block text-slate-700 font-semibold mb-1">Công Nghệ In Đề Xuất</label><selectvalue={printTech}onChange={(e) => setPrintTech(e.target.value as PrintTech)}className="w-full border border-slate-300 rounded-lg p-2 bg-white font-semibold text-blue-700"><option value="auto">✨ Tự Động So Sánh & Chọn Rẻ Nhất</option><option value="offset">In Offset Công Nghiệp</option><option value="digital">In Nhanh Kỹ Thuật Số (Click)</option></select></div></div>{/* Kích thước & Số lượng */}<div className="p-3 bg-slate-50 rounded-xl border border-slate-200/80 space-y-2.5"><div className="grid grid-cols-3 gap-2"><div><label className="block text-slate-600 font-medium mb-1">Rộng (mm)</label><inputtype="number"value={widthMm}onChange={(e) => setWidthMm(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-2 font-bold text-slate-800"/></div><div><label className="block text-slate-600 font-medium mb-1">Dài (mm)</label><inputtype="number"value={heightMm}onChange={(e) => setHeightMm(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-2 font-bold text-slate-800"/></div><div><label className="block text-slate-600 font-medium mb-1">Tràn Lề (mm)</label><inputtype="number"value={bleedMm}onChange={(e) => setBleedMm(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-2 text-slate-700"/></div></div><div><label className="block text-slate-700 font-semibold mb-1 flex items-center justify-between"><span>Số Lượng Thành Phẩm:</span><strong className="text-blue-700 text-sm">{quantity.toLocaleString('vi-VN')} chiếc</strong></label><inputtype="number"step="50"value={quantity}onChange={(e) => setQuantity(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-2 font-black text-slate-900 text-base"/></div></div>{/* Loại giấy in */}<div><label className="block text-slate-700 font-semibold mb-1">Chất Liệu Giấy In</label><selectvalue={paperTypeId}onChange={(e) => setPaperTypeId(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-2.5 bg-white font-medium text-slate-900">{papers.map((p) => (<option key={p.id} value={p.id}>{p.name} ({p.parentWidthCm}x{p.parentHeightCm}cm) - {p.pricePerRam > 0 ? `${p.pricePerRam.toLocaleString('vi-VN')}đ/ram` : `${p.pricePerKg.toLocaleString('vi-VN')}đ/kg`}</option>))}</select></div>{/* Mặt in & Kiểu trở kẽm Offset */}<div className="grid grid-cols-2 gap-3"><div><label className="block text-slate-700 font-semibold mb-1">Số Mặt In</label><selectvalue={printSides}onChange={(e) => setPrintSides(e.target.value as '1_side' | '2_side')}className="w-full border border-slate-300 rounded-lg p-2 bg-white font-medium"><option value="1_side">In 1 Mặt</option><option value="2_side">In 2 Mặt</option></select></div>{printSides === '2_side' ? (<div><label className="block text-slate-700 font-semibold mb-1">Kiểu Trở Kẽm (Offset)</label><selectvalue={offsetWorkType}onChange={(e) => setOffsetWorkType(e.target.value as OffsetWorkType)}className="w-full border border-slate-300 rounded-lg p-2 bg-white"><option value="self_turn">Tự Trở (1 bộ kẽm)</option><option value="sheetwise">In 2 Bài (2 bộ kẽm riêng)</option><option value="tumble">Trở Nhíp</option></select></div>) : (<div><label className="block text-slate-700 font-semibold mb-1">Số Màu CMYK</label><selectvalue={colorsFront}onChange={(e) => setColorsFront(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-2 bg-white"><option value={4}>4 Màu Chuẩn (CMYK)</option><option value={1}>1 Màu (Đen/Pha)</option></select></div>)}</div>{/* Danh mục gia công sau in */}<div className="space-y-2 pt-2 border-t border-slate-200"><label className="block text-slate-800 font-bold flex items-center justify-between"><span className="flex items-center gap-1.5"><Scissors className="w-3.5 h-3.5 text-blue-600" /> Gia Công Sau In:</span><span className="text-[11px] font-normal text-slate-500">({selectedFinishing.length} khâu đã chọn)</span></label><div className="max-h-48 overflow-y-auto space-y-1.5 pr-1 no-scrollbar">{finishingServices.map((service) => {const selected = selectedFinishing.find((f) => f.serviceId === service.id);return (<divkey={service.id}onClick={() => toggleFinishing(service.id)}className={`p-2 rounded-lg border text-xs cursor-pointer flex items-center justify-between transition-all ${selected? 'bg-blue-50/80 border-blue-400 text-blue-900 font-semibold': 'bg-white border-slate-200 hover:border-slate-300 text-slate-700'}`}><div className="flex items-center gap-2"><divclassName={`w-4 h-4 rounded flex items-center justify-center border ${selected ? 'bg-blue-600 border-blue-600 text-white' : 'border-slate-300 bg-white'}`}>{selected && <Check className="w-3 h-3" />}</div><span>{service.name}</span></div><div className="flex items-center gap-2"><span className="text-slate-500 text-[11px]">{service.unitPrice.toLocaleString('vi-VN')}đ</span>{/* Tùy chọn 1 mặt / 2 mặt nếu là cán màng */}{selected && service.category === 'can_mang' && (<divonClick={(e) => e.stopPropagation()}className="flex items-center gap-1 bg-white border border-blue-200 rounded px-1.5 py-0.5"><buttontype="button"onClick={() => updateFinishingSides(service.id, 1)}className={`px-1 rounded text-[10px] ${selected.sides === 1 ? 'bg-blue-600 text-white font-bold' : 'text-slate-600'}`}>1 mặt</button><buttontype="button"onClick={() => updateFinishingSides(service.id, 2)}className={`px-1 rounded text-[10px] ${selected.sides === 2 ? 'bg-blue-600 text-white font-bold' : 'text-slate-600'}`}>2 mặt</button></div>)}</div></div>);})}</div></div>{/* Lợi nhuận & Chiết khấu & Thuế */}<div className="pt-2 border-t border-slate-200 grid grid-cols-3 gap-2"><div><label className="block text-slate-600 font-medium mb-1">Lợi Nhuận (%)</label><inputtype="number"value={profitMarginPercent}onChange={(e) => setProfitMarginPercent(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-1.5 text-center font-bold text-emerald-700"/></div><div><label className="block text-slate-600 font-medium mb-1">Giảm Giá (đ)</label><inputtype="number"value={discountAmount}onChange={(e) => setDiscountAmount(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-1.5 text-center text-rose-600"/></div><div><label className="block text-slate-600 font-medium mb-1">VAT (%)</label><inputtype="number"value={vatPercent}onChange={(e) => setVatPercent(Number(e.target.value))}className="w-full border border-slate-300 rounded-lg p-1.5 text-center"/></div></div>{/* Thông tin khách hàng nhanh */}<div className="pt-2 border-t border-slate-200 grid grid-cols-2 gap-2"><div><label className="block text-slate-600 font-medium mb-1">Tên Khách Hàng</label><inputtype="text"value={customerName}onChange={(e) => setCustomerName(e.target.value)}placeholder="Anh/Chị..."className="w-full border border-slate-300 rounded-lg p-1.5"/></div><div><label className="block text-slate-600 font-medium mb-1">Số Điện Thoại</label><inputtype="tel"value={customerPhone}onChange={(e) => setCustomerPhone(e.target.value)}placeholder="090..."className="w-full border border-slate-300 rounded-lg p-1.5"/></div></div></div></div>{/* CỘT 2: TRỰC QUAN HÓA 2D & SO SÁNH HÒA VỐN (4 CỘT) */}<div className="lg:col-span-4 space-y-4">{result && (<>{/* Bản vẽ 2D Mô phỏng cắt khổ giấy */}<ImpositionVisualizerimposition={result.imposition}productName={jobName}productWidthMm={widthMm}productHeightMm={heightMm}/>{/* Biểu đồ so sánh In Nhanh vs Offset */}<BreakEvenChartcurrentQty={quantity}chosenTech={result.chosenTech}comparisonTable={result.recommendation?.comparisonTable}breakEvenQty={result.recommendation?.breakEvenQty}reason={result.recommendation?.reason}/></>)}</div>{/* CỘT 3: TỔNG HỢP CHI PHÍ & GIÁ BÁN & IN BÁO GIÁ (3 CỘT) */}<div className="lg:col-span-3">{result && selectedPaper && (<CostBreakdownCardinput={{jobName,productType,printTech,quantity,widthMm,heightMm,bleedMm,paperTypeId,printSides,colorsFront,colorsBack,offsetWorkType,selectedFinishing,profitMarginPercent,discountAmount,vatPercent,}}result={result}paperType={selectedPaper}onOpenPrintModal={() => setIsPrintModalOpen(true)}onSaveOrder={handleSaveOrder}isSavingOrder={isSavingOrder}/>)}</div></div></div>)}{/* PHÂN HỆ 2: QUẢN LÝ ĐƠN HÀNG */}{activeTab === 'orders' && <OrdersManager />}{/* PHÂN HỆ 3: QUẢN LÝ GIÁ GIẤY */}{activeTab === 'papers' && <PaperManager />}{/* PHÂN HỆ 4: QUẢN LÝ MÁY IN OFFSET & KTS */}{activeTab === 'machines' && <MachineManager />}{/* PHÂN HỆ 5: QUẢN LÝ DỊCH VỤ GIA CÔNG */}{activeTab === 'finishing' && <FinishingManager />}{/* PHÂN HỆ 6: QUẢN LÝ KHÁCH HÀNG */}{activeTab === 'customers' && <CustomerManager />}{/* PHÂN HỆ 7: CÀI ĐẶT HỆ THỐNG */}{activeTab === 'settings' && <SettingsManager />}</main>{/* Modal In Báo Giá Chuẩn A4 & Lệnh Sản Xuất */}{result && selectedPaper && (<QuotePrintModalisOpen={isPrintModalOpen}onClose={() => setIsPrintModalOpen(false)}input={{jobName,productType,printTech,quantity,widthMm,heightMm,bleedMm,paperTypeId,printSides,colorsFront,colorsBack,offsetWorkType,selectedFinishing,profitMarginPercent,discountAmount,vatPercent,}}result={result}paperType={selectedPaper}settings={settings}quoteCode={currentQuoteCode}customerInfo={{name: customerName,phone: customerPhone,}}/>)}</div>);}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156'use client';
import React from 'react';import { ComparisonItem } from '@/types';import { TrendingUp, Zap, Sparkles, HelpCircle } from 'lucide-react';
interface BreakEvenChartProps { currentQty: number; chosenTech: 'offset' | 'digital'; comparisonTable?: ComparisonItem[]; breakEvenQty?: number; reason?: string;}
export const BreakEvenChart: React.FC<BreakEvenChartProps> = ({ currentQty, chosenTech, comparisonTable = [], breakEvenQty = 300, reason,}) => { if (!comparisonTable || comparisonTable.length === 0) return null;
// Tìm giá trị max để scale chiều cao cột const maxPrice = Math.max(...comparisonTable.map((c) => Math.max(c.digitalTotal, c.offsetTotal)));
return ( <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-4 flex flex-col"> <div className="flex items-center justify-between pb-3 mb-3 border-b border-slate-100"> <div className="flex items-center gap-2"> <div className="p-1.5 bg-purple-50 text-purple-600 rounded-lg"> <TrendingUp className="w-5 h-5" /> </div> <div> <h3 className="font-semibold text-slate-800 text-sm md:text-base">Phân Tích Hòa Vốn & So Sánh Công Nghệ In</h3> <p className="text-xs text-slate-500">In Nhanh KTS (Click) vs In Offset (Kẽm + Công Máy)</p> </div> </div>
<div className="flex items-center gap-2 text-xs"> <span className="flex items-center gap-1 text-sky-600 font-medium"> <span className="w-2.5 h-2.5 rounded-full bg-sky-500 inline-block" /> In Nhanh </span> <span className="flex items-center gap-1 text-indigo-600 font-medium"> <span className="w-2.5 h-2.5 rounded-full bg-indigo-600 inline-block" /> In Offset </span> </div> </div>
{/* Khuyến nghị thông minh */} {reason && ( <div className="mb-4 p-3 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/80 rounded-lg flex items-start gap-2.5"> <Sparkles className="w-4 h-4 text-blue-600 shrink-0 mt-0.5" /> <div className="text-xs text-slate-700 leading-relaxed"> <span className="font-semibold text-blue-900 block mb-0.5">Khuyến Nghị Tối Ưu Chi Phí:</span> {reason} </div> </div> )}
{/* Biểu đồ cột so sánh theo số lượng */} <div className="pt-4 pb-2"> <div className="grid grid-cols-4 sm:grid-cols-8 gap-2 items-end h-[160px] border-b border-slate-200 px-1 pb-1"> {comparisonTable.map((item) => { const digHeight = Math.max(12, Math.round((item.digitalTotal / maxPrice) * 130)); const offHeight = Math.max(12, Math.round((item.offsetTotal / maxPrice) * 130)); const isSelected = item.quantity === currentQty;
return ( <div key={item.quantity} className="flex flex-col items-center gap-1 group relative"> {/* Tooltip khi hover */} <div className="opacity-0 group-hover:opacity-100 transition-opacity absolute -top-12 z-20 bg-slate-900 text-white text-[10px] rounded py-1 px-2 pointer-events-none whitespace-nowrap shadow-lg"> <div>KTS: {item.digitalTotal.toLocaleString('vi-VN')}đ ({item.digitalUnit}đ/c)</div> <div>Offset: {item.offsetTotal.toLocaleString('vi-VN')}đ ({item.offsetUnit}đ/c)</div> </div>
<div className="flex items-end gap-1 w-full justify-center"> {/* Cột In Nhanh */} <div style={{ height: `${digHeight}px` }} className={`w-3.5 sm:w-4 rounded-t transition-all ${ item.recommended === 'digital' ? 'bg-sky-500 shadow-sm' : 'bg-sky-200' }`} /> {/* Cột Offset */} <div style={{ height: `${offHeight}px` }} className={`w-3.5 sm:w-4 rounded-t transition-all ${ item.recommended === 'offset' ? 'bg-indigo-600 shadow-sm' : 'bg-indigo-200' }`} /> </div>
<span className={`text-[11px] font-medium mt-1 ${isSelected ? 'text-blue-600 font-bold' : 'text-slate-500'}`}> {item.quantity >= 1000 ? `${item.quantity / 1000}k` : item.quantity} </span> </div> ); })} </div> </div>
{/* Bảng chi tiết các mốc số lượng */} <div className="overflow-x-auto mt-2"> <table className="w-full text-[11px] text-left"> <thead> <tr className="text-slate-400 border-b border-slate-100 font-medium"> <th className="py-1.5 px-2">Số lượng</th> <th className="py-1.5 px-2 text-right">In Nhanh KTS</th> <th className="py-1.5 px-2 text-right">Đơn giá KTS</th> <th className="py-1.5 px-2 text-right">In Offset</th> <th className="py-1.5 px-2 text-right">Đơn giá Offset</th> <th className="py-1.5 px-2 text-center">Tối ưu</th> </tr> </thead> <tbody className="divide-y divide-slate-50 text-slate-700"> {comparisonTable.map((item) => { const isMatch = item.quantity === currentQty; return ( <tr key={item.quantity} className={`hover:bg-slate-50 transition-colors ${isMatch ? 'bg-blue-50/70 font-semibold text-blue-900' : ''}`} > <td className="py-1.5 px-2 font-medium">{item.quantity.toLocaleString('vi-VN')} con</td> <td className="py-1.5 px-2 text-right">{item.digitalTotal.toLocaleString('vi-VN')}đ</td> <td className="py-1.5 px-2 text-right text-slate-500">{item.digitalUnit.toLocaleString('vi-VN')}đ</td> <td className="py-1.5 px-2 text-right">{item.offsetTotal.toLocaleString('vi-VN')}đ</td> <td className="py-1.5 px-2 text-right text-slate-500">{item.offsetUnit.toLocaleString('vi-VN')}đ</td> <td className="py-1.5 px-2 text-center"> <span className={`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium ${ item.recommended === 'digital' ? 'bg-sky-100 text-sky-700' : 'bg-indigo-100 text-indigo-700' }`} > {item.recommended === 'digital' ? 'In Nhanh' : 'Offset'} </span> </td> </tr> ); })} </tbody> </table> </div>
<div className="mt-3 text-[11px] text-slate-500 flex items-center justify-between border-t border-slate-100 pt-2"> <span className="flex items-center gap-1"> <Zap className="w-3.5 h-3.5 text-amber-500" /> Điểm hòa vốn ước lượng: <strong className="text-slate-800">~{breakEvenQty.toLocaleString('vi-VN')} sản phẩm</strong> </span> <span className="text-slate-400">< {breakEvenQty}: In Nhanh | ≥ {breakEvenQty}: Offset</span> </div> </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211'use client';
import React, { useState } from 'react';import { CalculationInput, CalculationResult, PaperType } from '@/types';import { FileText, Copy, Printer, Save, Check, TrendingUp, Percent, Layers, Sparkles,} from 'lucide-react';
interface CostBreakdownCardProps { input: CalculationInput; result: CalculationResult; paperType: PaperType; onOpenPrintModal: () => void; onSaveOrder: () => void; isSavingOrder?: boolean;}
export const CostBreakdownCard: React.FC<CostBreakdownCardProps> = ({ input, result, paperType, onOpenPrintModal, onSaveOrder, isSavingOrder = false,}) => { const [copied, setCopied] = useState(false);
const { costs, quantities, chosenTech, imposition } = result;
// Sao chép báo giá nhanh gửi Zalo / Tin nhắn const handleCopyZalo = () => { const text = `📢 BÁO GIÁ IN ẤN - ${input.jobName}----------------------------------------- Kích thước: ${input.widthMm} x ${input.heightMm} mm- Số lượng: ${input.quantity.toLocaleString('vi-VN')} chiếc- Chất liệu: ${paperType.name}- Công nghệ in: ${chosenTech === 'offset' ? 'In Offset' : 'In Nhanh Kỹ Thuật Số'} (${input.printSides === '2_side' ? '2 mặt' : '1 mặt'})${costs.finishingDetails.length > 0 ? `- Gia công: ${costs.finishingDetails.map((f) => f.name).join(', ')}\n` : ''}- Tổng thanh toán: ${costs.finalPrice.toLocaleString('vi-VN')} VNĐ- Đơn giá: ${costs.unitPrice.toLocaleString('vi-VN')} VNĐ / chiếc----------------------------------------Hotline / Zalo: Liên hệ xưởng in PrintCal`;
navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2500); };
return ( <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden flex flex-col h-full"> {/* Header giá bán nổi bật */} <div className="bg-gradient-to-br from-slate-900 via-indigo-950 to-blue-900 text-white p-5"> <div className="flex items-center justify-between text-xs text-blue-300 mb-1"> <span className="uppercase font-semibold tracking-wider">Tổng Giá Bán Đề Xuất</span> <span className="px-2 py-0.5 rounded-full bg-blue-500/20 text-blue-300 border border-blue-400/30 text-[11px] font-bold"> {chosenTech === 'offset' ? 'Công Nghệ In Offset' : 'Công Nghệ In Nhanh'} </span> </div>
<div className="flex items-baseline gap-2 mt-1"> <span className="text-3xl sm:text-4xl font-black tracking-tight text-white"> {costs.finalPrice.toLocaleString('vi-VN')} </span> <span className="text-base font-bold text-blue-300">VNĐ</span> </div>
<div className="flex items-center justify-between text-xs text-slate-300 mt-2 pt-2 border-t border-white/10"> <span> Đơn giá: <strong className="text-white text-sm">{costs.unitPrice.toLocaleString('vi-VN')}đ</strong> / chiếc </span> <span> Số lượng: <strong className="text-white">{quantities.productQty.toLocaleString('vi-VN')}</strong> </span> </div> </div>
{/* Chi tiết chi phí từng khâu */} <div className="p-4 space-y-3 flex-1 text-xs"> {/* 1. Tiền giấy */} <div className="p-3 bg-slate-50 border border-slate-100 rounded-xl space-y-1"> <div className="flex items-center justify-between"> <span className="font-semibold text-slate-700 flex items-center gap-1.5"> <Layers className="w-3.5 h-3.5 text-blue-600" /> Tiền Giấy In: </span> <strong className="text-slate-900 text-sm">{costs.paperCost.toLocaleString('vi-VN')}đ</strong> </div> <p className="text-[11px] text-slate-500"> Cần {quantities.parentSheetsNeeded} tờ mẹ ({quantities.ramsNeeded} Ram / ~{quantities.kgNeeded} Kg) • {imposition.parentSheet.name} </p> </div>
{/* 2. Tiền in ấn */} <div className="p-3 bg-slate-50 border border-slate-100 rounded-xl space-y-1"> <div className="flex items-center justify-between"> <span className="font-semibold text-slate-700 flex items-center gap-1.5"> <Sparkles className="w-3.5 h-3.5 text-indigo-600" /> Tiền In Máy ({chosenTech === 'offset' ? 'Offset' : 'KTS'}): </span> <strong className="text-slate-900 text-sm">{costs.totalPrintCost.toLocaleString('vi-VN')}đ</strong> </div> <div className="text-[11px] text-slate-500 space-y-0.5"> {chosenTech === 'offset' ? ( <> <p>Khuôn kẽm CTP: {costs.platesCount} lá × {costs.plateCost.toLocaleString('vi-VN')}đ</p> <p>Công in ({quantities.totalPrintSheets} tờ lớn + bù hao): {costs.printRunCost.toLocaleString('vi-VN')}đ</p> </> ) : ( <p>Phí in click ({quantities.totalPrintSheets} lượt A3/A4): {costs.printRunCost.toLocaleString('vi-VN')}đ</p> )} </div> </div>
{/* 3. Tiền gia công */} <div className="p-3 bg-slate-50 border border-slate-100 rounded-xl space-y-1.5"> <div className="flex items-center justify-between"> <span className="font-semibold text-slate-700">Gia Công Sau In ({costs.finishingDetails.length} khâu):</span> <strong className="text-slate-900 text-sm">{costs.finishingCost.toLocaleString('vi-VN')}đ</strong> </div> {costs.finishingDetails.length > 0 ? ( <div className="space-y-1 pt-1 border-t border-slate-200/60"> {costs.finishingDetails.map((f, i) => ( <div key={i} className="flex justify-between text-[11px] text-slate-600"> <span className="truncate pr-2">• {f.name}:</span> <span className="font-medium shrink-0">{f.subtotal.toLocaleString('vi-VN')}đ</span> </div> ))} </div> ) : ( <p className="text-[11px] text-slate-400">Không chọn gia công phức tạp</p> )} </div>
{/* Chi phí vốn, Lợi nhuận, Thuế */} <div className="pt-2 border-t border-slate-200 space-y-1.5 text-slate-600"> <div className="flex justify-between"> <span>Chi phí vốn gốc:</span> <span className="font-semibold text-slate-800">{costs.totalBaseCost.toLocaleString('vi-VN')}đ</span> </div>
<div className="flex justify-between text-emerald-700"> <span className="flex items-center gap-1"> <TrendingUp className="w-3.5 h-3.5" /> Lợi nhuận gộp ({input.profitMarginPercent}%): </span> <span className="font-semibold">+{costs.profitAmount.toLocaleString('vi-VN')}đ</span> </div>
{costs.discountAmount > 0 && ( <div className="flex justify-between text-rose-600"> <span>Chiết khấu giảm giá:</span> <span className="font-semibold">-{costs.discountAmount.toLocaleString('vi-VN')}đ</span> </div> )}
{costs.vatAmount > 0 && ( <div className="flex justify-between text-slate-600"> <span>Thuế VAT ({input.vatPercent}%):</span> <span className="font-semibold">+{costs.vatAmount.toLocaleString('vi-VN')}đ</span> </div> )} </div> </div>
{/* Nhóm nút hành động */} <div className="p-4 bg-slate-50 border-t border-slate-200 space-y-2"> <button onClick={onSaveOrder} disabled={isSavingOrder} className="w-full flex items-center justify-center gap-2 py-2.5 px-4 bg-blue-600 hover:bg-blue-700 active:scale-[0.99] text-white rounded-xl font-semibold text-xs shadow-md shadow-blue-500/20 transition-all disabled:opacity-50" > <Save className="w-4 h-4" /> {isSavingOrder ? 'Đang lưu đơn hàng...' : 'Lưu Vào Quản Lý Đơn Hàng'} </button>
<div className="grid grid-cols-2 gap-2"> <button onClick={onOpenPrintModal} className="flex items-center justify-center gap-1.5 py-2 px-3 bg-white hover:bg-slate-100 border border-slate-300 text-slate-700 rounded-lg text-xs font-semibold shadow-xs transition-colors" > <Printer className="w-3.5 h-3.5 text-blue-600" /> In Báo Giá / Lệnh SX </button>
<button onClick={handleCopyZalo} className="flex items-center justify-center gap-1.5 py-2 px-3 bg-white hover:bg-slate-100 border border-slate-300 text-slate-700 rounded-lg text-xs font-semibold shadow-xs transition-colors" > {copied ? ( <> <Check className="w-3.5 h-3.5 text-emerald-600" /> <span className="text-emerald-700">Đã copy Zalo!</span> </> ) : ( <> <Copy className="w-3.5 h-3.5 text-slate-500" /> Copy Gửi Khách </> )} </button> </div> </div> </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227'use client';
import React, { useState, useEffect } from 'react';import { Customer } from '@/types';import { Users, Plus, Phone, Mail, Building, MapPin, X, RefreshCw } from 'lucide-react';
export const CustomerManager: React.FC = () => { const [customers, setCustomers] = useState<Customer[]>([]); const [loading, setLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); const [newCustomer, setNewCustomer] = useState({ name: '', phone: '', email: '', company: '', address: '', notes: '', });
const fetchCustomers = async () => { try { setLoading(true); const res = await fetch('/api/customers'); const data = await res.json(); if (Array.isArray(data)) setCustomers(data); } catch (err) { console.error(err); } finally { setLoading(false); } };
useEffect(() => { fetchCustomers(); }, []);
const handleSave = async (e: React.FormEvent) => { e.preventDefault(); try { const res = await fetch('/api/customers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newCustomer), }); if (res.ok) { setIsModalOpen(false); setNewCustomer({ name: '', phone: '', email: '', company: '', address: '', notes: '' }); fetchCustomers(); } } catch (err) { console.error(err); } };
return ( <div className="space-y-4"> <div className="flex items-center justify-between bg-white p-4 rounded-xl border border-slate-200 shadow-xs"> <div> <h2 className="text-base font-bold text-slate-800">Danh Sách Khách Hàng (CRM mini)</h2> <p className="text-xs text-slate-500">Lưu trữ thông tin liên hệ, công ty và lịch sử đặt in của khách hàng</p> </div> <button onClick={() => setIsModalOpen(true)} className="flex items-center gap-1.5 px-3.5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-semibold shadow transition-colors" > <Plus className="w-4 h-4" /> Thêm Khách Hàng </button> </div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4"> {loading ? ( <div className="col-span-3 py-12 text-center text-slate-400"> <RefreshCw className="w-6 h-6 animate-spin mx-auto text-blue-500 mb-2" /> Đang tải danh sách khách hàng... </div> ) : customers.length === 0 ? ( <div className="col-span-3 py-12 text-center text-slate-400 bg-white rounded-xl border border-slate-200"> <Users className="w-10 h-10 mx-auto text-slate-300 mb-2" /> Chưa có khách hàng nào trong hệ thống </div> ) : ( customers.map((c) => ( <div key={c.id} className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-2.5"> <div className="flex items-center justify-between"> <strong className="text-sm font-bold text-slate-900">{c.name}</strong> <span className="text-[10px] text-slate-400 font-mono">#{c.id}</span> </div>
{c.company && ( <div className="flex items-center gap-1.5 text-xs text-slate-600"> <Building className="w-3.5 h-3.5 text-slate-400 shrink-0" /> <span className="truncate">{c.company}</span> </div> )}
<div className="flex items-center gap-1.5 text-xs text-slate-700 font-medium"> <Phone className="w-3.5 h-3.5 text-blue-600 shrink-0" /> <span>{c.phone}</span> </div>
{c.email && ( <div className="flex items-center gap-1.5 text-xs text-slate-600"> <Mail className="w-3.5 h-3.5 text-slate-400 shrink-0" /> <span className="truncate">{c.email}</span> </div> )}
{c.address && ( <div className="flex items-center gap-1.5 text-xs text-slate-500"> <MapPin className="w-3.5 h-3.5 text-slate-400 shrink-0" /> <span className="truncate">{c.address}</span> </div> )}
{c.notes && ( <p className="text-[11px] text-slate-500 bg-slate-50 p-2 rounded border border-slate-100 italic"> “{c.notes}” </p> )} </div> )) )} </div>
{isModalOpen && ( <div className="fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-4"> <div className="bg-white rounded-xl shadow-xl max-w-md w-full overflow-hidden"> <div className="p-4 bg-slate-900 text-white flex items-center justify-between"> <h3 className="font-bold text-sm">Thêm Mới Khách Hàng</h3> <button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-white"> <X className="w-5 h-5" /> </button> </div>
<form onSubmit={handleSave} className="p-5 space-y-3 text-xs"> <div> <label className="block text-slate-600 font-medium mb-1">Tên Khách Hàng *</label> <input type="text" required value={newCustomer.name} onChange={(e) => setNewCustomer({ ...newCustomer, name: e.target.value })} placeholder="Ví dụ: Anh Hoàng / Chị Mai" className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div>
<div className="grid grid-cols-2 gap-3"> <div> <label className="block text-slate-600 font-medium mb-1">Số Điện Thoại *</label> <input type="tel" required value={newCustomer.phone} onChange={(e) => setNewCustomer({ ...newCustomer, phone: e.target.value })} placeholder="0901234567" className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> <div> <label className="block text-slate-600 font-medium mb-1">Email</label> <input type="email" value={newCustomer.email} onChange={(e) => setNewCustomer({ ...newCustomer, email: e.target.value })} placeholder="email@example.com" className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div> <label className="block text-slate-600 font-medium mb-1">Tên Công Ty / Cửa Hàng</label> <input type="text" value={newCustomer.company} onChange={(e) => setNewCustomer({ ...newCustomer, company: e.target.value })} placeholder="Công ty TNHH..." className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div>
<div> <label className="block text-slate-600 font-medium mb-1">Địa Chỉ Giao Hàng</label> <input type="text" value={newCustomer.address} onChange={(e) => setNewCustomer({ ...newCustomer, address: e.target.value })} placeholder="Số nhà, tên đường, quận/huyện..." className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div>
<div> <label className="block text-slate-600 font-medium mb-1">Ghi Chú Về Khách Hàng</label> <textarea rows={2} value={newCustomer.notes} onChange={(e) => setNewCustomer({ ...newCustomer, notes: e.target.value })} placeholder="Thói quen đặt hàng, lưu ý kỹ thuật..." className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div>
<div className="flex justify-end gap-2 pt-3 border-t border-slate-100"> <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 border border-slate-300 rounded-lg text-slate-600 hover:bg-slate-50" > Hủy </button> <button type="submit" className="px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700" > Lưu Khách Hàng </button> </div> </form> </div> </div> )} </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308'use client';
import React, { useState, useEffect } from 'react';import { FinishingService } from '@/types';import { Scissors, Plus, Edit2, Trash2, X, RefreshCw } from 'lucide-react';
export const FinishingManager: React.FC = () => { const [services, setServices] = useState<FinishingService[]>([]); const [loading, setLoading] = useState(true); const [editingService, setEditingService] = useState<Partial<FinishingService> | null>(null); const [isModalOpen, setIsModalOpen] = useState(false);
const fetchServices = async () => { try { setLoading(true); const res = await fetch('/api/finishing'); const data = await res.json(); if (Array.isArray(data)) setServices(data); } catch (err) { console.error(err); } finally { setLoading(false); } };
useEffect(() => { fetchServices(); }, []);
const handleOpenAdd = () => { setEditingService({ code: `FIN_${Date.now().toString().slice(-4)}`, name: 'Dịch vụ gia công ', category: 'can_mang', calcType: 'per_product', unitPrice: 150, minPrice: 50000, setupFee: 0, wastePercent: 1.0, wasteSheets: 10, isActive: true, }); setIsModalOpen(true); };
const handleOpenEdit = (s: FinishingService) => { setEditingService({ ...s }); setIsModalOpen(true); };
const handleSave = async (e: React.FormEvent) => { e.preventDefault(); if (!editingService) return;
const isUpdate = Boolean(editingService.id); const method = isUpdate ? 'PUT' : 'POST';
try { const res = await fetch('/api/finishing', { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(editingService), }); if (res.ok) { setIsModalOpen(false); setEditingService(null); fetchServices(); } } catch (err) { console.error(err); } };
const handleDelete = async (id: number) => { if (!confirm('Bạn có chắc chắn muốn xóa dịch vụ gia công này?')) return; try { const res = await fetch(`/api/finishing?id=${id}`, { method: 'DELETE' }); if (res.ok) fetchServices(); } catch (err) { console.error(err); } };
return ( <div className="space-y-4"> <div className="flex items-center justify-between bg-white p-4 rounded-xl border border-slate-200 shadow-xs"> <div> <h2 className="text-base font-bold text-slate-800">Bảng Giá Gia Công Sau In (Post-Press)</h2> <p className="text-xs text-slate-500">Cán màng, cấn, bế demi/đứt, ép kim, dập nổi, UV định hình, đóng ghim, dán hộp...</p> </div> <button onClick={handleOpenAdd} className="flex items-center gap-1.5 px-3.5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-semibold shadow transition-colors" > <Plus className="w-4 h-4" /> Thêm Công Đoạn </button> </div>
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden"> <div className="overflow-x-auto"> <table className="w-full text-xs text-left"> <thead className="bg-slate-50 border-b border-slate-200 text-slate-600 font-semibold uppercase"> <tr> <th className="py-3 px-4">Tên Công Đoạn</th> <th className="py-3 px-4 text-center">Phân Loại</th> <th className="py-3 px-4 text-center">Cách Tính</th> <th className="py-3 px-4 text-right">Đơn Giá</th> <th className="py-3 px-4 text-right">Mở Máy Min</th> <th className="py-3 px-4 text-right">Tiền Khuôn</th> <th className="py-3 px-4 text-center">Bù Hao</th> <th className="py-3 px-4 text-right">Thao Tác</th> </tr> </thead> <tbody className="divide-y divide-slate-100 text-slate-700"> {loading ? ( <tr> <td colSpan={8} className="py-8 text-center text-slate-400"> <RefreshCw className="w-5 h-5 animate-spin mx-auto text-blue-500 mb-1" /> Đang tải dữ liệu gia công... </td> </tr> ) : ( services.map((s) => ( <tr key={s.id} className="hover:bg-slate-50 transition-colors"> <td className="py-2.5 px-4 font-bold text-slate-900">{s.name}</td> <td className="py-2.5 px-4 text-center"> <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-slate-100 text-slate-700 uppercase"> {s.category} </span> </td> <td className="py-2.5 px-4 text-center text-slate-500"> {s.calcType === 'per_m2' ? 'Theo m²' : s.calcType === 'die_cut' ? 'Khuôn + Công bế' : s.calcType === 'per_sheet' ? 'Theo tờ in' : s.calcType === 'fixed' ? 'Cố định' : 'Theo cái'} </td> <td className="py-2.5 px-4 text-right font-semibold text-blue-700"> {s.unitPrice.toLocaleString('vi-VN')}đ </td> <td className="py-2.5 px-4 text-right text-slate-600"> {s.minPrice > 0 ? `${s.minPrice.toLocaleString('vi-VN')}đ` : '-'} </td> <td className="py-2.5 px-4 text-right font-medium text-amber-700"> {s.setupFee > 0 ? `${s.setupFee.toLocaleString('vi-VN')}đ` : '-'} </td> <td className="py-2.5 px-4 text-center text-slate-500"> +{s.wastePercent}% ({s.wasteSheets} tờ) </td> <td className="py-2.5 px-4 text-right whitespace-nowrap"> <div className="flex items-center justify-end gap-1"> <button onClick={() => handleOpenEdit(s)} className="p-1.5 text-slate-500 hover:text-blue-600 rounded hover:bg-slate-100" > <Edit2 className="w-3.5 h-3.5" /> </button> <button onClick={() => handleDelete(s.id)} className="p-1.5 text-slate-400 hover:text-rose-600 rounded hover:bg-rose-50" > <Trash2 className="w-3.5 h-3.5" /> </button> </div> </td> </tr> )) )} </tbody> </table> </div> </div>
{/* Modal Thêm/Sửa */} {isModalOpen && editingService && ( <div className="fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-4"> <div className="bg-white rounded-xl shadow-xl max-w-md w-full overflow-hidden"> <div className="p-4 bg-slate-900 text-white flex items-center justify-between"> <h3 className="font-bold text-sm"> {editingService.id ? 'Cập Nhật Công Đoạn Gia Công' : 'Thêm Mới Công Đoạn'} </h3> <button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-white"> <X className="w-5 h-5" /> </button> </div>
<form onSubmit={handleSave} className="p-5 space-y-3 text-xs"> <div> <label className="block text-slate-600 font-medium mb-1">Tên Công Đoạn Gia Công *</label> <input type="text" required value={editingService.name || ''} onChange={(e) => setEditingService({ ...editingService, name: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div>
<div className="grid grid-cols-2 gap-3"> <div> <label className="block text-slate-600 font-medium mb-1">Phân Loại *</label> <select value={editingService.category || 'can_mang'} onChange={(e) => setEditingService({ ...editingService, category: e.target.value as FinishingService['category'] })} className="w-full border border-slate-300 rounded-lg p-2 bg-white" > <option value="can_mang">Cán màng</option> <option value="can_gap">Cấn & Gấp</option> <option value="be">Cắt bế khuôn</option> <option value="ep_kim">Ép kim / Dập nổi</option> <option value="phu_uv">Phủ UV</option> <option value="dong_cuon">Đóng cuốn / Gáy</option> <option value="dan">Dán thành phẩm</option> <option value="khac">Khác</option> </select> </div>
<div> <label className="block text-slate-600 font-medium mb-1">Phương Thức Tính *</label> <select value={editingService.calcType || 'per_product'} onChange={(e) => setEditingService({ ...editingService, calcType: e.target.value as FinishingService['calcType'] })} className="w-full border border-slate-300 rounded-lg p-2 bg-white" > <option value="per_product">Theo cái (con)</option> <option value="per_m2">Theo diện tích (m²)</option> <option value="die_cut">Khuôn + Lượt bế</option> <option value="per_sheet">Theo tờ in</option> <option value="fixed">Cố định</option> </select> </div> </div>
<div className="grid grid-cols-3 gap-3"> <div> <label className="block text-slate-600 font-medium mb-1">Đơn Giá (VNĐ) *</label> <input type="number" required value={editingService.unitPrice || 0} onChange={(e) => setEditingService({ ...editingService, unitPrice: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> <div> <label className="block text-slate-600 font-medium mb-1">Mở Máy Min</label> <input type="number" value={editingService.minPrice || 0} onChange={(e) => setEditingService({ ...editingService, minPrice: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> <div> <label className="block text-slate-600 font-medium mb-1">Tiền Khuôn</label> <input type="number" value={editingService.setupFee || 0} onChange={(e) => setEditingService({ ...editingService, setupFee: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div className="grid grid-cols-2 gap-3"> <div> <label className="block text-slate-600 font-medium mb-1">Bù Hao (%)</label> <input type="number" step="0.1" value={editingService.wastePercent || 0} onChange={(e) => setEditingService({ ...editingService, wastePercent: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> <div> <label className="block text-slate-600 font-medium mb-1">Bù Hao Cố Định (tờ)</label> <input type="number" value={editingService.wasteSheets || 0} onChange={(e) => setEditingService({ ...editingService, wasteSheets: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div className="flex justify-end gap-2 pt-3 border-t border-slate-100"> <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 border border-slate-300 rounded-lg text-slate-600 hover:bg-slate-50" > Hủy </button> <button type="submit" className="px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700" > Lưu Dịch Vụ </button> </div> </form> </div> </div> )} </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187'use client';
import React from 'react';import { ImpositionResult } from '@/types';import { LayoutGrid, Layers, AlertCircle, CheckCircle2 } from 'lucide-react';
interface ImpositionVisualizerProps { imposition: ImpositionResult; productName?: string; productWidthMm: number; productHeightMm: number;}
export const ImpositionVisualizer: React.FC<ImpositionVisualizerProps> = ({ imposition, productName = 'Sản phẩm', productWidthMm, productHeightMm,}) => { const { printSheet, parentSheet, upsPerPrintSheet, cutsPerParentSheet, totalUpsPerParentSheet, gripperMarginMm, cols, rows, boxes, sheetEfficiencyPercent, isRotated, } = imposition;
// ViewBox của SVG dựa trên kích thước thật của tờ in (mm) const svgWidth = printSheet.widthMm; const svgHeight = printSheet.heightMm;
return ( <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-4 flex flex-col h-full"> <div className="flex items-center justify-between pb-3 mb-3 border-b border-slate-100"> <div className="flex items-center gap-2"> <div className="p-1.5 bg-blue-50 text-blue-600 rounded-lg"> <LayoutGrid className="w-5 h-5" /> </div> <div> <h3 className="font-semibold text-slate-800 text-sm md:text-base">Mô Phỏng Bình Trang & Cắt Giấy 2D</h3> <p className="text-xs text-slate-500"> Tờ in: <span className="font-medium text-slate-700">{printSheet.name}</span> ({printSheet.widthMm} × {printSheet.heightMm} mm) </p> </div> </div>
<div className="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 bg-emerald-50 text-emerald-700 rounded-full border border-emerald-200"> <CheckCircle2 className="w-3.5 h-3.5" /> Tận dụng {sheetEfficiencyPercent}% </div> </div>
{/* Vùng vẽ đồ họa SVG hiển thị khổ in và các con */} <div className="relative flex-1 bg-slate-900 rounded-lg p-4 flex items-center justify-center overflow-hidden min-h-[260px]"> {/* Lưới nền xưởng in */} <div className="absolute inset-0 opacity-10 bg-[linear-gradient(to_right,#ffffff_1px,transparent_1px),linear-gradient(to_bottom,#ffffff_1px,transparent_1px)] bg-[size:20px_20px]" />
<div className="relative max-w-full max-h-full flex items-center justify-center"> <svg viewBox={`0 0 ${svgWidth} ${svgHeight}`} className="w-full max-h-[280px] drop-shadow-2xl border border-slate-600 rounded bg-amber-50/90 transition-all duration-300" style={{ aspectRatio: `${svgWidth} / ${svgHeight}` }} > {/* Vùng lề kẹp nhíp máy in (Gripper) - màu sọc cảnh báo */} <defs> <pattern id="gripperStripe" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"> <line x1="0" y1="0" x2="0" y2="8" stroke="#f59e0b" strokeWidth="4" /> <line x1="4" y1="0" x2="4" y2="8" stroke="#fbbf24" strokeWidth="4" /> </pattern> </defs>
{/* Khung tờ in */} <rect x="0" y="0" width={svgWidth} height={svgHeight} fill="#ffffff" stroke="#cbd5e1" strokeWidth="1.5" />
{/* Dải lề nhíp ở đáy tờ in */} <rect x="0" y={svgHeight - gripperMarginMm} width={svgWidth} height={gripperMarginMm} fill="url(#gripperStripe)" opacity="0.75" /> <text x={svgWidth / 2} y={svgHeight - gripperMarginMm / 2 + 3} textAnchor="middle" fill="#b45309" fontSize={Math.max(10, Math.min(16, svgWidth / 30))} fontWeight="bold" > Lề kẹp nhíp ({gripperMarginMm}mm) </text>
{/* Các con sản phẩm được xếp trên tờ in */} {boxes.map((b) => ( <g key={b.index}> {/* Khối con */} <rect x={b.x} y={b.y} width={b.w} height={b.h} fill="#dbeafe" stroke="#2563eb" strokeWidth="1" rx="1" className="transition-colors hover:fill-blue-200" /> {/* Đường xén thành phẩm bên trong (Bleed 2mm) */} <rect x={b.x + 2} y={b.y + 2} width={Math.max(1, b.w - 4)} height={Math.max(1, b.h - 4)} fill="none" stroke="#93c5fd" strokeWidth="0.5" strokeDasharray="2,2" /> {/* Số thứ tự con */} <text x={b.x + b.w / 2} y={b.y + b.h / 2 + 4} textAnchor="middle" fill="#1e40af" fontSize={Math.max(9, Math.min(14, b.w / 6))} fontWeight="bold" > #{b.index} </text> </g> ))} </svg> </div> </div>
{/* Thông số bình trang chi tiết */} <div className="grid grid-cols-2 md:grid-cols-4 gap-2.5 mt-3 text-xs"> <div className="bg-slate-50 border border-slate-200 rounded-lg p-2 text-center"> <span className="text-slate-500 block">Số con / tờ in</span> <span className="text-base font-bold text-blue-600">{upsPerPrintSheet} con</span> <span className="text-[10px] text-slate-400 block">({cols} cột × {rows} hàng {isRotated ? '• Xoay' : ''})</span> </div>
<div className="bg-slate-50 border border-slate-200 rounded-lg p-2 text-center"> <span className="text-slate-500 block">Tờ in / Giấy mẹ</span> <span className="text-base font-bold text-indigo-600">Chia {cutsPerParentSheet}</span> <span className="text-[10px] text-slate-400 block">Từ {parentSheet.name}</span> </div>
<div className="bg-slate-50 border border-slate-200 rounded-lg p-2 text-center"> <span className="text-slate-500 block">Tổng con / Tờ mẹ</span> <span className="text-base font-bold text-purple-600">{totalUpsPerParentSheet} con</span> <span className="text-[10px] text-slate-400 block">{upsPerPrintSheet} × {cutsPerParentSheet} tờ</span> </div>
<div className="bg-slate-50 border border-slate-200 rounded-lg p-2 text-center"> <span className="text-slate-500 block">Khổ thành phẩm</span> <span className="text-base font-bold text-slate-700">{productWidthMm} × {productHeightMm}</span> <span className="text-[10px] text-slate-400 block">mm (Tràn lề +2mm)</span> </div> </div>
<div className="mt-2.5 flex items-start gap-1.5 text-[11px] text-slate-500 bg-amber-50/70 border border-amber-200/60 rounded p-2"> <AlertCircle className="w-3.5 h-3.5 text-amber-600 shrink-0 mt-0.5" /> <span> Đã chừa lề nhíp {gripperMarginMm}mm và đường dao xén thành phẩm. Bản vẽ mô phỏng chính xác hướng xếp giấy nhằm giảm thiểu phế liệu. </span> </div> </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326'use client';
import React, { useState, useEffect } from 'react';import { DigitalMachine, OffsetMachine } from '@/types';import { Cpu, Printer, Edit2, Check, RefreshCw } from 'lucide-react';
export const MachineManager: React.FC = () => { const [offsetMachines, setOffsetMachines] = useState<OffsetMachine[]>([]); const [digitalMachines, setDigitalMachines] = useState<DigitalMachine[]>([]); const [loading, setLoading] = useState(true); const [editingOffset, setEditingOffset] = useState<OffsetMachine | null>(null); const [editingDigital, setEditingDigital] = useState<DigitalMachine | null>(null);
const fetchMachines = async () => { try { setLoading(true); const res = await fetch('/api/machines'); const data = await res.json(); if (data.offsetMachines) setOffsetMachines(data.offsetMachines); if (data.digitalMachines) setDigitalMachines(data.digitalMachines); } catch (err) { console.error(err); } finally { setLoading(false); } };
useEffect(() => { fetchMachines(); }, []);
const handleSaveOffset = async (m: OffsetMachine) => { try { const res = await fetch('/api/machines', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'offset', ...m }), }); if (res.ok) { setEditingOffset(null); fetchMachines(); } } catch (err) { console.error(err); } };
const handleSaveDigital = async (m: DigitalMachine) => { try { const res = await fetch('/api/machines', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'digital', ...m }), }); if (res.ok) { setEditingDigital(null); fetchMachines(); } } catch (err) { console.error(err); } };
return ( <div className="space-y-6"> {/* MÁY IN OFFSET */} <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden"> <div className="p-4 border-b border-slate-200 bg-slate-50 flex items-center justify-between"> <div className="flex items-center gap-2"> <Cpu className="w-5 h-5 text-indigo-600" /> <div> <h3 className="font-bold text-slate-800 text-sm">Cấu Hình Máy In Offset & Đơn Giá Kẽm, Công In</h3> <p className="text-xs text-slate-500">Thiết lập khổ máy, giá khuôn kẽm CTP, phí mở máy và lũy tiến</p> </div> </div> <button onClick={fetchMachines} className="p-2 text-slate-500 hover:text-indigo-600 rounded"> <RefreshCw className="w-4 h-4" /> </button> </div>
<div className="p-4 grid grid-cols-1 md:grid-cols-3 gap-4"> {offsetMachines.map((m) => { const isEditing = editingOffset?.id === m.id; const current = isEditing ? editingOffset : m;
return ( <div key={m.id} className="border border-slate-200 rounded-xl p-4 bg-slate-50/50 flex flex-col justify-between space-y-3"> <div className="flex items-center justify-between border-b border-slate-200 pb-2"> <strong className="text-xs font-bold text-slate-900">{current.name}</strong> <button onClick={() => setEditingOffset(isEditing ? null : { ...m })} className="p-1 text-slate-400 hover:text-indigo-600" > <Edit2 className="w-3.5 h-3.5" /> </button> </div>
<div className="space-y-2 text-xs"> <div className="flex justify-between items-center"> <span className="text-slate-500">Khổ in max:</span> {isEditing ? ( <div className="flex gap-1 w-32"> <input type="number" className="w-1/2 p-1 border rounded text-right" value={current.maxWidthMm} onChange={(e) => setEditingOffset({ ...current, maxWidthMm: Number(e.target.value) })} /> <input type="number" className="w-1/2 p-1 border rounded text-right" value={current.maxHeightMm} onChange={(e) => setEditingOffset({ ...current, maxHeightMm: Number(e.target.value) })} /> </div> ) : ( <span className="font-medium text-slate-800">{current.maxWidthMm} × {current.maxHeightMm} mm</span> )} </div>
<div className="flex justify-between items-center"> <span className="text-slate-500">Giá kẽm CTP / lá:</span> {isEditing ? ( <input type="number" className="w-28 p-1 border rounded text-right" value={current.platePrice} onChange={(e) => setEditingOffset({ ...current, platePrice: Number(e.target.value) })} /> ) : ( <span className="font-bold text-indigo-700">{current.platePrice.toLocaleString('vi-VN')}đ</span> )} </div>
<div className="flex justify-between items-center"> <span className="text-slate-500">Mở máy (≤1000 lượt):</span> {isEditing ? ( <input type="number" className="w-28 p-1 border rounded text-right" value={current.setupCost} onChange={(e) => setEditingOffset({ ...current, setupCost: Number(e.target.value) })} /> ) : ( <span className="font-bold text-slate-800">{current.setupCost.toLocaleString('vi-VN')}đ</span> )} </div>
<div className="flex justify-between items-center"> <span className="text-slate-500">Mỗi 1000 lượt tiếp:</span> {isEditing ? ( <input type="number" className="w-28 p-1 border rounded text-right" value={current.stepCost} onChange={(e) => setEditingOffset({ ...current, stepCost: Number(e.target.value) })} /> ) : ( <span className="font-medium text-slate-700">{current.stepCost.toLocaleString('vi-VN')}đ</span> )} </div>
<div className="flex justify-between items-center"> <span className="text-slate-500">Bù hao canh màu:</span> {isEditing ? ( <input type="number" className="w-28 p-1 border rounded text-right" value={current.defaultWasteSheets} onChange={(e) => setEditingOffset({ ...current, defaultWasteSheets: Number(e.target.value) })} /> ) : ( <span className="font-medium text-amber-700">{current.defaultWasteSheets} tờ</span> )} </div> </div>
{isEditing && ( <div className="pt-2 border-t border-slate-200 flex justify-end gap-1.5"> <button onClick={() => setEditingOffset(null)} className="px-2 py-1 border rounded text-[11px] text-slate-600 hover:bg-slate-100" > Hủy </button> <button onClick={() => handleSaveOffset(current)} className="px-2.5 py-1 bg-indigo-600 text-white rounded text-[11px] font-semibold hover:bg-indigo-700" > Lưu </button> </div> )} </div> ); })} </div> </div>
{/* MÁY IN NHANH KTS */} <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden"> <div className="p-4 border-b border-slate-200 bg-slate-50 flex items-center justify-between"> <div className="flex items-center gap-2"> <Printer className="w-5 h-5 text-sky-600" /> <div> <h3 className="font-bold text-slate-800 text-sm">Bảng Giá Máy In Nhanh Kỹ Thuật Số (Digital Click)</h3> <p className="text-xs text-slate-500">Đơn giá in theo click A4, A3 1 mặt và 2 mặt</p> </div> </div> </div>
<div className="p-4 grid grid-cols-1 md:grid-cols-2 gap-4"> {digitalMachines.map((m) => { const isEditing = editingDigital?.id === m.id; const current = isEditing ? editingDigital : m;
return ( <div key={m.id} className="border border-slate-200 rounded-xl p-4 bg-slate-50/50 flex flex-col justify-between space-y-3"> <div className="flex items-center justify-between border-b border-slate-200 pb-2"> <strong className="text-xs font-bold text-slate-900">{current.name}</strong> <button onClick={() => setEditingDigital(isEditing ? null : { ...m })} className="p-1 text-slate-400 hover:text-sky-600" > <Edit2 className="w-3.5 h-3.5" /> </button> </div>
<div className="space-y-2 text-xs"> <div className="grid grid-cols-2 gap-2"> <div className="p-2 bg-white rounded border border-slate-200"> <span className="text-slate-400 block text-[10px]">Click A4 1 mặt</span> {isEditing ? ( <input type="number" className="w-full p-1 border rounded text-right mt-1" value={current.clickA41Side} onChange={(e) => setEditingDigital({ ...current, clickA41Side: Number(e.target.value) })} /> ) : ( <strong className="text-slate-800 text-sm">{current.clickA41Side.toLocaleString('vi-VN')}đ</strong> )} </div> <div className="p-2 bg-white rounded border border-slate-200"> <span className="text-slate-400 block text-[10px]">Click A4 2 mặt</span> {isEditing ? ( <input type="number" className="w-full p-1 border rounded text-right mt-1" value={current.clickA42Side} onChange={(e) => setEditingDigital({ ...current, clickA42Side: Number(e.target.value) })} /> ) : ( <strong className="text-slate-800 text-sm">{current.clickA42Side.toLocaleString('vi-VN')}đ</strong> )} </div> </div>
<div className="grid grid-cols-2 gap-2"> <div className="p-2 bg-white rounded border border-slate-200"> <span className="text-slate-400 block text-[10px]">Click A3/A3+ 1 mặt</span> {isEditing ? ( <input type="number" className="w-full p-1 border rounded text-right mt-1" value={current.clickA31Side} onChange={(e) => setEditingDigital({ ...current, clickA31Side: Number(e.target.value) })} /> ) : ( <strong className="text-sky-700 text-sm">{current.clickA31Side.toLocaleString('vi-VN')}đ</strong> )} </div> <div className="p-2 bg-white rounded border border-slate-200"> <span className="text-slate-400 block text-[10px]">Click A3/A3+ 2 mặt</span> {isEditing ? ( <input type="number" className="w-full p-1 border rounded text-right mt-1" value={current.clickA32Side} onChange={(e) => setEditingDigital({ ...current, clickA32Side: Number(e.target.value) })} /> ) : ( <strong className="text-sky-700 text-sm">{current.clickA32Side.toLocaleString('vi-VN')}đ</strong> )} </div> </div>
<div className="flex justify-between items-center pt-1"> <span className="text-slate-500">Phí tối thiểu / bài:</span> {isEditing ? ( <input type="number" className="w-28 p-1 border rounded text-right" value={current.minCharge} onChange={(e) => setEditingDigital({ ...current, minCharge: Number(e.target.value) })} /> ) : ( <span className="font-semibold text-slate-800">{current.minCharge.toLocaleString('vi-VN')}đ</span> )} </div> </div>
{isEditing && ( <div className="pt-2 border-t border-slate-200 flex justify-end gap-1.5"> <button onClick={() => setEditingDigital(null)} className="px-2 py-1 border rounded text-[11px] text-slate-600 hover:bg-slate-100" > Hủy </button> <button onClick={() => handleSaveDigital(current)} className="px-2.5 py-1 bg-sky-600 text-white rounded text-[11px] font-semibold hover:bg-sky-700" > Lưu </button> </div> )} </div> ); })} </div> </div> </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131'use client';
import React from 'react';import { Printer, Calculator, ClipboardList, FileSpreadsheet, Cpu, Scissors, Users, Settings, Sparkles,} from 'lucide-react';
export type ActiveTab = | 'calculator' | 'orders' | 'papers' | 'machines' | 'finishing' | 'customers' | 'settings';
interface NavbarProps { activeTab: ActiveTab; setActiveTab: (tab: ActiveTab) => void; orderCount?: number;}
export const Navbar: React.FC<NavbarProps> = ({ activeTab, setActiveTab, orderCount = 0,}) => { const navItems = [ { id: 'calculator', label: 'Tính Giá In', icon: Calculator, badge: null }, { id: 'orders', label: 'Đơn Hàng & Báo Giá', icon: ClipboardList, badge: orderCount > 0 ? orderCount : null }, { id: 'papers', label: 'Kho Giá Giấy', icon: FileSpreadsheet, badge: null }, { id: 'machines', label: 'Bảng Giá In Máy', icon: Cpu, badge: null }, { id: 'finishing', label: 'Gia Công Sau In', icon: Scissors, badge: null }, { id: 'customers', label: 'Khách Hàng', icon: Users, badge: null }, { id: 'settings', label: 'Cài Đặt', icon: Settings, badge: null }, ] as const;
return ( <header className="bg-slate-900 border-b border-slate-800 text-white sticky top-0 z-40 shadow-md"> <div className="max-w-7xl mx-auto px-4 sm:px-6"> <div className="flex items-center justify-between h-16"> {/* Logo & Brand */} <div className="flex items-center gap-3 cursor-pointer" onClick={() => setActiveTab('calculator')}> <div className="w-10 h-10 rounded-xl bg-gradient-to-tr from-blue-600 via-indigo-600 to-cyan-400 flex items-center justify-center shadow-lg shadow-blue-500/30"> <Printer className="w-5 h-5 text-white" /> </div> <div> <div className="flex items-center gap-1.5"> <span className="font-black text-lg tracking-wider text-white">PrintCal</span> <span className="text-[10px] uppercase font-bold tracking-widest px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 border border-blue-500/30 flex items-center gap-1"> <Sparkles className="w-2.5 h-2.5" /> ERP Pro </span> </div> <p className="text-[11px] text-slate-400 hidden sm:block">Tính Giá In Offset & In Nhanh Thông Minh</p> </div> </div>
{/* Navigation Links */} <nav className="hidden lg:flex items-center gap-1"> {navItems.map((item) => { const Icon = item.icon; const isActive = activeTab === item.id; return ( <button key={item.id} onClick={() => setActiveTab(item.id as ActiveTab)} className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all ${ isActive ? 'bg-blue-600 text-white shadow-sm font-semibold' : 'text-slate-300 hover:text-white hover:bg-slate-800/80' }`} > <Icon className="w-4 h-4" /> <span>{item.label}</span> {item.badge !== null && ( <span className="px-1.5 py-0.2 bg-rose-500 text-white text-[10px] font-bold rounded-full"> {item.badge} </span> )} </button> ); })} </nav>
{/* Quick status pill */} <div className="flex items-center gap-2 text-xs"> <div className="hidden sm:flex items-center gap-1.5 px-2.5 py-1 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 rounded-full font-medium"> <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" /> <span>SQLite CSDL Sẵn Sàng</span> </div> </div> </div>
{/* Mobile menu tab bar */} <div className="lg:hidden flex items-center gap-1 overflow-x-auto py-2 border-t border-slate-800/80 text-xs no-scrollbar"> {navItems.map((item) => { const Icon = item.icon; const isActive = activeTab === item.id; return ( <button key={item.id} onClick={() => setActiveTab(item.id as ActiveTab)} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg whitespace-nowrap text-xs transition-colors shrink-0 ${ isActive ? 'bg-blue-600 text-white font-medium' : 'text-slate-300 hover:text-white hover:bg-slate-800' }`} > <Icon className="w-3.5 h-3.5" /> <span>{item.label}</span> {item.badge !== null && ( <span className="px-1 bg-rose-500 text-white text-[9px] font-bold rounded-full"> {item.badge} </span> )} </button> ); })} </div> </div> </header> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263'use client';
import React, { useState, useEffect } from 'react';import { OrderStatus, QuoteOrder } from '@/types';import { ClipboardList, Search, Printer, Trash2, Eye, CheckCircle, Clock, Wrench, Truck, AlertCircle, RefreshCw,} from 'lucide-react';
interface OrdersManagerProps { onViewOrder?: (order: QuoteOrder) => void;}
export const OrdersManager: React.FC<OrdersManagerProps> = ({ onViewOrder }) => { const [orders, setOrders] = useState<QuoteOrder[]>([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); const [statusFilter, setStatusFilter] = useState('all'); const [selectedOrder, setSelectedOrder] = useState<QuoteOrder | null>(null);
const fetchOrders = async () => { try { setLoading(true); const url = new URL('/api/orders', window.location.origin); if (statusFilter !== 'all') url.searchParams.set('status', statusFilter); if (search) url.searchParams.set('search', search);
const res = await fetch(url.toString()); const data = await res.json(); if (Array.isArray(data)) { setOrders(data); } } catch (err) { console.error('Fetch orders error:', err); } finally { setLoading(false); } };
useEffect(() => { fetchOrders(); }, [statusFilter]);
const handleSearchSubmit = (e: React.FormEvent) => { e.preventDefault(); fetchOrders(); };
const handleUpdateStatus = async (orderId: number, newStatus: OrderStatus) => { try { const res = await fetch('/api/orders', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'status', id: orderId, status: newStatus }), }); if (res.ok) { setOrders((prev) => prev.map((o) => (o.id === orderId ? { ...o, status: newStatus } : o)) ); } } catch (err) { console.error('Update order status error:', err); } };
const handleDeleteOrder = async (orderId: number) => { if (!confirm('Bạn có chắc chắn muốn xóa đơn hàng này?')) return; try { const res = await fetch(`/api/orders?id=${orderId}`, { method: 'DELETE' }); if (res.ok) { setOrders((prev) => prev.filter((o) => o.id !== orderId)); } } catch (err) { console.error('Delete order error:', err); } };
const getStatusBadge = (status: OrderStatus) => { switch (status) { case 'quote': return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-slate-100 text-slate-700 border border-slate-300">Báo Giá</span>; case 'approved': return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-blue-100 text-blue-800 border border-blue-200">Đã Duyệt / Đặt Cọc</span>; case 'printing': return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-amber-100 text-amber-800 border border-amber-200">Đang In Máy</span>; case 'finishing': return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-purple-100 text-purple-800 border border-purple-200">Đang Gia Công</span>; case 'completed': return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-emerald-100 text-emerald-800 border border-emerald-200">Đã Hoàn Thành</span>; case 'delivered': return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-teal-100 text-teal-800 border border-teal-200">Đã Giao Hàng</span>; case 'cancelled': return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-rose-100 text-rose-800 border border-rose-200">Đã Hủy</span>; default: return <span className="px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-slate-100 text-slate-600">{status}</span>; } };
return ( <div className="space-y-4"> {/* Thanh tìm kiếm & lọc trạng thái */} <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs flex flex-col md:flex-row items-center justify-between gap-3"> <form onSubmit={handleSearchSubmit} className="relative w-full md:w-80"> <input type="text" placeholder="Tìm theo mã đơn, tên khách, SĐT..." value={search} onChange={(e) => setSearch(e.target.value)} className="w-full pl-9 pr-3 py-2 text-xs border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" /> <Search className="w-4 h-4 text-slate-400 absolute left-3 top-2.5" /> </form>
<div className="flex items-center gap-2 w-full md:w-auto overflow-x-auto pb-1 md:pb-0"> <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="text-xs border border-slate-300 rounded-lg px-3 py-2 bg-white text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="all">Tất cả trạng thái</option> <option value="quote">Báo giá</option> <option value="approved">Đã duyệt / Đặt cọc</option> <option value="printing">Đang in máy</option> <option value="finishing">Đang gia công</option> <option value="completed">Đã hoàn thành</option> <option value="delivered">Đã giao hàng</option> <option value="cancelled">Đã hủy</option> </select>
<button onClick={fetchOrders} className="p-2 text-slate-600 hover:text-blue-600 rounded-lg hover:bg-slate-100 transition-colors" title="Tải lại" > <RefreshCw className="w-4 h-4" /> </button> </div> </div>
{/* Bảng danh sách đơn hàng */} <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden"> <div className="overflow-x-auto"> <table className="w-full text-xs text-left"> <thead className="bg-slate-50 border-b border-slate-200 text-slate-600 uppercase font-semibold"> <tr> <th className="py-3 px-4">Mã Đơn</th> <th className="py-3 px-4">Khách Hàng</th> <th className="py-3 px-4">Tên Ấn Phẩm</th> <th className="py-3 px-4 text-center">Công Nghệ</th> <th className="py-3 px-4 text-center">Số Lượng</th> <th className="py-3 px-4 text-right">Tổng Tiền</th> <th className="py-3 px-4 text-center">Trạng Thái</th> <th className="py-3 px-4 text-right">Thao Tác</th> </tr> </thead> <tbody className="divide-y divide-slate-100 text-slate-700"> {loading ? ( <tr> <td colSpan={8} className="py-12 text-center text-slate-400"> <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-blue-500" /> Đang tải danh sách đơn hàng... </td> </tr> ) : orders.length === 0 ? ( <tr> <td colSpan={8} className="py-12 text-center text-slate-400"> <ClipboardList className="w-10 h-10 mx-auto mb-2 text-slate-300" /> Không tìm thấy đơn hàng nào </td> </tr> ) : ( orders.map((order) => ( <tr key={order.id} className="hover:bg-slate-50/80 transition-colors"> <td className="py-3 px-4 font-bold text-blue-600 whitespace-nowrap"> {order.code} <span className="block text-[10px] text-slate-400 font-normal"> {new Date(order.createdAt).toLocaleDateString('vi-VN')} </span> </td>
<td className="py-3 px-4"> <strong className="block text-slate-800">{order.customerName}</strong> <span className="text-[11px] text-slate-500">{order.customerPhone}</span> </td>
<td className="py-3 px-4"> <strong className="block text-slate-800">{order.jobName}</strong> <span className="text-[11px] text-slate-500"> {order.widthMm}x{order.heightMm}mm • {order.paperName} </span> </td>
<td className="py-3 px-4 text-center"> <span className={`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase ${ order.printTech === 'offset' ? 'bg-indigo-100 text-indigo-700 border border-indigo-200' : 'bg-sky-100 text-sky-700 border border-sky-200' }`} > {order.printTech} </span> </td>
<td className="py-3 px-4 text-center font-bold text-slate-800"> {order.quantity.toLocaleString('vi-VN')} </td>
<td className="py-3 px-4 text-right font-black text-slate-900 text-sm"> {order.finalPrice.toLocaleString('vi-VN')}đ <span className="block text-[10px] text-slate-500 font-normal"> ({order.unitPrice.toLocaleString('vi-VN')}đ/c) </span> </td>
<td className="py-3 px-4 text-center"> <div className="inline-block relative"> <select value={order.status} onChange={(e) => handleUpdateStatus(order.id, e.target.value as OrderStatus)} className="text-[11px] font-medium border border-slate-200 rounded-md px-2 py-1 bg-white cursor-pointer hover:border-slate-400 focus:outline-none focus:ring-1 focus:ring-blue-500" > <option value="quote">Báo giá</option> <option value="approved">Đã duyệt / Cọc</option> <option value="printing">Đang in máy</option> <option value="finishing">Gia công</option> <option value="completed">Hoàn thành</option> <option value="delivered">Đã giao</option> <option value="cancelled">Hủy đơn</option> </select> </div> </td>
<td className="py-3 px-4 text-right whitespace-nowrap"> <div className="flex items-center justify-end gap-1.5"> <button onClick={() => handleDeleteOrder(order.id)} className="p-1.5 text-slate-400 hover:text-rose-600 rounded hover:bg-rose-50 transition-colors" title="Xóa đơn hàng" > <Trash2 className="w-4 h-4" /> </button> </div> </td> </tr> )) )} </tbody> </table> </div> </div> </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296'use client';
import React, { useState, useEffect } from 'react';import { PaperType } from '@/types';import { Plus, Edit2, Trash2, Check, X, FileSpreadsheet, RefreshCw } from 'lucide-react';
export const PaperManager: React.FC = () => { const [papers, setPapers] = useState<PaperType[]>([]); const [loading, setLoading] = useState(true); const [editingPaper, setEditingPaper] = useState<Partial<PaperType> | null>(null); const [isModalOpen, setIsModalOpen] = useState(false);
const fetchPapers = async () => { try { setLoading(true); const res = await fetch('/api/papers'); const data = await res.json(); if (Array.isArray(data)) setPapers(data); } catch (err) { console.error(err); } finally { setLoading(false); } };
useEffect(() => { fetchPapers(); }, []);
const handleOpenAdd = () => { setEditingPaper({ code: `C_${Date.now().toString().slice(-4)}`, name: 'Couche ', gsm: 150, parentWidthCm: 65, parentHeightCm: 86, pricePerRam: 500000, pricePerKg: 28500, unit: 'ram', description: '', isActive: true, }); setIsModalOpen(true); };
const handleOpenEdit = (p: PaperType) => { setEditingPaper({ ...p }); setIsModalOpen(true); };
const handleSave = async (e: React.FormEvent) => { e.preventDefault(); if (!editingPaper) return;
const isUpdate = Boolean(editingPaper.id); const method = isUpdate ? 'PUT' : 'POST';
try { const res = await fetch('/api/papers', { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(editingPaper), }); if (res.ok) { setIsModalOpen(false); setEditingPaper(null); fetchPapers(); } } catch (err) { console.error(err); } };
const handleDelete = async (id: number) => { if (!confirm('Bạn có chắc chắn muốn xóa loại giấy này?')) return; try { const res = await fetch(`/api/papers?id=${id}`, { method: 'DELETE' }); if (res.ok) fetchPapers(); } catch (err) { console.error(err); } };
return ( <div className="space-y-4"> <div className="flex items-center justify-between bg-white p-4 rounded-xl border border-slate-200 shadow-xs"> <div> <h2 className="text-base font-bold text-slate-800">Kho Bảng Giá Giấy In</h2> <p className="text-xs text-slate-500">Quản lý các loại giấy (Couche, Ivory, Ford, Bristol, Kraft) và đơn giá thị trường</p> </div> <button onClick={handleOpenAdd} className="flex items-center gap-1.5 px-3.5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-semibold shadow transition-colors" > <Plus className="w-4 h-4" /> Thêm Loại Giấy </button> </div>
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden"> <div className="overflow-x-auto"> <table className="w-full text-xs text-left"> <thead className="bg-slate-50 border-b border-slate-200 text-slate-600 font-semibold uppercase"> <tr> <th className="py-3 px-4">Mã Giấy</th> <th className="py-3 px-4">Tên Loại Giấy</th> <th className="py-3 px-4 text-center">Định Lượng</th> <th className="py-3 px-4 text-center">Khổ Giấy Mẹ</th> <th className="py-3 px-4 text-right">Giá / Ram (500 tờ)</th> <th className="py-3 px-4 text-right">Giá / Kg</th> <th className="py-3 px-4 text-center">Trạng Thái</th> <th className="py-3 px-4 text-right">Thao Tác</th> </tr> </thead> <tbody className="divide-y divide-slate-100 text-slate-700"> {loading ? ( <tr> <td colSpan={8} className="py-8 text-center text-slate-400"> <RefreshCw className="w-5 h-5 animate-spin mx-auto text-blue-500 mb-1" /> Đang tải dữ liệu giấy... </td> </tr> ) : ( papers.map((p) => ( <tr key={p.id} className="hover:bg-slate-50 transition-colors"> <td className="py-2.5 px-4 font-mono font-bold text-slate-700">{p.code}</td> <td className="py-2.5 px-4"> <strong className="block text-slate-900">{p.name}</strong> {p.description && <span className="text-[11px] text-slate-400">{p.description}</span>} </td> <td className="py-2.5 px-4 text-center font-semibold text-blue-700">{p.gsm} gsm</td> <td className="py-2.5 px-4 text-center font-medium text-slate-700">{p.parentWidthCm} × {p.parentHeightCm} cm</td> <td className="py-2.5 px-4 text-right font-bold text-slate-900 text-sm"> {p.pricePerRam > 0 ? `${p.pricePerRam.toLocaleString('vi-VN')}đ` : '-'} </td> <td className="py-2.5 px-4 text-right font-medium text-slate-600"> {p.pricePerKg > 0 ? `${p.pricePerKg.toLocaleString('vi-VN')}đ` : '-'} </td> <td className="py-2.5 px-4 text-center"> <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${p.isActive ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-100 text-slate-500'}`}> {p.isActive ? 'Đang dùng' : 'Tạm khóa'} </span> </td> <td className="py-2.5 px-4 text-right whitespace-nowrap"> <div className="flex items-center justify-end gap-1"> <button onClick={() => handleOpenEdit(p)} className="p-1.5 text-slate-500 hover:text-blue-600 rounded hover:bg-slate-100" title="Sửa giá giấy" > <Edit2 className="w-3.5 h-3.5" /> </button> <button onClick={() => handleDelete(p.id)} className="p-1.5 text-slate-400 hover:text-rose-600 rounded hover:bg-rose-50" title="Xóa loại giấy" > <Trash2 className="w-3.5 h-3.5" /> </button> </div> </td> </tr> )) )} </tbody> </table> </div> </div>
{/* Modal Thêm/Sửa Giấy */} {isModalOpen && editingPaper && ( <div className="fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-4"> <div className="bg-white rounded-xl shadow-xl max-w-lg w-full overflow-hidden"> <div className="p-4 bg-slate-900 text-white flex items-center justify-between"> <h3 className="font-bold text-sm"> {editingPaper.id ? 'Cập Nhật Loại Giấy' : 'Thêm Mới Loại Giấy'} </h3> <button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-white"> <X className="w-5 h-5" /> </button> </div>
<form onSubmit={handleSave} className="p-5 space-y-3 text-xs"> <div className="grid grid-cols-2 gap-3"> <div> <label className="block text-slate-600 font-medium mb-1">Mã Giấy *</label> <input type="text" required value={editingPaper.code || ''} onChange={(e) => setEditingPaper({ ...editingPaper, code: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> <div> <label className="block text-slate-600 font-medium mb-1">Định Lượng (GSM) *</label> <input type="number" required value={editingPaper.gsm || 150} onChange={(e) => setEditingPaper({ ...editingPaper, gsm: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div> <label className="block text-slate-600 font-medium mb-1">Tên Giấy Đầy Đủ *</label> <input type="text" required value={editingPaper.name || ''} onChange={(e) => setEditingPaper({ ...editingPaper, name: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div>
<div className="grid grid-cols-2 gap-3"> <div> <label className="block text-slate-600 font-medium mb-1">Khổ Mẹ Rộng (cm) *</label> <input type="number" step="0.1" required value={editingPaper.parentWidthCm || 65} onChange={(e) => setEditingPaper({ ...editingPaper, parentWidthCm: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> <div> <label className="block text-slate-600 font-medium mb-1">Khổ Mẹ Dài (cm) *</label> <input type="number" step="0.1" required value={editingPaper.parentHeightCm || 86} onChange={(e) => setEditingPaper({ ...editingPaper, parentHeightCm: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div className="grid grid-cols-2 gap-3"> <div> <label className="block text-slate-600 font-medium mb-1">Giá / Ram (500 tờ) VNĐ</label> <input type="number" value={editingPaper.pricePerRam || 0} onChange={(e) => setEditingPaper({ ...editingPaper, pricePerRam: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> <div> <label className="block text-slate-600 font-medium mb-1">Giá / Kg (VNĐ)</label> <input type="number" value={editingPaper.pricePerKg || 0} onChange={(e) => setEditingPaper({ ...editingPaper, pricePerKg: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div> <label className="block text-slate-600 font-medium mb-1">Ghi Chú / Ứng Dụng</label> <input type="text" value={editingPaper.description || ''} onChange={(e) => setEditingPaper({ ...editingPaper, description: e.target.value })} placeholder="Ví dụ: Dùng in tờ rơi, ruột catalogue..." className="w-full border border-slate-300 rounded-lg p-2 focus:ring-1 focus:ring-blue-500" /> </div>
<div className="flex justify-end gap-2 pt-3 border-t border-slate-100"> <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 border border-slate-300 rounded-lg text-slate-600 hover:bg-slate-50" > Hủy </button> <button type="submit" className="px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700" > Lưu Thông Tin </button> </div> </form> </div> </div> )} </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417'use client';
import React, { useState } from 'react';import { CalculationInput, CalculationResult, PaperType, SystemSetting } from '@/types';import { Printer, X, FileText, Wrench, Download, Check } from 'lucide-react';
interface QuotePrintModalProps { isOpen: boolean; onClose: () => void; input: CalculationInput; result: CalculationResult; paperType: PaperType; settings?: SystemSetting; quoteCode?: string; customerInfo?: { name: string; phone: string; company?: string; email?: string; address?: string; };}
export const QuotePrintModal: React.FC<QuotePrintModalProps> = ({ isOpen, onClose, input, result, paperType, settings, quoteCode = 'BG-202609-001', customerInfo = { name: 'Quý Khách Hàng', phone: '', company: '', },}) => { const [activeDoc, setActiveDoc] = useState<'quote' | 'job_ticket'>('quote');
if (!isOpen) return null;
const defaultSettings: SystemSetting = settings || { companyName: 'XƯỞNG IN ẤN & THIẾT KẾ PRINTCAL', companyAddress: 'Tòa nhà PrintCal, Số 123 Đường In Ấn, TP.HCM', companyPhone: '0900.888.999 - 028.3888.9999', companyEmail: 'baogia@printcal.vn', bankAccount: '19038889999999 - Techcombank (CN TP.HCM) - CTK: PRINTCAL VIETNAM', bankName: 'Techcombank Chi nhánh TP.HCM', quoteFooterNote: '1. Báo giá có hiệu lực trong vòng 15 ngày.\n2. Giá trên chưa bao gồm phí vận chuyển ngoại tỉnh.\n3. Thời gian giao hàng tính từ lúc duyệt bản in mẫu và đặt cọc 50%.\n4. Đảm bảo chất lượng màu sắc chuẩn theo file thiết kế.', defaultProfitMargin: 25, defaultVatPercent: 8, };
const todayStr = new Date().toLocaleDateString('vi-VN');
const handlePrint = () => { window.print(); };
return ( <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4"> {/* Container Modal */} <div className="bg-white w-full max-w-4xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]"> {/* Header điều khiển (Không in) */} <div className="bg-slate-800 text-white p-4 flex items-center justify-between print:hidden"> <div className="flex items-center gap-2"> <button onClick={() => setActiveDoc('quote')} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors ${ activeDoc === 'quote' ? 'bg-blue-600 text-white' : 'bg-slate-700 text-slate-300 hover:bg-slate-600' }`} > <FileText className="w-4 h-4" /> Phiếu Báo Giá Khách Hàng </button> <button onClick={() => setActiveDoc('job_ticket')} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors ${ activeDoc === 'job_ticket' ? 'bg-amber-600 text-white' : 'bg-slate-700 text-slate-300 hover:bg-slate-600' }`} > <Wrench className="w-4 h-4" /> Lệnh Sản Xuất Xưởng In </button> </div>
<div className="flex items-center gap-2"> <button onClick={handlePrint} className="flex items-center gap-1.5 px-4 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-xs font-semibold shadow transition-colors" > <Printer className="w-4 h-4" /> In / Lưu PDF </button> <button onClick={onClose} className="p-1.5 text-slate-400 hover:text-white rounded-lg hover:bg-slate-700 transition-colors" > <X className="w-5 h-5" /> </button> </div> </div>
{/* Nội dung tài liệu A4 để xem & in */} <div className="p-8 overflow-y-auto flex-1 bg-slate-100 flex justify-center print:p-0 print:bg-white"> <div className="w-full max-w-[210mm] min-h-[297mm] bg-white p-8 md:p-10 shadow-lg print:shadow-none print:p-4 text-slate-900 text-sm font-sans flex flex-col justify-between"> {activeDoc === 'quote' ? ( // ================= PHIẾU BÁO GIÁ KHÁCH HÀNG ================= <div className="flex flex-col h-full justify-between space-y-6"> <div> {/* Tiêu đề nhà in */} <div className="flex justify-between items-start border-b-2 border-slate-900 pb-4"> <div> <h1 className="text-xl font-black tracking-wider text-slate-900 uppercase"> {defaultSettings.companyName} </h1> <p className="text-xs text-slate-600 mt-1">{defaultSettings.companyAddress}</p> <p className="text-xs text-slate-600"> Hotline: <strong className="text-slate-800">{defaultSettings.companyPhone}</strong> | Email: {defaultSettings.companyEmail} </p> </div> <div className="text-right"> <span className="text-xs font-bold text-blue-600 uppercase tracking-widest block">BÁO GIÁ DỊCH VỤ</span> <span className="text-base font-extrabold text-slate-800">{quoteCode}</span> <p className="text-xs text-slate-500 mt-0.5">Ngày: {todayStr}</p> </div> </div>
{/* Thông tin khách hàng */} <div className="grid grid-cols-2 gap-4 bg-slate-50 p-3.5 rounded-lg my-4 text-xs border border-slate-200"> <div> <span className="text-slate-500 block">Khách hàng / Công ty:</span> <strong className="text-slate-800 text-sm">{customerInfo.name || 'Khách Hàng'}</strong> {customerInfo.company && <p className="text-slate-600">{customerInfo.company}</p>} </div> <div className="text-right"> <span className="text-slate-500 block">Số điện thoại / Email:</span> <strong className="text-slate-800">{customerInfo.phone || 'Chưa cung cấp'}</strong> {customerInfo.email && <p className="text-slate-600">{customerInfo.email}</p>} </div> </div>
{/* Bảng chi tiết quy cách in ấn */} <div className="space-y-3"> <h3 className="font-bold text-slate-800 text-sm uppercase tracking-wide">1. Quy Cách Sản Phẩm</h3> <table className="w-full text-xs border border-slate-300"> <tbody> <tr className="border-b border-slate-200"> <td className="p-2 font-semibold bg-slate-100 w-1/4">Tên ấn phẩm:</td> <td className="p-2 font-bold text-slate-800 text-sm">{input.jobName}</td> <td className="p-2 font-semibold bg-slate-100 w-1/4">Số lượng:</td> <td className="p-2 font-bold text-blue-700 text-sm">{input.quantity.toLocaleString('vi-VN')} {input.productType === 'hop_giay' ? 'hộp' : input.productType === 'tui_giay' ? 'túi' : 'cái/cuốn'}</td> </tr> <tr className="border-b border-slate-200"> <td className="p-2 font-semibold bg-slate-100">Kích thước:</td> <td className="p-2">{input.widthMm} × {input.heightMm} mm</td> <td className="p-2 font-semibold bg-slate-100">Chất liệu giấy:</td> <td className="p-2">{paperType.name}</td> </tr> <tr className="border-b border-slate-200"> <td className="p-2 font-semibold bg-slate-100">Công nghệ in:</td> <td className="p-2"> {result.chosenTech === 'offset' ? 'In Offset Công Nghiệp (Chuẩn màu cao)' : 'In Nhanh Kỹ Thuật Số (Chất lượng cao)'} </td> <td className="p-2 font-semibold bg-slate-100">Số màu in:</td> <td className="p-2"> {input.printSides === '2_side' ? `In 2 mặt (${input.colorsFront || 4} màu / ${input.colorsBack || 4} màu)` : `In 1 mặt (${input.colorsFront || 4} màu)`} </td> </tr> <tr> <td className="p-2 font-semibold bg-slate-100 align-top">Gia công sau in:</td> <td colSpan={3} className="p-2"> {result.costs.finishingDetails.length > 0 ? ( <ul className="list-disc list-inside space-y-0.5"> {result.costs.finishingDetails.map((f, i) => ( <li key={i}>{f.name}</li> ))} </ul> ) : ( <span className="text-slate-400">Xén thành phẩm chuẩn</span> )} </td> </tr> </tbody> </table> </div>
{/* Bảng báo giá chi tiết */} <div className="mt-5 space-y-3"> <h3 className="font-bold text-slate-800 text-sm uppercase tracking-wide">2. Bảng Giá Chi Tiết</h3> <table className="w-full text-xs border border-slate-300"> <thead> <tr className="bg-slate-900 text-white font-semibold"> <th className="p-2 text-center w-12">STT</th> <th className="p-2 text-left">Nội Dung Ấn Phẩm</th> <th className="p-2 text-center">ĐVT</th> <th className="p-2 text-center">Số Lượng</th> <th className="p-2 text-right">Đơn Giá</th> <th className="p-2 text-right">Thành Tiền</th> </tr> </thead> <tbody> <tr className="border-b border-slate-200"> <td className="p-2 text-center">01</td> <td className="p-2"> <strong className="block">{input.jobName}</strong> <span className="text-[11px] text-slate-500"> {input.widthMm}x{input.heightMm}mm, Giấy {paperType.name}, In {input.printSides === '2_side' ? '2 mặt' : '1 mặt'} </span> </td> <td className="p-2 text-center">Chiếc</td> <td className="p-2 text-center font-semibold">{input.quantity.toLocaleString('vi-VN')}</td> <td className="p-2 text-right font-semibold">{result.costs.unitPrice.toLocaleString('vi-VN')}đ</td> <td className="p-2 text-right font-bold">{result.costs.finalPrice.toLocaleString('vi-VN')}đ</td> </tr> </tbody> <tfoot> {result.costs.discountAmount > 0 && ( <tr className="border-b border-slate-200 text-slate-600"> <td colSpan={5} className="p-2 text-right">Chiết khấu ưu đãi:</td> <td className="p-2 text-right font-semibold text-rose-600">-{result.costs.discountAmount.toLocaleString('vi-VN')}đ</td> </tr> )} {result.costs.vatAmount > 0 && ( <tr className="border-b border-slate-200 text-slate-600"> <td colSpan={5} className="p-2 text-right">Thuế VAT ({input.vatPercent}%):</td> <td className="p-2 text-right font-semibold">+{result.costs.vatAmount.toLocaleString('vi-VN')}đ</td> </tr> )} <tr className="bg-blue-50 font-bold text-slate-900 text-sm"> <td colSpan={5} className="p-2.5 text-right text-blue-900 uppercase">TỔNG CỘNG THANH TOÁN:</td> <td className="p-2.5 text-right text-blue-700 text-base">{result.costs.finalPrice.toLocaleString('vi-VN')} VNĐ</td> </tr> </tfoot> </table> </div>
{/* Thông tin chuyển khoản & Điều khoản */} <div className="grid grid-cols-2 gap-4 mt-5 text-[11px] border-t border-slate-200 pt-3"> <div> <h4 className="font-bold text-slate-800 uppercase mb-1">Thông Tin Thanh Toán:</h4> <p className="text-slate-700">Ngân hàng: <strong>{defaultSettings.bankName}</strong></p> <p className="text-slate-700">Tài khoản: <strong>{defaultSettings.bankAccount}</strong></p> <p className="text-slate-500 mt-1 italic">Nội dung CK: Tên KH + SĐT + {quoteCode}</p> </div> <div> <h4 className="font-bold text-slate-800 uppercase mb-1">Điều Khoản Giao Nhận:</h4> <p className="text-slate-600 whitespace-pre-line">{defaultSettings.quoteFooterNote}</p> </div> </div> </div>
{/* Chữ ký xác nhận */} <div className="grid grid-cols-2 gap-4 pt-6 text-xs text-center"> <div> <span className="font-bold text-slate-800 uppercase block">ĐẠI DIỆN KHÁCH HÀNG</span> <span className="text-[11px] text-slate-400 italic block mt-0.5">(Ký và ghi rõ họ tên)</span> <div className="h-16" /> </div> <div> <span className="font-bold text-slate-800 uppercase block">ĐẠI DIỆN XƯỞNG IN</span> <span className="text-[11px] text-slate-400 italic block mt-0.5">(Ký, đóng dấu xác nhận)</span> <div className="h-16" /> </div> </div> </div> ) : ( // ================= LỆNH SẢN XUẤT XƯỞNG IN ================= <div className="flex flex-col h-full justify-between space-y-6"> <div> <div className="flex justify-between items-start border-b-2 border-amber-500 pb-3"> <div> <span className="px-2 py-0.5 bg-amber-500 text-white text-xs font-black rounded uppercase">NỘI BỘ XƯỞNG</span> <h1 className="text-xl font-black tracking-wide text-slate-900 uppercase mt-1"> LỆNH SẢN XUẤT IN ẤN </h1> <p className="text-xs text-slate-600">Đơn hàng: <strong className="text-slate-900">{input.jobName}</strong></p> </div> <div className="text-right"> <span className="text-xs font-bold text-amber-600 uppercase tracking-widest block">MÃ LỆNH</span> <span className="text-lg font-black text-slate-900">{quoteCode}</span> <p className="text-xs text-slate-500">Ngày tạo: {todayStr}</p> </div> </div>
{/* Thông số kỹ thuật xưởng in */} <div className="grid grid-cols-3 gap-3 my-4 text-xs"> <div className="bg-slate-50 p-2.5 rounded border border-slate-200"> <span className="text-slate-500 block">Số lượng thành phẩm:</span> <strong className="text-base text-blue-700 font-bold">{input.quantity.toLocaleString('vi-VN')} con</strong> </div> <div className="bg-slate-50 p-2.5 rounded border border-slate-200"> <span className="text-slate-500 block">Khổ thành phẩm (sau xén):</span> <strong className="text-base text-slate-800 font-bold">{input.widthMm} × {input.heightMm} mm</strong> </div> <div className="bg-slate-50 p-2.5 rounded border border-slate-200"> <span className="text-slate-500 block">Công nghệ in:</span> <strong className="text-base text-purple-700 font-bold uppercase">{result.chosenTech}</strong> </div> </div>
{/* KHÂU 1: CẮT XẢ GIẤY MẸ */} <div className="border border-slate-300 rounded p-3 mb-3 text-xs bg-amber-50/40"> <h3 className="font-bold text-slate-800 text-xs uppercase flex items-center gap-1.5 text-amber-900 mb-2"> <Check className="w-4 h-4 text-amber-600" /> Khâu 1: Chuẩn Bị & Cắt Xả Giấy </h3> <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-slate-700"> <div> <span className="text-slate-500 block">Loại giấy:</span> <strong>{paperType.name}</strong> </div> <div> <span className="text-slate-500 block">Khổ giấy mẹ:</span> <strong>{result.imposition.parentSheet.name}</strong> </div> <div> <span className="text-slate-500 block">Cách chia khổ in:</span> <strong className="text-blue-700">Chia {result.imposition.cutsPerParentSheet} ({result.imposition.printSheet.widthMm}x{result.imposition.printSheet.heightMm}mm)</strong> </div> <div> <span className="text-slate-500 block">Tổng giấy mẹ cần:</span> <strong className="text-rose-700 font-bold">{result.quantities.parentSheetsNeeded} tờ ({result.quantities.ramsNeeded} Ram / ~{result.quantities.kgNeeded} Kg)</strong> </div> </div> </div>
{/* KHÂU 2: MÁY IN OFFSET / KTS */} <div className="border border-slate-300 rounded p-3 mb-3 text-xs bg-blue-50/40"> <h3 className="font-bold text-slate-800 text-xs uppercase flex items-center gap-1.5 text-blue-900 mb-2"> <Check className="w-4 h-4 text-blue-600" /> Khâu 2: In Ấn Máy {result.chosenTech.toUpperCase()} </h3> <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-slate-700"> <div> <span className="text-slate-500 block">Số con / tờ in:</span> <strong className="text-blue-700 font-bold">{result.imposition.upsPerPrintSheet} con/tờ</strong> </div> <div> <span className="text-slate-500 block">Kiểu in & Màu:</span> <strong>{input.printSides === '2_side' ? 'In 2 mặt (CMYK)' : 'In 1 mặt'}</strong> </div> <div> <span className="text-slate-500 block">Tờ in thực tế (Net):</span> <strong>{result.quantities.netPrintSheets} tờ</strong> </div> <div> <span className="text-slate-500 block">Bù hao in + gia công:</span> <strong className="text-amber-700 font-bold">+{result.quantities.printWasteSheets + result.quantities.finishingWasteSheets} tờ</strong> </div> </div> <div className="mt-2 pt-2 border-t border-blue-200 flex justify-between font-bold text-blue-900"> <span>TỔNG TỜ IN BÀN GIAO THỢ MÁY:</span> <span className="text-sm text-rose-700">{result.quantities.totalPrintSheets} TỜ IN KHỔ {result.imposition.printSheet.widthMm}×{result.imposition.printSheet.heightMm}MM</span> </div> </div>
{/* KHÂU 3: GIA CÔNG SAU IN */} <div className="border border-slate-300 rounded p-3 text-xs"> <h3 className="font-bold text-slate-800 text-xs uppercase flex items-center gap-1.5 text-purple-900 mb-2"> <Check className="w-4 h-4 text-purple-600" /> Khâu 3: Danh Mục Gia Công Hoàn Thiện </h3> {result.costs.finishingDetails.length > 0 ? ( <table className="w-full text-left border border-slate-200"> <thead className="bg-slate-100 text-slate-700"> <tr> <th className="p-1.5">Công đoạn</th> <th className="p-1.5">Loại</th> <th className="p-1.5">Quy cách kỹ thuật</th> <th className="p-1.5 text-center">Ký nhận thợ</th> </tr> </thead> <tbody className="divide-y divide-slate-100"> {result.costs.finishingDetails.map((f, idx) => ( <tr key={idx}> <td className="p-1.5 font-bold text-slate-800">{f.name}</td> <td className="p-1.5 uppercase text-[10px] text-slate-500">{f.category}</td> <td className="p-1.5 text-slate-600">{f.formula}</td> <td className="p-1.5 text-center text-slate-300">__________</td> </tr> ))} </tbody> </table> ) : ( <p className="text-slate-500 italic">Chỉ xén đóng gói thành phẩm.</p> )} </div> </div>
{/* Chữ ký các bộ phận sản xuất */} <div className="grid grid-cols-4 gap-2 pt-6 text-[11px] text-center border-t border-slate-200"> <div> <span className="font-bold block">Ra Kẽm / File</span> <div className="h-12" /> </div> <div> <span className="font-bold block">Thợ Cắt Giấy</span> <div className="h-12" /> </div> <div> <span className="font-bold block">Thợ Máy In</span> <div className="h-12" /> </div> <div> <span className="font-bold block">Thợ Gia Công QC</span> <div className="h-12" /> </div> </div> </div> )} </div> </div> </div> </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202'use client';
import React, { useState, useEffect } from 'react';import { SystemSetting } from '@/types';import { Settings, Save, Check, RefreshCw, Building, Phone, Mail, CreditCard, FileText } from 'lucide-react';
export const SettingsManager: React.FC = () => { const [settings, setSettings] = useState<SystemSetting>({ companyName: '', companyAddress: '', companyPhone: '', companyEmail: '', bankAccount: '', bankName: '', quoteFooterNote: '', defaultProfitMargin: 25, defaultVatPercent: 8, }); const [loading, setLoading] = useState(true); const [saved, setSaved] = useState(false);
const fetchSettings = async () => { try { setLoading(true); const res = await fetch('/api/settings'); const data = await res.json(); setSettings(data); } catch (err) { console.error(err); } finally { setLoading(false); } };
useEffect(() => { fetchSettings(); }, []);
const handleSave = async (e: React.FormEvent) => { e.preventDefault(); try { const res = await fetch('/api/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(settings), }); if (res.ok) { setSaved(true); setTimeout(() => setSaved(false), 2500); } } catch (err) { console.error(err); } };
return ( <div className="max-w-3xl mx-auto bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden"> <div className="p-4 border-b border-slate-200 bg-slate-50 flex items-center justify-between"> <div className="flex items-center gap-2"> <Settings className="w-5 h-5 text-slate-700" /> <div> <h2 className="font-bold text-slate-800 text-sm">Cấu Hình Thông Tin Xưởng In & Mặc Định</h2> <p className="text-xs text-slate-500">Thông tin xuất hiện trên Phiếu Báo Giá gửi khách và Lệnh Sản Xuất</p> </div> </div> </div>
<form onSubmit={handleSave} className="p-6 space-y-4 text-xs"> {saved && ( <div className="p-3 bg-emerald-50 border border-emerald-200 rounded-lg text-emerald-800 flex items-center gap-2 font-medium"> <Check className="w-4 h-4 text-emerald-600" /> Đã lưu thông tin cấu hình hệ thống thành công! </div> )}
<div> <label className="block text-slate-700 font-semibold mb-1 flex items-center gap-1.5"> <Building className="w-3.5 h-3.5 text-blue-600" /> Tên Doanh Nghiệp / Xưởng In (Header Báo Giá) </label> <input type="text" required value={settings.companyName} onChange={(e) => setSettings({ ...settings, companyName: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div>
<div> <label className="block text-slate-700 font-semibold mb-1">Địa Chỉ Xưởng Sản Xuất</label> <input type="text" value={settings.companyAddress} onChange={(e) => setSettings({ ...settings, companyAddress: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div> <label className="block text-slate-700 font-semibold mb-1 flex items-center gap-1.5"> <Phone className="w-3.5 h-3.5 text-blue-600" /> Hotline / Điện Thoại </label> <input type="text" value={settings.companyPhone} onChange={(e) => setSettings({ ...settings, companyPhone: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div>
<div> <label className="block text-slate-700 font-semibold mb-1 flex items-center gap-1.5"> <Mail className="w-3.5 h-3.5 text-blue-600" /> Email Liên Hệ </label> <input type="email" value={settings.companyEmail} onChange={(e) => setSettings({ ...settings, companyEmail: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div> <label className="block text-slate-700 font-semibold mb-1 flex items-center gap-1.5"> <CreditCard className="w-3.5 h-3.5 text-blue-600" /> Số Tài Khoản & Chủ Tài Khoản </label> <input type="text" value={settings.bankAccount} onChange={(e) => setSettings({ ...settings, bankAccount: e.target.value })} placeholder="VD: 19038889999999 - CTK: PRINTCAL" className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div>
<div> <label className="block text-slate-700 font-semibold mb-1">Tên Ngân Hàng & Chi Nhánh</label> <input type="text" value={settings.bankName} onChange={(e) => setSettings({ ...settings, bankName: e.target.value })} placeholder="VD: Techcombank CN TP.HCM" className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div className="grid grid-cols-2 gap-4"> <div> <label className="block text-slate-700 font-semibold mb-1">Tỷ Lệ Lợi Nhuận Mặc Định (%)</label> <input type="number" value={settings.defaultProfitMargin} onChange={(e) => setSettings({ ...settings, defaultProfitMargin: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div>
<div> <label className="block text-slate-700 font-semibold mb-1">Thuế Suất VAT Mặc Định (%)</label> <input type="number" value={settings.defaultVatPercent} onChange={(e) => setSettings({ ...settings, defaultVatPercent: Number(e.target.value) })} className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500" /> </div> </div>
<div> <label className="block text-slate-700 font-semibold mb-1 flex items-center gap-1.5"> <FileText className="w-3.5 h-3.5 text-blue-600" /> Điều Khoản & Lưu Ý Báo Giá Khách Hàng </label> <textarea rows={4} value={settings.quoteFooterNote} onChange={(e) => setSettings({ ...settings, quoteFooterNote: e.target.value })} className="w-full border border-slate-300 rounded-lg p-2.5 focus:ring-1 focus:ring-blue-500 font-mono text-[11px]" /> </div>
<div className="flex justify-end pt-4 border-t border-slate-200"> <button type="submit" className="flex items-center gap-1.5 px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-semibold shadow transition-colors" > <Save className="w-4 h-4" /> Lưu Cài Đặt </button> </div> </form> </div> );};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287import { DatabaseSync } from 'node:sqlite';import path from 'node:path';import fs from 'node:fs';
const dataDir = path.join(process.cwd(), 'data');if (!fs.existsSync(dataDir)) { fs.mkdirSync(dataDir, { recursive: true });}
const dbPath = path.join(dataDir, 'printcal.db');let _db: DatabaseSync | null = null;
export function getDb(): DatabaseSync { if (!_db) { _db = new DatabaseSync(dbPath); _db.exec('PRAGMA journal_mode = WAL;'); _db.exec('PRAGMA foreign_keys = ON;'); initSchema(_db); } return _db;}
function initSchema(db: DatabaseSync) { db.exec(` CREATE TABLE IF NOT EXISTS paper_types ( id INTEGER PRIMARY KEY AUTOINCREMENT, code TEXT NOT NULL UNIQUE, name TEXT NOT NULL, gsm INTEGER NOT NULL, parent_width_cm REAL NOT NULL, parent_height_cm REAL NOT NULL, price_per_ram REAL NOT NULL, price_per_kg REAL NOT NULL, unit TEXT NOT NULL DEFAULT 'ram', description TEXT, is_active INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP );
CREATE TABLE IF NOT EXISTS offset_machines ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, max_width_mm REAL NOT NULL, max_height_mm REAL NOT NULL, min_width_mm REAL NOT NULL, min_height_mm REAL NOT NULL, plate_price REAL NOT NULL, setup_cost REAL NOT NULL, step_cost REAL NOT NULL, default_waste_sheets INTEGER NOT NULL, gripper_margin_mm REAL NOT NULL DEFAULT 10, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP );
CREATE TABLE IF NOT EXISTS digital_machines ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, max_width_mm REAL NOT NULL, max_height_mm REAL NOT NULL, click_a4_1side REAL NOT NULL, click_a4_2side REAL NOT NULL, click_a3_1side REAL NOT NULL, click_a3_2side REAL NOT NULL, default_waste_sheets INTEGER NOT NULL DEFAULT 3, min_charge REAL NOT NULL DEFAULT 20000, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP );
CREATE TABLE IF NOT EXISTS finishing_services ( id INTEGER PRIMARY KEY AUTOINCREMENT, code TEXT NOT NULL UNIQUE, name TEXT NOT NULL, category TEXT NOT NULL, calc_type TEXT NOT NULL, unit_price REAL NOT NULL, min_price REAL NOT NULL DEFAULT 0, setup_fee REAL NOT NULL DEFAULT 0, waste_percent REAL NOT NULL DEFAULT 0, waste_sheets INTEGER NOT NULL DEFAULT 0, is_active INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP );
CREATE TABLE IF NOT EXISTS customers ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, phone TEXT NOT NULL, email TEXT, company TEXT, address TEXT, notes TEXT, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP );
CREATE TABLE IF NOT EXISTS quotes_orders ( id INTEGER PRIMARY KEY AUTOINCREMENT, code TEXT NOT NULL UNIQUE, customer_id INTEGER, customer_name TEXT NOT NULL, customer_phone TEXT NOT NULL, customer_email TEXT, customer_company TEXT, job_name TEXT NOT NULL, product_type TEXT NOT NULL, print_tech TEXT NOT NULL, quantity INTEGER NOT NULL, width_mm REAL NOT NULL, height_mm REAL NOT NULL, pages INTEGER NOT NULL DEFAULT 2, paper_name TEXT NOT NULL, paper_gsm INTEGER NOT NULL, parent_size TEXT NOT NULL, print_size TEXT NOT NULL, ups_per_sheet INTEGER NOT NULL, total_print_sheets INTEGER NOT NULL, total_parent_sheets INTEGER NOT NULL, paper_cost REAL NOT NULL, print_cost REAL NOT NULL, finishing_cost REAL NOT NULL, total_cost REAL NOT NULL, profit_margin_percent REAL NOT NULL, profit_amount REAL NOT NULL, discount_amount REAL NOT NULL DEFAULT 0, vat_percent REAL NOT NULL DEFAULT 0, vat_amount REAL NOT NULL DEFAULT 0, final_price REAL NOT NULL, unit_price REAL NOT NULL, status TEXT NOT NULL DEFAULT 'quote', notes TEXT, spec_json TEXT, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE SET NULL );
CREATE TABLE IF NOT EXISTS system_settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); `);
// Seed default data if empty seedDefaultData(db);}
function seedDefaultData(db: DatabaseSync) { const paperCount = db.prepare('SELECT COUNT(*) as cnt FROM paper_types').get() as { cnt: number }; if (paperCount.cnt === 0) { const insertPaper = db.prepare(` INSERT INTO paper_types (code, name, gsm, parent_width_cm, parent_height_cm, price_per_ram, price_per_kg, unit, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `);
// Standard Vietnamese paper inventory const papers = [ // Giấy Couche (C) ['C100_65x86', 'Couche 100gsm (65x86)', 100, 65, 86, 320000, 28000, 'ram', 'In tờ rơi mỏng, ruột catalogue, kẹp file'], ['C150_65x86', 'Couche 150gsm (65x86)', 150, 65, 86, 480000, 28500, 'ram', 'Giấy chuẩn in tờ rơi, brochure, ruột catalogue'], ['C150_79x109', 'Couche 150gsm (79x109)', 150, 79, 109, 740000, 28500, 'ram', 'Giấy tờ lớn in tờ rơi, brochure số lượng lớn'], ['C200_65x86', 'Couche 200gsm (65x86)', 200, 65, 86, 640000, 29000, 'ram', 'In bìa catalogue, tờ gấp cao cấp, poster nhỏ'], ['C250_65x86', 'Couche 250gsm (65x86)', 250, 65, 86, 800000, 29000, 'ram', 'In kẹp file, bìa sách, thẻ treo, tag bài'], ['C300_65x86', 'Couche 300gsm (65x86)', 300, 65, 86, 960000, 29000, 'ram', 'In namecard, bìa catalogue dày, thẻ bài, hộp nhẹ'], ['C300_79x109', 'Couche 300gsm (79x109)', 300, 79, 109, 1480000, 29000, 'ram', 'In kẹp file, folder, namecard khổ lớn ghép bài'],
// Giấy Bristol (B) ['B250_65x86', 'Bristol 250gsm (65x86)', 250, 65, 86, 850000, 31000, 'ram', 'Xốp, dày, thích hợp in thiệp, bìa hồ sơ, namecard'], ['B300_65x86', 'Bristol 300gsm (65x86)', 300, 65, 86, 1020000, 31000, 'ram', 'Dày cứng in hộp giấy thuốc, mỹ phẩm, thiệp cưới'],
// Giấy Ivory (I) - Chuyên bao bì hộp ['I250_79x109', 'Ivory 250gsm (79x109)', 250, 79, 109, 1350000, 31500, 'ram', 'Mặt trắng bóng, mặt sau nhám, in hộp dược phẩm, thức ăn'], ['I300_79x109', 'Ivory 300gsm (79x109)', 300, 79, 109, 1620000, 31500, 'ram', 'In hộp mỹ phẩm, túi giấy cao cấp, hộp quà tặng'], ['I350_79x109', 'Ivory 350gsm (79x109)', 350, 79, 109, 1890000, 31500, 'ram', 'Hộp cứng, túi giấy chịu lực tốt, khay giấy'],
// Giấy Ford (F) / Woodfree ['F80_65x86', 'Ford 80gsm (65x86)', 80, 65, 86, 260000, 29000, 'ram', 'In phong bì, tiêu đề thư, ruột sổ tay, giấy note'], ['F100_65x86', 'Ford 100gsm (65x86)', 100, 65, 86, 325000, 29000, 'ram', 'In bao thư lớn A4, biểu mẫu, hóa đơn, tài liệu họp'], ['F120_65x86', 'Ford 120gsm (65x86)', 120, 65, 86, 390000, 29000, 'ram', 'Bao thư cao cấp, sổ tay'],
// Giấy Kraft (Bao bì xi măng tái chế) ['K170_79x109', 'Kraft Nâu 170gsm (79x109)', 170, 79, 109, 820000, 28000, 'ram', 'Túi giấy kraft cà phê, shop quần áo eco'], ['K250_79x109', 'Kraft Nâu 250gsm (79x109)', 250, 79, 109, 1200000, 28000, 'ram', 'In hộp kraft takeaway, tag quần áo vintage'],
// Giấy Decal ['DECAL_GIAY_CAM', 'Decal Giấy Kham Vàng/Đế Trắng (A3+ 33x48)', 135, 33, 48, 550000, 0, 'ram', 'In nhãn dán chai lọ, sticker tem vỡ, mã vạch'], ['DECAL_NHUA_SUA', 'Decal Nhựa Sữa PVC (33x48)', 150, 33, 48, 1200000, 0, 'ram', 'Chống nước xé không rách dán ly trà sữa, đông lạnh'] ];
for (const p of papers) { insertPaper.run(...p); } }
const offsetCount = db.prepare('SELECT COUNT(*) as cnt FROM offset_machines').get() as { cnt: number }; if (offsetCount.cnt === 0) { const insertOffset = db.prepare(` INSERT INTO offset_machines (name, max_width_mm, max_height_mm, min_width_mm, min_height_mm, plate_price, setup_cost, step_cost, default_waste_sheets, gripper_margin_mm) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `);
// Common offset press formats in Vietnam insertOffset.run('Máy Offset 4 màu Khổ 39x54 (1/4 khổ 79x109)', 540, 390, 210, 297, 75000, 450000, 160000, 80, 10); insertOffset.run('Máy Offset 4 màu Khổ 54x79 (1/2 khổ 79x109)', 790, 540, 390, 540, 120000, 650000, 220000, 100, 10); insertOffset.run('Máy Offset 4 màu Khổ 65x86 (Máy lớn)', 860, 650, 430, 650, 150000, 850000, 280000, 120, 12); }
const digitalCount = db.prepare('SELECT COUNT(*) as cnt FROM digital_machines').get() as { cnt: number }; if (digitalCount.cnt === 0) { const insertDigital = db.prepare(` INSERT INTO digital_machines (name, max_width_mm, max_height_mm, click_a4_1side, click_a4_2side, click_a3_1side, click_a3_2side, default_waste_sheets, min_charge) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `);
insertDigital.run('Máy In Nhanh KTS Konica / Ricoh Pro (Khổ A3+ 33x48)', 488, 330, 1200, 2200, 2400, 4200, 3, 20000); insertDigital.run('Máy In Nhanh Fuji Xerox Versant 3100 (Cao Cấp)', 660, 330, 1500, 2800, 3000, 5400, 3, 30000); }
const finishingCount = db.prepare('SELECT COUNT(*) as cnt FROM finishing_services').get() as { cnt: number }; if (finishingCount.cnt === 0) { const insertFinishing = db.prepare(` INSERT INTO finishing_services (code, name, category, calc_type, unit_price, min_price, setup_fee, waste_percent, waste_sheets, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `);
const finishings = [ // Cán màng (per_m2) ['CAN_MANG_MO', 'Cán màng mờ nhiệt', 'can_mang', 'per_m2', 850, 80000, 0, 1.5, 10, 1], ['CAN_MANG_BONG', 'Cán màng bóng nhiệt', 'can_mang', 'per_m2', 800, 80000, 0, 1.5, 10, 1], ['CAN_MANG_METALIZE', 'Cán màng Metalize bạc/vàng', 'can_mang', 'per_m2', 3500, 250000, 0, 2.5, 20, 1],
// Cắt bế định hình (die_cut) ['BE_THANH_PHAM', 'Làm khuôn bế & Công bế hộp/túi/thẻ', 'be', 'die_cut', 150, 150000, 220000, 2.0, 30, 1], ['BE_DEMI_DECAL', 'Bế demi decal tem nhãn (đứt decal)', 'be', 'die_cut', 120, 120000, 180000, 1.5, 15, 1],
// Cấn & Gấp (per_product) ['CAN_GAP_1_DUONG', 'Cấn 1 đường & Gấp đôi (Flyer)', 'can_gap', 'per_product', 80, 50000, 0, 0.5, 10, 1], ['CAN_GAP_2_DUONG', 'Cấn 2 đường & Gấp 3 (Brochure ziczac/lồng)', 'can_gap', 'per_product', 140, 70000, 0, 1.0, 15, 1],
// Ép kim & Dập nổi (ep_kim) ['EP_KIM_LOGO', 'Ép kim nhũ vàng/bạc logo (khuôn kẽm)', 'ep_kim', 'per_product', 200, 150000, 180000, 2.0, 25, 1], ['DAP_NOI_LOGO', 'Dập nổi/dập chìm logo (nổi khối 3D)', 'ep_kim', 'per_product', 180, 150000, 160000, 1.5, 20, 1],
// Phủ UV (phu_uv) ['PHU_UV_DINH_HINH', 'Phủ UV định hình (Spot UV)', 'phu_uv', 'per_product', 350, 250000, 200000, 2.0, 30, 1],
// Cắt xén (fixed) ['XEN_THANH_PHAM', 'Xén thành phẩm đóng gói', 'khac', 'fixed', 30000, 30000, 0, 0.2, 5, 1], ['BO_GOC_NAMECARD', 'Bo 4 góc (Namecard/Thẻ tích điểm)', 'khac', 'per_product', 50, 40000, 0, 0.5, 5, 1],
// Đóng cuốn & Dán (dong_cuon / dan) ['DONG_GHIM_LONG', 'Đóng 2 ghim lồng giữa (Tạp chí, catalogue)', 'dong_cuon', 'per_product', 350, 80000, 0, 1.0, 10, 1], ['DAN_GAY_KEO_NHIET', 'Dán keo nhiệt gáy sách vuông vắn', 'dong_cuon', 'per_product', 2500, 200000, 0, 1.5, 15, 1], ['DONG_LO_XO', 'Đóng gáy lò xo kẽm trắng/đen', 'dong_cuon', 'per_product', 4000, 150000, 0, 1.0, 10, 1], ['DAN_HOP_TU_DONG', 'Dán dính mép hộp giấy', 'dan', 'per_product', 250, 150000, 0, 1.0, 20, 1], ['DAN_DAY_TUI_GIAY', 'Gấp dán túi giấy & Xỏ dây quai dù', 'dan', 'per_product', 1500, 300000, 0, 1.5, 25, 1] ];
for (const f of finishings) { insertFinishing.run(...f); } }
const customerCount = db.prepare('SELECT COUNT(*) as cnt FROM customers').get() as { cnt: number }; if (customerCount.cnt === 0) { const insertCustomer = db.prepare(` INSERT INTO customers (name, phone, email, company, address, notes) VALUES (?, ?, ?, ?, ?, ?) `);
insertCustomer.run('Anh Tuấn', '0912345678', 'tuan@vinatech.com', 'Công ty TNHH VinaTech', '123 Cầu Giấy, Hà Nội', 'Khách hàng thường xuyên in catalogue và tờ rơi'); insertCustomer.run('Chị Lan', '0987654321', 'lan@beautycosmetics.vn', 'Mỹ Phẩm Trúc Lan', '456 Lê Lợi, Q.1, TP.HCM', 'Đặt in hộp mỹ phẩm và túi giấy Ivory'); insertCustomer.run('Anh Hùng', '0903112233', 'hung@hungphat.vn', 'Hùng Phát Food', '789 Tân Bình, TP.HCM', 'Chuyên in decal tem nhãn số lượng lớn'); }
const settingsCount = db.prepare('SELECT COUNT(*) as cnt FROM system_settings').get() as { cnt: number }; if (settingsCount.cnt === 0) { const insertSetting = db.prepare(`INSERT INTO system_settings (key, value) VALUES (?, ?)`); insertSetting.run('companyName', 'XƯỞNG IN ẤN & THIẾT KẾ PRINTCAL'); insertSetting.run('companyAddress', 'Tòa nhà PrintCal, Số 123 Đường In Ấn, TP.HCM'); insertSetting.run('companyPhone', '0900.888.999 - 028.3888.9999'); insertSetting.run('companyEmail', 'baogia@printcal.vn'); insertSetting.run('bankAccount', '19038889999999 - Techcombank (CN TP.HCM) - CTK: PRINTCAL VIETNAM'); insertSetting.run('bankName', 'Techcombank Chi nhánh TP.HCM'); insertSetting.run('quoteFooterNote', '1. Báo giá có hiệu lực trong vòng 15 ngày.\n2. Giá trên chưa bao gồm phí vận chuyển ngoại tỉnh.\n3. Thời gian giao hàng tính từ lúc duyệt bản in mẫu và đặt cọc 50%.\n4. Đảm bảo chất lượng màu sắc chuẩn theo file thiết kế.'); insertSetting.run('defaultProfitMargin', '25'); insertSetting.run('defaultVatPercent', '8'); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413import { CalculationInput, CalculationResult, ComparisonItem, DigitalMachine, FinishingCostDetail, FinishingService, OffsetMachine, PaperType,} from '@/types';import { calculateImposition } from './imposition';
interface CostCalculatorOptions { input: CalculationInput; paperType: PaperType; offsetMachine?: OffsetMachine; digitalMachine?: DigitalMachine; allFinishingServices: FinishingService[];}
export function calculatePrintCost({ input, paperType, offsetMachine, digitalMachine, allFinishingServices,}: CostCalculatorOptions): CalculationResult { // 1. Xác định công nghệ in mục tiêu let chosenTech: 'offset' | 'digital' = 'offset'; if (input.printTech === 'digital') { chosenTech = 'digital'; } else if (input.printTech === 'offset') { chosenTech = 'offset'; } else { // Tự động: số lượng < 300 con thường in nhanh rẻ hơn, >= 300 in offset rẻ hơn chosenTech = input.quantity < 300 ? 'digital' : 'offset'; }
// 2. Tính bình trang & số con const preferredSheet = chosenTech === 'offset' && offsetMachine ? { widthMm: offsetMachine.maxWidthMm, heightMm: offsetMachine.maxHeightMm, name: offsetMachine.name } : undefined;
const imposition = calculateImposition({ widthMm: input.widthMm, heightMm: input.heightMm, bleedMm: input.bleedMm ?? 2, paperType, printTech: chosenTech, preferredMachineSheet: preferredSheet, gripperMarginMm: offsetMachine?.gripperMarginMm ?? 10, });
const ups = Math.max(1, imposition.upsPerPrintSheet); const netPrintSheets = Math.ceil(input.quantity / ups);
// 3. Tính bù hao gia công let finishingWasteSheets = 0; let totalFinishingWastePercent = 0; const activeFinishingDetails: FinishingCostDetail[] = [];
for (const sel of input.selectedFinishing) { const service = allFinishingServices.find((s) => s.id === sel.serviceId); if (!service) continue;
totalFinishingWastePercent += service.wastePercent; finishingWasteSheets += service.wasteSheets;
// Tính chi phí từng mục gia công let subtotal = 0; let formula = ''; const sides = sel.sides || 1;
if (service.calcType === 'per_m2') { // Tính theo m2 sản phẩm hoặc m2 tờ in const areaM2 = ((input.widthMm + (input.bleedMm || 2) * 2) / 1000) * ((input.heightMm + (input.bleedMm || 2) * 2) / 1000) * input.quantity * sides; const rawCost = areaM2 * service.unitPrice; subtotal = Math.max(service.minPrice, Math.round(rawCost)) + service.setupFee; formula = `${areaM2.toFixed(2)} m² × ${service.unitPrice.toLocaleString('vi-VN')}đ (tối thiểu ${service.minPrice.toLocaleString('vi-VN')}đ)`; } else if (service.calcType === 'die_cut') { const runCost = input.quantity * service.unitPrice; subtotal = Math.max(service.minPrice, runCost) + service.setupFee; formula = `Khuôn bế ${service.setupFee.toLocaleString('vi-VN')}đ + Công bế (${input.quantity} con × ${service.unitPrice}đ)`; } else if (service.calcType === 'per_product') { const rawCost = input.quantity * service.unitPrice; subtotal = Math.max(service.minPrice, rawCost) + service.setupFee; formula = `${input.quantity} con × ${service.unitPrice.toLocaleString('vi-VN')}đ`; } else if (service.calcType === 'per_sheet') { const rawCost = netPrintSheets * service.unitPrice; subtotal = Math.max(service.minPrice, rawCost) + service.setupFee; formula = `${netPrintSheets} tờ in × ${service.unitPrice.toLocaleString('vi-VN')}đ`; } else { // Fixed subtotal = service.unitPrice + service.setupFee; formula = `Trọn gói ${service.unitPrice.toLocaleString('vi-VN')}đ`; }
activeFinishingDetails.push({ serviceId: service.id, name: service.name, category: service.category, calcType: service.calcType, quantity: input.quantity, unitPrice: service.unitPrice, setupFee: service.setupFee, subtotal, wasteSheets: service.wasteSheets, formula, }); }
// Bù hao gia công theo % finishingWasteSheets += Math.ceil((netPrintSheets * totalFinishingWastePercent) / 100);
// 4. Bù hao in ấn & Tổng số tờ in let printWasteSheets = 0; if (chosenTech === 'offset') { printWasteSheets = offsetMachine?.defaultWasteSheets ?? 100; } else { printWasteSheets = digitalMachine?.defaultWasteSheets ?? 4; }
const totalPrintSheets = netPrintSheets + printWasteSheets + finishingWasteSheets; const cuts = Math.max(1, imposition.cutsPerParentSheet); const parentSheetsNeeded = Math.ceil(totalPrintSheets / cuts); const ramsNeeded = Math.round((parentSheetsNeeded / 500) * 100) / 100;
// Tính kg giấy = Số tờ lớn * Dài (m) * Rộng (m) * (gsm / 1000) const parentAreaM2 = (paperType.parentWidthCm / 100) * (paperType.parentHeightCm / 100); const kgNeeded = Math.round(((parentSheetsNeeded * parentAreaM2 * paperType.gsm) / 1000) * 10) / 10;
// 5. Tiền giấy let paperCost = 0; if (paperType.unit === 'kg' && paperType.pricePerKg > 0) { paperCost = Math.round(kgNeeded * paperType.pricePerKg); } else { // Tính theo ram quy đổi tờ paperCost = Math.round(parentSheetsNeeded * (paperType.pricePerRam / 500)); }
// 6. Tiền in ấn let plateCost = 0; let platesCount = 0; let printRunCost = 0;
if (chosenTech === 'offset') { const machine = offsetMachine || { platePrice: 80000, setupCost: 450000, stepCost: 160000, };
const is2Sides = input.printSides === '2_side'; const workType = input.offsetWorkType || 'self_turn';
if (!is2Sides) { // In 1 mặt: 1 bộ kẽm platesCount = input.colorsFront || 4; plateCost = platesCount * machine.platePrice;
const impressions = totalPrintSheets; if (impressions <= 1000) { printRunCost = machine.setupCost; } else { const extraThousands = Math.ceil((impressions - 1000) / 1000); printRunCost = machine.setupCost + extraThousands * machine.stepCost; } } else { // In 2 mặt if (workType === 'sheetwise') { // 2 bộ kẽm riêng biệt platesCount = (input.colorsFront || 4) + (input.colorsBack || 4); plateCost = platesCount * machine.platePrice;
// 2 ca in độc lập const impressionsPerSide = totalPrintSheets; const costSide1 = impressionsPerSide <= 1000 ? machine.setupCost : machine.setupCost + Math.ceil((impressionsPerSide - 1000) / 1000) * machine.stepCost; const costSide2 = impressionsPerSide <= 1000 ? machine.setupCost : machine.setupCost + Math.ceil((impressionsPerSide - 1000) / 1000) * machine.stepCost; printRunCost = costSide1 + costSide2; } else { // Tự trở (Work & Turn) hoặc Trở nhíp (Tumble): Dùng 1 bộ kẽm ghép cả 2 mặt platesCount = Math.max(input.colorsFront || 4, input.colorsBack || 4); plateCost = platesCount * machine.platePrice;
// Chạy 2 lượt in (lượt ép x 2) const totalImpressions = totalPrintSheets * 2; if (totalImpressions <= 1000) { printRunCost = machine.setupCost; } else { const extraThousands = Math.ceil((totalImpressions - 1000) / 1000); printRunCost = machine.setupCost + extraThousands * machine.stepCost; } } } } else { // In nhanh kỹ thuật số const machine = digitalMachine || { clickA41Side: 1200, clickA42Side: 2200, clickA31Side: 2400, clickA32Side: 4200, minCharge: 20000, };
const is2Sides = input.printSides === '2_side'; // Đánh giá khổ in của Digital: Nếu khổ in > A4 thì tính click A3, ngược lại click A4 const isA3 = imposition.printSheet.widthMm > 220 || imposition.printSheet.heightMm > 310;
let clickRate = 0; if (isA3) { clickRate = is2Sides ? machine.clickA32Side : machine.clickA31Side; } else { clickRate = is2Sides ? machine.clickA42Side : machine.clickA41Side; }
// Giảm giá theo bậc thang số lượng in nhanh let volumeDiscountFactor = 1.0; if (totalPrintSheets > 500) { volumeDiscountFactor = 0.75; // Giảm 25% cho đơn > 500 tờ A3 } else if (totalPrintSheets > 200) { volumeDiscountFactor = 0.85; // Giảm 15% } else if (totalPrintSheets > 50) { volumeDiscountFactor = 0.92; // Giảm 8% }
const calculatedClick = Math.round(totalPrintSheets * clickRate * volumeDiscountFactor); printRunCost = Math.max(machine.minCharge, calculatedClick); plateCost = 0; platesCount = 0; }
const totalPrintCost = plateCost + printRunCost; const totalFinishingCost = activeFinishingDetails.reduce((sum, item) => sum + item.subtotal, 0);
// 7. Tổng chi phí cơ sở & Giá bán const totalBaseCost = paperCost + totalPrintCost + totalFinishingCost; const profitMarginPercent = input.profitMarginPercent ?? 25; const profitAmount = Math.round((totalBaseCost * profitMarginPercent) / 100); const discountAmount = input.discountAmount ?? 0; const preTaxTotal = Math.max(0, totalBaseCost + profitAmount - discountAmount); const vatPercent = input.vatPercent ?? 0; const vatAmount = Math.round((preTaxTotal * vatPercent) / 100); const finalPrice = preTaxTotal + vatAmount; const unitPrice = input.quantity > 0 ? Math.round(finalPrice / input.quantity) : 0;
// 8. Thuật toán So sánh In Nhanh vs In Offset & Tìm điểm hòa vốn const comparisonTable: ComparisonItem[] = []; const testQuantities = [50, 100, 200, 300, 500, 1000, 2000, 5000];
for (const qty of testQuantities) { // Tính thử chi phí digital const digResult = runQuickEstimate({ ...input, quantity: qty, printTech: 'digital', }, paperType, offsetMachine, digitalMachine, allFinishingServices);
// Tính thử chi phí offset const offResult = runQuickEstimate({ ...input, quantity: qty, printTech: 'offset', }, paperType, offsetMachine, digitalMachine, allFinishingServices);
comparisonTable.push({ quantity: qty, digitalTotal: digResult.finalPrice, digitalUnit: digResult.unitPrice, offsetTotal: offResult.finalPrice, offsetUnit: offResult.unitPrice, recommended: digResult.finalPrice <= offResult.finalPrice ? 'digital' : 'offset', }); }
// Điểm hòa vốn (Break-even): Tìm mốc số lượng mà offset bắt đầu rẻ hơn digital let breakEvenQty = 300; for (let i = 0; i < comparisonTable.length - 1; i++) { if (comparisonTable[i].recommended === 'digital' && comparisonTable[i + 1].recommended === 'offset') { breakEvenQty = Math.round((comparisonTable[i].quantity + comparisonTable[i + 1].quantity) / 2); break; } }
// Tính lại cho số lượng hiện tại nếu người dùng chọn 'auto' const curDigital = runQuickEstimate({ ...input, printTech: 'digital' }, paperType, offsetMachine, digitalMachine, allFinishingServices); const curOffset = runQuickEstimate({ ...input, printTech: 'offset' }, paperType, offsetMachine, digitalMachine, allFinishingServices);
let recommendationText = ''; const diff = Math.abs(curDigital.finalPrice - curOffset.finalPrice);
if (curDigital.finalPrice < curOffset.finalPrice) { recommendationText = `Với số lượng ${input.quantity} sản phẩm, In Nhanh (Kỹ thuật số) rẻ hơn In Offset ${diff.toLocaleString('vi-VN')}đ (${Math.round((diff / curOffset.finalPrice) * 100)}%), không tốn tiền xuất kẽm CTP, lấy ngay trong ngày.`; } else { recommendationText = `Với số lượng ${input.quantity} sản phẩm, In Offset rẻ hơn In Nhanh ${diff.toLocaleString('vi-VN')}đ (${Math.round((diff / curDigital.finalPrice) * 100)}%), tối ưu chi phí tối đa cho số lượng công nghiệp lớn.`; }
return { imposition, quantities: { productQty: input.quantity, netPrintSheets, printWasteSheets, finishingWasteSheets, totalPrintSheets, parentSheetsNeeded, ramsNeeded, kgNeeded, }, costs: { paperCost, plateCost, platesCount, printRunCost, totalPrintCost, finishingCost: totalFinishingCost, finishingDetails: activeFinishingDetails, totalBaseCost, profitAmount, preTaxTotal, discountAmount, vatAmount, finalPrice, unitPrice, }, chosenTech, recommendation: { bestTech: curDigital.finalPrice <= curOffset.finalPrice ? 'digital' : 'offset', reason: recommendationText, digitalTotal: curDigital.finalPrice, offsetTotal: curOffset.finalPrice, difference: diff, breakEvenQty, comparisonTable, }, };}
// Hàm tính nhanh phục vụ bảng so sánh (tránh đệ quy)function runQuickEstimate( input: CalculationInput, paperType: PaperType, offsetMachine?: OffsetMachine, digitalMachine?: DigitalMachine, allFinishingServices: FinishingService[] = []): { finalPrice: number; unitPrice: number } { const isDigital = input.printTech === 'digital'; const preferredSheet = !isDigital && offsetMachine ? { widthMm: offsetMachine.maxWidthMm, heightMm: offsetMachine.maxHeightMm, name: offsetMachine.name } : undefined;
const imposition = calculateImposition({ widthMm: input.widthMm, heightMm: input.heightMm, bleedMm: input.bleedMm ?? 2, paperType, printTech: input.printTech, preferredMachineSheet: preferredSheet, });
const ups = Math.max(1, imposition.upsPerPrintSheet); const netSheets = Math.ceil(input.quantity / ups); const printWaste = isDigital ? 4 : (offsetMachine?.defaultWasteSheets ?? 100); const totalSheets = netSheets + printWaste + 20;
const cuts = Math.max(1, imposition.cutsPerParentSheet); const parentSheets = Math.ceil(totalSheets / cuts); const paperCost = Math.round(parentSheets * (paperType.pricePerRam / 500));
let printCost = 0; if (isDigital) { const isA3 = imposition.printSheet.widthMm > 220 || imposition.printSheet.heightMm > 310; const rate = isA3 ? (input.printSides === '2_side' ? 4200 : 2400) : (input.printSides === '2_side' ? 2200 : 1200); printCost = Math.max(20000, totalSheets * rate); } else { const machine = offsetMachine || { platePrice: 80000, setupCost: 450000, stepCost: 160000 }; const plates = input.printSides === '2_side' ? 4 : 4; // giả định tự trở const platePrice = plates * machine.platePrice; const impressions = input.printSides === '2_side' ? totalSheets * 2 : totalSheets; const runPrice = impressions <= 1000 ? machine.setupCost : machine.setupCost + Math.ceil((impressions - 1000) / 1000) * machine.stepCost; printCost = platePrice + runPrice; }
// Ước tính gia công cơ bản let finishingCost = 0; for (const sel of input.selectedFinishing) { const service = allFinishingServices.find((s) => s.id === sel.serviceId); if (service) { if (service.calcType === 'per_m2') { const area = ((input.widthMm + 4) / 1000) * ((input.heightMm + 4) / 1000) * input.quantity * (sel.sides || 1); finishingCost += Math.max(service.minPrice, Math.round(area * service.unitPrice)) + service.setupFee; } else { finishingCost += Math.max(service.minPrice, input.quantity * service.unitPrice) + service.setupFee; } } }
const baseCost = paperCost + printCost + finishingCost; const margin = input.profitMarginPercent ?? 25; const finalPrice = Math.round(baseCost * (1 + margin / 100)); const unitPrice = input.quantity > 0 ? Math.round(finalPrice / input.quantity) : 0;
return { finalPrice, unitPrice };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242import { BoxCoordinate, ImpositionResult, PaperType, PrintTech } from '@/types';
interface ImpositionOptions { widthMm: number; heightMm: number; bleedMm?: number; paperType: PaperType; printTech: PrintTech; preferredMachineSheet?: { widthMm: number; heightMm: number; name: string }; gripperMarginMm?: number;}
export function calculateImposition({ widthMm, heightMm, bleedMm = 2, paperType, printTech, 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;
// 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; }[] = [];
if (preferredMachineSheet) { // Máy in cụ thể được chọn const cuts = calculateCutsFromParent(parentW_mm, parentH_mm, preferredMachineSheet.widthMm, preferredMachineSheet.heightMm); candidatePrintSheets.push({ name: preferredMachineSheet.name, widthMm: preferredMachineSheet.widthMm, heightMm: preferredMachineSheet.heightMm, cutsFromParent: cuts, }); } 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 }, ]; } else { // In Offset: tính các phương án chia khổ giấy mẹ (chia 2, chia 4, chia 6, chia 8) // 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, });
// Trường hợp 2: Chia 2 (vd 79x109 -> 2 tờ 545 x 790 mm) const cut2_w = Math.floor(parentW_mm / 2); const cut2_h = parentH_mm; candidatePrintSheets.push({ name: `Khổ chia 2 (${cut2_w} x ${cut2_h} mm)`, widthMm: cut2_w, heightMm: cut2_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, cutsFromParent: 8, }); }
// Đá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; ups: number; cols: number; rows: number; isRotated: boolean; boxes: BoxCoordinate[]; efficiency: number; usableW: number; 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, }; } }
// 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, ups: 1, cols: 1, rows: 1, isRotated: false, boxes: [{ x: 10, y: gripperMarginMm + 5, w: itemW, h: itemH, index: 1 }], efficiency: 10, usableW: fallbackSheet.widthMm, usableH: fallbackSheet.heightMm, }; }
return { parentSheet: { widthCm: paperType.parentWidthCm, heightCm: paperType.parentHeightCm, name: `${paperType.name} (${paperType.parentWidthCm}x${paperType.parentHeightCm}cm)`, }, printSheet: { widthMm: bestResult.printSheet.widthMm, heightMm: bestResult.printSheet.heightMm, name: bestResult.printSheet.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, };}
// 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
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); const ups1 = cols1 * rows1;
// Cách 2: Xếp xoay 90 độ const cols2 = Math.floor(usableW / itemH); const rows2 = Math.floor(usableH / itemW); const ups2 = cols2 * rows2;
const isRotated = ups2 > ups1; const bestCols = isRotated ? cols2 : cols1; const bestRows = isRotated ? rows2 : rows1; const bestUps = isRotated ? ups2 : ups1; 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)
let idx = 1; for (let r = 0; r < bestRows; r++) { for (let c = 0; c < bestCols; c++) { boxes.push({ index: idx++, x: Math.round((startX + c * boxW) * 10) / 10, y: Math.round((startY + r * boxH) * 10) / 10, w: boxW, h: boxH, }); } }
const itemArea = itemW * itemH * bestUps; const sheetArea = sheetW * sheetH; const efficiency = sheetArea > 0 ? (itemArea / sheetArea) * 100 : 0;
return { ups: bestUps, cols: bestCols, rows: bestRows, isRotated, boxes, efficiency, usableW, usableH, };}
// Tính số tờ in có thể cắt ra từ tờ giấy mẹ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);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246export type PrintTech = 'offset' | 'digital' | 'auto';export type ProductType = 'to_roi' | 'namecard' | 'catalogue' | 'hop_giay' | 'tui_giay' | 'decal' | 'khac';export type OffsetWorkType = 'self_turn' | 'sheetwise' | 'tumble'; // Tự trở, In 2 bài, Trở nhípexport type OrderStatus = 'quote' | 'approved' | 'printing' | 'finishing' | 'completed' | 'delivered' | 'cancelled';
export interface PaperType { id: number; code: string; name: string; gsm: number; parentWidthCm: number; parentHeightCm: number; pricePerRam: number; pricePerKg: number; unit: 'ram' | 'kg'; description?: string; isActive: boolean;}
export interface OffsetMachine { id: number; name: string; maxWidthMm: number; maxHeightMm: number; minWidthMm: number; minHeightMm: number; platePrice: number; // Giá kẽm CTP / lá setupCost: number; // Phí mở máy in (<1000 lượt ép) stepCost: number; // Đơn giá mỗi 1000 lượt tiếp theo defaultWasteSheets: number; // Bù hao canh màu chuẩn (ví dụ 100 tờ) gripperMarginMm: number; // Lề kẹp nhíp (10-12mm)}
export interface DigitalMachine { id: number; name: string; maxWidthMm: number; maxHeightMm: number; clickA41Side: number; // Đơn giá in A4 1 mặt clickA42Side: number; // Đơn giá in A4 2 mặt clickA31Side: number; // Đơn giá in A3/A3+ 1 mặt clickA32Side: number; // Đơn giá in A3/A3+ 2 mặt defaultWasteSheets: number; // Bù hao giấy (3-5 tờ) minCharge: number; // Đơn giá tối thiểu 1 lần in}
export interface FinishingService { id: number; code: string; name: string; category: 'can_mang' | 'can_gap' | 'be' | 'ep_kim' | 'phu_uv' | 'dong_cuon' | 'dan' | 'khac'; calcType: 'per_m2' | 'per_sheet' | 'per_product' | 'fixed' | 'die_cut'; unitPrice: number; minPrice: number; // Giá tối thiểu mở máy setupFee: number; // Tiền làm khuôn (khuôn bế, khuôn ép kim...) wastePercent: number; // % bù hao (vd: 2%) wasteSheets: number; // Số tờ bù hao cố định isActive: boolean;}
export interface Customer { id: number; name: string; phone: string; email?: string; company?: string; address?: string; notes?: string; createdAt?: string;}
export interface SelectedFinishing { serviceId: number; sides?: number; // 1 hoặc 2 mặt (đối với cán màng) customQuantity?: number; foilAreaCm2?: number; // Diện tích ép kim nếu có customNote?: string;}
export interface CalculationInput { jobName: string; productType: ProductType; printTech: PrintTech; quantity: number; widthMm: number; heightMm: number; pages?: number; bleedMm?: number; paperTypeId: number; printSides: '1_side' | '2_side'; colorsFront: number; colorsBack: number; offsetWorkType?: OffsetWorkType; offsetMachineId?: number; digitalMachineId?: number; selectedFinishing: SelectedFinishing[]; profitMarginPercent: number; discountAmount?: number; vatPercent?: number;}
export interface BoxCoordinate { x: number; y: number; w: number; h: number; index: number;}
export interface ImpositionResult { parentSheet: { widthCm: number; heightCm: number; name: string; }; printSheet: { widthMm: number; heightMm: number; name: string; }; upsPerPrintSheet: number; cutsPerParentSheet: number; totalUpsPerParentSheet: number; gripperMarginMm: number; usableWidthMm: number; usableHeightMm: number; cols: number; rows: number; isRotated: boolean; boxes: BoxCoordinate[]; sheetEfficiencyPercent: number;}
export interface FinishingCostDetail { serviceId: number; name: string; category: string; calcType: string; quantity: number; unitPrice: number; setupFee: number; subtotal: number; wasteSheets: number; formula: string;}
export interface ComparisonItem { quantity: number; digitalTotal: number; digitalUnit: number; offsetTotal: number; offsetUnit: number; recommended: 'offset' | 'digital';}
export interface CalculationResult { imposition: ImpositionResult; quantities: { productQty: number; netPrintSheets: number; printWasteSheets: number; finishingWasteSheets: number; totalPrintSheets: number; parentSheetsNeeded: number; ramsNeeded: number; kgNeeded: number; }; costs: { paperCost: number; plateCost: number; platesCount: number; printRunCost: number; totalPrintCost: number; // plate + printRun finishingCost: number; finishingDetails: FinishingCostDetail[]; totalBaseCost: number; profitAmount: number; preTaxTotal: number; discountAmount: number; vatAmount: number; finalPrice: number; unitPrice: number; }; chosenTech: 'offset' | 'digital'; recommendation?: { bestTech: 'offset' | 'digital'; reason: string; digitalTotal?: number; offsetTotal?: number; difference?: number; breakEvenQty?: number; comparisonTable?: ComparisonItem[]; };}
export interface QuoteOrder { id: number; code: string; customerId?: number; customerName: string; customerPhone: string; customerEmail?: string; customerCompany?: string; jobName: string; productType: ProductType; printTech: 'offset' | 'digital'; quantity: number; widthMm: number; heightMm: number; pages: number; paperName: string; paperGsm: number; parentSize: string; printSize: string; upsPerSheet: number; totalPrintSheets: number; totalParentSheets: number; paperCost: number; printCost: number; finishingCost: number; totalCost: number; profitMarginPercent: number; profitAmount: number; discountAmount: number; vatPercent: number; vatAmount: number; finalPrice: number; unitPrice: number; status: OrderStatus; notes?: string; specJson?: string; createdAt: string; updatedAt: string;}
export interface SystemSetting { companyName: string; companyAddress: string; companyPhone: string; companyEmail: string; bankAccount: string; bankName: string; quoteFooterNote: string; defaultProfitMargin: number; defaultVatPercent: number;}1234567891011121314declare module 'node:sqlite' { export class DatabaseSync { constructor(location: string, options?: { open?: boolean }); close(): void; exec(sql: string): void; prepare(sql: string): StatementSync; }
export class StatementSync { all(...params: unknown[]): unknown[]; get(...params: unknown[]): unknown; run(...params: unknown[]): { changes: number; lastInsertRowid: number | bigint }; }}.dockerignoreAdded+8
.gitignore+6
DockerfileAdded+29
README.md+57-23
data/printcal.dbAdded
package-lock.json+78-2
package.json+3-2
src/app/api/calculate/route.tsAdded+117
src/app/api/customers/route.tsAdded+48
src/app/api/finishing/route.tsAdded+99
src/app/api/machines/route.tsAdded+90
src/app/api/orders/route.tsAdded+216
src/app/api/papers/route.tsAdded+99
src/app/api/settings/route.tsAdded+57
src/app/layout.tsx+4-4
src/app/page.tsx+839-63
src/components/BreakEvenChart.tsxAdded+156
src/components/CostBreakdownCard.tsxAdded+211
src/components/CustomerManager.tsxAdded+227
src/components/FinishingManager.tsxAdded+308
src/components/ImpositionVisualizer.tsxAdded+187
src/components/MachineManager.tsxAdded+326
src/components/Navbar.tsxAdded+131
src/components/OrdersManager.tsxAdded+263
src/components/PaperManager.tsxAdded+296
src/components/QuotePrintModal.tsxAdded+417
src/components/SettingsManager.tsxAdded+202
src/lib/db.tsAdded+287
src/lib/engine/costCalculator.tsAdded+413
src/lib/engine/imposition.tsAdded+242
src/types/index.tsAdded+246
src/types/sqlite.d.tsAdded+14