Files
SupplierSystem/miniprogram/components/inspection-panel/index.js
T
雨天 2f439026d3
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(验收): 入库补存放区域,默认取上次区域
Web 验收弹窗与小程序验收面板新增「存放区域」,随批次写入 inventory.storage_zone;独立进货走同一段 INSERT 一并覆盖。

默认值 = 该商品上次入库区域(同 SKU 最近一批非空区域):后端列表接口带 last_storage_zone,只拼在带 LIMIT 的列表查询上,不并入计数类查询。

区域为自由文本、无独立表:Web 复用 /inventory/storage-zones 候选 + 输入即新增;小程序原生 picker + 末尾「+ 新增区域」。不新增前端文案。称重台/Android 不做。

测试:server/tests/inspectionStorageZone.test.ts(8 例)、src/utils/inspectionStorageZone.contract.test.ts(13 例);npm run typecheck 通过;last_zone 片段已对本地库实跑。
2026-10-13 16:26:17 +08:00

1021 lines
34 KiB
JavaScript
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.
const {
fetchInspectionTasks,
completeInspection,
uploadInspectionPhoto,
deleteInspectionPhoto,
analyzeInspectionQuality,
fetchStockInboundStorageZones,
} = require('../../utils/request');
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: '',
};
}
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,
photoInspectionEnabled: false,
pendingCount: 0,
doneCount: 0,
photoRequiredCount: 0,
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(),
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: '' });
}
},
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(
'当前为不合格',
'AI 判定为不合格。请先将结果改为合格,再点确认入库。'
);
return;
}
await this.submitInspection(e);
},
async markFailThenSubmit(e) {
const id = e.currentTarget.dataset.id;
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 });
},
choosePhoto(e) {
const id = e.currentTarget.dataset.id;
wx.chooseImage({
count: 3,
sizeType: ['compressed'],
sourceType: ['camera', 'album'],
success: async (res) => {
const paths = res.tempFilePaths || [];
if (!paths.length) return;
wx.showLoading({ title: '上传中…', mask: true });
try {
let latestScan = null;
for (const filePath of paths) {
latestScan = await this.uploadPhoto(id, filePath);
}
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);
if (row?.photoRequired && Number(row.photoCount || 0) > 0) {
wx.showLoading({ title: 'AI分析中…', mask: true });
await this.runAiForRow(id);
} else if (!(latestScan && latestScan.label_matched === false)) {
wx.showToast({ title: '拍照验收已上传', icon: 'success' });
}
} 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;
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];
this.clearAiState(id);
const rows = await this.loadRows();
const row = (rows || []).find((item) => item.id === id);
if (row?.photoRequired && Number(row.photoCount || 0) > 0) {
wx.showLoading({ title: 'AI分析中…', mask: true });
await this.runAiForRow(id);
} else {
wx.showToast({ title: '已删除', icon: 'success' });
}
} catch (err) {
wx.showToast({ title: err.message || '删除失败', icon: 'none' });
} finally {
wx.hideLoading();
}
},
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 && photoRequired && !row.aiDone) {
wx.showToast({ title: '请先完成 AI 质检', 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,
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: '' });
}
},
/**
* 一键全部合格入库:仅非须拍照、非预包装行,按应收量合格入库。
* 须拍照行需单独走 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} 项(无损耗)。须拍照行请单独完成 AI 质检后处理。继续吗?`
);
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,
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();
},
},
});