diff --git a/src/components/QuotePriceImportModal.test.tsx b/src/components/QuotePriceImportModal.test.tsx new file mode 100644 index 0000000..945336e --- /dev/null +++ b/src/components/QuotePriceImportModal.test.tsx @@ -0,0 +1,30 @@ +// @vitest-environment jsdom +import { render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { I18nProvider } from '../i18n/I18nProvider'; +import { QuotePriceImportModal } from './QuotePriceImportModal'; + +const lines = [ + { key: 'l1', sku_code: 'SKU1', sku_name: '白菜', cost_price: '1', sale_price: '2' }, +]; +const skus = [{ sku_code: 'SKU1', sku_name: '白菜', spec: '500g' }]; + +describe('QuotePriceImportModal', () => { + it('open=false 不渲染;打开显示导入成本价标题与模板/选文件入口', () => { + const { rerender } = render( + + + + ); + expect(screen.queryByText('导入成本价')).toBeNull(); + + rerender( + + + + ); + expect(screen.getByText(/导入成本价/)).toBeTruthy(); + expect(screen.getByText('下载模板')).toBeTruthy(); + expect(screen.getByText('选择 Excel')).toBeTruthy(); + }); +}); diff --git a/src/components/QuotePriceImportModal.tsx b/src/components/QuotePriceImportModal.tsx new file mode 100644 index 0000000..2dcb7c8 --- /dev/null +++ b/src/components/QuotePriceImportModal.tsx @@ -0,0 +1,343 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { AlertCircle, CheckCircle2, Download, FileSpreadsheet, Loader2, Upload, X } from 'lucide-react'; +import { useI18n } from '../i18n/I18nProvider'; +import { DialogOverlay } from './ui/DialogOverlay'; +import { parseExcelFileDetailed, type ParsedExcel } from '../utils/excelImportExport'; +import { + autoMapColumns, + missingRequiredFields, + remapRows, + type ColumnMapping, + type ImportFieldDef, + type MappingConfidence, +} from '../utils/smartColumnMapping'; +import { + downloadQuotePriceImportTemplate, + planQuotePriceImport, + type QuotePriceImportLine, + type QuotePriceImportMode, + type QuotePriceImportPlan, + type QuotePriceImportSku, +} from '../utils/quotePriceImport'; + +type Props = { + open: boolean; + mode: QuotePriceImportMode; + lines: QuotePriceImportLine[]; + skus: QuotePriceImportSku[]; + onClose: () => void; + onApply: (updates: Array<{ lineKey: string; value: string }>) => void; +}; + +function importFields(mode: QuotePriceImportMode, t: (key: string) => string): ImportFieldDef[] { + const priceLabel = mode === 'cost' ? t('quotes.priceImport.costPrice') : t('quotes.priceImport.salePrice'); + return [ + { + key: 'name', + label: t('quotes.priceImport.colName'), + required: true, + templateHeader: '商品名*', + aliases: ['商品名', '商品名称', '品名', '产品名称', '名称', 'sku名称', 'itemname', 'productname', 'name'], + patterns: [/品名|商品名|名称/], + }, + { + key: 'spec', + label: t('quotes.priceImport.colSpec'), + templateHeader: '规格', + aliases: ['规格', '规格型号', '规格详情', '型号', 'spec', 'specification'], + patterns: [/规格|型号/], + }, + { + key: 'price', + label: priceLabel, + required: true, + templateHeader: `${priceLabel}*`, + aliases: [priceLabel, `${priceLabel}*`, mode === 'cost' ? '成本单价' : '销售单价', mode === 'cost' ? '成本' : '售价', mode === 'cost' ? '进价' : '单价', mode === 'cost' ? 'cost' : 'sale', mode === 'cost' ? 'costprice' : 'saleprice'], + patterns: [mode === 'cost' ? /成本|进价|采购价/ : /销售价|售价|单价|报价/], + }, + ]; +} + +export function QuotePriceImportModal({ open, mode, lines, skus, onClose, onApply }: Props) { + const { t } = useI18n(); + const inputRef = useRef(null); + const [step, setStep] = useState<'pick' | 'mapping' | 'preview'>('pick'); + const [parsing, setParsing] = useState(false); + const [fileName, setFileName] = useState(''); + const [parsed, setParsed] = useState(null); + const [mapping, setMapping] = useState({}); + const [confidence, setConfidence] = useState>({}); + const [plan, setPlan] = useState(null); + const [error, setError] = useState(''); + const [downloading, setDownloading] = useState(false); + const fields = importFields(mode, t); + const label = mode === 'cost' ? t('quotes.priceImport.costPrice') : t('quotes.priceImport.salePrice'); + + useEffect(() => { + if (!open) return; + setStep('pick'); + setParsing(false); + setFileName(''); + setParsed(null); + setMapping({}); + setConfidence({}); + setPlan(null); + setError(''); + if (inputRef.current) inputRef.current.value = ''; + }, [open, mode, t]); + + if (!open) return null; + + const handleFile = async (file: File | undefined) => { + if (!file) return; + setParsing(true); + setError(''); + setPlan(null); + setFileName(file.name); + try { + const detail = await parseExcelFileDetailed(file, { + preferredSheetNames: [`${label}导入`, '报价导入', '报价单', '商品'], + requiredHeaderHints: ['商品名', label], + }); + if (!detail.rows.length) { + setError(t('quotes.priceImport.noRows', { label })); + setStep('pick'); + return; + } + const auto = autoMapColumns(detail.headers, fields); + setParsed(detail); + setMapping(auto.mapping); + setConfidence(auto.confidence); + setStep('mapping'); + } catch (err: any) { + setError(err?.message || t('quotes.priceImport.parseFail')); + setStep('pick'); + } finally { + setParsing(false); + } + }; + + const downloadTemplate = async () => { + setDownloading(true); + try { + await downloadQuotePriceImportTemplate(mode); + } finally { + setDownloading(false); + } + }; + + const missing = missingRequiredFields(mapping, fields); + const fieldToHeader: Record = {}; + for (const [header, key] of Object.entries(mapping)) if (key) fieldToHeader[key] = header; + + const setFieldSource = (fieldKey: string, sourceHeader: string) => { + setMapping((prev) => { + const next = { ...prev }; + for (const h of Object.keys(next)) { + if (next[h] === fieldKey) next[h] = ''; + } + if (sourceHeader) next[sourceHeader] = fieldKey; + return next; + }); + }; + + const runMatch = () => { + if (!parsed || missing.length > 0) return; + const rows = remapRows(parsed.rows, mapping, fields); + setPlan(planQuotePriceImport({ mode, rows, lines, skus })); + setStep('preview'); + }; + + return ( +
+
+
+
+

