Files
SupplierSystem/miniprogram/pages/order-detail/order-detail.js
T
Ubuntu deb3e72750
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: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

399 lines
12 KiB
JavaScript

const {
fetchOrderEntryDetail,
updateOrderEntryOrder,
fetchOrderCategories,
createOrderCategory,
} = require('../../utils/request');
const { getSession } = require('../../utils/auth');
const { requireMobileRole } = require('../../utils/roleGuard');
const { PROCESSING_METHOD_OPTIONS, ORDER_STATUS_LABELS } = require('../../utils/constants');
const {
buildCategorySummary,
buildItemGroupsByLevel1,
buildCategoryPickerOptions,
buildCategoryPickerLabels,
enrichItemsCategoryFields,
applyManualCategory,
validateItemsCategories,
mappingStatusText,
} = require('../../utils/orderCategory');
const { goHome: navigateHome } = require('../../utils/nav');
function normalizeItem(item) {
const qty = Number(item.quantity) || 0;
const price = Number(item.price) || 0;
const amount = Math.round((Number(item.amount) || qty * price) * 100) / 100;
return {
...item,
quantity: item.quantity,
price: item.price,
amount,
amountText: amount.toFixed(2),
category_name: item.category_name || '',
category_manually_set: Boolean(item.category_manually_set || item.category_code),
library_category_code: item.library_category_code || item.category_code || '',
mapping_status: mappingStatusText(item),
};
}
function normalizeItems(items) {
return (items || []).map(normalizeItem);
}
function decorateItemGroups(groups) {
let rowNo = 0;
return (groups || []).map((group) => {
const items = (group.items || []).map((item) => {
rowNo += 1;
return { ...item, _rowNo: rowNo };
});
const amount = items.reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
return {
...group,
items,
amountText: amount.toFixed(2),
};
});
}
function estimateTotal(items) {
return items.reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
}
const ADD_CATEGORY_LABEL = '新增分类';
function pickerLabelsWithAdd(options) {
return [...buildCategoryPickerLabels(options), ADD_CATEGORY_LABEL];
}
Page({
data: {
orderCode: '',
order: {},
items: [],
editable: false,
loading: true,
saving: false,
error: '',
statusLabel: '',
totalText: '0.00',
processingMethods: PROCESSING_METHOD_OPTIONS,
categoryOptions: [{ category_code: '', category_name: '未分类', label: '未分类' }],
categoryPickerLabels: ['未分类', '新增分类'],
showQuickCategoryModal: false,
quickCategoryTargetIndex: -1,
quickCategoryName: '',
creatingCategory: false,
showItemEditModal: false,
itemEditIndex: -1,
itemEditName: '',
itemEditQty: '',
itemEditUnit: '',
itemEditPrice: '',
itemEditAmount: '0.00',
itemEditFocus: '',
categoryColumns: [],
categorySummaryTotalCount: 0,
categorySummaryTotalAmount: '0.00',
itemGroups: [],
},
onLoad(options) {
const orderCode = String(options.orderCode || '').trim();
if (!orderCode) {
this.setData({ loading: false, error: '缺少订单号' });
return;
}
this.setData({ orderCode });
},
onShow() {
if (!requireMobileRole('order_entry')) return;
this.loadCategories();
if (this.data.orderCode) {
this.loadOrder(this.data.orderCode);
}
},
refreshView(order, items, editable) {
const categoryOptions = this.data.categoryOptions;
const enriched = normalizeItems(enrichItemsCategoryFields(items, categoryOptions));
const summary = buildCategorySummary(enriched, categoryOptions);
const itemGroups = decorateItemGroups(buildItemGroupsByLevel1(enriched, categoryOptions));
this.setData({
order,
items: enriched,
itemGroups,
editable: Boolean(editable),
statusLabel: ORDER_STATUS_LABELS[Number(order.order_status)] || `状态${order.order_status}`,
totalText: estimateTotal(enriched).toFixed(2),
categoryColumns: summary.categoryColumns,
categorySummaryTotalCount: summary.totalCount,
categorySummaryTotalAmount: summary.totalAmountText,
loading: false,
error: '',
});
},
async loadCategories() {
try {
const result = await fetchOrderCategories();
const categoryOptions = buildCategoryPickerOptions(result.data || []);
this.setData({
categoryOptions,
categoryPickerLabels: pickerLabelsWithAdd(categoryOptions),
});
if (this.data.items.length) {
this.refreshView(this.data.order, this.data.items, this.data.editable);
}
} catch (err) {
console.warn('loadCategories failed', err);
}
},
async loadOrder(orderCode) {
this.setData({ loading: true, error: '' });
try {
const result = await fetchOrderEntryDetail(orderCode);
const payload = result.data || {};
this.refreshView(payload, payload.items || [], payload.editable);
} catch (err) {
this.setData({
loading: false,
error: err.message || '加载订单失败',
});
}
},
openItemEdit(e) {
const index = Number(e.currentTarget.dataset.index);
const field = e.currentTarget.dataset.field || 'name';
const item = this.data.items[index];
if (!item) return;
const qty = Number(item.quantity) || 0;
const price = Number(item.price) || 0;
this.setData({
showItemEditModal: true,
itemEditIndex: index,
itemEditName: item.item_name || '',
itemEditQty: item.quantity == null ? '' : String(item.quantity),
itemEditUnit: item.unit || '',
itemEditPrice: item.price == null ? '' : String(item.price),
itemEditAmount: (qty * price || Number(item.amount) || 0).toFixed(2),
itemEditFocus: '',
});
if (!this.data.editable) return;
setTimeout(() => {
this.setData({ itemEditFocus: field });
}, 250);
},
closeItemEditModal() {
this.setData({
showItemEditModal: false,
itemEditIndex: -1,
itemEditName: '',
itemEditQty: '',
itemEditUnit: '',
itemEditPrice: '',
itemEditAmount: '0.00',
itemEditFocus: '',
});
},
stopModalTap() {},
onItemEditField(e) {
const field = e.currentTarget.dataset.field;
const value = typeof e.detail === 'string' ? e.detail : (e.detail && e.detail.value) || '';
const patch = { [field]: value };
const qty = Number(field === 'itemEditQty' ? value : this.data.itemEditQty) || 0;
const price = Number(field === 'itemEditPrice' ? value : this.data.itemEditPrice) || 0;
patch.itemEditAmount = (qty * price).toFixed(2);
this.setData(patch);
},
onItemEditBlur() {
if (this.data.itemEditFocus) {
this.setData({ itemEditFocus: '' });
}
},
submitItemEdit() {
if (!this.data.editable) {
this.closeItemEditModal();
return;
}
const index = this.data.itemEditIndex;
if (index < 0) {
this.closeItemEditModal();
return;
}
const name = String(this.data.itemEditName || '').trim();
const unit = String(this.data.itemEditUnit || '').trim() || '斤';
const qtyValue = this.data.itemEditQty;
const priceValue = this.data.itemEditPrice;
const items = normalizeItems(this.data.items.map((item, idx) => {
if (idx !== index) return item;
const qty = Number(qtyValue) || 0;
const price = Number(priceValue) || 0;
return {
...item,
item_name: name,
quantity: qtyValue,
unit,
price: priceValue,
amount: Math.round(qty * price * 100) / 100,
};
}));
this.closeItemEditModal();
this.refreshView(this.data.order, items, this.data.editable);
},
onCategoryPick(e) {
if (!this.data.editable) return;
const index = Number(e.currentTarget.dataset.index);
const pickIndex = Number(e.detail.value);
const labels = this.data.categoryPickerLabels || [];
if (labels[pickIndex] === ADD_CATEGORY_LABEL) {
this.openQuickCategory({ currentTarget: { dataset: { index } } });
return;
}
const option = this.data.categoryOptions[pickIndex] || this.data.categoryOptions[0];
const items = normalizeItems(this.data.items.map((item, idx) => (
idx === index ? applyManualCategory(item, option) : item
)));
this.refreshView(this.data.order, items, this.data.editable);
},
openQuickCategory(e) {
if (!this.data.editable) return;
const index = Number(e.currentTarget.dataset.index);
this.setData({
showQuickCategoryModal: true,
quickCategoryTargetIndex: index,
quickCategoryName: '',
});
},
closeQuickCategoryModal() {
if (this.data.creatingCategory) return;
this.setData({ showQuickCategoryModal: false, quickCategoryTargetIndex: -1, quickCategoryName: '' });
},
onQuickCategoryNameInput(e) {
this.setData({ quickCategoryName: e.detail.value });
},
async submitQuickCategory() {
const name = String(this.data.quickCategoryName || '').trim();
if (!name) {
wx.showToast({ title: '请输入分类名称', icon: 'none' });
return;
}
this.setData({ creatingCategory: true });
try {
const result = await createOrderCategory(name);
const created = result.data || {};
const categoryOptions = buildCategoryPickerOptions([
...(this.data.categoryOptions || []).filter((item) => item.category_code),
created,
]);
const targetIndex = this.data.quickCategoryTargetIndex;
let items = this.data.items;
if (targetIndex >= 0) {
items = normalizeItems(items.map((item, idx) => (
idx === targetIndex ? applyManualCategory(item, created) : item
)));
}
this.setData({
categoryOptions,
categoryPickerLabels: pickerLabelsWithAdd(categoryOptions),
items,
showQuickCategoryModal: false,
quickCategoryTargetIndex: -1,
quickCategoryName: '',
});
this.refreshView(this.data.order, items, this.data.editable);
wx.showToast({ title: '分类已创建', icon: 'success' });
} catch (err) {
wx.showToast({ title: err.message || '创建失败', icon: 'none' });
} finally {
this.setData({ creatingCategory: false });
}
},
onProcessingMethodPick(e) {
if (!this.data.editable) return;
const index = Number(e.currentTarget.dataset.index);
const method = this.data.processingMethods[Number(e.detail.value)] || '原材料';
const items = normalizeItems(this.data.items.map((item, idx) => (
idx === index ? { ...item, processing_method: method } : item
)));
this.refreshView(this.data.order, items, this.data.editable);
},
async saveAdjustments() {
if (!this.data.editable) return;
const categoryError = validateItemsCategories(this.data.items);
if (categoryError) {
wx.showToast({ title: categoryError, icon: 'none' });
return;
}
this.setData({ saving: true });
try {
const payload = {
items: this.data.items.map((item) => ({
id: item.id,
item_name: String(item.item_name || '').trim(),
quantity: Number(item.quantity) || 0,
unit: item.unit || '斤',
price: Number(item.price) || 0,
amount: Number(item.amount) || 0,
processing_method: item.processing_method || '原材料',
sku_code: item.sku_code || undefined,
category_code: item.category_code || undefined,
category_name: item.category_name || undefined,
category_manually_set: Boolean(item.category_manually_set || item.category_code),
library_category_code: item.library_category_code || item.category_code || undefined,
})),
};
const result = await updateOrderEntryOrder(this.data.orderCode, payload);
const data = result.data || {};
this.refreshView(
{ ...this.data.order, ...data },
data.items || this.data.items,
data.editable
);
wx.showToast({ title: '已保存并同步映射库', icon: 'success' });
} catch (err) {
wx.showToast({ title: err.message || '保存失败', icon: 'none' });
} finally {
this.setData({ saving: false });
}
},
continueEntry() {
const pages = getCurrentPages() || [];
const homeIndex = pages.findIndex((page) => page.route === 'pages/home/home');
const homeUrl = '/pages/home/home?module=order-entry';
if (homeIndex >= 0) {
const home = pages[homeIndex];
if (home) home._pendingHomeModuleId = 'order-entry';
const delta = pages.length - 1 - homeIndex;
if (delta > 0) {
wx.navigateBack({
delta,
fail: () => wx.reLaunch({ url: homeUrl }),
});
return;
}
}
wx.reLaunch({ url: homeUrl });
},
goHome() {
navigateHome();
},
});