Files
SupplierSystem/src/pages/inventory/StockInboundPanel.tsx
T
Ubuntu 38002e0706
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(库存入库): 保质期单位默认「月」(AI 解析有条目时仍以解析结果为准)
2026-10-20 21:55:11 +08:00

1096 lines
43 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Web 独立库存入库面板(无订单)—— 对齐小程序:
* 多图 AI 识别 → 人工审核(逐行可改/可删/可点候选)→ 批量入库。
* 对接 POST /workflow/inventory/recognize-lines、stock-in-batch、categories。
*/
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Upload } from 'lucide-react';
import { notify } from '../../utils/notify';
import { useOperatingBranch } from '../../hooks/useOperatingBranch';
import { readOperatingBranchCode } from '../../utils/operatingBranch';
import { supabase } from '../../supabase/client';
import { compressOrderRecognitionImage, isGeneralImageFile } from '../../utils/imageFileLimits';
import { useFileDropUpload } from '../../hooks/useFileDropUpload';
import {
createInventoryCatalogProductApi,
createInventoryCategoryApi,
listInventorySkuOptionsApi,
listInventoryStorageZonesApi,
listUnitsApi,
recognizeInventoryLinesApi,
submitInventoryStockInBatchApi,
type InventoryInboundBatchRowInput,
type InventoryInboundCandidate,
type InventoryInboundLineBackfill,
type InventoryInboundRecognizedLine,
type InventoryInboundSkuOption,
} from '../../utils/workflowApi';
import { applyInboundBackfill } from '../../utils/inboundSkuPrefill';
import { buildBatchRowArchive } from '../../utils/inboundArchiveBatch';
import { confirmDialog } from '../../utils/confirmDialog';
import {
composeShelfLifeText,
parseShelfLife,
resolveRecognizedDateFields,
} from '../../utils/shelfLife';
import { useT } from '../../i18n';
import { SearchableSelect } from '../../components/ui/SearchableSelect';
import { Modal } from '../../components/ui/Modal';
type Category = { category_code: string; category_name: string };
type ImageItem = { id: string; dataUrl: string };
type InboundLine = {
id: string;
item_name: string;
spec: string;
qty: string;
unit: string;
unit_cost: string;
sku_code: string;
candidates: InventoryInboundCandidate[];
category_code: string;
category_name: string;
production_date: string;
/** 保质期原文(落库值,如 `30天`/`6个月`/`1年`)——由下面「数值 + 单位」两控件同步合成,提交与预填都读它 */
shelf_life: string;
/** 保质期「数值」控件值 */
shelf_life_value: string;
/** 保质期「单位」控件值:年 / 月 / 日(空 = 未选) */
shelf_life_unit: string;
storage_zone: string;
origin: string;
/** 规格被操作员手工改过(置 true 才随批量入库回写商品档案);程序化预填一律清 false */
archiveSpecEdited?: boolean;
/** 生产地区(档案的「厂家/产地」列)被操作员手工改过,同上 */
archiveOriginEdited?: boolean;
};
/** 「新建商品」弹窗草稿(2026-11-02,见 docs/design/20261102-入库品名下拉修整与新建商品弹窗.md) */
type NewProductDraft = {
lineId: string;
name: string;
categoryCode: string;
spec: string;
unit: string;
origin: string;
};
function lineId() {
return `l_${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
}
/**
* 把「保质期原文」铺进「数值 + 单位」两控件(只在数值还为空时铺,避免覆盖人工输入)。
* 原文来源:档案回填 `applyInboundBackfill`(写 `N天`)、AI 识别 `resolveRecognizedDateFields`、多图合并。
* ⚠️ 落库仍以 `shelf_life` 原文为准(服务端据此推有效期)——两控件只是它的可视化,见 src/utils/shelfLife.ts。
*/
function withShelfLifeFields(line: InboundLine): InboundLine {
if (line.shelf_life_value) return line;
const text = line.shelf_life.trim();
if (!text) return line;
const parsed = parseShelfLife(text);
if (parsed) {
return {
...line,
shelf_life_value: String(parsed.n),
shelf_life_unit: parsed.unit === 'day' ? '日' : parsed.unit === 'month' ? '月' : '年',
};
}
// 只有数字没单位(AI 只给 value 的兜底):填数字,单位留空由人补
return Number(text) > 0 ? { ...line, shelf_life_value: String(Math.trunc(Number(text))) } : line;
}
/** 单位/规格/分类 → 匹配到的商品优先;成本价/存放区域/保质期/生产地区 → AI 优先,空才回填 */
function applyMatchedFields(
line: InboundLine,
candidate: InventoryInboundCandidate | null,
backfill: InventoryInboundLineBackfill | null
): InboundLine {
// 规则只有一份:utils/inboundSkuPrefill(「选择已有商品」走同一份,避免两条路径漂移)
return applyInboundBackfill(line, candidate, backfill);
}
function lineFromRecognized(item: InventoryInboundRecognizedLine): InboundLine {
const matched = item.matched || ({} as InventoryInboundRecognizedLine['matched']);
const candidates = Array.isArray(matched.candidates) ? matched.candidates : [];
const line: InboundLine = {
id: lineId(),
item_name: item.item_name || '',
spec: item.spec || '',
qty: item.qty != null ? String(item.qty) : '',
unit: item.unit || '',
unit_cost: item.unit_cost != null ? String(item.unit_cost) : '',
sku_code: matched.sku_code || '',
candidates,
category_code: item.category_code || '',
category_name: item.category_name || '',
// 日期两列走**与服务端同口径**的归一:AI 现在给 `production_date`(YYYY-MM-DD/中文/纯数字)
// 与 `shelf_life_value`(数字)+`shelf_life_unit`(年/月/日);旧字段 `shelf_life` 整串仍兼容。
// 见 src/utils/shelfLife.ts(与 server/src/utils/shelfLife.ts 逐值对拍)
...resolveRecognizedDateFields(item),
shelf_life_value: '',
shelf_life_unit: '月',
storage_zone: '',
origin: item.origin || '',
};
const candidate = line.sku_code
? candidates.find((c) => c.sku_code === line.sku_code) || null
: null;
const backfill = matched.backfill || (candidate && candidate.backfill) || null;
return withShelfLifeFields(applyMatchedFields(line, candidate, backfill));
}
function normProductName(value: string): string {
return String(value || '').replace(/\s+/g, '').toLowerCase();
}
/**
* 判断两行是否指同一商品(多图拍到的同一实物):
* ① 命中同一 SKU;② 归一化品名完全相同;③ 一方品名包含另一方(如「矿泉水」⊂「农夫山泉矿泉水」)。
*/
function isSameProduct(a: InboundLine, b: InboundLine): boolean {
if (a.sku_code && b.sku_code && a.sku_code === b.sku_code) return true;
const na = normProductName(a.item_name);
const nb = normProductName(b.item_name);
if (!na || !nb) return false;
if (na === nb) return true;
const shorter = na.length <= nb.length ? na : nb;
const longer = na.length <= nb.length ? nb : na;
return shorter.length >= 2 && longer.includes(shorter);
}
/** 同一商品多图合并:数量取最大值(多张图是补全信息,不叠加),其余字段以第一个为准、空的才补 */
function mergeInboundLine(target: InboundLine, source: InboundLine): void {
const tq = target.qty === '' ? null : Number(target.qty);
const sq = source.qty === '' ? null : Number(source.qty);
if (tq != null && sq != null) target.qty = String(Math.max(tq, sq));
else if (tq == null && sq != null) target.qty = source.qty;
if (!target.unit && source.unit) target.unit = source.unit;
if (!target.unit_cost && source.unit_cost) target.unit_cost = source.unit_cost;
if (!target.production_date && source.production_date) target.production_date = source.production_date;
if (!target.shelf_life && source.shelf_life) target.shelf_life = source.shelf_life;
if (!target.storage_zone && source.storage_zone) target.storage_zone = source.storage_zone;
if (!target.origin && source.origin) target.origin = source.origin;
if (!target.category_code && source.category_code) {
target.category_code = source.category_code;
target.category_name = source.category_name;
}
if (!target.sku_code && source.sku_code) target.sku_code = source.sku_code;
if (!target.candidates.length && source.candidates.length) {
target.candidates = source.candidates;
}
}
export const StockInboundPanel: React.FC = () => {
const t = useT();
const { operatingBranchCode } = useOperatingBranch();
const branch = operatingBranchCode || readOperatingBranchCode();
const [images, setImages] = useState<ImageItem[]>([]);
const [recognizing, setRecognizing] = useState(false);
const [lines, setLines] = useState<InboundLine[]>([]);
const [submitting, setSubmitting] = useState(false);
const [categories, setCategories] = useState<Category[]>([]);
const [unitChoices, setUnitChoices] = useState<string[]>([]);
/** 「选择已有商品」的检索结果(远程搜索,见 fetchSkuOptions) */
const [skuOptions, setSkuOptions] = useState<InventoryInboundSkuOption[]>([]);
/** 「存放区域」候选(区域是自由文本:首次入库用了新值,下次就会出现在这里) */
const [zoneChoices, setZoneChoices] = useState<string[]>([]);
/** 「新建商品」弹窗草稿(null = 关闭) */
const [newProductDraft, setNewProductDraft] = useState<NewProductDraft | null>(null);
const [creatingProduct, setCreatingProduct] = useState(false);
const recognizeInputRef = useRef<HTMLInputElement>(null);
const recognizeDropRef = useRef<HTMLDivElement>(null);
useEffect(() => {
let cancelled = false;
void (async () => {
const { data, error } = await supabase
.from('categories')
.select('category_code, category_name')
.eq('status', 1)
.order('category_code')
.limit(500);
if (cancelled || error) return;
setCategories((data || []) as Category[]);
})();
return () => {
cancelled = true;
};
}, [branch]);
useEffect(() => {
let cancelled = false;
void listUnitsApi({ activeOnly: true })
.then((res) => {
if (cancelled) return;
const labels = (res.data || [])
.map((row) => String(row.unit_name || row.unit_code || '').trim())
.filter(Boolean);
setUnitChoices([...new Set(labels)]);
})
.catch(() => {
if (!cancelled) setUnitChoices([]);
});
return () => {
cancelled = true;
};
}, []);
// 存放区域候选(只读、失败即空:不阻塞入库)
useEffect(() => {
let cancelled = false;
void listInventoryStorageZonesApi()
.then((res) => {
if (!cancelled) setZoneChoices((res.data || []).filter(Boolean));
})
.catch(() => {
if (!cancelled) setZoneChoices([]);
});
return () => {
cancelled = true;
};
}, []);
const zoneOptions = useMemo(
() => zoneChoices.map((z) => ({ value: z, label: z })),
[zoneChoices]
);
const categoryOptions = useMemo(
() =>
categories.map((c) => ({
value: c.category_code,
label: c.category_name || c.category_code,
})),
[categories]
);
/** 「选择已有商品」:按关键词远程检索商品档案(带上次设置回填) */
const fetchSkuOptions = useCallback(
async (search = '') => {
try {
const res = await listInventorySkuOptionsApi(search, 20);
setSkuOptions(res.data || []);
} catch (e: any) {
notify.error(e?.message || t('inventory.stockIn.similarFail'));
}
},
[t]
);
// 输入防抖(前端纪律:搜索须防抖或确认才请求)
const skuSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const onSkuQueryChange = useCallback(
(query: string) => {
if (skuSearchTimer.current) clearTimeout(skuSearchTimer.current);
skuSearchTimer.current = setTimeout(() => void fetchSkuOptions(query), 300);
},
[fetchSkuOptions]
);
useEffect(
() => () => {
if (skuSearchTimer.current) clearTimeout(skuSearchTimer.current);
},
[]
);
const addFiles = useCallback(
async (files: File[]) => {
const added: ImageItem[] = [];
for (const file of files) {
if (!isGeneralImageFile(file)) continue;
try {
const dataUrl = await compressOrderRecognitionImage(file);
added.push({ id: `img_${Date.now()}_${Math.random()}`, dataUrl });
} catch {
/* skip unreadable */
}
}
if (!added.length) {
notify.error(t('inventory.stockIn.errReadImage'));
return;
}
setImages((prev) => [...prev, ...added]);
},
[t]
);
const { isDropZoneActive: isRecognizeDropActive } = useFileDropUpload(recognizeDropRef, {
enabled: true,
acceptFile: isGeneralImageFile,
rejectMessage: t('inventory.stockIn.dropJpg'),
onReject: (message) => notify.error(message),
onFiles: (files) => void addFiles(files),
});
const removeImage = (id: string) => setImages((prev) => prev.filter((img) => img.id !== id));
const clearImages = () => setImages([]);
const recognizeAll = async () => {
if (!images.length) {
notify.error(t('inventory.stockIn.errPickImage'));
return;
}
setRecognizing(true);
// 多张图片一次性提交(服务端一次多图调用,由 AI 合并同一商品)
const imagesBase64 = images.map((img) =>
img.dataUrl.includes(',') ? img.dataUrl.split(',')[1] : img.dataUrl
);
let collected: InventoryInboundRecognizedLine[] = [];
try {
const data = await recognizeInventoryLinesApi({
images_base64: imagesBase64,
operatingBranchCode: branch,
});
if (data.no_llm) {
setRecognizing(false);
notify.error(t('inventory.stockIn.errNoLlm'));
return;
}
collected = data.items || [];
} catch (e: any) {
setRecognizing(false);
notify.error(e?.message || t('inventory.stockIn.errRecognize'));
return;
}
setRecognizing(false);
if (!collected.length) {
notify.error(t('inventory.stockIn.errNoItems'));
return;
}
setLines((prev) => {
// 同一商品多图合并:数量取最大值,其余字段以第一个为准
const next = prev.map((l) => ({ ...l }));
for (const item of collected) {
const incoming = lineFromRecognized(item);
const idx = next.findIndex((l) => isSameProduct(l, incoming));
if (idx >= 0) {
mergeInboundLine(next[idx], incoming);
next[idx] = withShelfLifeFields(next[idx]);
} else {
next.push(incoming);
}
}
return next;
});
notify.success(t('inventory.stockIn.filled'));
};
const updateLine = (id: string, patch: Partial<InboundLine>) => {
setLines((prev) => prev.map((l) => (l.id === id ? { ...l, ...patch } : l)));
};
/** 保质期「数值」改动:把「数值 + 单位」组回原文写进 `shelf_life`(提交/预填仍读原文) */
const setLineShelfLifeValue = (line: InboundLine, value: string) => {
updateLine(line.id, {
shelf_life_value: value,
shelf_life: composeShelfLifeText(value, line.shelf_life_unit) || value,
});
};
/** 保质期「单位」改动:同上 */
const setLineShelfLifeUnit = (line: InboundLine, unit: string) => {
updateLine(line.id, {
shelf_life_unit: unit,
shelf_life: composeShelfLifeText(line.shelf_life_value, unit) || line.shelf_life_value,
});
};
const removeLine = (id: string) => setLines((prev) => prev.filter((l) => l.id !== id));
const addEmptyLine = () =>
setLines((prev) => [
...prev,
{
id: lineId(),
item_name: '',
spec: '',
qty: '',
unit: '',
unit_cost: '',
sku_code: '',
candidates: [],
category_code: '',
category_name: '',
production_date: '',
shelf_life: '',
shelf_life_value: '',
shelf_life_unit: '月',
storage_zone: '',
origin: '',
},
]);
const pickCandidate = (line: InboundLine, sku: string) => {
const candidate = line.candidates.find((c) => c.sku_code === sku) || null;
const next: InboundLine = { ...line, sku_code: sku };
if (candidate) {
if (candidate.sku_name) next.item_name = candidate.sku_name;
}
applyMatchedFields(next, candidate, (candidate && candidate.backfill) || null);
// 预填值出自档案/候选,不算人工改过 ⇒ 清掉脏标记,避免把预填值回写成「人工值」
next.archiveSpecEdited = false;
next.archiveOriginEdited = false;
updateLine(line.id, withShelfLifeFields(next));
};
/**
* 行内「品名」格选中已有商品:规格/单位取商品档案;成本价/分类/保质期/存放区域/生产地区按
* **只补空**规则取该商品**上次设置**(操作员已填的不被覆盖);**数量与生产日期不动**
* (数量每次不同、生产日期每批不同,由操作员按本批填)。
*/
const pickSkuForLine = (line: InboundLine, skuCode: string) => {
const option = skuOptions.find((o) => o.sku_code === skuCode);
if (!option) return;
const next: InboundLine = { ...line, sku_code: option.sku_code, item_name: option.sku_name };
applyInboundBackfill(
next,
{ spec: option.spec, unit: option.unit || option.backfill?.unit || '' },
option.backfill ?? null
);
// 预填值出自商品档案,不算人工改过 ⇒ 清掉脏标记
next.archiveSpecEdited = false;
next.archiveOriginEdited = false;
updateLine(line.id, withShelfLifeFields(next));
};
/** 品名格输入自由文本 ⇒ 该行按「待新建商品」处理(与手动加一行/拍照未命中同一口径) */
const onLineNameQuery = (line: InboundLine, query: string) => {
onSkuQueryChange(query);
const name = query.trim();
if (!name) return;
updateLine(line.id, { item_name: query });
};
/** 行内「新建分类」:建好后自动选中该行 */
const createCategoryForLine = async (targetLineId: string, name: string) => {
const trimmed = name.trim();
if (!trimmed) return;
try {
const created = await createInventoryCategoryApi({ name: trimmed, operatingBranchCode: branch });
const row: Category = {
category_code: String(created.category_code || ''),
category_name: String(created.category_name || created.label || trimmed),
};
if (!row.category_code) {
notify.error(t('inventory.stockIn.createCategoryFail'));
return;
}
setCategories((prev) => [...prev, row]);
updateLine(targetLineId, {
category_code: row.category_code,
category_name: row.category_name,
});
notify.success(t('inventory.stockIn.categoryCreated'));
} catch (e: any) {
notify.error(e?.message || t('inventory.stockIn.createCategoryFail'));
}
};
// ── B:新建商品弹窗(2026-11-02)───────────────────────────
const openNewProductDialog = (line: InboundLine, name: string) => {
setNewProductDraft({
lineId: line.id,
name: (name || line.item_name || '').trim(),
categoryCode: line.category_code || '',
spec: line.spec || '',
unit: line.unit || '',
origin: line.origin || '',
});
};
const confirmNewProduct = async () => {
const draft = newProductDraft;
if (!draft || creatingProduct) return;
const name = draft.name.trim();
if (!name) {
notify.error(t('inventory.stockIn.newProductNeedName'));
return;
}
if (!draft.categoryCode.trim()) {
notify.error(t('inventory.stockIn.newProductNeedCategory'));
return;
}
setCreatingProduct(true);
try {
const created = await createInventoryCatalogProductApi({
name,
parent_code: draft.categoryCode.trim(),
spec: draft.spec.trim() || undefined,
unit: draft.unit.trim() || undefined,
origin: draft.origin.trim() || undefined,
operatingBranchCode: branch,
});
const code = String(created?.skuCode || created?.sku_code || '');
if (!code) {
notify.error(t('inventory.stockIn.newProductFail'));
return;
}
const cat = categories.find((c) => c.category_code === draft.categoryCode);
updateLine(draft.lineId, {
sku_code: code,
item_name: String(created?.name || name),
spec: draft.spec.trim(),
unit: draft.unit.trim(),
origin: draft.origin.trim(),
category_code: draft.categoryCode,
category_name: cat?.category_name || draft.categoryCode,
candidates: [],
// 建档已写入档案(新建商品走 createCatalogSkuForInbound)⇒ 不当作人工改过的档案字段
archiveSpecEdited: false,
archiveOriginEdited: false,
});
setNewProductDraft(null);
notify.success(t('inventory.stockIn.newProductOk'));
void fetchSkuOptions('');
} catch (e: any) {
notify.error(e?.message || t('inventory.stockIn.newProductFail'));
} finally {
setCreatingProduct(false);
}
};
const submitBatch = async () => {
if (submitting) return;
if (!lines.length) {
notify.error(t('inventory.stockIn.errNeedRows'));
return;
}
const rows: InventoryInboundBatchRowInput[] = [];
for (const line of lines) {
const qty = Number(line.qty);
if (!(qty > 0)) {
notify.error(
t('inventory.stockIn.errQty', { name: line.item_name || t('inventory.stockIn.phName') })
);
return;
}
if (!line.sku_code) {
if (!line.item_name.trim()) {
notify.error(t('inventory.stockIn.errName'));
return;
}
if (!line.category_code) {
notify.error(t('inventory.stockIn.errNeedCategory', { name: line.item_name }));
return;
}
}
rows.push({
sku_code: line.sku_code || undefined,
new_product: line.sku_code
? undefined
: {
name: line.item_name.trim(),
category_code: line.category_code,
spec: line.spec.trim() || undefined,
unit: line.unit.trim() || undefined,
origin: line.origin.trim() || undefined,
},
qty,
unit_cost: line.unit_cost === '' ? null : Number(line.unit_cost),
/**
* 批次规格(方案丙 2026-10-16):落 `inventory.spec` —— 抵扣"按客户要求的规格选批次"的唯一依据。
* 取本行当前显示的规格(识别值或人工改过的值);空 ⇒ 不传(服务端写 NULL,不回填、不猜)。
*/
spec: line.spec.trim() || undefined,
production_date: line.production_date || undefined,
shelf_life: line.shelf_life.trim() || undefined,
storage_zone: line.storage_zone.trim() || undefined,
// 已匹配商品且操作员改过规格/生产地区 ⇒ 回写商品档案(只发人工改过的字段;新建商品走 new_product,不由这里回写)
archive: line.sku_code
? buildBatchRowArchive(
{ spec: line.spec, origin: line.origin },
{
specEdited: line.archiveSpecEdited === true,
originEdited: line.archiveOriginEdited === true,
}
) || undefined
: undefined,
});
}
setSubmitting(true);
try {
/**
* 规格一致性闸门(2026-10-16):服务端发现「本次人工填的规格 ≠ 该商品档案规格」时返回
* 409 `spec_conflict`。这里弹确认 —— 确认后带 `confirmSpecConflict` 重提交(放行)。
* 正常路径不会走到这里(零影响)。
*/
let data: Awaited<ReturnType<typeof submitInventoryStockInBatchApi>>;
try {
data = await submitInventoryStockInBatchApi({ rows, operatingBranchCode: branch });
} catch (conflictError: any) {
const message = String(conflictError?.message || '');
if (!/规格/.test(message) || !/不一致/.test(message)) throw conflictError;
const ok = await confirmDialog({
title: t('inventory.stockIn.specConflictTitle'),
message,
confirmText: t('inventory.stockIn.specConflictOk'),
cancelText: t('common.cancel'),
});
if (!ok) {
setSubmitting(false);
return;
}
data = await submitInventoryStockInBatchApi({
rows,
operatingBranchCode: branch,
confirmSpecConflict: true,
});
}
const ok = Number(data?.ok_count || 0);
const failed = Number(data?.failed_count || 0);
if (!failed) {
notify.success(t('inventory.stockIn.okInbound', { n: ok }));
setLines([]);
setImages([]);
} else {
const failedRows = (data?.results || []).filter((r) => r.mode === 'failed');
const first = failedRows[0]?.error || '';
notify.error(
`${t('inventory.stockIn.partialTitle')}:${t('inventory.stockIn.partialBody', {
ok,
failed,
first,
})}`
);
const failedNumbers = new Set(failedRows.map((r) => Number(r.rowNumber)));
setLines((prev) => prev.filter((_, i) => failedNumbers.has(i + 1)));
}
} catch (e: any) {
notify.error(e?.message || t('inventory.stockIn.batchFail'));
} finally {
setSubmitting(false);
}
};
const cellCls = 'app-input min-w-0 px-2 py-1.5 border rounded-md text-sm';
return (
<div className="space-y-4">
<p className="text-sm text-gray-600">{t('inventory.stockIn.intro')}</p>
{/* 图片识别 */}
<div className="app-surface app-border rounded-lg border p-4 space-y-3">
<h3 className="font-semibold">{t('inventory.stockIn.recognizeSection')}</h3>
<p className="text-xs text-gray-500">{t('inventory.stockIn.imageHint')}</p>
<input
ref={recognizeInputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
multiple
className="hidden"
onChange={(e) => {
const files = Array.from(e.target.files || []);
e.target.value = '';
if (files.length) void addFiles(files);
}}
/>
<div
ref={recognizeDropRef}
className={`rounded-lg border-2 border-dashed p-3 ${
isRecognizeDropActive
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-950/30'
: 'border-gray-300 dark:border-gray-600'
}`}
>
{images.length > 0 && (
<div className="flex flex-wrap gap-2 mb-2">
{images.map((img) => (
<div key={img.id} className="relative">
<img
src={img.dataUrl}
alt={t('inventory.stockIn.previewAlt')}
className="h-16 w-16 rounded object-cover border"
/>
<button
type="button"
className="absolute -top-2 -right-2 h-5 w-5 leading-5 rounded-full bg-slate-800/70 text-white text-xs"
onClick={() => removeImage(img.id)}
aria-label={t('common.delete')}
>
✕
</button>
</div>
))}
</div>
)}
<button
type="button"
className="w-full text-center py-2"
onClick={() => recognizeInputRef.current?.click()}
disabled={recognizing}
>
<Upload className="w-5 h-5 mx-auto text-gray-400 mb-1" />
<p className="text-sm text-gray-600">
{recognizing ? t('inventory.stockIn.recognizing') : t('inventory.stockIn.uploadHint')}
</p>
<p className="text-xs text-gray-400 mt-1">{t('inventory.stockIn.uploadSub')}</p>
</button>
</div>
<button
type="button"
disabled={recognizing || !images.length}
onClick={() => void recognizeAll()}
className="w-full py-2 rounded-md bg-emerald-600 text-white text-sm font-medium disabled:opacity-50"
>
{recognizing ? t('inventory.stockIn.recognizing') : t('inventory.stockIn.startRecognize')}
</button>
{images.length > 0 && (
<button
type="button"
className="text-sm text-emerald-700 hover:underline"
onClick={clearImages}
>
{t('inventory.stockIn.clearAllImages')}
</button>
)}
</div>
{/* 识别结果 · 待审核 */}
<div className="app-surface app-border rounded-lg border p-4 space-y-3">
<h3 className="font-semibold">
{t('inventory.stockIn.reviewSection', { n: lines.length })}
</h3>
{!lines.length && <p className="text-xs text-gray-500">{t('inventory.stockIn.reviewEmpty')}</p>}
{lines.map((line, index) => (
<div
key={line.id}
className="app-border rounded-lg border bg-slate-50/60 dark:bg-slate-900/30 p-2.5 space-y-2"
>
<div className="flex items-center gap-2">
<span className="h-6 w-6 leading-6 text-center rounded-full bg-emerald-50 text-emerald-700 text-xs">
{index + 1}
</span>
<span
className={`text-xs px-2 py-0.5 rounded-full ${
line.sku_code
? 'bg-emerald-50 text-emerald-700'
: 'bg-amber-100 text-amber-700'
}`}
>
{line.sku_code
? `${t('inventory.stockIn.badgeMatched')} ${line.sku_code}`
: t('inventory.stockIn.badgeNew')}
</span>
<button
type="button"
className="ml-auto text-sm text-red-600"
onClick={() => removeLine(line.id)}
aria-label={t('common.delete')}
>
✕
</button>
</div>
<div className="grid grid-cols-5 gap-2">
{/* 品名格 = 商品选择:输入即搜已有商品(选中则带出上次设置);直接输入文字 = 待新建商品 */}
<SearchableSelect
className="min-w-0"
inputClassName="px-2 py-1.5"
value={line.sku_code}
fallbackLabel={line.item_name}
options={skuOptions.map((o) => ({
value: o.sku_code,
// 品名选择器**不再把规格拼到名字后面**(开发者 2026-10-16:规格有自己的字段会自动带出)
label: o.sku_name,
searchText: o.sku_code,
}))}
onChange={(code) => {
if (code) pickSkuForLine(line, code);
}}
onQueryChange={(q) => onLineNameQuery(line, q)}
onOpenChange={(open) => {
if (open) void fetchSkuOptions('');
}}
placeholder={t('inventory.stockIn.phName')}
disabled={Boolean(newProductDraft)}
allowCreateFromQuery
createFromQueryLabel={(q) => t('inventory.stockIn.newProductNamed', { name: q })}
onCreateFromQuery={(q) => openNewProductDialog(line, q)}
hideSearchIcon
compact
portal
portalZIndex={10200}
/>
<input
className={cellCls}
placeholder={t('inventory.stockIn.phSpec')}
value={line.spec}
onChange={(e) =>
updateLine(line.id, { spec: e.target.value, archiveSpecEdited: true })
}
/>
<input
className={cellCls}
type="number"
min={0}
step="0.001"
placeholder={t('inventory.stockIn.phQty')}
value={line.qty}
onChange={(e) => updateLine(line.id, { qty: e.target.value })}
/>
<input
className={cellCls}
list="stock-inbound-units"
placeholder={t('inventory.stockIn.phUnit')}
value={line.unit}
onChange={(e) => updateLine(line.id, { unit: e.target.value })}
/>
{/**
* 成本价用**文本输入**(2026-10-20 开发者要求):
* 原来的 `type="number"` 带上下箭头,滚轮在输入框上会**直接改价**(误操作风险高)。
* 改成 text + inputMode=decimal(移动端仍弹数字键盘),并过滤非法字符。
*/}
<input
className={cellCls}
type="text"
inputMode="decimal"
placeholder={t('inventory.stockIn.phCost')}
value={line.unit_cost}
onChange={(e) => {
const raw = e.target.value.replace(/[^0-9.]/g, '');
const normalized = raw.includes('.')
? `${raw.slice(0, raw.indexOf('.') + 1)}${raw.split('.').slice(1).join('')}`
: raw;
updateLine(line.id, { unit_cost: normalized });
}}
onWheel={(e) => (e.currentTarget as HTMLInputElement).blur()}
/>
</div>
<div className="grid grid-cols-5 gap-2">
{/* 分类格:与「品名 / 存放区域」同口径 —— 不再用 placeholder 文案当空选项 / 常驻新建行
(`emptyLabel=分类` 会让下拉里能选到一行「分类」;空查询的常驻新建行也无意义)。 */}
<SearchableSelect
className="min-w-0"
inputClassName="px-2 py-1.5"
value={line.category_code}
onChange={(code) => {
const found = categories.find((c) => c.category_code === code);
updateLine(line.id, {
category_code: code,
category_name: found?.category_name || '',
});
}}
options={categoryOptions}
placeholder={t('inventory.stockIn.phCategory')}
fallbackLabel={line.category_name}
allowCreateFromQuery
createFromQueryLabel={(q) => t('inventory.stockIn.newCategoryNamed', { name: q })}
onCreateFromQuery={(q) => void createCategoryForLine(line.id, q)}
hideSearchIcon
compact
portalZIndex={10200}
/>
<input
className={cellCls}
type="date"
title={t('inventory.stockIn.phProdDate')}
aria-label={t('inventory.stockIn.phProdDate')}
value={line.production_date}
onChange={(e) => updateLine(line.id, { production_date: e.target.value })}
/>
{/* 保质期 = 数值 + 年/月/日(与小程序订单入库、Web 验收弹窗同形态);提交/预填仍以 `shelf_life` 原文为准 */}
<div className="flex min-w-0 items-center gap-1.5">
<input
className={`${cellCls} flex-1`}
type="number"
min={1}
title={t('inventory.stockIn.phShelf')}
aria-label={t('inventory.stockIn.phShelf')}
placeholder={t('inventory.stockIn.phShelf')}
value={line.shelf_life_value}
onChange={(e) => setLineShelfLifeValue(line, e.target.value)}
/>
<select
className={`${cellCls} shrink-0`}
title={t('inventory.stockIn.phShelf')}
aria-label={t('inventory.stockIn.phShelf')}
value={line.shelf_life_unit}
onChange={(e) => setLineShelfLifeUnit(line, e.target.value)}
>
<option value="">{t('inspection.qc.shelfUnit')}</option>
<option value="年">{t('inspection.qc.shelfYear')}</option>
<option value="月">{t('inspection.qc.shelfMonth')}</option>
<option value="日">{t('inspection.qc.shelfDay')}</option>
</select>
</div>
{/* 存放区域 = 区域选择(候选为既有区域;输入没有的即新增,落库后自动进候选)。
与「品名」格同口径:不再用 placeholder 文案当空选项 / 常驻新建行(会出现两行「存放区域」)。 */}
<SearchableSelect
className="min-w-0"
inputClassName="px-2 py-1.5"
value={line.storage_zone}
fallbackLabel={line.storage_zone}
options={zoneOptions}
onChange={(zone) => updateLine(line.id, { storage_zone: zone })}
placeholder={t('inventory.stockIn.phZone')}
allowCreateFromQuery
createFromQueryLabel={(q) => t('inventory.stockIn.createNamed', { name: q })}
onCreateFromQuery={(q) => updateLine(line.id, { storage_zone: q })}
hideSearchIcon
compact
portal
portalZIndex={10200}
/>
<input
className={cellCls}
placeholder={t('inventory.stockIn.phOrigin')}
value={line.origin}
onChange={(e) =>
updateLine(line.id, { origin: e.target.value, archiveOriginEdited: true })
}
/>
</div>
{!line.sku_code && line.candidates.length > 0 && (
<div className="flex flex-wrap gap-2">
{line.candidates.map((c) => (
<button
key={c.sku_code}
type="button"
className="text-xs px-2.5 py-1 rounded-full bg-white border border-emerald-200 text-emerald-700 hover:bg-emerald-50"
onClick={() => pickCandidate(line, c.sku_code)}
>
{c.sku_name}
{c.spec ? ` · ${c.spec}` : ''}
</button>
))}
</div>
)}
</div>
))}
<button
type="button"
className="text-sm text-emerald-700 hover:underline"
onClick={addEmptyLine}
>
{t('inventory.stockIn.addLine')}
</button>
</div>
{/* 确认入库 */}
<div className="app-surface app-border rounded-lg border p-4">
<button
type="button"
disabled={submitting}
onClick={() => void submitBatch()}
className="w-full py-2.5 rounded-md bg-emerald-600 text-white text-sm font-medium disabled:opacity-50"
>
{submitting ? t('inventory.stockIn.submitting') : t('inventory.stockIn.confirm')}
</button>
</div>
<datalist id="stock-inbound-units">
{unitChoices.map((u) => (
<option key={u} value={u} />
))}
</datalist>
<datalist id="stock-inbound-categories">
{categoryOptions.map((item) => (
<option key={item.value} value={item.label} />
))}
</datalist>
{/* B:新建商品弹窗(2026-11-02) */}
<Modal
open={Boolean(newProductDraft)}
title={t('inventory.stockIn.newProductTitle')}
onClose={() => {
if (!creatingProduct) setNewProductDraft(null);
}}
className="max-w-lg"
footer={
<div className="flex justify-end gap-2">
<button
type="button"
disabled={creatingProduct}
onClick={() => setNewProductDraft(null)}
className="app-surface app-border rounded-md border px-4 py-2 text-sm disabled:opacity-50"
>
{t('common.cancel')}
</button>
<button
type="button"
disabled={creatingProduct}
onClick={() => void confirmNewProduct()}
className="app-focus-ring rounded-md bg-emerald-600 px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
>
{creatingProduct ? t('common.saving') : t('common.ok')}
</button>
</div>
}
>
<div className="space-y-3">
<label className="block text-sm">
<span className="app-foreground-muted mb-1 block">{t('inventory.stockIn.skuName')}</span>
<input
className={`${cellCls} w-full`}
value={newProductDraft?.name || ''}
onChange={(e) => setNewProductDraft((d) => (d ? { ...d, name: e.target.value } : d))}
/>
</label>
<div className="grid grid-cols-3 gap-2">
<label className="block text-sm">
<span className="app-foreground-muted mb-1 block">{t('inventory.stockIn.phSpec')}</span>
<input
className={`${cellCls} w-full`}
value={newProductDraft?.spec || ''}
onChange={(e) => setNewProductDraft((d) => (d ? { ...d, spec: e.target.value } : d))}
/>
</label>
<label className="block text-sm">
<span className="app-foreground-muted mb-1 block">{t('inventory.stockIn.phUnit')}</span>
<input
className={`${cellCls} w-full`}
list="stock-inbound-units"
value={newProductDraft?.unit || ''}
onChange={(e) => setNewProductDraft((d) => (d ? { ...d, unit: e.target.value } : d))}
/>
</label>
<label className="block text-sm">
<span className="app-foreground-muted mb-1 block">{t('inventory.stockIn.phOrigin')}</span>
<input
className={`${cellCls} w-full`}
value={newProductDraft?.origin || ''}
onChange={(e) => setNewProductDraft((d) => (d ? { ...d, origin: e.target.value } : d))}
/>
</label>
</div>
{/* 「分类」移到规格这一行**下方**,并改用与左邻右舍同款的**原生输入框 + datalist**
(2026-10-16 真机缺陷):原先只有它用共享 `SearchableSelect`,那个组件的下拉是 portal 到
body 的浮层,会**盖住**下面的规格/单位/生产地区,且它的输入框 `value` 绑的是内部
`inputDisplay`(`open ? query : 选中项 label`)⇒ 真机上**打不进字**、点单位却操作到分类。
原生控件没有浮层、输入天然可用,与旁边的规格/单位/生产地区保持同一套交互。 */}
<label className="block text-sm">
<span className="app-foreground-muted mb-1 block">{t('inventory.stockIn.phCategory')}</span>
<input
className={`${cellCls} w-full`}
list="stock-inbound-categories"
value={
categoryOptions.find((item) => item.value === newProductDraft?.categoryCode)?.label || ''
}
onChange={(e) => {
const next = e.target.value;
const hit = categoryOptions.find((item) => item.label === next);
setNewProductDraft((d) => (d ? { ...d, categoryCode: hit ? hit.value : '' } : d));
}}
placeholder={t('inventory.stockIn.phCategory')}
/>
</label>
</div>
</Modal>
</div>
);
};