+ + {t('quotes.priceImport.title', { label })} +

+

{t('quotes.priceImport.hint', { label })}

+
+
+ + +
+
+ +
+
+ void handleFile(e.target.files?.[0])} /> + {step === 'pick' && ( + + )} + {fileName && {fileName}} + {step === 'mapping' && parsed && ( + + {t('quotes.priceImport.mappingHint')} + + )} + {step === 'preview' && plan && ( + + {t('quotes.priceImport.summary', { matched: plan.matched, skipped: plan.skipped, failed: plan.failed })} + + )} +
+ {error && ( +
+ + {error} +
+ )} +
+ +
+ {step === 'pick' && ( +
+ {t('quotes.priceImport.pickHint', { label })} +
+ )} + + {step === 'mapping' && parsed && ( +
+

{t('quotes.priceImport.mappingTitle')}

+ {missing.length > 0 && ( +
+ + {t('bulkImport.mapping.missingRequired', { fields: missing.map((f) => f.label).join(t('bulkImport.mapping.listSep')) })} +
+ )} +
+ + + + + + + + + + {fields.map((field) => { + const sourceHeader = fieldToHeader[field.key] || ''; + const conf = sourceHeader ? confidence[sourceHeader] : 'none'; + const sample = sourceHeader ? parsed.rows.slice(0, 2).map((r) => r[sourceHeader]).filter(Boolean).join(' / ') : ''; + return ( + + + + + + ); + })} + +
{t('bulkImport.mapping.col.systemField')}{t('bulkImport.mapping.col.sourceColumn')}{t('bulkImport.mapping.col.sample')}
+ {field.label} + {field.required && *} + {sourceHeader && conf === 'medium' &&
{t('bulkImport.mapping.confidence.medium')}
} + {sourceHeader && conf === 'high' &&
{t('bulkImport.mapping.confidence.high')}
} +
+ + {sample || '—'}
+
+
+ )} + + {step === 'preview' && plan && ( + + + + + + + + + + + + + {plan.rows.map((row) => ( + + + + + + + + + ))} + +
{t('quotes.priceImport.colName')}{t('quotes.priceImport.colSpec')}{t('quotes.priceImport.colLine')}{t('quotes.priceImport.colOld')}{t('quotes.priceImport.colNew')}{t('quotes.priceImport.colStatus')}
{row.name || '-'}{row.spec || '-'}{row.lineLabel || '-'}{row.oldValue ?? '-'}{row.newValue || '-'} + {row.status === 'matched' ? ( + {t('quotes.priceImport.statusMatched')} + ) : row.status === 'skipped' ? ( + {t('quotes.priceImport.statusSkipped')}{row.reason ? `:${row.reason}` : ''} + ) : ( + {t('quotes.priceImport.statusFailed')}{row.reason ? `:${row.reason}` : ''} + )} +
+ )} +
+ +
+ {step === 'mapping' && ( + + )} + {step === 'preview' && ( + + )} + + {step === 'mapping' ? ( + + ) : step === 'preview' ? ( + + ) : null} +
+
+
+ ); +} diff --git a/src/i18n/locales/en/quotes.ts b/src/i18n/locales/en/quotes.ts index aff5443..14f878c 100644 --- a/src/i18n/locales/en/quotes.ts +++ b/src/i18n/locales/en/quotes.ts @@ -147,6 +147,33 @@ export const quotes: MessageDict = { 'import.templateHint': 'Headers: No., product name, L1/L2 category, spec, manufacturer, spec detail, cost, sale price. Products must already exist in the library.', 'import.completeToast': 'Quote lines loaded; review and save the quote sheet', + 'priceImport.importCost': 'Import cost price', + 'priceImport.importSale': 'Import sale price', + 'priceImport.costPrice': 'cost price', + 'priceImport.salePrice': 'sale price', + 'priceImport.title': 'Import {label}', + 'priceImport.hint': 'Matched by product name against the current quote. Use spec to disambiguate duplicate names. Only {label} changes; other fields and sale ratio stay unchanged.', + 'priceImport.downloadTemplate': 'Download template', + 'priceImport.selectFile': 'Choose Excel', + 'priceImport.parsing': 'Parsing…', + 'priceImport.summary': '{matched} updatable, {skipped} skipped, {failed} failed', + 'priceImport.noRows': 'No usable rows. Make sure the file contains "product name" and "{label}".', + 'priceImport.parseFail': 'Failed to parse Excel', + 'priceImport.pickHint': 'Choose a filled "{label}" Excel. A preview appears before anything is changed.', + 'priceImport.colName': 'Product', + 'priceImport.colSpec': 'Spec', + 'priceImport.colLine': 'Matched line', + 'priceImport.colOld': 'Old price', + 'priceImport.colNew': 'New price', + 'priceImport.colStatus': 'Status', + 'priceImport.statusMatched': 'Updatable', + 'priceImport.statusSkipped': 'Skipped', + 'priceImport.statusFailed': 'Failed', + 'priceImport.apply': 'Update ({count})', + 'priceImport.applied': 'Updated {count} line(s) {label}; save the quote to apply', + 'priceImport.mappingTitle': 'Map columns', + 'priceImport.mappingHint': 'Headers were auto-detected. Adjust product name / spec / price columns before matching.', + 'priceImport.next': 'Match', 'toast.loadSkusFail': 'Failed to load products', 'toast.loadSheetsFail': 'Failed to load quote sheets', diff --git a/src/i18n/locales/id/quotes.ts b/src/i18n/locales/id/quotes.ts index b968674..3c49876 100644 --- a/src/i18n/locales/id/quotes.ts +++ b/src/i18n/locales/id/quotes.ts @@ -151,6 +151,33 @@ export const quotes: MessageDict = { 'Header: No., nama produk, kategori L1/L2, spek, pabrik, detail spek, biaya, harga jual. Produk harus sudah ada di pustaka.', 'import.completeToast': 'Baris penawaran dimuat; periksa lalu simpan lembar penawaran', + 'priceImport.importCost': 'Impor harga modal', + 'priceImport.importSale': 'Impor harga jual', + 'priceImport.costPrice': 'harga modal', + 'priceImport.salePrice': 'harga jual', + 'priceImport.title': 'Impor {label}', + 'priceImport.hint': 'Dicocokkan berdasarkan nama produk pada penawaran saat ini; gunakan spesifikasi untuk nama ganda. Hanya {label} yang diubah, kolom lain dan rasio penjualan tetap.', + 'priceImport.downloadTemplate': 'Unduh templat', + 'priceImport.selectFile': 'Pilih Excel', + 'priceImport.parsing': 'Mengurai…', + 'priceImport.summary': '{matched} dapat diperbarui, {skipped} dilewati, {failed} gagal', + 'priceImport.noRows': 'Tidak ada baris yang bisa dipakai. Pastikan ada "nama produk" dan "{label}".', + 'priceImport.parseFail': 'Gagal mengurai Excel', + 'priceImport.pickHint': 'Pilih Excel "{label}" yang sudah diisi. Pratinjau tampil sebelum ada perubahan.', + 'priceImport.colName': 'Produk', + 'priceImport.colSpec': 'Spesifikasi', + 'priceImport.colLine': 'Baris cocok', + 'priceImport.colOld': 'Harga lama', + 'priceImport.colNew': 'Harga baru', + 'priceImport.colStatus': 'Status', + 'priceImport.statusMatched': 'Dapat diperbarui', + 'priceImport.statusSkipped': 'Dilewati', + 'priceImport.statusFailed': 'Gagal', + 'priceImport.apply': 'Perbarui ({count})', + 'priceImport.applied': '{count} baris {label} diperbarui; simpan penawaran untuk menerapkan', + 'priceImport.mappingTitle': 'Petakan kolom', + 'priceImport.mappingHint': 'Header terdeteksi otomatis. Sesuaikan kolom nama produk / spesifikasi / harga sebelum mencocokkan.', + 'priceImport.next': 'Cocokkan', 'toast.loadSkusFail': 'Gagal memuat produk', 'toast.loadSheetsFail': 'Gagal memuat lembar penawaran', diff --git a/src/i18n/locales/zh-CN/quotes.ts b/src/i18n/locales/zh-CN/quotes.ts index 77fb5b4..3055f46 100644 --- a/src/i18n/locales/zh-CN/quotes.ts +++ b/src/i18n/locales/zh-CN/quotes.ts @@ -145,6 +145,33 @@ export const quotes: MessageDict = { 'import.templateHint': '表头:序号、商品名、一级分类、二级分类、规格、厂家、规格详情、成本价、销售价。商品须已在商品库中存在。', 'import.completeToast': '报价明细已载入,请核对后保存报价单', + 'priceImport.importCost': '导入成本价', + 'priceImport.importSale': '导入销售价', + 'priceImport.costPrice': '成本价', + 'priceImport.salePrice': '销售价', + 'priceImport.title': '导入{label}', + 'priceImport.hint': '按商品名匹配当前报价单明细;同名商品可用规格区分,仅更新{label},其它字段和销售比例保持不变。', + 'priceImport.downloadTemplate': '下载模板', + 'priceImport.selectFile': '选择 Excel', + 'priceImport.parsing': '解析中…', + 'priceImport.summary': '可更新 {matched} 条,跳过 {skipped} 条,失败 {failed} 条', + 'priceImport.noRows': '表格里没有可用数据,请确认表头包含「商品名」和「{label}」', + 'priceImport.parseFail': '解析 Excel 失败', + 'priceImport.pickHint': '请选择填好的「{label}」Excel;匹配后会先展示预览,不会直接保存。', + 'priceImport.colName': '商品名', + 'priceImport.colSpec': '规格', + 'priceImport.colLine': '匹配到的明细', + 'priceImport.colOld': '原价格', + 'priceImport.colNew': '新价格', + 'priceImport.colStatus': '状态', + 'priceImport.statusMatched': '可更新', + 'priceImport.statusSkipped': '跳过', + 'priceImport.statusFailed': '失败', + 'priceImport.apply': '确认更新({count} 条)', + 'priceImport.applied': '已更新 {count} 条明细的{label},请保存报价单', + 'priceImport.mappingTitle': '映射导入列名', + 'priceImport.mappingHint': '系统已自动识别表头,可手动调整商品名/规格/价格列后再匹配。', + 'priceImport.next': '开始匹配', 'toast.loadSkusFail': '加载商品列表失败', 'toast.loadSheetsFail': '加载报价单失败', diff --git a/src/pages/customers/QuoteVersionManagement.priceImport.contract.test.ts b/src/pages/customers/QuoteVersionManagement.priceImport.contract.test.ts new file mode 100644 index 0000000..3902831 --- /dev/null +++ b/src/pages/customers/QuoteVersionManagement.priceImport.contract.test.ts @@ -0,0 +1,42 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +const page = readFileSync(new URL('./QuoteVersionManagement.tsx', import.meta.url), 'utf8'); +const modal = readFileSync(new URL('../../components/QuotePriceImportModal.tsx', import.meta.url), 'utf8'); + +describe('报价单导入成本价/销售价', () => { + it('明细区提供两个独立导入入口,并保留原 Excel 导入', () => { + expect(page).toContain("t('quotes.priceImport.importCost')"); + expect(page).toContain("t('quotes.priceImport.importSale')"); + expect(page).toContain("t('quotes.form.excelImport')"); + expect(page).toContain(' { + expect(page).toContain("const mode = priceImportMode === 'sale' ? 'sale' : 'cost';"); + expect(page).toContain("const field = mode === 'sale' ? 'sale_price' : 'cost_price';"); + expect(page).toContain('applyDetailPriceImport'); + expect(page).toContain('buildSheetItemsPayload(nextItems)'); + expect(page).toContain('[field]: byKey.get(line.key) || \'\''); + expect(page).not.toContain('markup_ratio: byKey'); + // 详情页也提供导入入口,并持久化只改目标价格 + expect(page).toContain("setPriceImportContext('detail')"); + expect(page).toContain("const field = mode === 'sale' ? 'sale_price' : 'cost_price';"); + expect(page).toContain('applyDetailPriceImport'); + expect(page).toContain('buildSheetItemsPayload(nextItems)'); + }); + + it('支持自动列名映射并能手动调整', () => { + expect(modal).toContain('autoMapColumns'); + expect(modal).toContain('remapRows'); + expect(modal).toContain("step === 'mapping'"); + expect(modal).toContain("t('quotes.priceImport.mappingTitle')"); + }); + + it('匹配后先进入预览表,确认后才 apply', () => { + expect(modal).toContain('planQuotePriceImport'); + expect(modal).toContain("t('quotes.priceImport.colStatus')"); + expect(modal).toContain('onApply(plan.updates)'); + expect(modal).toContain('disabled={!plan || plan.matched === 0}'); + }); +}); diff --git a/src/pages/customers/QuoteVersionManagement.tsx b/src/pages/customers/QuoteVersionManagement.tsx index 2b17b24..8900e5c 100644 --- a/src/pages/customers/QuoteVersionManagement.tsx +++ b/src/pages/customers/QuoteVersionManagement.tsx @@ -29,6 +29,8 @@ import { } from '../../utils/workflowApi'; import { DocumentExportButton } from '../../components/export/DocumentExportButton'; import { BulkImportModal } from '../../components/BulkImportModal'; +import { QuotePriceImportModal } from '../../components/QuotePriceImportModal'; +import type { QuotePriceImportMode } from '../../utils/quotePriceImport'; import { downloadQuoteImportTemplate, parseQuoteLinesFromExcel, @@ -683,6 +685,8 @@ export const QuoteVersionManagement: React.FC = () => { }, [lines]); const [importingLines, setImportingLines] = useState(false); const [showExcelImportModal, setShowExcelImportModal] = useState(false); + const [priceImportMode, setPriceImportMode] = useState(null); + const [priceImportContext, setPriceImportContext] = useState<'form' | 'detail'>('form'); const { categoryRows } = useCategoryRows({ enabledOnly: false }); const categoryLabelMap = useMemo(() => buildCategoryLabelMap(categoryRows), [categoryRows]); const createCategoryOptions = useMemo( @@ -1379,6 +1383,49 @@ export const QuoteVersionManagement: React.FC = () => { }); }; + const applyFormPriceImport = ( + mode: QuotePriceImportMode, + updates: Array<{ lineKey: string; value: string }> + ) => { + const byKey = new Map(updates.map((u) => [u.lineKey, u.value])); + const field = mode === 'sale' ? 'sale_price' : 'cost_price'; + setLines((prev) => + prev.map((line) => + byKey.has(line.key) ? { ...line, [field]: byKey.get(line.key) || '' } : line + ) + ); + notify.success(t('quotes.priceImport.applied', { count: updates.length, label: mode === 'sale' ? t('quotes.priceImport.salePrice') : t('quotes.priceImport.costPrice') })); + }; + + const applyDetailPriceImport = async ( + mode: QuotePriceImportMode, + updates: Array<{ lineKey: string; value: string }> + ) => { + const sheet = expandedDetail; + if (!sheet || !expandedEditable) return; + const bySku = new Map(updates.map((u) => [u.lineKey, Number(u.value)])); + const field = mode === 'sale' ? 'sale_price' : 'cost_price'; + const nextItems = (sheet.enrichedItems || []).map((item) => { + const value = bySku.get(item.sku_code); + if (value === undefined || !Number.isFinite(value)) return item; + return { ...item, [field]: value }; + }); + try { + const items = buildSheetItemsPayload(nextItems); + const response = await updateQuoteSheetApi(sheet.quote_sheet_code, { items }); + if (response.delivery_handoff && response.delivery_handoff.ok === false) { + notify.error(response.delivery_handoff.message || t('quotes.toast.updateFail')); + return; + } + await loadSheets({ silent: true }); + await loadExpandedDetail(sheet.quote_sheet_code, { silent: true }); + notify.success(t('quotes.priceImport.applied', { count: updates.length, label: mode === 'sale' ? t('quotes.priceImport.salePrice') : t('quotes.priceImport.costPrice') })); + } catch (error: any) { + notify.error(error?.message || t('quotes.toast.updateFail')); + await loadExpandedDetail(sheet.quote_sheet_code, { silent: true }); + } + }; + const handleExcelImport = async (file: File, preMapped?: Record[]) => { const { lines: imported, result } = await parseQuoteLinesFromExcel(file, skus, effectiveBranchCode, preMapped); if (imported.length) { @@ -1972,6 +2019,24 @@ export const QuoteVersionManagement: React.FC = () => { + 新增商品 ) : null} + {expandedEditable ? ( + <> + + + + ) : null} @@ -2313,6 +2378,20 @@ export const QuoteVersionManagement: React.FC = () => { > {t('quotes.form.excelImport')} + + {form.customer_codes.length > 0 && (