Files
SupplierSystem/miniprogram/components/stock-inbound-panel/index.js
T
Ubuntu 1d47267a8d
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
chore(sync): 提交剩余本地改动(规则文档 / 部署配置 / 小程序入库归档 / 工具与测试)
- .cursor/rules + AGENTS.md:供应商二次开发的隔离硬规则落库(库/端口/上传目录/对象前缀)
- 部署与本地配置:docker-compose*.yml、.env.*.example(仅占位值)、start-split-native / sync-prod-db-to-local 脚本
- 小程序:入库归档识别(stockInboundArchive + 识别与入库面板改动)
- tools:设计门禁脚本(check-migrations / run-all / verify-facts)与架构图脚本更新
- docs:跨系统改价改量审核、第三方订单退货跟随、免入库推进、500+ 分公司规模改造、
  拍照入库识别与档案回写等设计文档;对接清单新增 §4.5.4 我方回执(第六批端到端)
- server:存量修数脚本(legacy CS / 供应商应付 / 结算口径)、采购耳标核对脚本;
  新增测试:入库归档回写、租户优选顺序、规模并发
2026-10-09 22:28:15 +08:00

575 lines
18 KiB
JavaScript

const {
fetchStockInboundCategories,
createStockInboundCategory,
fetchStockInboundSkuSimilar,
createStockInboundProduct,
submitStockInbound,
recognizeStockInboundCatalog,
fetchUnits,
} = require('../../utils/request');
const { filterCategoryOptions, findCategoryOptionByName } = require('../../utils/orderCategory');
const { ensureMobileRole } = require('../../utils/roleGuard');
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
const { prepareOrderImageBase64 } = require('../../utils/orderImage');
const { applyStockInboundSuggestion } = require('../../utils/stockInboundRecognize');
const {
buildArchivePayload,
hasUnsavedArchiveEdits,
} = require('../../utils/stockInboundArchive');
const {
buildUnitPicker,
ensureUnitDictionary,
getUnitDictionaryLabels,
} = require('../../utils/units');
const WAREHOUSE_ROLES = ['warehouse', 'inspector'];
function unitPickerPatch(currentUnit) {
const picker = buildUnitPicker(currentUnit || '', getUnitDictionaryLabels());
return {
skuUnit: picker.unit,
newUnit: picker.unit,
unitOptions: picker.unitOptions,
unitIndex: picker.unitIndex,
};
}
function categoryLabel(row) {
return String((row && (row.category_name || row.label || row.category_code)) || '').trim();
}
function todayYmd() {
const d = new Date();
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
Component({
options: { addGlobalClass: true },
properties: {
embedded: { type: Boolean, value: false },
},
data: {
nameQuery: '',
similar: [],
skuCode: '',
skuUnit: '',
unitOptions: [],
unitIndex: 0,
qty: '',
unitCost: '',
productionDate: '',
productionDateEnd: '',
categories: [],
categoryQuery: '',
categorySuggestions: [],
categoryCanCreate: false,
categoryDropdownOpen: false,
selectedCategory: null,
newName: '',
newSpec: '',
newBrand: '',
newUnit: '',
newOrigin: '',
archiveSpec: '',
archiveBrand: '',
archiveOrigin: '',
archiveEditHint: '',
imagePreview: '',
recognizing: false,
searching: false,
showCreateHint: false,
dropdownOpen: false,
createOpen: false,
},
lifetimes: {
attached() {
this.onPanelShow();
},
},
pageLifetimes: {
show() {
this.onPanelShow();
},
},
methods: {
async onPanelShow() {
if (!beginPanelShow(this)) return;
try {
const ok = await ensureMobileRole(WAREHOUSE_ROLES);
if (!ok) return;
await Promise.all([this.loadCategories(), ensureUnitDictionary(fetchUnits)]);
this.setData({
productionDateEnd: todayYmd(),
...unitPickerPatch(this.data.skuUnit),
});
} finally {
endPanelShow(this);
}
},
async loadCategories() {
try {
const res = await fetchStockInboundCategories();
const rows = res.data || res || [];
const list = Array.isArray(rows) ? rows : [];
this.setData({ categories: list });
this.refreshCategoryDropdown(this.data.categoryQuery);
} catch (e) {
wx.showToast({ title: e.message || '加载分类失败', icon: 'none' });
}
},
refreshCategoryDropdown(query) {
const q = String(query || '').trim();
const suggestions = filterCategoryOptions(q, this.data.categories, 30);
this.setData({
categoryQuery: query == null ? this.data.categoryQuery : query,
categorySuggestions: suggestions,
categoryCanCreate: Boolean(q) && !findCategoryOptionByName(q, this.data.categories),
});
},
onCategoryFocus() {
this.refreshCategoryDropdown(this.data.categoryQuery);
this.setData({ categoryDropdownOpen: true });
},
onCategoryInput(e) {
const value = e.detail.value;
const matched = findCategoryOptionByName(value, this.data.categories);
this.setData({
categoryQuery: value,
selectedCategory: matched || null,
categoryDropdownOpen: true,
});
this.refreshCategoryDropdown(value);
},
onCategoryBlur() {
setTimeout(() => this.setData({ categoryDropdownOpen: false }), 220);
},
pickCategory(e) {
const idx = Number(e.currentTarget.dataset.idx);
const row = this.data.categorySuggestions[idx];
if (!row) return;
this.setData({
selectedCategory: row,
categoryQuery: categoryLabel(row),
categoryCanCreate: false,
categoryDropdownOpen: false,
});
},
async createCategoryFromQuery() {
const name = String(this.data.categoryQuery || '').trim();
if (!name) return;
try {
wx.showLoading({ title: '创建分类' });
const row = await this.ensureCategoryByName(name);
this.setData({
selectedCategory: row,
categoryQuery: categoryLabel(row),
categoryCanCreate: false,
categoryDropdownOpen: false,
});
wx.showToast({ title: '分类已创建', icon: 'success' });
} catch (e) {
wx.showToast({ title: e.message || '创建分类失败', icon: 'none' });
} finally {
wx.hideLoading();
}
},
mergeCategory(row) {
const code = String(row.category_code || '');
const list = (this.data.categories || []).filter((c) => String(c.category_code) !== code);
list.unshift(row);
this.setData({ categories: list });
return row;
},
async ensureCategoryByName(name) {
const q = String(name || '').trim();
const existing = findCategoryOptionByName(q, this.data.categories);
if (existing && existing.category_code) return existing;
const res = await createStockInboundCategory(q);
const created = res.data || res || {};
const row = {
category_code: created.category_code,
category_name: created.category_name || created.label || q,
parent_code: created.parent_code || null,
label: created.label || created.category_name || q,
};
if (!row.category_code) throw new Error('无分类编码');
return this.mergeCategory(row);
},
onNameFocus() {
if (String(this.data.nameQuery || '').trim() || this.data.similar.length) {
this.setData({ dropdownOpen: true });
}
},
onNameQuery(e) {
const nameQuery = e.detail.value;
// 改品名 = 脱离原来那个商品:清档案字段与编辑标记,
// 否则会把上一个商品的人工改动回写到之后选中的另一个商品上。
this._archiveEdited = {};
this.setData({
nameQuery,
skuCode: '',
archiveSpec: '',
archiveBrand: '',
archiveOrigin: '',
archiveEditHint: '',
dropdownOpen: true,
...unitPickerPatch(''),
});
if (this._similarTimer) clearTimeout(this._similarTimer);
this._similarTimer = setTimeout(() => this.searchSimilarLive(nameQuery), 250);
},
async searchSimilarLive(name) {
const q = String(name || '').trim();
if (!q) {
this.setData({ similar: [], showCreateHint: false, searching: false, dropdownOpen: false });
return;
}
this.setData({ searching: true, dropdownOpen: true });
try {
const res = await fetchStockInboundSkuSimilar({ name: q });
const rows = res.data || res || [];
const list = Array.isArray(rows) ? rows : [];
const exact = list.some((r) => String(r.sku_name || '').trim() === q);
this.setData({
similar: list,
showCreateHint: !exact,
searching: false,
dropdownOpen: true,
});
} catch (e) {
this.setData({ similar: [], showCreateHint: true, searching: false, dropdownOpen: true });
}
},
onInboundUnitChange(e) {
const idx = Number(e.detail.value) || 0;
const options = this.data.unitOptions || [];
const unit = options[idx] || this.data.skuUnit;
this.setData({
unitIndex: idx,
skuUnit: unit,
newUnit: unit,
});
},
onQty(e) {
this.setData({ qty: e.detail.value });
},
onUnitCost(e) {
this.setData({ unitCost: e.detail.value });
},
onProd(e) {
this.setData({ productionDate: e.detail.value });
},
onNewName(e) {
this.setData({ newName: e.detail.value });
},
onNewSpec(e) {
this.setData({ newSpec: e.detail.value });
},
onNewBrand(e) {
this.setData({ newBrand: e.detail.value });
},
onNewUnit(e) {
this.setData({ newUnit: e.detail.value });
},
onNewOrigin(e) {
this.setData({ newOrigin: e.detail.value });
},
onArchiveSpec(e) {
this.markArchiveEdited('archiveSpec', e.detail.value);
},
onArchiveBrand(e) {
this.markArchiveEdited('archiveBrand', e.detail.value);
},
onArchiveOrigin(e) {
this.markArchiveEdited('archiveOrigin', e.detail.value);
},
/** 人工改动档案字段:记录字段名(提交时只回写被记录过的字段) */
markArchiveEdited(key, value) {
this._archiveEdited = Object.assign({}, this._archiveEdited, { [key]: true });
this.setData({ [key]: value === undefined ? '' : value }, () => this.refreshArchiveEditHint());
},
/** 表单值整体替换后刷新「未建档」提示(不生成编辑标记) */
refreshArchiveEditHint() {
const hint = hasUnsavedArchiveEdits(
{
archiveSpec: this.data.archiveSpec,
archiveBrand: this.data.archiveBrand,
archiveOrigin: this.data.archiveOrigin,
},
this._archiveEdited || {},
this.data.skuCode
)
? '该商品尚未建档,改动不会写入商品档案'
: '';
if (hint !== this.data.archiveEditHint) this.setData({ archiveEditHint: hint });
},
noop() {},
onCreateFromQuery() {
const name = String(this.data.nameQuery || '').trim();
this.setData({
newName: name || this.data.newName,
skuCode: '',
similar: [],
showCreateHint: false,
dropdownOpen: false,
createOpen: true,
categoryDropdownOpen: false,
});
},
closeCreate() {
this.setData({ createOpen: false });
},
chooseImageFromCamera() {
this.pickRecognizeImage(['camera']);
},
chooseImageFromAlbum() {
this.pickRecognizeImage(['album']);
},
pickRecognizeImage(sourceType) {
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType,
success: (res) => {
const filePath = (res.tempFilePaths || [])[0];
if (!filePath) return;
this.setData({ imagePreview: filePath, recognizing: true });
prepareOrderImageBase64(filePath)
.then((base64) => this.runRecognize(base64))
.catch(() => {
this.setData({ recognizing: false });
wx.showToast({ title: '读取图片失败', icon: 'none' });
});
},
});
},
clearRecognizePreview() {
this.setData({ imagePreview: '' });
},
async runRecognize(base64) {
this.setData({ recognizing: true });
try {
const res = await recognizeStockInboundCatalog({ image_base64: base64 });
const data = res.data || res || {};
const unique =
data.match === 'unique' && data.candidates && data.candidates[0]
? data.candidates[0]
: null;
const next = applyStockInboundSuggestion(
{
skuCode: this.data.skuCode,
skuName: this.data.nameQuery,
skuUnit: this.data.skuUnit,
qty: this.data.qty,
unitCost: this.data.unitCost,
productionDate: this.data.productionDate,
newName: this.data.newName,
newSpec: this.data.newSpec,
newBrand: this.data.newBrand,
newUnit: this.data.newUnit,
newOrigin: this.data.newOrigin,
archiveSpec: this.data.archiveSpec,
archiveBrand: this.data.archiveBrand,
archiveOrigin: this.data.archiveOrigin,
},
data.suggested,
unique
);
const patch = {
skuCode: next.skuCode,
nameQuery: next.skuName,
qty: next.qty,
unitCost: next.unitCost,
productionDate: next.productionDate,
newName: next.newName,
newSpec: next.newSpec,
newBrand: next.newBrand,
newOrigin: next.newOrigin,
archiveSpec: next.archiveSpec,
archiveBrand: next.archiveBrand,
archiveOrigin: next.archiveOrigin,
recognizing: false,
dropdownOpen: false,
createOpen: false,
...unitPickerPatch(next.skuUnit || next.newUnit || unique?.unit || ''),
};
// 识别回填不是人工编辑:清掉编辑标记,避免把识别值当人工值回写档案
this._archiveEdited = {};
if (data.match === 'multi' && Array.isArray(data.candidates)) {
patch.similar = data.candidates.map((c) => ({
sku_code: c.sku_code,
sku_name: c.item_name,
spec: c.spec || '',
brand: c.brand || '',
origin: c.origin || '',
unit: c.unit || '',
quote_cost: c.quote_cost,
}));
patch.dropdownOpen = true;
patch.showCreateHint = true;
} else if (data.match === 'none') {
patch.createOpen = true;
patch.showCreateHint = false;
}
this.setData(patch, () => this.refreshArchiveEditHint());
wx.showToast({
title:
data.match === 'none'
? data.message || '未命中,请补全后新建'
: data.message || '已回填识别结果',
icon: 'none',
});
} catch (e) {
this.setData({ recognizing: false });
wx.showToast({ title: e.message || '识别失败', icon: 'none' });
}
},
onPickSimilar(e) {
const idx = Number(e.currentTarget.dataset.idx);
const row = this.data.similar[idx];
if (!row) return;
const quote = Number(row.quote_cost);
const patch = {
skuCode: row.sku_code,
nameQuery: row.sku_name,
similar: [],
showCreateHint: false,
dropdownOpen: false,
// 选中商品后,把该商品档案里已有的规格/品牌/厂家显示出来(可供人工修正后回写)
archiveSpec: row.spec || '',
archiveBrand: row.brand || '',
archiveOrigin: row.origin || '',
...unitPickerPatch(row.unit),
};
if (!(Number(this.data.unitCost) > 0) && quote > 0) {
patch.unitCost = String(quote);
}
// 换商品即换档案:清掉上一个商品的人工编辑标记,避免把 A 的改动写到 B 的档案上
this._archiveEdited = {};
this.setData(patch, () => this.refreshArchiveEditHint());
},
async onCreateProduct() {
const name = String(this.data.newName || '').trim();
const spec = String(this.data.newSpec || '').trim();
const categoryName = String(this.data.categoryQuery || '').trim();
if (!categoryName || !name || !spec) {
wx.showToast({ title: '分类/品名/规格必填', icon: 'none' });
return;
}
try {
wx.showLoading({ title: '建品中' });
const cat = this.data.selectedCategory && this.data.selectedCategory.category_code
? this.data.selectedCategory
: await this.ensureCategoryByName(categoryName);
this.setData({
selectedCategory: cat,
categoryQuery: categoryLabel(cat),
});
const res = await createStockInboundProduct({
name,
parent_code: cat.category_code,
spec,
brand: this.data.newBrand,
unit: this.data.skuUnit || this.data.newUnit,
origin: this.data.newOrigin,
stock_mode: 'inventory',
});
const data = res.data || res || {};
const code = data.skuCode || data.sku_code;
if (!code) throw new Error('无商品编码');
this.setData({
skuCode: code,
nameQuery: name,
createOpen: false,
// 新建时规格/品牌/厂家已随建品落库,表单显示建品用的值;
// 清掉编辑标记(这些值已经写进档案了,不需要再走一次回写)
archiveSpec: spec,
archiveBrand: this.data.newBrand || '',
archiveOrigin: this.data.newOrigin || '',
archiveEditHint: '',
...unitPickerPatch(this.data.skuUnit || this.data.newUnit),
});
this._archiveEdited = {};
wx.showToast({ title: '已建品', icon: 'success' });
} catch (e) {
wx.showToast({ title: e.message || '建品失败', icon: 'none' });
} finally {
wx.hideLoading();
}
},
async onSubmit() {
const sku = String(this.data.skuCode || '').trim();
const qty = Number(this.data.qty);
const cost = Number(this.data.unitCost);
if (!sku) {
wx.showToast({ title: '请选择或新建商品', icon: 'none' });
return;
}
if (!(qty > 0)) {
wx.showToast({ title: '数量须大于 0', icon: 'none' });
return;
}
if (!(cost > 0)) {
wx.showToast({ title: '成本价须大于 0', icon: 'none' });
return;
}
try {
wx.showLoading({ title: '入库中' });
// 只把人工改过的档案字段上报;没改过就不传 archive(服务端随即不写档案)
const archive = buildArchivePayload(
{
archiveSpec: this.data.archiveSpec,
archiveBrand: this.data.archiveBrand,
archiveOrigin: this.data.archiveOrigin,
},
this._archiveEdited || {}
);
await submitStockInbound({
sku_code: sku,
qty,
unit: this.data.skuUnit || undefined,
unit_cost: cost,
production_date: this.data.productionDate || undefined,
remark: '独立入库(小程序)',
pending: true,
...(archive ? { archive } : {}),
});
wx.showToast({ title: '已提交,待验收入库', icon: 'none' });
this._archiveEdited = {};
this.setData({ qty: '', unitCost: '', archiveEditHint: '' });
} catch (e) {
wx.showToast({ title: e.message || '入库失败', icon: 'none' });
} finally {
wx.hideLoading();
}
},
},
});