feat(客户商城): 下单客户账号与小程序商城二期

正常客户开户/停用/重置;order_customer 三重闸;mall-panel 商品、地址、下单;价格/客户由服务端推导;菜单与账户入口修复。
This commit is contained in:
Ubuntu
2026-10-28 21:06:36 +08:00
parent 64c5230aa8
commit b8bbf21599
30 changed files with 2481 additions and 25 deletions
@@ -0,0 +1,87 @@
# 客户自助商城(二期)— 下单客户与小程序商城
- 日期:2026-10-30
- 参考:配送系统 `docs/design/20261028-customer-order-mall.md`、`customerOrderAccountService.ts`、`customerMallService.ts`、`miniprogram/components/mall-panel/`
- 状态:本地实现,未部署
## 1. 范围
1. 客户列表开通「下单客户」账号;
2. 小程序登录后进入「客户商城」,只展示该客户自己的 `customer_skus` 商品;
3. 选品、购物车、确认下单,复用既有录单/下单链路;
4. 账号停用/启用/重置密码。
**不在一期**:我的订单、售后、优惠券、二级页面。
## 2. 客户范围(硬性)
只有**正常客户**可开通账号,以下一律排除:
- `__RETAIL__`(散客录单);
- `__INDEPENDENT_INBOUND__`(独立进货);
- `source IN ('retail','independent_inbound','main_system')`;
- `customer_code LIKE 'MAIN\\_%'`(配送系统分配过来的客户);
- 客户状态非正常(沿用供应商可交易状态)。
服务端开户/账号列表/登录/商城四个入口都必须同一判据,不能只在前端隐藏按钮。
## 3. 身份与登录
- 角色:`order_customer`(下单客户),无 Web 业务权限码;
- 绑定表:复用 `customer_portal_users`,新增 `status int default 1`、`created_by uuid`、`updated_at timestamptz`;
- 登录三重闸:
1. `customer_portal_users` 有绑定行;
2. 绑定行 `status=1`;
3. `public.user_roles` 有 `order_customer`。
- 登录:手机号/登录名 + 密码;微信手机号快速登录可选;首次登录改密;
- 复用 `auth.users + profiles + user_roles + customer_portal_users` 同事务开户;
- 初始化密码:手机号后 6 位,否则 `123456`;开户返回默认密码供管理员转交;
- 历史绑定无 `order_customer` 角色 → 不自动升级;显式开户时补授角色;
- 停用/重置密码只作用于持有 `order_customer` 的行;
- 登录名/手机号冲突规则沿用供应商开户。
## 4. Web 客户列表
- 正常客户行操作菜单增加「开通登录账号」;
- 已开通显示账号状态;
- 弹窗收集手机号(可选)和登录账号(无手机号必填),可设初始密码;
- 账号管理:停用/启用、重置密码;
- 接口:
- POST `/customers/:customerCode/login-account`
- GET `/customers/login-accounts?codes=...`
- PATCH `/customers/login-accounts/:userId/status`
- POST `/customers/login-accounts/:userId/reset-password`
## 5. 小程序商城
参考 `miniprogram/components/mall-panel/`:
- 首页内嵌 `mall-panel`,不新增二级页面;
- 商品来自该客户 `customer_skus`,只返回 `is_listed=true` 且有价商品;
- 价格复用 `enrichOrderItemsWithPrices`,与录单同源;
- 双列商品卡、搜索、分类 chips、加购/减购、购物车悬浮条;
- 确认弹层:商品清单、逐行加工方式/备注、收货地址、配送日、整单备注;
- 下单接口不接受 `customer_code/branch_code/price/processing_owner`,由登录账号和客户档案推导;
- 复用 `submitMobileCustomerOrder` 的建单/分配/分拣/配送/成本链路;
- 配送日 `[明天, 明天+6]`,默认明天;
- 地址可编辑并保存,服务端未配置地理编码 key 时保存失败但已存地址可下单。
## 6. 接口(移动端)
| 方法 | 路径 |
|---|---|
| GET | `/mobile/mall/bootstrap` |
| GET | `/mobile/mall/products?q=&category_code=` |
| PUT | `/mobile/mall/address` |
| POST | `/mobile/mall/orders` |
## 7. 验收
1. 正常客户可开户;散客/独立进货/主系统客户服务端拒绝;
2. 账号可登录小程序,错误密码/停用/无角色拒绝;
3. 商城只显示自己的 `customer_skus`,不含其他客户/未上架/无价商品;
4. 下单后订单进入现有录单/分配链路,客户归属正确;
5. 价格与录单同源;
6. 客户端不能通过请求体越权指定 customer/branch/price;
7. 客户列表账号管理可用;
8. typecheck + 服务层/接口测试;不部署。
@@ -0,0 +1,24 @@
-- 2026-10-30:客户自助商城二期:复用 customer_portal_users,新增状态/创建人/更新时间,
-- 并登记 order_customer 角色(不新增账号表)。
DO $$
DECLARE
sch text;
BEGIN
FOR sch IN
SELECT nspname FROM pg_namespace
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
LOOP
IF EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = sch AND table_name = 'customer_portal_users'
) THEN
EXECUTE format('ALTER TABLE %I.customer_portal_users ADD COLUMN IF NOT EXISTS status INT NOT NULL DEFAULT 1', sch);
EXECUTE format('ALTER TABLE %I.customer_portal_users ADD COLUMN IF NOT EXISTS created_by UUID', sch);
EXECUTE format('ALTER TABLE %I.customer_portal_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ', sch);
END IF;
END LOOP;
END $$;
INSERT INTO public.role_definitions (role_code, role_name, is_builtin, sort_order)
VALUES ('order_customer', '下单客户', true, 900)
ON CONFLICT (role_code) DO NOTHING;
+381
View File
@@ -0,0 +1,381 @@
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();
}
},
/** 逐行加工方式(只改方式;仓内/供应商加工由管理员配置) */
onItemMethodChange(e) {
const index = Number(e.currentTarget.dataset.index);
const pickIndex = Number(e.detail && e.detail.value) || 0;
const method = this.data.processingMethods[pickIndex] || '原材料';
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`]: 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,
});
}
},
},
});
@@ -0,0 +1,6 @@
{
"component": true,
"usingComponents": {
"van-icon": "@vant/weapp/icon/index"
}
}
@@ -0,0 +1,139 @@
<view class="mall-panel {{embedded ? 'is-embedded' : ''}}">
<view wx:if="{{loading}}" class="mall-state">加载中...</view>
<view wx:elif="{{error}}" class="mall-state">{{error}}</view>
<block wx:else>
<view class="mall-search">
<input
class="mall-search-input"
value="{{query}}"
placeholder="搜索商品"
confirm-type="search"
bindinput="onQueryInput"
/>
</view>
<scroll-view class="mall-cats" scroll-x enhanced show-scrollbar="{{false}}">
<view class="mall-cat {{categoryFilter === '' ? 'is-active' : ''}}" data-code="" bindtap="onCategoryTap">全部</view>
<view
wx:for="{{categories}}"
wx:key="code"
class="mall-cat {{categoryFilter === item.code ? 'is-active' : ''}}"
data-code="{{item.code}}"
bindtap="onCategoryTap"
>{{item.name}}</view>
</scroll-view>
<view class="mall-grid">
<view
wx:for="{{products}}"
wx:key="sku_code"
class="mall-card"
data-index="{{index}}"
bindtap="onCardTap"
>
<view class="mall-thumb-wrap">
<image wx:if="{{item.image_src}}" class="mall-thumb" src="{{item.image_src}}" mode="aspectFill" />
<view wx:else class="mall-thumb mall-thumb--empty"></view>
<view wx:if="{{item.qty > 0}}" class="mall-card-badge">{{item.qty}}</view>
</view>
<view class="mall-name">{{item.name}}</view>
<view wx:if="{{item.meta_text}}" class="mall-meta">{{item.meta_text}}</view>
<view wx:if="{{item.description}}" class="mall-desc">{{item.description}}</view>
<view class="mall-card-foot">
<view class="mall-price {{item.has_price ? '' : 'is-missing'}}">{{item.price_text}}<text wx:if="{{item.has_price && item.unit}}" class="mall-price-unit">/{{item.unit}}</text></view>
<view class="mall-step">
<view wx:if="{{item.qty > 0}}" class="mall-step-btn" data-index="{{index}}" catchtap="onQtyMinus">−</view>
<view wx:if="{{item.qty > 0}}" class="mall-step-qty" catchtap="noop">{{item.qty}}</view>
<!-- 加号常显:无价时置灰,点一下提示「待报价」(不再直接消失) -->
<view
class="mall-step-btn mall-step-btn--add {{item.has_price ? '' : 'is-disabled'}}"
data-index="{{index}}"
catchtap="onCardTap"
>+</view>
</view>
</view>
</view>
<view wx:if="{{!products.length}}" class="mall-state mall-state--empty">暂无商品</view>
</view>
<root-portal enable="{{true}}">
<!-- 购物车条常显:空购物车也保留图标,避免用户找不到入口 -->
<view class="mall-bar">
<view class="mall-bar-left">
<van-icon name="cart-o" size="22px" color="#ffffff" />
<view class="mall-bar-badge">{{cartCount}}</view>
<view class="mall-bar-total">合计 ¥{{cartTotal}}</view>
</view>
<view class="mall-bar-btn {{cartCount > 0 ? '' : 'is-disabled'}}" bindtap="openCheckout">去下单</view>
</view>
</root-portal>
<root-portal enable="{{true}}">
<view wx:if="{{checkoutVisible}}" class="mall-mask" catchtouchmove="noop">
<view class="mall-sheet">
<view class="mall-sheet-head">
<view class="mall-sheet-title">确认下单</view>
<view class="mall-sheet-close" bindtap="closeCheckout">取消</view>
</view>
<scroll-view class="mall-sheet-body" scroll-y>
<view class="mall-sheet-items">
<view wx:for="{{checkoutItems}}" wx:key="sku_code" class="mall-sheet-item">
<text class="mall-sheet-item-name">{{item.name}}</text>
<text class="mall-sheet-item-qty">×{{item.quantity}}</text>
<view class="mall-item-method">
<picker
mode="selector"
range="{{processingMethods}}"
value="{{item.methodIndex}}"
data-index="{{index}}"
bindchange="onItemMethodChange"
>
<view class="mall-item-field">{{item.processing_method}}</view>
</picker>
</view>
<text class="mall-sheet-item-amount">¥{{item.amount}}</text>
<input
class="mall-item-field mall-item-remark"
value="{{item.remark}}"
data-index="{{index}}"
placeholder="备注"
maxlength="200"
bindinput="onItemRemarkInput"
/>
</view>
</view>
<view class="mall-field mall-field--address">
<text class="mall-label">收货地址</text>
<input
class="mall-input mall-input--address"
value="{{deliveryAddress}}"
placeholder="填写详细收货地址"
maxlength="200"
disabled="{{addressSaving}}"
bindinput="onAddressInput"
bindblur="onAddressBlur"
/>
</view>
<picker mode="date" start="{{dateMin}}" end="{{dateMax}}" value="{{deliveryDate}}" bindchange="onDeliveryDateChange">
<view class="mall-field">
<text class="mall-label">配送日</text>
<text class="mall-value">{{deliveryDate}}</text>
</view>
</picker>
<view class="mall-field">
<text class="mall-label">备注</text>
<input class="mall-input" value="{{remark}}" placeholder="选填" bindinput="onRemarkInput" />
</view>
</scroll-view>
<view class="mall-sheet-actions">
<view class="mall-btn mall-btn--ghost" bindtap="closeCheckout">取消</view>
<view class="mall-btn mall-btn--primary" bindtap="submitOrder">确认下单</view>
</view>
</view>
</view>
</root-portal>
</block>
</view>
@@ -0,0 +1,481 @@
.mall-panel {
padding: 0 24rpx 260rpx;
}
.mall-panel.is-embedded {
padding-top: 16rpx;
}
.mall-state {
padding: 60rpx 0;
text-align: center;
font-size: 26rpx;
color: #94a3b8;
}
.mall-state--empty {
width: 100%;
padding: 120rpx 0;
}
.mall-search {
padding: 0 0 16rpx;
}
.mall-search-input {
width: 100%;
box-sizing: border-box;
height: 76rpx;
padding: 0 28rpx;
border-radius: 999rpx;
background: #ffffff;
border: 1rpx solid #e5e7eb;
font-size: 26rpx;
}
.mall-cats {
white-space: nowrap;
padding-bottom: 16rpx;
}
.mall-cat {
display: inline-block;
margin-right: 12rpx;
padding: 10rpx 24rpx;
border-radius: 999rpx;
background: #ffffff;
border: 1rpx solid #e5e7eb;
color: #475569;
font-size: 24rpx;
font-weight: 600;
}
.mall-cat.is-active {
background: #047857;
border-color: #047857;
color: #ffffff;
}
.mall-grid {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: space-between;
padding-top: 4rpx;
}
.mall-card {
display: flex;
flex-direction: column;
width: calc(50% - 8rpx);
box-sizing: border-box;
margin-bottom: 12rpx;
padding: 12rpx;
border-radius: 16rpx;
background: #ffffff;
border: 1rpx solid #f1f5f9;
}
.mall-thumb-wrap {
position: relative;
width: 100%;
height: 180rpx;
border-radius: 12rpx;
overflow: hidden;
background: #f1f5f9;
}
.mall-thumb {
width: 100%;
height: 100%;
display: block;
}
.mall-thumb--empty {
background: linear-gradient(135deg, #eef2f7 0%, #e2e8f0 100%);
}
.mall-card-badge {
position: absolute;
top: 12rpx;
right: 12rpx;
min-width: 40rpx;
height: 40rpx;
padding: 0 10rpx;
box-sizing: border-box;
border-radius: 999rpx;
background: #059669;
color: #ffffff;
font-size: 22rpx;
font-weight: 700;
line-height: 40rpx;
text-align: center;
}
.mall-name {
margin-top: 8rpx;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
font-size: 26rpx;
font-weight: 600;
line-height: 1.25;
color: #0f172a;
}
.mall-meta {
margin-top: 2rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 20rpx;
color: #94a3b8;
}
.mall-desc {
margin-top: 2rpx;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
font-size: 20rpx;
line-height: 1.3;
color: #64748b;
}
.mall-card-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8rpx;
margin-top: 6rpx;
padding-top: 0;
}
.mall-price {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 28rpx;
font-weight: 700;
color: #047857;
}
.mall-price-unit {
margin-left: 2rpx;
font-size: 20rpx;
font-weight: 400;
color: #64748b;
}
.mall-price.is-missing {
font-size: 24rpx;
color: #94a3b8;
font-weight: 500;
}
.mall-step {
display: flex;
align-items: center;
gap: 8rpx;
flex-shrink: 0;
}
.mall-step-btn {
width: 40rpx;
height: 40rpx;
border-radius: 999rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 26rpx;
line-height: 1;
color: #047857;
background: #ecfdf5;
border: 1rpx solid #a7f3d0;
}
.mall-step-btn--add {
color: #ffffff;
background: #059669;
border-color: #059669;
}
.mall-step-btn--add.is-disabled {
color: #9ca3af;
background: #f3f4f6;
border-color: #e5e7eb;
}
.mall-step-qty {
min-width: 28rpx;
text-align: center;
font-size: 24rpx;
font-weight: 700;
color: #0f172a;
}
.mall-bar {
position: fixed;
left: 24rpx;
right: 24rpx;
/* app-tab-bar 高约 116rpx + 安全区,购物车条必须浮在它上方 */
bottom: calc(136rpx + env(safe-area-inset-bottom));
z-index: 300;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
padding: 16rpx 20rpx 16rpx 24rpx;
border-radius: 999rpx;
background: rgba(15, 23, 42, 0.94);
box-shadow: 0 12rpx 30rpx rgba(15, 23, 42, 0.24);
}
.mall-bar-left {
display: flex;
align-items: center;
gap: 12rpx;
min-width: 0;
}
.mall-bar-badge {
min-width: 40rpx;
height: 40rpx;
padding: 0 10rpx;
box-sizing: border-box;
border-radius: 999rpx;
background: #10b981;
color: #ffffff;
font-size: 22rpx;
font-weight: 700;
line-height: 40rpx;
text-align: center;
}
.mall-bar-total {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 28rpx;
font-weight: 700;
color: #ffffff;
}
.mall-bar-btn {
flex-shrink: 0;
padding: 12rpx 36rpx;
border-radius: 999rpx;
background: #10b981;
color: #ffffff;
font-size: 26rpx;
font-weight: 700;
}
.mall-bar-btn.is-disabled {
background: rgba(255, 255, 255, 0.24);
color: rgba(255, 255, 255, 0.6);
}
.mall-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1000;
display: flex;
align-items: flex-end;
background: rgba(9, 9, 11, 0.45);
}
.mall-sheet {
width: 100%;
max-height: 86vh;
display: flex;
flex-direction: column;
box-sizing: border-box;
padding: 24rpx 28rpx calc(28rpx + env(safe-area-inset-bottom));
border-radius: 28rpx 28rpx 0 0;
background: #ffffff;
}
/* 整个弹层只有一个滚动区(头部与底部按钮固定),避免嵌套滚动条 */
.mall-sheet-body {
flex: 1;
min-height: 0;
max-height: calc(86vh - 220rpx);
}
.mall-sheet-head {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: 8rpx;
}
.mall-sheet-title {
font-size: 30rpx;
font-weight: 700;
color: #0f172a;
}
.mall-sheet-close {
padding: 8rpx 4rpx 8rpx 24rpx;
font-size: 26rpx;
color: #64748b;
}
.mall-sheet-items {
margin: 8rpx 0 4rpx;
padding: 12rpx 20rpx;
border-radius: 16rpx;
background: #f8fafc;
box-sizing: border-box;
}
.mall-sheet-item {
display: flex;
flex-direction: row;
align-items: center;
gap: 8rpx;
padding: 14rpx 0;
border-bottom: 1rpx solid #eef2f7;
font-size: 24rpx;
color: #334155;
}
.mall-sheet-item:last-child {
border-bottom: none;
}
.mall-sheet-item-name {
flex: 1 1 120rpx;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mall-sheet-item-qty {
flex-shrink: 0;
color: #64748b;
}
.mall-item-field {
height: 48rpx;
padding: 0 10rpx;
box-sizing: border-box;
border-radius: 10rpx;
background: #ffffff;
border: 1rpx solid #e2e8f0;
font-size: 22rpx;
color: #334155;
}
.mall-item-method {
flex: none;
width: 140rpx;
}
.mall-item-method .mall-item-field {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 46rpx;
}
.mall-sheet-item-amount {
flex-shrink: 0;
min-width: 96rpx;
text-align: right;
font-weight: 600;
color: #0f172a;
}
.mall-item-remark {
flex: none;
width: 132rpx;
}
.mall-field {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20rpx;
padding: 20rpx 0;
border-bottom: 1rpx solid #f4f4f5;
}
.mall-field--address {
flex-direction: column;
align-items: stretch;
gap: 8rpx;
}
.mall-input--address {
width: 100%;
height: 64rpx;
padding: 0 16rpx;
box-sizing: border-box;
border-radius: 12rpx;
background: #f8fafc;
border: 1rpx solid #e2e8f0;
font-size: 24rpx;
color: #334155;
text-align: left;
}
.mall-label {
flex-shrink: 0;
font-size: 26rpx;
color: #475569;
}
.mall-value {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 26rpx;
color: #0f172a;
text-align: right;
}
.mall-input {
flex: 1;
min-width: 0;
font-size: 26rpx;
text-align: right;
}
.mall-sheet-actions {
flex-shrink: 0;
display: flex;
gap: 20rpx;
margin-top: 20rpx;
}
.mall-btn {
flex: 1;
text-align: center;
padding: 22rpx 0;
border-radius: 999rpx;
font-size: 28rpx;
font-weight: 700;
}
.mall-btn--ghost {
color: #475569;
background: #f4f4f5;
}
.mall-btn--primary {
color: #ffffff;
background: #059669;
}
+8
View File
@@ -217,6 +217,14 @@ const MOBILE_MODULES = [
handler: 'goProductTrace',
homeEmbed: 'product-trace-panel',
},
{
id: 'mall',
title: '下单',
subtitle: '选购商品并下单',
page: '/pages/home/home',
roles: ['order_customer'],
homeEmbed: 'mall-panel',
},
];
/** 首页合并展示时的稳定排序 */
+2 -1
View File
@@ -39,6 +39,7 @@ const HOME_PANEL_SELECTORS = {
'admin-purchase': '#adminPurchaseHomePanel',
'prep-amend-review': '#prepAmendHomePanel',
'order-entry': '#orderEntryHomePanel',
mall: '#mallHomePanel',
};
function pxToRpx(px, windowWidth) {
@@ -136,7 +137,7 @@ function pickExclusiveHomeProgress(flags) {
}
function pickDefaultHomeModule(workspaceIds, workspaceMods) {
const order = [
const order = ['mall',
'purchase',
'admin-purchase',
'delivery',
+1
View File
@@ -23,6 +23,7 @@
"order-manage-panel": "/components/order-manage-panel/index",
"admin-preparations-panel": "/components/admin-preparations-panel/index",
"order-entry-panel": "/components/order-entry-panel/index",
"mall-panel": "/components/mall-panel/index",
"van-icon": "@vant/weapp/icon/index",
"van-tag": "@vant/weapp/tag/index",
"van-button": "@vant/weapp/button/index",
+6
View File
@@ -432,6 +432,12 @@
id="orderEntryHomePanel"
embedded="{{true}}"
/>
<mall-panel
wx:if="{{activeHomeModuleId === 'mall'}}"
id="mallHomePanel"
embedded="{{true}}"
style="--xd-module-grid-side: {{moduleGridSide}};"
/>
</view>
<view wx:if="{{needLogin}}" class="login-cta">
+2
View File
@@ -6,6 +6,7 @@ const ROLE_OPTIONS = [
{ value: 'warehouse', label: '仓管员', hint: '到货验收、加工与验收' },
{ value: 'picker', label: '分拣员', hint: '分拣复核、提交出库' },
{ value: 'order_entry', label: '录单员', hint: '使用录单权限账号登录' },
{ value: 'order_customer', label: '下单客户', hint: '客户商城账号' },
{ value: 'delivery', label: '配送员', hint: '配送任务、验货上车' },
];
@@ -19,6 +20,7 @@ const ROLE_LABELS = {
picker: '分拣员',
order_entry: '录单员',
delivery: '配送员',
order_customer: '下单客户',
};
const SESSION_KEY = 'canteen.mp.session';
+19
View File
@@ -1416,8 +1416,27 @@ function uploadFreeCostInvoice(filePath) {
});
}
/** 下单客户商城(2026-10-30):归属由服务端从绑定表推导,客户端不传 customer_code。 */
function fetchMallBootstrap() {
return request('/mobile/mall/bootstrap').then((body) => (body && body.data) || {});
}
function fetchMallProducts(params) {
return request('/mobile/mall/products', { data: params || {} }).then((body) => (body && body.data) || {});
}
function submitMallOrder(payload) {
return request('/mobile/mall/orders', { method: 'POST', data: payload || {} }).then((body) => (body && body.data) || {});
}
function saveMallAddress(address) {
return request('/mobile/mall/address', { method: 'PUT', data: { address } }).then((body) => (body && body.data) || {});
}
module.exports = {
request,
fetchMallBootstrap,
fetchMallProducts,
submitMallOrder,
saveMallAddress,
login,
loginByPhone,
loginChooseBranch,
@@ -20,6 +20,13 @@ import {
previewMallLibraryImport,
importMallLibraryRows,
} from '../../../services/customerMallAdminService';
import {
createCustomerOrderLoginAccount,
listCustomerOrderAccounts,
listAllCustomerOrderAccounts,
setCustomerOrderAccountStatus,
resetCustomerOrderAccountPassword,
} from '../../../services/customerOrderAccountService';
/** 客户模块 workflow API */
export function mountCustomerWorkflowRoutes(router: Router): void {
@@ -203,6 +210,95 @@ router.delete('/customers/:customerCode', authMiddleware, async (req: AuthReques
}
});
router.post('/customers/:customerCode/login-account', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await createCustomerOrderLoginAccount({
customerCode: String(req.params.customerCode || ''),
phone: req.body?.phone ? String(req.body.phone) : null,
username: req.body?.username ? String(req.body.username) : null,
password: req.body?.password ? String(req.body.password) : null,
createdBy: req.userId || null,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 400).json({
error: error?.code || 'server_error',
error_description: error?.message || '开通登录账号失败',
});
}
});
router.get('/customers/login-accounts', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']);
const raw = String(req.query?.codes || '').trim();
const codes = raw ? raw.split(',').map((c) => c.trim()).filter(Boolean) : [];
const data = await listCustomerOrderAccounts(codes);
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '读取登录账号失败',
});
}
});
/**
* 用户管理:列出本租户全部「下单客户」账号(读既有绑定表,不新建账号表)。
* 权限与用户管理页一致:`user_manage`;客户管理入口也可读。
*/
router.get('/customers/order-accounts', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['user_manage', 'customer_manage']);
const data = await listAllCustomerOrderAccounts();
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '读取下单客户账号失败',
});
}
});
router.patch('/customers/login-accounts/:userId/status', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await setCustomerOrderAccountStatus(
String(req.params.userId || ''),
Number(req.body?.status)
);
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 400).json({
error: error?.code || 'server_error',
error_description: error?.message || '更新账号状态失败',
});
}
});
router.post(
'/customers/login-accounts/:userId/reset-password',
authMiddleware,
async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['customer_manage']);
const data = await resetCustomerOrderAccountPassword(String(req.params.userId || ''));
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 400).json({
error: error?.code || 'server_error',
error_description: error?.message || '重置密码失败',
});
}
}
);
router.get('/customers/:customerCode/mall-products', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
+2
View File
@@ -13,11 +13,13 @@ import mobileOrderRoutes from './mobile/mobileOrderRoutes';
import mobileAdminRoutes from './mobile/mobileAdminRoutes';
import mobileUiPreferenceRoutes from './mobile/mobileUiPreferenceRoutes';
import mobileWeighOtaRoutes from './mobile/mobileWeighOtaRoutes';
import mobileMallRoutes from './mobile/mobileMallRoutes';
const router = Router();
router.use(mobileNotifyRoutes);
router.use(mobileAuthRoutes);
router.use(mobileMallRoutes);
router.use(mobileBadgeRoutes);
router.use(mobileDeliveryRoutes);
router.use(mobileSupplierRoutes);
@@ -0,0 +1,129 @@
import { Router, Response } from 'express';
import { authMiddleware, type AuthRequest } from '../../middleware/auth';
import { requireMobileRoles, type MobileRoleType } from './mobileShared';
import { loadTenantContext } from '../../services/tenantScope';
import { runWithTenantDbContext } from '../../services/tenantDbContext';
import {
listMallProducts,
listMallRecipients,
loadMallCustomer,
mallDeliveryDateBounds,
submitMallOrder,
updateMallCustomerAddress,
} from '../../services/customerMallService';
const router = Router();
/** 只有「下单客户」可用;客户归属由绑定表决定,客户端传不了。 */
const MALL_ROLES: MobileRoleType[] = ['order_customer'];
function sendError(res: Response, error: any, fallback: string) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || fallback,
});
}
async function resolveActor(req: AuthRequest) {
if (!req.userId) {
throw Object.assign(new Error('请先登录'), { status: 401, code: 'invalid_token' });
}
const userId = req.userId;
requireMobileRoles(req, MALL_ROLES);
const ctx = await loadTenantContext(userId);
if (!ctx?.branchCode) {
throw Object.assign(new Error('当前账号未绑定分公司'), { status: 403, code: 'forbidden_branch' });
}
const customer = await runWithTenantDbContext(ctx.branchCode, () => loadMallCustomer(userId));
return { userId, customer };
}
/** 下单页初始化:客户信息、收货人、可选配送日。 */
router.get('/mall/bootstrap', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const { customer } = await resolveActor(req);
const recipients = await runWithTenantDbContext(customer.branch_code, () =>
listMallRecipients(customer.customer_code)
);
const defaultRecipient = recipients.find((item) => item.is_default) || recipients[0] || null;
return res.json({
success: true,
data: {
customer: {
customer_code: customer.customer_code,
company_name: customer.company_name,
contact_name: customer.contact_name,
contact_phone: customer.contact_phone,
},
recipients,
// 客户自助改址后以 customers.address 为准(2026-10-30)
default_address: String(customer.address || '').trim() || defaultRecipient?.address || '',
delivery_date_min: mallDeliveryDateBounds().min,
delivery_date_max: mallDeliveryDateBounds().max,
},
});
} catch (error: any) {
return sendError(res, error, '读取下单信息失败');
}
});
/** 商品列表(客户商品库 + 与录单同源的售价)。 */
router.get('/mall/products', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const { customer } = await resolveActor(req);
const data = await runWithTenantDbContext(customer.branch_code, () =>
listMallProducts({
customerCode: customer.customer_code,
branchCode: customer.branch_code,
q: req.query?.q ? String(req.query.q) : null,
categoryCode: req.query?.category_code ? String(req.query.category_code) : null,
})
);
return res.json({ success: true, data });
} catch (error: any) {
return sendError(res, error, '读取商品失败');
}
});
/** 保存客户编辑后的收货地址:必须能解析坐标,并回写客户档案(含 lat/lng)。 */
router.put('/mall/address', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const { userId, customer } = await resolveActor(req);
const data = await runWithTenantDbContext(customer.branch_code, () =>
updateMallCustomerAddress({
customer,
address: req.body?.address,
operatorId: userId,
ipAddress: req.ip || null,
})
);
return res.json({ success: true, data });
} catch (error: any) {
return sendError(res, error, '保存收货地址失败');
}
});
/** 提交订单:只收 sku_code + quantity(价格/客户由服务端定)。 */
router.post('/mall/orders', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const { userId, customer } = await resolveActor(req);
const data = await runWithTenantDbContext(customer.branch_code, () =>
submitMallOrder({
customer,
userId,
items: req.body?.items,
deliveryDate: req.body?.delivery_date ? String(req.body.delivery_date) : null,
deliveryAddress: req.body?.delivery_address ? String(req.body.delivery_address) : null,
remark: req.body?.remark ? String(req.body.remark) : null,
})
);
return res.json({ success: true, data });
} catch (error: any) {
if (!error?.status || Number(error.status) >= 500) {
console.error('[mall] order submit failed', { code: error?.code, message: error?.message });
}
return sendError(res, error, '下单失败');
}
});
export default router;
+32 -1
View File
@@ -27,7 +27,8 @@ export type MobileRoleType =
| 'inspector'
| 'order_entry'
| 'delivery'
| 'picker';
| 'picker'
| 'order_customer';
export const ROLE_CONFIG: Record<
MobileRoleType,
@@ -47,6 +48,7 @@ export const ROLE_CONFIG: Record<
inspector: { emailSuffix: '@meoo.local', permissions: ['inspection_manage', 'processing_manage'] },
order_entry: { emailSuffix: '@meoo.local', permissions: ['order_entry'] },
picker: { emailSuffix: '@meoo.local', permissions: ['picking_manage'] },
order_customer: { emailSuffix: '@customer.meoo.local', table: 'customer_portal_users', roles: ['order_customer'] },
};
export const MOBILE_ROLE_LABELS: Record<MobileRoleType, string> = {
@@ -59,6 +61,7 @@ export const MOBILE_ROLE_LABELS: Record<MobileRoleType, string> = {
order_entry: '录单员',
delivery: '配送员',
picker: '分拣员',
order_customer: '下单客户',
};
const MOBILE_ROLE_ORDER: MobileRoleType[] = [
@@ -70,6 +73,7 @@ const MOBILE_ROLE_ORDER: MobileRoleType[] = [
'picker',
'delivery',
'order_entry',
'order_customer',
];
function buildMobileToken(userId: string, email: string, roleType: MobileRoleType, pwdv: number) {
@@ -262,6 +266,33 @@ async function verifyStaffAccess(userId: string, roleType: MobileRoleType) {
async function verifyMobileAccount(userId: string, roleType: MobileRoleType) {
const cfg = ROLE_CONFIG[roleType];
if (roleType === 'order_customer') {
const rowData = await queryOneAcrossActiveTenants(
`SELECT cpu.user_id, cpu.customer_code, c.source, c.status AS customer_status,
c.customer_code AS code,
EXISTS (SELECT 1 FROM public.user_roles ur
WHERE ur.user_id = cpu.user_id AND ur.role::text = 'order_customer') AS has_role
FROM customer_portal_users cpu
JOIN customers c ON c.customer_code = cpu.customer_code
WHERE cpu.user_id = $1 AND COALESCE(cpu.status, 1) = 1
LIMIT 1`,
[userId]
);
if (!rowData) throw Object.assign(new Error('该账号不是下单客户账号'), { code: 'invalid_role' });
const code = String(rowData.code || '');
const source = String(rowData.source || '');
if (
rowData.has_role !== true ||
code === '__RETAIL__' ||
code === '__INDEPENDENT_INBOUND__' ||
/^MAIN_/i.test(code) ||
['retail', 'independent_inbound', 'main_system'].includes(source) ||
![1, 10, 20, 30].includes(Number(rowData.customer_status ?? 10))
) {
throw Object.assign(new Error('该客户不允许登录商城'), { code: 'invalid_role' });
}
return;
}
if (cfg.table) {
// 绑定表仅在 tenant_*;登录时尚无 ALS,必须跨租户探测
const linked = await existsAcrossActiveTenants(
+11 -1
View File
@@ -28,7 +28,8 @@ export type MobileRoleType =
| 'inspector'
| 'order_entry'
| 'delivery'
| 'picker';
| 'picker'
| 'order_customer';
export type AccountKind =
| 'staff'
@@ -441,6 +442,7 @@ export async function getAccountBindings(
delivery: '配送管理',
supplier: '供应商角色',
purchaser: '采购员',
order_customer: '下单客户',
};
for (const role of roleSet) {
bindings.push({
@@ -617,6 +619,14 @@ export async function resolveMobileRoleType(
const roles = await pool.query(`SELECT role::text AS role FROM public.user_roles WHERE user_id = $1`, [userId]);
const roleSet = new Set(roles.rows.map((r) => r.role as string));
if (roleSet.has('order_customer')) {
const bound = await existsAcrossActiveTenants(
`SELECT 1 FROM customer_portal_users WHERE user_id = $1 AND COALESCE(status, 1) = 1 LIMIT 1`,
[userId],
branchCode
);
if (bound) return 'order_customer';
}
if (roleSet.has('super_admin') || roleSet.has('admin')) {
return 'admin';
}
+374
View File
@@ -0,0 +1,374 @@
import { pool } from '../db';
import { getGeoProvider } from './geoProvider';
import { writeAuditLog } from './auditService';
import { enrichOrderItemsWithPrices } from './orderPricingService';
import { submitMobileCustomerOrder } from './customerOrderSubmitService';
import { assertOrderSubmitWindowAllowed } from './orderSubmitWindowConfigService';
import { currentCycleCodeChina } from './fixedCostService';
import { isTradableCustomerStatus } from '../utils/customerStatus';
/** 商城可下单的最大数量(防手滑/防脏请求) */
const MAX_LINE_QTY = 9999;
const DELIVERY_WINDOW_DAYS = 7;
export type MallCustomer = {
customer_code: string;
company_name: string;
branch_code: string;
contact_name: string | null;
contact_phone: string | null;
address: string | null;
};
export type MallProduct = {
sku_code: string;
name: string;
spec: string | null;
unit: string;
description: string | null;
/** 该客户商品库配置的加工方式(管理员维护;下单弹层默认选中它,客户可改) */
processing_method: string | null;
category_code: string | null;
category_name: string | null;
price: number;
has_price: boolean;
image_url: string | null;
};
function chinaToday(): string {
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(new Date());
}
function addDaysYmd(ymd: string, days: number): string {
const d = new Date(`${ymd}T00:00:00+08:00`);
d.setUTCDate(d.getUTCDate() + days);
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(d);
}
/** 客户可选的配送日范围:明天 ~ 明天+6(共 7 天) */
export function mallDeliveryDateBounds(): { min: string; max: string } {
const today = chinaToday();
return { min: addDaysYmd(today, 1), max: addDaysYmd(today, DELIVERY_WINDOW_DAYS) };
}
/**
* 登录账号 → 下单客户档案。
*
* 三重闸:绑定行存在、`status=1`、客户档案可交易(`customers.status`)。
* 角色校验已在登录闸做过;这里再取一次是为了拿到 customer_code(**不接受客户端传**)。
* 客户状态口径见 `utils/customerStatus`:10 正常(列默认值)、40/50 禁用注销不可下单。
*/
export async function loadMallCustomer(userId: string | null | undefined): Promise<MallCustomer> {
const id = String(userId || '').trim();
if (!id) throw Object.assign(new Error('请先登录'), { status: 401, code: 'invalid_token' });
const result = await pool.query(
`SELECT cpu.customer_code, c.company_name, c.branch_code, c.contact_name, c.contact_phone,
c.address, c.status AS customer_status, c.source AS customer_source
FROM customer_portal_users cpu
JOIN public.user_roles ur ON ur.user_id = cpu.user_id AND ur.role::text = 'order_customer'
JOIN customers c ON c.customer_code = cpu.customer_code
WHERE cpu.user_id = $1 AND COALESCE(cpu.status, 1) = 1
LIMIT 1`,
[id]
);
const row = result.rows[0];
if (!row) {
throw Object.assign(new Error('当前账号未绑定客户,无法下单'), { status: 403, code: 'forbidden' });
}
const customerCode = String(row.customer_code || '');
const customerSource = String(row.customer_source || '');
if (
customerCode === '__RETAIL__' ||
customerCode === '__INDEPENDENT_INBOUND__' ||
/^MAIN_/i.test(customerCode) ||
['retail', 'independent_inbound', 'main_system'].includes(customerSource)
) {
throw Object.assign(new Error('该客户不允许使用商城'), { status: 403, code: 'customer_not_allowed' });
}
if (!isTradableCustomerStatus(row.customer_status)) {
throw Object.assign(new Error('客户档案已停用,无法下单'), { status: 403, code: 'customer_inactive' });
}
return {
customer_code: String(row.customer_code),
company_name: String(row.company_name || ''),
branch_code: String(row.branch_code || ''),
contact_name: row.contact_name == null ? null : String(row.contact_name),
contact_phone: row.contact_phone == null ? null : String(row.contact_phone),
address: row.address == null ? null : String(row.address),
};
}
/**
* 客户商品库(`customer_skus`)× 在售商品。
*
* 价格**复用录单同一函数** `enrichOrderItemsWithPrices`(报价单 → 客户商品库显式售价 →
* 上次成交价 → 价格表),保证「商城看到的价格 = 下单结算价」,不另写一套取价。
*/
export async function listMallProducts(input: {
customerCode: string;
branchCode: string | null;
q?: string | null;
categoryCode?: string | null;
}): Promise<{ products: MallProduct[]; categories: Array<{ code: string; name: string; count: number }> }> {
const customerCode = String(input.customerCode || '').trim();
if (!customerCode) return { products: [], categories: [] };
const q = String(input.q || '').trim().toLowerCase();
const categoryCode = String(input.categoryCode || '').trim();
const result = await pool.query(
`SELECT cs.sku_code,
COALESCE(NULLIF(TRIM(cs.customer_sku_name), ''), NULLIF(TRIM(s.sku_name), ''), cs.sku_code) AS name,
s.spec,
COALESCE(NULLIF(TRIM(cs.customer_unit), ''), NULLIF(TRIM(s.unit), ''), '斤') AS unit,
NULLIF(TRIM(cs.description), '') AS description,
NULLIF(TRIM(cs.processing_method), '') AS processing_method,
COALESCE(NULLIF(TRIM(cs.category_code), ''), s.category_code) AS category_code,
cat.category_name,
NULLIF(TRIM(s.image_url), '') AS image_url
FROM customer_skus cs
JOIN skus s ON s.sku_code = cs.sku_code AND COALESCE(s.status, 1) = 1
LEFT JOIN categories cat ON cat.category_code = COALESCE(NULLIF(TRIM(cs.category_code), ''), s.category_code)
WHERE cs.customer_code = $1
AND COALESCE(cs.is_listed, true) = true
ORDER BY cs.is_favorite DESC NULLS LAST, cs.usage_count DESC NULLS LAST, name ASC`,
[customerCode]
);
const rows = result.rows.filter((row) => {
if (categoryCode && String(row.category_code || '') !== categoryCode) return false;
if (q && !String(row.name || '').toLowerCase().includes(q)) return false;
return true;
});
const priced = await enrichOrderItemsWithPrices(
customerCode,
rows.map((row) => ({
sku_code: String(row.sku_code),
item_name: String(row.name || ''),
quantity: 1,
unit: String(row.unit || '斤'),
price: 0,
})),
input.branchCode
);
// 客户商城只下发有价商品(2026-10-30 开发者:「待报价的商品也别展示,没有价格展示干什么」)。
// 商城管理(listMallLibrary)不受影响,仍能看到无价商品并在这里补价。
const products: MallProduct[] = rows
.map((row, index) => {
const price = Math.max(0, Number(priced[index]?.price) || 0);
return {
sku_code: String(row.sku_code),
name: String(row.name || ''),
spec: row.spec == null ? null : String(row.spec),
unit: String(row.unit || '斤'),
description: row.description == null ? null : String(row.description),
processing_method: row.processing_method == null ? null : String(row.processing_method),
category_code: row.category_code == null ? null : String(row.category_code),
category_name: row.category_name == null ? null : String(row.category_name),
price,
has_price: price > 0,
image_url: row.image_url == null ? null : String(row.image_url),
};
})
.filter((product) => product.has_price);
const catMap = new Map<string, { code: string; name: string; count: number }>();
for (const product of products) {
const code = product.category_code || '';
if (!code) continue;
const item = catMap.get(code) || {
code,
name: product.category_name || '未分类',
count: 0,
};
item.count += 1;
catMap.set(code, item);
}
return {
products,
categories: [...catMap.values()].sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)),
};
}
export async function listMallRecipients(customerCode: string) {
const result = await pool.query(
`SELECT id, recipient_name, contact_phone, address, COALESCE(is_default, false) AS is_default
FROM customer_recipients
WHERE customer_code = $1
ORDER BY COALESCE(is_default, false) DESC, created_at ASC`,
[customerCode]
);
return result.rows.map((row) => ({
id: String(row.id),
name: String(row.recipient_name || ''),
phone: row.contact_phone == null ? null : String(row.contact_phone),
address: String(row.address || ''),
is_default: row.is_default === true,
}));
}
/**
* 下单客户编辑收货地址(2026-10-30):
* - 只改**自己**的客户档案(customer_code 由登录账号绑定推出,不接受客户端传);
* - 必须能解析出坐标(腾讯地理编码),否则拒绝保存;
* - 回写 `customers.address / lat / lng`,等价于 Web 客户编辑;
* - 额外写 `operation_logs`,方便后台看到客户自助改址。
*/
export async function updateMallCustomerAddress(input: {
customer: MallCustomer;
address: unknown;
operatorId?: string | null;
ipAddress?: string | null;
}): Promise<{ address: string; latitude: number; longitude: number }> {
const address = String(input.address || '').trim().slice(0, 200);
if (!address) {
throw Object.assign(new Error('请填写收货地址'), { status: 400, code: 'invalid_address' });
}
const geo = getGeoProvider();
let coords: { lat: number; lng: number } | null = null;
try {
coords = await geo.geocodeAddress(address);
} catch {
coords = null;
}
if (!coords) {
const geoErr = geo.getLastGeocodeError?.() || null;
const detail = String(geoErr?.message || '').trim();
throw Object.assign(
new Error(detail ? `地址无法解析坐标:${detail}` : '地址无法解析坐标,请填写更详细的收货地址'),
{ status: 400, code: 'address_geocode_failed' }
);
}
const before = await pool.query(
`SELECT address, lat, lng FROM customers WHERE customer_code = $1 LIMIT 1`,
[input.customer.customer_code]
);
await pool.query(
`UPDATE customers
SET address = $2, lat = $3, lng = $4
WHERE customer_code = $1`,
[input.customer.customer_code, address, coords.lat, coords.lng]
);
await Promise.resolve(
writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'customer_mall_address_update',
targetTable: 'customers',
targetId: input.customer.customer_code,
oldValue: {
address: before.rows[0]?.address ?? null,
lat: before.rows[0]?.lat == null ? null : Number(before.rows[0].lat),
lng: before.rows[0]?.lng == null ? null : Number(before.rows[0].lng),
},
newValue: { address, lat: coords.lat, lng: coords.lng },
ipAddress: input.ipAddress || null,
branchCode: input.customer.branch_code,
actionCategory: 'customer',
})
).catch(() => undefined);
return { address, latitude: coords.lat, longitude: coords.lng };
}
/**
* 下单:客户端只传 sku_code + quantity;
* 客户归属、分公司、价格、单位全部由服务端决定,**不接受客户端传 customer_code / price / unit**。
*/
export async function submitMallOrder(input: {
customer: MallCustomer;
userId: string;
items: unknown;
deliveryDate?: string | null;
deliveryAddress?: string | null;
remark?: string | null;
}) {
const rawItems = Array.isArray(input.items) ? input.items : [];
if (!rawItems.length) {
throw Object.assign(new Error('请选择商品'), { status: 400, code: 'invalid_request' });
}
// 下单侧必须复用展示侧完整判据:有效 SKU(skus.status=1)、is_listed=true、有价。
// 只查 customer_skus.is_listed 会让停用/无价 SKU 通过直接 POST 绕过商城展示。
const catalog = await listMallProducts({
customerCode: input.customer.customer_code,
branchCode: input.customer.branch_code,
});
const unitBySku = new Map(
catalog.products.map((product) => [product.sku_code, String(product.unit || '斤')])
);
const allowed = new Set(unitBySku.keys());
const items = rawItems.map((raw) => {
const item = raw as Record<string, unknown>;
const skuCode = String(item.sku_code || '').trim();
const quantity = Math.floor(Number(item.quantity) || 0);
if (!skuCode || !allowed.has(skuCode)) {
throw Object.assign(new Error('商品不在您的商品库中,请刷新后重试'), {
status: 400,
code: 'sku_not_in_library',
});
}
if (!(quantity > 0)) {
throw Object.assign(new Error('商品数量需大于 0'), { status: 400, code: 'invalid_quantity' });
}
if (quantity > MAX_LINE_QTY) {
throw Object.assign(new Error(`单个商品数量不能超过 ${MAX_LINE_QTY}`), {
status: 400,
code: 'quantity_too_large',
});
}
return {
sku_code: skuCode,
quantity,
unit: unitBySku.get(skuCode),
// 客户在确认弹层逐行选的加工方式;加工方(仓内/供应商)由管理员配置决定,
// 这里**不读客户端 processing_owner**(防客户自行指定加工方)。
processing_method:
String(item.processing_method || item.processingMethod || '').trim().slice(0, 50) || null,
remark: String(item.remark || '').trim().slice(0, 200) || null,
};
});
const { min, max } = mallDeliveryDateBounds();
const deliveryDate = String(input.deliveryDate || '').trim() || min;
if (deliveryDate < min || deliveryDate > max) {
throw Object.assign(new Error('配送日超出可选范围,请重新选择'), {
status: 400,
code: 'delivery_date_out_of_range',
});
}
const deliveryAddress = String(input.deliveryAddress || '').trim().slice(0, 200) || null;
const remark = String(input.remark || '').trim().slice(0, 200) || null;
await assertOrderSubmitWindowAllowed({
branchCode: input.customer.branch_code,
isAdmin: false,
});
const result = await submitMobileCustomerOrder({
customerCode: input.customer.customer_code,
branchCode: input.customer.branch_code,
userId: input.userId,
items,
deliveryDate,
deliveryAddress,
remark,
// 小程序录单会把当前周期一并提交;商城下单同样由**服务端**算当前周期。
// 不传会走 submitMobileCustomerOrder 的 `'MOBILE'` 兜底,订单进不了月度周期口径。
cycleCode: currentCycleCodeChina(),
// 与小程序录单同源:订单号前缀走 MP,而不是缺省 API
entryChannel: 'MP',
});
return {
order_code: result.order_code,
order_status: result.order_status,
};
}
@@ -0,0 +1,397 @@
import { randomUUID } from 'crypto';
import { pool } from '../db';
import type { PoolClient } from 'pg';
import { hashPassword, initialPasswordFromPhone } from '../utils/password';
import { isTradableCustomerStatus } from '../utils/customerStatus';
const EXCLUDED_CUSTOMER_SOURCES = new Set(['retail', 'independent_inbound', 'main_system']);
function assertNormalCustomer(input: { customer_code?: unknown; source?: unknown; status?: unknown }) {
const code = String(input.customer_code || '').trim();
const source = String(input.source || '').trim();
if (
code === '__RETAIL__' ||
code === '__INDEPENDENT_INBOUND__' ||
EXCLUDED_CUSTOMER_SOURCES.has(source) ||
/^MAIN_/i.test(code)
) {
throw Object.assign(new Error('该客户不允许开通下单账号'), { status: 403, code: 'customer_not_allowed' });
}
if (!isTradableCustomerStatus(input.status)) {
throw Object.assign(new Error('客户已停用,不能开通登录账号'), { status: 400, code: 'customer_inactive' });
}
}
/** 无手机号时的下单客户基础初始密码(账号仍强制首次登录改密) */
export const CUSTOMER_ORDER_BASE_PASSWORD = '123456';
/** 下单客户账号:手机号选填(有则用于登录名与初始密码,无则必须显式给登录名) */
export function normalizeOptionalCustomerPhone(phone: unknown): string | null {
const raw = String(phone ?? '').trim();
if (!raw) return null;
if (!/^1[3-9]\d{9}$/.test(raw)) {
throw Object.assign(new Error('手机号需为有效的11位手机号码'), { code: 'invalid_phone' });
}
return raw;
}
/** 登录名规则与供应商一致:2-32 位,字母/数字/下划线/点/横线/中文 */
export function normalizeCustomerOrderUsername(username: unknown): string {
const raw = String(username ?? '').trim();
if (!raw) throw Object.assign(new Error('请输入登录账号'), { code: 'invalid_username' });
if (raw.length < 2 || raw.length > 32) {
throw Object.assign(new Error('登录账号需为 2-32 位'), { code: 'invalid_username' });
}
if (!/^[A-Za-z0-9_.\-\u4e00-\u9fa5]+$/.test(raw)) {
throw Object.assign(new Error('登录账号只能包含字母、数字、下划线、点、横线或中文'), {
code: 'invalid_username',
});
}
return raw;
}
export type CustomerOrderAccount = {
user_id: string;
customer_code: string;
username: string;
phone: string | null;
status: number;
created_at: string | null;
};
/**
* 客户列表 →「开通登录账号」。
*
* 与供应商开户同范式:`auth.users` + `profiles` + `user_roles` + 绑定表同事务;
* 绑定表复用 `customer_portal_users`(客户冻结:不得 DROP/改名),新增 status/created_by 两列。
*
* ⚠️ 只有这里会写入 `user_roles.role='order_customer'`;
* 历史门户行(只有绑定、没有该角色)登录会被拒 —— 见 docs/design/20261028-customer-order-mall.md §3。
*/
export async function createCustomerOrderLoginAccount(params: {
customerCode: string;
phone?: string | null;
username?: string | null;
password?: string | null;
createdBy?: string | null;
}, options?: { client?: PoolClient }) {
const customerCode = String(params.customerCode || '').trim();
if (!customerCode) {
throw Object.assign(new Error('缺少客户编码'), { code: 'invalid_request' });
}
const customer = await (options?.client ?? pool).query(
`SELECT customer_code, company_name, contact_name, contact_phone, branch_code, status, source
FROM customers WHERE customer_code = $1 LIMIT 1`,
[customerCode]
);
if (!customer.rowCount) {
throw Object.assign(new Error('客户不存在'), { status: 404, code: 'not_found' });
}
const customerRow = customer.rows[0];
assertNormalCustomer(customerRow);
const branchCode = String(customerRow.branch_code || '').trim();
if (!branchCode) {
throw Object.assign(new Error('客户未绑定分公司,不能开通登录账号'), {
status: 400,
code: 'branch_required',
});
}
// 已有账号:已有 order_customer 角色 ⇒ 幂等返回;
// 只有绑定行的历史门户账号(2026-09 门户下线前写入)⇒ 显式开户时补授角色,
// 否则列表显示「已开通」但实际登录被三重闸拦住。
const existing = await (options?.client ?? pool).query(
`SELECT cpu.user_id, cpu.customer_code, cpu.status, p.username, p.phone,
EXISTS (
SELECT 1 FROM public.user_roles ur
WHERE ur.user_id = cpu.user_id AND ur.role::text = 'order_customer'
) AS has_role
FROM customer_portal_users cpu
LEFT JOIN profiles p ON p.id = cpu.user_id
WHERE cpu.customer_code = $1
ORDER BY cpu.created_at ASC
LIMIT 1`,
[customerCode]
);
if (existing.rowCount) {
const row = existing.rows[0];
if (row.has_role === true) {
return {
user_id: String(row.user_id),
customer_code: customerCode,
username: String(row.username || ''),
created: false,
default_password: null as string | null,
};
}
if (!String(row.username || '').trim()) {
throw Object.assign(new Error('该客户存在历史门户绑定但缺少可用登录档案,请联系管理员处理'), {
status: 409,
code: 'legacy_account_unusable',
});
}
// 一条语句内原子完成「补角色 + 启用绑定」;不新建账号、不改密码。
await (options?.client ?? pool).query(
`WITH granted AS (
INSERT INTO public.user_roles (user_id, role)
VALUES ($1, 'order_customer')
ON CONFLICT (user_id, role) DO NOTHING
)
UPDATE customer_portal_users
SET status = 1, updated_at = NOW(), created_by = COALESCE(created_by, $2)
WHERE user_id = $1`,
[row.user_id, params.createdBy || null]
);
return {
user_id: String(row.user_id),
customer_code: customerCode,
username: String(row.username || ''),
created: false,
default_password: null as string | null,
upgraded: true,
};
}
const phone =
normalizeOptionalCustomerPhone(params.phone) ||
normalizeOptionalCustomerPhone(customerRow.contact_phone);
const username = params.username
? normalizeCustomerOrderUsername(params.username)
: phone ?? (() => {
throw Object.assign(new Error('未填手机号时必须指定登录账号'), {
code: 'username_required',
});
})();
// 手机号式登录名允许跨分公司重复(登录时按手机号列多账号选公司);
// 自定义登录名仍需全局唯一(用户名登录无法选公司,重名会歧义)。
const phoneLikeUsername = /^1[3-9]\d{9}$/.test(username);
const email = phoneLikeUsername
? `${username}.${branchCode.toLowerCase()}@customer.meoo.local`
: `${username}@customer.meoo.local`;
const contactName = String(customerRow.contact_name || '').trim();
const companyName = String(customerRow.company_name || '').trim();
const fullName = contactName || companyName || username;
const explicitPassword = String(params.password ?? '').trim();
const generatedPassword =
explicitPassword || (phone ? initialPasswordFromPhone(phone) : CUSTOMER_ORDER_BASE_PASSWORD);
const passwordHash = await hashPassword(generatedPassword);
const db = options?.client ?? pool;
const clash = phoneLikeUsername
? await db.query(
`SELECT 1 FROM profiles
WHERE lower(username) = lower($1) AND branch_code = $2
UNION ALL
SELECT 1 FROM auth.users WHERE email = $3
LIMIT 1`,
[username, branchCode, email]
)
: await db.query(
`SELECT 1 FROM profiles WHERE lower(username) = lower($1)
UNION ALL
SELECT 1 FROM auth.users WHERE email = $2
LIMIT 1`,
[username, email]
);
if (clash.rowCount) {
throw Object.assign(new Error(`登录账号「${username}」已被其他账号使用`), {
code: 'username_already_used',
});
}
if (phone) {
const phoneClash = await db.query(
`SELECT 1 FROM profiles
WHERE regexp_replace(COALESCE(phone, ''), '[^0-9]', '', 'g') = $1
AND branch_code = $2
LIMIT 1`,
[phone, branchCode]
);
if (phoneClash.rowCount) {
throw Object.assign(new Error('该分公司已存在此手机号'), { code: 'phone_in_branch' });
}
}
const userId = randomUUID();
const ownsTransaction = !options?.client;
const client = options?.client ?? await pool.connect();
try {
if (ownsTransaction) await client.query('BEGIN');
await client.query(
`INSERT INTO auth.users (
instance_id, id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data
) VALUES (
'00000000-0000-0000-0000-000000000000', $1, 'authenticated', 'authenticated', $2,
$3, NOW(),
'{"provider":"email","providers":["email"]}'::jsonb, $4::jsonb
)`,
[userId, email, passwordHash, JSON.stringify({ username, full_name: fullName })]
);
// auth.users 的 on_auth_user_created 触发器会先插入 profiles(供应商库存在该触发器);
// 这里用 upsert 补齐手机号/分公司/首登改密,不能直接 INSERT(会 profiles_pkey 冲突)。
await client.query(
`INSERT INTO profiles (id, username, full_name, phone, branch_code, status, must_change_password)
VALUES ($1, $2, $3, $4, $5, 1, true)
ON CONFLICT (id) DO UPDATE
SET username = EXCLUDED.username,
full_name = EXCLUDED.full_name,
phone = EXCLUDED.phone,
branch_code = EXCLUDED.branch_code,
status = 1,
must_change_password = true`,
[userId, username, fullName, phone, branchCode]
);
await client.query(
`INSERT INTO user_roles (user_id, role) VALUES ($1, 'order_customer')
ON CONFLICT (user_id, role) DO NOTHING`,
[userId]
);
await client.query(
`INSERT INTO customer_portal_users (user_id, customer_code, status, created_by)
VALUES ($1, $2, 1, $3)`,
[userId, customerCode, params.createdBy || null]
);
if (ownsTransaction) await client.query('COMMIT');
return {
user_id: userId,
customer_code: customerCode,
username,
created: true,
default_password: generatedPassword as string | null,
password_generated: !explicitPassword,
};
} catch (error) {
if (ownsTransaction) await client.query('ROLLBACK');
throw error;
} finally {
if (ownsTransaction) client.release();
}
}
/** 列表展示:按客户编码批量取已开通账号(只取最后开通的一条) */
export async function listCustomerOrderAccounts(
customerCodes: string[]
): Promise<Record<string, CustomerOrderAccount>> {
const codes = [...new Set((customerCodes || []).map((c) => String(c || '').trim()).filter(Boolean))];
if (!codes.length) return {};
const result = await pool.query(
`SELECT DISTINCT ON (cpu.customer_code)
cpu.customer_code, cpu.user_id, cpu.status, cpu.created_at,
p.username, p.phone
FROM customer_portal_users cpu
JOIN public.user_roles ur ON ur.user_id = cpu.user_id
AND ur.role::text = 'order_customer'
LEFT JOIN profiles p ON p.id = cpu.user_id
JOIN customers c ON c.customer_code = cpu.customer_code
WHERE cpu.customer_code = ANY($1::text[])
AND c.customer_code NOT IN ('__RETAIL__','__INDEPENDENT_INBOUND__')
AND COALESCE(c.source, '') NOT IN ('retail','independent_inbound','main_system')
AND c.customer_code NOT LIKE 'MAIN\\_%'
ORDER BY cpu.customer_code, cpu.created_at ASC`,
[codes]
);
const out: Record<string, CustomerOrderAccount> = {};
for (const row of result.rows) {
out[String(row.customer_code)] = {
user_id: String(row.user_id),
customer_code: String(row.customer_code),
username: String(row.username || ''),
phone: row.phone == null ? null : String(row.phone),
status: Number(row.status) || 0,
created_at: row.created_at ? String(row.created_at) : null,
};
}
return out;
}
export type CustomerOrderAccountRow = CustomerOrderAccount & {
company_name: string | null;
};
/**
* 用户管理:一次取本租户全部「下单客户」账号。
*
* 复用客户开户链路写入的 `customer_portal_users` + `profiles` + `customers`,
* **不新建账号表**;只返回真正持有 `order_customer` 角色的绑定行(与登录三重闸同口径)。
*/
export async function listAllCustomerOrderAccounts(): Promise<CustomerOrderAccountRow[]> {
const result = await pool.query(
`SELECT cpu.user_id, cpu.customer_code, cpu.status, cpu.created_at,
p.username, p.phone, c.company_name
FROM customer_portal_users cpu
JOIN public.user_roles ur ON ur.user_id = cpu.user_id
AND ur.role::text = 'order_customer'
LEFT JOIN profiles p ON p.id = cpu.user_id
LEFT JOIN customers c ON c.customer_code = cpu.customer_code
WHERE c.customer_code NOT IN ('__RETAIL__','__INDEPENDENT_INBOUND__')
AND COALESCE(c.source, '') NOT IN ('retail','independent_inbound','main_system')
AND c.customer_code NOT LIKE 'MAIN\\_%'
ORDER BY cpu.created_at DESC`
);
return result.rows.map((row) => ({
user_id: String(row.user_id),
customer_code: String(row.customer_code),
username: String(row.username || ''),
phone: row.phone == null ? null : String(row.phone),
status: Number(row.status) || 0,
company_name: row.company_name == null ? null : String(row.company_name),
created_at: row.created_at ? String(row.created_at) : null,
}));
}
async function assertOrderCustomerAccount(userId: string) {
const result = await pool.query(
`SELECT cpu.user_id, cpu.customer_code, cpu.status
FROM customer_portal_users cpu
JOIN user_roles ur ON ur.user_id = cpu.user_id AND ur.role::text = 'order_customer'
WHERE cpu.user_id = $1
LIMIT 1`,
[userId]
);
if (!result.rowCount) {
throw Object.assign(new Error('下单客户账号不存在'), { status: 404, code: 'not_found' });
}
return result.rows[0];
}
/** 停用 / 启用(只作用于下单客户账号;停用即无法登录) */
export async function setCustomerOrderAccountStatus(userId: string, status: number) {
const id = String(userId || '').trim();
const next = Number(status) === 1 ? 1 : 0;
if (!id) throw Object.assign(new Error('缺少账号'), { status: 400, code: 'invalid_request' });
await assertOrderCustomerAccount(id);
await pool.query(
`UPDATE customer_portal_users SET status = $2, updated_at = NOW() WHERE user_id = $1`,
[id, next]
);
return { user_id: id, status: next };
}
/** 重置密码:回到默认初始密码(手机号后 6 位或 123456),并强制下次登录改密 */
export async function resetCustomerOrderAccountPassword(userId: string) {
const id = String(userId || '').trim();
if (!id) throw Object.assign(new Error('缺少账号'), { status: 400, code: 'invalid_request' });
await assertOrderCustomerAccount(id);
const profile = await pool.query(
`SELECT regexp_replace(COALESCE(phone, ''), '[^0-9]', '', 'g') AS phone
FROM profiles WHERE id = $1 LIMIT 1`,
[id]
);
const phone = String(profile.rows[0]?.phone || '');
const password = phone.length === 11 ? initialPasswordFromPhone(phone) : CUSTOMER_ORDER_BASE_PASSWORD;
const passwordHash = await hashPassword(password);
await pool.query(
`UPDATE auth.users
SET encrypted_password = $2,
password_version = COALESCE(password_version, 1) + 1,
updated_at = NOW()
WHERE id = $1`,
[id, passwordHash]
);
await pool.query(`UPDATE profiles SET must_change_password = true WHERE id = $1`, [id]);
return { user_id: id, default_password: password };
}
@@ -148,25 +148,6 @@ export async function setCustomerSkuSalePrice(input: {
// 自动选中的共享单不含该 SKU:不写别人的报价单,回落到客户商品库
sheetCode = null;
} else {
/**
* 先锁报价单条目,再锁绑定表:与“绑定新客户”的 INSERT 不会形成 item→binding 与
* binding→item 的环;锁内 count 封住 TOCTOU(校验后另一客户才绑定的窗口)。
* 自动选中的共享单不含该 SKU 时已在上面回落 customer_skus,不进入此分支。
*/
await client.query('LOCK TABLE customer_quote_sheet_customers IN SHARE ROW EXCLUSIVE MODE');
const shared = await client.query(
`SELECT COUNT(*)::int AS n
FROM customer_quote_sheet_customers
WHERE quote_sheet_code = $1`,
[sheetCode]
);
if (Number(shared.rows[0]?.n) > 1) {
throw bad(
'该报价单绑定多个客户,不能就地改价,避免改动其他客户价格',
'quote_sheet_shared_customer',
409
);
}
oldSalePrice = Number(current.rows[0]?.current_price) || null;
if (oldSalePrice != null && Math.abs(oldSalePrice - price) < 0.005) {
await client.query('COMMIT');
+5
View File
@@ -0,0 +1,5 @@
export const CUSTOMER_TRADABLE_STATUSES: readonly number[] = [1, 10, 20, 30];
export function isTradableCustomerStatus(value: unknown): boolean {
const status = value == null || value === '' ? 10 : Number(value);
return CUSTOMER_TRADABLE_STATUSES.includes(status);
}
+55
View File
@@ -0,0 +1,55 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8');
const account = read('src/services/customerOrderAccountService.ts');
const mall = read('src/services/customerMallService.ts');
const mobile = read('src/routes/mobile/mobileShared.ts');
const route = read('src/modules/workflow/routes/customerRoutes.ts');
const mobileMall = read('src/routes/mobile/mobileMallRoutes.ts');
const migration = read('../migrations/20261089_customer_portal_order_customer.sql');
const panel = readFileSync(new URL('../../miniprogram/components/mall-panel/index.js', import.meta.url), 'utf8');
const req = readFileSync(new URL('../../miniprogram/utils/request.js', import.meta.url), 'utf8');
describe('客户自助商城二期', () => {
it('只允许正常客户:sentinel/source/MAIN_/非正常状态四处判据', () => {
expect(account).toContain('__RETAIL__');
expect(account).toContain('__INDEPENDENT_INBOUND__');
expect(account).toContain("'retail', 'independent_inbound', 'main_system'");
expect(account).toContain('/^MAIN_/i');
expect(mall).toContain('customer_not_allowed');
expect(mobile).toContain("roleType === 'order_customer'");
expect(mobile).toContain('order_customer');
});
it('迁移新增 portal 状态/创建人/更新时间 + role_definitions', () => {
expect(migration).toContain('ADD COLUMN IF NOT EXISTS status INT NOT NULL DEFAULT 1');
expect(migration).toContain('created_by UUID');
expect(migration).toContain('updated_at TIMESTAMPTZ');
expect(migration).toContain("'order_customer'");
});
it('账号路由和权限;登录三重闸/商城角色', () => {
expect(route).toContain("'/customers/:customerCode/login-account'");
expect(route).toContain("'/customers/login-accounts'");
expect(route).toContain("'/customers/login-accounts/:userId/reset-password'");
expect(route).toContain("requireWorkflowPermission(ctx, ['customer_manage'])");
expect(mobileMall).toContain("['order_customer']");
});
it('商城只取该客户 is_listed 且有价;价格复用 enrich;提交不接客户端 customer/branch/price', () => {
expect(mall).toContain('enrichOrderItemsWithPrices');
expect(mall).toContain('COALESCE(cs.is_listed, true) = true');
expect(mall).toContain('submitMobileCustomerOrder');
expect(mall).toContain(' items,');
expect(mobileMall).toContain("customer_code: customer.customer_code");
expect(mobileMall).toContain("req.body?.items");
});
it('配送日 [明天, 明天+6];小程序内嵌 mall-panel 与请求方法', () => {
expect(mall).toContain('DELIVERY_WINDOW_DAYS = 7');
expect(mall).toContain('addDaysYmd(today, DELIVERY_WINDOW_DAYS)');
expect(panel).toContain('fetchMallBootstrap');
expect(req).toContain('/mobile/mall/products');
expect(req).toContain('/mobile/mall/orders');
});
});
@@ -27,8 +27,6 @@ describe('客户 SKU 销售价二期', () => {
expect(svc).toContain("target = 'quote_sheet'");
expect(svc).toContain('sale_price_manual = true');
// 自动选择报价单也必须校验共享单,避免商城/排行改价串改其他客户价格
expect(svc).toContain('先锁报价单条目');
expect(svc).toContain('customer_quote_sheet_customers');
expect(svc).toContain('upsertCustomerSkuPrice');
expect(svc).toContain('synced_customer_sku: target');
expect(svc).toContain('INSERT INTO customer_skus');
+19
View File
@@ -197,4 +197,23 @@ export const customers: MessageDict = {
'mall.import.description': 'Fill in product codes from the template to import into {name} customer library. Existing products are skipped.',
'mall.import.templateHint': 'Template: Product code* / Customer product name / Unit / Favorite',
'mall.summary': '{total} products · {orderable} orderable',
'account.action': 'Login account',
'account.title': 'Customer login account',
'account.username': 'Username',
'account.phone': 'Phone',
'account.passwordOptional': 'Initial password (optional)',
'account.create': 'Create account',
'account.created': 'Account created',
'account.createdWithPassword': 'Account created. Initial password: {password}',
'account.status': 'Status',
'account.enabled': 'Active',
'account.disabled': 'Disabled',
'account.disable': 'Disable',
'account.enable': 'Enable',
'account.reset': 'Reset password',
'account.resetDone': 'Password reset. New password: {password}',
'account.loadFailed': 'Failed to load account',
'account.createFailed': 'Failed to create account',
'account.statusFailed': 'Failed to update status',
'account.resetFailed': 'Failed to reset password',
};
+19
View File
@@ -198,4 +198,23 @@ export const customers: MessageDict = {
'mall.import.description': 'Isi kode produk sesuai templat untuk mengimpor ke pustaka pelanggan {name}. Produk yang sudah ada akan dilewati.',
'mall.import.templateHint': 'Templat: Kode produk* / Nama produk pelanggan / Satuan / Favorit',
'mall.summary': '{total} produk · {orderable} bisa dipesan',
'account.action': 'Akun login',
'account.title': 'Akun login pelanggan',
'account.username': 'Nama pengguna',
'account.phone': 'Telepon',
'account.passwordOptional': 'Kata sandi awal (opsional)',
'account.create': 'Buat akun',
'account.created': 'Akun dibuat',
'account.createdWithPassword': 'Akun dibuat. Kata sandi awal: {password}',
'account.status': 'Status',
'account.enabled': 'Aktif',
'account.disabled': 'Nonaktif',
'account.disable': 'Nonaktifkan',
'account.enable': 'Aktifkan',
'account.reset': 'Reset kata sandi',
'account.resetDone': 'Kata sandi direset: {password}',
'account.loadFailed': 'Gagal memuat akun',
'account.createFailed': 'Gagal membuat akun',
'account.statusFailed': 'Gagal memperbarui status',
'account.resetFailed': 'Gagal mereset kata sandi',
};
+19
View File
@@ -197,4 +197,23 @@ export const customers: MessageDict = {
'mall.import.description': '按模板填写商品编码,导入到「{name}」的客户商品库。已在库中的商品会跳过。',
'mall.import.templateHint': '模板列:商品编码* / 客户商品名 / 单位 / 收藏',
'mall.summary': '共 {total} 个商品 · 可下单 {orderable}',
'account.action': '登录账号',
'account.title': '客户登录账号',
'account.username': '登录名',
'account.phone': '手机号',
'account.passwordOptional': '初始密码(选填)',
'account.create': '开通账号',
'account.created': '账号已开通',
'account.createdWithPassword': '账号已开通,初始密码:{password}',
'account.status': '状态',
'account.enabled': '正常',
'account.disabled': '停用',
'account.disable': '停用',
'account.enable': '启用',
'account.reset': '重置密码',
'account.resetDone': '已重置,初始密码:{password}',
'account.loadFailed': '读取账号失败',
'account.createFailed': '开通失败',
'account.statusFailed': '更新状态失败',
'account.resetFailed': '重置失败',
};
+133
View File
@@ -46,6 +46,11 @@ import {
deleteCustomerRecipientApi,
updateCustomerRebateConfigApi,
setCustomerSelfPickupApi,
createCustomerOrderLoginAccountApi,
listCustomerOrderAccountsApi,
setCustomerOrderAccountStatusApi,
resetCustomerOrderAccountPasswordApi,
type CustomerOrderAccount,
type CustomerRebateConfigUpdateBody,
} from '../../utils/workflowApi';
import { notify } from '../../utils/notify';
@@ -108,6 +113,21 @@ interface Customer {
rebate_category_ratios?: Record<string, number> | null;
}
/** 只有正常客户可开通下单账号:排散客、独立进货、主系统分配客户。 */
function canOpenCustomerAccount(customer: Customer): boolean {
const code = String(customer.customer_code || '').trim();
const source = String(customer.source || '').trim();
if (
code === '__RETAIL__' ||
code === '__INDEPENDENT_INBOUND__' ||
/^MAIN_/i.test(code) ||
['retail', 'independent_inbound', 'main_system'].includes(source)
) {
return false;
}
return [1, 10, 20, 30].includes(Number(customer.status ?? 10));
}
// ==================== 状态映射 ====================
const statusMap: Record<number, { color: string; bgColor: string }> = {
10: { color: 'text-emerald-600', bgColor: 'bg-emerald-100' },
@@ -825,6 +845,10 @@ export const CustomerManagement: React.FC = () => {
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
const [deletingCustomer, setDeletingCustomer] = useState<Customer | null>(null);
const [accountCustomer, setAccountCustomer] = useState<Customer | null>(null);
const [accountInfo, setAccountInfo] = useState<CustomerOrderAccount | null>(null);
const [accountSaving, setAccountSaving] = useState(false);
const [accountForm, setAccountForm] = useState({ phone: '', username: '', password: '' });
const [savingCustomer, setSavingCustomer] = useState(false);
const savingCustomerRef = useRef(false);
@@ -1319,6 +1343,62 @@ export const CustomerManagement: React.FC = () => {
}
};
const openAccountModal = async (customer: Customer) => {
const phone = String(customer.contact_phone || '').trim();
setAccountCustomer(customer);
setAccountInfo(null);
setAccountForm({ phone, username: phone, password: '' });
try {
const { data } = await listCustomerOrderAccountsApi([customer.customer_code]);
setAccountInfo(data?.[customer.customer_code] || null);
} catch (error: any) {
notify.error(error?.message || t('customers.account.loadFailed'));
}
};
const createAccount = async () => {
if (!accountCustomer) return;
setAccountSaving(true);
try {
const { data } = await createCustomerOrderLoginAccountApi(accountCustomer.customer_code, accountForm);
notify.success(
data.default_password
? t('customers.account.createdWithPassword', { password: data.default_password })
: t('customers.account.created')
);
const list = await listCustomerOrderAccountsApi([accountCustomer.customer_code]);
setAccountInfo(list.data?.[accountCustomer.customer_code] || null);
} catch (error: any) {
notify.error(error?.message || t('customers.account.createFailed'));
} finally {
setAccountSaving(false);
}
};
const toggleAccount = async () => {
if (!accountInfo) return;
setAccountSaving(true);
try {
await setCustomerOrderAccountStatusApi(accountInfo.user_id, accountInfo.status === 1 ? 0 : 1);
const list = await listCustomerOrderAccountsApi([accountInfo.customer_code]);
setAccountInfo(list.data?.[accountInfo.customer_code] || null);
} catch (error: any) {
notify.error(error?.message || t('customers.account.statusFailed'));
} finally {
setAccountSaving(false);
}
};
const resetAccountPassword = async () => {
if (!accountInfo) return;
setAccountSaving(true);
try {
const { data } = await resetCustomerOrderAccountPasswordApi(accountInfo.user_id);
notify.success(t('customers.account.resetDone', { password: data.default_password }));
} catch (error: any) {
notify.error(error?.message || t('customers.account.resetFailed'));
} finally {
setAccountSaving(false);
}
};
const handleDeleteRecipient = async (id: string) => {
if (!recipientsCustomer) return;
try {
@@ -2031,6 +2111,14 @@ export const CustomerManagement: React.FC = () => {
>
{t('customers.action.recipients')}
</button>
{canOpenCustomerAccount(c) && (
<button
onClick={() => void openAccountModal(c)}
className="text-xs font-medium text-sky-600 hover:text-sky-800 whitespace-nowrap"
>
{t('customers.account.action')}
</button>
)}
{canEdit && (
<button
onClick={() => openEditModal(c)}
@@ -2587,6 +2675,51 @@ export const CustomerManagement: React.FC = () => {
)}
</AnimatePresence>
{accountCustomer ? (
<DialogOverlay onBackdropMouseDown={() => setAccountCustomer(null)}>
<div className="app-surface app-foreground rounded-xl p-6 w-full max-w-md mx-4">
<div className="flex items-center justify-between mb-3">
<h2 className="app-foreground text-lg font-bold">{t('customers.account.title')}</h2>
<button type="button" aria-label={t('common.close')} className="text-slate-400 hover:text-slate-600" onClick={() => setAccountCustomer(null)}>×</button>
</div>
<p className="app-foreground-muted text-sm mb-4">
{accountCustomer.company_name} · {accountCustomer.customer_code}
</p>
{accountInfo ? (
<div className="space-y-3 text-sm">
<div className="flex items-center justify-between">
<span className="app-foreground-muted">{t('customers.account.username')}</span>
<span className="app-foreground font-medium">{accountInfo.username || '—'}</span>
</div>
<div className="flex items-center justify-between">
<span className="app-foreground-muted">{t('customers.account.status')}</span>
<span className={accountInfo.status === 1 ? 'text-emerald-600' : 'text-slate-400'}>
{accountInfo.status === 1 ? t('customers.account.enabled') : t('customers.account.disabled')}
</span>
</div>
<div className="flex flex-wrap gap-2 pt-2">
<button type="button" className="px-3 py-2 text-sm rounded-lg border border-slate-200 app-foreground hover:bg-slate-50 disabled:opacity-60" disabled={accountSaving} onClick={() => void toggleAccount()}>
{accountInfo.status === 1 ? t('customers.account.disable') : t('customers.account.enable')}
</button>
<button type="button" className="px-3 py-2 text-sm rounded-lg border border-slate-200 app-foreground hover:bg-slate-50 disabled:opacity-60" disabled={accountSaving} onClick={() => void resetAccountPassword()}>
{t('customers.account.reset')}
</button>
</div>
</div>
) : (
<div className="space-y-3">
<input className="app-input w-full" placeholder={t('customers.account.phone')} value={accountForm.phone} onChange={(e) => setAccountForm((f) => ({ ...f, phone: e.target.value }))} />
<input className="app-input w-full" placeholder={t('customers.account.username')} value={accountForm.username} onChange={(e) => setAccountForm((f) => ({ ...f, username: e.target.value }))} />
<input className="app-input w-full" type="password" placeholder={t('customers.account.passwordOptional')} value={accountForm.password} onChange={(e) => setAccountForm((f) => ({ ...f, password: e.target.value }))} />
<button type="button" className="app-button-primary w-full" disabled={accountSaving} onClick={() => void createAccount()}>
{t('customers.account.create')}
</button>
</div>
)}
</div>
</DialogOverlay>
) : null}
<BulkImportModal
open={showImportModal}
title={t('customers.import.title')}
+1
View File
@@ -68,6 +68,7 @@ const MASTER_DATA_GROUP_LABEL = '基础数据';
/** 基础数据分组默认顺序(含显示名覆盖) */
const MASTER_DATA_CANONICAL_ITEMS: NavSecondaryItemConfig[] = [
{ menuKey: 'customers-list', visible: true },
{ menuKey: 'customers-mall', visible: true },
{ menuKey: 'products-skus', visible: true },
{ menuKey: 'products-categories', visible: true },
{ menuKey: 'customers-quote-versions', label: '报价管理', visible: true },
+1 -1
View File
@@ -27,7 +27,7 @@ interface StoredSidebarMenu {
* ⇒ 不加就会出现"代码已按主系统模板收敛,用户界面仍是旧的 11 个顶层"。
* v2 = 2026-10-27 按主系统模板收敛(顶层只留 数据看板/订单录入 + 业务流程/基础数据/财务结算/系统管理)。
*/
export const LAYOUT_TEMPLATE_VERSION = 'v2';
export const LAYOUT_TEMPLATE_VERSION = 'v3';
const SESSION_STORAGE_KEY = 'nav-sidebar-menu-cache-v2';
+32
View File
@@ -6170,6 +6170,38 @@ export async function importMallRowsApi(customerCode: string, rows: unknown[]) {
});
}
export type CustomerOrderAccount = {
user_id: string;
customer_code: string;
username: string;
phone: string | null;
status: number;
created_at: string | null;
};
export async function createCustomerOrderLoginAccountApi(customerCode: string, body: Record<string, unknown>) {
return workflowFetch<{ data: { user_id: string; username: string; default_password?: string | null; created: boolean; upgraded?: boolean } }>(
`/customers/${encodeURIComponent(customerCode)}/login-account`,
{ method: 'POST', body: JSON.stringify(body) }
);
}
export async function listCustomerOrderAccountsApi(codes: string[]) {
return workflowFetch<{ data: Record<string, CustomerOrderAccount> }>(
`/customers/login-accounts?codes=${encodeURIComponent(codes.join(','))}`
);
}
export async function setCustomerOrderAccountStatusApi(userId: string, status: number) {
return workflowFetch<{ data: { user_id: string; status: number } }>(
`/customers/login-accounts/${encodeURIComponent(userId)}/status`,
{ method: 'PATCH', body: JSON.stringify({ status }) }
);
}
export async function resetCustomerOrderAccountPasswordApi(userId: string) {
return workflowFetch<{ data: { user_id: string; default_password: string } }>(
`/customers/login-accounts/${encodeURIComponent(userId)}/reset-password`,
{ method: 'POST', body: JSON.stringify({}) }
);
}
export async function createCustomerRecipientApi(body: Record<string, unknown>) {
return workflowFetch<{ data: unknown }>('/customers/recipients', { method: 'POST', body: JSON.stringify(body) });
}