Files
SupplierSystem/miniprogram/components/warehouse-panel/index.js
T
雨天 482c7c1e89
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(小程序): 新增仓库管理内嵌面板与授权
首页 Tab 内嵌仓库管理面板:批次/可用/成本价/报告/入库时间

默认仅看可用,顶部统计库存批次、可用总量、可用货值

批量上传按 Web 流程:上传→识别→候选→人工确认,编辑可直传

新增权限码 warehouse_manage,默认赋予仓管,不映射 Web 菜单

6 条移动端薄路由,全部复用 Web 同一批 service

修复首页未转发 onReachBottom 导致内嵌列表只有第 1 页

修复录单员获授权后点仓库管理回弹(漏传 permissions)
2026-10-25 13:47:33 +08:00

648 lines
23 KiB
JavaScript

/**
* 小程序「仓库管理」面板(2026-10-23 开发者):
* 与 Web 库存管理同一套能力与执行函数 —— 批次库存、成本价、商品名、报告状态,
* 支持**批量上传报告**、行内改成本价 / 可用数量、按批次查看与删除报告。
*
* 交互与其它模块一致:作为首页一级 Tab 内嵌(`embedded`),需要独立打开时由 `pages/warehouse` 包一层。
* 权限:默认仓管可见;其他角色在 Web「角色权限」勾 `warehouse_manage` 后同样可用。
*/
const { requireWarehouseModuleRole } = require('../../utils/roleGuard');
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
const {
fetchInventoryBatches,
fetchInventoryBatchReports,
uploadInventoryBatchReports,
parseInventoryBatchReports,
confirmInventoryBatchReportMatches,
deleteInventoryBatchReport,
updateInventoryBatchCostPrice,
updateInventoryBatchAvailableQty,
uploadQualityReportStorageFile,
} = require('../../utils/request');
const PAGE_SIZE = 20;
const REPORT_TYPE_LABELS = {
batch: '批次报告',
pesticide: '农残报告',
quarantine: '检疫报告',
annual: '年度报告',
};
function roundQty(value) {
const num = Number(value);
if (!Number.isFinite(num)) return 0;
return Math.round(num * 1000) / 1000;
}
function formatQty(value) {
return String(roundQty(value));
}
function formatMoney(value) {
const num = Number(value);
if (!Number.isFinite(num)) return '';
return num.toFixed(2);
}
/** 千位分隔(列表统计卡用):1234567.5 → 1,234,567.5 */
function withThousands(text) {
const [intPart, decPart] = String(text).split('.');
const grouped = String(intPart).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return decPart == null ? grouped : `${grouped}.${decPart}`;
}
/** 合计数量:千位分隔,最多 3 位小数,去尾零 */
function formatQtyTotal(value) {
const text = roundQty(value)
.toFixed(3)
.replace(/\.?0+$/, '');
return withThousands(text || '0');
}
/** 合计货值:千位分隔 + 固定两位小数 */
function formatMoneyTotal(value) {
const num = Number(value);
return withThousands((Number.isFinite(num) ? num : 0).toFixed(2));
}
function toRow(row) {
const reportCount = Number(row.batch_report_count) || 0;
const cost = row.cost_price == null ? null : Number(row.cost_price);
return {
id: String(row.id || ''),
sku_name: String(row.sku_name || row.sku_code || ''),
category_name: String(row.category_name || ''),
batch_no: String(row.batch_no || ''),
available_text: formatQty(row.available_qty),
cost_text: cost == null ? '' : formatMoney(cost),
cost_missing: cost == null || cost <= 0,
storage_zone: String(row.storage_zone || ''),
production_date: row.production_date ? String(row.production_date).slice(0, 10) : '',
expiry_date: row.expiry_date ? String(row.expiry_date).slice(0, 10) : '',
/** 入库时间 = 该批次最早一次入库流水(后端已出 'YYYY-MM-DD';无流水为空串) */
inbound_at: row.inbound_at ? String(row.inbound_at).slice(0, 10) : '',
report_count: reportCount,
report_missing: reportCount <= 0,
};
}
function totalLabel(count) {
const n = Number(count) || 0;
return `共 ${n} 批`;
}
Component({
options: { addGlobalClass: true },
properties: {
embedded: { type: Boolean, value: false },
homeTabFilter: { type: String, value: '' },
},
data: {
loading: false,
loadingMore: false,
rows: [],
totalText: '共 0 批',
page: 1,
hasMore: true,
search: '',
// 进入面板默认只看有可用库存的批次(2026-10-25 开发者)
onlyAvailable: true,
onlyMissingReport: false,
uploading: false,
uploadText: '',
// 批量上传报告:上传 → 解析 → 人工确认匹配(与 Web 同流程)
uploadOpen: false,
uploadFiles: [],
uploadParsing: false,
uploadConfirming: false,
uploadReports: [],
uploadSelectedCount: 0,
// 修改弹窗(点行直接弹出:可用数量 + 成本价 + 报告入口)
editItem: null,
editAvailable: '',
editCost: '',
editSaving: false,
// 批次报告
reportItem: null,
reports: [],
reportsLoading: false,
},
lifetimes: {
attached() {
this.onPanelShow();
},
},
pageLifetimes: {
show() {
this.onPanelShow();
},
},
methods: {
onPanelShow() {
if (!beginPanelShow(this)) return;
try {
if (!requireWarehouseModuleRole()) return;
if (!this._panelReady) {
this._panelReady = true;
this.reload();
return;
}
// 再次切回本 Tab 时刷新;但选图/编辑/报告弹层进行中不打断
if (this.data.uploading || this.data.editSaving || this.data.editItem || this.data.reportItem) {
return;
}
this.reload();
} finally {
endPanelShow(this);
}
},
onPullDownRefresh() {
this.reload().then(() => wx.stopPullDownRefresh());
},
onReachBottom() {
if (!this.data.hasMore || this.data.loading || this.data.loadingMore) return;
this.loadPage(this.data.page + 1, true);
},
reload() {
this.setData({ page: 1, hasMore: true });
return this.loadPage(1, false);
},
async loadPage(page, append) {
if (append) this.setData({ loadingMore: true });
else this.setData({ loading: true });
try {
const res = await fetchInventoryBatches({
page,
page_size: PAGE_SIZE,
search: String(this.data.search || '').trim() || undefined,
only_available: this.data.onlyAvailable === true,
});
const rawRows = ((res && res.data) || []).map(toRow);
// 「缺报告」是本地筛选(服务端列表口径不动):hasMore 按**原始条数**判断,避免筛完误判到底
const rows = this.data.onlyMissingReport
? rawRows.filter((row) => row.report_missing)
: rawRows;
const nextRows = append ? (this.data.rows || []).concat(rows) : rows;
this.setData({
rows: nextRows,
totalText: totalLabel(res && res.total),
page,
hasMore: rawRows.length >= PAGE_SIZE,
});
// 顶部统计卡(与列表同一筛选口径,服务端已算好):批次数量 / 可用总量 / 可用货值
const stats = (res && res.stats) || {};
this.triggerEvent('statschange', {
batches: Number(res && res.total) || 0,
availableQtyText: formatQtyTotal(stats.total_available_qty),
availableValueText: formatMoneyTotal(stats.total_value),
});
} catch (err) {
wx.showToast({ title: (err && err.message) || '加载失败', icon: 'none' });
} finally {
this.setData({ loading: false, loadingMore: false });
}
},
noop() {},
onSearchInput(e) {
const value = String((e && e.detail && e.detail.value) || '');
this.setData({ search: value });
clearTimeout(this._searchTimer);
this._searchTimer = setTimeout(() => this.reload(), 400);
},
onSearchConfirm() {
this.reload();
},
toggleOnlyAvailable() {
this.setData({ onlyAvailable: !this.data.onlyAvailable }, () => this.reload());
},
toggleOnlyMissingReport() {
this.setData({ onlyMissingReport: !this.data.onlyMissingReport }, () => this.reload());
},
// ── 批量上传报告:上传 → 解析 → 人工确认匹配(与 Web 同流程) ──
openUploadSheet() {
this.setData({
uploadOpen: true,
uploadFiles: [],
uploadParsing: false,
uploadConfirming: false,
uploadReports: [],
uploadSelectedCount: 0,
});
},
closeUploadSheet() {
if (this.data.uploadParsing || this.data.uploadConfirming) return;
this.setData({ uploadOpen: false });
},
async pickUploadFiles() {
if (this.data.uploadParsing || this.data.uploadConfirming) return;
const files = await this.chooseReportFiles();
if (!files || !files.length) return;
const next = (this.data.uploadFiles || []).concat(files).slice(0, 9);
this.setData({ uploadFiles: next });
},
removeUploadFile(e) {
const index = Number(e.currentTarget.dataset.index);
if (!Number.isInteger(index) || index < 0) return;
const next = (this.data.uploadFiles || []).filter((_, i) => i !== index);
this.setData({ uploadFiles: next });
},
/** 上传并识别:服务端 OCR + 匹配候选批次(同一 service,与 Web 页级上传一致) */
async parseUploadFiles() {
if (this.data.uploadParsing || this.data.uploadConfirming) return;
const files = this.data.uploadFiles || [];
if (!files.length) {
wx.showToast({ title: '请先选择报告文件', icon: 'none' });
return;
}
this.setData({ uploadParsing: true, uploadText: '上传识别中…' });
try {
const paths = [];
for (let i = 0; i < files.length; i += 1) {
this.setData({ uploadText: `上传文件 ${i + 1}/${files.length}…` });
const res = await uploadQualityReportStorageFile(files[i].path, files[i].name);
const key =
typeof res === 'string'
? res
: (res && (res.path || res.key || res.file || res.url)) || '';
if (key) paths.push(String(key));
}
if (!paths.length) {
wx.showToast({ title: '上传文件失败', icon: 'none' });
return;
}
const res = await parseInventoryBatchReports({ files: paths, report_type: 'batch' });
const reports = (res && res.data) || [];
let selectedCount = 0;
const mapped = reports.map((report) => ({
id: report.id,
title: REPORT_TYPE_LABELS[report.report_type] || '报告',
report_no: report.report_no || '',
matches: (report.matches || []).map((match) => ({
product_name: match.product_name || '',
status: match.status,
status_text:
match.status === 'unique'
? '唯一匹配'
: match.status === 'multi'
? '多个候选'
: '未匹配',
candidates: (match.candidates || []).map((candidate) => {
// 唯一命中自动勾上(与 Web 一致),其余交给人工确认
const selected = match.status === 'unique';
if (selected) selectedCount += 1;
return {
key: `${report.id}::${candidate.inventory_id}`,
report_id: report.id,
inventory_id: candidate.inventory_id,
label: `${candidate.sku_name || candidate.sku_code || '未命名'} · ${candidate.batch_no || ''}`,
meta: [
candidate.available_qty != null ? `可用 ${candidate.available_qty}` : '',
candidate.unit || '',
candidate.production_date ? `生产 ${String(candidate.production_date).slice(0, 10)}` : '',
]
.filter(Boolean)
.join(' · '),
selected,
};
}),
})),
}));
this.setData({
uploadReports: mapped,
uploadSelectedCount: selectedCount,
});
if (!reports.length) {
wx.showToast({ title: '未识别到报告内容,可重拍后重试', icon: 'none' });
}
} catch (err) {
wx.showToast({ title: (err && err.message) || '识别失败', icon: 'none' });
} finally {
this.setData({ uploadParsing: false, uploadText: '' });
}
},
toggleUploadCandidate(e) {
if (this.data.uploadConfirming) return;
const key = String((e.currentTarget.dataset && e.currentTarget.dataset.key) || '');
if (!key) return;
let selectedCount = 0;
const reports = (this.data.uploadReports || []).map((report) => ({
...report,
matches: (report.matches || []).map((match) => ({
...match,
candidates: (match.candidates || []).map((candidate) => {
const selected = candidate.key === key ? !candidate.selected : candidate.selected;
if (selected) selectedCount += 1;
return { ...candidate, selected };
}),
})),
}));
this.setData({ uploadReports: reports, uploadSelectedCount: selectedCount });
},
async confirmUploadMatches() {
if (this.data.uploadConfirming) return;
const reports = this.data.uploadReports || [];
const payloads = reports
.map((report) => ({
reportId: report.id,
matches: (report.matches || []).flatMap((match) =>
(match.candidates || [])
.filter((candidate) => candidate.selected)
.map((candidate) => ({
inventory_id: candidate.inventory_id,
product_name: match.product_name,
}))
),
}))
.filter((row) => row.matches.length);
if (!payloads.length) {
wx.showToast({ title: '请至少选择一条入库批次', icon: 'none' });
return;
}
this.setData({ uploadConfirming: true, uploadText: '确认中…' });
try {
for (let i = 0; i < payloads.length; i += 1) {
this.setData({ uploadText: `确认匹配 ${i + 1}/${payloads.length}…` });
await confirmInventoryBatchReportMatches(payloads[i].reportId, payloads[i].matches);
}
wx.showToast({ title: '报告已匹配并绑定', icon: 'success' });
this.setData({ uploadOpen: false, uploadReports: [], uploadFiles: [] });
await this.reload();
} catch (err) {
wx.showToast({ title: (err && err.message) || '确认失败', icon: 'none' });
} finally {
this.setData({ uploadConfirming: false, uploadText: '' });
}
},
chooseReportFiles() {
return new Promise((resolve) => {
wx.showActionSheet({
itemList: ['拍照 / 相册', '微信文件(PDF 等)'],
success: (tap) => {
if (tap.tapIndex === 0) {
wx.chooseMedia({
count: 9,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: (res) => {
resolve(
(res.tempFiles || []).map((file, index) => ({
path: file.tempFilePath,
name: file.name || `photo-${Date.now()}-${index}.jpg`,
}))
);
},
fail: () => resolve([]),
});
return;
}
wx.chooseMessageFile({
count: 9,
type: 'all',
success: (res) => {
resolve(
(res.tempFiles || [])
.map((file) => ({ path: file.path, name: file.name || '' }))
.filter((file) => /\.(pdf|jpe?g|png|webp)$/i.test(String(file.name || file.path)))
);
},
fail: () => resolve([]),
});
},
fail: () => resolve([]),
});
});
},
// ── 行点击:表格行太窄,操作用底部 actionSheet 收口 ─────────
/** 点行 → 直接弹「修改」弹窗(不再先出选择菜单,2026-10-23 开发者) */
onRowTap(e) {
this.openEditSheetById(String((e.currentTarget.dataset && e.currentTarget.dataset.id) || ''));
},
// ── 修改弹窗:可用数量 + 成本价一次改完 ───────────────────
openEditSheetById(id) {
const row = (this.data.rows || []).find((item) => item.id === id);
if (!row) return;
this.setData({
editItem: {
id: row.id,
sku_name: row.sku_name,
batch_no: row.batch_no,
category_name: row.category_name,
storage_zone: row.storage_zone,
report_count: row.report_count,
report_missing: row.report_missing,
available: row.available_text,
cost: row.cost_missing ? '' : row.cost_text,
},
editAvailable: row.available_text,
editCost: row.cost_missing ? '' : row.cost_text,
});
},
onEditAvailableInput(e) {
this.setData({ editAvailable: String((e && e.detail && e.detail.value) || '') });
},
onEditCostInput(e) {
this.setData({ editCost: String((e && e.detail && e.detail.value) || '') });
},
closeEdit() {
if (this.data.editSaving) return;
this.setData({ editItem: null, editAvailable: '', editCost: '' });
},
/** 从修改弹窗跳到该批次报告(弹窗关闭,避免叠层) */
openReportsFromEdit() {
const id = this.data.editItem && this.data.editItem.id;
if (!id) return;
this.setData({ editItem: null, editAvailable: '', editCost: '' });
void this.openReportsById(String(id));
},
async submitEditSheet() {
const item = this.data.editItem;
if (!item || this.data.editSaving) return;
const qtyText = String(this.data.editAvailable || '').trim();
const costText = String(this.data.editCost || '').trim();
const nextQty = qtyText === '' ? Number.NaN : Number(qtyText);
if (!Number.isFinite(nextQty) || nextQty < 0) {
wx.showToast({ title: '可用数量须为不小于 0 的数字', icon: 'none' });
return;
}
const nextCost = costText === '' ? null : Number(costText);
if (nextCost != null && (!Number.isFinite(nextCost) || nextCost < 0)) {
wx.showToast({ title: '成本价须为不小于 0 的数字', icon: 'none' });
return;
}
const prevQty = Number(item.available);
const prevCost = item.cost === '' ? null : Number(item.cost);
const qtyChanged = Math.abs(nextQty - prevQty) > 1e-9;
const costChanged = (prevCost == null ? null : prevCost) !== nextCost;
if (!qtyChanged && !costChanged) {
wx.showToast({ title: '没有改动', icon: 'none' });
return;
}
this.setData({ editSaving: true });
try {
// 只提交真正改过的字段:两条写路径与 Web 完全一致(各带自己的审计/流水)
if (qtyChanged) await updateInventoryBatchAvailableQty(item.id, nextQty);
if (costChanged) await updateInventoryBatchCostPrice(item.id, nextCost);
this.setData({ editItem: null, editAvailable: '', editCost: '' });
wx.showToast({ title: '已保存', icon: 'success' });
await this.reload();
} catch (err) {
wx.showToast({ title: (err && err.message) || '保存失败', icon: 'none' });
} finally {
this.setData({ editSaving: false });
}
},
// ── 批次报告:查看 / 删除 ───────────────────────────────
openReports(e) {
void this.openReportsById(String((e.currentTarget.dataset && e.currentTarget.dataset.id) || ''));
},
/** 报告行 → 展示结构(列表/弹窗共用) */
mapReportRows(rows) {
return (Array.isArray(rows) ? rows : []).map((report) => ({
id: report.id,
type_label: REPORT_TYPE_LABELS[report.report_type] || report.report_type || '报告',
report_no: report.report_no || '',
uploaded_at: report.uploaded_at || '',
}));
},
/**
* 单批次上传报告(编辑弹窗 / 报告弹窗共用):
* 选文件 → 上传一次 → 绑定到该批次 → 刷新报告列表与表格里的报告列。
*/
async uploadReportsForBatch(inventoryId) {
const id = String(inventoryId || '');
if (!id || this.data.uploading) return;
const files = await this.chooseReportFiles();
if (!files || !files.length) return;
this.setData({ uploading: true, uploadText: '上传中…' });
try {
const paths = [];
for (let i = 0; i < files.length; i += 1) {
const res = await uploadQualityReportStorageFile(files[i].path, files[i].name);
const key =
typeof res === 'string'
? res
: (res && (res.path || res.key || res.file || res.url)) || '';
if (key) paths.push(String(key));
}
if (!paths.length) {
wx.showToast({ title: '上传文件失败', icon: 'none' });
return;
}
await uploadInventoryBatchReports(id, { files: paths, report_type: 'batch' });
wx.showToast({ title: '报告已上传', icon: 'success' });
await this.refreshBatchReports(id);
} catch (err) {
wx.showToast({ title: (err && err.message) || '上传失败', icon: 'none' });
} finally {
this.setData({ uploading: false, uploadText: '' });
}
},
/** 上传/删除后刷新:报告弹窗列表 + 编辑弹窗的报告状态 + 表格报告列 */
async refreshBatchReports(inventoryId) {
try {
const res = await fetchInventoryBatchReports(inventoryId);
const list = this.mapReportRows(res && res.data);
const patch = {};
if (this.data.reportItem && this.data.reportItem.id === inventoryId) {
patch.reports = list;
}
if (this.data.editItem && this.data.editItem.id === inventoryId) {
patch['editItem.report_count'] = list.length;
patch['editItem.report_missing'] = list.length <= 0;
}
if (Object.keys(patch).length) this.setData(patch);
} catch {
// 刷新失败不影响已完成的绑定
}
// 表格里的「报告」列同步(不重置已选)
await this.loadPage(1, false);
},
onUploadFromEdit() {
const id = this.data.editItem && this.data.editItem.id;
if (!id) return;
void this.uploadReportsForBatch(id);
},
onUploadFromReports() {
const id = this.data.reportItem && this.data.reportItem.id;
if (!id) return;
void this.uploadReportsForBatch(id);
},
async openReportsById(id) {
const row = (this.data.rows || []).find((item) => item.id === id);
if (!row) return;
this.setData({ reportItem: row, reports: [], reportsLoading: true });
try {
const res = await fetchInventoryBatchReports(id);
this.setData({ reports: this.mapReportRows(res && res.data) });
} catch (err) {
wx.showToast({ title: (err && err.message) || '加载报告失败', icon: 'none' });
} finally {
this.setData({ reportsLoading: false });
}
},
closeReports() {
this.setData({ reportItem: null, reports: [] });
},
async onDeleteReport(e) {
const reportId = String((e.currentTarget.dataset && e.currentTarget.dataset.id) || '');
const batchId = this.data.reportItem && this.data.reportItem.id;
if (!reportId) return;
const confirm = await new Promise((resolve) => {
wx.showModal({
title: '删除报告',
content: '删除后该批次会显示「缺少批次报告」,确定删除吗?',
success: (res) => resolve(res.confirm === true),
fail: () => resolve(false),
});
});
if (!confirm) return;
try {
await deleteInventoryBatchReport(reportId);
wx.showToast({ title: '已删除', icon: 'success' });
if (batchId) await this.refreshBatchReports(String(batchId));
else await this.reload();
} catch (err) {
wx.showToast({ title: (err && err.message) || '删除失败', icon: 'none' });
}
},
},
});