Files
Ubuntu 4e0cf2e217
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
fix(小程序): 商城面板与商品溯源模块顺序对齐配送系统
2026-10-28 21:38:19 +08:00

399 lines
13 KiB
JavaScript
Raw Permalink 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 {
fetchMallBootstrap,
fetchMallProducts,
submitMallOrder,
saveMallAddress,
} = require('../../utils/request');
const { resolveSkuImageUrl } = require('../../utils/skuImage');
const { PROCESSING_METHOD_OPTIONS } = require('../../utils/constants');
function money(value) {
return (Math.round((Number(value) || 0) * 100) / 100).toFixed(2);
}
/** 统一在这里格式化:避免 WXML 里拼 null/单位、价格小数位不一致。 */
function decorateProduct(item, qty) {
const price = Number(item.price) || 0;
const hasPrice = item.has_price === true || price > 0;
const spec = String(item.spec || '').trim();
// 单位已在价格后缀(/斤)展示,这里只留规格,避免同名信息占两行(2026-10-30)。
const metaText = spec;
return {
...item,
price,
has_price: hasPrice,
price_text: hasPrice ? `¥${money(price)}` : '待报价',
meta_text: metaText,
image_src: resolveSkuImageUrl(item.image_url, item.sku_code),
qty,
// 下单弹层默认选中该客户商品库配置的加工方式(客户可改);加工方由后台决定。
processing_method: String(item.processing_method || '').trim() || '原材料',
};
}
Component({
options: {
addGlobalClass: true,
},
properties: {
embedded: {
type: Boolean,
value: false,
},
},
data: {
loading: true,
error: '',
customer: {},
// 收货地址:客户可直接编辑;失焦/下单前保存(服务端解析坐标并回写客户档案)
deliveryAddress: '',
savedAddress: '',
addressSaving: false,
deliveryDate: '',
dateMin: '',
dateMax: '',
query: '',
categoryFilter: '',
categories: [],
products: [],
// 加工方式选项(客户只选方式,仓内/供应商加工由管理员配置决定)
processingMethods: PROCESSING_METHOD_OPTIONS,
// sku_code → { sku_code, name, unit, price, quantity };与商品列表筛选解耦,
// 搜索/切分类重载商品时不丢已选数量。
cart: {},
cartCount: 0,
cartTotal: '0.00',
checkoutVisible: false,
checkoutItems: [],
submitting: false,
remark: '',
},
lifetimes: {
attached() {
this.bootstrap();
},
},
methods: {
async bootstrap() {
await this.loadBootstrap();
if (!this.data.error) await this.loadProducts();
},
async loadBootstrap() {
try {
const data = (await fetchMallBootstrap()) || {};
const defaultAddress = String(data.default_address || '').trim();
this.setData({
loading: false,
error: '',
customer: data.customer || {},
deliveryAddress: defaultAddress,
savedAddress: defaultAddress,
deliveryDate: String(data.delivery_date_min || ''),
dateMin: String(data.delivery_date_min || ''),
dateMax: String(data.delivery_date_max || ''),
});
} catch (err) {
this.setData({
loading: false,
error: (err && err.message) || '加载失败',
});
}
},
async loadProducts() {
try {
// 空筛选不能传 undefined:wx.request 会把它序列化成字面量 "undefined",
// 服务端按关键词过滤后就会变成「暂无商品」。
const params = {};
if (this.data.query) params.q = this.data.query;
if (this.data.categoryFilter) params.category_code = this.data.categoryFilter;
const data = (await fetchMallProducts(params)) || {};
const products = (Array.isArray(data.products) ? data.products : []).map((item) =>
decorateProduct(item, Number((this.data.cart || {})[item.sku_code]?.quantity) || 0)
);
const cart = { ...(this.data.cart || {}) };
products.forEach((item) => {
if (!cart[item.sku_code]) return;
cart[item.sku_code] = {
...cart[item.sku_code],
name: item.name,
unit: item.unit,
price: Number(item.price) || 0,
};
});
this.setData(
{
products,
categories: Array.isArray(data.categories) ? data.categories : [],
cart,
},
() => this.recalc()
);
} catch (err) {
this.setData({ error: (err && err.message) || '加载失败' });
}
},
recalc() {
let cartCount = 0;
let cartTotal = 0;
Object.values(this.data.cart || {}).forEach((item) => {
const qty = Number(item.quantity) || 0;
if (qty <= 0) return;
cartCount += qty;
cartTotal += qty * (Number(item.price) || 0);
});
this.setData({ cartCount, cartTotal: money(cartTotal) });
},
onCardTap(e) {
const index = Number(e.currentTarget.dataset.index);
const product = this.data.products[index];
if (!product) return;
if (!product.has_price) {
wx.showToast({ title: '待报价', icon: 'none' });
return;
}
this.onQtyPlus(e);
},
onQtyPlus(e) {
const index = Number(e.currentTarget.dataset.index);
const product = this.data.products[index];
if (!product || !product.has_price) return;
const quantity = (Number(product.qty) || 0) + 1;
const cart = { ...(this.data.cart || {}) };
cart[product.sku_code] = {
sku_code: product.sku_code,
name: product.name,
unit: product.unit,
price: Number(product.price) || 0,
processing_method:
(cart[product.sku_code] || {}).processing_method ||
product.processing_method ||
'原材料',
remark: (cart[product.sku_code] || {}).remark || '',
quantity,
};
this.setData(
{ cart, [`products[${index}].qty`]: quantity },
() => this.recalc()
);
},
onQtyMinus(e) {
const index = Number(e.currentTarget.dataset.index);
const product = this.data.products[index];
if (!product) return;
const quantity = Math.max(0, (Number(product.qty) || 0) - 1);
const cart = { ...(this.data.cart || {}) };
if (quantity > 0) {
cart[product.sku_code] = { ...(cart[product.sku_code] || {}), quantity };
} else {
delete cart[product.sku_code];
}
this.setData(
{ cart, [`products[${index}].qty`]: quantity },
() => this.recalc()
);
},
onQueryInput(e) {
const query = String((e && e.detail && e.detail.value) || '');
this.setData({ query });
if (this._queryTimer) clearTimeout(this._queryTimer);
this._queryTimer = setTimeout(() => {
this._queryTimer = null;
this.loadProducts();
}, 400);
},
onCategoryTap(e) {
const code = String(e.currentTarget.dataset.code || '').trim();
if (code === this.data.categoryFilter) return;
this.setData({ categoryFilter: code }, () => this.loadProducts());
},
onDeliveryDateChange(e) {
this.setData({ deliveryDate: String((e && e.detail && e.detail.value) || '') });
},
onAddressInput(e) {
this.setData({
deliveryAddress: String((e && e.detail && e.detail.value) || '').slice(0, 200),
});
},
/** 地址保存到客户档案(服务端必须能解析出坐标,否则返回 400) */
async saveAddress() {
const address = String(this.data.deliveryAddress || '').trim();
if (!address) {
wx.showToast({ title: '请填写收货地址', icon: 'none' });
return false;
}
if (address === this.data.savedAddress) return true;
if (this._addressSavePromise) return this._addressSavePromise;
this.setData({ addressSaving: true });
this._addressSavePromise = (async () => {
try {
const data = (await saveMallAddress(address)) || {};
const saved = String(data.address || address).trim();
this.setData({ deliveryAddress: saved, savedAddress: saved });
return true;
} catch (err) {
wx.showToast({
title: (err && err.message) || '地址保存失败',
icon: 'none',
duration: 2500,
});
return false;
} finally {
this.setData({ addressSaving: false });
this._addressSavePromise = null;
}
})();
return this._addressSavePromise;
},
onAddressBlur() {
if (String(this.data.deliveryAddress || '').trim() !== this.data.savedAddress) {
void this.saveAddress();
}
},
/** 写入加工方式:列表点选或手输自定义均可。 */
writeItemMethod(index, method) {
const checkoutItem = this.data.checkoutItems[index];
if (!checkoutItem) return;
const cart = { ...(this.data.cart || {}) };
if (cart[checkoutItem.sku_code]) {
cart[checkoutItem.sku_code] = {
...cart[checkoutItem.sku_code],
processing_method: method,
};
}
this.setData({
cart,
[`checkoutItems[${index}].processing_method`]: method,
[`checkoutItems[${index}].methodIndex`]: Math.max(
0,
this.data.processingMethods.indexOf(method)
),
});
},
onItemMethodInput(e) {
const index = Number(e.currentTarget.dataset.index);
this.writeItemMethod(index, String((e.detail && e.detail.value) || '').slice(0, 50));
},
onItemMethodBlur(e) {
const index = Number(e.currentTarget.dataset.index);
const method = String((e.detail && e.detail.value) || '').trim().slice(0, 50) || '原材料';
this.writeItemMethod(index, method);
},
onItemMethodChange(e) {
const index = Number(e.currentTarget.dataset.index);
const pickIndex = Number(e.detail && e.detail.value) || 0;
this.writeItemMethod(index, this.data.processingMethods[pickIndex] || '原材料');
},
/** 逐行备注 */
onItemRemarkInput(e) {
const index = Number(e.currentTarget.dataset.index);
const remark = String((e.detail && e.detail.value) || '').slice(0, 200);
const checkoutItem = this.data.checkoutItems[index];
if (!checkoutItem) return;
const cart = { ...(this.data.cart || {}) };
if (cart[checkoutItem.sku_code]) {
cart[checkoutItem.sku_code] = { ...cart[checkoutItem.sku_code], remark };
}
this.setData({ cart, [`checkoutItems[${index}].remark`]: remark });
},
onRemarkInput(e) {
this.setData({ remark: String((e && e.detail && e.detail.value) || '') });
},
openCheckout() {
if (!this.data.cartCount || this.data.submitting) return;
const checkoutItems = Object.values(this.data.cart || {})
.filter((item) => Number(item.quantity) > 0)
.map((item) => {
const method = item.processing_method || '原材料';
return {
...item,
processing_method: method,
methodIndex: Math.max(0, this.data.processingMethods.indexOf(method)),
remark: item.remark || '',
amount: money((Number(item.quantity) || 0) * (Number(item.price) || 0)),
};
});
this.setData({
checkoutVisible: true,
checkoutItems,
});
},
closeCheckout() {
if (this.data.submitting) return;
this.setData({ checkoutVisible: false });
},
noop() {},
async submitOrder() {
if (this.data.submitting) return;
const items = Object.values(this.data.cart || {})
.filter((item) => Number(item.quantity) > 0)
.map((item) => ({
sku_code: item.sku_code,
quantity: Number(item.quantity),
processing_method: item.processing_method || '原材料',
remark: item.remark || '',
}));
if (!items.length) {
this.setData({ checkoutVisible: false });
return;
}
// 地址改过就先保存(服务端解析坐标并回写客户档案);失败则不下单
const addressOk = await this.saveAddress();
if (!addressOk) return;
this.setData({ submitting: true });
try {
await submitMallOrder({
items,
delivery_date: this.data.deliveryDate,
delivery_address: String(this.data.deliveryAddress || '').trim(),
remark: this.data.remark,
});
this.setData({
checkoutVisible: false,
submitting: false,
remark: '',
cart: {},
checkoutItems: [],
products: this.data.products.map((item) => ({ ...item, qty: 0 })),
cartCount: 0,
cartTotal: '0.00',
});
wx.showToast({ title: '下单成功', icon: 'success' });
} catch (err) {
this.setData({ submitting: false });
wx.showToast({
title: (err && err.message) || '下单失败',
icon: 'none',
duration: 2500,
});
}
},
},
});