① Web 验收拍照/拖入后自动 AI 识别(复用库存入库识别,预填 规格/生产日期/保质期/产地,只补空、切单丢弃过期响应,零新增文案)。 ② 修「拍照后上传失败」:根因是照片 dataURL 内联在提交体,而全局 express.json 仅 2mb 且照片不降尺寸/质量 0.92 ⇒ 大图必 413。 甲:照片先降尺寸再画水印(≤1600px / q0.8,对齐小程序); 丙:仅把 /api/workflow/inspection/submit 体上限放宽到 20mb。 ③ 小程序逐张上传单张失败不中断整批 + 汇总提示。 新增契约测试;门禁与全量回归对基线。
1353 lines
49 KiB
JavaScript
1353 lines
49 KiB
JavaScript
const {
|
||
fetchInspectionTasks,
|
||
completeInspection,
|
||
uploadInspectionPhoto,
|
||
deleteInspectionPhoto,
|
||
analyzeInspectionQuality,
|
||
fetchStockInboundStorageZones,
|
||
uploadQualityReportStorageFile,
|
||
createInspectionBatchReports,
|
||
recognizeStockInboundLines,
|
||
} = require('../../utils/request');
|
||
const { buildArchivePayload } = require('../../utils/stockInboundArchive');
|
||
const {
|
||
SHELF_LIFE_UNITS,
|
||
applyShelfLifeFromAi,
|
||
shelfLifeTextFromLine,
|
||
} = require('../../utils/shelfLife');
|
||
const { getSession } = require('../../utils/auth');
|
||
const { ensureMobileRole } = require('../../utils/roleGuard');
|
||
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
|
||
// 复用订单识图图片压缩管线:上传前压缩,避免冷库弱网原图 base64 上传超时
|
||
const { prepareOrderImageBase64, readFileAsBase64 } = require('../../utils/orderImage');
|
||
const { fmtLocalDate } = require('../../utils/purchaseToday');
|
||
const { resolveLevel1CategoryInfo } = require('../../utils/orderCategory');
|
||
|
||
const WAREHOUSE_ROLES = ['warehouse', 'inspector'];
|
||
|
||
function displayText(value, fallback = '') {
|
||
if (value === undefined || value === null) return fallback;
|
||
const text = String(value).trim();
|
||
if (!text || text.toLowerCase() === 'null') return fallback;
|
||
return text;
|
||
}
|
||
|
||
function resolveInspectionItemName(row) {
|
||
return displayText(row.item_name, '未知商品');
|
||
}
|
||
|
||
function resolvePartyInfo(row) {
|
||
const sourceType = row.source_type || 'supplier';
|
||
if (sourceType === 'purchase') {
|
||
return {
|
||
partyLabel: '采购员',
|
||
partyName: displayText(row.purchaser_name, '-'),
|
||
};
|
||
}
|
||
return {
|
||
partyLabel: '供应商',
|
||
partyName: displayText(row.supplier_name, '-'),
|
||
};
|
||
}
|
||
|
||
const DATE_FIELD_OPTIONS = [
|
||
{ label: '下单日', value: 'created_at' },
|
||
{ label: '配送日', value: 'delivery_date' },
|
||
];
|
||
const SOURCE_OPTIONS = ['全部入库', '供应商入库', '自采入库'];
|
||
const SOURCE_VALUES = ['', 'supplier', 'purchase'];
|
||
|
||
const SOURCE_TEXT = {
|
||
purchase: '自采',
|
||
supplier: '供应商',
|
||
};
|
||
|
||
const RESULT_OPTIONS = ['合格', '不合格'];
|
||
const RESULT_PASS = '合格';
|
||
const RESULT_FAIL = '不合格';
|
||
|
||
/** 存放区域选择器末尾的「新增区域」项(区域无独立表,输入即新增) */
|
||
const ZONE_CREATE_LABEL = '+ 新增区域';
|
||
|
||
function zoneIndexOf(zone, options, createIndex) {
|
||
const z = String(zone || '').trim();
|
||
const list = options || [];
|
||
if (!z) return 0;
|
||
const i = list.indexOf(z);
|
||
return i >= 0 ? i : createIndex;
|
||
}
|
||
|
||
function currentMonthValue() {
|
||
const now = new Date();
|
||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||
return `${now.getFullYear()}-${month}`;
|
||
}
|
||
|
||
function defaultRatingFromGrade(grade) {
|
||
return String(grade || '').trim().toUpperCase() === 'D' ? RESULT_FAIL : RESULT_PASS;
|
||
}
|
||
|
||
function emptyAiFields() {
|
||
return {
|
||
aiDone: false,
|
||
aiGrade: '',
|
||
aiConclusion: '',
|
||
aiSource: '',
|
||
aiScore: '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 多图识别结果合并(2026-10-16「可以多拍」):同一行的多张照片是**同一实物的不同角度**,
|
||
* 模型正常会把它们合并成一行;万一仍拆成多行,这里按字段取**第一个非空值**合并
|
||
* (规格/产地/生产日期;保质期单独走 `applyShelfLifeFromAi`)。
|
||
*/
|
||
function mergeRecognizedItemFields(items) {
|
||
const out = { spec: '', origin: '', production_date: '' };
|
||
for (const item of items || []) {
|
||
if (!item) continue;
|
||
if (!out.spec) out.spec = String(item.spec || '').trim();
|
||
if (!out.origin) out.origin = String(item.origin || '').trim();
|
||
if (!out.production_date) {
|
||
out.production_date = String(item.production_date || '').trim().slice(0, 10);
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function downloadImageAsBase64(url) {
|
||
return new Promise((resolve, reject) => {
|
||
wx.downloadFile({
|
||
url,
|
||
success: async (res) => {
|
||
if (res.statusCode !== 200 || !res.tempFilePath) {
|
||
reject(new Error('下载验收照片失败'));
|
||
return;
|
||
}
|
||
try {
|
||
resolve(await readFileAsBase64(res.tempFilePath));
|
||
} catch (err) {
|
||
reject(err);
|
||
}
|
||
},
|
||
fail: (err) => reject(new Error(err.errMsg || '下载验收照片失败')),
|
||
});
|
||
});
|
||
}
|
||
|
||
function confirmModal(title, content) {
|
||
return new Promise((resolve) => {
|
||
wx.showModal({
|
||
title,
|
||
content,
|
||
success: (res) => resolve(Boolean(res.confirm)),
|
||
fail: () => resolve(false),
|
||
});
|
||
});
|
||
}
|
||
|
||
function alertModal(title, content) {
|
||
return new Promise((resolve) => {
|
||
wx.showModal({
|
||
title,
|
||
content,
|
||
showCancel: false,
|
||
confirmText: '知道了',
|
||
success: () => resolve(),
|
||
fail: () => resolve(),
|
||
});
|
||
});
|
||
}
|
||
|
||
function formatGroupQty(value) {
|
||
const num = Number(value);
|
||
if (!Number.isFinite(num)) return '0';
|
||
const rounded = Math.round(num * 100) / 100;
|
||
return Number.isInteger(rounded) ? String(rounded) : String(rounded);
|
||
}
|
||
|
||
function skuGroupKey(row) {
|
||
const sku = String(row.sku_code || '').trim();
|
||
if (sku) return `sku:${sku}`;
|
||
return `name:${String(row.item_name || '').trim()}|${String(row.unit || '').trim()}`;
|
||
}
|
||
|
||
function rowCategoryLabel(row) {
|
||
const info = resolveLevel1CategoryInfo(row, []);
|
||
return String(info.name || '未分类').trim() || '未分类';
|
||
}
|
||
|
||
function formatInspectionDayHead(dayKey) {
|
||
if (!dayKey || dayKey === 'unknown') return '配送日';
|
||
const parts = String(dayKey).split('-');
|
||
if (parts.length !== 3) return `配送日 ${dayKey}`;
|
||
return `配送日 ${Number(parts[1])}月${Number(parts[2])}日`;
|
||
}
|
||
|
||
function inspectionDeliveryDay(row) {
|
||
const delivery = String(row?.delivery_date || '').trim().slice(0, 10);
|
||
if (/^\d{4}-\d{2}-\d{2}$/.test(delivery)) return delivery;
|
||
return 'unknown';
|
||
}
|
||
|
||
function buildDayCategoryGroups(rows) {
|
||
const byDay = new Map();
|
||
for (const row of rows || []) {
|
||
const dayKey = inspectionDeliveryDay(row);
|
||
if (!byDay.has(dayKey)) byDay.set(dayKey, []);
|
||
byDay.get(dayKey).push(row);
|
||
}
|
||
const dayKeys = [...byDay.keys()].sort((a, b) => String(a).localeCompare(String(b)));
|
||
const result = [];
|
||
for (const dayKey of dayKeys) {
|
||
const dayRows = [...(byDay.get(dayKey) || [])]
|
||
.sort((a, b) => {
|
||
const byCat = String(a.categoryLabel || a.category_name || '').localeCompare(
|
||
String(b.categoryLabel || b.category_name || ''),
|
||
'zh-CN'
|
||
);
|
||
if (byCat !== 0) return byCat;
|
||
return String(a.item_name || '').localeCompare(String(b.item_name || ''), 'zh-CN');
|
||
});
|
||
result.push({
|
||
groupKey: dayKey,
|
||
dayKey,
|
||
dayLabel: formatInspectionDayHead(dayKey),
|
||
showDayHeader: true,
|
||
items: dayRows,
|
||
});
|
||
}
|
||
return result;
|
||
}
|
||
|
||
function buildCategoryChips(rows) {
|
||
const map = new Map();
|
||
(rows || []).forEach((row) => {
|
||
const name = row.categoryLabel || '未分类';
|
||
map.set(name, (map.get(name) || 0) + 1);
|
||
});
|
||
return Array.from(map.entries())
|
||
.map(([name, count]) => ({ name, count }))
|
||
.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
|
||
}
|
||
|
||
Component({
|
||
options: { addGlobalClass: true },
|
||
|
||
properties: {
|
||
embedded: { type: Boolean, value: false },
|
||
hideProgress: { type: Boolean, value: false },
|
||
homeSourceFilter: { type: String, value: 'all' },
|
||
},
|
||
|
||
data: {
|
||
rows: [],
|
||
visibleRows: [],
|
||
categoryChips: [],
|
||
categoryFilter: '',
|
||
loading: false,
|
||
error: '',
|
||
submittingId: '',
|
||
analyzingId: '',
|
||
batchSubmitting: false,
|
||
sourceOptions: SOURCE_OPTIONS,
|
||
sourceIndex: 0,
|
||
sourceType: '',
|
||
resultOptions: RESULT_OPTIONS,
|
||
/** 存放区域候选(自由文本,无独立表;末尾恒带「+ 新增区域」) */
|
||
zoneOptions: [],
|
||
zoneRange: [],
|
||
zoneCreateIndex: 0,
|
||
shelfLifeUnits: SHELF_LIFE_UNITS,
|
||
photoInspectionEnabled: false,
|
||
pendingCount: 0,
|
||
doneCount: 0,
|
||
photoRequiredCount: 0,
|
||
/** 批次报告上传/解析进行中 */
|
||
reportBusy: false,
|
||
/** 批次报告核对表(null = 不显示):[{key, report_id, product_name, production_date, row_id, match_label}] */
|
||
reportReview: null,
|
||
foldSameSku: false,
|
||
skuGroups: [],
|
||
dayCategoryGroups: [],
|
||
collapsedGroupKeys: {},
|
||
dateField: 'created_at',
|
||
dateFieldLabel: '下单日',
|
||
dateFieldIndex: 0,
|
||
dateFieldOptions: DATE_FIELD_OPTIONS,
|
||
dateFrom: '',
|
||
dateTo: '',
|
||
todayValue: fmtLocalDate(),
|
||
},
|
||
|
||
observers: {
|
||
homeSourceFilter(next) {
|
||
if (!this.properties.embedded) return;
|
||
const mapped = this.mapHomeSourceFilter(next);
|
||
if (mapped.sourceType === this.data.sourceType && mapped.sourceIndex === this.data.sourceIndex) {
|
||
return;
|
||
}
|
||
this.setData(mapped, () => {
|
||
if (this._panelReady) this.loadRows();
|
||
});
|
||
},
|
||
},
|
||
|
||
lifetimes: {
|
||
attached() {
|
||
this.onPanelShow();
|
||
},
|
||
},
|
||
|
||
pageLifetimes: {
|
||
show() {
|
||
this.onPanelShow();
|
||
},
|
||
},
|
||
|
||
methods: {
|
||
mapHomeSourceFilter(raw) {
|
||
const value = String(raw || 'all');
|
||
if (value === 'supplier') return { sourceIndex: 1, sourceType: 'supplier' };
|
||
if (value === 'purchase') return { sourceIndex: 2, sourceType: 'purchase' };
|
||
return { sourceIndex: 0, sourceType: '' };
|
||
},
|
||
|
||
emitBadge(count) {
|
||
const value = Number(count);
|
||
if (Number.isFinite(value)) {
|
||
this.triggerEvent('badgechange', {
|
||
count: value,
|
||
badgeKey: 'inspectionPendingBadgeCount',
|
||
});
|
||
return;
|
||
}
|
||
this.triggerEvent('badgechange', { badgeKey: 'inspectionPendingBadgeCount' });
|
||
},
|
||
|
||
emitProgress(patch = {}) {
|
||
if (!this.properties.hideProgress) return;
|
||
this.triggerEvent('progresschange', {
|
||
pendingCount:
|
||
patch.pendingCount != null ? patch.pendingCount : this.data.pendingCount,
|
||
doneCount: patch.doneCount != null ? patch.doneCount : this.data.doneCount,
|
||
photoRequiredCount:
|
||
patch.photoRequiredCount != null
|
||
? patch.photoRequiredCount
|
||
: this.data.photoRequiredCount,
|
||
});
|
||
},
|
||
|
||
async onPanelShow() {
|
||
if (!beginPanelShow(this)) return;
|
||
try {
|
||
const ok = await ensureMobileRole(WAREHOUSE_ROLES);
|
||
if (!ok) return;
|
||
if (this.properties.embedded) {
|
||
const mapped = this.mapHomeSourceFilter(this.properties.homeSourceFilter);
|
||
if (mapped.sourceType !== this.data.sourceType || mapped.sourceIndex !== this.data.sourceIndex) {
|
||
this.setData(mapped);
|
||
}
|
||
}
|
||
await this.loadZoneOptions();
|
||
await this.loadRows();
|
||
this._panelReady = true;
|
||
} finally {
|
||
endPanelShow(this);
|
||
}
|
||
},
|
||
|
||
/** 存放区域候选(只读、失败即空:不阻塞验收) */
|
||
async loadZoneOptions() {
|
||
try {
|
||
const res = await fetchStockInboundStorageZones();
|
||
const rows = (res && res.data) || res || [];
|
||
this.applyZoneOptions(rows);
|
||
} catch (_e) {
|
||
/* 候选拉不到不影响验收 */
|
||
}
|
||
},
|
||
|
||
applyZoneOptions(zones) {
|
||
const zoneOptions = (Array.isArray(zones) ? zones : [])
|
||
.map((z) => String(z || '').trim())
|
||
.filter(Boolean);
|
||
const zoneRange = [...zoneOptions, ZONE_CREATE_LABEL];
|
||
const zoneCreateIndex = zoneOptions.length;
|
||
// 候选到位后重算每行的打开位置(显示文案取 item.storage_zone,不受影响)
|
||
const rows = (this.data.rows || []).map((row) => ({
|
||
...row,
|
||
zoneIndex: zoneIndexOf(row.storage_zone, zoneOptions, zoneCreateIndex),
|
||
}));
|
||
this.setData({ zoneOptions, zoneRange, zoneCreateIndex, rows }, () => this.rebuildSkuGroups());
|
||
},
|
||
|
||
onSourceChange(e) {
|
||
const index = Number(e.detail.value) || 0;
|
||
this.setData({
|
||
sourceIndex: index,
|
||
sourceType: SOURCE_VALUES[index] || '',
|
||
categoryFilter: '',
|
||
});
|
||
this.loadRows();
|
||
},
|
||
|
||
onRefresh() {
|
||
this.setData({ categoryFilter: '' }, () => this.loadRows());
|
||
},
|
||
|
||
async loadRows() {
|
||
this.setData({ loading: true, error: '' });
|
||
try {
|
||
const params = {};
|
||
if (this.data.sourceType) params.source_type = this.data.sourceType;
|
||
if (this.data.dateField) params.date_field = this.data.dateField;
|
||
if (this.data.dateFrom) params.date_from = this.data.dateFrom;
|
||
if (this.data.dateTo) params.date_to = this.data.dateTo;
|
||
const result = await fetchInspectionTasks(params);
|
||
const prevById = {};
|
||
(this.data.rows || []).forEach((row) => {
|
||
prevById[row.id] = row;
|
||
});
|
||
const rows = (result.data || [])
|
||
.map((row) => {
|
||
const party = resolvePartyInfo(row);
|
||
const requiresPrepackagedCheck = row.requires_prepackaged_check === true;
|
||
const photoUrls = Array.isArray(row.inspection_photo_urls)
|
||
? row.inspection_photo_urls
|
||
: [];
|
||
const photoCount = photoUrls.length || (Array.isArray(row.inspection_photos) ? row.inspection_photos.length : 0);
|
||
const prev = prevById[row.id];
|
||
const aiState = (this._aiStateById || {})[row.id] || emptyAiFields();
|
||
return {
|
||
...row,
|
||
item_name: resolveInspectionItemName(row),
|
||
partyLabel: party.partyLabel,
|
||
partyName: party.partyName,
|
||
sourceText: SOURCE_TEXT[row.source_type] || '入库',
|
||
photoUrls,
|
||
photoCount,
|
||
input_qty:
|
||
prev && prev.input_qty !== undefined ? prev.input_qty : String(row.prepare_qty || ''),
|
||
input_rating: prev?.input_rating || RESULT_PASS,
|
||
// 存放区域:默认取该商品上次入库的区域(可改);保留操作员已填(刷新不丢)
|
||
storage_zone:
|
||
prev && prev.storage_zone !== undefined
|
||
? prev.storage_zone
|
||
: String(row.last_storage_zone || '').trim(),
|
||
// 批次报告提取的生产日期与报告 id:本会话内保留(同 input_qty,刷新不丢)
|
||
production_date:
|
||
prev && prev.production_date !== undefined ? prev.production_date : '',
|
||
batch_report_id:
|
||
prev && prev.batch_report_id !== undefined ? prev.batch_report_id : '',
|
||
// 规格 / 保质期 / 产地(2026-10-16 补齐):规格「商品有就带过去」= 商品库 skus.spec 预填
|
||
input_spec:
|
||
prev && prev.input_spec !== undefined
|
||
? prev.input_spec
|
||
: String(row.spec || '').trim(),
|
||
input_shelf_life_value:
|
||
prev && prev.input_shelf_life_value !== undefined ? prev.input_shelf_life_value : '',
|
||
input_shelf_life_unit: prev?.input_shelf_life_unit || '',
|
||
input_shelf_life_unit_index: prev?.input_shelf_life_unit_index || 0,
|
||
input_origin:
|
||
prev && prev.input_origin !== undefined ? prev.input_origin : '',
|
||
specEdited: prev?.specEdited === true,
|
||
originEdited: prev?.originEdited === true,
|
||
zoneIndex: zoneIndexOf(
|
||
prev && prev.storage_zone !== undefined
|
||
? prev.storage_zone
|
||
: String(row.last_storage_zone || '').trim(),
|
||
this.data.zoneOptions,
|
||
this.data.zoneCreateIndex
|
||
),
|
||
production_month:
|
||
prev?.production_month ||
|
||
row.production_month ||
|
||
row.prepackaged_scan?.ocr_production_month ||
|
||
currentMonthValue(),
|
||
prepackaged_scan: row.prepackaged_scan || prev?.prepackaged_scan || null,
|
||
requires_prepackaged_check: requiresPrepackagedCheck,
|
||
photoRequired: row.requires_photo_inspection !== false || requiresPrepackagedCheck,
|
||
categoryLabel: rowCategoryLabel(row),
|
||
deliveryDay: inspectionDeliveryDay(row),
|
||
...aiState,
|
||
};
|
||
})
|
||
.sort((a, b) => {
|
||
const byName = String(a.item_name || '').localeCompare(String(b.item_name || ''), 'zh-CN');
|
||
if (byName !== 0) return byName;
|
||
const bySku = String(a.sku_code || '').localeCompare(String(b.sku_code || ''), 'zh-CN');
|
||
if (bySku !== 0) return bySku;
|
||
return String(a.created_at || '').localeCompare(String(b.created_at || ''));
|
||
});
|
||
const pendingCount = rows.length;
|
||
const doneCount = rows.length;
|
||
const photoRequiredCount = rows.filter((r) => r.photoRequired).length;
|
||
await new Promise((resolve) => {
|
||
this.setData(
|
||
{
|
||
rows,
|
||
photoInspectionEnabled: result.photo_inspection_enabled !== false,
|
||
pendingCount,
|
||
doneCount,
|
||
photoRequiredCount,
|
||
},
|
||
() => {
|
||
this.refreshInboundView();
|
||
this.emitProgress({ pendingCount, doneCount, photoRequiredCount });
|
||
this.emitBadge(result.pending_count);
|
||
resolve();
|
||
}
|
||
);
|
||
});
|
||
return rows;
|
||
} catch (err) {
|
||
this.setData({
|
||
error: err.message || '加载失败',
|
||
rows: [],
|
||
visibleRows: [],
|
||
categoryChips: [],
|
||
categoryFilter: '',
|
||
skuGroups: [],
|
||
dayCategoryGroups: [],
|
||
photoInspectionEnabled: false,
|
||
pendingCount: 0,
|
||
doneCount: 0,
|
||
photoRequiredCount: 0,
|
||
});
|
||
this.emitProgress({ pendingCount: 0, doneCount: 0, photoRequiredCount: 0 });
|
||
return [];
|
||
} finally {
|
||
this.setData({ loading: false });
|
||
}
|
||
},
|
||
|
||
onSourcePillTap(e) {
|
||
const index = Number(e.currentTarget.dataset.index) || 0;
|
||
this.setData({
|
||
sourceIndex: index,
|
||
sourceType: SOURCE_VALUES[index] || '',
|
||
categoryFilter: '',
|
||
});
|
||
this.loadRows();
|
||
},
|
||
|
||
onDateFieldPick(e) {
|
||
const idx = Number(e.detail.value) || 0;
|
||
const opt = DATE_FIELD_OPTIONS[idx] || DATE_FIELD_OPTIONS[0];
|
||
if (opt.value === this.data.dateField) return;
|
||
this.setData(
|
||
{
|
||
dateField: opt.value,
|
||
dateFieldIndex: idx,
|
||
dateFieldLabel: opt.label,
|
||
},
|
||
() => this.loadRows()
|
||
);
|
||
},
|
||
|
||
onCustomFromChange(e) {
|
||
const next = String(e.detail.value || '').trim().slice(0, 10);
|
||
if (!/^\d{4}-\d{2}-\d{2}$/.test(next)) return;
|
||
let to = this.data.dateTo || '';
|
||
if (to && next > to) to = next;
|
||
this.setData({ dateFrom: next, dateTo: to }, () => this.loadRows());
|
||
},
|
||
|
||
onCustomToChange(e) {
|
||
const next = String(e.detail.value || '').trim().slice(0, 10);
|
||
if (!/^\d{4}-\d{2}-\d{2}$/.test(next)) return;
|
||
let from = this.data.dateFrom || '';
|
||
if (from && next < from) from = next;
|
||
this.setData({ dateFrom: from, dateTo: next }, () => this.loadRows());
|
||
},
|
||
|
||
onCategoryTap(e) {
|
||
const name = String(e.currentTarget.dataset.name || '');
|
||
const next = this.data.categoryFilter === name ? '' : name;
|
||
this.setData({ categoryFilter: next }, () => this.refreshInboundView());
|
||
},
|
||
|
||
refreshInboundView() {
|
||
const rows = this.data.rows || [];
|
||
const chips = buildCategoryChips(rows);
|
||
let categoryFilter = this.data.categoryFilter || '';
|
||
if (categoryFilter && !chips.some((c) => c.name === categoryFilter)) {
|
||
categoryFilter = '';
|
||
}
|
||
const visibleRows = categoryFilter
|
||
? rows.filter((row) => row.categoryLabel === categoryFilter)
|
||
: rows;
|
||
const skuGroups = this.data.foldSameSku ? this.buildSkuGroupsFrom(visibleRows) : [];
|
||
const dayCategoryGroups = buildDayCategoryGroups(visibleRows).map((group) => ({
|
||
...group,
|
||
skuGroups: this.data.foldSameSku ? this.buildSkuGroupsFrom(group.items) : [],
|
||
}));
|
||
this.setData({
|
||
visibleRows,
|
||
categoryChips: chips,
|
||
categoryFilter,
|
||
skuGroups,
|
||
dayCategoryGroups,
|
||
});
|
||
},
|
||
|
||
buildSkuGroupsFrom(list) {
|
||
const buckets = new Map();
|
||
(list || []).forEach((row) => {
|
||
const key = skuGroupKey(row);
|
||
if (!buckets.has(key)) buckets.set(key, []);
|
||
buckets.get(key).push(row);
|
||
});
|
||
const collapsedMap = this.data.collapsedGroupKeys || {};
|
||
return Array.from(buckets.entries()).map(([key, items]) => {
|
||
const first = items[0] || {};
|
||
const prepareSum = items.reduce((sum, row) => sum + (Number(row.prepare_qty) || 0), 0);
|
||
const actualSum = items.reduce((sum, row) => sum + (Number(row.input_qty) || 0), 0);
|
||
const multi = items.length > 1;
|
||
return {
|
||
key,
|
||
name: first.item_name || '未知商品',
|
||
unit: first.unit || '',
|
||
count: items.length,
|
||
multi,
|
||
collapsed: multi && collapsedMap[key] !== false,
|
||
prepareSumText: formatGroupQty(prepareSum),
|
||
actualSumText: formatGroupQty(actualSum),
|
||
items,
|
||
};
|
||
});
|
||
},
|
||
|
||
rebuildSkuGroups() {
|
||
this.refreshInboundView();
|
||
},
|
||
|
||
toggleFoldSameSku() {
|
||
const foldSameSku = !this.data.foldSameSku;
|
||
this.setData(
|
||
{
|
||
foldSameSku,
|
||
collapsedGroupKeys: foldSameSku ? this.data.collapsedGroupKeys : {},
|
||
},
|
||
() => this.rebuildSkuGroups()
|
||
);
|
||
},
|
||
|
||
toggleSkuGroup(e) {
|
||
const key = e.currentTarget.dataset.key;
|
||
if (!key) return;
|
||
const collapsed = { ...(this.data.collapsedGroupKeys || {}) };
|
||
const isCollapsed = collapsed[key] !== false;
|
||
collapsed[key] = isCollapsed ? false : true;
|
||
this.setData({ collapsedGroupKeys: collapsed }, () => this.rebuildSkuGroups());
|
||
},
|
||
|
||
patchRow(id, patch) {
|
||
this.setData(
|
||
{
|
||
rows: this.data.rows.map((row) => (row.id === id ? { ...row, ...patch } : row)),
|
||
},
|
||
() => this.rebuildSkuGroups()
|
||
);
|
||
},
|
||
|
||
clearAiState(id) {
|
||
if (this._aiStateById) delete this._aiStateById[id];
|
||
this.patchRow(id, emptyAiFields());
|
||
},
|
||
|
||
async resolveAiImage(row) {
|
||
const cached = this._aiImageById && this._aiImageById[row.id];
|
||
if (cached) return cached;
|
||
const url = (row.photoUrls || []).find((item) => String(item || '').trim());
|
||
if (!url) {
|
||
throw new Error('请先拍照验收');
|
||
}
|
||
const content = await downloadImageAsBase64(url);
|
||
this._aiImageById = this._aiImageById || {};
|
||
this._aiImageById[row.id] = content;
|
||
return content;
|
||
},
|
||
|
||
resetAiResult(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
this.clearAiState(id);
|
||
const row = this.data.rows.find((item) => item.id === id);
|
||
if (row?.photoRequired && Number(row.photoCount || 0) > 0) {
|
||
this.runAiForRow(id);
|
||
}
|
||
},
|
||
|
||
async analyzeQuality(e) {
|
||
await this.runAiForRow(e.currentTarget.dataset.id);
|
||
},
|
||
|
||
async runAiForRow(id) {
|
||
const row = this.data.rows.find((item) => item.id === id);
|
||
if (!row) return;
|
||
if (Number(row.photoCount || 0) <= 0) {
|
||
wx.showToast({ title: '请先拍照验收', icon: 'none' });
|
||
return;
|
||
}
|
||
if (this.data.analyzingId) return;
|
||
this.setData({ analyzingId: id });
|
||
try {
|
||
const image = await this.resolveAiImage(row);
|
||
const data = await analyzeInspectionQuality({
|
||
image,
|
||
product_name: row.item_name || row.sku_name,
|
||
expected_qty: Number(row.prepare_qty) || 0,
|
||
actual_qty: Number(row.input_qty || row.prepare_qty) || 0,
|
||
});
|
||
const grade = String(data.grade || '').trim().toUpperCase();
|
||
const rating = defaultRatingFromGrade(grade);
|
||
const aiPatch = {
|
||
aiDone: true,
|
||
aiGrade: grade || '-',
|
||
aiConclusion: data.conclusion || '',
|
||
aiSource: data.analysis_source || '',
|
||
aiScore: data.score != null ? String(data.score) : '',
|
||
};
|
||
this._aiStateById = this._aiStateById || {};
|
||
this._aiStateById[id] = aiPatch;
|
||
this.patchRow(id, { ...aiPatch, input_rating: rating });
|
||
wx.showToast({
|
||
title: data.analysis_source === 'vision_unavailable' ? '视觉暂不可用,请人工判定' : 'AI 分析完成',
|
||
icon: 'none',
|
||
});
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || 'AI 分析失败', icon: 'none' });
|
||
} finally {
|
||
this.setData({ analyzingId: '' });
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 拍照后「识别商品信息」(2026-10-16,取代「拍照鉴别是否合格」):
|
||
* 复用库存入库那套识别,把 规格/生产日期/保质期/产地 **预填**到该行;**只补空、不覆盖已有值**。
|
||
* **支持多拍**(2026-10-16 开发者:「相当于可以多拍的」):本批全部照片**一次**提交给 AI(不再只用最后一张),
|
||
* 结果跨行按字段合并。识别失败不阻断入库(可人工填)。
|
||
*/
|
||
async runRecognizeForRow(id) {
|
||
const cached = (this._aiImagesById && this._aiImagesById[id]) || [];
|
||
const fallback = this._aiImageById && this._aiImageById[id];
|
||
const images = cached.length ? cached : fallback ? [fallback] : [];
|
||
if (!images.length) return;
|
||
const row = this.data.rows.find((item) => item.id === id) || {};
|
||
try {
|
||
const res = await recognizeStockInboundLines({ images_base64: images });
|
||
const data = (res && (res.data || res)) || {};
|
||
const items = Array.isArray(data.items) ? data.items : [];
|
||
if (!items.length) return;
|
||
const merged = mergeRecognizedItemFields(items);
|
||
const patch = {};
|
||
const spec = merged.spec;
|
||
const origin = merged.origin;
|
||
const pd = merged.production_date;
|
||
if (spec && !String(row.input_spec || '').trim()) patch.input_spec = spec;
|
||
if (origin && !String(row.input_origin || '').trim()) patch.input_origin = origin;
|
||
if (/^\d{4}-\d{2}-\d{2}$/.test(pd) && !String(row.production_date || '').trim()) {
|
||
patch.production_date = pd;
|
||
}
|
||
const hasShelf =
|
||
String(row.input_shelf_life_value || '').trim() ||
|
||
String(row.input_shelf_life_unit || '').trim();
|
||
if (!hasShelf) {
|
||
// 保质期:跨项取第一个能解析出值的(新字段优先、旧字段兜底)
|
||
let shelfLine = null;
|
||
for (const item of items) {
|
||
const line = applyShelfLifeFromAi({}, item);
|
||
if (line.shelf_life_value || line.shelf_life_unit) {
|
||
shelfLine = line;
|
||
break;
|
||
}
|
||
}
|
||
if (shelfLine) {
|
||
patch.input_shelf_life_value = shelfLine.shelf_life_value || '';
|
||
patch.input_shelf_life_unit = shelfLine.shelf_life_unit || '';
|
||
patch.input_shelf_life_unit_index = shelfLine.shelf_life_unit_index || 0;
|
||
}
|
||
}
|
||
if (Object.keys(patch).length) {
|
||
this.patchRow(id, patch);
|
||
wx.showToast({ title: '已识别商品信息', icon: 'none' });
|
||
} else {
|
||
wx.showToast({ title: '未识别到新信息,可手动填写', icon: 'none' });
|
||
}
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || '识别失败,可手动填写', icon: 'none' });
|
||
}
|
||
},
|
||
|
||
async completeWithOverQty(payload) {
|
||
try {
|
||
const body = await completeInspection(payload);
|
||
return body;
|
||
} catch (err) {
|
||
const code =
|
||
err.code || (typeof err.body?.error === 'string' ? err.body.error : '');
|
||
if (code !== 'pass_through_over_qty') throw err;
|
||
const ok = await confirmModal(
|
||
'过手超量确认',
|
||
`${err.message || '实收超过订货上限'}\n\n确认按实收继续入库?`
|
||
);
|
||
if (!ok) return false;
|
||
return completeInspection({ ...payload, confirm_over_qty: true });
|
||
}
|
||
},
|
||
|
||
async submitPassInspection(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
const row = this.data.rows.find((item) => item.id === id);
|
||
if (row?.input_rating === RESULT_FAIL) {
|
||
await alertModal('当前为不合格', '请先将结果改为合格,再点确认入库。');
|
||
return;
|
||
}
|
||
await this.submitInspection(e);
|
||
},
|
||
|
||
async markFailThenSubmit(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
// 退回是不可逆动作(按不合格退回、不入库)⇒ 先弹窗二次确认
|
||
const row = this.data.rows.find((item) => item.id === id);
|
||
const ok = await confirmModal(
|
||
'确认退回',
|
||
`「${resolveInspectionItemName(row || {})}」将按不合格退回、不入库。确定退回?`
|
||
);
|
||
if (!ok) return;
|
||
await new Promise((resolve) => {
|
||
this.setData(
|
||
{
|
||
rows: this.data.rows.map((row) =>
|
||
row.id === id ? { ...row, input_rating: RESULT_FAIL } : row
|
||
),
|
||
},
|
||
resolve
|
||
);
|
||
});
|
||
await this.submitInspection({ currentTarget: { dataset: { id } }, reject_fulfillment: true });
|
||
},
|
||
|
||
onQtyInput(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
const value = e.detail.value;
|
||
this.setData(
|
||
{
|
||
rows: this.data.rows.map((row) => (row.id === id ? { ...row, input_qty: value } : row)),
|
||
},
|
||
() => this.rebuildSkuGroups()
|
||
);
|
||
},
|
||
|
||
onZoneChange(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
const idx = Number(e.detail.value);
|
||
if (!Number.isInteger(idx) || idx < 0) return;
|
||
if (idx === this.data.zoneCreateIndex) {
|
||
// 新增区域:区域是自由文本,弹输入框(wx.showModal editable)
|
||
wx.showModal({
|
||
title: '新增存放区域',
|
||
editable: true,
|
||
placeholderText: '如:冷库A',
|
||
success: (res) => {
|
||
if (!res.confirm) return;
|
||
const name = String(res.content || '').trim();
|
||
if (!name) return;
|
||
const zoneOptions = this.data.zoneOptions.includes(name)
|
||
? this.data.zoneOptions
|
||
: [...this.data.zoneOptions, name];
|
||
const zoneRange = [...zoneOptions, ZONE_CREATE_LABEL];
|
||
const zoneCreateIndex = zoneOptions.length;
|
||
this.setData({ zoneOptions, zoneRange, zoneCreateIndex });
|
||
this.patchRow(id, { storage_zone: name, zoneIndex: zoneIndexOf(name, zoneOptions, zoneCreateIndex) });
|
||
},
|
||
});
|
||
return;
|
||
}
|
||
const zone = this.data.zoneOptions[idx] || '';
|
||
this.patchRow(id, { storage_zone: zone, zoneIndex: idx });
|
||
},
|
||
|
||
onRatingChange(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
const idx = Number(e.detail.value);
|
||
const value = idx === 1 ? RESULT_FAIL : RESULT_PASS;
|
||
// 列表渲染走 visibleRows/skuGroups,须经 patchRow 同步,否则滚轮选了也不刷新
|
||
this.patchRow(id, { input_rating: value });
|
||
},
|
||
|
||
onProductionMonthChange(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
const raw = e.detail.value || '';
|
||
const match = raw.match(/^(\d{4})-(\d{1,2})/);
|
||
const value = match
|
||
? `${match[1]}-${String(Number(match[2])).padStart(2, '0')}`
|
||
: raw;
|
||
this.patchRow(id, { production_month: value });
|
||
},
|
||
|
||
/** 规格(人工改过 ⇒ 标记回写档案) */
|
||
onSpecInput(e) {
|
||
this.patchRow(e.currentTarget.dataset.id, { input_spec: e.detail.value, specEdited: true });
|
||
},
|
||
|
||
/** 生产日期(手填,优先于批次报告/预包装年月) */
|
||
onProductionDateChange(e) {
|
||
const raw = String(e.detail.value || '').slice(0, 10);
|
||
this.patchRow(e.currentTarget.dataset.id, { production_date: raw });
|
||
},
|
||
|
||
/** 保质期数值(与单位选择器合成原文,如 6个月;落 inventory.shelf_life 并推算效期) */
|
||
onShelfValueInput(e) {
|
||
this.patchRow(e.currentTarget.dataset.id, { input_shelf_life_value: e.detail.value });
|
||
},
|
||
|
||
/** 保质期单位(年 / 月 / 日) */
|
||
onShelfUnitChange(e) {
|
||
const idx = Number(e.detail.value) || 0;
|
||
this.patchRow(e.currentTarget.dataset.id, {
|
||
input_shelf_life_unit: SHELF_LIFE_UNITS[idx] || '',
|
||
input_shelf_life_unit_index: idx,
|
||
});
|
||
},
|
||
|
||
/** 生产产地(人工改过 ⇒ 标记回写档案 skus.origin) */
|
||
onOriginInput(e) {
|
||
this.patchRow(e.currentTarget.dataset.id, { input_origin: e.detail.value, originEdited: true });
|
||
},
|
||
|
||
choosePhoto(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
wx.chooseImage({
|
||
count: 9,
|
||
sizeType: ['compressed'],
|
||
sourceType: ['camera', 'album'],
|
||
success: async (res) => {
|
||
const paths = res.tempFilePaths || [];
|
||
if (!paths.length) return;
|
||
// 本批多拍:重置本行的待识别图片集合(重拍 = 重来一批)
|
||
this._aiImagesById = this._aiImagesById || {};
|
||
this._aiImagesById[id] = [];
|
||
wx.showLoading({ title: '上传中…', mask: true });
|
||
try {
|
||
let latestScan = null;
|
||
// 单张失败不中断其余(弱网常见):继续传下一张,最后汇总提示
|
||
let failed = 0;
|
||
for (const filePath of paths) {
|
||
try {
|
||
latestScan = await this.uploadPhoto(id, filePath);
|
||
} catch (err) {
|
||
failed += 1;
|
||
}
|
||
}
|
||
if (failed && failed === paths.length) {
|
||
wx.showToast({ title: '照片上传失败,请重试', icon: 'none' });
|
||
return;
|
||
}
|
||
if (latestScan && latestScan.label_matched === false) {
|
||
const hints = [];
|
||
if (!latestScan.name_matched) {
|
||
hints.push(`商品名「${latestScan.ocr_product_name || '未识别'}」`);
|
||
}
|
||
if (!latestScan.brand_matched) {
|
||
hints.push(`品牌「${latestScan.ocr_brand || '未识别'}」`);
|
||
}
|
||
wx.showToast({
|
||
title: `${hints.join('、')}不对应`,
|
||
icon: 'none',
|
||
duration: 3000,
|
||
});
|
||
}
|
||
const rows = await this.loadRows();
|
||
const row = (rows || []).find((item) => item.id === id);
|
||
// 须/免拍照都识别(2026-10-16 开发者:可以)——只要本行有照片就走识别预填
|
||
if (Number(row?.photoCount || 0) > 0) {
|
||
wx.showLoading({ title: '识别中…', mask: true });
|
||
await this.runRecognizeForRow(id);
|
||
} else if (!(latestScan && latestScan.label_matched === false)) {
|
||
wx.showToast({ title: '拍照验收已上传', icon: 'success' });
|
||
}
|
||
// 有失败张:最后再提示一次(覆盖上一条 toast,失败更该被看见)
|
||
if (failed) {
|
||
wx.showToast({ title: `${failed} 张未上传,请重试`, icon: 'none', duration: 3000 });
|
||
}
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || '上传失败', icon: 'none' });
|
||
} finally {
|
||
wx.hideLoading();
|
||
}
|
||
},
|
||
fail: () => {
|
||
wx.showToast({ title: '未选择照片', icon: 'none' });
|
||
},
|
||
});
|
||
},
|
||
|
||
async uploadPhoto(id, filePath) {
|
||
const content = await prepareOrderImageBase64(filePath);
|
||
this._aiImageById = this._aiImageById || {};
|
||
this._aiImageById[id] = content;
|
||
// 多拍:本批每张都留 base64,识别时一次交给 AI(原来只留最后一张)
|
||
this._aiImagesById = this._aiImagesById || {};
|
||
if (!Array.isArray(this._aiImagesById[id])) this._aiImagesById[id] = [];
|
||
this._aiImagesById[id].push(content);
|
||
this.clearAiState(id);
|
||
const ext = (filePath.split('.').pop() || 'jpg').toLowerCase();
|
||
const result = await uploadInspectionPhoto({ id, content, ext });
|
||
return result.prepackaged_scan || null;
|
||
},
|
||
|
||
previewPhoto(e) {
|
||
const url = e.currentTarget.dataset.url;
|
||
const row = this.data.rows.find((item) => (item.photoUrls || []).includes(url));
|
||
const urls = row?.photoUrls?.length ? row.photoUrls : url ? [url] : [];
|
||
if (!urls.length) return;
|
||
wx.previewImage({ current: url, urls });
|
||
},
|
||
|
||
async deletePhoto(e) {
|
||
const id = e.currentTarget.dataset.id;
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
if (!id || !Number.isInteger(index) || index < 0) return;
|
||
const ok = await confirmModal('删除照片', '删除后需重新拍照才能入库。确定删除?');
|
||
if (!ok) return;
|
||
try {
|
||
wx.showLoading({ title: '删除中…', mask: true });
|
||
await deleteInspectionPhoto({ id, index });
|
||
if (this._aiImageById) delete this._aiImageById[id];
|
||
if (this._aiImagesById) delete this._aiImagesById[id];
|
||
this.clearAiState(id);
|
||
const rows = await this.loadRows();
|
||
const row = (rows || []).find((item) => item.id === id);
|
||
// 须/免拍照都识别(删图后若有剩余照片同样重识别)
|
||
if (Number(row?.photoCount || 0) > 0) {
|
||
wx.showLoading({ title: '识别中…', mask: true });
|
||
await this.runRecognizeForRow(id);
|
||
} else {
|
||
wx.showToast({ title: '已删除', icon: 'success' });
|
||
}
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || '删除失败', icon: 'none' });
|
||
} finally {
|
||
wx.hideLoading();
|
||
}
|
||
},
|
||
|
||
/** 批次报告:上传(拍照 / 相册 / 聊天里的 PDF,三者分开)→ 解析 → 按商品名匹配待验收行 → 弹核对表 */
|
||
onUploadBatchReports() {
|
||
if (this.data.reportBusy) return;
|
||
wx.showActionSheet({
|
||
itemList: ['拍照', '相册', '聊天文件(PDF)'],
|
||
success: (res) => {
|
||
if (res.tapIndex === 0) this.pickReportImages(['camera']);
|
||
else if (res.tapIndex === 1) this.pickReportImages(['album']);
|
||
else if (res.tapIndex === 2) this.pickReportFiles();
|
||
},
|
||
fail: () => undefined,
|
||
});
|
||
},
|
||
|
||
pickReportImages(sourceType) {
|
||
wx.chooseMedia({
|
||
count: 9,
|
||
mediaType: ['image'],
|
||
sourceType: sourceType || ['camera', 'album'],
|
||
success: (res) => {
|
||
const files = (res.tempFiles || []).filter((f) => f && f.tempFilePath);
|
||
if (files.length) {
|
||
this.submitReportFiles(files.map((f) => ({ path: f.tempFilePath, name: 'report.jpg' })));
|
||
}
|
||
},
|
||
fail: () => undefined,
|
||
});
|
||
},
|
||
|
||
pickReportFiles() {
|
||
if (typeof wx.chooseMessageFile !== 'function') {
|
||
wx.showToast({ title: '当前微信版本不支持选文件', icon: 'none' });
|
||
return;
|
||
}
|
||
wx.chooseMessageFile({
|
||
count: 9,
|
||
type: 'file',
|
||
extension: ['pdf'],
|
||
success: (res) => {
|
||
const files = (res.tempFiles || []).filter((f) => f && f.path);
|
||
if (files.length) {
|
||
this.submitReportFiles(files.map((f) => ({ path: f.path, name: f.name || 'report.pdf' })));
|
||
}
|
||
},
|
||
fail: () => undefined,
|
||
});
|
||
},
|
||
|
||
/** 逐张上传到 quality-reports 桶 → 调后端 OCR → 匹配 → 弹核对表 */
|
||
async submitReportFiles(files) {
|
||
this.setData({ reportBusy: true });
|
||
wx.showLoading({ title: '识别批次报告中…', mask: true });
|
||
try {
|
||
const paths = [];
|
||
for (const f of files) {
|
||
try {
|
||
paths.push(await uploadQualityReportStorageFile(f.path, f.name));
|
||
} catch (err) {
|
||
wx.showToast({ title: (err && err.message) || '报告上传失败', icon: 'none' });
|
||
}
|
||
}
|
||
if (!paths.length) return;
|
||
const res = await createInspectionBatchReports({ files: paths });
|
||
const reports = (res && res.data) || [];
|
||
const review = this.buildReportReview(reports);
|
||
if (!review.length) {
|
||
wx.showToast({ title: '未从报告中识别到商品', icon: 'none' });
|
||
return;
|
||
}
|
||
this.setData({ reportReview: review });
|
||
} catch (err) {
|
||
wx.showToast({ title: (err && err.message) || '批次报告识别失败', icon: 'none' });
|
||
} finally {
|
||
wx.hideLoading();
|
||
this.setData({ reportBusy: false });
|
||
}
|
||
},
|
||
|
||
/** 把 OCR 结果按商品名匹配到当前待验收行,生成核对表行 */
|
||
buildReportReview(reports) {
|
||
const rows = this.data.rows || [];
|
||
const norm = (v) =>
|
||
String(v || '')
|
||
.toLowerCase()
|
||
.replace(/[\s\u3000]+/g, '')
|
||
.replace(/[()()【】\[\]「」『』《》<>·•..]/g, '');
|
||
const out = [];
|
||
(reports || []).forEach((rep, ri) => {
|
||
const reportId = String((rep && rep.id) || '');
|
||
const producedAt = String((rep && rep.produced_at) || '').slice(0, 10);
|
||
const names = Array.isArray(rep && rep.product_names) ? rep.product_names : [];
|
||
const list = names.length ? names : [''];
|
||
list.forEach((name, ni) => {
|
||
const key = norm(name);
|
||
let rowId = '';
|
||
let matchLabel = '未匹配';
|
||
if (key) {
|
||
const hits = rows.filter((r) => norm(resolveInspectionItemName(r)) === key);
|
||
if (hits.length >= 1) {
|
||
rowId = hits[0].id;
|
||
matchLabel = `已匹配:${resolveInspectionItemName(hits[0])}`;
|
||
} else {
|
||
const fuzzy = rows.filter((r) => {
|
||
const n = norm(resolveInspectionItemName(r));
|
||
return n && (n.indexOf(key) >= 0 || key.indexOf(n) >= 0);
|
||
});
|
||
if (fuzzy.length) {
|
||
rowId = fuzzy[0].id;
|
||
matchLabel = `疑似:${resolveInspectionItemName(fuzzy[0])}`;
|
||
}
|
||
}
|
||
}
|
||
out.push({
|
||
key: `r${ri}_${ni}`,
|
||
report_id: reportId,
|
||
product_name: String(name || ''),
|
||
production_date: producedAt,
|
||
row_id: rowId,
|
||
match_label: matchLabel,
|
||
});
|
||
});
|
||
});
|
||
return out;
|
||
},
|
||
|
||
onReportDateChange(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
if (!Number.isInteger(index) || !this.data.reportReview) return;
|
||
this.setData({ [`reportReview[${index}].production_date`]: String(e.detail.value || '').slice(0, 10) });
|
||
},
|
||
|
||
onReportCancel() {
|
||
this.setData({ reportReview: null });
|
||
},
|
||
|
||
/** 确定:把核对表里(匹配到行且有日期)的生产日期写到该行,连同报告 id 随入库提交 */
|
||
onReportConfirm() {
|
||
const review = this.data.reportReview || [];
|
||
let applied = 0;
|
||
review.forEach((item) => {
|
||
if (!item.row_id) return;
|
||
const date = String(item.production_date || '').slice(0, 10);
|
||
const patch = { batch_report_id: item.report_id || '' };
|
||
if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
||
patch.production_date = date;
|
||
applied += 1;
|
||
}
|
||
this.patchRow(item.row_id, patch);
|
||
});
|
||
this.setData({ reportReview: null });
|
||
wx.showToast({ title: applied ? `已记录 ${applied} 项生产日期` : '未匹配到可入库的行', icon: 'none' });
|
||
},
|
||
|
||
noop() {},
|
||
|
||
async submitInspection(e) {
|
||
if (this.data.batchSubmitting) return;
|
||
const id = e.currentTarget.dataset.id;
|
||
const rejectFulfillment = e.reject_fulfillment === true;
|
||
const row = this.data.rows.find((item) => item.id === id);
|
||
const photoRequired = row?.photoRequired === true;
|
||
const photoCount = Number(row?.photoCount || 0);
|
||
if (photoRequired && photoCount <= 0) {
|
||
wx.showToast({ title: '请先拍照验收', icon: 'none' });
|
||
return;
|
||
}
|
||
|
||
if (!rejectFulfillment && row?.requires_prepackaged_check) {
|
||
if (!row.production_month) {
|
||
wx.showToast({ title: '请选择生产日期(月)', icon: 'none' });
|
||
return;
|
||
}
|
||
if (!row.prepackaged_scan?.label_matched) {
|
||
const parts = [];
|
||
if (!row.prepackaged_scan?.name_matched) {
|
||
parts.push(`商品名「${row.prepackaged_scan?.ocr_product_name || '未识别'}」`);
|
||
}
|
||
if (!row.prepackaged_scan?.brand_matched) {
|
||
parts.push(`品牌「${row.prepackaged_scan?.ocr_brand || '未识别'}」`);
|
||
}
|
||
wx.showToast({
|
||
title: `${parts.join('、')}与系统不对应`,
|
||
icon: 'none',
|
||
duration: 3000,
|
||
});
|
||
return;
|
||
}
|
||
}
|
||
|
||
const actualQty = Number(row?.input_qty || row?.prepare_qty || 0);
|
||
if (!rejectFulfillment && (!actualQty || actualQty <= 0)) {
|
||
wx.showToast({ title: '请输入实收数量', icon: 'none' });
|
||
return;
|
||
}
|
||
if (!rejectFulfillment && row?.input_rating === RESULT_FAIL) {
|
||
wx.showToast({ title: '请先将结果改为合格后再确认入库', icon: 'none' });
|
||
return;
|
||
}
|
||
|
||
const session = getSession();
|
||
this.setData({ submittingId: id });
|
||
try {
|
||
const body = await this.completeWithOverQty({
|
||
id,
|
||
actual_qty: rejectFulfillment ? Math.max(0, actualQty) : actualQty,
|
||
quality_rating: rejectFulfillment ? RESULT_FAIL : RESULT_PASS,
|
||
loss_qty: 0,
|
||
storage_zone: String(row?.storage_zone || '').trim() || undefined,
|
||
production_date_month: row?.requires_prepackaged_check ? row.production_month : undefined,
|
||
// 批次报告提取 / 卡面手填的生产日期(手填优先)——入库时带上
|
||
production_date: String(row?.production_date || '').trim() || undefined,
|
||
// 保质期(数值 + 年/月/日 合成原文,如 6个月)——服务端落 inventory.shelf_life 并推算 expiry_date
|
||
shelf_life:
|
||
shelfLifeTextFromLine({
|
||
shelf_life_value: row?.input_shelf_life_value,
|
||
shelf_life_unit: row?.input_shelf_life_unit,
|
||
}) || undefined,
|
||
// 规格/产地:人工改过才回写商品档案(product_catalog.spec / skus.origin)
|
||
archive: buildArchivePayload(
|
||
{ archiveSpec: row?.input_spec, archiveOrigin: row?.input_origin },
|
||
{ archiveSpec: row?.specEdited === true, archiveOrigin: row?.originEdited === true }
|
||
) || undefined,
|
||
batch_report_id: String(row?.batch_report_id || '').trim() || undefined,
|
||
location: session?.profile?.branch_name || '',
|
||
watermark_meta: {
|
||
branch_code: session?.profile?.branch_code,
|
||
branch_name: session?.profile?.branch_name,
|
||
source: 'miniprogram',
|
||
},
|
||
reject_fulfillment: rejectFulfillment || undefined,
|
||
});
|
||
if (!body) return;
|
||
const result = body.data || body;
|
||
const bounced =
|
||
result?.independentInboundReturned || result?.code === 'independent_inbound_returned';
|
||
wx.showToast({
|
||
title: bounced
|
||
? '已退回自采,请改数量或价格后再次完成'
|
||
: rejectFulfillment
|
||
? '已退回'
|
||
: '入库完成',
|
||
icon: bounced ? 'none' : 'success',
|
||
duration: bounced ? 2500 : 1500,
|
||
});
|
||
this.loadRows();
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || '提交失败', icon: 'none' });
|
||
} finally {
|
||
this.setData({ submittingId: '' });
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 一键全部合格入库:仅非须拍照、非预包装行,按应收量合格入库。
|
||
* 须拍照行需单独拍照后逐行确认入库(2026-10-16 起不再有 AI 质检),不进入批量。
|
||
*/
|
||
async submitAllEligible() {
|
||
if (this.data.batchSubmitting) return;
|
||
const targets = (this.data.visibleRows || this.data.rows).filter((row) => {
|
||
if (row.photoRequired === true) return false;
|
||
if (row.requires_prepackaged_check) return false;
|
||
const qty = Number(row.prepare_qty || 0);
|
||
return Number.isFinite(qty) && qty > 0;
|
||
});
|
||
if (!targets.length) {
|
||
wx.showToast({ title: '没有可一键入库的任务', icon: 'none' });
|
||
return;
|
||
}
|
||
const confirmed = await confirmModal(
|
||
'一键全部合格入库',
|
||
`将按应收量合格入库当前列表 ${targets.length} 项(无损耗)。须拍照行请单独拍照确认后处理。继续吗?`
|
||
);
|
||
if (!confirmed) return;
|
||
|
||
const session = getSession();
|
||
this.setData({ batchSubmitting: true });
|
||
wx.showLoading({ title: '批量入库中…', mask: true });
|
||
let success = 0;
|
||
const failed = [];
|
||
for (const row of targets) {
|
||
try {
|
||
await completeInspection({
|
||
id: row.id,
|
||
actual_qty: Number(row.prepare_qty),
|
||
quality_rating: RESULT_PASS,
|
||
loss_qty: 0,
|
||
storage_zone: String(row.storage_zone || '').trim() || undefined,
|
||
production_date: String(row.production_date || '').trim() || undefined,
|
||
batch_report_id: String(row.batch_report_id || '').trim() || undefined,
|
||
location: session?.profile?.branch_name || '',
|
||
watermark_meta: {
|
||
branch_code: session?.profile?.branch_code,
|
||
branch_name: session?.profile?.branch_name,
|
||
source: 'miniprogram',
|
||
},
|
||
});
|
||
success += 1;
|
||
} catch (_err) {
|
||
failed.push(row.item_name || row.id);
|
||
}
|
||
}
|
||
this.setData({ batchSubmitting: false });
|
||
wx.hideLoading();
|
||
if (failed.length) {
|
||
wx.showToast({
|
||
title: `入库 ${success} 项,失败 ${failed.length} 项请单独处理`,
|
||
icon: 'none',
|
||
duration: 3000,
|
||
});
|
||
} else {
|
||
wx.showToast({ title: `已入库 ${success} 项`, icon: 'success' });
|
||
}
|
||
this.loadRows();
|
||
},
|
||
},
|
||
});
|