feat(报价单): 导入成本价/销售价(Excel 预览、自动列名映射、按商品名+规格匹配)

- 表单与详情均提供导入入口
- 先预览后应用,只改成本价/销售价,不动数量/客户/状态
- 自动识别列名并支持手动调整
- 补三语文案与契约/工具测试
This commit is contained in:
Ubuntu
2026-10-25 19:42:33 +08:00
parent 684958ea1f
commit ab6f95fdc7
9 changed files with 876 additions and 0 deletions
@@ -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(
<I18nProvider>
<QuotePriceImportModal open={false} mode="cost" lines={lines} skus={skus} onClose={vi.fn()} onApply={vi.fn()} />
</I18nProvider>
);
expect(screen.queryByText('导入成本价')).toBeNull();
rerender(
<I18nProvider>
<QuotePriceImportModal open mode="cost" lines={lines} skus={skus} onClose={vi.fn()} onApply={vi.fn()} />
</I18nProvider>
);
expect(screen.getByText(/导入成本价/)).toBeTruthy();
expect(screen.getByText('下载模板')).toBeTruthy();
expect(screen.getByText('选择 Excel')).toBeTruthy();
});
});
+343
View File
@@ -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<HTMLInputElement | null>(null);
const [step, setStep] = useState<'pick' | 'mapping' | 'preview'>('pick');
const [parsing, setParsing] = useState(false);
const [fileName, setFileName] = useState('');
const [parsed, setParsed] = useState<ParsedExcel | null>(null);
const [mapping, setMapping] = useState<ColumnMapping>({});
const [confidence, setConfidence] = useState<Record<string, MappingConfidence>>({});
const [plan, setPlan] = useState<QuotePriceImportPlan | null>(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<string, string> = {};
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 (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[120] p-4">
<div className="app-surface app-border app-foreground rounded-xl border w-full max-w-5xl max-h-[88vh] flex flex-col shadow-xl">
<div className="flex items-start justify-between gap-3 px-5 py-4 border-b app-border">
<div>
<h3 className="text-lg font-semibold flex items-center gap-2">
<FileSpreadsheet className="w-5 h-5" />
{t('quotes.priceImport.title', { label })}
</h3>
<p className="text-xs app-foreground-muted mt-1">{t('quotes.priceImport.hint', { label })}</p>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => void downloadTemplate()}
disabled={downloading}
className="inline-flex items-center gap-1.5 rounded-lg border app-border px-3 py-1.5 text-sm hover:bg-black/[0.04] disabled:opacity-50"
>
{downloading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
{t('quotes.priceImport.downloadTemplate')}
</button>
<button type="button" onClick={onClose} className="p-2 rounded-lg hover:bg-black/[0.04]" aria-label={t('common.close')}>
<X className="w-5 h-5" />
</button>
</div>
</div>
<div className="px-5 py-4 border-b app-border">
<div className="flex flex-wrap items-center gap-3">
<input ref={inputRef} type="file" accept=".xlsx,.xls,.csv" className="hidden" onChange={(e) => void handleFile(e.target.files?.[0])} />
{step === 'pick' && (
<button
type="button"
onClick={() => inputRef.current?.click()}
disabled={parsing}
className="inline-flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm text-white hover:bg-emerald-700 disabled:opacity-50"
>
{parsing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
{parsing ? t('quotes.priceImport.parsing') : t('quotes.priceImport.selectFile')}
</button>
)}
{fileName && <span className="text-sm app-foreground-muted">{fileName}</span>}
{step === 'mapping' && parsed && (
<span className="text-sm app-foreground-muted">
{t('quotes.priceImport.mappingHint')}
</span>
)}
{step === 'preview' && plan && (
<span className="text-sm app-foreground-muted">
{t('quotes.priceImport.summary', { matched: plan.matched, skipped: plan.skipped, failed: plan.failed })}
</span>
)}
</div>
{error && (
<div className="mt-3 flex items-start gap-2 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950/30 dark:text-red-300">
<AlertCircle className="w-4 h-4 mt-0.5 shrink-0" />
{error}
</div>
)}
</div>
<div className="flex-1 overflow-auto">
{step === 'pick' && (
<div className="px-5 py-12 text-center app-foreground-muted text-sm">
{t('quotes.priceImport.pickHint', { label })}
</div>
)}
{step === 'mapping' && parsed && (
<div className="space-y-4 p-5">
<p className="text-sm font-medium app-foreground">{t('quotes.priceImport.mappingTitle')}</p>
{missing.length > 0 && (
<div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-700 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300 flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
{t('bulkImport.mapping.missingRequired', { fields: missing.map((f) => f.label).join(t('bulkImport.mapping.listSep')) })}
</div>
)}
<div className="app-border rounded-lg border overflow-hidden">
<table className="w-full text-sm">
<thead className="app-surface-subtle">
<tr>
<th className="text-left px-3 py-2 font-medium">{t('bulkImport.mapping.col.systemField')}</th>
<th className="text-left px-3 py-2 font-medium">{t('bulkImport.mapping.col.sourceColumn')}</th>
<th className="text-left px-3 py-2 font-medium">{t('bulkImport.mapping.col.sample')}</th>
</tr>
</thead>
<tbody>
{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 (
<tr key={field.key} className="border-t app-border">
<td className="px-3 py-2">
<span className="font-medium">{field.label}</span>
{field.required && <span className="text-red-500 ml-0.5">*</span>}
{sourceHeader && conf === 'medium' && <div className="text-[10px] text-amber-600">{t('bulkImport.mapping.confidence.medium')}</div>}
{sourceHeader && conf === 'high' && <div className="text-[10px] text-emerald-600">{t('bulkImport.mapping.confidence.high')}</div>}
</td>
<td className="px-3 py-2">
<select
value={sourceHeader}
onChange={(e) => setFieldSource(field.key, e.target.value)}
className="app-surface app-border border rounded-lg px-2 py-1.5 text-sm w-full"
>
<option value="">{t('bulkImport.mapping.option.skip')}</option>
{parsed.headers.filter(Boolean).map((h) => <option key={h} value={h}>{h}</option>)}
</select>
</td>
<td className="px-3 py-2 app-foreground-muted text-xs max-w-[180px] truncate">{sample || '—'}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
)}
{step === 'preview' && plan && (
<table className="w-full text-sm">
<thead className="sticky top-0 z-10 bg-black/[0.03] app-foreground-muted">
<tr>
<th className="px-3 py-2 text-left font-medium">{t('quotes.priceImport.colName')}</th>
<th className="px-3 py-2 text-left font-medium">{t('quotes.priceImport.colSpec')}</th>
<th className="px-3 py-2 text-left font-medium">{t('quotes.priceImport.colLine')}</th>
<th className="px-3 py-2 text-right font-medium">{t('quotes.priceImport.colOld')}</th>
<th className="px-3 py-2 text-right font-medium">{t('quotes.priceImport.colNew')}</th>
<th className="px-3 py-2 text-left font-medium">{t('quotes.priceImport.colStatus')}</th>
</tr>
</thead>
<tbody>
{plan.rows.map((row) => (
<tr key={`${row.rowNo}-${row.name}-${row.spec}`} className="border-t app-border">
<td className="px-3 py-2">{row.name || '-'}</td>
<td className="px-3 py-2">{row.spec || '-'}</td>
<td className="px-3 py-2">{row.lineLabel || '-'}</td>
<td className="px-3 py-2 text-right">{row.oldValue ?? '-'}</td>
<td className="px-3 py-2 text-right">{row.newValue || '-'}</td>
<td className="px-3 py-2">
{row.status === 'matched' ? (
<span className="inline-flex items-center gap-1 text-emerald-700 dark:text-emerald-400"><CheckCircle2 className="w-4 h-4" />{t('quotes.priceImport.statusMatched')}</span>
) : row.status === 'skipped' ? (
<span className="text-gray-500">{t('quotes.priceImport.statusSkipped')}{row.reason ? `:${row.reason}` : ''}</span>
) : (
<span className="text-red-600 dark:text-red-400">{t('quotes.priceImport.statusFailed')}{row.reason ? `:${row.reason}` : ''}</span>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<div className="flex items-center justify-end gap-3 px-5 py-3 border-t app-border">
{step === 'mapping' && (
<button type="button" onClick={() => setStep('pick')} className="rounded-lg border app-border px-4 py-2 text-sm hover:bg-black/[0.04]">
{t('bulkImport.mapping.back')}
</button>
)}
{step === 'preview' && (
<button type="button" onClick={() => setStep('mapping')} className="rounded-lg border app-border px-4 py-2 text-sm hover:bg-black/[0.04]">
{t('bulkImport.confirm.back')}
</button>
)}
<button type="button" onClick={onClose} className="rounded-lg border app-border px-4 py-2 text-sm hover:bg-black/[0.04]">
{t('common.cancel')}
</button>
{step === 'mapping' ? (
<button
type="button"
onClick={runMatch}
disabled={!parsed || missing.length > 0}
className="rounded-lg bg-emerald-600 px-4 py-2 text-sm text-white hover:bg-emerald-700 disabled:opacity-50"
>
{t('quotes.priceImport.next')}
</button>
) : step === 'preview' ? (
<button
type="button"
disabled={!plan || plan.matched === 0}
onClick={() => plan && onApply(plan.updates)}
className="rounded-lg bg-emerald-600 px-4 py-2 text-sm text-white hover:bg-emerald-700 disabled:opacity-50"
>
{t('quotes.priceImport.apply', { count: plan?.matched ?? 0 })}
</button>
) : null}
</div>
</div>
</div>
);
}
+27
View File
@@ -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',
+27
View File
@@ -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',
+27
View File
@@ -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': '加载报价单失败',
@@ -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('<QuotePriceImportModal');
});
it('导入只更新目标价格字段,不改销售比例', () => {
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}');
});
});
@@ -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<QuotePriceImportMode | null>(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<string, string>[]) => {
const { lines: imported, result } = await parseQuoteLinesFromExcel(file, skus, effectiveBranchCode, preMapped);
if (imported.length) {
@@ -1972,6 +2019,24 @@ export const QuoteVersionManagement: React.FC = () => {
+ 新增商品
</button>
) : null}
{expandedEditable ? (
<>
<button
type="button"
onClick={() => { setPriceImportContext('detail'); setPriceImportMode('cost'); }}
className="mb-0.5 text-sm text-emerald-600 hover:underline"
>
{t('quotes.priceImport.importCost')}
</button>
<button
type="button"
onClick={() => { setPriceImportContext('detail'); setPriceImportMode('sale'); }}
className="mb-0.5 text-sm text-blue-600 hover:underline"
>
{t('quotes.priceImport.importSale')}
</button>
</>
) : null}
</div>
</div>
@@ -2313,6 +2378,20 @@ export const QuoteVersionManagement: React.FC = () => {
>
{t('quotes.form.excelImport')}
</button>
<button
type="button"
onClick={() => { setPriceImportContext('form'); setPriceImportMode('cost'); }}
className="text-sm text-emerald-600 hover:underline"
>
{t('quotes.priceImport.importCost')}
</button>
<button
type="button"
onClick={() => { setPriceImportContext('form'); setPriceImportMode('sale'); }}
className="text-sm text-blue-600 hover:underline"
>
{t('quotes.priceImport.importSale')}
</button>
{form.customer_codes.length > 0 && (
<button
type="button"
@@ -2445,6 +2524,31 @@ export const QuoteVersionManagement: React.FC = () => {
)}
</AnimatePresence>
<QuotePriceImportModal
open={priceImportMode !== null}
mode={priceImportMode || 'cost'}
lines={
priceImportContext === 'detail' && expandedDetail
? (expandedDetail.enrichedItems || []).map((item) => ({
key: item.sku_code,
sku_code: item.sku_code,
sku_name: item.sku_name || '',
cost_price: String(item.cost_price ?? ''),
sale_price: String(item.sale_price ?? ''),
}))
: lines
}
skus={skus}
onClose={() => setPriceImportMode(null)}
onApply={(updates) => {
const mode = priceImportMode === 'sale' ? 'sale' : 'cost';
const context = priceImportContext;
setPriceImportMode(null);
if (context === 'detail') void applyDetailPriceImport(mode, updates);
else applyFormPriceImport(mode, updates);
}}
/>
<BulkImportModal
open={showExcelImportModal}
title={t('quotes.import.modalTitle')}
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it } from 'vitest';
import { planQuotePriceImport, type QuotePriceImportLine, type QuotePriceImportSku } from './quotePriceImport';
const lines: QuotePriceImportLine[] = [
{ key: 'l1', sku_code: 'SKU1', sku_name: '白菜', cost_price: '1.00', sale_price: '2.00' },
{ key: 'l2', sku_code: 'SKU2A', sku_name: '苹果', cost_price: '3.00', sale_price: '5.00' },
{ key: 'l3', sku_code: 'SKU2B', sku_name: '苹果', cost_price: '4.00', sale_price: '6.00' },
];
const skus: QuotePriceImportSku[] = [
{ sku_code: 'SKU1', sku_name: '白菜', spec: '500g' },
{ sku_code: 'SKU2A', sku_name: '苹果', spec: '1斤' },
{ sku_code: 'SKU2B', sku_name: '苹果', spec: '2斤' },
];
describe('报价单价格导入匹配', () => {
it('按商品名更新单一匹配,并保留其它字段(计划只返回价格)', () => {
const plan = planQuotePriceImport({
mode: 'cost',
rows: [{ __row: '2', 商品名: '白菜', 成本价: '1.50' }],
lines,
skus,
});
expect(plan.updates).toEqual([{ lineKey: 'l1', value: '1.5' }]);
expect(plan.matched).toBe(1);
expect(plan.rows[0].status).toBe('matched');
});
it('同名商品用规格区分', () => {
const plan = planQuotePriceImport({
mode: 'sale',
rows: [{ __row: '2', 商品名: '苹果', 规格: '2斤', 销售价: '8.80' }],
lines,
skus,
});
expect(plan.updates).toEqual([{ lineKey: 'l3', value: '8.8' }]);
});
it('报价单没有的商品跳过;同名但规格不匹配失败', () => {
const plan = planQuotePriceImport({
mode: 'cost',
rows: [
{ __row: '2', 商品名: '不存在', 成本价: '2' },
{ __row: '3', 商品名: '苹果', 规格: '3斤', 成本价: '9' },
],
lines,
skus,
});
expect(plan.updates).toEqual([]);
expect(plan.skipped).toBe(1);
expect(plan.failed).toBe(1);
});
it('销售价必须大于 0,成本价允许 0', () => {
const badSale = planQuotePriceImport({
mode: 'sale',
rows: [{ __row: '2', 商品名: '白菜', 销售价: '0' }],
lines,
skus,
});
expect(badSale.failed).toBe(1);
const zeroCost = planQuotePriceImport({
mode: 'cost',
rows: [{ __row: '2', 商品名: '白菜', 成本价: '0' }],
lines,
skus,
});
expect(zeroCost.matched).toBe(1);
});
});
+207
View File
@@ -0,0 +1,207 @@
import {
downloadExcelTemplate,
getCell,
parseExcelFile,
} from './excelImportExport';
/** 金额文本解析:与主系统 parseMoneyText 同义(供应商 excel 工具未导出该函数)。 */
function parseMoneyText(value: string, defaultValue: number): number {
const text = String(value ?? '').trim();
if (!text) return defaultValue;
const cleaned = text
.replace(/[¥¥$€,\s]/g, '')
.replace(/元.*$/, '')
.replace(/\/.*$/, '')
.replace(/[^\d.+-]/g, '');
if (!cleaned) return defaultValue;
const parsed = Number(cleaned);
return Number.isFinite(parsed) ? parsed : defaultValue;
}
export type QuotePriceImportMode = 'cost' | 'sale';
export interface QuotePriceImportLine {
key: string;
sku_code: string;
sku_name: string;
cost_price: string;
sale_price: string;
}
export interface QuotePriceImportSku {
sku_code: string;
sku_name: string;
spec?: string | null;
unit?: string | null;
}
export interface QuotePriceImportPreviewRow {
rowNo: number;
name: string;
spec: string;
newValue: string;
oldValue: string | null;
lineKey: string | null;
lineLabel: string | null;
status: 'matched' | 'skipped' | 'failed';
reason?: string;
}
export interface QuotePriceImportPlan {
rows: QuotePriceImportPreviewRow[];
updates: Array<{ lineKey: string; value: string }>;
matched: number;
skipped: number;
failed: number;
}
export function normalizeQuoteImportText(value: unknown): string {
return String(value || '')
.trim()
.replace(/\s+/g, '')
.replace(/(/g, '(')
.replace(/)/g, ')')
.toLowerCase();
}
function priceHeader(mode: QuotePriceImportMode): string {
return mode === 'cost' ? '成本价' : '销售价';
}
export async function downloadQuotePriceImportTemplate(mode: QuotePriceImportMode): Promise<void> {
const label = mode === 'cost' ? '成本价' : '销售价';
await downloadExcelTemplate(
`报价单-${label}导入模板.xlsx`,
`${label}导入`,
['商品名*', '规格', `${label}*`],
[
['大白菜', '约500g/份', mode === 'cost' ? 2.5 : 3.5],
['五花肉', '冷鲜切块', mode === 'cost' ? 22 : 28],
],
[
{
name: '填写说明',
headers: ['字段', '说明'],
rows: [
['商品名*', '必填;按当前报价单中的商品名匹配,找不到会跳过'],
['规格', '选填;商品名重复时用它区分'],
[`${label}*`, mode === 'cost' ? '必填,允许 0' : '必填,必须大于 0'],
],
},
]
);
}
export async function parseQuotePriceImportFile(
file: File,
mode: QuotePriceImportMode
): Promise<Record<string, string>[]> {
const label = priceHeader(mode);
return parseExcelFile(file, {
preferredSheetNames: [`${label}导入`, '报价导入', '报价单', '商品'],
requiredHeaderHints: ['商品名', label],
});
}
function matchesSpec(uploaded: string, skuSpec?: string | null): boolean {
const a = normalizeQuoteImportText(uploaded);
const b = normalizeQuoteImportText(skuSpec);
if (!a || !b) return false;
return a === b || a.includes(b) || b.includes(a);
}
/** 把导入表匹配到当前报价单草稿;不改其它字段,只产出价格更新计划。 */
export function planQuotePriceImport(input: {
mode: QuotePriceImportMode;
rows: Record<string, string>[];
lines: QuotePriceImportLine[];
skus: QuotePriceImportSku[];
}): QuotePriceImportPlan {
const { mode, rows, lines, skus } = input;
const label = priceHeader(mode);
const skuMap = new Map(skus.map((sku) => [String(sku.sku_code || '').trim(), sku]));
const lineName = (line: QuotePriceImportLine) =>
String(line.sku_name || skuMap.get(String(line.sku_code || '').trim())?.sku_name || '').trim();
const lineSpec = (line: QuotePriceImportLine) =>
skuMap.get(String(line.sku_code || '').trim())?.spec || null;
const preview: QuotePriceImportPreviewRow[] = [];
const updates: Array<{ lineKey: string; value: string }> = [];
const seenLineKeys = new Set<string>();
let matched = 0;
let skipped = 0;
let failed = 0;
rows.forEach((row, index) => {
const rowNo = Number(row.__row) || index + 2;
const name = getCell(row, '商品名', '商品名称', '品名', '商品名*').trim();
const spec = getCell(row, '规格', '规格型号', '规格详情').trim();
const rawValue = getCell(row, label, `${label}*`, label === '成本价' ? '成本单价' : '销售单价');
const newValue = parseMoneyText(rawValue, NaN);
const base = { rowNo, name, spec, newValue: Number.isFinite(newValue) ? String(newValue) : '', oldValue: null };
if (!name) {
skipped += 1;
preview.push({ ...base, lineKey: null, lineLabel: null, status: 'skipped', reason: '缺少商品名' });
return;
}
const nameKey = normalizeQuoteImportText(name);
const candidates = lines.filter((line) => normalizeQuoteImportText(lineName(line)) === nameKey);
if (candidates.length === 0) {
skipped += 1;
preview.push({ ...base, lineKey: null, lineLabel: null, status: 'skipped', reason: '报价单中不存在该商品' });
return;
}
let target = candidates.length === 1 ? candidates[0] : null;
if (!target && spec) {
const bySpec = candidates.filter((line) => matchesSpec(spec, lineSpec(line)));
if (bySpec.length === 1) target = bySpec[0];
}
if (!target) {
failed += 1;
preview.push({
...base,
lineKey: null,
lineLabel: null,
status: 'failed',
reason: candidates.length > 1 ? '商品名重复,请用规格区分(规格未匹配或仍有多条)' : '匹配失败',
});
return;
}
if (!Number.isFinite(newValue) || (mode === 'sale' ? newValue <= 0 : newValue < 0)) {
failed += 1;
preview.push({
...base,
lineKey: target.key,
lineLabel: lineName(target),
status: 'failed',
reason: mode === 'sale' ? '销售价必须大于 0' : '成本价不能小于 0',
});
return;
}
if (seenLineKeys.has(target.key)) {
failed += 1;
preview.push({
...base,
lineKey: target.key,
lineLabel: lineName(target),
oldValue: mode === 'cost' ? target.cost_price : target.sale_price,
status: 'failed',
reason: '同一商品在表格中重复出现',
});
return;
}
seenLineKeys.add(target.key);
matched += 1;
const oldValue = mode === 'cost' ? target.cost_price : target.sale_price;
preview.push({
...base,
lineKey: target.key,
lineLabel: lineName(target),
oldValue: oldValue || null,
status: 'matched',
});
updates.push({ lineKey: target.key, value: String(newValue) });
});
return { rows: preview, updates, matched, skipped, failed };
}