feat: cap nhat bang gia in nhanh kem giay INTC va in gia cong Konica C12000
Browse filesFiles changed (17)
- .gitignore+3
- data/digital_pricing_giacong.jsonAdded+67
- data/digital_pricing_kem_giay.jsonAdded+162
- scripts/extract_pdf_images.pyAdded+26
- scripts/inspect_pdf_details.pyAdded+20
- scripts/inspect_pdfs.pyAdded+37
- scripts/setup_digital_pricing.pyAdded+110
- scripts/update_cost_calculator.pyAdded+690
- src/app/api/calculate/route.ts+47-2
- src/app/api/machines/route.ts+63-1
- src/app/page.tsx+78
- src/components/CostBreakdownCard.tsx+37-2
- src/components/MachineManager.tsx+569-246
- src/lib/db.ts+77-1
- src/lib/engine/costCalculator.ts+230-55
- src/lib/engine/imposition.ts+24-8
- src/types/index.ts+42
44 unmodified lines45464744 unmodified linesdata/*.db-shmdata/*.db-journal44 unmodified lines45464748495044 unmodified linesdata/*.db-shmdata/*.db-journal# extracted imagesscripts/extracted_images/
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667[ { "machine_name": "KONICA C12000 / C12010S 5 MÀU", "sheet_size": "A4", "width_mm": 210, "height_mm": 297, "paper_lt_249": 600, "paper_250_349": 800, "paper_350_450": 1000, "decal_paper_plastic": 1200, "decal_clear": 1500, "synthetic_paper": 1000, "pvc_plastic": 1500 }, { "machine_name": "KONICA C12000 / C12010S 5 MÀU", "sheet_size": "330x355", "width_mm": 330, "height_mm": 355, "paper_lt_249": 800, "paper_250_349": 1000, "paper_350_450": 1800, "decal_paper_plastic": 1500, "decal_clear": 1700, "synthetic_paper": 1800, "pvc_plastic": 2000 }, { "machine_name": "KONICA C12000 / C12010S 5 MÀU", "sheet_size": "A3", "width_mm": 297, "height_mm": 420, "paper_lt_249": 1200, "paper_250_349": 1600, "paper_350_450": 2100, "decal_paper_plastic": 2100, "decal_clear": 2300, "synthetic_paper": 2100, "pvc_plastic": 2500 }, { "machine_name": "KONICA C12000 / C12010S 5 MÀU", "sheet_size": "330x483", "width_mm": 330, "height_mm": 483, "paper_lt_249": 2000, "paper_250_349": 2500, "paper_350_450": 2700, "decal_paper_plastic": 2500, "decal_clear": 2800, "synthetic_paper": 2700, "pvc_plastic": 3000 }, { "machine_name": "KONICA C12000 / C12010S 5 MÀU", "sheet_size": "330x1200", "width_mm": 330, "height_mm": 1200, "paper_lt_249": 4000, "paper_250_349": 7000, "paper_350_450": 10000, "decal_paper_plastic": 6000, "decal_clear": 7500, "synthetic_paper": 15000, "pvc_plastic": 0 }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162[ { "paper_code": "C100", "paper_name": "Couche 100gsm", "gsm": 100, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 1600, "price_2side": 2800 }, { "paper_code": "C120", "paper_name": "Couche 120gsm", "gsm": 120, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 1700, "price_2side": 2900 }, { "paper_code": "C150", "paper_name": "Couche 150gsm", "gsm": 150, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 1800, "price_2side": 3000 }, { "paper_code": "C200", "paper_name": "Couche 200gsm", "gsm": 200, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 1900, "price_2side": 3100 }, { "paper_code": "C250", "paper_name": "Couche 250gsm", "gsm": 250, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 2100, "price_2side": 3300 }, { "paper_code": "C300", "paper_name": "Couche 300gsm", "gsm": 300, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 2700, "price_2side": 4300 }, { "paper_code": "I250", "paper_name": "Ivory 250gsm", "gsm": 250, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 2100, "price_2side": 3300 }, { "paper_code": "I300", "paper_name": "Ivory 300gsm", "gsm": 300, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 2600, "price_2side": 4200 }, { "paper_code": "I350", "paper_name": "Ivory 350gsm", "gsm": 350, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 3300, "price_2side": 5300 }, { "paper_code": "F100", "paper_name": "Fort 100gsm", "gsm": 100, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 1600, "price_2side": 2800 }, { "paper_code": "F120", "paper_name": "Fort 120gsm", "gsm": 120, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 1700, "price_2side": 2900 }, { "paper_code": "F180", "paper_name": "Fort 180gsm", "gsm": 180, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 1900, "price_2side": 3100 }, { "paper_code": "F230", "paper_name": "Fort 230gsm", "gsm": 230, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 2100, "price_2side": 3300 }, { "paper_code": "F250", "paper_name": "Fort 250gsm", "gsm": 250, "sheet_size": "325x430", "width_mm": 325, "height_mm": 430, "price_1side": 2300, "price_2side": 3500 }, { "paper_code": "F180_355", "paper_name": "Fort 180gsm (325x355)", "gsm": 180, "sheet_size": "325x355", "width_mm": 325, "height_mm": 355, "price_1side": 1400, "price_2side": 2200 }, { "paper_code": "F230_355", "paper_name": "Fort 230gsm (325x355)", "gsm": 230, "sheet_size": "325x355", "width_mm": 325, "height_mm": 355, "price_1side": 1500, "price_2side": 2300 }]1234567891011121314151617181920212223242526import fitzimport os
pdf1_path = r"C:\Users\admin\Downloads\BẢNG GIÁ IN NHANH 14.03.2026.pdf"pdf2_path = r"C:\Users\admin\Downloads\BẢNG GIÁ IN GIA CÔNG 26.02.2026.pdf"
os.makedirs("scripts/extracted_images", exist_ok=True)
# Extract PDF 1 Page 1doc1 = fitz.open(pdf1_path)page1 = doc1[0]pix1 = page1.get_pixmap(dpi=150)pix1.save("scripts/extracted_images/in_nhanh_page1.png")print("Saved in_nhanh_page1.png")
# Extract PDF 2 Page 2doc2 = fitz.open(pdf2_path)page2 = doc2[1] # 0-indexed page 2pix2 = page2.get_pixmap(dpi=150)pix2.save("scripts/extracted_images/in_gia_cong_page2.png")print("Saved in_gia_cong_page2.png")
# Also let's extract page 1 and page 3 of PDF 2 just in casedoc2[0].get_pixmap(dpi=100).save("scripts/extracted_images/in_gia_cong_page1.png")doc2[2].get_pixmap(dpi=100).save("scripts/extracted_images/in_gia_cong_page3.png")print("Saved in_gia_cong_page1.png and page3.png")1234567891011121314151617181920import fitzimport sys
sys.stdout.reconfigure(encoding='utf-8')
for path, name in [ (r"C:\Users\admin\Downloads\BẢNG GIÁ IN NHANH 14.03.2026.pdf", "PDF 1"), (r"C:\Users\admin\Downloads\BẢNG GIÁ IN GIA CÔNG 26.02.2026.pdf", "PDF 2")]: print(f"\n*** Checking {name}: {path} ***") doc = fitz.open(path) for p_idx, page in enumerate(doc): imgs = page.get_images() text = page.get_text() drawings = page.get_drawings() print(f"Page {p_idx+1}: text_len={len(text)}, images_count={len(imgs)}, drawings_count={len(drawings)}") for img_idx, img in enumerate(imgs): xref = img[0] base_img = doc.extract_image(xref) print(f" Image {img_idx+1}: xref={xref}, ext={base_img['ext']}, width={base_img['width']}, height={base_img['height']}")12345678910111213141516171819202122232425262728293031323334353637import fitzimport sys
sys.stdout.reconfigure(encoding='utf-8')
pdf1_path = r"C:\Users\admin\Downloads\BẢNG GIÁ IN NHANH 14.03.2026.pdf"pdf2_path = r"C:\Users\admin\Downloads\BẢNG GIÁ IN GIA CÔNG 26.02.2026.pdf"
print("==================================================")print("=== PDF 1: BẢNG GIÁ IN NHANH 14.03.2026.pdf ===")print("==================================================")try: doc1 = fitz.open(pdf1_path) print("Number of pages in PDF 1:", len(doc1)) for i, page in enumerate(doc1): print(f"\n--- PDF 1 - Page {i+1} ---") text = page.get_text() print(text[:2000]) if len(text) > 2000: print(f"... [Total length: {len(text)} chars]")except Exception as e: print("Error reading PDF 1:", e)
print("\n==================================================")print("=== PDF 2: BẢNG GIÁ IN GIA CÔNG 26.02.2026.pdf ===")print("==================================================")try: doc2 = fitz.open(pdf2_path) print("Number of pages in PDF 2:", len(doc2)) for i, page in enumerate(doc2): print(f"\n--- PDF 2 - Page {i+1} ---") text = page.get_text() print(text[:2000]) if len(text) > 2000: print(f"... [Total length: {len(text)} chars]")except Exception as e: print("Error reading PDF 2:", e)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import sqlite3import jsonimport os
db_path = "data/printcal.db"conn = sqlite3.connect(db_path)cur = conn.cursor()
# 1. Create digital_pricing_giacongcur.execute("""CREATE TABLE IF NOT EXISTS digital_pricing_giacong ( id INTEGER PRIMARY KEY AUTOINCREMENT, machine_name TEXT NOT NULL, sheet_size TEXT NOT NULL UNIQUE, width_mm REAL NOT NULL, height_mm REAL NOT NULL, paper_lt_249 REAL NOT NULL, paper_250_349 REAL NOT NULL, paper_350_450 REAL NOT NULL, decal_paper_plastic REAL NOT NULL, decal_clear REAL NOT NULL, synthetic_paper REAL NOT NULL, pvc_plastic REAL NOT NULL, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);""")
# 2. Create digital_pricing_kem_giaycur.execute("""CREATE TABLE IF NOT EXISTS digital_pricing_kem_giay ( id INTEGER PRIMARY KEY AUTOINCREMENT, paper_code TEXT NOT NULL UNIQUE, paper_name TEXT NOT NULL, gsm INTEGER NOT NULL, sheet_size TEXT NOT NULL, width_mm REAL NOT NULL, height_mm REAL NOT NULL, price_1side REAL NOT NULL, price_2side REAL NOT NULL, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);""")
# 3. Data for In Gia Cong (Konica C12000 / C12010S 5 Mau - Trang 2 PDF)giacong_data = [ # machine_name, sheet_size, w, h, lt249, 250-349, 350-450, decal, decal_trong, giay_nhua, pvc ("KONICA C12000 / C12010S 5 MÀU", "A4", 210, 297, 600, 800, 1000, 1200, 1500, 1000, 1500), ("KONICA C12000 / C12010S 5 MÀU", "330x355", 330, 355, 800, 1000, 1800, 1500, 1700, 1800, 2000), ("KONICA C12000 / C12010S 5 MÀU", "A3", 297, 420, 1200, 1600, 2100, 2100, 2300, 2100, 2500), ("KONICA C12000 / C12010S 5 MÀU", "330x483", 330, 483, 2000, 2500, 2700, 2500, 2800, 2700, 3000), ("KONICA C12000 / C12010S 5 MÀU", "330x1200", 330, 1200, 4000, 7000, 10000, 6000, 7500, 15000, 0),]
cur.execute("DELETE FROM digital_pricing_giacong;")cur.executemany("""INSERT INTO digital_pricing_giacong (machine_name, sheet_size, width_mm, height_mm, paper_lt_249, paper_250_349, paper_350_450, decal_paper_plastic, decal_clear, synthetic_paper, pvc_plastic)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);""", giacong_data)
# 4. Data for In Nhanh Kem Giay (INTC - PDF In Nhanh 14.03.2026)kem_giay_data = [ # code, name, gsm, sheet_size, w, h, p1, p2 ("C100", "Couche 100gsm", 100, "325x430", 325, 430, 1600, 2800), ("C120", "Couche 120gsm", 120, "325x430", 325, 430, 1700, 2900), ("C150", "Couche 150gsm", 150, "325x430", 325, 430, 1800, 3000), ("C200", "Couche 200gsm", 200, "325x430", 325, 430, 1900, 3100), ("C250", "Couche 250gsm", 250, "325x430", 325, 430, 2100, 3300), ("C300", "Couche 300gsm", 300, "325x430", 325, 430, 2700, 4300), ("I250", "Ivory 250gsm", 250, "325x430", 325, 430, 2100, 3300), ("I300", "Ivory 300gsm", 300, "325x430", 325, 430, 2600, 4200), ("I350", "Ivory 350gsm", 350, "325x430", 325, 430, 3300, 5300), ("F100", "Fort 100gsm", 100, "325x430", 325, 430, 1600, 2800), ("F120", "Fort 120gsm", 120, "325x430", 325, 430, 1700, 2900), ("F180", "Fort 180gsm", 180, "325x430", 325, 430, 1900, 3100), ("F230", "Fort 230gsm", 230, "325x430", 325, 430, 2100, 3300), ("F250", "Fort 250gsm", 250, "325x430", 325, 430, 2300, 3500), ("F180_355", "Fort 180gsm (325x355)", 180, "325x355", 325, 355, 1400, 2200), ("F230_355", "Fort 230gsm (325x355)", 230, "325x355", 325, 355, 1500, 2300),]
cur.execute("DELETE FROM digital_pricing_kem_giay;")cur.executemany("""INSERT INTO digital_pricing_kem_giay (paper_code, paper_name, gsm, sheet_size, width_mm, height_mm, price_1side, price_2side)VALUES (?, ?, ?, ?, ?, ?, ?, ?);""", kem_giay_data)
conn.commit()print("Saved tables to SQLite successfully!")
# Export to JSONwith open("data/digital_pricing_giacong.json", "w", encoding="utf-8") as f: json.dump([ { "machine_name": r[0], "sheet_size": r[1], "width_mm": r[2], "height_mm": r[3], "paper_lt_249": r[4], "paper_250_349": r[5], "paper_350_450": r[6], "decal_paper_plastic": r[7], "decal_clear": r[8], "synthetic_paper": r[9], "pvc_plastic": r[10] } for r in giacong_data ], f, ensure_ascii=False, indent=2)
with open("data/digital_pricing_kem_giay.json", "w", encoding="utf-8") as f: json.dump([ { "paper_code": r[0], "paper_name": r[1], "gsm": r[2], "sheet_size": r[3], "width_mm": r[4], "height_mm": r[5], "price_1side": r[6], "price_2side": r[7] } for r in kem_giay_data ], f, ensure_ascii=False, indent=2)
print("Exported JSON files successfully!")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690new_content = """import { CalculationInput, CalculationResult, ComparisonItem, DigitalMachine, DigitalMode, DigitalPrintGiaCong, DigitalPrintKemGiay, FinishingCostDetail, FinishingService, OffsetMachine, PaperType,} from '@/types';import { calculateImposition } from './imposition';
export const DEFAULT_DIGITAL_GIA_CONG: DigitalPrintGiaCong[] = [ { id: 1, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: 'A4', widthMm: 210, heightMm: 297, paperLt249: 600, paper250To349: 800, paper350To450: 1000, decalPaperPlastic: 1200, decalClear: 1500, syntheticPaper: 1000, pvcPlastic: 1500 }, { id: 2, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: '330x355', widthMm: 330, heightMm: 355, paperLt249: 800, paper250To349: 1000, paper350To450: 1800, decalPaperPlastic: 1500, decalClear: 1700, syntheticPaper: 1800, pvcPlastic: 2000 }, { id: 3, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: 'A3', widthMm: 297, heightMm: 420, paperLt249: 1200, paper250To349: 1600, paper350To450: 2100, decalPaperPlastic: 2100, decalClear: 2300, syntheticPaper: 2100, pvcPlastic: 2500 }, { id: 4, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: '330x483', widthMm: 330, heightMm: 483, paperLt249: 2000, paper250To349: 2500, paper350To450: 2700, decalPaperPlastic: 2500, decalClear: 2800, syntheticPaper: 2700, pvcPlastic: 3000 }, { id: 5, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: '330x1200', widthMm: 330, heightMm: 1200, paperLt249: 4000, paper250To349: 7000, paper350To450: 10000, decalPaperPlastic: 6000, decalClear: 7500, syntheticPaper: 15000, pvcPlastic: 0 },];
export const DEFAULT_DIGITAL_KEM_GIAY: DigitalPrintKemGiay[] = [ { id: 1, paperCode: 'C100', paperName: 'Couche 100gsm', gsm: 100, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1600, price2Side: 2800 }, { id: 2, paperCode: 'C120', paperName: 'Couche 120gsm', gsm: 120, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1700, price2Side: 2900 }, { id: 3, paperCode: 'C150', paperName: 'Couche 150gsm', gsm: 150, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1800, price2Side: 3000 }, { id: 4, paperCode: 'C200', paperName: 'Couche 200gsm', gsm: 200, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1900, price2Side: 3100 }, { id: 5, paperCode: 'C250', paperName: 'Couche 250gsm', gsm: 250, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2100, price2Side: 3300 }, { id: 6, paperCode: 'C300', paperName: 'Couche 300gsm', gsm: 300, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2700, price2Side: 4300 }, { id: 7, paperCode: 'I250', paperName: 'Ivory 250gsm', gsm: 250, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2100, price2Side: 3300 }, { id: 8, paperCode: 'I300', paperName: 'Ivory 300gsm', gsm: 300, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2600, price2Side: 4200 }, { id: 9, paperCode: 'I350', paperName: 'Ivory 350gsm', gsm: 350, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 3300, price2Side: 5300 }, { id: 10, paperCode: 'F100', paperName: 'Fort 100gsm', gsm: 100, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1600, price2Side: 2800 }, { id: 11, paperCode: 'F120', paperName: 'Fort 120gsm', gsm: 120, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1700, price2Side: 2900 }, { id: 12, paperCode: 'F180', paperName: 'Fort 180gsm', gsm: 180, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1900, price2Side: 3100 }, { id: 13, paperCode: 'F230', paperName: 'Fort 230gsm', gsm: 230, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2100, price2Side: 3300 }, { id: 14, paperCode: 'F250', paperName: 'Fort 250gsm', gsm: 250, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2300, price2Side: 3500 }, { id: 15, paperCode: 'F180_355', paperName: 'Fort 180gsm (325x355)', gsm: 180, sheetSize: '325x355', widthMm: 325, heightMm: 355, price1Side: 1400, price2Side: 2200 }, { id: 16, paperCode: 'F230_355', paperName: 'Fort 230gsm (325x355)', gsm: 230, sheetSize: '325x355', widthMm: 325, heightMm: 355, price1Side: 1500, price2Side: 2300 },];
interface CostCalculatorOptions { input: CalculationInput; paperType: PaperType; offsetMachine?: OffsetMachine; allOffsetMachines?: OffsetMachine[]; digitalMachine?: DigitalMachine; digitalPricingGiaCong?: DigitalPrintGiaCong[]; digitalPricingKemGiay?: DigitalPrintKemGiay[]; allFinishingServices: FinishingService[];}
export function matchOffsetMachine( printSheet: { widthMm: number; heightMm: number }, allMachines?: OffsetMachine[], selectedMachineId?: number): OffsetMachine { if (selectedMachineId && allMachines) { const found = allMachines.find((m) => m.id === selectedMachineId); if (found) return found; }
const dimMin = Math.min(printSheet.widthMm, printSheet.heightMm); const dimMax = Math.max(printSheet.widthMm, printSheet.heightMm);
if (allMachines && allMachines.length > 0) { // Khổ nhỏ dưới 65x43cm (nếu vừa trong 650 x 430 mm) if (dimMin <= 435 && dimMax <= 655) { const small = allMachines.find( (m) => m.name.toLowerCase().includes('nhỏ') || (m.maxWidthMm <= 655 && m.maxHeightMm <= 435) || (m.maxWidthMm <= 435 && m.maxHeightMm <= 655) ); if (small) return small; } // Khổ 65x86cm bắt nhíp chiều 86 const large = allMachines.find( (m) => m.name.includes('65x86') || m.maxWidthMm >= 800 || m.maxHeightMm >= 800 ); if (large) return large; }
// Fallback mặc định chuẩn theo yêu cầu xưởng in if (dimMin <= 435 && dimMax <= 655) { return { id: 1, name: 'Máy Offset Khổ Nhỏ (dưới 65x43cm)', maxWidthMm: 650, maxHeightMm: 430, minWidthMm: 210, minHeightMm: 297, platePrice: 75000, setupCost: 900000, stepCost: 150000, defaultWasteSheets: 80, gripperMarginMm: 10, baseImpressions: 3000, includesPlate: true, }; } else { return { id: 2, name: 'Máy Offset Khổ 65x86cm (Bắt nhíp chiều 86)', maxWidthMm: 860, maxHeightMm: 650, minWidthMm: 430, minHeightMm: 650, platePrice: 100000, setupCost: 1200000, stepCost: 200000, defaultWasteSheets: 100, gripperMarginMm: 10, baseImpressions: 3000, includesPlate: true, }; }}
export function calculatePrintCost({ input, paperType, offsetMachine, allOffsetMachines, digitalMachine, digitalPricingGiaCong = DEFAULT_DIGITAL_GIA_CONG, digitalPricingKemGiay = DEFAULT_DIGITAL_KEM_GIAY, allFinishingServices,}: CostCalculatorOptions): CalculationResult { const digitalMode: DigitalMode = input.digitalMode || 'with_paper';
// 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, digitalMode, 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 = '';
if (service.calcType === 'per_m2') { const areaM2 = ((input.widthMm + (input.bleedMm || 2) * 2) / 1000) * ((input.heightMm + (input.bleedMm || 2) * 2) / 1000) * input.quantity * (sel.sides || 1); 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: Bỏ giá /kg, chỉ áp dụng giá trên 500 tờ (trên ram) và giá dưới 500 tờ (dưới ram) const priceAbove500 = paperType.priceAbove500 || paperType.pricePerRam; const priceBelow500 = paperType.priceBelow500 || priceAbove500;
// Nếu số tờ mẹ >= 500 (trên 1 ram) áp dụng giá sỉ nguyên ram, nếu < 500 tờ áp dụng giá lẻ dưới ram const isWholesale = parentSheetsNeeded >= 500; const effectiveRamPrice = isWholesale ? priceAbove500 : priceBelow500; let paperCost = Math.round(parentSheetsNeeded * (effectiveRamPrice / 500));
// 6. Tiền in ấn let plateCost = 0; let platesCount = 0; let printRunCost = 0; let shortRunFee = 0; let digitalDetails: CalculationResult['costs']['digitalDetails'] | undefined;
if (chosenTech === 'offset') { const machine = offsetMachine || matchOffsetMachine(imposition.printSheet, allOffsetMachines, input.offsetMachineId);
const is2Sides = input.printSides === '2_side'; const workType = input.offsetWorkType || 'self_turn'; const baseImpressions = machine.baseImpressions || 3000; const includesPlate = machine.includesPlate ?? true;
if (!is2Sides) { // In 1 mặt: 1 ca máy, 1 bộ kẽm (chuẩn 4 màu) const colors = input.colorsFront || 4; platesCount = colors;
if (includesPlate) { // Gói mở máy đã bao gồm kẽm 4 màu, chỉ tính thêm tiền kẽm nếu khách in màu thứ 5+ const extraColors = Math.max(0, colors - 4); plateCost = extraColors * machine.platePrice; } else { plateCost = platesCount * machine.platePrice; }
const impressions = totalPrintSheets; if (impressions <= baseImpressions) { printRunCost = machine.setupCost; } else { const extraThousands = Math.ceil((impressions - baseImpressions) / 1000); printRunCost = machine.setupCost + extraThousands * machine.stepCost; } } else { // In 2 mặt if (workType === 'sheetwise') { // In 2 bài riêng: 2 ca in độc lập, 2 bộ kẽm const colors = (input.colorsFront || 4) + (input.colorsBack || 4); platesCount = colors;
if (includesPlate) { // Gói mở máy đã bao gồm 1 bộ kẽm 4 màu cơ bản, bài thứ 2 hoặc màu thứ 5+ tính riêng kẽm const extraColors = Math.max(0, colors - 4); plateCost = extraColors * machine.platePrice; } else { plateCost = platesCount * machine.platePrice; }
// 2 ca in độc lập const impressionsPerSide = totalPrintSheets; const costSide1 = impressionsPerSide <= baseImpressions ? machine.setupCost : machine.setupCost + Math.ceil((impressionsPerSide - baseImpressions) / 1000) * machine.stepCost; const costSide2 = impressionsPerSide <= baseImpressions ? machine.setupCost : machine.setupCost + Math.ceil((impressionsPerSide - baseImpressions) / 1000) * machine.stepCost; printRunCost = costSide1 + costSide2; } else { // Tự trở (Work & Turn) hoặc Trở nhíp (Tumble): Dùng chung 1 bộ kẽm ghép cả 2 mặt (1 ca máy) const colors = Math.max(input.colorsFront || 4, input.colorsBack || 4); platesCount = colors;
if (includesPlate) { const extraColors = Math.max(0, colors - 4); plateCost = extraColors * machine.platePrice; } else { plateCost = platesCount * machine.platePrice; }
// Chạy 2 lượt in (lượt ép x 2) const totalImpressions = totalPrintSheets * 2; if (totalImpressions <= baseImpressions) { printRunCost = machine.setupCost; } else { const extraThousands = Math.ceil((totalImpressions - baseImpressions) / 1000); printRunCost = machine.setupCost + extraThousands * machine.stepCost; } } } } else { // In nhanh kỹ thuật số (Digital) const is2Sides = input.printSides === '2_side'; let ratePerSheet = 0; let machineName = ''; let sheetSizeName = imposition.printSheet.name; let whiteInkCost = 0;
// Phụ phí số lượng ít: // < 50 tờ: +30.000đ // < 100 tờ: +20.000đ // >= 100 tờ: 0đ if (totalPrintSheets < 50) { shortRunFee = 30000; } else if (totalPrintSheets < 100) { shortRunFee = 20000; } else { shortRunFee = 0; }
if (digitalMode === 'with_paper') { // 1. In nhanh kèm giấy (INTC) - Đã gồm tiền giấy trọn gói machineName = 'In Nhanh Kèm Giấy (INTC)'; const kemGiayList = digitalPricingKemGiay && digitalPricingKemGiay.length > 0 ? digitalPricingKemGiay : DEFAULT_DIGITAL_KEM_GIAY;
// Tìm dòng giá phù hợp theo mã giấy let matchedPricing = kemGiayList.find((kg) => paperType.code.toUpperCase().includes(kg.paperCode.toUpperCase()) );
// Nếu không khớp chính xác mã, so khớp theo tiền tố chất liệu (C, I, F) + GSM gần nhất if (!matchedPricing) { const pName = paperType.name.toLowerCase(); let prefix = 'C'; if (pName.includes('ivory') || paperType.code.toUpperCase().startsWith('I')) prefix = 'I'; else if (pName.includes('fort') || pName.includes('ford') || paperType.code.toUpperCase().startsWith('F')) prefix = 'F';
const sameType = kemGiayList.filter((kg) => kg.paperCode.startsWith(prefix)); if (sameType.length > 0) { matchedPricing = sameType.reduce((prev, curr) => Math.abs(curr.gsm - paperType.gsm) < Math.abs(prev.gsm - paperType.gsm) ? curr : prev ); } else { matchedPricing = kemGiayList[0]; } }
if (matchedPricing) { ratePerSheet = is2Sides ? matchedPricing.price2Side : matchedPricing.price1Side; sheetSizeName = `${matchedPricing.sheetSize} mm (${matchedPricing.paperName})`; } else { ratePerSheet = is2Sides ? 3000 : 1800; }
printRunCost = Math.round(totalPrintSheets * ratePerSheet) + shortRunFee;
// Đã kèm giấy nên tiền giấy = 0 paperCost = 0; plateCost = 0; platesCount = 0;
digitalDetails = { mode: 'with_paper', machineName, sheetSizeName, ratePerSheet, shortRunFee, note: `Bảng giá In Nhanh Kèm Giấy INTC (Đã gồm công in + giấy ${matchedPricing?.paperName || ''}). Phí SL ít: +${shortRunFee.toLocaleString('vi-VN')}đ`, }; } else { // 2. In nhanh gia công (Konica C12000 / C12010S 5 màu - Trang 2 PDF) machineName = 'Konica C12000 / C12010S 5 Màu'; const giaCongList = digitalPricingGiaCong && digitalPricingGiaCong.length > 0 ? digitalPricingGiaCong : DEFAULT_DIGITAL_GIA_CONG;
// Nhận diện khổ in máy const pW = imposition.printSheet.widthMm; const pH = imposition.printSheet.heightMm; const maxDim = Math.max(pW, pH); const minDim = Math.min(pW, pH);
let sheetRow: DigitalPrintGiaCong | undefined; if (maxDim > 500) { sheetRow = giaCongList.find((g) => g.sheetSize === '330x1200'); } else if (maxDim > 430 || minDim > 300) { sheetRow = giaCongList.find((g) => g.sheetSize === '330x483'); } else if (maxDim > 360 || minDim > 250) { sheetRow = giaCongList.find((g) => g.sheetSize === 'A3'); } else if (maxDim > 300) { sheetRow = giaCongList.find((g) => g.sheetSize === '330x355'); } else { sheetRow = giaCongList.find((g) => g.sheetSize === 'A4'); }
if (!sheetRow) { sheetRow = giaCongList.find((g) => g.sheetSize === '330x483') || giaCongList[0]; }
// Nhận diện nhóm chất liệu const pName = paperType.name.toLowerCase(); let click1Side = 0;
if (sheetRow) { if (pName.includes('pvc')) { click1Side = sheetRow.pvcPlastic || sheetRow.paper350To450; } else if (pName.includes('nhựa') || pName.includes('synthetic')) { click1Side = sheetRow.syntheticPaper; } else if (pName.includes('trong') && pName.includes('decal')) { click1Side = sheetRow.decalClear; } else if (pName.includes('decal')) { click1Side = sheetRow.decalPaperPlastic; } else { // Giấy thường theo định lượng GSM if (paperType.gsm < 250) { click1Side = sheetRow.paperLt249; } else if (paperType.gsm <= 349) { click1Side = sheetRow.paper250To349; } else { click1Side = sheetRow.paper350To450; } } sheetSizeName = `${sheetRow.sheetSize} (${sheetRow.widthMm}x${sheetRow.heightMm}mm)`; } else { click1Side = is2Sides ? 2000 : 1000; }
// Giá in 2 mặt = x2 giá 1 mặt ratePerSheet = is2Sides ? (click1Side * 2) : click1Side;
// In mực trắng nếu có tùy chọn if (input.whiteInk) { whiteInkCost = totalPrintSheets * (is2Sides ? 4000 : 2000); }
printRunCost = Math.round(totalPrintSheets * ratePerSheet) + whiteInkCost + shortRunFee;
// Nếu khách tự cấp giấy -> tiền giấy = 0 if (input.customerSuppliedPaper) { paperCost = 0; }
plateCost = 0; platesCount = 0;
digitalDetails = { mode: 'without_paper', machineName, sheetSizeName, ratePerSheet, shortRunFee, whiteInkCost, note: `In Gia Công Konica C12000 (Khổ ${sheetSizeName}, Đơn giá ${ratePerSheet.toLocaleString('vi-VN')}đ/tờ). Phí SL ít: +${shortRunFee.toLocaleString('vi-VN')}đ${input.customerSuppliedPaper ? ' • Khách cấp giấy' : ''}`, }; } }
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, digitalPricingGiaCong, digitalPricingKemGiay);
// Tính thử chi phí offset const offResult = runQuickEstimate({ ...input, quantity: qty, printTech: 'offset', }, paperType, offsetMachine, digitalMachine, allFinishingServices, digitalPricingGiaCong, digitalPricingKemGiay);
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, digitalPricingGiaCong, digitalPricingKemGiay); const curOffset = runQuickEstimate({ ...input, printTech: 'offset' }, paperType, offsetMachine, digitalMachine, allFinishingServices, digitalPricingGiaCong, digitalPricingKemGiay);
let recommendationText = ''; const diff = Math.abs(curDigital.finalPrice - curOffset.finalPrice);
if (curDigital.finalPrice < curOffset.finalPrice) { recommendationText = `Với số lượng ${input.quantity.toLocaleString('vi-VN')} sản phẩm, In Nhanh KTS tiết kiệm hơn In Offset ${diff.toLocaleString('vi-VN')}đ (${Math.round((diff / curOffset.finalPrice) * 100)}%), không tốn phí mở máy và kẽm CTP, lấy nhanh trong ngày.`; } else { recommendationText = `Với số lượng ${input.quantity.toLocaleString('vi-VN')} sản phẩm, In Offset tối ưu chi phí hơn In Nhanh ${diff.toLocaleString('vi-VN')}đ (${Math.round((diff / curDigital.finalPrice) * 100)}%), giá đơn vị giảm sâu theo số lượng 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, shortRunFee, digitalDetails, }, 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[] = [], digitalPricingGiaCong: DigitalPrintGiaCong[] = DEFAULT_DIGITAL_GIA_CONG, digitalPricingKemGiay: DigitalPrintKemGiay[] = DEFAULT_DIGITAL_KEM_GIAY): { finalPrice: number; unitPrice: number } { const isDigital = input.printTech === 'digital'; const digitalMode: DigitalMode = input.digitalMode || 'with_paper'; 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, digitalMode, 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 + 10;
const cuts = Math.max(1, imposition.cutsPerParentSheet); const parentSheets = Math.ceil(totalSheets / cuts); const pAbove = paperType.priceAbove500 || paperType.pricePerRam; const pBelow = paperType.priceBelow500 || pAbove; const effectiveRamPrice = parentSheets >= 500 ? pAbove : pBelow; let paperCost = Math.round(parentSheets * (effectiveRamPrice / 500));
let printCost = 0; if (isDigital) { const is2Sides = input.printSides === '2_side'; let shortFee = 0; if (totalSheets < 50) shortFee = 30000; else if (totalSheets < 100) shortFee = 20000;
if (digitalMode === 'with_paper') { const matched = digitalPricingKemGiay.find((kg) => paperType.code.toUpperCase().includes(kg.paperCode.toUpperCase()) ) || digitalPricingKemGiay[0]; const rate = is2Sides ? matched.price2Side : matched.price1Side; printCost = Math.round(totalSheets * rate) + shortFee; paperCost = 0; } else { const isA3 = imposition.printSheet.widthMm > 220 || imposition.printSheet.heightMm > 310; const rate = isA3 ? (is2Sides ? 4000 : 2000) : (is2Sides ? 1600 : 800); printCost = Math.round(totalSheets * rate) + shortFee; if (input.customerSuppliedPaper) paperCost = 0; } } else { const machine = offsetMachine || matchOffsetMachine(imposition.printSheet); const baseImpressions = machine.baseImpressions || 3000; const includesPlate = machine.includesPlate ?? true; const platePrice = includesPlate ? 0 : 4 * machine.platePrice; const impressions = input.printSides === '2_side' ? totalSheets * 2 : totalSheets; const runPrice = impressions <= baseImpressions ? machine.setupCost : machine.setupCost + Math.ceil((impressions - baseImpressions) / 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 };}"""
with open("src/lib/engine/costCalculator.ts", "w", encoding="utf-8") as f: f.write(new_content)print("Updated costCalculator.ts successfully!")12345675 unmodified lines1314151617181943 unmodified lines63646566676846 unmodified lines1151161171181191207 unmodified lines128129130131132133import { 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 {5 unmodified linesif (input.paperTypeId) {paperRow = db.prepare('SELECT * FROM paper_types WHERE id = ?').get(input.paperTypeId) as Record<string, unknown> | undefined;} else if ((input as unknown as Record<string, unknown>).paperCode) {paperRow = db.prepare('SELECT * FROM paper_types WHERE code = ?').get((input as unknown as Record<string, unknown>).paperCode as string) as Record<string, unknown> | undefined;} else {paperRow = db.prepare('SELECT * FROM paper_types WHERE is_active = 1 LIMIT 1').get() as Record<string, unknown> | undefined;}43 unmodified linesif (row) digitalMachine = mapDigitalMachine(row);}// Lấy danh mục dịch vụ gia côngconst finishingRows = db.prepare('SELECT * FROM finishing_services WHERE is_active = 1').all() as Record<string, unknown>[];const allFinishingServices: FinishingService[] = finishingRows.map((r) => ({46 unmodified linesoffsetWorkType: (rawBody.offsetWorkType as CalculationInput['offsetWorkType']) || 'self_turn',offsetMachineId: rawBody.offsetMachineId ? Number(rawBody.offsetMachineId) : undefined,digitalMachineId: rawBody.digitalMachineId ? Number(rawBody.digitalMachineId) : undefined,selectedFinishing: sanitizedFinishing,profitMarginPercent: Number(rawBody.profitMarginPercent) || 0,discountAmount: Number(rawBody.discountAmount) || 0,7 unmodified linesallOffsetMachines,digitalMachine,allFinishingServices,});return NextResponse.json(result);1234567891011121314155 unmodified lines212223242526272843 unmodified lines7273747576777879808182838485868788899091929394959697989910010110210310410510610710846 unmodified lines1551561571581591601611621637 unmodified lines171172173174175176177178import { NextRequest, NextResponse } from 'next/server';import { getDb } from '@/lib/db';import { calculatePrintCost } from '@/lib/engine/costCalculator';import {CalculationInput,DigitalMachine,DigitalPrintGiaCong,DigitalPrintKemGiay,FinishingService,OffsetMachine,PaperType,} from '@/types';export async function POST(req: NextRequest) {try {5 unmodified linesif (input.paperTypeId) {paperRow = db.prepare('SELECT * FROM paper_types WHERE id = ?').get(input.paperTypeId) as Record<string, unknown> | undefined;} else if ((input as unknown as Record<string, unknown>).paperCode) {const codeStr = (input as unknown as Record<string, unknown>).paperCode as string;paperRow = db.prepare('SELECT * FROM paper_types WHERE code = ? OR code LIKE ? LIMIT 1').get(codeStr, `${codeStr}%`) as Record<string, unknown> | undefined;} else {paperRow = db.prepare('SELECT * FROM paper_types WHERE is_active = 1 LIMIT 1').get() as Record<string, unknown> | undefined;}43 unmodified linesif (row) digitalMachine = mapDigitalMachine(row);}// Lấy bảng giá in nhanh gia công (Konica C12000)const digitalGiaCongRows = db.prepare('SELECT * FROM digital_pricing_giacong ORDER BY id ASC').all() as Record<string, unknown>[];const digitalPricingGiaCong: DigitalPrintGiaCong[] = digitalGiaCongRows.map((r) => ({id: r.id as number,machineName: r.machine_name as string,sheetSize: r.sheet_size as string,widthMm: r.width_mm as number,heightMm: r.height_mm as number,paperLt249: r.paper_lt_249 as number,paper250To349: r.paper_250_349 as number,paper350To450: r.paper_350_450 as number,decalPaperPlastic: r.decal_paper_plastic as number,decalClear: r.decal_clear as number,syntheticPaper: r.synthetic_paper as number,pvcPlastic: r.pvc_plastic as number,}));// Lấy bảng giá in nhanh kèm giấy (INTC)const digitalKemGiayRows = db.prepare('SELECT * FROM digital_pricing_kem_giay ORDER BY id ASC').all() as Record<string, unknown>[];const digitalPricingKemGiay: DigitalPrintKemGiay[] = digitalKemGiayRows.map((r) => ({id: r.id as number,paperCode: r.paper_code as string,paperName: r.paper_name as string,gsm: r.gsm as number,sheetSize: r.sheet_size as string,widthMm: r.width_mm as number,heightMm: r.height_mm as number,price1Side: r.price_1side as number,price2Side: r.price_2side as number,}));// Lấy danh mục dịch vụ gia côngconst finishingRows = db.prepare('SELECT * FROM finishing_services WHERE is_active = 1').all() as Record<string, unknown>[];const allFinishingServices: FinishingService[] = finishingRows.map((r) => ({46 unmodified linesoffsetWorkType: (rawBody.offsetWorkType as CalculationInput['offsetWorkType']) || 'self_turn',offsetMachineId: rawBody.offsetMachineId ? Number(rawBody.offsetMachineId) : undefined,digitalMachineId: rawBody.digitalMachineId ? Number(rawBody.digitalMachineId) : undefined,digitalMode: (rawBody.digitalMode as CalculationInput['digitalMode']) || 'with_paper',customerSuppliedPaper: Boolean(rawBody.customerSuppliedPaper),whiteInk: Boolean(rawBody.whiteInk),selectedFinishing: sanitizedFinishing,profitMarginPercent: Number(rawBody.profitMarginPercent) || 0,discountAmount: Number(rawBody.discountAmount) || 0,7 unmodified linesallOffsetMachines,digitalMachine,allFinishingServices,digitalPricingGiaCong,digitalPricingKemGiay,});return NextResponse.json(result);
36 unmodified lines3738394041424341 unmodified lines85868788899036 unmodified linesminCharge: r.min_charge as number,}));return NextResponse.json({ offsetMachines, digitalMachines });} catch (err: unknown) {return NextResponse.json({ error: (err as Error).message }, { status: 500 });}41 unmodified linesbody.minCharge,body.id);}return NextResponse.json({ success: true });36 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717273747576777841 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115236 unmodified linesminCharge: r.min_charge as number,}));const digitalGiaCongRows = db.prepare('SELECT * FROM digital_pricing_giacong ORDER BY id ASC').all() as Record<string, unknown>[];const digitalKemGiayRows = db.prepare('SELECT * FROM digital_pricing_kem_giay ORDER BY id ASC').all() as Record<string, unknown>[];const digitalPricingGiaCong = digitalGiaCongRows.map((r) => ({id: r.id as number,machineName: r.machine_name as string,sheetSize: r.sheet_size as string,widthMm: r.width_mm as number,heightMm: r.height_mm as number,paperLt249: r.paper_lt_249 as number,paper250To349: r.paper_250_349 as number,paper350To450: r.paper_350_450 as number,decalPaperPlastic: r.decal_paper_plastic as number,decalClear: r.decal_clear as number,syntheticPaper: r.synthetic_paper as number,pvcPlastic: r.pvc_plastic as number,}));const digitalPricingKemGiay = digitalKemGiayRows.map((r) => ({id: r.id as number,paperCode: r.paper_code as string,paperName: r.paper_name as string,gsm: r.gsm as number,sheetSize: r.sheet_size as string,widthMm: r.width_mm as number,heightMm: r.height_mm as number,price1Side: r.price_1side as number,price2Side: r.price_2side as number,}));return NextResponse.json({offsetMachines,digitalMachines,digitalPricingGiaCong,digitalPricingKemGiay,});} catch (err: unknown) {return NextResponse.json({ error: (err as Error).message }, { status: 500 });}41 unmodified linesbody.minCharge,body.id);} else if (body.type === 'digital_giacong') {const stmt = db.prepare(`UPDATE digital_pricing_giacongSET paper_lt_249 = ?, paper_250_349 = ?, paper_350_450 = ?, decal_paper_plastic = ?, decal_clear = ?, synthetic_paper = ?, pvc_plastic = ?, updated_at = CURRENT_TIMESTAMPWHERE id = ?`);stmt.run(body.paperLt249,body.paper250To349,body.paper350To450,body.decalPaperPlastic,body.decalClear,body.syntheticPaper,body.pvcPlastic,body.id);} else if (body.type === 'digital_kem_giay') {const stmt = db.prepare(`UPDATE digital_pricing_kem_giaySET price_1side = ?, price_2side = ?, updated_at = CURRENT_TIMESTAMPWHERE id = ?`);stmt.run(body.price1Side,body.price2Side,body.id);}return NextResponse.json({ success: true });
16 unmodified lines17181920212232 unmodified lines55565758596082 unmodified lines14314414514614714819 unmodified lines168169170171172173417 unmodified lines59159259359459559616 unmodified linesCalculationInput,CalculationResult,DigitalMachine,FinishingService,OffsetMachine,PaperType,32 unmodified linesconst [jobName, setJobName] = useState('In Tờ Rơi A4');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);82 unmodified linescolorsFront: Number(colorsFront) || 4,colorsBack: printSides === '2_side' ? (Number(colorsBack) || 4) : 0,offsetWorkType,selectedFinishing,profitMarginPercent: Number(profitMarginPercent) || 0,discountAmount: Number(discountAmount) || 0,19 unmodified linesjobName,productType,printTech,quantity,widthMm,heightMm,417 unmodified lines</div></div></div></div></div>16 unmodified lines1718192021222332 unmodified lines56575859606162636482 unmodified lines14714814915015115215315415519 unmodified lines175176177178179180181182183417 unmodified lines60160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367416 unmodified linesCalculationInput,CalculationResult,DigitalMachine,DigitalMode,FinishingService,OffsetMachine,PaperType,32 unmodified linesconst [jobName, setJobName] = useState('In Tờ Rơi A4');const [productType, setProductType] = useState<ProductType>('to_roi');const [printTech, setPrintTech] = useState<PrintTech>('auto');const [digitalMode, setDigitalMode] = useState<DigitalMode>('with_paper');const [customerSuppliedPaper, setCustomerSuppliedPaper] = useState(false);const [whiteInk, setWhiteInk] = useState(false);const [quantity, setQuantity] = useState(1000);const [widthMm, setWidthMm] = useState(210);const [heightMm, setHeightMm] = useState(297);82 unmodified linescolorsFront: Number(colorsFront) || 4,colorsBack: printSides === '2_side' ? (Number(colorsBack) || 4) : 0,offsetWorkType,digitalMode,customerSuppliedPaper,whiteInk,selectedFinishing,profitMarginPercent: Number(profitMarginPercent) || 0,discountAmount: Number(discountAmount) || 0,19 unmodified linesjobName,productType,printTech,digitalMode,customerSuppliedPaper,whiteInk,quantity,widthMm,heightMm,417 unmodified lines</div></div></div>{/* Tùy chọn in nhanh KTS (Kèm giấy INTC vs Gia công Konica C12000) */}{(printTech === 'digital' || printTech === 'auto') && (<div className="mt-3 p-3 bg-sky-50/70 border border-sky-200/80 rounded-xl space-y-2.5"><div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1.5"><span className="text-xs font-bold text-sky-950 flex items-center gap-1.5"><Sparkles className="w-3.5 h-3.5 text-sky-600" />Chế độ in nhanh KTS:</span><div className="flex gap-1 bg-white p-0.5 rounded-lg border border-sky-200 text-xs"><buttontype="button"onClick={() => setDigitalMode('with_paper')}className={`px-2.5 py-1 rounded font-semibold text-[11px] transition-colors ${digitalMode === 'with_paper'? 'bg-sky-600 text-white shadow-2xs': 'text-slate-600 hover:text-slate-900'}`}>📦 Kèm giấy (INTC)</button><buttontype="button"onClick={() => setDigitalMode('without_paper')}className={`px-2.5 py-1 rounded font-semibold text-[11px] transition-colors ${digitalMode === 'without_paper'? 'bg-sky-600 text-white shadow-2xs': 'text-slate-600 hover:text-slate-900'}`}>⚙️ In gia công (Konica C12000)</button></div></div>{digitalMode === 'with_paper' ? (<div className="text-[11px] text-sky-800 bg-white/70 p-2 rounded-lg border border-sky-100"><strong>Bảng giá INTC (14.03.2026):</strong> Trọn gói công in + giấy theo mã giấy. Khổ in 325×430 & 325×355mm. Phụ phí SL ít: <50 tờ (+30k), <100 tờ (+20k), ≥100 tờ miễn phí.</div>) : (<div className="text-[11px] text-sky-800 bg-white/70 p-2 rounded-lg border border-sky-100 space-y-2"><div><strong>Bảng giá Konica C12000 (Trang 2 PDF 26.02.2026):</strong> 5 khổ in (A4, 330×355, A3, 330×483, 330×1200) cho 7 nhóm chất liệu. In 2 mặt ×2. Phụ phí SL ít: <50 tờ (+30k), <100 tờ (+20k).</div><div className="flex flex-wrap gap-4 text-xs font-semibold text-slate-800 pt-1 border-t border-sky-100"><label className="flex items-center gap-1.5 cursor-pointer"><inputtype="checkbox"checked={customerSuppliedPaper}onChange={(e) => setCustomerSuppliedPaper(e.target.checked)}className="rounded text-sky-600 focus:ring-sky-500 w-3.5 h-3.5"/><span>Khách tự cấp giấy (Tiền giấy = 0đ)</span></label><label className="flex items-center gap-1.5 cursor-pointer"><inputtype="checkbox"checked={whiteInk}onChange={(e) => setWhiteInk(e.target.checked)}className="rounded text-sky-600 focus:ring-sky-500 w-3.5 h-3.5"/><span>In mực trắng (5 màu)</span></label></div></div>)}</div>)}</div></div>
111 unmodified lines112113114115116117118119120121122123124125126127128111 unmodified lines<Layers className="w-3.5 h-3.5 text-blue-600" />Tiền giấy ({quantities.parentSheetsNeeded} tờ mẹ):</span><span className="font-semibold text-slate-900">{costs.paperCost.toLocaleString('vi-VN')}đ</span></div><div className="py-2 flex justify-between items-center"><span className="flex items-center gap-1.5 text-slate-600"><Sparkles className="w-3.5 h-3.5 text-indigo-600" />Tiền in {chosenTech === 'offset' ? (costs.plateCost === 0 ? '(Gói trọn gồm kẽm)' : `(${costs.platesCount} kẽm + công)`) : '(click in)'}:</span><span className="font-semibold text-slate-900">{costs.totalPrintCost.toLocaleString('vi-VN')}đ</span></div><div className="py-2 flex justify-between items-center"><span className="flex items-center gap-1.5 text-slate-600"><Scissors className="w-3.5 h-3.5 text-purple-600" />111 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163111 unmodified lines<Layers className="w-3.5 h-3.5 text-blue-600" />Tiền giấy ({quantities.parentSheetsNeeded} tờ mẹ):</span><span className="font-semibold text-slate-900">{costs.paperCost === 0 && costs.digitalDetails?.mode === 'with_paper' ? (<span className="text-emerald-600 font-bold text-xs bg-emerald-50 px-2 py-0.5 rounded">Đã gồm trong giá in</span>) : costs.paperCost === 0 && input.customerSuppliedPaper ? (<span className="text-emerald-600 font-bold text-xs bg-emerald-50 px-2 py-0.5 rounded">Khách tự cấp giấy</span>) : (`${costs.paperCost.toLocaleString('vi-VN')}đ`)}</span></div><div className="py-2 flex justify-between items-center"><span className="flex items-center gap-1.5 text-slate-600"><Sparkles className="w-3.5 h-3.5 text-indigo-600" />Tiền in {chosenTech === 'offset' ? (costs.plateCost === 0 ? '(Gói trọn gồm kẽm)' : `(${costs.platesCount} kẽm + công)`) : `(${costs.digitalDetails?.mode === 'with_paper' ? 'Kèm giấy INTC' : 'Gia công Konica'})`}:</span><span className="font-semibold text-slate-900">{costs.totalPrintCost.toLocaleString('vi-VN')}đ</span></div>{chosenTech === 'digital' && costs.digitalDetails && (<div className="py-2 px-3 bg-sky-50/80 border border-sky-100 rounded-xl text-[11px] text-sky-900 space-y-1 my-1"><div className="flex justify-between font-bold"><span>{costs.digitalDetails.mode === 'with_paper'? '📦 In kèm giấy (INTC 14.03)': '⚙️ In gia công (Konica C12000)'}</span><span className="text-sky-700">Khổ: {costs.digitalDetails.sheetSizeName || imposition.printSheet.name}</span></div><div className="flex justify-between text-slate-600"><span>Đơn giá: {costs.digitalDetails.ratePerSheet.toLocaleString('vi-VN')}đ / tờ in</span>{costs.shortRunFee && costs.shortRunFee > 0 ? (<span className="font-bold text-amber-700 bg-amber-50 px-1.5 py-0.5 rounded">Phụ phí SL ít: +{costs.shortRunFee.toLocaleString('vi-VN')}đ</span>) : (<span className="text-emerald-700 font-semibold">Miễn phụ phí</span>)}</div></div>)}<div className="py-2 flex justify-between items-center"><span className="flex items-center gap-1.5 text-slate-600"><Scissors className="w-3.5 h-3.5 text-purple-600" />
1234567891011121314152 unmodified lines18192021222321 unmodified lines4546474849505152535455565758591 unmodified line616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361'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 {2 unmodified linesconst data = await res.json();if (data.offsetMachines) setOffsetMachines(data.offsetMachines);if (data.digitalMachines) setDigitalMachines(data.digitalMachines);} catch (err) {console.error(err);} finally {21 unmodified lines}};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) {1 unmodified line}};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><buttononClick={() => 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"><inputtype="number"className="w-1/2 p-1 border rounded text-right"value={current.maxWidthMm}onChange={(e) => setEditingOffset({ ...current, maxWidthMm: Number(e.target.value) })}/><inputtype="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 ? (<inputtype="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 (≤{current.baseImpressions || 3000} lượt):</span>{isEditing ? (<inputtype="number"className="w-28 p-1 border rounded text-right"value={current.setupCost}onChange={(e) => setEditingOffset({ ...current, setupCost: Number(e.target.value) })}/>) : (<div className="text-right"><span className="font-bold text-slate-800">{current.setupCost.toLocaleString('vi-VN')}đ</span>{current.includesPlate && (<span className="text-[10px] font-semibold text-emerald-600 block">Đã gồm kẽm</span>)}</div>)}</div><div className="flex justify-between items-center"><span className="text-slate-500">Số lượt in cơ bản:</span>{isEditing ? (<inputtype="number"className="w-28 p-1 border rounded text-right"value={current.baseImpressions || 3000}onChange={(e) => setEditingOffset({ ...current, baseImpressions: Number(e.target.value) })}/>) : (<span className="font-medium text-slate-700">{(current.baseImpressions || 3000).toLocaleString('vi-VN')} lượt</span>)}</div><div className="flex justify-between items-center"><span className="text-slate-500">Bao gồm kẽm CTP:</span>{isEditing ? (<inputtype="checkbox"className="h-4 w-4 text-indigo-600 rounded"checked={current.includesPlate ?? true}onChange={(e) => setEditingOffset({ ...current, includesPlate: e.target.checked })}/>) : (<span className={`font-semibold ${current.includesPlate ? 'text-emerald-600' : 'text-slate-500'}`}>{current.includesPlate ? 'Đã gồm trong giá mở máy' : 'Tính riêng theo kẽm'}</span>)}</div><div className="flex justify-between items-center"><span className="text-slate-500">Mỗi 1000 lượt tiếp:</span>{isEditing ? (<inputtype="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 ? (<inputtype="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"><buttononClick={() => setEditingOffset(null)}className="px-2 py-1 border rounded text-[11px] text-slate-600 hover:bg-slate-100">Hủy</button><buttononClick={() => 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><buttononClick={() => 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 ? (<inputtype="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 ? (<inputtype="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 ? (<inputtype="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 ? (<inputtype="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 ? (<inputtype="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"><buttononClick={() => setEditingDigital(null)}className="px-2 py-1 border rounded text-[11px] text-slate-600 hover:bg-slate-100">Hủy</button><buttononClick={() => 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>);};1234567891011121314151617181920212223242 unmodified lines272829303132333421 unmodified lines565758596061626364656667686970717273747576777879808182838485861 unmodified line888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684'use client';import React, { useState, useEffect } from 'react';import { DigitalMachine, DigitalPrintGiaCong, DigitalPrintKemGiay, OffsetMachine } from '@/types';import { Cpu, Printer, Edit2, Check, RefreshCw, Layers, FileText, Info, Save, X } from 'lucide-react';export const MachineManager: React.FC = () => {const [activeTab, setActiveTab] = useState<'giacong' | 'kem_giay' | 'offset'>('giacong');const [offsetMachines, setOffsetMachines] = useState<OffsetMachine[]>([]);const [digitalMachines, setDigitalMachines] = useState<DigitalMachine[]>([]);const [digitalPricingGiaCong, setDigitalPricingGiaCong] = useState<DigitalPrintGiaCong[]>([]);const [digitalPricingKemGiay, setDigitalPricingKemGiay] = useState<DigitalPrintKemGiay[]>([]);const [loading, setLoading] = useState(true);// Editing stateconst [editingOffset, setEditingOffset] = useState<OffsetMachine | null>(null);const [editingGiaCong, setEditingGiaCong] = useState<DigitalPrintGiaCong | null>(null);const [editingKemGiay, setEditingKemGiay] = useState<DigitalPrintKemGiay | null>(null);// Filter for INTC paperconst [paperFilter, setPaperFilter] = useState<'all' | 'C' | 'I' | 'F'>('all');const fetchMachines = async () => {try {2 unmodified linesconst data = await res.json();if (data.offsetMachines) setOffsetMachines(data.offsetMachines);if (data.digitalMachines) setDigitalMachines(data.digitalMachines);if (data.digitalPricingGiaCong) setDigitalPricingGiaCong(data.digitalPricingGiaCong);if (data.digitalPricingKemGiay) setDigitalPricingKemGiay(data.digitalPricingKemGiay);} catch (err) {console.error(err);} finally {21 unmodified lines}};const handleSaveGiaCong = async (item: DigitalPrintGiaCong) => {try {const res = await fetch('/api/machines', {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ type: 'digital_giacong', ...item }),});if (res.ok) {setEditingGiaCong(null);fetchMachines();}} catch (err) {console.error(err);}};const handleSaveKemGiay = async (item: DigitalPrintKemGiay) => {try {const res = await fetch('/api/machines', {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ type: 'digital_kem_giay', ...item }),});if (res.ok) {setEditingKemGiay(null);fetchMachines();}} catch (err) {1 unmodified line}};const filteredKemGiay = digitalPricingKemGiay.filter((item) => {if (paperFilter === 'all') return true;if (paperFilter === 'C') return item.paperCode.startsWith('C');if (paperFilter === 'I') return item.paperCode.startsWith('I');if (paperFilter === 'F') return item.paperCode.startsWith('F');return true;});return (<div className="space-y-5">{/* Top Header & Navigation Tabs */}<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-white p-4 rounded-2xl border border-slate-200 shadow-2xs"><div><h2 className="text-base font-bold text-slate-900 flex items-center gap-2"><Printer className="w-5 h-5 text-blue-600" />Quản Lý Bảng Giá In Ấn</h2><p className="text-xs text-slate-500 mt-0.5">Cập nhật biểu giá In nhanh gia công (Konica C12000), In nhanh kèm giấy (INTC) và Máy in Offset</p></div><div className="flex items-center gap-2"><div className="flex bg-slate-100 p-1 rounded-xl text-xs font-semibold"><buttononClick={() => setActiveTab('giacong')}className={`px-3 py-1.5 rounded-lg transition-all ${activeTab === 'giacong'? 'bg-white shadow text-sky-700 font-bold': 'text-slate-600 hover:text-slate-900'}`}>⚙️ Konica C12000 (Gia Công)</button><buttononClick={() => setActiveTab('kem_giay')}className={`px-3 py-1.5 rounded-lg transition-all ${activeTab === 'kem_giay'? 'bg-white shadow text-indigo-700 font-bold': 'text-slate-600 hover:text-slate-900'}`}>📦 INTC (Kèm Giấy)</button><buttononClick={() => setActiveTab('offset')}className={`px-3 py-1.5 rounded-lg transition-all ${activeTab === 'offset'? 'bg-white shadow text-blue-700 font-bold': 'text-slate-600 hover:text-slate-900'}`}>🏭 Máy In Offset</button></div><buttononClick={fetchMachines}disabled={loading}className="p-2 text-slate-500 hover:text-blue-600 rounded-lg hover:bg-slate-100 transition-colors"title="Làm mới dữ liệu"><RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} /></button></div></div>{/* TAB 1: BẢNG GIÁ IN GIA CÔNG KONICA C12000 (TRANG 2 PDF 26.02.2026) */}{activeTab === 'giacong' && (<div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden space-y-4"><div className="p-5 border-b border-slate-200 bg-gradient-to-r from-sky-50 to-blue-50/40"><div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2"><div><span className="px-2.5 py-0.5 bg-sky-600 text-white rounded-md text-[10px] font-bold uppercase tracking-wider">Trang 2 PDF 26.02.2026</span><h3 className="text-base font-black text-slate-900 mt-1">MÁY IN KONICA MINOLTA C12000 / C12010S 5 MÀU</h3><p className="text-xs text-slate-600 mt-0.5">Đơn giá in gia công (chưa gồm giấy) theo 5 kích thước tiêu chuẩn & 7 nhóm chất liệu.</p></div></div>{/* Quy tắc phụ phí & lưu ý */}<div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2 text-xs"><div className="bg-white/80 border border-sky-200 rounded-xl p-2.5 flex items-start gap-2"><Info className="w-4 h-4 text-sky-600 shrink-0 mt-0.5" /><div><strong className="text-sky-900 block font-semibold">Phụ phí số lượng ít:</strong><span className="text-slate-600 text-[11px]">< 50 tờ: <strong>+30.000đ</strong> | < 100 tờ: <strong>+20.000đ</strong> | ≥ 100 tờ: <strong>Miễn phí</strong></span></div></div><div className="bg-white/80 border border-sky-200 rounded-xl p-2.5 flex items-start gap-2"><Info className="w-4 h-4 text-indigo-600 shrink-0 mt-0.5" /><div><strong className="text-indigo-900 block font-semibold">Quy ước tính mặt in:</strong><span className="text-slate-600 text-[11px]">Đơn giá hiển thị dưới đây là đơn giá <strong>in 1 mặt</strong>. In 2 mặt được tính <strong>nhân đôi (×2)</strong>.</span></div></div></div></div><div className="p-5 pt-0 overflow-x-auto"><table className="w-full text-xs text-left border-collapse min-w-[760px]"><thead><tr className="bg-slate-100 text-slate-700 font-bold border-b border-slate-200"><th className="p-3 text-center w-36">Khổ in</th><th className="p-3 text-right">Giấy <249gsm</th><th className="p-3 text-right">Giấy 250-349gsm</th><th className="p-3 text-right">Giấy 350-450gsm</th><th className="p-3 text-right">Decal (Giấy-nhựa)</th><th className="p-3 text-right">Decal trong</th><th className="p-3 text-right">Giấy nhựa <280gsm</th><th className="p-3 text-right">Nhựa PVC</th><th className="p-3 text-center w-24">Thao tác</th></tr></thead><tbody className="divide-y divide-slate-100">{digitalPricingGiaCong.map((row) => {const isEditing = editingGiaCong?.id === row.id;const cur = isEditing ? editingGiaCong : row;return (<tr key={row.id} className="hover:bg-slate-50/70 transition-colors"><td className="p-3 text-center font-bold text-slate-800"><span className="text-sm block">{row.sheetSize}</span><span className="text-[10px] text-slate-500 font-normal">{row.widthMm} × {row.heightMm} mm</span></td>{/* Giấy <249gsm */}<td className="p-2 text-right">{isEditing ? (<inputtype="number"className="w-20 p-1 border rounded text-right font-bold text-blue-700 text-xs"value={cur.paperLt249}onChange={(e) => setEditingGiaCong({ ...cur, paperLt249: Number(e.target.value) })}/>) : (<span className="font-bold text-slate-800">{row.paperLt249.toLocaleString('vi-VN')}đ</span>)}</td>{/* Giấy 250-349gsm */}<td className="p-2 text-right">{isEditing ? (<inputtype="number"className="w-20 p-1 border rounded text-right font-bold text-blue-700 text-xs"value={cur.paper250To349}onChange={(e) => setEditingGiaCong({ ...cur, paper250To349: Number(e.target.value) })}/>) : (<span className="font-bold text-slate-800">{row.paper250To349.toLocaleString('vi-VN')}đ</span>)}</td>{/* Giấy 350-450gsm */}<td className="p-2 text-right">{isEditing ? (<inputtype="number"className="w-20 p-1 border rounded text-right font-bold text-blue-700 text-xs"value={cur.paper350To450}onChange={(e) => setEditingGiaCong({ ...cur, paper350To450: Number(e.target.value) })}/>) : (<span className="font-bold text-slate-800">{row.paper350To450.toLocaleString('vi-VN')}đ</span>)}</td>{/* Decal giấy nhựa */}<td className="p-2 text-right">{isEditing ? (<inputtype="number"className="w-20 p-1 border rounded text-right font-bold text-blue-700 text-xs"value={cur.decalPaperPlastic}onChange={(e) => setEditingGiaCong({ ...cur, decalPaperPlastic: Number(e.target.value) })}/>) : (<span className="font-medium text-slate-700">{row.decalPaperPlastic.toLocaleString('vi-VN')}đ</span>)}</td>{/* Decal trong */}<td className="p-2 text-right">{isEditing ? (<inputtype="number"className="w-20 p-1 border rounded text-right font-bold text-blue-700 text-xs"value={cur.decalClear}onChange={(e) => setEditingGiaCong({ ...cur, decalClear: Number(e.target.value) })}/>) : (<span className="font-medium text-slate-700">{row.decalClear.toLocaleString('vi-VN')}đ</span>)}</td>{/* Giấy nhựa <280 */}<td className="p-2 text-right">{isEditing ? (<inputtype="number"className="w-20 p-1 border rounded text-right font-bold text-blue-700 text-xs"value={cur.syntheticPaper}onChange={(e) => setEditingGiaCong({ ...cur, syntheticPaper: Number(e.target.value) })}/>) : (<span className="font-medium text-slate-700">{row.syntheticPaper.toLocaleString('vi-VN')}đ</span>)}</td>{/* Nhựa PVC */}<td className="p-2 text-right">{isEditing ? (<inputtype="number"className="w-20 p-1 border rounded text-right font-bold text-blue-700 text-xs"value={cur.pvcPlastic}onChange={(e) => setEditingGiaCong({ ...cur, pvcPlastic: Number(e.target.value) })}/>) : (<span className="font-medium text-slate-700">{row.pvcPlastic > 0 ? `${row.pvcPlastic.toLocaleString('vi-VN')}đ` : '—'}</span>)}</td>{/* Nút hành động */}<td className="p-2 text-center">{isEditing ? (<div className="flex items-center justify-center gap-1"><buttononClick={() => handleSaveGiaCong(cur)}className="p-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded shadow-xs"title="Lưu thay đổi"><Save className="w-3.5 h-3.5" /></button><buttononClick={() => setEditingGiaCong(null)}className="p-1.5 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded"title="Hủy"><X className="w-3.5 h-3.5" /></button></div>) : (<buttononClick={() => setEditingGiaCong({ ...row })}className="p-1.5 text-slate-400 hover:text-sky-600 rounded hover:bg-sky-50 transition-colors"title="Chỉnh sửa đơn giá hàng này"><Edit2 className="w-3.5 h-3.5" /></button>)}</td></tr>);})}</tbody></table></div></div>)}{/* TAB 2: BẢNG GIÁ IN NHANH KÈM GIẤY INTC (PDF 14.03.2026) */}{activeTab === 'kem_giay' && (<div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden space-y-4"><div className="p-5 border-b border-slate-200 bg-gradient-to-r from-indigo-50 to-purple-50/40"><div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3"><div><span className="px-2.5 py-0.5 bg-indigo-600 text-white rounded-md text-[10px] font-bold uppercase tracking-wider">Bảng Giá INTC 14.03.2026</span><h3 className="text-base font-black text-slate-900 mt-1">BẢNG GIÁ IN NHANH KÈM GIẤY (TRỌN GÓI)</h3><p className="text-xs text-slate-600 mt-0.5">Đơn giá trọn gói đã bao gồm tiền giấy và công in. Khổ in 325 × 430 mm và 325 × 355 mm.</p></div>{/* Bộ lọc loại giấy */}<div className="flex items-center gap-1 bg-white p-1 rounded-xl border border-indigo-200 text-xs font-semibold"><buttononClick={() => setPaperFilter('all')}className={`px-2.5 py-1 rounded-lg ${paperFilter === 'all' ? 'bg-indigo-600 text-white' : 'text-slate-600'}`}>Tất cả ({digitalPricingKemGiay.length})</button><buttononClick={() => setPaperFilter('C')}className={`px-2.5 py-1 rounded-lg ${paperFilter === 'C' ? 'bg-indigo-600 text-white' : 'text-slate-600'}`}>Couche (6)</button><buttononClick={() => setPaperFilter('I')}className={`px-2.5 py-1 rounded-lg ${paperFilter === 'I' ? 'bg-indigo-600 text-white' : 'text-slate-600'}`}>Ivory (3)</button><buttononClick={() => setPaperFilter('F')}className={`px-2.5 py-1 rounded-lg ${paperFilter === 'F' ? 'bg-indigo-600 text-white' : 'text-slate-600'}`}>Fort (7)</button></div></div>{/* Phụ phí */}<div className="mt-3 bg-white/80 border border-indigo-200 rounded-xl p-2.5 flex items-start gap-2 text-xs"><Info className="w-4 h-4 text-indigo-600 shrink-0 mt-0.5" /><div><strong className="text-indigo-900 block font-semibold">Quy định phụ phí số lượng ít:</strong><span className="text-slate-600 text-[11px]">Số lượng < 50 tờ: <strong>+30.000đ</strong> | < 100 tờ: <strong>+20.000đ</strong> | ≥ 100 tờ: <strong>Miễn phí phụ phí</strong></span></div></div></div><div className="p-5 pt-0 overflow-x-auto"><table className="w-full text-xs text-left border-collapse"><thead><tr className="bg-slate-100 text-slate-700 font-bold border-b border-slate-200"><th className="p-3 text-center w-20">Mã</th><th className="p-3 text-left">Chất liệu & Định lượng</th><th className="p-3 text-center w-32">Khổ in</th><th className="p-3 text-right w-36">In 1 mặt (+ Giấy)</th><th className="p-3 text-right w-36">In 2 mặt (+ Giấy)</th><th className="p-3 text-center w-24">Thao tác</th></tr></thead><tbody className="divide-y divide-slate-100">{filteredKemGiay.map((row) => {const isEditing = editingKemGiay?.id === row.id;const cur = isEditing ? editingKemGiay : row;return (<tr key={row.id} className="hover:bg-slate-50/70 transition-colors"><td className="p-3 text-center font-bold text-indigo-700"><span className="px-2 py-0.5 bg-indigo-50 border border-indigo-200 rounded font-mono">{row.paperCode}</span></td><td className="p-3"><strong className="text-slate-900 block text-xs">{row.paperName}</strong><span className="text-[11px] text-slate-500 font-medium">Định lượng: {row.gsm} gsm</span></td><td className="p-3 text-center font-semibold text-slate-700"><span className="px-2 py-0.5 bg-slate-100 rounded text-[11px]">{row.sheetSize} mm</span></td>{/* Đơn giá 1 mặt */}<td className="p-3 text-right">{isEditing ? (<inputtype="number"className="w-24 p-1.5 border rounded text-right font-bold text-indigo-700 text-xs"value={cur.price1Side}onChange={(e) => setEditingKemGiay({ ...cur, price1Side: Number(e.target.value) })}/>) : (<span className="font-bold text-slate-900 text-sm">{row.price1Side.toLocaleString('vi-VN')}đ</span>)}</td>{/* Đơn giá 2 mặt */}<td className="p-3 text-right">{isEditing ? (<inputtype="number"className="w-24 p-1.5 border rounded text-right font-bold text-purple-700 text-xs"value={cur.price2Side}onChange={(e) => setEditingKemGiay({ ...cur, price2Side: Number(e.target.value) })}/>) : (<span className="font-bold text-purple-700 text-sm">{row.price2Side.toLocaleString('vi-VN')}đ</span>)}</td>{/* Nút thao tác */}<td className="p-3 text-center">{isEditing ? (<div className="flex items-center justify-center gap-1"><buttononClick={() => handleSaveKemGiay(cur)}className="p-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded shadow-xs"title="Lưu thay đổi"><Save className="w-3.5 h-3.5" /></button><buttononClick={() => setEditingKemGiay(null)}className="p-1.5 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded"title="Hủy"><X className="w-3.5 h-3.5" /></button></div>) : (<buttononClick={() => setEditingKemGiay({ ...row })}className="p-1.5 text-slate-400 hover:text-indigo-600 rounded hover:bg-indigo-50 transition-colors"title="Sửa giá"><Edit2 className="w-3.5 h-3.5" /></button>)}</td></tr>);})}</tbody></table></div></div>)}{/* TAB 3: MÁY IN OFFSET */}{activeTab === 'offset' && (<div className="bg-white rounded-2xl border border-slate-200 shadow-2xs overflow-hidden space-y-4"><div className="p-5 border-b border-slate-200 bg-gradient-to-r from-blue-50 to-indigo-50/40"><h3 className="font-bold text-slate-900 text-sm flex items-center gap-2"><Cpu className="w-5 h-5 text-indigo-600" />Cấu Hình Máy In Offset & Gói In Trọn Gói Gồm Kẽm</h3><p className="text-xs text-slate-600 mt-0.5">Khổ 65 × 86 cm (bắt nhíp chiều 86): 1.200.000đ | Khổ nhỏ dưới 65 × 43 cm: 900.000đ (Dưới 3.000 lượt in đã bao gồm 4 kẽm)</p></div><div className="p-5 pt-0 grid grid-cols-1 md:grid-cols-2 lg: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><buttononClick={() => 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"><inputtype="number"className="w-1/2 p-1 border rounded text-right"value={current.maxWidthMm}onChange={(e) => setEditingOffset({ ...current, maxWidthMm: Number(e.target.value) })}/><inputtype="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 ? (<inputtype="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 (≤{current.baseImpressions || 3000} lượt):</span>{isEditing ? (<inputtype="number"className="w-28 p-1 border rounded text-right"value={current.setupCost}onChange={(e) => setEditingOffset({ ...current, setupCost: Number(e.target.value) })}/>) : (<div className="text-right"><span className="font-bold text-slate-800">{current.setupCost.toLocaleString('vi-VN')}đ</span>{current.includesPlate && (<span className="text-[10px] font-semibold text-emerald-600 block">Đã gồm kẽm</span>)}</div>)}</div><div className="flex justify-between items-center"><span className="text-slate-500">Lũy tiến / 1.000 lượt:</span>{isEditing ? (<inputtype="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-800">{current.stepCost.toLocaleString('vi-VN')}đ</span>)}</div><div className="flex justify-between items-center"><span className="text-slate-500">Bù hao kẹp nhíp:</span>{isEditing ? (<inputtype="number"className="w-28 p-1 border rounded text-right"value={current.gripperMarginMm || 10}onChange={(e) => setEditingOffset({ ...current, gripperMarginMm: Number(e.target.value) })}/>) : (<span className="font-medium text-slate-800">{current.gripperMarginMm || 10} mm</span>)}</div><div className="flex justify-between items-center"><span className="text-slate-500">Bù hao giấy in:</span>{isEditing ? (<inputtype="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"><buttononClick={() => setEditingOffset(null)}className="px-2 py-1 border rounded text-[11px] text-slate-600 hover:bg-slate-100">Hủy</button><buttononClick={() => 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>)}</div>);};
70 unmodified lines717273747576179 unmodified lines25625725825926026126226326426570 unmodified linesupdated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);CREATE TABLE IF NOT EXISTS finishing_services (id INTEGER PRIMARY KEY AUTOINCREMENT,code TEXT NOT NULL UNIQUE,179 unmodified linesVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);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(`70 unmodified lines7172737475767778798081828384858687888990919293949596979899100101102103104105179 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034170 unmodified linesupdated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);CREATE TABLE IF NOT EXISTS digital_pricing_giacong (id INTEGER PRIMARY KEY AUTOINCREMENT,machine_name TEXT NOT NULL,sheet_size TEXT NOT NULL UNIQUE,width_mm REAL NOT NULL,height_mm REAL NOT NULL,paper_lt_249 REAL NOT NULL,paper_250_349 REAL NOT NULL,paper_350_450 REAL NOT NULL,decal_paper_plastic REAL NOT NULL,decal_clear REAL NOT NULL,synthetic_paper REAL NOT NULL,pvc_plastic REAL NOT NULL,updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);CREATE TABLE IF NOT EXISTS digital_pricing_kem_giay (id INTEGER PRIMARY KEY AUTOINCREMENT,paper_code TEXT NOT NULL UNIQUE,paper_name TEXT NOT NULL,gsm INTEGER NOT NULL,sheet_size TEXT NOT NULL,width_mm REAL NOT NULL,height_mm REAL NOT NULL,price_1side REAL NOT NULL,price_2side REAL NOT NULL,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,179 unmodified linesVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);insertDigital.run('Máy In Nhanh Konica C12000 / C12010S (5 Màu - Khổ 33x48)', 488, 330, 800, 1600, 2000, 4000, 3, 20000);insertDigital.run('Máy In Nhanh Fuji Xerox Versant 3100 (Cao Cấp)', 660, 330, 1500, 2800, 3000, 5400, 3, 30000);}// Seed digital_pricing_giacongconst giaCongCount = db.prepare('SELECT COUNT(*) as cnt FROM digital_pricing_giacong').get() as { cnt: number };if (giaCongCount.cnt === 0) {const jsonPath = path.join(process.cwd(), 'data', 'digital_pricing_giacong.json');if (fs.existsSync(jsonPath)) {try {const rows = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));const insertGC = db.prepare(`INSERT INTO digital_pricing_giacong (machine_name, sheet_size, width_mm, height_mm, paper_lt_249, paper_250_349, paper_350_450, decal_paper_plastic, decal_clear, synthetic_paper, pvc_plastic)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for (const r of rows) {insertGC.run(r.machine_name, r.sheet_size, r.width_mm, r.height_mm,r.paper_lt_249, r.paper_250_349, r.paper_350_450,r.decal_paper_plastic, r.decal_clear, r.synthetic_paper, r.pvc_plastic);}} catch (err) {console.error('Error seeding digital_pricing_giacong:', err);}}}// Seed digital_pricing_kem_giayconst kemGiayCount = db.prepare('SELECT COUNT(*) as cnt FROM digital_pricing_kem_giay').get() as { cnt: number };if (kemGiayCount.cnt === 0) {const jsonPath = path.join(process.cwd(), 'data', 'digital_pricing_kem_giay.json');if (fs.existsSync(jsonPath)) {try {const rows = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));const insertKG = db.prepare(`INSERT INTO digital_pricing_kem_giay (paper_code, paper_name, gsm, sheet_size, width_mm, height_mm, price_1side, price_2side)VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for (const r of rows) {insertKG.run(r.paper_code, r.paper_name, r.gsm, r.sheet_size,r.width_mm, r.height_mm, r.price_1side, r.price_2side);}} catch (err) {console.error('Error seeding digital_pricing_kem_giay:', err);}}}const finishingCount = db.prepare('SELECT COUNT(*) as cnt FROM finishing_services').get() as { cnt: number };if (finishingCount.cnt === 0) {const insertFinishing = db.prepare(`
2 unmodified lines3456781 unmodified line10111213141516171819202126 unmodified lines484950515253545538 unmodified lines94959697989910010116 unmodified lines11811912012112212316 unmodified lines14014114214314414514614714814915015115256 unmodified lines20921021121221321421521621721821922027 unmodified lines24824925025125225325425525625725825926026130 unmodified lines29229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033120 unmodified lines35235335435535635735835936036136236336436515 unmodified lines38138238338438538638738838939039139239339439539623 unmodified lines42042142242342442514 unmodified lines4404414424434444454464474484 unmodified lines4534544554564574584594604614624634644654664674684694704714724734744754764774784794802 unmodified linesCalculationResult,ComparisonItem,DigitalMachine,FinishingCostDetail,FinishingService,OffsetMachine,1 unmodified line} from '@/types';import { calculateImposition } from './imposition';interface CostCalculatorOptions {input: CalculationInput;paperType: PaperType;offsetMachine?: OffsetMachine;allOffsetMachines?: OffsetMachine[];digitalMachine?: DigitalMachine;allFinishingServices: FinishingService[];}26 unmodified lines(m) => m.name.includes('65x86') || m.maxWidthMm >= 800 || m.maxHeightMm >= 800);if (large) return large;return allMachines[0];}// Fallback mặc định chuẩn theo yêu cầu xưởng in38 unmodified linesoffsetMachine,allOffsetMachines,digitalMachine,allFinishingServices,}: CostCalculatorOptions): CalculationResult {// 1. Xác định công nghệ in mục tiêulet chosenTech: 'offset' | 'digital' = 'offset';if (input.printTech === 'digital') {16 unmodified linesbleedMm: input.bleedMm ?? 2,paperType,printTech: chosenTech,preferredMachineSheet: preferredSheet,gripperMarginMm: offsetMachine?.gripperMarginMm ?? 10,});16 unmodified lines// Tính chi phí từng mục gia cônglet 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ờ inconst 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')}đ)`;56 unmodified lines// Nếu số tờ mẹ >= 500 (trên 1 ram) áp dụng giá sỉ nguyên ram, nếu < 500 tờ áp dụng giá lẻ dưới ramconst isWholesale = parentSheetsNeeded >= 500;const effectiveRamPrice = isWholesale ? priceAbove500 : priceBelow500;const paperCost = Math.round(parentSheetsNeeded * (effectiveRamPrice / 500));// 6. Tiền in ấnlet plateCost = 0;let platesCount = 0;let printRunCost = 0;if (chosenTech === 'offset') {const machine = offsetMachine || matchOffsetMachine(imposition.printSheet, allOffsetMachines, input.offsetMachineId);27 unmodified lines// In 2 mặtif (workType === 'sheetwise') {// In 2 bài riêng: 2 ca in độc lập, 2 bộ kẽmconst colorsF = input.colorsFront || 4;const colorsB = input.colorsBack || 4;platesCount = colorsF + colorsB;if (includesPlate) {const extraColorsF = Math.max(0, colorsF - 4);const extraColorsB = Math.max(0, colorsB - 4);plateCost = (extraColorsF + extraColorsB) * machine.platePrice;} else {plateCost = platesCount * machine.platePrice;}30 unmodified lines}}} 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 A4const 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 nhanhlet 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;20 unmodified lines...input,quantity: qty,printTech: 'digital',}, paperType, offsetMachine, digitalMachine, allFinishingServices);// Tính thử chi phí offsetconst offResult = runQuickEstimate({...input,quantity: qty,printTech: 'offset',}, paperType, offsetMachine, digitalMachine, allFinishingServices);comparisonTable.push({quantity: qty,15 unmodified lines}// 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 {23 unmodified linesvatAmount,finalPrice,unitPrice,},chosenTech,recommendation: {14 unmodified linespaperType: 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;4 unmodified linesbleedMm: 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 pAbove = paperType.priceAbove500 || paperType.pricePerRam;const pBelow = paperType.priceBelow500 || pAbove;const effectiveRamPrice = parentSheets >= 500 ? pAbove : pBelow;const paperCost = Math.round(parentSheets * (effectiveRamPrice / 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 || matchOffsetMachine(imposition.printSheet);const baseImpressions = machine.baseImpressions || 3000;2 unmodified lines345678910111 unmodified line131415161718192021222324252627282930313233343536373839404142434445464748495051525326 unmodified lines80818283848538 unmodified lines12412512612712812913013113213313413516 unmodified lines15215315415515615715816 unmodified lines17517617717817918018118218318418556 unmodified lines24224324424524624724824925025125225325425527 unmodified lines28328428528628728828929029129229329429530 unmodified lines32632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648720 unmodified lines50850951051151251351451551651751851952052115 unmodified lines53753853954054154254354454554654754854955055155223 unmodified lines57657757857958058158258314 unmodified lines5985996006016026036046056066076086094 unmodified lines6146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546552 unmodified linesCalculationResult,ComparisonItem,DigitalMachine,DigitalMode,DigitalPrintGiaCong,DigitalPrintKemGiay,FinishingCostDetail,FinishingService,OffsetMachine,1 unmodified line} from '@/types';import { calculateImposition } from './imposition';export const DEFAULT_DIGITAL_GIA_CONG: DigitalPrintGiaCong[] = [{ id: 1, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: 'A4', widthMm: 210, heightMm: 297, paperLt249: 600, paper250To349: 800, paper350To450: 1000, decalPaperPlastic: 1200, decalClear: 1500, syntheticPaper: 1000, pvcPlastic: 1500 },{ id: 2, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: '330x355', widthMm: 330, heightMm: 355, paperLt249: 800, paper250To349: 1000, paper350To450: 1800, decalPaperPlastic: 1500, decalClear: 1700, syntheticPaper: 1800, pvcPlastic: 2000 },{ id: 3, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: 'A3', widthMm: 297, heightMm: 420, paperLt249: 1200, paper250To349: 1600, paper350To450: 2100, decalPaperPlastic: 2100, decalClear: 2300, syntheticPaper: 2100, pvcPlastic: 2500 },{ id: 4, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: '330x483', widthMm: 330, heightMm: 483, paperLt249: 2000, paper250To349: 2500, paper350To450: 2700, decalPaperPlastic: 2500, decalClear: 2800, syntheticPaper: 2700, pvcPlastic: 3000 },{ id: 5, machineName: 'KONICA C12000 / C12010S 5 MÀU', sheetSize: '330x1200', widthMm: 330, heightMm: 1200, paperLt249: 4000, paper250To349: 7000, paper350To450: 10000, decalPaperPlastic: 6000, decalClear: 7500, syntheticPaper: 15000, pvcPlastic: 0 },];export const DEFAULT_DIGITAL_KEM_GIAY: DigitalPrintKemGiay[] = [{ id: 1, paperCode: 'C100', paperName: 'Couche 100gsm', gsm: 100, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1600, price2Side: 2800 },{ id: 2, paperCode: 'C120', paperName: 'Couche 120gsm', gsm: 120, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1700, price2Side: 2900 },{ id: 3, paperCode: 'C150', paperName: 'Couche 150gsm', gsm: 150, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1800, price2Side: 3000 },{ id: 4, paperCode: 'C200', paperName: 'Couche 200gsm', gsm: 200, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1900, price2Side: 3100 },{ id: 5, paperCode: 'C250', paperName: 'Couche 250gsm', gsm: 250, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2100, price2Side: 3300 },{ id: 6, paperCode: 'C300', paperName: 'Couche 300gsm', gsm: 300, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2700, price2Side: 4300 },{ id: 7, paperCode: 'I250', paperName: 'Ivory 250gsm', gsm: 250, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2100, price2Side: 3300 },{ id: 8, paperCode: 'I300', paperName: 'Ivory 300gsm', gsm: 300, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2600, price2Side: 4200 },{ id: 9, paperCode: 'I350', paperName: 'Ivory 350gsm', gsm: 350, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 3300, price2Side: 5300 },{ id: 10, paperCode: 'F100', paperName: 'Fort 100gsm', gsm: 100, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1600, price2Side: 2800 },{ id: 11, paperCode: 'F120', paperName: 'Fort 120gsm', gsm: 120, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1700, price2Side: 2900 },{ id: 12, paperCode: 'F180', paperName: 'Fort 180gsm', gsm: 180, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 1900, price2Side: 3100 },{ id: 13, paperCode: 'F230', paperName: 'Fort 230gsm', gsm: 230, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2100, price2Side: 3300 },{ id: 14, paperCode: 'F250', paperName: 'Fort 250gsm', gsm: 250, sheetSize: '325x430', widthMm: 325, heightMm: 430, price1Side: 2300, price2Side: 3500 },{ id: 15, paperCode: 'F180_355', paperName: 'Fort 180gsm (325x355)', gsm: 180, sheetSize: '325x355', widthMm: 325, heightMm: 355, price1Side: 1400, price2Side: 2200 },{ id: 16, paperCode: 'F230_355', paperName: 'Fort 230gsm (325x355)', gsm: 230, sheetSize: '325x355', widthMm: 325, heightMm: 355, price1Side: 1500, price2Side: 2300 },];interface CostCalculatorOptions {input: CalculationInput;paperType: PaperType;offsetMachine?: OffsetMachine;allOffsetMachines?: OffsetMachine[];digitalMachine?: DigitalMachine;digitalPricingGiaCong?: DigitalPrintGiaCong[];digitalPricingKemGiay?: DigitalPrintKemGiay[];allFinishingServices: FinishingService[];}26 unmodified lines(m) => m.name.includes('65x86') || m.maxWidthMm >= 800 || m.maxHeightMm >= 800);if (large) return large;}// Fallback mặc định chuẩn theo yêu cầu xưởng in38 unmodified linesoffsetMachine,allOffsetMachines,digitalMachine,digitalPricingGiaCong = DEFAULT_DIGITAL_GIA_CONG,digitalPricingKemGiay = DEFAULT_DIGITAL_KEM_GIAY,allFinishingServices,}: CostCalculatorOptions): CalculationResult {const digitalMode: DigitalMode = input.digitalMode || 'with_paper';// 1. Xác định công nghệ in mục tiêulet chosenTech: 'offset' | 'digital' = 'offset';if (input.printTech === 'digital') {16 unmodified linesbleedMm: input.bleedMm ?? 2,paperType,printTech: chosenTech,digitalMode,preferredMachineSheet: preferredSheet,gripperMarginMm: offsetMachine?.gripperMarginMm ?? 10,});16 unmodified lines// Tính chi phí từng mục gia cônglet subtotal = 0;let formula = '';if (service.calcType === 'per_m2') {const areaM2 = ((input.widthMm + (input.bleedMm || 2) * 2) / 1000) *((input.heightMm + (input.bleedMm || 2) * 2) / 1000) *input.quantity * (sel.sides || 1);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')}đ)`;56 unmodified lines// Nếu số tờ mẹ >= 500 (trên 1 ram) áp dụng giá sỉ nguyên ram, nếu < 500 tờ áp dụng giá lẻ dưới ramconst isWholesale = parentSheetsNeeded >= 500;const effectiveRamPrice = isWholesale ? priceAbove500 : priceBelow500;let paperCost = Math.round(parentSheetsNeeded * (effectiveRamPrice / 500));// 6. Tiền in ấnlet plateCost = 0;let platesCount = 0;let printRunCost = 0;let shortRunFee = 0;let digitalDetails: CalculationResult['costs']['digitalDetails'] | undefined;if (chosenTech === 'offset') {const machine = offsetMachine || matchOffsetMachine(imposition.printSheet, allOffsetMachines, input.offsetMachineId);27 unmodified lines// In 2 mặtif (workType === 'sheetwise') {// In 2 bài riêng: 2 ca in độc lập, 2 bộ kẽmconst colors = (input.colorsFront || 4) + (input.colorsBack || 4);platesCount = colors;if (includesPlate) {// Gói mở máy đã bao gồm 1 bộ kẽm 4 màu cơ bản, bài thứ 2 hoặc màu thứ 5+ tính riêng kẽmconst extraColors = Math.max(0, colors - 4);plateCost = extraColors * machine.platePrice;} else {plateCost = platesCount * machine.platePrice;}30 unmodified lines}}} else {// In nhanh kỹ thuật số (Digital)const is2Sides = input.printSides === '2_side';let ratePerSheet = 0;let machineName = '';let sheetSizeName = imposition.printSheet.name;let whiteInkCost = 0;// Phụ phí số lượng ít:// < 50 tờ: +30.000đ// < 100 tờ: +20.000đ// >= 100 tờ: 0đif (totalPrintSheets < 50) {shortRunFee = 30000;} else if (totalPrintSheets < 100) {shortRunFee = 20000;} else {shortRunFee = 0;}if (digitalMode === 'with_paper') {// 1. In nhanh kèm giấy (INTC) - Đã gồm tiền giấy trọn góimachineName = 'In Nhanh Kèm Giấy (INTC)';const kemGiayList = digitalPricingKemGiay && digitalPricingKemGiay.length > 0? digitalPricingKemGiay: DEFAULT_DIGITAL_KEM_GIAY;// Tìm dòng giá phù hợp theo mã giấylet matchedPricing = kemGiayList.find((kg) =>paperType.code.toUpperCase().includes(kg.paperCode.toUpperCase()));// Nếu không khớp chính xác mã, so khớp theo tiền tố chất liệu (C, I, F) + GSM gần nhấtif (!matchedPricing) {const pName = paperType.name.toLowerCase();let prefix = 'C';if (pName.includes('ivory') || paperType.code.toUpperCase().startsWith('I')) prefix = 'I';else if (pName.includes('fort') || pName.includes('ford') || paperType.code.toUpperCase().startsWith('F')) prefix = 'F';const sameType = kemGiayList.filter((kg) => kg.paperCode.startsWith(prefix));if (sameType.length > 0) {matchedPricing = sameType.reduce((prev, curr) =>Math.abs(curr.gsm - paperType.gsm) < Math.abs(prev.gsm - paperType.gsm) ? curr : prev);} else {matchedPricing = kemGiayList[0];}}if (matchedPricing) {ratePerSheet = is2Sides ? matchedPricing.price2Side : matchedPricing.price1Side;sheetSizeName = `${matchedPricing.sheetSize} mm (${matchedPricing.paperName})`;} else {ratePerSheet = is2Sides ? 3000 : 1800;}printRunCost = Math.round(totalPrintSheets * ratePerSheet) + shortRunFee;// Đã kèm giấy nên tiền giấy = 0paperCost = 0;plateCost = 0;platesCount = 0;digitalDetails = {mode: 'with_paper',machineName,sheetSizeName,ratePerSheet,shortRunFee,note: `Bảng giá In Nhanh Kèm Giấy INTC (Đã gồm công in + giấy ${matchedPricing?.paperName || ''}). Phí SL ít: +${shortRunFee.toLocaleString('vi-VN')}đ`,};} else {// 2. In nhanh gia công (Konica C12000 / C12010S 5 màu - Trang 2 PDF)machineName = 'Konica C12000 / C12010S 5 Màu';const giaCongList = digitalPricingGiaCong && digitalPricingGiaCong.length > 0? digitalPricingGiaCong: DEFAULT_DIGITAL_GIA_CONG;// Nhận diện khổ in máyconst pW = imposition.printSheet.widthMm;const pH = imposition.printSheet.heightMm;const maxDim = Math.max(pW, pH);const minDim = Math.min(pW, pH);let sheetRow: DigitalPrintGiaCong | undefined;if (maxDim > 500) {sheetRow = giaCongList.find((g) => g.sheetSize === '330x1200');} else if (maxDim > 430 || minDim > 300) {sheetRow = giaCongList.find((g) => g.sheetSize === '330x483');} else if (maxDim > 360 || minDim > 250) {sheetRow = giaCongList.find((g) => g.sheetSize === 'A3');} else if (maxDim > 300) {sheetRow = giaCongList.find((g) => g.sheetSize === '330x355');} else {sheetRow = giaCongList.find((g) => g.sheetSize === 'A4');}if (!sheetRow) {sheetRow = giaCongList.find((g) => g.sheetSize === '330x483') || giaCongList[0];}// Nhận diện nhóm chất liệuconst pName = paperType.name.toLowerCase();let click1Side = 0;if (sheetRow) {if (pName.includes('pvc')) {click1Side = sheetRow.pvcPlastic || sheetRow.paper350To450;} else if (pName.includes('nhựa') || pName.includes('synthetic')) {click1Side = sheetRow.syntheticPaper;} else if (pName.includes('trong') && pName.includes('decal')) {click1Side = sheetRow.decalClear;} else if (pName.includes('decal')) {click1Side = sheetRow.decalPaperPlastic;} else {// Giấy thường theo định lượng GSMif (paperType.gsm < 250) {click1Side = sheetRow.paperLt249;} else if (paperType.gsm <= 349) {click1Side = sheetRow.paper250To349;} else {click1Side = sheetRow.paper350To450;}}sheetSizeName = `${sheetRow.sheetSize} (${sheetRow.widthMm}x${sheetRow.heightMm}mm)`;} else {click1Side = is2Sides ? 2000 : 1000;}// Giá in 2 mặt = x2 giá 1 mặtratePerSheet = is2Sides ? (click1Side * 2) : click1Side;// In mực trắng nếu có tùy chọnif (input.whiteInk) {whiteInkCost = totalPrintSheets * (is2Sides ? 4000 : 2000);}printRunCost = Math.round(totalPrintSheets * ratePerSheet) + whiteInkCost + shortRunFee;// Nếu khách tự cấp giấy -> tiền giấy = 0if (input.customerSuppliedPaper) {paperCost = 0;}plateCost = 0;platesCount = 0;digitalDetails = {mode: 'without_paper',machineName,sheetSizeName,ratePerSheet,shortRunFee,whiteInkCost,note: `In Gia Công Konica C12000 (Khổ ${sheetSizeName}, Đơn giá ${ratePerSheet.toLocaleString('vi-VN')}đ/tờ). Phí SL ít: +${shortRunFee.toLocaleString('vi-VN')}đ${input.customerSuppliedPaper ? ' • Khách cấp giấy' : ''}`,};}}const totalPrintCost = plateCost + printRunCost;20 unmodified lines...input,quantity: qty,printTech: 'digital',}, paperType, offsetMachine, digitalMachine, allFinishingServices, digitalPricingGiaCong, digitalPricingKemGiay);// Tính thử chi phí offsetconst offResult = runQuickEstimate({...input,quantity: qty,printTech: 'offset',}, paperType, offsetMachine, digitalMachine, allFinishingServices, digitalPricingGiaCong, digitalPricingKemGiay);comparisonTable.push({quantity: qty,15 unmodified lines}// 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, digitalPricingGiaCong, digitalPricingKemGiay);const curOffset = runQuickEstimate({ ...input, printTech: 'offset' }, paperType, offsetMachine, digitalMachine, allFinishingServices, digitalPricingGiaCong, digitalPricingKemGiay);let recommendationText = '';const diff = Math.abs(curDigital.finalPrice - curOffset.finalPrice);if (curDigital.finalPrice < curOffset.finalPrice) {recommendationText = `Với số lượng ${input.quantity.toLocaleString('vi-VN')} sản phẩm, In Nhanh KTS tiết kiệm hơn In Offset ${diff.toLocaleString('vi-VN')}đ (${Math.round((diff / curOffset.finalPrice) * 100)}%), không tốn phí mở máy và kẽm CTP, lấy nhanh trong ngày.`;} else {recommendationText = `Với số lượng ${input.quantity.toLocaleString('vi-VN')} sản phẩm, In Offset tối ưu chi phí hơn In Nhanh ${diff.toLocaleString('vi-VN')}đ (${Math.round((diff / curDigital.finalPrice) * 100)}%), giá đơn vị giảm sâu theo số lượng lớn.`;}return {23 unmodified linesvatAmount,finalPrice,unitPrice,shortRunFee,digitalDetails,},chosenTech,recommendation: {14 unmodified linespaperType: PaperType,offsetMachine?: OffsetMachine,digitalMachine?: DigitalMachine,allFinishingServices: FinishingService[] = [],digitalPricingGiaCong: DigitalPrintGiaCong[] = DEFAULT_DIGITAL_GIA_CONG,digitalPricingKemGiay: DigitalPrintKemGiay[] = DEFAULT_DIGITAL_KEM_GIAY): { finalPrice: number; unitPrice: number } {const isDigital = input.printTech === 'digital';const digitalMode: DigitalMode = input.digitalMode || 'with_paper';const preferredSheet = !isDigital && offsetMachine? { widthMm: offsetMachine.maxWidthMm, heightMm: offsetMachine.maxHeightMm, name: offsetMachine.name }: undefined;4 unmodified linesbleedMm: input.bleedMm ?? 2,paperType,printTech: input.printTech,digitalMode,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 + 10;const cuts = Math.max(1, imposition.cutsPerParentSheet);const parentSheets = Math.ceil(totalSheets / cuts);const pAbove = paperType.priceAbove500 || paperType.pricePerRam;const pBelow = paperType.priceBelow500 || pAbove;const effectiveRamPrice = parentSheets >= 500 ? pAbove : pBelow;let paperCost = Math.round(parentSheets * (effectiveRamPrice / 500));let printCost = 0;if (isDigital) {const is2Sides = input.printSides === '2_side';let shortFee = 0;if (totalSheets < 50) shortFee = 30000;else if (totalSheets < 100) shortFee = 20000;if (digitalMode === 'with_paper') {const matched = digitalPricingKemGiay.find((kg) =>paperType.code.toUpperCase().includes(kg.paperCode.toUpperCase())) || digitalPricingKemGiay[0];const rate = is2Sides ? matched.price2Side : matched.price1Side;printCost = Math.round(totalSheets * rate) + shortFee;paperCost = 0;} else {const isA3 = imposition.printSheet.widthMm > 220 || imposition.printSheet.heightMm > 310;const rate = isA3 ? (is2Sides ? 4000 : 2000) : (is2Sides ? 1600 : 800);printCost = Math.round(totalSheets * rate) + shortFee;if (input.customerSuppliedPaper) paperCost = 0;}} else {const machine = offsetMachine || matchOffsetMachine(imposition.printSheet);const baseImpressions = machine.baseImpressions || 3000;
12341 unmodified line6789101113 unmodified lines25262728293016 unmodified lines4748495051525354555657584 unmodified lines63646566676869import { BoxCoordinate, ImpositionResult, PaperCutBlock, PaperCutLine, PaperCutScheme, PaperType, PrintTech } from '@/types';interface ImpositionOptions {widthMm: number;1 unmodified linebleedMm?: number;paperType: PaperType;printTech: PrintTech;preferredMachineSheet?: { widthMm: number; heightMm: number; name: string };gripperMarginMm?: number;}13 unmodified linesbleedMm = 2,paperType,printTech,preferredMachineSheet,gripperMarginMm = 10,}: ImpositionOptions): ImpositionResult {16 unmodified linesgripperMarginMm,});} else if (printTech === 'digital') {// In nhanh KTS: các khổ in máy tiêu chuẩn A3+, A3, A4const digitalCandidates = [{ name: 'Khổ A3+ (330 x 488 mm)', w: 488, h: 330, cuts: 4 },{ name: 'Khổ A3 chuẩn (297 x 420 mm)', w: 420, h: 297, cuts: 4 },{ name: 'Khổ A4 chuẩn (210 x 297 mm)', w: 297, h: 210, cuts: 8 },];for (const dc of digitalCandidates) {const cuts = calculateCutsFromParent(parentW, parentH, dc.w, dc.h);4 unmodified linessheetHeightMm: dc.h,cutsFromParent: cuts,cutScheme,gripperMarginMm: 5,});}} else {12341 unmodified line678910111213 unmodified lines2627282930313216 unmodified lines49505152535455565758596061626364656667686970717273744 unmodified lines79808182838485import { BoxCoordinate, DigitalMode, ImpositionResult, PaperCutBlock, PaperCutLine, PaperCutScheme, PaperType, PrintTech } from '@/types';interface ImpositionOptions {widthMm: number;1 unmodified linebleedMm?: number;paperType: PaperType;printTech: PrintTech;digitalMode?: DigitalMode;preferredMachineSheet?: { widthMm: number; heightMm: number; name: string };gripperMarginMm?: number;}13 unmodified linesbleedMm = 2,paperType,printTech,digitalMode = 'with_paper',preferredMachineSheet,gripperMarginMm = 10,}: ImpositionOptions): ImpositionResult {16 unmodified linesgripperMarginMm,});} else if (printTech === 'digital') {// In nhanh KTS: Theo chuẩn Bảng Giá In Nhanh Kèm Giấy & In Gia Công Konica C12000let digitalCandidates: { name: string; w: number; h: number; cuts: number }[] = [];if (digitalMode === 'with_paper') {// BẢNG GIÁ IN NHANH KÈM GIẤY: Khổ 325 x 430 mm (chính) & 325 x 355 mm (Fort)digitalCandidates = [{ name: 'Khổ in kèm giấy (325 x 430 mm)', w: 430, h: 325, cuts: 4 },{ name: 'Khổ in kèm giấy đứng (325 x 430 mm)', w: 325, h: 430, cuts: 4 },{ name: 'Khổ in kèm giấy (325 x 355 mm)', w: 355, h: 325, cuts: 4 },];} else {// BẢNG GIÁ IN GIA CÔNG KONICA C12000 / C12010S: 5 khổ in máydigitalCandidates = [{ name: 'Khổ Konica A3+ (330 x 483 mm)', w: 483, h: 330, cuts: 4 },{ name: 'Khổ Konica A3 chuẩn (297 x 420 mm)', w: 420, h: 297, cuts: 4 },{ name: 'Khổ Konica 330 x 355 mm', w: 355, h: 330, cuts: 4 },{ name: 'Khổ Konica A4 chuẩn (210 x 297 mm)', w: 297, h: 210, cuts: 8 },{ name: 'Khổ Konica Banner (330 x 1200 mm)', w: 1200, h: 330, cuts: 1 },];}for (const dc of digitalCandidates) {const cuts = calculateCutsFromParent(parentW, parentH, dc.w, dc.h);4 unmodified linessheetHeightMm: dc.h,cutsFromParent: cuts,cutScheme,gripperMarginMm: 4,});}} else {
35 unmodified lines36373839404156 unmodified lines9899100101102103117 unmodified lines22122222322422522635 unmodified linesincludesPlate?: boolean; // Đã bao gồm kẽm CTP trong phí mở máy}export interface DigitalMachine {id: number;name: string;56 unmodified linesoffsetWorkType?: OffsetWorkType;offsetMachineId?: number;digitalMachineId?: number;selectedFinishing: SelectedFinishing[];profitMarginPercent: number;discountAmount?: number;117 unmodified linesvatAmount: number;finalPrice: number;unitPrice: number;};chosenTech: 'offset' | 'digital';recommendation?: {35 unmodified lines363738394041424344454647484950515253545556575859606162636465666768697056 unmodified lines127128129130131132133134135117 unmodified lines25325425525625725825926026126226326426526626726835 unmodified linesincludesPlate?: boolean; // Đã bao gồm kẽm CTP trong phí mở máy}export type DigitalMode = 'with_paper' | 'without_paper'; // In nhanh kèm giấy hoặc In gia công không kèm giấyexport interface DigitalPrintGiaCong {id: number;machineName: string;sheetSize: string; // 'A4' | '330x355' | 'A3' | '330x483' | '330x1200'widthMm: number;heightMm: number;paperLt249: number; // Giấy (<249gsm)paper250To349: number; // Giấy (250gsm - 349gsm)paper350To450: number; // Giấy (350gsm - 450gsm)decalPaperPlastic: number; // Decal (giấy - nhựa)decalClear: number; // Decal trongsyntheticPaper: number; // Giấy nhựa (<280gsm)pvcPlastic: number; // Nhựa PVC}export interface DigitalPrintKemGiay {id: number;paperCode: string;paperName: string;gsm: number;sheetSize: string; // '325x430' | '325x355'widthMm: number;heightMm: number;price1Side: number; // In 1 mặt + giấyprice2Side: number; // In 2 mặt + giấy}export interface DigitalMachine {id: number;name: string;56 unmodified linesoffsetWorkType?: OffsetWorkType;offsetMachineId?: number;digitalMachineId?: number;digitalMode?: DigitalMode; // 'with_paper' (Kèm giấy xưởng) | 'without_paper' (In gia công Konica)customerSuppliedPaper?: boolean; // Nếu in gia công mà khách mang giấy đến -> tiền giấy = 0whiteInk?: boolean; // Tùy chọn in mực trắng (Konica C12000)selectedFinishing: SelectedFinishing[];profitMarginPercent: number;discountAmount?: number;117 unmodified linesvatAmount: number;finalPrice: number;unitPrice: number;shortRunFee?: number; // Phí số lượng ít (<50 tờ: +30k, <100 tờ: +20k)digitalDetails?: {mode: DigitalMode;machineName?: string;sheetSizeName?: string;ratePerSheet: number;shortRunFee: number;whiteInkCost?: number;note?: string;};};chosenTech: 'offset' | 'digital';recommendation?: {
.gitignore+3
data/digital_pricing_giacong.jsonAdded+67
data/digital_pricing_kem_giay.jsonAdded+162
scripts/extract_pdf_images.pyAdded+26
scripts/inspect_pdf_details.pyAdded+20
scripts/inspect_pdfs.pyAdded+37
scripts/setup_digital_pricing.pyAdded+110
scripts/update_cost_calculator.pyAdded+690
src/app/api/calculate/route.ts+47-2
src/app/api/machines/route.ts+63-1
src/app/page.tsx+78
src/components/CostBreakdownCard.tsx+37-2
src/components/MachineManager.tsx+569-246
src/lib/db.ts+77-1
src/lib/engine/costCalculator.ts+230-55
src/lib/engine/imposition.ts+24-8
src/types/index.ts+42