Compare commits

..

2 Commits

Author SHA1 Message Date
liufumingren
fec1dd9f55 chore: update consume progress 2026-04-17 19:23:49 +08:00
liufumingren
622869787a feat: sync workspace changes 2026-04-17 19:21:57 +08:00
62 changed files with 6029 additions and 119 deletions

6
app.js
View File

@ -25,18 +25,18 @@ module.exports = app => {
app.logger.info('⚠️ skipping OrderDelivery/OrderItems factory init: app.model not available');
return;
}
try {
const OrderItemsFactory = require('./app/model/order_items_factory');
app.model.OrderDeliveryFactory = app.OrderDeliveryFactory;
app.OrderItemsFactory = OrderItemsFactory(app);
app.model.OrderItemsFactory = app.OrderItemsFactory;
app.logger.info('✅ 工厂类初始化完成');
//await ensureOrderDeliverySelfCheck(app);
// await ensureOrderDeliverySelfCheck(app);
} catch (error) {
app.logger.error('❌ 工厂类初始化失败:', error);
}
// 验证缓存方法
if (typeof app.setCacheAsync === 'function') {
await app.setCacheAsync('system', 'wms', 10);

View File

@ -18,9 +18,19 @@ class HomeController extends Controller {
const {
ctx,
} = this;
const result = await ctx.service.systems.poloApi.test();
ctx.body = result;
// 获取get参数
const platid = ctx.params.platid;
const result = await ctx.service.systems.poloApi.test(platid);
ctx.body = JSON.parse(result);
}
async PoloApiGetWayBillCondition() {
const {
ctx,
} = this;
// 获取get参数
const platid = ctx.params.platid;
const result = await ctx.service.systems.poloApi.GetWayBillCondition(platid);
ctx.body = JSON.parse(result);
}
async index() {
const {

View File

@ -26,7 +26,8 @@ class PoloApiClient {
* 优先读取应用级缓存;缓存未命中或读取失败时,再回源数据库。
* 数据库查到配置后,会回写到应用级缓存,缓存 TTL 为 1 小时。
*
* @returns {Promise<object|null>} PolyAPI 配置记录。
* @param platid
* @return {Promise<object|null>} PolyAPI 配置记录。
*/
async getConfig(platid) {
if (this._config) {
@ -48,7 +49,8 @@ class PoloApiClient {
/**
* 读取 PolyAPI 配置:先查缓存,未命中则查数据库。
*
* @returns {Promise<object|null>} PolyAPI 配置记录。
* @param platid
* @return {Promise<object|null>} PolyAPI 配置记录。
*/
async _loadConfig(platid) {
const cachedConfig = await this._getCachedConfig(platid);
@ -69,7 +71,8 @@ class PoloApiClient {
*
* 缓存读取失败时,返回 null 并由调用方继续回源数据库。
*
* @returns {Promise<object|null>} 缓存中的配置记录。
* @param platid
* @return {Promise<object|null>} 缓存中的配置记录。
*/
async _getCachedConfig(platid) {
if (!this.ctx.app || typeof this.ctx.app.getCacheAsync !== 'function') {
@ -90,7 +93,8 @@ class PoloApiClient {
/**
* 查询数据库中的 PolyAPI 配置。
*
* @returns {Promise<object|null>} 数据库中的配置记录。
* @param platid
* @return {Promise<object|null>} 数据库中的配置记录。
*/
async _loadConfigFromDatabase(platid) {
if (!this.ctx.app || !this.ctx.app.model || !this.ctx.app.model.ExpressPlatform || typeof this.ctx.app.model.ExpressPlatform.findOne !== 'function') {
@ -98,7 +102,7 @@ class PoloApiClient {
}
return await this.ctx.app.model.ExpressPlatform.findOne({
where: { platid: platid },
where: { platid },
});
}
@ -106,7 +110,7 @@ class PoloApiClient {
* 将 PolyAPI 配置写回应用级缓存。
*
* @param {object} config - PolyAPI 配置记录。
* @returns {Promise<void>}
* @return {Promise<void>}
*/
async _setCachedConfig(config) {
if (!this.ctx.app || typeof this.ctx.app.setCacheAsync !== 'function') {
@ -130,7 +134,7 @@ class PoloApiClient {
* @param {string} options.method - 远端接口方法名。
* @param {number|string} options.platid - 平台 ID。
* @param {object|string} [options.bizcontent={}] - 业务参数内容。
* @returns {Promise<any>} 接口响应 data。
* @return {Promise<any>} 接口响应 data。
*/
async request(options = {}) {
const {
@ -139,9 +143,10 @@ class PoloApiClient {
bizcontent = {},
} = options;
const config = await this.getConfig(platid);
let config = await this.getConfig(platid);
if (!config) {
throw new Error('未找到 polyapi 配置');
// throw new Error('未找到 polyapi 配置');
config = await this.getConfig(633);
}
const signMap = this._buildSignMap(config, method, platid, bizcontent);
@ -165,6 +170,10 @@ class PoloApiClient {
/**
* 组装签名所需的请求参数。
* @param config
* @param method
* @param platid
* @param bizcontent
*/
_buildSignMap(config, method, platid, bizcontent) {
const normalizedBizcontent = bizcontent && typeof bizcontent === 'object'
@ -185,6 +194,8 @@ class PoloApiClient {
/**
* 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。
* @param signMap
* @param secret
*/
_getSignText(signMap, secret) {
let sb = '' + secret;
@ -197,6 +208,8 @@ class PoloApiClient {
/**
* MD5 摘要。
* @param text
* @param encoding
*/
_md5(text, encoding = 'utf8') {
return crypto.createHash('md5').update(text, encoding).digest('hex');
@ -204,6 +217,7 @@ class PoloApiClient {
/**
* 将参数编码为 application/x-www-form-urlencoded。
* @param map
*/
_encodeForm(map) {
const params = new URLSearchParams();
@ -216,6 +230,7 @@ class PoloApiClient {
/**
* 格式化日期 → yyyy-MM-dd HH:mm:ss。
* @param date
*/
_formatDate(date) {
const pad = n => (n < 10 ? '0' + n : n);
@ -225,6 +240,9 @@ class PoloApiClient {
/**
* 格式化取件日期。
* @param year
* @param month
* @param day
*/
_formatPickupDate(year, month, day) {
const pad = n => (n < 10 ? '0' + n : n);

View File

@ -1,7 +1,7 @@
'use strict';
module.exports = app => {
const { STRING } = app.Sequelize;
const { STRING, JSON } = app.Sequelize;
const Express = app.model.define('express', {
code: {
@ -15,11 +15,27 @@ module.exports = app => {
allowNull: true,
comment: '快递名称',
},
polyapi_code: {
type: STRING(255),
allowNull: true,
comment: '聚合接口编码',
},
polyapi_extra_info: {
type: JSON,
allowNull: true,
comment: '聚合接口扩展信息',
},
pdd_code: {
type: STRING(255),
allowNull: true,
comment: '拼多多编码',
},
}, {
tableName: 'wms_express',
freezeTableName: true,
underscored: true,
timestamps: false,
paranoid: false,
comment: '快递基础信息表',
});

View File

@ -0,0 +1,132 @@
'use strict';
module.exports = app => {
const { INTEGER, STRING, BIGINT, TINYINT } = app.Sequelize;
const ExpressInterface = app.model.define('express_interface', {
id: {
type: INTEGER(11).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
name: {
type: STRING(255),
allowNull: true,
comment: '接口名称',
},
express_code: {
type: STRING(255),
allowNull: true,
comment: '快递编码',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '仓库编码',
},
platform_code: {
type: STRING(20),
allowNull: true,
comment: '平台id',
},
express_platform_id: {
type: INTEGER(11),
allowNull: true,
comment: '快递接口id',
},
sender_name: {
type: STRING(50),
allowNull: true,
comment: '寄件人',
},
sender_tel: {
type: STRING(11),
allowNull: true,
comment: '寄件电话',
},
weight: {
type: INTEGER(11),
allowNull: true,
comment: '排序',
},
token: {
type: STRING(500),
allowNull: true,
comment: '令牌',
},
viewer: {
type: STRING(50),
allowNull: true,
comment: '验视员',
},
client_id: {
type: STRING(50),
allowNull: true,
comment: '客户id',
},
is_share: {
type: TINYINT(1),
allowNull: true,
defaultValue: 0,
comment: '是否分享接口',
},
share_id: {
type: INTEGER(11).UNSIGNED,
allowNull: true,
comment: '分享id',
},
can_use_count: {
type: INTEGER(11),
allowNull: true,
defaultValue: 0,
comment: '可用数量',
},
province_name: {
type: STRING(255),
allowNull: true,
comment: '寄件人名称',
},
city_name: {
type: STRING(255),
allowNull: true,
comment: '寄件人城市',
},
district_name: {
type: STRING(255),
allowNull: true,
comment: '寄件人区/县',
},
site_code: {
type: STRING(255),
allowNull: true,
comment: '网点编码',
},
product_type: {
type: STRING(50),
allowNull: true,
comment: '产品编码',
},
shop_name: {
type: STRING(255),
allowNull: true,
comment: '平台店铺',
},
}, {
tableName: 'wms_express_interface',
freezeTableName: true,
underscored: true,
timestamps: false,
paranoid: false,
comment: '快递接口配置表',
indexes: [
{
name: 'idx_warehouse_id',
fields: [ 'warehouse_id' ],
},
],
});
return ExpressInterface;
};

View File

@ -26,10 +26,10 @@ module.exports = app => {
allowNull: false,
comment: '接口名称',
},
interface_url_jd: {
type: STRING(500),
platid: {
type: STRING(20),
allowNull: true,
comment: '京东接口URL',
comment: '菠萝派平台id',
},
appkey: {
type: STRING(100),
@ -39,7 +39,7 @@ module.exports = app => {
app_secret: {
type: STRING(255),
allowNull: true,
field: 'AppSecret',
field: 'app_secret',
comment: '应用密钥',
},
token: {
@ -53,7 +53,7 @@ module.exports = app => {
comment: '接口版本',
},
}, {
tableName: 'wms_express_interface',
tableName: 'wms_express_platform',
freezeTableName: true,
underscored: true,
timestamps: false,
@ -72,4 +72,4 @@ module.exports = app => {
});
return ExpressPlatform;
};
};

View File

@ -0,0 +1,44 @@
'use strict';
/**
* 定义快递产品类型模型。
* @param {Object} app Egg 应用对象。
* @return {Object} 快递产品类型模型。
*/
module.exports = app => {
const { INTEGER, STRING } = app.Sequelize;
const ExpressProductType = app.model.define('express_product_type', {
id: {
type: INTEGER(11).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
name: {
type: STRING(255),
allowNull: true,
comment: '产品名称',
},
express_code: {
type: STRING(50),
allowNull: true,
comment: '物流编码',
},
code: {
type: STRING(50),
allowNull: true,
comment: '产品编码',
},
}, {
tableName: 'wms_express_product_type',
freezeTableName: true,
underscored: true,
timestamps: false,
paranoid: false,
comment: '快递产品类型表',
});
return ExpressProductType;
};

View File

@ -13,17 +13,22 @@ module.exports = app => {
},
express_code: {
type: STRING(50),
allowNull: true,
comment: '快递编码',
allowNull: false,
comment: '系统快递编码',
},
code: {
type: STRING(50),
allowNull: true,
comment: '设置项编码',
allowNull: false,
comment: '自设编码',
},
name: {
type: STRING(50),
allowNull: false,
comment: '别名',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
allowNull: false,
comment: '仓库主体ID',
},
}, {

View File

@ -1,7 +1,7 @@
'use strict';
module.exports = app => {
const { BIGINT, STRING, DATE, ENUM } = app.Sequelize;
const { BIGINT, STRING, DATE, ENUM, INTEGER, TINYINT } = app.Sequelize;
const OrderExpress = app.model.define('order_express', {
id: {
@ -17,7 +17,7 @@ module.exports = app => {
comment: '运单号',
},
order_id: {
type: BIGINT(20).UNSIGNED,
type: BIGINT(20),
allowNull: true,
comment: '订单ID',
},
@ -71,6 +71,22 @@ module.exports = app => {
allowNull: true,
comment: '平台编码',
},
business_key: {
type: INTEGER(3),
allowNull: true,
comment: '业务键',
},
status: {
type: TINYINT(1),
allowNull: true,
defaultValue: 0,
comment: '状态',
},
retry_count: {
type: TINYINT(3),
allowNull: true,
comment: '重试次数',
},
}, {
tableName: 'wms_order_express',
freezeTableName: true,
@ -79,8 +95,17 @@ module.exports = app => {
comment: '订单快递信息表',
indexes: [
{
name: 'idx_order_id',
fields: [ 'order_id' ],
name: 'uk_order_id_business_key',
unique: true,
fields: [ 'order_id', 'business_key' ],
},
{
name: 'idx_waybill_code',
fields: [ 'waybill_code' ],
},
{
name: 'idx_create_at',
fields: [ 'create_at' ],
},
],
});

View File

@ -125,4 +125,4 @@ module.exports = app => {
};
return Picking;
};
};

View File

@ -1,9 +1,14 @@
'use strict';
/**
* 平台设置模型定义。
*
* @param {Egg.Application} app 应用实例
* @return {Object} 平台设置模型
*/
module.exports = app => {
const { STRING, BIGINT, INTEGER } = app.Sequelize;
// 修改这里的变量名,与文件名一致
const PlatformSetting = app.model.define('platform_setting', {
id: {
type: INTEGER(11),
@ -22,6 +27,11 @@ module.exports = app => {
allowNull: false,
comment: '设置代码',
},
name: {
type: STRING(100),
allowNull: false,
comment: '别名',
},
warehouse_id: {
type: BIGINT(20),
allowNull: false,
@ -34,33 +44,40 @@ module.exports = app => {
comment: '平台设置表',
indexes: [
{
name: 'platform_code',
name: 'uk_platform_setting_warehouse_platform_code',
unique: true,
fields: [ 'platform_code', 'warehouse_id' ],
},
{
name: 'warehouse_id',
name: 'uk_platform_setting_warehouse_code',
unique: true,
fields: [ 'code', 'warehouse_id' ],
},
{
name: 'idx_platform_setting_warehouse_id',
fields: [ 'warehouse_id' ],
},
],
});
// 定义关联关系
/**
* 定义平台设置关联关系。
*/
PlatformSetting.associate = function() {
const { Store, Platform } = app.model;
// 关联仓库
PlatformSetting.belongsTo(Platform, {
foreignKey: 'platform_code',
targetKey: 'code',
as: 'platform',
});
// 关联仓库
PlatformSetting.belongsTo(Store, {
foreignKey: 'warehouse_id',
targetKey: 'id',
as: 'warehouse',
});
};
// 返回正确的变量名
return PlatformSetting;
};

View File

@ -191,22 +191,22 @@ module.exports = app => {
type: INTEGER(11).UNSIGNED,
defaultValue: 0,
},
inbound_min_days:{
inbound_min_days: {
type: INTEGER(11),
defaultValue: 0,
comment: '入库最小天数要求',
},
outbound_min_days:{
outbound_min_days: {
type: INTEGER(11),
defaultValue: 0,
comment: '出库最小天数要求',
},
shelf_life_days:{
shelf_life_days: {
type: INTEGER(11),
defaultValue: 0,
comment: '保质期天数',
},
remaining_threshold_days:{
remaining_threshold_days: {
type: INTEGER(11),
defaultValue: 0,
comment: '剩余有效期阈值天数',

View File

@ -569,13 +569,13 @@ module.exports = app => {
app.model.Express && typeof app.model.Express.findAll === 'function'
? app.model.Express.findAll({
attributes: [ 'code', 'name' ],
order: [ [ 'code', 'ASC' ] ],
order: [[ 'code', 'ASC' ]],
})
: Promise.resolve([]),
app.model.Platform && typeof app.model.Platform.findAll === 'function'
? app.model.Platform.findAll({
attributes: [ 'code', 'name' ],
order: [ [ 'code', 'ASC' ] ],
order: [[ 'code', 'ASC' ]],
})
: Promise.resolve([]),
]);

View File

@ -35,7 +35,8 @@ module.exports = app => {
router.get('/__temp/file-writer/consume', controller.tempFileWriter.consume);
// Polo API 测试入口
router.get('/testPoloApi', controller.home.testPoloApi);
router.get('/testPoloApi/:platid', controller.home.testPoloApi);
router.get('/PoloApiGetWayBillCondition/:platid', controller.home.PoloApiGetWayBillCondition);
// 测试接口
router.get('/testSendData', controller.home.testSendData);

View File

@ -11,9 +11,9 @@ class indexService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'getI18nMessage,putI18nCollect';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getPlatformList,recognizeLicensePlate';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
const _noNeedLog = '*';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getPlatformList,recognizeLicensePlate';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async fastWhereTree(data) {
@ -423,6 +423,20 @@ class indexService extends MainService {
return this.success('ok', { data: result, code: 200 });
}
/**
* 获取快递产品类型列表。
*
* @param {Object} data 请求参数
* @param {string} [data.express_code] 快递公司编码
* @return {Promise<Object>} 返回结果
*/
async getExpressProductTypeList(data) {
const { service } = this;
const { express_code: expressCode = '' } = data || {};
const result = await service.systems.express.getExpressProductTypeList(expressCode);
return this.success('ok', { data: result, code: 200 });
}
async getPlatformList() {
const { service } = this;
const result = await service.systems.platform.getPlatformList();

View File

@ -44,4 +44,4 @@ class StorageAllocationService extends OrderBaseService {
}
}
module.exports = StorageAllocationService;
module.exports = StorageAllocationService;

View File

@ -0,0 +1,171 @@
'use strict';
const MainService = require('../../main');
class expressService extends MainService {
/**
* 初始化快递映射模块的权限配置。
*
* @param {Egg.Context} ctx 上下文对象
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,listBase,create,checkCodeUnique,update';
const _noNeedLog = '*';
const _noNeedAuth = 'list,listBase,create,checkCodeUnique,update';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 调用快递映射系统服务。
*
* @param {string} methodName 系统服务方法名
* @param {Object} data 请求参数
* @param {string} defaultMessage 默认错误信息
* @return {Promise<Object>} 统一返回结果
*/
async callSystemExpress(methodName, data, defaultMessage) {
const { service } = this;
try {
const result = await service.systems.setting.express[methodName](data);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || defaultMessage, {
code: Number(error.code) || 500,
});
}
}
/**
* 获取快递映射列表。
*
* @param {Object} data 请求参数
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} 列表结果
*/
async list(data = {}) {
const { service } = this;
const {
where = {},
pagination: inputPagination,
page,
page_size: pageSize,
pageSize: camelPageSize,
...rest
} = data || {};
const pagination = {
...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}),
};
if (page !== undefined) {
pagination.page = page;
}
const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize;
if (resolvedPageSize !== undefined) {
pagination.pageSize = resolvedPageSize;
}
const payload = {
...rest,
where,
pagination,
};
this.prepareWhereContext(payload, {
specialFieldMap: {
id: {
field: 'id',
},
code: {
field: 'code',
},
name: {
field: 'name',
},
express_code: {
field: 'express_code',
},
quickWhere: {
bucket: 'quick',
},
},
});
try {
const result = await service.systems.setting.express.list(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '获取快递映射列表失败', {
code: Number(error.code) || 500,
});
}
}
/**
* 获取系统快递编码和名称列表。
*
* @return {Promise<Object>} 基础快递列表结果
*/
async listBase() {
return await this.callSystemExpress('listBase', {}, '获取系统快递基础列表失败');
}
/**
* 创建快递映射。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 创建结果
*/
async create(data = {}) {
const { code, name, express_code: expressCode, expressCode: camelExpressCode, ...rest } = data || {};
const payload = {
...rest,
code,
name,
express_code: expressCode !== undefined ? expressCode : camelExpressCode,
};
return await this.callSystemExpress('create', payload, '创建快递映射失败');
}
/**
* 校验快递编码是否已被占用。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 校验结果
*/
async checkCodeUnique(data = {}) {
const { id, code, ...rest } = data || {};
const payload = {
...rest,
id,
code,
};
return await this.callSystemExpress('checkCodeUnique', payload, '校验快递编码失败');
}
/**
* 修改快递映射。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 修改结果
*/
async update(data = {}) {
const { id, code, name, express_code: expressCode, expressCode: camelExpressCode, ...rest } = data || {};
const payload = {
...rest,
id,
code,
name,
express_code: expressCode !== undefined ? expressCode : camelExpressCode,
};
return await this.callSystemExpress('update', payload, '更新快递映射失败');
}
}
module.exports = expressService;

View File

@ -0,0 +1,230 @@
'use strict';
const MainService = require('../../main');
class expressInterfaceService extends MainService {
/**
* 初始化快递接口管理模块的权限配置。
*
* @param {Egg.Context} ctx 上下文对象
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,create,update,delete';
const _noNeedLog = '*';
const _noNeedAuth = 'list,create,update,delete';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 调用快递接口系统服务。
*
* @param {string} methodName 系统服务方法名
* @param {Object} data 请求参数
* @param {string} defaultMessage 默认错误信息
* @return {Promise<Object>} 统一返回结果
*/
async callSystemExpressInterface(methodName, data, defaultMessage) {
const { service } = this;
try {
const result = await service.systems.setting.expressInterface[methodName](data);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || defaultMessage, {
code: Number(error.code) || 500,
});
}
}
/**
* 获取快递接口列表。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 列表结果
*/
async list(data = {}) {
const {
where = {},
pagination: inputPagination,
page,
page_size: pageSize,
pageSize: camelPageSize,
...rest
} = data || {};
const pagination = {
...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}),
};
if (page !== undefined) {
pagination.page = page;
}
const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize;
if (resolvedPageSize !== undefined) {
pagination.pageSize = resolvedPageSize;
}
const payload = {
...rest,
where,
pagination,
};
this.prepareWhereContext(payload, {
specialFieldMap: {
id: {
field: 'id',
},
name: {
field: 'name',
},
express_code: {
field: 'express_code',
},
platform_code: {
field: 'platform_code',
},
express_platform_id: {
field: 'express_platform_id',
},
sender_name: {
field: 'sender_name',
},
sender_tel: {
field: 'sender_tel',
},
viewer: {
field: 'viewer',
},
client_id: {
field: 'client_id',
},
share_id: {
field: 'share_id',
},
site_code: {
field: 'site_code',
},
product_type: {
field: 'product_type',
},
shop_name: {
field: 'shop_name',
},
quickWhere: {
bucket: 'quick',
},
},
});
return await this.callSystemExpressInterface('list', payload, '获取快递接口列表失败');
}
/**
* 创建快递接口。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 创建结果
*/
async create(data = {}) {
const {
name,
express_code: expressCode,
expressCode: camelExpressCode,
platform_code: platformCode,
platformCode: camelPlatformCode,
express_platform_id: expressPlatformId,
expressPlatformId: camelExpressPlatformId,
...rest
} = data || {};
const payload = {
...rest,
};
if (name !== undefined) {
payload.name = name;
}
if (expressCode !== undefined || camelExpressCode !== undefined) {
payload.express_code = expressCode !== undefined ? expressCode : camelExpressCode;
}
if (platformCode !== undefined || camelPlatformCode !== undefined) {
payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode;
}
if (expressPlatformId !== undefined || camelExpressPlatformId !== undefined) {
payload.express_platform_id = expressPlatformId !== undefined ? expressPlatformId : camelExpressPlatformId;
}
return await this.callSystemExpressInterface('create', payload, '创建快递接口失败');
}
/**
* 修改快递接口。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 修改结果
*/
async update(data = {}) {
const {
id,
interface_id: interfaceId,
interfaceId: camelInterfaceId,
name,
express_code: expressCode,
expressCode: camelExpressCode,
platform_code: platformCode,
platformCode: camelPlatformCode,
express_platform_id: expressPlatformId,
expressPlatformId: camelExpressPlatformId,
...rest
} = data || {};
const payload = {
...rest,
};
payload.id = id !== undefined ? id : (interfaceId !== undefined ? interfaceId : camelInterfaceId);
if (name !== undefined) {
payload.name = name;
}
if (expressCode !== undefined || camelExpressCode !== undefined) {
payload.express_code = expressCode !== undefined ? expressCode : camelExpressCode;
}
if (platformCode !== undefined || camelPlatformCode !== undefined) {
payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode;
}
if (expressPlatformId !== undefined || camelExpressPlatformId !== undefined) {
payload.express_platform_id = expressPlatformId !== undefined ? expressPlatformId : camelExpressPlatformId;
}
return await this.callSystemExpressInterface('update', payload, '更新快递接口失败');
}
/**
* 删除快递接口。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 删除结果
*/
async delete(data = {}) {
const {
id,
interface_id: interfaceId,
interfaceId: camelInterfaceId,
...rest
} = data || {};
const payload = {
...rest,
};
payload.id = id !== undefined ? id : (interfaceId !== undefined ? interfaceId : camelInterfaceId);
return await this.callSystemExpressInterface('delete', payload, '删除快递接口失败');
}
}
module.exports = expressInterfaceService;

View File

@ -0,0 +1,186 @@
'use strict';
const MainService = require('../../main');
class platformService extends MainService {
/**
* 初始化平台设置模块的权限配置。
*
* @param {Egg.Context} ctx 上下文对象
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,create,update,delete';
const _noNeedLog = '*';
const _noNeedAuth = 'list,create,update,delete';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 调用平台设置系统服务。
*
* @param {string} methodName 系统服务方法名
* @param {Object} data 请求参数
* @param {string} defaultMessage 默认错误信息
* @return {Promise<Object>} 统一返回结果
*/
async callSystemPlatform(methodName, data, defaultMessage) {
const { service } = this;
try {
const result = await service.systems.setting.platform[methodName](data);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || defaultMessage, {
code: Number(error.code) || 500,
});
}
}
/**
* 获取平台设置列表。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 列表结果
*/
async list(data = {}) {
const {
where = {},
pagination: inputPagination,
page,
page_size: pageSize,
pageSize: camelPageSize,
...rest
} = data || {};
const pagination = {
...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}),
};
if (page !== undefined) {
pagination.page = page;
}
const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize;
if (resolvedPageSize !== undefined) {
pagination.pageSize = resolvedPageSize;
}
const payload = {
...rest,
where,
pagination,
};
this.prepareWhereContext(payload, {
specialFieldMap: {
id: {
field: 'id',
},
code: {
field: 'code',
},
name: {
field: 'name',
},
platform_code: {
field: 'platform_code',
},
quickWhere: {
bucket: 'quick',
},
},
});
return await this.callSystemPlatform('list', payload, '获取平台设置列表失败');
}
/**
* 创建平台设置。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 创建结果
*/
async create(data = {}) {
const {
code,
name,
platform_code: platformCode,
platformCode: camelPlatformCode,
...rest
} = data || {};
const payload = {
...rest,
code,
name,
platform_code: platformCode !== undefined ? platformCode : camelPlatformCode,
};
return await this.callSystemPlatform('create', payload, '创建平台设置失败');
}
/**
* 修改平台设置。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 修改结果
*/
async update(data = {}) {
const {
id,
setting_id: settingId,
settingId: camelSettingId,
code,
name,
platform_code: platformCode,
platformCode: camelPlatformCode,
...rest
} = data || {};
const payload = {
...rest,
};
payload.id = id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId);
if (code !== undefined) {
payload.code = code;
}
if (name !== undefined) {
payload.name = name;
}
if (platformCode !== undefined || camelPlatformCode !== undefined) {
payload.platform_code = platformCode !== undefined ? platformCode : camelPlatformCode;
}
return await this.callSystemPlatform('update', payload, '更新平台设置失败');
}
/**
* 删除平台设置。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 删除结果
*/
async delete(data = {}) {
const {
id,
setting_id: settingId,
settingId: camelSettingId,
...rest
} = data || {};
const payload = {
...rest,
id: id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId),
};
return await this.callSystemPlatform('delete', payload, '删除平台设置失败');
}
}
module.exports = platformService;

View File

@ -94,20 +94,83 @@ class DeliveryOrderService extends Service {
return String(option.name || option.label || option.code || option.value || '').trim();
}
/**
* 按平台码解析平台列表项,优先基础平台,再匹配平台设置。
*
* @param {Array<Object>} platformList 平台列表。
* @param {string} platformCode 平台编码。
* @return {Object|null} 匹配到的平台项。
*/
findPlatformOptionByCode(platformList, platformCode) {
const normalizedCode = String(platformCode || '').trim();
if (!normalizedCode || !Array.isArray(platformList)) {
return null;
}
const basePlatform = platformList.find(item => item
&& !item.is_system_setting
&& String(item.code || item.value || '').trim() === normalizedCode) || null;
if (basePlatform) {
return basePlatform;
}
return platformList.find(item => item
&& item.is_system_setting
&& String(item.code || item.value || '').trim() === normalizedCode) || null;
}
/**
* 获取平台快照里的系统平台码。
*
* @param {Object} option 平台项。
* @param {string} fallbackCode 兜底编码。
* @return {string} 系统平台码。
*/
getPlatformSnapshotCode(option, fallbackCode = '') {
return String(option && (option.platform_code || option.code || option.value || fallbackCode) || '').trim();
}
/**
* 获取平台快照里的系统平台名称。
*
* @param {Object} option 平台项。
* @return {string} 系统平台名称。
*/
getPlatformSnapshotName(option) {
if (!option || typeof option !== 'object') {
return '';
}
return String(option.platform_name || option.name || option.label || option.code || option.value || '').trim();
}
/**
* 解析平台快照。
*
* 优先级:
* 1. 直接匹配 wms_platform.code;
* 2. 再按 wms_platfrom_setting.code 读取平台映射;
* 3. 最后才回退货主默认平台 code。
*
* @param {string} sourcePlatformCode 外部平台编码。
* @param {Object} storeSubjectConfig 货主签约配置。
* @param {Object} [info={}] 上下文信息。
* @return {Promise<Object>} 平台快照。
*/
async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}) {
const platformList = await this.ctx.service.systems.platform.getPlatformList();
const externalCode = String(sourcePlatformCode || '').trim();
const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim();
const matchedPlatform = this.findCodeOption(platformList, externalCode);
const matchedPlatform = this.findPlatformOptionByCode(platformList, externalCode);
if (matchedPlatform) {
return {
sysPlatformCode: String(matchedPlatform.code || matchedPlatform.value || externalCode).trim(),
sysPlatformName: this.getOptionName(matchedPlatform),
sysPlatformCode: this.getPlatformSnapshotCode(matchedPlatform, externalCode),
sysPlatformName: this.getPlatformSnapshotName(matchedPlatform),
};
}
const fallbackPlatform = this.findCodeOption(platformList, defaultCode);
const fallbackPlatform = this.findPlatformOptionByCode(platformList, defaultCode);
if (fallbackPlatform) {
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid platform code fallback to store default', {
deliveryOrderCode: info.deliveryOrderCode,
@ -118,8 +181,8 @@ class DeliveryOrderService extends Service {
});
return {
sysPlatformCode: String(fallbackPlatform.code || fallbackPlatform.value || defaultCode).trim(),
sysPlatformName: this.getOptionName(fallbackPlatform),
sysPlatformCode: this.getPlatformSnapshotCode(fallbackPlatform, defaultCode),
sysPlatformName: this.getPlatformSnapshotName(fallbackPlatform),
};
}
@ -137,6 +200,58 @@ class DeliveryOrderService extends Service {
};
}
/**
* 通过快递设置表解析系统快递编码。
*
* 说明:wms_express_setting 以 `code` 作为匹配键,以 `express_code` 作为系统快递编码。
* 由于该表带有 `warehouse_id` 作用域,这里优先按 `warehouse_id + code` 进行限定查询,
* 命中后直接返回对应的系统快递编码。
*
* @param {string} logisticsCode 外部快递编码。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<string>} 系统快递编码,未命中时返回空字符串。
*/
async resolveExpressCodeFromSetting(logisticsCode, warehouseId) {
const normalizedLogisticsCode = String(logisticsCode || '').trim();
if (!normalizedLogisticsCode) {
return '';
}
const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting;
if (!expressSettingModel || typeof expressSettingModel.findOne !== 'function') {
return '';
}
const where = {
code: normalizedLogisticsCode,
};
const normalizedWarehouseId = Number(warehouseId || 0);
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
where.warehouse_id = normalizedWarehouseId;
}
const expressSetting = await expressSettingModel.findOne({
attributes: [ 'express_code' ],
where,
raw: true,
});
return String(expressSetting && expressSetting.express_code || '').trim();
}
/**
* 解析订单快递快照。
*
* 优先级:
* 1. 直接匹配 wms_express.code;
* 2. 再按 wms_express_setting.code + warehouse_id 读取 express_code 映射为系统快递编码;
* 3. 最后才回退货主默认 express code。
*
* @param {string} logisticsCode 外部快递编码。
* @param {Object} storeSubjectConfig 货主签约配置。
* @param {Object} [info={}] 上下文信息。
* @return {Promise<Object>} 快递快照。
*/
async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}) {
const expressList = await this.ctx.service.systems.express.getExpressList();
const externalCode = String(logisticsCode || '').trim();
@ -145,11 +260,35 @@ class DeliveryOrderService extends Service {
if (matchedExpress) {
return {
sysLogisticsCode: String(matchedExpress.code || matchedExpress.value || externalCode).trim(),
sysLogisticsCode: String(matchedExpress.express_code || matchedExpress.code || matchedExpress.value || externalCode).trim(),
sysLogisticsName: this.getOptionName(matchedExpress),
};
}
const expressSettingCode = await this.resolveExpressCodeFromSetting(externalCode, info.warehouseId);
if (expressSettingCode) {
const fallbackExpress = this.findCodeOption(expressList, expressSettingCode);
if (fallbackExpress) {
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to express setting mapping', {
deliveryOrderCode: info.deliveryOrderCode,
warehouseId: info.warehouseId,
storeId: info.storeId,
logisticsCode: externalCode,
expressSettingCode,
});
return {
sysLogisticsCode: String(fallbackExpress.express_code || fallbackExpress.code || fallbackExpress.value || expressSettingCode).trim(),
sysLogisticsName: this.getOptionName(fallbackExpress),
};
}
return {
sysLogisticsCode: expressSettingCode,
sysLogisticsName: '',
};
}
const fallbackExpress = this.findCodeOption(expressList, defaultCode);
if (fallbackExpress) {
this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to store default', {
@ -161,7 +300,7 @@ class DeliveryOrderService extends Service {
});
return {
sysLogisticsCode: String(fallbackExpress.code || fallbackExpress.value || defaultCode).trim(),
sysLogisticsCode: String(fallbackExpress.express_code || fallbackExpress.code || fallbackExpress.value || defaultCode).trim(),
sysLogisticsName: this.getOptionName(fallbackExpress),
};
}

View File

@ -3,12 +3,226 @@
const { Service } = require('egg');
const DEFAULT_CACHE_TTL_SECONDS = 600;
const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60;
class ExpressService extends Service {
getExpressListCacheKey() {
/**
* 生成快递列表缓存键。
*
* @param {number|string} warehouseId 仓库ID
* @return {string} 缓存键
*/
getExpressListCacheKey(warehouseId = 0) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
return `express:list:${normalizedWarehouseId}`;
}
return 'express:list';
}
/**
* 获取当前上下文中的仓库ID。
*
* @return {number} 仓库ID,未获取到时返回 0
*/
getCurrentWarehouseId() {
const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0);
if (Number.isFinite(warehouseId) && warehouseId > 0) {
return warehouseId;
}
return 0;
}
/**
* 生成合并后的快递项展示名称。
*
* @param {string} settingCode 快递设置编码
* @param {Object} expressItem 系统快递项
* @return {string} 展示名称
*/
buildMergedExpressLabel(settingCode, expressItem) {
const normalizedSettingCode = String(settingCode || '').trim();
const expressName = String(expressItem && (expressItem.name || expressItem.label || expressItem.code || expressItem.value) || '').trim();
if (!normalizedSettingCode) {
return expressName;
}
if (!expressName) {
return normalizedSettingCode;
}
return `${normalizedSettingCode} (${expressName})`;
}
/**
* 规范化快递设置记录。
*
* @param {Object} row 数据库记录
* @param {Map<string, Object>} expressMap 系统快递映射
* @return {Object|null} 规范化后的记录
*/
normalizeExpressSettingRow(row, expressMap) {
if (!row || typeof row !== 'object') {
return null;
}
const code = String(row.code || '').trim();
if (!code) {
return null;
}
const expressCode = String(row.express_code || '').trim();
const expressItem = expressMap instanceof Map ? expressMap.get(expressCode) : null;
const label = this.buildMergedExpressLabel(code, expressItem);
return {
code,
name: label,
value: code,
label,
is_system_setting: true,
id: row.id === undefined || row.id === null ? null : row.id,
alias: String(row.name || '').trim(),
express_code: String((expressItem && (expressItem.code || expressItem.value)) || expressCode || '').trim(),
};
}
/**
* 从数据库加载快递设置列表。
*
* @param {number|string} warehouseId 仓库ID
* @return {Promise<Array>} 快递设置列表
*/
async loadExpressSettingListFromDatabase(warehouseId = 0) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return [];
}
const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting;
if (!expressSettingModel || typeof expressSettingModel.findAll !== 'function') {
return [];
}
const rows = await expressSettingModel.findAll({
attributes: [ 'id', 'code', 'name', 'express_code' ],
where: {
warehouse_id: normalizedWarehouseId,
},
order: [[ 'code', 'ASC' ]],
raw: true,
});
if (!Array.isArray(rows)) {
return [];
}
return rows;
}
/**
* 合并系统快递和快递设置列表。
*
* @param {Array<Object>} expressList 系统快递列表
* @param {Array<Object>} expressSettingList 快递设置列表
* @return {Array<Object>} 合并后的快递列表
*/
buildMergedExpressList(expressList, expressSettingList) {
const mergedList = [];
const seenCodeMap = new Set();
const normalizedExpressList = Array.isArray(expressList) ? expressList : [];
const expressMap = new Map();
for (const expressItem of normalizedExpressList) {
if (!expressItem || typeof expressItem !== 'object') {
continue;
}
const code = String(expressItem.code || expressItem.value || '').trim();
if (!code) {
continue;
}
if (!expressMap.has(code)) {
expressMap.set(code, expressItem);
}
}
for (const expressItem of normalizedExpressList) {
if (!expressItem || typeof expressItem !== 'object') {
continue;
}
const code = String(expressItem.code || expressItem.value || '').trim();
if (!code || seenCodeMap.has(code)) {
continue;
}
mergedList.push(expressItem);
seenCodeMap.add(code);
}
for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) {
const mergedItem = this.normalizeExpressSettingRow(row, expressMap);
if (!mergedItem || seenCodeMap.has(mergedItem.code)) {
continue;
}
mergedList.push(mergedItem);
seenCodeMap.add(mergedItem.code);
}
return mergedList;
}
/**
* 生成快递产品类型列表缓存键。
*
* @param {string} expressCode 快递公司编码
* @return {string} 缓存键
*/
getExpressProductTypeListCacheKey(expressCode = '') {
const normalizedExpressCode = String(expressCode || '').trim();
if (!normalizedExpressCode) {
return 'express:product-type:list';
}
return `express:product-type:list:${normalizedExpressCode}`;
}
/**
* 规范化快递产品类型记录。
*
* @param {Object} row 数据库记录
* @return {Object|null} 规范化后的记录
*/
normalizeExpressProductTypeRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
const code = String(row.code || '').trim();
if (!code) {
return null;
}
const name = String(row.name || '').trim();
return {
code,
express_code: String(row.express_code || '').trim(),
name,
value: code,
label: name || code,
};
}
normalizeExpressRow(row) {
if (!row || typeof row !== 'object') {
return null;
@ -24,6 +238,9 @@ class ExpressService extends Service {
name: String(row.name || '').trim(),
value: code,
label: String(row.name || code).trim(),
is_system_setting: false,
id: null,
alias: null,
};
}
@ -43,8 +260,58 @@ class ExpressService extends Service {
.filter(Boolean);
}
/**
* 获取系统快递编码和名称列表。
*
* 该接口只返回系统基础快递数据,不合并仓库自定义映射。
*
* @return {Promise<Array>} 系统快递编码和名称列表
*/
async getSystemExpressList() {
return await this.loadExpressListFromDatabase();
}
/**
* 从数据库加载快递产品类型列表。
*
* @param {string} expressCode 快递公司编码
* @return {Promise<Array>} 快递产品类型列表
*/
async loadExpressProductTypeListFromDatabase(expressCode = '') {
const normalizedExpressCode = String(expressCode || '').trim();
const query = {
attributes: [ 'code', 'name', 'express_code' ],
order: [[ 'express_code', 'ASC' ], [ 'code', 'ASC' ]],
raw: true,
};
if (normalizedExpressCode) {
query.where = {
express_code: normalizedExpressCode,
};
}
const rows = await this.ctx.model.ExpressProductType.findAll(query);
if (!Array.isArray(rows)) {
return [];
}
return rows
.map(row => this.normalizeExpressProductTypeRow(row))
.filter(Boolean);
}
/**
* 获取快递列表。
*
* 先读取系统快递,再按当前仓库合并快递设置;同一编码只保留一条记录。
*
* @return {Promise<Array>} 快递列表
*/
async getExpressList() {
const cacheKey = this.getExpressListCacheKey();
const warehouseId = this.getCurrentWarehouseId();
const cacheKey = this.getExpressListCacheKey(warehouseId);
try {
const cachedList = await this.app.getCacheAsync(cacheKey);
@ -52,10 +319,15 @@ class ExpressService extends Service {
return Array.isArray(cachedList) ? cachedList : [];
}
const expressList = await this.loadExpressListFromDatabase();
await this.app.setCacheAsync(cacheKey, expressList, DEFAULT_CACHE_TTL_SECONDS);
const [ expressList, expressSettingList ] = await Promise.all([
this.loadExpressListFromDatabase(),
this.loadExpressSettingListFromDatabase(warehouseId),
]);
return expressList;
const mergedList = this.buildMergedExpressList(expressList, expressSettingList);
await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_CACHE_TTL_SECONDS);
return mergedList;
} catch (error) {
this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', {
error: error.message,
@ -64,6 +336,169 @@ class ExpressService extends Service {
throw error;
}
}
/**
* 获取快递产品类型列表。
*
* @param {string} expressCode 快递公司编码
* @return {Promise<Array>} 快递产品类型列表
*/
async getExpressProductTypeList(expressCode = '') {
const cacheKey = this.getExpressProductTypeListCacheKey(expressCode);
const normalizedExpressCode = String(expressCode || '').trim();
try {
const cachedList = await this.app.getCacheAsync(cacheKey);
if (cachedList !== null && cachedList !== undefined) {
return Array.isArray(cachedList) ? cachedList : [];
}
const expressProductTypeList = await this.loadExpressProductTypeListFromDatabase(normalizedExpressCode);
await this.app.setCacheAsync(cacheKey, expressProductTypeList, DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS);
return expressProductTypeList;
} catch (error) {
this.ctx.logger.error('[ExpressService.getExpressProductTypeList] 获取快递产品类型失败', {
error: error.message,
stack: error.stack,
expressCode: normalizedExpressCode,
});
throw error;
}
}
/**
* 处理订单快递记录。
* 先按订单ID和业务键筛选 wms_order_express,再排除已存在且状态不为 0 的记录,
* 对可重试记录重置 retry_count,并为缺失记录补插状态为 0 的快递记录。
*
* @param {Array<Object>} orders 订单与业务键列表。
* @param {number} orders[].order_id 订单ID。
* @param {number} orders[].business_key 业务键。
* @return {Promise<Object>} 处理后的订单列表与运单号列表。
*/
async createWaybillCode(orders = []) {
const { app, ctx } = this;
const { Op } = app.Sequelize;
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
if (!orderExpressModel
|| typeof orderExpressModel.findAll !== 'function'
|| typeof orderExpressModel.update !== 'function'
|| typeof orderExpressModel.bulkCreate !== 'function') {
throw new Error('订单快递模型未初始化');
}
// orders 入参去重归一化。
const normalizedOrderMap = new Map();
for (const order of Array.isArray(orders) ? orders : []) {
const orderId = Number(order && order.order_id);
const businessKey = Number(order && order.business_key);
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) {
continue;
}
const orderKey = `${orderId}:${businessKey}`;
if (!normalizedOrderMap.has(orderKey)) {
normalizedOrderMap.set(orderKey, {
order_id: orderId,
business_key: businessKey,
});
}
}
const normalizedOrders = Array.from(normalizedOrderMap.values());
if (normalizedOrders.length === 0) {
return {
orders: [],
waybill_codes: [],
};
}
// 事务开始。
return await app.model.transaction(async transaction => {
// 事务内批量查询已有记录。
const existingRows = await orderExpressModel.findAll({
where: {
[Op.or]: normalizedOrders.map(order => ({
order_id: order.order_id,
business_key: order.business_key,
})),
},
attributes: [ 'id', 'order_id', 'business_key', 'status', 'retry_count' ],
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
const existingMap = new Map();
const retryIds = [];
for (const row of Array.isArray(existingRows) ? existingRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) {
continue;
}
const orderKey = `${orderId}:${businessKey}`;
existingMap.set(orderKey, row);
// 过滤 status != 0 的已存在记录。
if (Number(row && row.status) === 0) {
retryIds.push(row.id);
}
}
// 重置可重试记录 retry_count=0。
const retryableIds = Array.from(new Set(retryIds.filter(id => Number.isFinite(Number(id)) && Number(id) > 0)));
if (retryableIds.length > 0) {
await orderExpressModel.update({
retry_count: 0,
}, {
where: {
id: {
[Op.in]: retryableIds,
},
},
transaction,
});
}
// 组装待插入记录。
const rowsToCreate = [];
for (const order of normalizedOrders) {
const orderKey = `${order.order_id}:${order.business_key}`;
const existingRow = existingMap.get(orderKey);
if (existingRow) {
const status = Number(existingRow.status);
if (status !== 0) {
continue;
}
continue;
}
rowsToCreate.push({
order_id: order.order_id,
business_key: order.business_key,
status: 0,
retry_count: 0,
});
}
// 批量插入 status=0 的新记录。
if (rowsToCreate.length > 0) {
await orderExpressModel.bulkCreate(rowsToCreate, {
transaction,
});
}
return {
orders: normalizedOrders,
waybill_codes: [],
};
});
}
}
module.exports = ExpressService;
module.exports = ExpressService;

View File

@ -633,4 +633,4 @@ class OrderStorageAllocationService extends MainService {
}
}
module.exports = OrderStorageAllocationService;
module.exports = OrderStorageAllocationService;

View File

@ -4,10 +4,65 @@ const Service = require('egg').Service;
const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600;
class PlatformService extends Service {
getPlatformListCacheKey() {
/**
* 获取当前上下文中的仓库ID。
*
* @return {number} 仓库ID,未获取到时返回 0。
*/
getCurrentWarehouseId() {
const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0);
if (Number.isFinite(warehouseId) && warehouseId > 0) {
return warehouseId;
}
return 0;
}
/**
* 生成平台列表缓存键。
*
* @param {number|string} warehouseId 仓库ID。
* @return {string} 缓存键。
*/
getPlatformListCacheKey(warehouseId = 0) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
return `platform:list:${normalizedWarehouseId}`;
}
return 'platform:list';
}
/**
* 生成平台设置项展示名称。
*
* @param {string} settingCode 平台设置编码。
* @param {Object} platformItem 系统平台项。
* @return {string} 展示名称。
*/
buildMergedPlatformLabel(settingCode, platformItem) {
const normalizedSettingCode = String(settingCode || '').trim();
const platformName = String(platformItem && (platformItem.name || platformItem.label || platformItem.code || platformItem.value) || '').trim();
if (!normalizedSettingCode) {
return platformName;
}
if (!platformName) {
return normalizedSettingCode;
}
return `${normalizedSettingCode} (${platformName})`;
}
/**
* 规范化系统平台记录。
*
* @param {Object} row 数据库记录。
* @return {Object|null} 规范化后的记录。
*/
normalizePlatformRow(row) {
if (!row || typeof row !== 'object') {
return null;
@ -27,9 +82,135 @@ class PlatformService extends Service {
default_express_interface: defaultExpressInterface,
value: code,
label: name || code,
platform_code: code,
platform_name: name,
is_system_setting: false,
};
}
/**
* 从数据库加载当前仓库的平台设置列表。
*
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Array>} 平台设置列表。
*/
async loadPlatformSettingListFromDatabase(warehouseId = 0) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return [];
}
const platformSettingModel = this.ctx.model && this.ctx.model.PlatformSetting;
if (!platformSettingModel || typeof platformSettingModel.findAll !== 'function') {
return [];
}
const rows = await platformSettingModel.findAll({
attributes: [ 'id', 'code', 'platform_code', 'warehouse_id' ],
where: {
warehouse_id: normalizedWarehouseId,
},
order: [[ 'code', 'ASC' ]],
raw: true,
});
if (!Array.isArray(rows)) {
return [];
}
return rows;
}
/**
* 规范化平台设置记录。
*
* @param {Object} row 数据库记录。
* @param {Map<string, Object>} platformMap 系统平台映射。
* @return {Object|null} 规范化后的记录。
*/
normalizePlatformSettingRow(row, platformMap) {
if (!row || typeof row !== 'object') {
return null;
}
const code = String(row.code || '').trim();
if (!code) {
return null;
}
const platformCode = String(row.platform_code || '').trim();
const platformItem = platformMap instanceof Map ? platformMap.get(platformCode) : null;
const label = this.buildMergedPlatformLabel(code, platformItem);
return {
code,
name: label,
value: code,
label,
is_system_setting: true,
id: row.id === undefined || row.id === null ? null : row.id,
alias: '',
platform_code: String((platformItem && (platformItem.code || platformItem.value)) || platformCode || '').trim(),
platform_name: String((platformItem && (platformItem.name || platformItem.label || platformItem.value)) || '').trim(),
default_express_interface: String((platformItem && platformItem.default_express_interface) || '').trim(),
};
}
/**
* 合并基础平台列表和平台设置列表。
*
* @param {Array<Object>} platformList 系统平台列表。
* @param {Array<Object>} platformSettingList 平台设置列表。
* @return {Array<Object>} 合并后的平台列表。
*/
buildMergedPlatformList(platformList, platformSettingList) {
const mergedList = [];
const seenCodeMap = new Set();
const normalizedPlatformList = Array.isArray(platformList) ? platformList : [];
const platformMap = new Map();
for (const platformItem of normalizedPlatformList) {
if (!platformItem || typeof platformItem !== 'object') {
continue;
}
const code = String(platformItem.code || platformItem.value || '').trim();
if (!code) {
continue;
}
if (!platformMap.has(code)) {
platformMap.set(code, platformItem);
}
}
for (const platformItem of normalizedPlatformList) {
if (!platformItem || typeof platformItem !== 'object') {
continue;
}
const code = String(platformItem.code || platformItem.value || '').trim();
if (!code || seenCodeMap.has(code)) {
continue;
}
mergedList.push(platformItem);
seenCodeMap.add(code);
}
for (const row of Array.isArray(platformSettingList) ? platformSettingList : []) {
const mergedItem = this.normalizePlatformSettingRow(row, platformMap);
if (!mergedItem || seenCodeMap.has(mergedItem.code)) {
continue;
}
mergedList.push(mergedItem);
seenCodeMap.add(mergedItem.code);
}
return mergedList;
}
async loadPlatformListFromDatabase() {
const rows = await this.ctx.model.Platform.findAll({
attributes: [ 'code', 'name', 'default_express_interface' ],
@ -46,8 +227,16 @@ class PlatformService extends Service {
.filter(Boolean);
}
/**
* 获取平台列表。
*
* 先读取系统平台,再按当前仓库合并平台设置;同一编码只保留一条记录。
*
* @return {Promise<Array>} 平台列表。
*/
async getPlatformList() {
const cacheKey = this.getPlatformListCacheKey();
const warehouseId = this.getCurrentWarehouseId();
const cacheKey = this.getPlatformListCacheKey(warehouseId);
try {
const cachedList = await this.app.getCacheAsync(cacheKey);
@ -55,10 +244,15 @@ class PlatformService extends Service {
return Array.isArray(cachedList) ? cachedList : [];
}
const platformList = await this.loadPlatformListFromDatabase();
await this.app.setCacheAsync(cacheKey, platformList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS);
const [ platformList, platformSettingList ] = await Promise.all([
this.loadPlatformListFromDatabase(),
this.loadPlatformSettingListFromDatabase(warehouseId),
]);
return platformList;
const mergedList = this.buildMergedPlatformList(platformList, platformSettingList);
await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS);
return mergedList;
} catch (error) {
this.ctx.logger.error('[PlatformService.getPlatformList] 获取平台列表失败', {
error: error.message,

View File

@ -15,20 +15,23 @@ class PoloApiService extends Service {
/**
* 测试 Polo API 请求并返回请求结果。
*
* @returns {Promise<any>} request() 的返回结果。
* @param platid
* @return {Promise<any>} request() 的返回结果。
*/
async test() {
async test(platid) {
return this.client.request({
method: 'Differ.JH.LogisticsPlatFeatures',
platid: 556,
platid,
bizcontent: {},
});
}
async test2() {
async GetWayBillCondition(platid) {
return this.client.request({
method: 'Differ.JH.LogisticsPlatFeatures',
platid: 556,
bizcontent: {},
method: 'Differ.JH.Logistics.GetWayBillCondition',
platid,
bizcontent: {
cpcode: 'POSTB',
},
});
}
/**
@ -38,7 +41,7 @@ class PoloApiService extends Service {
* @param {string} [options.express_id=''] - 快手平台对应的承运商编码。
* @param {object} [options.wmsOrder={}] - WMS 订单信息。
* @param {object} [options.expressConfig={}] - 发件方与店铺配置。
* @returns {Promise<any>} 接口响应 data。
* @return {Promise<any>} 接口响应 data。
*/
async kuaishou(options = {}) {
const {
@ -80,7 +83,7 @@ class PoloApiService extends Service {
const shoptype = 'JH_001';
const sourceIdText = String(sourceId || '');
const sourceOrderCodeText = String(sourceOrderCode || '');
const [senderArea = '', senderTown = ''] = String(districtName || '').split(';');
const [ senderArea = '', senderTown = '' ] = String(districtName || '').split(';');
const mobile = tempMobile || tel || '';
const cpcode = express_id || '';
const txLogisticID = sourceIdText.replace(/_/g, '');
@ -144,7 +147,7 @@ class PoloApiService extends Service {
tel: senderTel,
province: provinceName,
},
shipperno: ['p22', 'p35', 'p10'].includes(postcode) ? siteCode : clientId,
shipperno: [ 'p22', 'p35', 'p10' ].includes(postcode) ? siteCode : clientId,
sitecode: siteCode || '',
Inputsite: siteCode || '',
transtype: '0',
@ -164,7 +167,7 @@ class PoloApiService extends Service {
method,
platid,
bizcontent: {
orders: [order],
orders: [ order ],
shoptype,
},
});

View File

@ -0,0 +1,530 @@
'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
class SettingExpressService extends Service {
/**
* 创建业务错误对象。
*
* @param {string} message 错误信息
* @param {number} [code=500] 错误码
* @return {Error} 错误对象
*/
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 获取当前仓库主体ID。
*
* @return {number} 当前仓库主体ID
*/
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作快递映射', 400);
}
return storeId;
}
/**
* 规范化文本值。
*
* @param {string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} [maxLength=255] 最大长度
* @return {string} 规范化后的文本
*/
normalizeText(value, fieldName, maxLength = 255) {
if (value === undefined || value === null) {
return '';
}
const normalized = String(value).trim();
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化编码值。
*
* @param {string} value 原始值
* @param {string} [fieldName='code'] 字段名称
* @param {number} [maxLength=50] 最大长度
* @return {string} 规范化后的编码
*/
normalizeCode(value, fieldName = 'code', maxLength = 50) {
return this.normalizeText(value, fieldName, maxLength).toUpperCase();
}
/**
* 规范化分页参数。
*
* @param {number|string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} defaultValue 默认值
* @param {number} maxValue 最大值
* @return {number} 规范化后的分页值
*/
normalizePage(value, fieldName, defaultValue, maxValue) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (!Number.isFinite(num) || num <= 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.min(Math.floor(num), maxValue);
}
/**
* 返回 where 字段映射。
*
* @return {Object} where 字段映射
*/
getListWhereSpecialFieldMap() {
return {
id: {
field: 'id',
},
code: {
field: 'code',
},
name: {
field: 'name',
},
express_code: {
field: 'express_code',
},
quickWhere: {
bucket: 'quick',
},
};
}
/**
* 获取系统快递列表。
*
* @return {Promise<Array>} 系统快递列表
*/
async getSystemExpressList() {
const systemExpressService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.express;
if (!systemExpressService || typeof systemExpressService.getSystemExpressList !== 'function') {
return [];
}
return await systemExpressService.getSystemExpressList();
}
/**
* 构建系统快递映射表。
*
* @return {Promise<Map<string, Object>>} 系统快递映射表
*/
async getSystemExpressMap() {
const expressList = await this.getSystemExpressList();
const expressMap = new Map();
for (const expressItem of Array.isArray(expressList) ? expressList : []) {
if (!expressItem || typeof expressItem !== 'object') {
continue;
}
const code = String(expressItem.code || expressItem.value || '').trim().toUpperCase();
if (!code) {
continue;
}
if (!expressMap.has(code)) {
expressMap.set(code, {
code,
name: String(expressItem.name || expressItem.label || '').trim(),
});
}
}
return expressMap;
}
/**
* 规范化映射记录。
*
* @param {Object} row 数据库记录
* @param {Map<string, Object>} expressMap 系统快递映射表
* @return {Object|null} 规范化后的记录
*/
normalizeSettingRow(row, expressMap) {
if (!row || typeof row !== 'object') {
return null;
}
const code = String(row.code || '').trim().toUpperCase();
if (!code) {
return null;
}
const expressCode = String(row.express_code || '').trim().toUpperCase();
const expressInfo = expressMap instanceof Map ? expressMap.get(expressCode) : null;
return {
id: row.id === undefined || row.id === null ? null : Number(row.id),
warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id),
code,
name: String(row.name || '').trim(),
express_code: expressCode,
express_name: expressInfo ? expressInfo.name : '',
express_label: expressInfo ? expressInfo.name : '',
};
}
/**
* 查找当前仓库下的映射记录。
*
* @param {number} id 映射ID
* @return {Promise<Object>} 映射记录
*/
async findSettingById(id) {
const { ctx } = this;
const setting = await ctx.model.ExpressSetting.findOne({
where: {
id,
warehouse_id: this.getCurrentStoreId(),
},
});
if (!setting) {
throw this.createError('快递映射不存在或无权限操作', 404);
}
return setting;
}
/**
* 查找同仓下的编码冲突记录。
*
* @param {string} code 映射编码
* @param {number|null} [excludeId=null] 排除的记录ID
* @return {Promise<Object|null>} 冲突记录
*/
async findCodeConflict(code, excludeId = null) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const where = {
warehouse_id: this.getCurrentStoreId(),
code,
};
const normalizedExcludeId = Number(excludeId || 0);
if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) {
where.id = {
[Op.ne]: normalizedExcludeId,
};
}
return await ctx.model.ExpressSetting.findOne({
where,
attributes: [ 'id', 'code' ],
});
}
/**
* 校验系统快递编码是否存在。
*
* @param {string} expressCode 系统快递编码
* @param {Map<string, Object>} [expressMap] 系统快递映射表
* @return {Promise<Object>} 系统快递信息
*/
async ensureSystemExpressExists(expressCode, expressMap = null) {
const normalizedExpressCode = this.normalizeCode(expressCode, 'express_code');
const resolvedMap = expressMap instanceof Map ? expressMap : await this.getSystemExpressMap();
const expressInfo = resolvedMap.get(normalizedExpressCode);
if (!expressInfo) {
throw this.createError('系统快递编码不存在', 400);
}
return expressInfo;
}
/**
* 校验同仓编码是否可用。
*
* @param {string} code 映射编码
* @param {number|null} [excludeId=null] 排除的记录ID
* @return {Promise<boolean>} 是否可用
*/
async ensureCodeAvailable(code, excludeId = null) {
const conflict = await this.findCodeConflict(code, excludeId);
if (conflict) {
throw this.createError('快递编码已被当前仓库使用', 409);
}
return true;
}
/**
* 解析列表查询条件。
*
* @param {Object} data 请求参数
* @return {Object} 查询条件信息
*/
resolveListWhere(data = {}) {
const { ctx, app } = this;
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? { ...ctx.where }
: (data.where && typeof data.where === 'object' ? { ...data.where } : {});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: this.getListWhereSpecialFieldMap(),
});
if (!parsed.ok) {
throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400);
}
parsedResult = parsed.result;
}
return {
normalizedWhere,
parsedResult,
};
}
/**
* 查询映射列表。
*
* @param {Object} data 请求参数
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} 分页结果
*/
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentStoreId = this.getCurrentStoreId();
const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {};
const pageSource = pagination.page !== undefined ? pagination.page : data.page;
const pageSizeSource = pagination.pageSize !== undefined
? pagination.pageSize
: (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize));
const page = this.normalizePage(pageSource, 'page', 1, 1000000);
const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const { normalizedWhere, parsedResult } = this.resolveListWhere(data);
const andConditions = [
{
warehouse_id: currentStoreId,
},
];
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: quickWhereInput;
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const keyword = String(quickWhereValue).trim();
andConditions.push({
[Op.or]: [
{ code: { [Op.like]: `%${keyword}%` } },
{ name: { [Op.like]: `%${keyword}%` } },
{ express_code: { [Op.like]: `%${keyword}%` } },
],
});
}
const [ expressMap, result ] = await Promise.all([
this.getSystemExpressMap(),
ctx.model.ExpressSetting.findAndCountAll({
where: {
[Op.and]: andConditions,
},
attributes: [ 'id', 'warehouse_id', 'code', 'name', 'express_code' ],
order: [[ 'id', 'DESC' ]],
offset,
limit: pageSize,
raw: true,
}),
]);
const list = Array.isArray(result && result.rows)
? result.rows.map(row => this.normalizeSettingRow(row, expressMap)).filter(Boolean)
: [];
return {
code: 200,
data: {
list,
total: Number(result && result.count ? result.count : 0),
page,
page_size: pageSize,
},
};
}
/**
* 查询系统快递编码和名称列表。
*
* @return {Promise<Object>} 系统快递列表
*/
async listBase() {
const list = await this.getSystemExpressList();
return {
code: 200,
data: list,
};
}
/**
* 检查编码是否已被占用。
*
* @param {Object} data 请求参数
* @param {number} [data.id] 编辑时的映射ID
* @param {string} data.code 映射编码
* @return {Promise<Object>} 唯一性校验结果
*/
async checkCodeUnique(data = {}) {
const code = this.normalizeCode(data.code, 'code');
if (!code) {
throw this.createError('code 参数不能为空', 400);
}
const excludeId = Number(data.id || 0);
const conflict = await this.findCodeConflict(code, excludeId);
return {
code: 200,
data: {
isUnique: !conflict,
message: conflict ? '快递编码已被当前仓库使用' : 'ok',
},
};
}
/**
* 创建快递映射。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 创建结果
*/
async create(data = {}) {
const { ctx } = this;
const currentStoreId = this.getCurrentStoreId();
const expressMap = await this.getSystemExpressMap();
const code = this.normalizeCode(data.code, 'code');
const name = this.normalizeText(data.name, 'name', 50);
const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code');
if (!code) {
throw this.createError('code 参数不能为空', 400);
}
if (!name) {
throw this.createError('name 参数不能为空', 400);
}
if (!expressCode) {
throw this.createError('express_code 参数不能为空', 400);
}
const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap);
await this.ensureCodeAvailable(code);
const created = await ctx.model.ExpressSetting.create({
warehouse_id: currentStoreId,
code,
name,
express_code: expressInfo.code,
});
return {
code: 200,
data: this.normalizeSettingRow(created.get ? created.get({ plain: true }) : created, expressMap),
};
}
/**
* 修改快递映射。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 修改结果
*/
async update(data = {}) {
const { ctx } = this;
const id = Number(data.id || data.setting_id || data.settingId || 0);
if (!Number.isFinite(id) || id <= 0) {
throw this.createError('id 参数不能为空', 400);
}
const setting = await this.findSettingById(id);
const hasCode = Object.prototype.hasOwnProperty.call(data, 'code');
const hasName = Object.prototype.hasOwnProperty.call(data, 'name');
const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code')
|| Object.prototype.hasOwnProperty.call(data, 'expressCode');
if (!hasCode && !hasName && !hasExpressCode) {
throw this.createError('至少需要提供一个可更新字段', 400);
}
const updates = {};
let expressMap = null;
if (hasCode) {
const code = this.normalizeCode(data.code, 'code');
if (!code) {
throw this.createError('code 参数不能为空', 400);
}
await this.ensureCodeAvailable(code, id);
updates.code = code;
}
if (hasName) {
const name = this.normalizeText(data.name, 'name', 50);
if (!name) {
throw this.createError('name 参数不能为空', 400);
}
updates.name = name;
}
if (hasExpressCode) {
expressMap = await this.getSystemExpressMap();
const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code');
if (!expressCode) {
throw this.createError('express_code 参数不能为空', 400);
}
const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap);
updates.express_code = expressInfo.code;
}
await setting.update(updates);
if (!expressMap) {
expressMap = await this.getSystemExpressMap();
}
return {
code: 200,
data: this.normalizeSettingRow(setting.get ? setting.get({ plain: true }) : setting, expressMap),
};
}
}
module.exports = SettingExpressService;

View File

@ -0,0 +1,774 @@
'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
class SettingExpressInterfaceService extends Service {
/**
* 创建业务错误对象。
*
* @param {string} message 错误信息
* @param {number} [code=500] 错误码
* @return {Error} 业务错误对象
*/
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 获取当前仓库主体 ID。
*
* @return {number} 当前仓库主体 ID
*/
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作快递接口', 400);
}
return storeId;
}
/**
* 规范化文本值。
*
* @param {string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} [maxLength=255] 最大长度
* @return {string} 规范化后的文本
*/
normalizeText(value, fieldName, maxLength = 255) {
if (value === undefined || value === null) {
return '';
}
const normalized = String(value).trim();
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化可选文本值。
*
* @param {string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} [maxLength=255] 最大长度
* @return {string|null} 规范化后的文本
*/
normalizeOptionalText(value, fieldName, maxLength = 255) {
if (value === undefined || value === null) {
return null;
}
const normalized = String(value).trim();
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化整数值。
*
* @param {number|string} value 原始值
* @param {string} fieldName 字段名称
* @param {Object} [options] 额外选项
* @param {boolean} [options.allowEmpty=false] 是否允许空值
* @param {number|null} [options.min=null] 最小值
* @param {number|null} [options.max=null] 最大值
* @return {number|null} 规范化后的整数
*/
normalizeInteger(value, fieldName, options = {}) {
const {
allowEmpty = false,
min = null,
max = null,
} = options;
if (value === undefined || value === null || value === '') {
if (allowEmpty) {
return null;
}
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
const normalized = Number(value);
if (!Number.isInteger(normalized)) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (min !== null && normalized < min) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (max !== null && normalized > max) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return normalized;
}
/**
* 规范化布尔标记。
*
* @param {number|string} value 原始值
* @param {string} fieldName 字段名称
* @param {number|null} [defaultValue=null] 默认值
* @return {number|null} 规范化后的标记
*/
normalizeFlag(value, fieldName, defaultValue = null) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const normalized = Number(value);
if (normalized === 0 || normalized === 1) {
return normalized;
}
throw this.createError(`${fieldName} 参数不合法`, 400);
}
/**
* 规范化分页参数。
*
* @param {number|string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} defaultValue 默认值
* @param {number} maxValue 最大值
* @return {number} 规范化后的分页值
*/
normalizePage(value, fieldName, defaultValue, maxValue) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const normalized = Number(value);
if (!Number.isFinite(normalized) || normalized <= 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.min(Math.floor(normalized), maxValue);
}
/**
* 获取列表查询字段映射。
*
* @return {Object} 字段映射
*/
getListWhereSpecialFieldMap() {
return {
id: {
field: 'id',
},
name: {
field: 'name',
},
express_code: {
field: 'express_code',
},
platform_code: {
field: 'platform_code',
},
express_platform_id: {
field: 'express_platform_id',
},
sender_name: {
field: 'sender_name',
},
sender_tel: {
field: 'sender_tel',
},
viewer: {
field: 'viewer',
},
client_id: {
field: 'client_id',
},
share_id: {
field: 'share_id',
},
site_code: {
field: 'site_code',
},
product_type: {
field: 'product_type',
},
shop_name: {
field: 'shop_name',
},
quickWhere: {
bucket: 'quick',
},
};
}
/**
* 解析列表查询条件。
*
* @param {Object} data 请求参数
* @return {Object} 查询条件信息
*/
resolveListWhere(data = {}) {
const { ctx, app } = this;
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? { ...ctx.where }
: (data.where && typeof data.where === 'object' ? { ...data.where } : {});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: this.getListWhereSpecialFieldMap(),
});
if (!parsed.ok) {
throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400);
}
parsedResult = parsed.result;
}
return {
normalizedWhere,
parsedResult,
};
}
/**
* 规范化快递接口记录。
*
* @param {Object} row 数据库记录
* @return {Object|null} 规范化后的记录
*/
normalizeInterfaceRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
return {
id: row.id === undefined || row.id === null ? null : Number(row.id),
name: this.normalizeOptionalText(row.name, 'name', 255),
express_code: this.normalizeOptionalText(row.express_code, 'express_code', 255),
warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id),
platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20),
express_platform_id: row.express_platform_id === undefined || row.express_platform_id === null ? null : Number(row.express_platform_id),
sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50),
sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11),
weight: row.weight === undefined || row.weight === null ? null : Number(row.weight),
token: this.normalizeOptionalText(row.token, 'token', 500),
viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50),
client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50),
is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share),
share_id: row.share_id === undefined || row.share_id === null ? null : Number(row.share_id),
can_use_count: row.can_use_count === undefined || row.can_use_count === null ? null : Number(row.can_use_count),
province_name: this.normalizeOptionalText(row.province_name, 'province_name', 255),
city_name: this.normalizeOptionalText(row.city_name, 'city_name', 255),
district_name: this.normalizeOptionalText(row.district_name, 'district_name', 255),
site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255),
product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50),
shop_name: this.normalizeOptionalText(row.shop_name, 'shop_name', 255),
};
}
/**
* 查找当前仓库下的快递接口记录。
*
* @param {number} id 接口 ID
* @return {Promise<Object>} 接口记录
*/
async findInterfaceById(id) {
const { ctx } = this;
const currentStoreId = this.getCurrentStoreId();
const setting = await ctx.model.ExpressInterface.findOne({
where: {
id,
warehouse_id: currentStoreId,
},
});
if (!setting) {
throw this.createError('快递接口不存在或无权限操作', 404);
}
return setting;
}
/**
* 查找同仓下的快递编码冲突记录。
*
* @param {string} expressCode 快递编码
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<Object|null>} 冲突记录
*/
async findCodeConflict(expressCode, excludeId = null) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const where = {
warehouse_id: this.getCurrentStoreId(),
express_code: expressCode,
};
const normalizedExcludeId = Number(excludeId || 0);
if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) {
where.id = {
[Op.ne]: normalizedExcludeId,
};
}
return await ctx.model.ExpressInterface.findOne({
where,
attributes: [ 'id', 'express_code' ],
});
}
/**
* 查找同仓下的平台接口冲突记录。
*
* @param {string} platformCode 平台代码
* @param {number} expressPlatformId 快递接口 ID
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<Object|null>} 冲突记录
*/
async findInterfaceConflict(platformCode, expressPlatformId, excludeId = null) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const where = {
warehouse_id: this.getCurrentStoreId(),
platform_code: platformCode,
express_platform_id: expressPlatformId,
};
const normalizedExcludeId = Number(excludeId || 0);
if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) {
where.id = {
[Op.ne]: normalizedExcludeId,
};
}
return await ctx.model.ExpressInterface.findOne({
where,
attributes: [ 'id', 'platform_code', 'express_platform_id' ],
});
}
/**
* 校验快递编码是否可用。
*
* @param {string} expressCode 快递编码
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<boolean>} 是否可用
*/
async ensureCodeAvailable(expressCode, excludeId = null) {
const conflict = await this.findCodeConflict(expressCode, excludeId);
if (conflict) {
throw this.createError('快递编码已被当前仓库使用', 409);
}
return true;
}
/**
* 校验平台接口组合是否可用。
*
* @param {string} platformCode 平台代码
* @param {number} expressPlatformId 快递接口 ID
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<boolean>} 是否可用
*/
async ensureInterfaceAvailable(platformCode, expressPlatformId, excludeId = null) {
const conflict = await this.findInterfaceConflict(platformCode, expressPlatformId, excludeId);
if (conflict) {
throw this.createError('当前平台和快递接口组合已被使用', 409);
}
return true;
}
/**
* 获取快递接口列表。
*
* @param {Object} data 请求参数
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} 分页结果
*/
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentStoreId = this.getCurrentStoreId();
const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {};
const pageSource = pagination.page !== undefined ? pagination.page : data.page;
const pageSizeSource = pagination.pageSize !== undefined
? pagination.pageSize
: (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize));
const page = this.normalizePage(pageSource, 'page', 1, 1000000);
const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const { normalizedWhere, parsedResult } = this.resolveListWhere(data);
const andConditions = [
{
warehouse_id: currentStoreId,
},
];
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: quickWhereInput;
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const keyword = String(quickWhereValue).trim();
andConditions.push({
[Op.or]: [
{ name: { [Op.like]: `%${keyword}%` } },
{ express_code: { [Op.like]: `%${keyword}%` } },
{ platform_code: { [Op.like]: `%${keyword}%` } },
{ sender_name: { [Op.like]: `%${keyword}%` } },
{ sender_tel: { [Op.like]: `%${keyword}%` } },
{ viewer: { [Op.like]: `%${keyword}%` } },
{ client_id: { [Op.like]: `%${keyword}%` } },
{ province_name: { [Op.like]: `%${keyword}%` } },
{ city_name: { [Op.like]: `%${keyword}%` } },
{ district_name: { [Op.like]: `%${keyword}%` } },
{ site_code: { [Op.like]: `%${keyword}%` } },
{ product_type: { [Op.like]: `%${keyword}%` } },
{ shop_name: { [Op.like]: `%${keyword}%` } },
],
});
}
const result = await ctx.model.ExpressInterface.findAndCountAll({
where: {
[Op.and]: andConditions,
},
attributes: [
'id', 'name', 'express_code', 'warehouse_id', 'platform_code', 'express_platform_id',
'sender_name', 'sender_tel', 'weight', 'token', 'viewer', 'client_id', 'is_share',
'share_id', 'can_use_count', 'province_name', 'city_name', 'district_name', 'site_code',
'product_type', 'shop_name',
],
order: [[ 'id', 'DESC' ]],
offset,
limit: pageSize,
raw: true,
});
const list = Array.isArray(result && result.rows)
? result.rows.map(row => this.normalizeInterfaceRow(row)).filter(Boolean)
: [];
return {
code: 200,
data: {
list,
total: Number(result && result.count ? result.count : 0),
page,
page_size: pageSize,
},
};
}
/**
* 创建快递接口。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 创建结果
*/
async create(data = {}) {
const { ctx } = this;
const currentStoreId = this.getCurrentStoreId();
const name = this.normalizeText(data.name, 'name', 255);
const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase();
const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase();
const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', {
min: 1,
});
if (!name) {
throw this.createError('name 参数不能为空', 400);
}
if (!expressCode) {
throw this.createError('express_code 参数不能为空', 400);
}
if (!platformCode) {
throw this.createError('platform_code 参数不能为空', 400);
}
if (!expressPlatformId) {
throw this.createError('express_platform_id 参数不能为空', 400);
}
await this.ensureCodeAvailable(expressCode);
await this.ensureInterfaceAvailable(platformCode, expressPlatformId);
const payload = {
warehouse_id: currentStoreId,
name,
express_code: expressCode,
platform_code: platformCode,
express_platform_id: expressPlatformId,
sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50),
sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11),
weight: this.normalizeInteger(data.weight, 'weight', {
allowEmpty: true,
}),
token: this.normalizeOptionalText(data.token, 'token', 500),
viewer: this.normalizeOptionalText(data.viewer, 'viewer', 50),
client_id: this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50),
is_share: this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0),
share_id: this.normalizeInteger(data.share_id || data.shareId, 'share_id', {
allowEmpty: true,
min: 1,
}),
can_use_count: this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', {
allowEmpty: true,
min: 0,
}),
province_name: this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255),
city_name: this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255),
district_name: this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255),
site_code: this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255),
product_type: this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50),
shop_name: this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255),
};
const created = await ctx.model.ExpressInterface.create(payload);
const plainCreated = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
return {
code: 200,
data: this.normalizeInterfaceRow(plainCreated),
};
}
/**
* 修改快递接口。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 修改结果
*/
async update(data = {}) {
const id = Number(data.id || data.interface_id || data.interfaceId || 0);
if (!Number.isInteger(id) || id <= 0) {
throw this.createError('id 参数不能为空', 400);
}
const setting = await this.findInterfaceById(id);
const hasName = Object.prototype.hasOwnProperty.call(data, 'name');
const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code')
|| Object.prototype.hasOwnProperty.call(data, 'expressCode');
const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code')
|| Object.prototype.hasOwnProperty.call(data, 'platformCode');
const hasExpressPlatformId = Object.prototype.hasOwnProperty.call(data, 'express_platform_id')
|| Object.prototype.hasOwnProperty.call(data, 'expressPlatformId');
const hasSenderName = Object.prototype.hasOwnProperty.call(data, 'sender_name')
|| Object.prototype.hasOwnProperty.call(data, 'senderName');
const hasSenderTel = Object.prototype.hasOwnProperty.call(data, 'sender_tel')
|| Object.prototype.hasOwnProperty.call(data, 'senderTel');
const hasWeight = Object.prototype.hasOwnProperty.call(data, 'weight');
const hasToken = Object.prototype.hasOwnProperty.call(data, 'token');
const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer');
const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id')
|| Object.prototype.hasOwnProperty.call(data, 'clientId');
const hasIsShare = Object.prototype.hasOwnProperty.call(data, 'is_share')
|| Object.prototype.hasOwnProperty.call(data, 'isShare');
const hasShareId = Object.prototype.hasOwnProperty.call(data, 'share_id')
|| Object.prototype.hasOwnProperty.call(data, 'shareId');
const hasCanUseCount = Object.prototype.hasOwnProperty.call(data, 'can_use_count')
|| Object.prototype.hasOwnProperty.call(data, 'canUseCount');
const hasProvinceName = Object.prototype.hasOwnProperty.call(data, 'province_name')
|| Object.prototype.hasOwnProperty.call(data, 'provinceName');
const hasCityName = Object.prototype.hasOwnProperty.call(data, 'city_name')
|| Object.prototype.hasOwnProperty.call(data, 'cityName');
const hasDistrictName = Object.prototype.hasOwnProperty.call(data, 'district_name')
|| Object.prototype.hasOwnProperty.call(data, 'districtName');
const hasSiteCode = Object.prototype.hasOwnProperty.call(data, 'site_code')
|| Object.prototype.hasOwnProperty.call(data, 'siteCode');
const hasProductType = Object.prototype.hasOwnProperty.call(data, 'product_type')
|| Object.prototype.hasOwnProperty.call(data, 'productType');
const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name')
|| Object.prototype.hasOwnProperty.call(data, 'shopName');
if (!hasName && !hasExpressCode && !hasPlatformCode && !hasExpressPlatformId && !hasSenderName
&& !hasSenderTel && !hasWeight && !hasToken && !hasViewer && !hasClientId && !hasIsShare
&& !hasShareId && !hasCanUseCount && !hasProvinceName && !hasCityName && !hasDistrictName
&& !hasSiteCode && !hasProductType && !hasShopName) {
throw this.createError('至少需要提供一个可更新字段', 400);
}
const updates = {};
let nextExpressCode = setting.express_code || '';
let nextPlatformCode = setting.platform_code || '';
let nextExpressPlatformId = setting.express_platform_id === undefined || setting.express_platform_id === null
? null
: Number(setting.express_platform_id);
if (hasName) {
const name = this.normalizeText(data.name, 'name', 255);
if (!name) {
throw this.createError('name 参数不能为空', 400);
}
updates.name = name;
}
if (hasExpressCode) {
const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase();
if (!expressCode) {
throw this.createError('express_code 参数不能为空', 400);
}
nextExpressCode = expressCode;
updates.express_code = expressCode;
}
if (hasPlatformCode) {
const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase();
if (!platformCode) {
throw this.createError('platform_code 参数不能为空', 400);
}
nextPlatformCode = platformCode;
updates.platform_code = platformCode;
}
if (hasExpressPlatformId) {
const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', {
min: 1,
});
if (!expressPlatformId) {
throw this.createError('express_platform_id 参数不能为空', 400);
}
nextExpressPlatformId = expressPlatformId;
updates.express_platform_id = expressPlatformId;
}
if (hasSenderName) {
updates.sender_name = this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50);
}
if (hasSenderTel) {
updates.sender_tel = this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11);
}
if (hasWeight) {
updates.weight = this.normalizeInteger(data.weight, 'weight', {
allowEmpty: true,
});
}
if (hasToken) {
updates.token = this.normalizeOptionalText(data.token, 'token', 500);
}
if (hasViewer) {
updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50);
}
if (hasClientId) {
updates.client_id = this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50);
}
if (hasIsShare) {
updates.is_share = this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0);
}
if (hasShareId) {
updates.share_id = this.normalizeInteger(data.share_id || data.shareId, 'share_id', {
allowEmpty: true,
min: 1,
});
}
if (hasCanUseCount) {
updates.can_use_count = this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', {
allowEmpty: true,
min: 0,
});
}
if (hasProvinceName) {
updates.province_name = this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255);
}
if (hasCityName) {
updates.city_name = this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255);
}
if (hasDistrictName) {
updates.district_name = this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255);
}
if (hasSiteCode) {
updates.site_code = this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255);
}
if (hasProductType) {
updates.product_type = this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50);
}
if (hasShopName) {
updates.shop_name = this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255);
}
if (Object.prototype.hasOwnProperty.call(updates, 'express_code')) {
await this.ensureCodeAvailable(nextExpressCode, id);
}
if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')
|| Object.prototype.hasOwnProperty.call(updates, 'express_platform_id')) {
await this.ensureInterfaceAvailable(nextPlatformCode, nextExpressPlatformId, id);
}
await setting.update(updates);
const plainSetting = setting && typeof setting.get === 'function'
? setting.get({ plain: true })
: setting;
return {
code: 200,
data: this.normalizeInterfaceRow(plainSetting),
};
}
/**
* 删除快递接口。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 删除结果
*/
async delete(data = {}) {
const id = Number(data.id || data.interface_id || data.interfaceId || 0);
if (!Number.isInteger(id) || id <= 0) {
throw this.createError('id 参数不能为空', 400);
}
const setting = await this.findInterfaceById(id);
const plainSetting = setting && typeof setting.get === 'function'
? setting.get({ plain: true })
: setting;
await setting.destroy();
return {
code: 200,
data: {
id: Number(plainSetting.id),
warehouse_id: Number(plainSetting.warehouse_id),
deleted: true,
},
};
}
}
module.exports = SettingExpressInterfaceService;

View File

@ -0,0 +1,638 @@
'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
class SettingPlatformService extends Service {
/**
* 创建业务错误对象。
*
* @param {string} message 错误信息
* @param {number} [code=500] 错误码
* @return {Error} 业务错误对象
*/
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 获取当前仓库主体 ID。
*
* @return {number} 当前仓库主体 ID
*/
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作平台设置', 400);
}
return storeId;
}
/**
* 规范化必填文本。
*
* @param {string|number} value 原始值
* @param {string} fieldName 字段名称
* @param {number} maxLength 最大长度
* @return {string} 规范化后的文本
*/
normalizeRequiredText(value, fieldName, maxLength) {
if (value === undefined || value === null) {
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
if (typeof value !== 'string' && typeof value !== 'number') {
throw this.createError(`${fieldName} 参数类型不合法`, 400);
}
const normalized = String(value).trim();
if (!normalized) {
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化可选文本。
*
* @param {string|number} value 原始值
* @param {string} fieldName 字段名称
* @param {number} maxLength 最大长度
* @return {string|null} 规范化后的文本
*/
normalizeOptionalText(value, fieldName, maxLength) {
if (value === undefined || value === null) {
return null;
}
if (typeof value !== 'string' && typeof value !== 'number') {
throw this.createError(`${fieldName} 参数类型不合法`, 400);
}
const normalized = String(value).trim();
if (!normalized) {
return null;
}
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化整数。
*
* @param {number|string} value 原始值
* @param {string} fieldName 字段名称
* @param {Object} [options] 额外选项
* @param {boolean} [options.allowEmpty=false] 是否允许空值
* @param {number|null} [options.min=null] 最小值
* @param {number|null} [options.max=null] 最大值
* @return {number|null} 规范化后的整数
*/
normalizeInteger(value, fieldName, options = {}) {
const {
allowEmpty = false,
min = null,
max = null,
} = options;
if (value === undefined || value === null || value === '') {
if (allowEmpty) {
return null;
}
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
const normalized = Number(value);
if (!Number.isInteger(normalized)) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (min !== null && normalized < min) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (max !== null && normalized > max) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return normalized;
}
/**
* 规范化分页参数。
*
* @param {number|string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} defaultValue 默认值
* @param {number} maxValue 最大值
* @return {number} 规范化后的分页值
*/
normalizePage(value, fieldName, defaultValue, maxValue) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const normalized = Number(value);
if (!Number.isFinite(normalized) || normalized <= 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.min(Math.floor(normalized), maxValue);
}
/**
* 获取列表查询字段映射。
*
* @return {Object} 字段映射
*/
getListWhereSpecialFieldMap() {
return {
id: {
field: 'id',
},
code: {
field: 'code',
},
name: {
field: 'name',
},
platform_code: {
field: 'platform_code',
},
quickWhere: {
bucket: 'quick',
},
};
}
/**
* 解析列表查询条件。
*
* @param {Object} data 请求参数
* @return {Object} 查询条件信息
*/
resolveListWhere(data = {}) {
const { ctx, app } = this;
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? { ...ctx.where }
: (data.where && typeof data.where === 'object' ? { ...data.where } : {});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: this.getListWhereSpecialFieldMap(),
});
if (!parsed.ok) {
throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400);
}
parsedResult = parsed.result;
}
return {
normalizedWhere,
parsedResult,
};
}
/**
* 生成平台展示标签。
*
* @param {string} code 设置代码
* @param {string} platformName 平台名称
* @return {string} 展示标签
*/
buildPlatformLabel(code, platformName) {
const normalizedCode = String(code || '').trim();
const normalizedPlatformName = String(platformName || '').trim();
if (!normalizedCode) {
return normalizedPlatformName;
}
if (!normalizedPlatformName) {
return normalizedCode;
}
return `${normalizedCode} (${normalizedPlatformName})`;
}
/**
* 规范化平台设置记录。
*
* @param {Object} row 数据库记录
* @return {Object|null} 规范化后的记录
*/
normalizePlatformRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
const platform = row.platform && typeof row.platform === 'object' ? row.platform : null;
const code = this.normalizeOptionalText(row.code, 'code', 50);
if (!code) {
return null;
}
const platformCode = this.normalizeOptionalText(row.platform_code, 'platform_code', 50)
|| this.normalizeOptionalText(platform && platform.code, 'platform_code', 50)
|| '';
const platformName = this.normalizeOptionalText(
row.platform_name !== undefined ? row.platform_name : (platform && platform.name),
'platform_name',
255
) || '';
const platformLabel = this.buildPlatformLabel(code, platformName);
return {
id: row.id === undefined || row.id === null ? null : Number(row.id),
code,
name: this.normalizeOptionalText(row.name, 'name', 100),
platform_code: platformCode,
warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id),
label: platformLabel,
platform_name: platformName,
platform_label: platformLabel,
platform: platform ? {
code: this.normalizeOptionalText(platform.code, 'platform.code', 50),
name: this.normalizeOptionalText(platform.name, 'platform.name', 255),
default_express_interface: this.normalizeOptionalText(platform.default_express_interface, 'platform.default_express_interface', 50),
} : null,
};
}
/**
* 查找当前仓库下的平台设置记录。
*
* @param {number} id 设置 ID
* @return {Promise<Object>} 平台设置记录
*/
async findSettingById(id) {
const { ctx } = this;
const currentStoreId = this.getCurrentStoreId();
const setting = await ctx.model.PlatformSetting.findOne({
where: {
id,
warehouse_id: currentStoreId,
},
include: [
{
model: ctx.model.Platform,
as: 'platform',
attributes: [ 'code', 'name', 'default_express_interface' ],
required: false,
},
],
});
if (!setting) {
throw this.createError('平台设置不存在或无权限操作', 404);
}
return setting;
}
/**
* 查找同仓下的 code 冲突记录。
*
* @param {string} code 设置代码
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<Object|null>} 冲突记录
*/
async findCodeConflict(code, excludeId = null) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const where = {
warehouse_id: this.getCurrentStoreId(),
code,
};
const normalizedExcludeId = Number(excludeId || 0);
if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) {
where.id = {
[Op.ne]: normalizedExcludeId,
};
}
return await ctx.model.PlatformSetting.findOne({
where,
attributes: [ 'id', 'code' ],
});
}
/**
* 查找同仓下的平台代码冲突记录。
*
* @param {string} platformCode 平台代码
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<Object|null>} 冲突记录
*/
async findPlatformCodeConflict(platformCode, excludeId = null) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const where = {
warehouse_id: this.getCurrentStoreId(),
platform_code: platformCode,
};
const normalizedExcludeId = Number(excludeId || 0);
if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) {
where.id = {
[Op.ne]: normalizedExcludeId,
};
}
return await ctx.model.PlatformSetting.findOne({
where,
attributes: [ 'id', 'platform_code' ],
});
}
/**
* 校验平台是否存在。
*
* @param {string} platformCode 平台代码
* @return {Promise<Object>} 平台记录
*/
async ensurePlatformExists(platformCode) {
const { ctx } = this;
const platform = await ctx.model.Platform.findOne({
where: {
code: platformCode,
},
attributes: [ 'code', 'name', 'default_express_interface' ],
});
if (!platform) {
throw this.createError('platform_code 不存在或不支持', 400);
}
return platform;
}
/**
* 校验 code 是否可用。
*
* @param {string} code 设置代码
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<boolean>} 是否可用
*/
async ensureCodeAvailable(code, excludeId = null) {
const conflict = await this.findCodeConflict(code, excludeId);
if (conflict) {
throw this.createError('code 已被当前仓库使用', 409);
}
return true;
}
/**
* 校验平台代码是否可用。
*
* @param {string} platformCode 平台代码
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<boolean>} 是否可用
*/
async ensurePlatformCodeAvailable(platformCode, excludeId = null) {
const conflict = await this.findPlatformCodeConflict(platformCode, excludeId);
if (conflict) {
throw this.createError('platform_code 已被当前仓库使用', 409);
}
return true;
}
/**
* 获取平台设置列表。
*
* @param {Object} data 请求参数
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} 分页结果
*/
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentStoreId = this.getCurrentStoreId();
const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {};
const pageSource = pagination.page !== undefined ? pagination.page : data.page;
const pageSizeSource = pagination.pageSize !== undefined
? pagination.pageSize
: (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize));
const page = this.normalizePage(pageSource, 'page', 1, 1000000);
const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const { normalizedWhere, parsedResult } = this.resolveListWhere(data);
const andConditions = [
{
warehouse_id: currentStoreId,
},
];
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: quickWhereInput;
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const keyword = String(quickWhereValue).trim();
andConditions.push({
[Op.or]: [
{ code: { [Op.like]: `%${keyword}%` } },
{ name: { [Op.like]: `%${keyword}%` } },
{ platform_code: { [Op.like]: `%${keyword}%` } },
],
});
}
const result = await ctx.model.PlatformSetting.findAndCountAll({
where: {
[Op.and]: andConditions,
},
include: [
{
model: ctx.model.Platform,
as: 'platform',
attributes: [ 'code', 'name', 'default_express_interface' ],
required: false,
},
],
attributes: [ 'id', 'code', 'name', 'platform_code', 'warehouse_id' ],
order: [[ 'id', 'DESC' ]],
offset,
limit: pageSize,
});
const list = Array.isArray(result && result.rows)
? result.rows.map(row => this.normalizePlatformRow(row && typeof row.get === 'function' ? row.get({ plain: true }) : row)).filter(Boolean)
: [];
const total = Array.isArray(result && result.count)
? result.count.length
: Number(result && result.count ? result.count : 0);
return {
code: 200,
data: {
list,
total,
page,
page_size: pageSize,
},
};
}
/**
* 创建平台设置。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 创建结果
*/
async create(data = {}) {
const { ctx } = this;
const currentStoreId = this.getCurrentStoreId();
const code = this.normalizeRequiredText(data.code, 'code', 50);
const name = this.normalizeRequiredText(data.name, 'name', 100);
const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50);
const platform = await this.ensurePlatformExists(platformCode);
await this.ensureCodeAvailable(code);
await this.ensurePlatformCodeAvailable(platformCode);
const created = await ctx.model.PlatformSetting.create({
warehouse_id: currentStoreId,
code,
name,
platform_code: platformCode,
});
const plainCreated = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
return {
code: 200,
data: this.normalizePlatformRow({
...plainCreated,
platform,
}),
};
}
/**
* 修改平台设置。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 修改结果
*/
async update(data = {}) {
const id = Number(data.id || data.setting_id || data.settingId || 0);
if (!Number.isInteger(id) || id <= 0) {
throw this.createError('id 参数不能为空', 400);
}
const setting = await this.findSettingById(id);
const hasCode = Object.prototype.hasOwnProperty.call(data, 'code');
const hasName = Object.prototype.hasOwnProperty.call(data, 'name');
const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code')
|| Object.prototype.hasOwnProperty.call(data, 'platformCode');
if (!hasCode && !hasName && !hasPlatformCode) {
throw this.createError('至少需要提供一个可更新字段', 400);
}
const updates = {};
let nextCode = setting.code || '';
let nextPlatformCode = setting.platform_code || '';
let platform = setting.platform || null;
if (hasCode) {
const code = this.normalizeRequiredText(data.code, 'code', 50);
updates.code = code;
nextCode = code;
}
if (hasName) {
updates.name = this.normalizeRequiredText(data.name, 'name', 100);
}
if (hasPlatformCode) {
const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50);
platform = await this.ensurePlatformExists(platformCode);
updates.platform_code = platformCode;
nextPlatformCode = platformCode;
}
if (Object.prototype.hasOwnProperty.call(updates, 'code')) {
await this.ensureCodeAvailable(nextCode, id);
}
if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')) {
await this.ensurePlatformCodeAvailable(nextPlatformCode, id);
}
await setting.update(updates);
const plainSetting = setting && typeof setting.get === 'function'
? setting.get({ plain: true })
: setting;
return {
code: 200,
data: this.normalizePlatformRow({
...plainSetting,
platform,
}),
};
}
/**
* 删除平台设置。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 删除结果
*/
async delete(data = {}) {
const id = Number(data.id || data.setting_id || data.settingId || 0);
if (!Number.isInteger(id) || id <= 0) {
throw this.createError('id 参数不能为空', 400);
}
const setting = await this.findSettingById(id);
const plainSetting = setting && typeof setting.get === 'function'
? setting.get({ plain: true })
: setting;
await setting.destroy();
return {
code: 200,
data: {
id: Number(plainSetting.id),
warehouse_id: Number(plainSetting.warehouse_id),
deleted: true,
},
};
}
}
module.exports = SettingPlatformService;

View File

@ -11,6 +11,22 @@ function getStartOfDayMs(value) {
return date.getTime();
}
/**
* 判断到期日期是否早于当前日期。
* @param {string|Date|number} expiryDate 到期日期
* @param {Date} [currentDate=new Date()] 当前日期
* @return {boolean} 是否已过期
*/
function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) {
const expiryStartMs = getStartOfDayMs(expiryDate);
if (expiryStartMs === null) return false;
const currentStartMs = getStartOfDayMs(currentDate);
if (currentStartMs === null) return false;
return expiryStartMs < currentStartMs;
}
class ReceivingService extends Service {
/**
* 查询收货单列表。
@ -1945,8 +1961,8 @@ class ReceivingService extends Service {
}
}
/**
* 修改收货明细信息并触发库存/统计联动。
* @param {Object} data 请求体
* 修改收货明细。
* @param {Object} data 收货明细修改参数
* @return {Promise<Object>} 修改结果
*/
async detailChange(data) {
@ -2015,6 +2031,13 @@ class ReceivingService extends Service {
};
}
if (expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) {
return {
code: 400,
message: '到期日期已过期,不能录入收货',
};
}
// 5. 验证箱规数据
if (box_quantity !== undefined && box_quantity < 0) {
return {

View File

@ -29,4 +29,4 @@ module.exports = {
WHERE subject_config IS NOT NULL
`);
},
};
};

View File

@ -71,4 +71,4 @@ module.exports = {
await queryInterface.dropTable('wms_express_interface');
}
},
};
};

View File

@ -29,4 +29,4 @@ module.exports = {
await queryInterface.removeColumn(tableName, 'quantity');
}
},
};
};

View File

@ -1,4 +1,36 @@
[
{
"version": "2026.04.17-system-05",
"date": "2026-04-17",
"summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)",
"methods": [
"index.getPlatformList",
"setting.platform.list",
"setting.platform.create",
"setting.platform.update",
"setting.platform.delete"
],
"notes": [
"新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。",
"文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。"
],
"type": "added"
},
{
"version": "2026.04.17-system-04",
"date": "2026-04-17",
"summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。",
"methods": [
"setting.platform.list",
"setting.platform.create",
"setting.platform.update",
"setting.platform.delete"
],
"notes": [
"新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。"
],
"type": "added"
},
{
"version": "2026.04.15-system-07",
"date": "2026-04-15",
@ -651,4 +683,68 @@
],
"type": "updated"
}
]
,
{
"version": "2026.04.16-system-01",
"date": "2026-04-16",
"summary": "基础模块新增快递产品类型查询接口",
"methods": [
"index.getExpressProductTypeList"
],
"notes": [
"新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。",
"对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。",
"接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。"
],
"type": "added"
},
{
"version": "2026.04.17-system-01",
"date": "2026-04-17",
"summary": "新增快递管理模块(setting.express)及 5 个接口文档",
"methods": [
"setting.express.list",
"setting.express.listBase",
"setting.express.create",
"setting.express.checkCodeUnique",
"setting.express.update"
],
"notes": [
"新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。",
"接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。",
"接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。",
"已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。"
],
"type": "added"
},
{
"version": "2026.04.17-system-02",
"date": "2026-04-17",
"summary": "setting.express.list 分页入参统一为 pagination",
"methods": [
"setting.express.list"
],
"notes": [
"将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。",
"文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。"
],
"type": "updated"
},
{
"version": "2026.04.17-system-03",
"date": "2026-04-17",
"summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档",
"methods": [
"setting.expressInterface.list",
"setting.expressInterface.create",
"setting.expressInterface.update",
"setting.expressInterface.delete"
],
"notes": [
"新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。",
"接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。",
"已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。"
],
"type": "added"
}
]

View File

@ -561,15 +561,6 @@
"params": [],
"response": [],
"errors": []
},
{
"method": "index.getPlatformList",
"description": "index.getPlatformList 接口",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [],
"response": [],
"errors": []
}
]
},
@ -2362,6 +2353,89 @@
}
]
},
{
"groupName": "平台编码管理模块",
"module": "setting.platform",
"list": [
{
"method": "index.getPlatformList",
"description": "合并后的平台列表",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [],
"response": [],
"errors": []
},
{
"method": "setting.platform.list",
"description": "查询当前仓库范围的平台设置列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
},
{
"method": "setting.platform.create",
"description": "创建当前仓库范围的平台设置",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
},
{
"method": "setting.platform.update",
"description": "更新当前仓库范围的平台设置",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
},
{
"method": "setting.platform.delete",
"description": "删除当前仓库范围的平台设置",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
}
]
},
{
"groupName": "账号管理模块",
"module": "setting.account",

View File

@ -3,5 +3,5 @@
"offset": 1713,
"processedCount": 1,
"completedAt": "2026-04-12T14:54:22.636Z",
"updatedAt": "2026-04-16T11:59:44.134Z"
"updatedAt": "2026-04-17T11:23:32.286Z"
}

39
temp_check_json.js Normal file
View File

@ -0,0 +1,39 @@
const fs = require('fs');
const s = fs.readFileSync('methods/system.json','utf8');
let stack = [];
let inStr = false;
function isEscaped(str, idx){
let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;
}
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c === '"' && !isEscaped(s,i)) {
inStr = !inStr;
}
if (inStr) continue;
if (c === '{' || c === '[') stack.push({ c, pos: i });
else if (c === '}') {
if (!stack.length || stack[stack.length - 1].c !== '{') {
console.log('UNMATCHED } at', i);
break;
}
stack.pop();
} else if (c === ']') {
if (!stack.length || stack[stack.length - 1].c !== '[') {
console.log('UNMATCHED ] at', i);
break;
}
stack.pop();
}
}
if (stack.length) {
console.log('STACK NOT EMPTY len', stack.length);
stack.forEach(x=>{
console.log('---STACK ITEM---');
console.log(x.c, x.pos);
console.log(s.slice(Math.max(0,x.pos-120), x.pos+120));
});
} else {
console.log('ALL MATCHED');
}

15
temp_count_brackets.js Normal file
View File

@ -0,0 +1,15 @@
const fs=require('fs');
const s=fs.readFileSync('methods/system.json','utf8');
function isEscaped(str, idx){let cnt=0;let j=idx-1;while(j>=0&&str[j]=='\\'){cnt++;j--;}return cnt%2===1;}
let inStr=false, open=0, close=0, openB=0, closeB=0;
for(let i=0;i<s.length;i++){
const c=s[i];
if(c==='"' && !isEscaped(s,i)) inStr=!inStr;
if(inStr) continue;
if(c==='[') open++;
if(c===']') close++;
if(c==='{') openB++;
if(c==='}') closeB++;
}
console.log('square [ count',open,' ] count',close,' diff',open-close);
console.log('curly { count',openB,' } count',closeB,' diff',openB-closeB);

5
temp_debug_headers.js Normal file
View File

@ -0,0 +1,5 @@
const fs=require('fs');
const s=fs.readFileSync('methods/system.json','utf8');
let ph=s.indexOf('"headers"');
console.log('headers@index',ph);
if(ph!==-1){let posOpen=s.indexOf('[',ph);console.log('open@[',posOpen,']'); console.log('---snippet---'); console.log(s.slice(Math.max(0,posOpen-120), posOpen+400)); console.log('---end---');}

View File

@ -0,0 +1,15 @@
const fs=require('fs');
const s=fs.readFileSync('methods/system.json','utf8');
function isEscaped(str, idx){let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;}
let ph=s.indexOf('"headers"');
let posOpen=s.indexOf('[',ph);
let depth=0; let inStr=false; let posClose=-1;
for(let i=posOpen;i<s.length;i++){
const c=s[i];
if(c=='"' && !isEscaped(s,i)) inStr=!inStr;
if(inStr) continue;
if(c=='[') depth++;
else if(c==']'){ depth--; if(depth===0){ posClose=i; break; }}
}
console.log('posOpen',posOpen,'posClose',posClose);
console.log(s.slice(posClose-40,posClose+40));

View File

@ -0,0 +1 @@
const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/}\s*\n\s*\{/g;let found=false;while(true){const m=re.exec(s);if(!m) break;const idx=m.index;let j=idx-1;while(j>=0&&/\s/.test(s[j])) j--;const prev=s[j]||'';if(prev!==','){found=true;const start=Math.max(0,idx-60);const end=Math.min(s.length, idx+60);console.log('---possible missing comma at',idx,'prevChar:',prev);console.log(s.slice(start,end));console.log('---');}}if(!found) console.log('No obvious }\n{ without comma found');

1
temp_find_objsep.js Normal file
View File

@ -0,0 +1 @@
const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/}\s*\n\s*{\s*"method"\s*:/g;let m;let found=false;while(m=re.exec(s)){const idx=m.index;let j=idx-1;while(j>=0&&/\s/.test(s[j])) j--;const prev=s[j]||'';if(prev!==','){found=true;const start=Math.max(0,idx-80);const end=Math.min(s.length,idx+80);console.log('---missing comma between objects at',idx,'prevChar:',prev);console.log(s.slice(start,end));console.log('---');}}if(!found) console.log('No missing-comma-between-method-objects found');

View File

@ -0,0 +1 @@
const fs=require('fs');const s=fs.readFileSync('methods/system.json','utf8');const re=/(,\s*\n\s*\])/g;let m;let found=false;while(m=re.exec(s)){found=true;const idx=m.index;const start=Math.max(0,idx-60);const end=Math.min(s.length,idx+60);console.log('---trailing comma before ] at',idx);console.log(s.slice(start,end));console.log('---');}if(!found) console.log('No ",\n]" patterns found');

13
temp_parse_json.py Normal file
View File

@ -0,0 +1,13 @@
import json
s=open('methods/system.json','r',encoding='utf8').read()
try:
json.loads(s)
print('py OK')
except json.decoder.JSONDecodeError as e:
print('JSONDecodeError:', e.msg, 'lineno', e.lineno, 'colno', e.colno, 'pos', e.pos)
start=max(0,e.pos-120)
print('---context---')
print(s[start:e.pos+120])
print('---end---')
except Exception as e:
print('other error',e)

View File

@ -0,0 +1,49 @@
const fs=require('fs');
const path='methods/system.json';
let s=fs.readFileSync(path,'utf8');
function isEscaped(str, idx){let cnt=0; let j=idx-1; while(j>=0 && str[j]=='\\'){cnt++; j--; } return cnt%2===1;}
// find headers key
let ph = s.indexOf('"headers"');
if(ph===-1){console.error('no headers key'); process.exit(1)}
let posOpen = s.indexOf('[', ph);
if(posOpen===-1){console.error('no [ after headers'); process.exit(1)}
// find matching closing bracket for headers
let depth=0; let inStr=false; let posClose=-1;
for(let i=posOpen;i<s.length;i++){
const c=s[i];
if(c=='"' && !isEscaped(s,i)) inStr=!inStr;
if(inStr) continue;
if(c=='[') depth++;
else if(c==']'){ depth--; if(depth===0){ posClose=i; break; }}
}
if(posClose===-1){console.error('cannot find headers close'); process.exit(1)}
const preHeader = s.slice(0, posOpen);
const headerContent = s.slice(posOpen, posClose+1);
// find first group start after posClose
let gNameIndex = s.indexOf('"groupName"', posClose+1);
if(gNameIndex===-1){ console.error('no groupName found after headers'); process.exit(1)}
// find the starting '{' before this groupName
let groupStart = s.lastIndexOf('{', gNameIndex);
if(groupStart===-1 || groupStart<=posClose){
// try to find next '{' after posClose which encloses group
groupStart = s.indexOf('{', posClose+1);
}
if(groupStart===-1){console.error('cannot find group object start'); process.exit(1)}
// find the groups tail closers (we expect existing file to end with ]\n }\n}
let tailPattern='\n ]\n }\n}';
let tailIndex = s.lastIndexOf(tailPattern);
if(tailIndex===-1){
// fallback: try shorter pattern
tailIndex = s.lastIndexOf('\n }\n}\n');
}
if(tailIndex===-1){
// fallback use end of file
tailIndex = s.length;
}
// groups content is from groupStart to the position before tailPattern
const groupsContent = s.slice(groupStart, tailIndex);
// build new content
const newContent = preHeader + headerContent + ',\n "methods": {\n "groups": [\n' + groupsContent.replace(/^\s*/,'') + '\n ]\n }\n}';
// write to file
fs.writeFileSync(path, newContent, 'utf8');
console.log('rewritten', path);

View File

@ -60,7 +60,7 @@ async function switchToWarehouseRole(token) {
describe('test/app/controller/system.storage.inventory.list.test.js', () => {
let warehouseToken;
before(async function () {
before(async function() {
const { token } = await getAuthToken();
try {

View File

@ -0,0 +1,51 @@
'use strict';
const assert = require('node:assert/strict');
function createSequelizeTypes() {
const makeType = sql => ({
toSql() {
return sql;
},
});
return {
STRING: length => makeType(`VARCHAR(${length})`),
JSON: makeType('JSON'),
};
}
function createApp() {
return {
Sequelize: createSequelizeTypes(),
model: {
define(name, attributes, options) {
return {
name,
rawAttributes: attributes,
options,
};
},
},
};
}
describe('test/app/model/express.test.js', () => {
it('should define wms_express fields and table options', () => {
const app = createApp();
const Express = require('../../../app/model/express')(app);
assert.equal(Express.options.tableName, 'wms_express');
assert.equal(Express.options.freezeTableName, true);
assert.equal(Express.options.timestamps, false);
assert.equal(Express.options.underscored, true);
assert.equal(Express.options.paranoid, false);
assert.equal(Express.rawAttributes.code.primaryKey, true);
assert.equal(Express.rawAttributes.code.type.toSql(), 'VARCHAR(50)');
assert.equal(Express.rawAttributes.name.type.toSql(), 'VARCHAR(255)');
assert.equal(Express.rawAttributes.polyapi_code.type.toSql(), 'VARCHAR(255)');
assert.equal(Express.rawAttributes.polyapi_extra_info.type.toSql(), 'JSON');
assert.equal(Express.rawAttributes.pdd_code.type.toSql(), 'VARCHAR(255)');
});
});

View File

@ -0,0 +1,66 @@
'use strict';
const assert = require('node:assert/strict');
/**
* 构造最小 Sequelize 类型集合。
* @return {Object} Sequelize 类型集合。
*/
function createSequelizeTypes() {
const makeType = sql => ({
toSql() {
return sql;
},
});
const unsignedInteger = length => {
const type = makeType(`INT(${length})`);
type.UNSIGNED = makeType(`INT(${length}) UNSIGNED`);
return type;
};
return {
INTEGER: unsignedInteger,
STRING: length => makeType(`VARCHAR(${length})`),
};
}
/**
* 构造模型测试所需的最小应用对象。
* @return {Object} 最小应用对象。
*/
function createApp() {
const Sequelize = createSequelizeTypes();
return {
Sequelize,
model: {
define(name, attributes, options) {
return {
name,
rawAttributes: attributes,
options,
};
},
},
};
}
describe('test/app/model/express_product_type.test.js', () => {
it('should define wms_express_product_type fields and table options', () => {
const app = createApp();
const ExpressProductType = require('../../../app/model/express_product_type')(app);
assert.equal(ExpressProductType.options.tableName, 'wms_express_product_type');
assert.equal(ExpressProductType.options.freezeTableName, true);
assert.equal(ExpressProductType.options.underscored, true);
assert.equal(ExpressProductType.options.timestamps, false);
assert.equal(ExpressProductType.options.paranoid, false);
assert.equal(ExpressProductType.rawAttributes.id.type.toSql(), 'INT(11) UNSIGNED');
assert.equal(ExpressProductType.rawAttributes.name.type.toSql(), 'VARCHAR(255)');
assert.equal(ExpressProductType.rawAttributes.express_code.type.toSql(), 'VARCHAR(50)');
assert.equal(ExpressProductType.rawAttributes.code.type.toSql(), 'VARCHAR(50)');
assert.equal(ExpressProductType.rawAttributes.id.primaryKey, true);
assert.equal(ExpressProductType.rawAttributes.id.autoIncrement, true);
});
});

View File

@ -77,4 +77,4 @@ describe('test/app/model/picking.test.js', () => {
assert.ok(indexNames.includes('idx_wms_picking_status'));
assert.ok(indexNames.includes('idx_wms_picking_order_item_space'));
});
});
});

View File

@ -213,4 +213,4 @@ describe('test/app/service/qimenMethods/order.test.js', () => {
assert.equal(calls.update, 0);
assert.equal(calls.noticeSend, 0);
});
});
});

View File

@ -60,4 +60,4 @@ describe('test/app/service/systemMethods/order/storageAllocation.test.js', () =>
assert.equal(result.code, 200);
assert.deepEqual(result.data, { ok: true });
});
});
});

View File

@ -0,0 +1,178 @@
'use strict';
const assert = require('node:assert/strict');
const ExpressMethodService = require('../../../../../app/service/systemMethods/setting/express');
function createContext() {
const calls = {
list: [],
create: [],
update: [],
checkCodeUnique: [],
listBase: 0,
prepareWhereContext: 0,
};
const ctx = {
app: {
config: {
jwt: {},
},
Sequelize: {},
},
service: {
systems: {
setting: {
express: {
async list(payload) {
calls.list.push(payload);
payload.touched = true;
return {
code: 200,
data: {
list: [
{ id: 1, code: 'SF-001' },
],
},
};
},
async listBase() {
calls.listBase += 1;
return {
code: 200,
data: [
{ code: 'SF', name: '顺丰' },
],
};
},
async create(payload) {
calls.create.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 99,
},
};
},
async checkCodeUnique(payload) {
calls.checkCodeUnique.push(payload);
return {
code: 200,
data: {
isUnique: true,
},
};
},
async update(payload) {
calls.update.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 11,
},
};
},
},
},
},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systemMethods/setting/express.test.js', () => {
it('should copy payload before calling list', async () => {
const { ctx, calls } = createContext();
const service = new ExpressMethodService(ctx);
service.prepareWhereContext = function prepareWhereContext(data) {
calls.prepareWhereContext += 1;
data.where = {
quickWhere: 'SF',
};
return data;
};
const payload = {
page: 1,
page_size: 20,
where: {
quickWhere: 'SF',
},
extra: {
keep: true,
},
};
const result = await service.list(payload);
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(calls.prepareWhereContext, 1);
assert.equal(calls.list.length, 1);
assert.notStrictEqual(calls.list[0], payload);
assert.equal(payload.touched, undefined);
assert.deepEqual(calls.list[0].where, { quickWhere: 'SF' });
assert.deepEqual(calls.list[0].pagination, {
page: 1,
pageSize: 20,
});
});
it('should forward normalized create payload and keep the original payload intact', async () => {
const { ctx, calls } = createContext();
const service = new ExpressMethodService(ctx);
const payload = {
code: 'sf-001',
name: '顺丰设置',
express_code: 'SF',
extra: {
keep: true,
},
};
const result = await service.create(payload);
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(calls.create.length, 1);
assert.notStrictEqual(calls.create[0], payload);
assert.deepEqual(calls.create[0], {
code: 'sf-001',
name: '顺丰设置',
express_code: 'SF',
extra: {
keep: true,
},
touched: true,
});
assert.equal(payload.touched, undefined);
});
it('should delegate listBase and checkCodeUnique to the setting express service', async () => {
const { ctx, calls } = createContext();
const service = new ExpressMethodService(ctx);
const baseResult = await service.listBase();
const checkResult = await service.checkCodeUnique({
id: 11,
code: 'SF-001',
});
assert.equal(calls.listBase, 1);
assert.equal(calls.checkCodeUnique.length, 1);
assert.deepEqual(calls.checkCodeUnique[0], {
id: 11,
code: 'SF-001',
});
assert.equal(baseResult.flag, 'success');
assert.equal(checkResult.flag, 'success');
assert.equal(checkResult.data.isUnique, true);
});
});

View File

@ -0,0 +1,167 @@
'use strict';
const assert = require('node:assert/strict');
const ExpressInterfaceMethodService = require('../../../../../app/service/systemMethods/setting/expressInterface');
function createContext() {
const calls = {
list: [],
create: [],
update: [],
delete: [],
prepareWhereContext: 0,
};
const ctx = {
app: {
config: {
jwt: {},
},
Sequelize: {},
},
service: {
systems: {
setting: {
expressInterface: {
async list(payload) {
calls.list.push(payload);
payload.touched = true;
return {
code: 200,
data: {
list: [
{ id: 1, name: '顺丰接口' },
],
},
};
},
async create(payload) {
calls.create.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 99,
},
};
},
async update(payload) {
calls.update.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 11,
},
};
},
async delete(payload) {
calls.delete.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 11,
},
};
},
},
},
},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systemMethods/setting/expressInterface.test.js', () => {
it('should copy payload before calling list', async () => {
const { ctx, calls } = createContext();
const service = new ExpressInterfaceMethodService(ctx);
service.prepareWhereContext = function prepareWhereContext(data) {
calls.prepareWhereContext += 1;
data.where = {
quickWhere: '接口',
};
return data;
};
const payload = {
page: 1,
page_size: 20,
where: {
quickWhere: '接口',
},
extra: {
keep: true,
},
};
const result = await service.list(payload);
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(calls.prepareWhereContext, 1);
assert.equal(calls.list.length, 1);
assert.notStrictEqual(calls.list[0], payload);
assert.equal(payload.touched, undefined);
assert.deepEqual(calls.list[0].where, { quickWhere: '接口' });
assert.deepEqual(calls.list[0].pagination, {
page: 1,
pageSize: 20,
});
});
it('should forward normalized create update and delete payloads', async () => {
const { ctx, calls } = createContext();
const service = new ExpressInterfaceMethodService(ctx);
const createResult = await service.create({
name: '顺丰接口',
express_code: 'SF',
platform_code: 'TB',
express_platform_id: 1,
extra: {
keep: true,
},
});
const updateResult = await service.update({
id: 11,
name: '顺丰接口-更新',
token: 'token-2',
});
const deleteResult = await service.delete({
id: 11,
});
assert.equal(createResult.flag, 'success');
assert.equal(updateResult.flag, 'success');
assert.equal(deleteResult.flag, 'success');
assert.equal(calls.create.length, 1);
assert.equal(calls.update.length, 1);
assert.equal(calls.delete.length, 1);
assert.deepEqual(calls.create[0], {
name: '顺丰接口',
express_code: 'SF',
platform_code: 'TB',
express_platform_id: 1,
extra: {
keep: true,
},
touched: true,
});
assert.deepEqual(calls.update[0], {
id: 11,
name: '顺丰接口-更新',
token: 'token-2',
touched: true,
});
assert.deepEqual(calls.delete[0], {
id: 11,
touched: true,
});
});
});

View File

@ -0,0 +1,186 @@
'use strict';
const assert = require('node:assert/strict');
const PlatformMethodService = require('../../../../../app/service/systemMethods/setting/platform');
function createContext() {
const calls = {
list: [],
create: [],
update: [],
delete: [],
prepareWhereContext: 0,
};
const ctx = {
app: {
config: {
jwt: {},
},
Sequelize: {},
},
service: {
systems: {
setting: {
platform: {
async list(payload) {
calls.list.push(payload);
payload.touched = true;
return {
code: 200,
data: {
list: [
{ id: 1, code: 'TB-STORE' },
],
},
};
},
async create(payload) {
calls.create.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 99,
},
};
},
async update(payload) {
calls.update.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 11,
},
};
},
async delete(payload) {
calls.delete.push(payload);
payload.touched = true;
return {
code: 200,
data: {
id: 11,
},
};
},
},
},
},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systemMethods/setting/platform.test.js', () => {
it('should copy payload before calling list', async () => {
const { ctx, calls } = createContext();
const service = new PlatformMethodService(ctx);
service.prepareWhereContext = function prepareWhereContext(data) {
calls.prepareWhereContext += 1;
data.where = {
quickWhere: '设置',
};
return data;
};
const payload = {
page: 1,
page_size: 20,
where: {
quickWhere: '设置',
},
extra: {
keep: true,
},
};
const result = await service.list(payload);
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(calls.prepareWhereContext, 1);
assert.equal(calls.list.length, 1);
assert.notStrictEqual(calls.list[0], payload);
assert.equal(payload.touched, undefined);
assert.deepEqual(calls.list[0].where, { quickWhere: '设置' });
assert.deepEqual(calls.list[0].pagination, {
page: 1,
pageSize: 20,
});
});
it('should forward normalized create update and delete payloads', async () => {
const { ctx, calls } = createContext();
const service = new PlatformMethodService(ctx);
const createResult = await service.create({
code: 'TB-STORE',
name: '淘宝设置',
platform_code: 'TB',
extra: {
keep: true,
},
});
const updateResult = await service.update({
id: 11,
code: 'TB-STORE-NEW',
name: '淘宝设置-更新',
platformCode: 'JD',
});
const deleteResult = await service.delete({
id: 11,
});
assert.equal(createResult.flag, 'success');
assert.equal(updateResult.flag, 'success');
assert.equal(deleteResult.flag, 'success');
assert.equal(calls.create.length, 1);
assert.equal(calls.update.length, 1);
assert.equal(calls.delete.length, 1);
assert.deepEqual(calls.create[0], {
code: 'TB-STORE',
name: '淘宝设置',
platform_code: 'TB',
extra: {
keep: true,
},
touched: true,
});
assert.deepEqual(calls.update[0], {
id: 11,
code: 'TB-STORE-NEW',
name: '淘宝设置-更新',
platform_code: 'JD',
touched: true,
});
assert.deepEqual(calls.delete[0], {
id: 11,
touched: true,
});
});
it('should keep optional update fields omitted when not provided', async () => {
const { ctx, calls } = createContext();
const service = new PlatformMethodService(ctx);
const result = await service.update({
setting_id: 11,
platformCode: 'JD',
});
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(calls.update.length, 1);
assert.deepEqual(calls.update[0], {
id: 11,
platform_code: 'JD',
touched: true,
});
});
});

View File

@ -177,4 +177,74 @@ describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => {
assert.equal(secondPrepared.sys_logistics_code, 'STO');
assert.equal(findByPkCallCount, 1, 'store subject_config should be loaded from cache on second call');
});
it('should resolve platform setting code to the real system platform code and name', async () => {
const deliveryOrder = {
deliveryOrderCode: 'TEST_ORDER_003',
sourcePlatformCode: 'TB-SETTING',
sourcePlatformName: '外部平台设置码',
receiverInfo: { name: 'test' },
};
const info = {
storeId: 1000000,
warehouseId: 100000,
};
mm(ctx, 'model', {
...(ctx.model || {}),
Store: {
async findByPk() {
return {
id: 1000000,
subject_config: {
default_platform_code: 'JD',
default_express_code: 'STO',
},
};
},
},
});
mm(ctx.service.systems.platform, 'getPlatformList', async () => ([
{ code: 'TB', name: '淘宝平台', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false },
{ code: 'TB-SETTING', name: 'TB-SETTING (淘宝平台)', value: 'TB-SETTING', label: 'TB-SETTING (淘宝平台)', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: true },
{ code: 'JD', name: '京东平台', value: 'JD', label: '京东平台', platform_code: 'JD', platform_name: '京东平台', is_system_setting: false },
]));
mm(ctx.service.systems.express, 'getExpressList', async () => ([
{ code: 'STO', name: '申通' },
]));
const snapshot = await deliveryOrderService.resolvePlatformSnapshot('TB-SETTING', {
default_platform_code: 'JD',
default_express_code: 'STO',
}, {
warehouseId: info.warehouseId,
deliveryOrderCode: deliveryOrder.deliveryOrderCode,
storeId: info.storeId,
});
assert.deepEqual(snapshot, {
sysPlatformCode: 'TB',
sysPlatformName: '淘宝平台',
});
});
it('should resolve merged express settings to the real express code', async () => {
mm(ctx.service.systems.express, 'getExpressList', async () => ([
{ code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' },
{ code: 'SF-SETTING', name: 'SF-SETTING (顺丰)', value: 'SF-SETTING', label: 'SF-SETTING (顺丰)', express_code: 'STO', warehouse_id: 100000 },
]));
const snapshot = await deliveryOrderService.resolveExpressSnapshot('SF-SETTING', {
default_express_code: 'TB',
}, {
warehouseId: 100000,
deliveryOrderCode: 'TEST_ORDER_003',
storeId: 1000000,
});
assert.deepEqual(snapshot, {
sysLogisticsCode: 'STO',
sysLogisticsName: 'SF-SETTING (顺丰)',
});
});
});

View File

@ -6,7 +6,9 @@ const IndexMethodService = require('../../../../app/service/systemMethods/index'
function createExpressServiceHarness(options = {}) {
const calls = {
findAll: 0,
expressFindAll: 0,
expressSettingFindAll: 0,
expressProductTypeFindAll: 0,
getCache: 0,
setCache: 0,
};
@ -28,17 +30,35 @@ function createExpressServiceHarness(options = {}) {
}
},
},
user: options.user || null,
model: {
Express: {
async findAll(query) {
calls.findAll += 1;
calls.findAllQuery = query;
calls.expressFindAll += 1;
calls.expressFindAllQuery = query;
return options.rows || [
{ code: 'STO', name: '顺丰' },
{ code: 'TB', name: '淘宝快递' },
];
},
},
ExpressSetting: {
async findAll(query) {
calls.expressSettingFindAll += 1;
calls.expressSettingFindAllQuery = query;
return options.expressSettingRows || [];
},
},
ExpressProductType: {
async findAll(query) {
calls.expressProductTypeFindAll += 1;
calls.expressProductTypeFindAllQuery = query;
return options.expressProductTypeRows || [
{ code: 'SF-EXP', name: '顺丰标准', express_code: 'SF' },
{ code: 'SF-ECON', name: '顺丰经济', express_code: 'SF' },
];
},
},
},
logger: {
info() {},
@ -61,19 +81,79 @@ describe('test/app/service/systems/express.test.js', () => {
const result = await service.getExpressList();
assert.equal(calls.getCache, 1);
assert.equal(calls.findAll, 1);
assert.equal(calls.expressFindAll, 1);
assert.equal(calls.setCache, 1);
assert.equal(calls.cachePayload.cacheKey, 'express:list');
assert.equal(calls.cachePayload.ttl, 600);
assert.deepEqual(result, [
{ code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' },
{ code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递' },
{ code: 'STO', name: '顺丰', value: 'STO', label: '顺丰', is_system_setting: false, id: null, alias: null },
{ code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递', is_system_setting: false, id: null, alias: null },
]);
});
it('should merge express settings for the current warehouse and keep real express codes', async () => {
const { ctx, calls } = createExpressServiceHarness({
user: {
store_id: 100000,
},
rows: [
{ code: 'SF', name: '顺丰' },
{ code: 'YTO', name: '圆通' },
],
expressSettingRows: [
{ id: 11, code: 'SF-001', name: '顺丰设置', express_code: 'SF', warehouse_id: 100000 },
{ id: 12, code: 'SF-001', name: '圆通设置', express_code: 'YTO', warehouse_id: 100000 },
{ id: 13, code: 'YTO-001', name: '圆通设置', express_code: 'YTO', warehouse_id: 100000 },
],
});
const service = new ExpressService(ctx);
const result = await service.getExpressList();
assert.equal(calls.getCache, 1);
assert.equal(calls.expressFindAll, 1);
assert.equal(calls.expressSettingFindAll, 1);
assert.deepEqual(calls.expressSettingFindAllQuery.where, { warehouse_id: 100000 });
assert.equal(calls.cachePayload.cacheKey, 'express:list:100000');
assert.deepEqual(result, [
{ code: 'SF', name: '顺丰', value: 'SF', label: '顺丰', is_system_setting: false, id: null, alias: null },
{ code: 'YTO', name: '圆通', value: 'YTO', label: '圆通', is_system_setting: false, id: null, alias: null },
{ code: 'SF-001', name: 'SF-001 (顺丰)', value: 'SF-001', label: 'SF-001 (顺丰)', express_code: 'SF', is_system_setting: true, id: 11, alias: '顺丰设置' },
{ code: 'YTO-001', name: 'YTO-001 (圆通)', value: 'YTO-001', label: 'YTO-001 (圆通)', express_code: 'YTO', is_system_setting: true, id: 13, alias: '圆通设置' },
]);
});
it('should keep original express rows when a setting uses the same code', async () => {
const { ctx, calls } = createExpressServiceHarness({
user: {
store_id: 100000,
},
expressSettingRows: [
{ id: 21, code: 'STO', name: '系统同码设置', express_code: 'STO', warehouse_id: 100000 },
{ id: 22, code: 'SF-SETTING', name: '顺丰设置', express_code: 'STO', warehouse_id: 100000 },
],
});
const service = new ExpressService(ctx);
const result = await service.getExpressList();
assert.equal(calls.getCache, 1);
assert.equal(calls.expressFindAll, 1);
assert.equal(calls.expressSettingFindAll, 1);
assert.deepEqual(result.slice(0, 2), [
{ code: 'STO', name: '顺丰', value: 'STO', label: '顺丰', is_system_setting: false, id: null, alias: null },
{ code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递', is_system_setting: false, id: null, alias: null },
]);
assert.deepEqual(result, [
{ code: 'STO', name: '顺丰', value: 'STO', label: '顺丰', is_system_setting: false, id: null, alias: null },
{ code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递', is_system_setting: false, id: null, alias: null },
{ code: 'SF-SETTING', name: 'SF-SETTING (顺丰)', value: 'SF-SETTING', label: 'SF-SETTING (顺丰)', express_code: 'STO', is_system_setting: true, id: 22, alias: '顺丰设置' },
]);
});
it('should return cached express list without querying database', async () => {
const cachedValue = [
{ code: 'SF', name: '顺丰', value: 'SF', label: '顺丰' },
{ code: 'SF', name: '顺丰', value: 'SF', label: '顺丰', is_system_setting: false, id: null, alias: null },
];
const { ctx, calls } = createExpressServiceHarness({
cachedValue,
@ -83,11 +163,84 @@ describe('test/app/service/systems/express.test.js', () => {
const result = await service.getExpressList();
assert.equal(calls.getCache, 1);
assert.equal(calls.findAll, 0);
assert.equal(calls.expressFindAll, 0);
assert.equal(calls.setCache, 0);
assert.deepEqual(result, cachedValue);
});
it('should load express product types from database and cache them when cache is empty', async () => {
const { ctx, calls } = createExpressServiceHarness();
const service = new ExpressService(ctx);
const result = await service.getExpressProductTypeList();
assert.equal(calls.getCache, 1);
assert.equal(calls.expressProductTypeFindAll, 1);
assert.equal(calls.setCache, 1);
assert.equal(calls.cachePayload.cacheKey, 'express:product-type:list');
assert.equal(calls.cachePayload.ttl, 3600);
assert.deepEqual(result, [
{ code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' },
{ code: 'SF-ECON', express_code: 'SF', name: '顺丰经济', value: 'SF-ECON', label: '顺丰经济' },
]);
});
it('should load express product types by express code and cache them with code-specific key', async () => {
const { ctx, calls } = createExpressServiceHarness({
expressProductTypeRows: [
{ code: 'SF-EXP', name: '顺丰标准', express_code: 'SF' },
],
});
const service = new ExpressService(ctx);
const result = await service.getExpressProductTypeList('SF');
assert.equal(calls.getCache, 1);
assert.equal(calls.expressProductTypeFindAll, 1);
assert.deepEqual(calls.expressProductTypeFindAllQuery.where, { express_code: 'SF' });
assert.equal(calls.setCache, 1);
assert.equal(calls.cachePayload.cacheKey, 'express:product-type:list:SF');
assert.equal(calls.cachePayload.ttl, 3600);
assert.deepEqual(result, [
{ code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' },
]);
});
it('should return cached express product types without querying database', async () => {
const cachedValue = [
{ code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' },
];
const { ctx, calls } = createExpressServiceHarness({
cachedValue,
});
const service = new ExpressService(ctx);
const result = await service.getExpressProductTypeList('SF');
assert.equal(calls.getCache, 1);
assert.equal(calls.expressProductTypeFindAll, 0);
assert.equal(calls.setCache, 0);
it('should load system express list without merging warehouse settings', async () => {
const { ctx, calls } = createExpressServiceHarness({
rows: [
{ code: 'SF', name: '顺丰' },
],
});
const service = new ExpressService(ctx);
const result = await service.getSystemExpressList();
assert.equal(calls.getCache, 0);
assert.equal(calls.expressFindAll, 1);
assert.equal(calls.expressSettingFindAll, 0);
assert.deepEqual(result, [
{ code: 'SF', name: '顺丰', value: 'SF', label: '顺丰', is_system_setting: false, id: null, alias: null },
]);
});
assert.deepEqual(result, cachedValue);
});
it('should delegate index.getExpressList to the express service', async () => {
const { ctx } = createExpressServiceHarness();
let serviceCalls = 0;
@ -115,4 +268,35 @@ describe('test/app/service/systems/express.test.js', () => {
{ code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' },
]);
});
});
it('should delegate index.getExpressProductTypeList to the express service', async () => {
const { ctx } = createExpressServiceHarness();
let serviceCalls = 0;
let receivedExpressCode = '';
ctx.service = {
systems: {
express: {
async getExpressProductTypeList(expressCode) {
serviceCalls += 1;
receivedExpressCode = expressCode;
return [
{ code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' },
];
},
},
},
};
const methodService = new IndexMethodService(ctx);
const result = await methodService.getExpressProductTypeList({ express_code: 'SF' });
assert.equal(serviceCalls, 1);
assert.equal(receivedExpressCode, 'SF');
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
assert.deepEqual(result.data, [
{ code: 'SF-EXP', express_code: 'SF', name: '顺丰标准', value: 'SF-EXP', label: '顺丰标准' },
]);
});
});

View File

@ -518,4 +518,4 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.data.skipped_orders[0].skipped_reason, 'already_allocated');
assert.equal(captures.pickingRows, null);
});
});
});

View File

@ -4,14 +4,25 @@ const assert = require('node:assert/strict');
const PlatformService = require('../../../../app/service/systems/platform');
const IndexMethodService = require('../../../../app/service/systemMethods/index');
/**
* 创建平台服务测试桩。
*
* @param {Object} [options={}] 测试配置。
* @return {Object} 测试上下文和调用记录。
*/
function createPlatformServiceHarness(options = {}) {
const calls = {
findAll: 0,
platformFindAll: 0,
platformSettingFindAll: 0,
getCache: 0,
setCache: 0,
};
const ctx = {
user: {
store_id: options.storeId === undefined ? 100000 : options.storeId,
},
app: {
async getCacheAsync(cacheKey) {
calls.getCache += 1;
@ -32,13 +43,25 @@ function createPlatformServiceHarness(options = {}) {
Platform: {
async findAll(query) {
calls.findAll += 1;
calls.findAllQuery = query;
calls.platformFindAll += 1;
calls.platformFindAllQuery = query;
return options.rows || [
{ code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API' },
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS' },
];
},
},
PlatformSetting: {
async findAll(query) {
calls.findAll += 1;
calls.platformSettingFindAll += 1;
calls.platformSettingFindAllQuery = query;
return options.settingRows || [
{ id: 11, code: 'JD-STORE', platform_code: 'JD', warehouse_id: 100000 },
{ id: 12, code: 'TB-STORE', platform_code: 'TB', warehouse_id: 100000 },
];
},
},
},
logger: {
info() {},
@ -54,26 +77,30 @@ function createPlatformServiceHarness(options = {}) {
}
describe('test/app/service/systems/platform.test.js', () => {
it('should load platform list from database and cache it when cache is empty', async () => {
it('should load merged platform list from database and cache it when cache is empty', async () => {
const { ctx, calls } = createPlatformServiceHarness();
const service = new PlatformService(ctx);
const result = await service.getPlatformList();
assert.equal(calls.getCache, 1);
assert.equal(calls.findAll, 1);
assert.equal(calls.findAll, 2);
assert.equal(calls.platformFindAll, 1);
assert.equal(calls.platformSettingFindAll, 1);
assert.equal(calls.setCache, 1);
assert.equal(calls.cachePayload.cacheKey, 'platform:list');
assert.equal(calls.cachePayload.cacheKey, 'platform:list:100000');
assert.equal(calls.cachePayload.ttl, 600);
assert.deepEqual(result, [
{ code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API', value: 'JD', label: '京东平台' },
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' },
{ code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API', value: 'JD', label: '京东平台', platform_code: 'JD', platform_name: '京东平台', is_system_setting: false },
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false },
{ id: 11, code: 'JD-STORE', name: 'JD-STORE (京东平台)', value: 'JD-STORE', label: 'JD-STORE (京东平台)', is_system_setting: true, alias: '', platform_code: 'JD', platform_name: '京东平台', default_express_interface: 'OPEN_API' },
{ id: 12, code: 'TB-STORE', name: 'TB-STORE (淘宝平台)', value: 'TB-STORE', label: 'TB-STORE (淘宝平台)', is_system_setting: true, alias: '', platform_code: 'TB', platform_name: '淘宝平台', default_express_interface: 'QM_WMS' },
]);
});
it('should return cached platform list without querying database', async () => {
const cachedValue = [
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' },
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false },
];
const { ctx, calls } = createPlatformServiceHarness({
cachedValue,
@ -88,6 +115,25 @@ describe('test/app/service/systems/platform.test.js', () => {
assert.deepEqual(result, cachedValue);
});
it('should merge platform setting code to real platform code and name', async () => {
const { ctx } = createPlatformServiceHarness({
rows: [
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS' },
],
settingRows: [
{ id: 21, code: 'TB-STORE', platform_code: 'TB', warehouse_id: 100000 },
],
});
const service = new PlatformService(ctx);
const result = await service.getPlatformList();
assert.deepEqual(result, [
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台', platform_code: 'TB', platform_name: '淘宝平台', is_system_setting: false },
{ id: 21, code: 'TB-STORE', name: 'TB-STORE (淘宝平台)', value: 'TB-STORE', label: 'TB-STORE (淘宝平台)', is_system_setting: true, alias: '', platform_code: 'TB', platform_name: '淘宝平台', default_express_interface: 'QM_WMS' },
]);
});
it('should delegate index.getPlatformList to the platform service', async () => {
const { ctx } = createPlatformServiceHarness();
let serviceCalls = 0;
@ -115,4 +161,4 @@ describe('test/app/service/systems/platform.test.js', () => {
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' },
]);
});
});
});

View File

@ -219,4 +219,4 @@ describe('test/app/service/systems/polo_api.test.js', () => {
});
assert.strictEqual(result, expectedResult);
});
});
});

View File

@ -0,0 +1,284 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const SettingExpressService = require('../../../../../app/service/systems/setting/express');
function buildRecord(row, calls) {
return {
...row,
async update(updates) {
calls.updatePayload = {
id: Number(this.id),
updates: {
...updates,
},
};
Object.assign(this, updates);
return this;
},
get() {
return { ...this };
},
};
}
function createHarness(options = {}) {
const calls = {
systemExpressListCalls: 0,
findAndCountAllCalls: 0,
findOneCalls: [],
createPayload: null,
updatePayload: null,
};
const systemExpressList = options.systemExpressList || [
{ code: 'SF', name: '顺丰' },
{ code: 'YTO', name: '圆通' },
];
const settingRows = options.settingRows || [
{ id: 11, warehouse_id: 100000, code: 'SF-001', name: '顺丰设置', express_code: 'SF' },
{ id: 12, warehouse_id: 100000, code: 'YTO-001', name: '圆通设置', express_code: 'YTO' },
];
const ctx = {
user: {
store_id: options.storeId || 100000,
},
where: options.where || {},
whereParsed: options.whereParsed || null,
app: {
Sequelize: {
Op,
},
},
model: {
ExpressSetting: {
async findAndCountAll(query) {
calls.findAndCountAllCalls += 1;
calls.findAndCountAllQuery = query;
return {
rows: options.rows || settingRows,
count: options.count !== undefined ? options.count : (options.rows || settingRows).length,
};
},
async findOne(query) {
calls.findOneCalls.push(query);
const where = query.where || {};
const excludedId = where.id && where.id[Op.ne] ? Number(where.id[Op.ne]) : null;
const found = (options.settingRows || settingRows).find(row => {
const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id);
const isExcluded = excludedId && Number(row.id) === excludedId;
if (Object.prototype.hasOwnProperty.call(where, 'id') && !Object.prototype.hasOwnProperty.call(where, 'code')) {
return sameWarehouse && Number(row.id) === Number(where.id) && !isExcluded;
}
if (Object.prototype.hasOwnProperty.call(where, 'code')) {
const sameCode = String(row.code || '') === String(where.code || '');
return sameWarehouse && sameCode && !isExcluded;
}
return sameWarehouse && !isExcluded;
});
return found ? buildRecord({ ...found }, calls) : null;
},
async create(payload) {
calls.createPayload = {
...payload,
};
const created = buildRecord({
id: options.createdId || 99,
...payload,
}, calls);
return created;
},
},
},
service: {
systems: {
express: {
async getSystemExpressList() {
calls.systemExpressListCalls += 1;
return systemExpressList;
},
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systems/setting/express.test.js', () => {
it('should list mapped express settings with pagination and system express names', async () => {
const { ctx, calls } = createHarness({
where: {
quickWhere: '设置',
},
whereParsed: {
dynamicConditions: [],
rawConditionsByField: {
quickWhere: {
value: '设置',
},
},
},
rows: [
{ id: 12, warehouse_id: 100000, code: 'YTO-001', name: '圆通设置', express_code: 'YTO' },
],
count: 1,
});
const service = new SettingExpressService(ctx);
const result = await service.list({
page: 2,
page_size: 1,
where: {
quickWhere: '设置',
},
});
assert.equal(calls.findAndCountAllCalls, 1);
assert.equal(calls.systemExpressListCalls, 1);
assert.equal(calls.findAndCountAllQuery.offset, 1);
assert.equal(calls.findAndCountAllQuery.limit, 1);
assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000);
assert.equal(result.code, 200);
assert.equal(result.data.total, 1);
assert.equal(result.data.page, 2);
assert.equal(result.data.page_size, 1);
assert.deepEqual(result.data.list, [
{
id: 12,
warehouse_id: 100000,
code: 'YTO-001',
name: '圆通设置',
express_code: 'YTO',
express_name: '圆通',
express_label: '圆通',
},
]);
});
it('should prefer pagination object over legacy page fields', async () => {
const { ctx, calls } = createHarness({
whereParsed: {
dynamicConditions: [],
rawConditionsByField: {},
},
});
const service = new SettingExpressService(ctx);
const result = await service.list({
pagination: {
page: 3,
pageSize: 2,
},
page: 1,
page_size: 10,
where: {},
});
assert.equal(calls.findAndCountAllCalls, 1);
assert.equal(calls.findAndCountAllQuery.offset, 4);
assert.equal(calls.findAndCountAllQuery.limit, 2);
assert.equal(result.data.page, 3);
assert.equal(result.data.page_size, 2);
});
it('should load system express base list only', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const result = await service.listBase();
assert.equal(calls.systemExpressListCalls, 1);
assert.deepEqual(result, {
code: 200,
data: [
{ code: 'SF', name: '顺丰' },
{ code: 'YTO', name: '圆通' },
],
});
});
it('should mark code as occupied and exclude current record when checking uniqueness', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const occupied = await service.checkCodeUnique({
code: 'SF-001',
});
const available = await service.checkCodeUnique({
id: 11,
code: 'SF-001',
});
assert.equal(calls.findOneCalls.length, 2);
assert.equal(occupied.data.isUnique, false);
assert.equal(occupied.data.message, '快递编码已被当前仓库使用');
assert.equal(available.data.isUnique, true);
});
it('should create a mapping after validating system express and code uniqueness', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const result = await service.create({
code: 'jd-001',
name: '京东设置',
express_code: 'SF',
});
assert.equal(calls.systemExpressListCalls, 1);
assert.equal(calls.findOneCalls.length, 1);
assert.equal(calls.createPayload.warehouse_id, 100000);
assert.equal(calls.createPayload.code, 'JD-001'.toUpperCase());
assert.equal(calls.createPayload.express_code, 'SF');
assert.equal(result.data.code, 'JD-001'.toUpperCase());
assert.equal(result.data.express_name, '顺丰');
});
it('should reject create when system express code does not exist', async () => {
const { ctx } = createHarness();
const service = new SettingExpressService(ctx);
await assert.rejects(async () => {
await service.create({
code: 'SF-NEW',
name: '顺丰新增',
express_code: 'NOT_EXISTS',
});
}, /系统快递编码不存在/);
});
it('should update a mapping and allow the same code on the current record', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const result = await service.update({
id: 11,
code: 'SF-001',
name: '顺丰新设置',
express_code: 'SF',
});
assert.equal(calls.findOneCalls.length >= 1, true);
assert.equal(calls.updatePayload.id, 11);
assert.equal(calls.updatePayload.updates.code, 'SF-001');
assert.equal(calls.updatePayload.updates.name, '顺丰新设置');
assert.equal(calls.updatePayload.updates.express_code, 'SF');
assert.equal(result.data.code, 'SF-001');
assert.equal(result.data.name, '顺丰新设置');
});
});

View File

@ -0,0 +1,340 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const SettingExpressInterfaceService = require('../../../../../app/service/systems/setting/expressInterface');
function buildRecord(row, calls) {
return {
...row,
async update(updates) {
calls.updatePayload = {
id: Number(this.id),
updates: {
...updates,
},
};
Object.assign(this, updates);
return this;
},
async destroy() {
calls.destroyPayload = {
id: Number(this.id),
};
return 1;
},
get() {
return { ...this };
},
};
}
function createHarness(options = {}) {
const calls = {
findAndCountAllCalls: 0,
findOneCalls: [],
createPayload: null,
updatePayload: null,
destroyPayload: null,
};
const defaultRows = options.rows || [
{
id: 11,
warehouse_id: 100000,
name: '顺丰接口',
express_code: 'SF',
platform_code: 'TB',
express_platform_id: 1,
sender_name: '张三',
sender_tel: '13800000000',
weight: 10,
token: 'token-1',
viewer: '验视员A',
client_id: 'client-1',
is_share: 1,
share_id: 9001,
can_use_count: 3,
province_name: '广东省',
city_name: '深圳市',
district_name: '南山区',
site_code: 'SITE-01',
product_type: 'STD',
shop_name: '旗舰店',
},
{
id: 12,
warehouse_id: 100000,
name: '圆通接口',
express_code: 'YTO',
platform_code: 'JD',
express_platform_id: 2,
},
{
id: 21,
warehouse_id: 200000,
name: '其他仓库接口',
express_code: 'SF',
platform_code: 'TB',
express_platform_id: 1,
},
];
const ctx = {
user: {
store_id: options.storeId || 100000,
},
where: options.where || {},
whereParsed: options.whereParsed || null,
app: {
Sequelize: {
Op,
},
},
model: {
ExpressInterface: {
async findAndCountAll(query) {
calls.findAndCountAllCalls += 1;
calls.findAndCountAllQuery = query;
return {
rows: options.listRows || defaultRows,
count: options.count !== undefined ? options.count : (options.listRows || defaultRows).length,
};
},
async findOne(query) {
calls.findOneCalls.push(query);
const where = query.where || {};
const excludedId = where.id && where.id[Op.ne] ? Number(where.id[Op.ne]) : null;
const found = defaultRows.find(row => {
const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id);
const isExcluded = excludedId && Number(row.id) === excludedId;
if (Object.prototype.hasOwnProperty.call(where, 'id') && !Object.prototype.hasOwnProperty.call(where, 'express_code') && !Object.prototype.hasOwnProperty.call(where, 'platform_code')) {
return sameWarehouse && Number(row.id) === Number(where.id) && !isExcluded;
}
if (Object.prototype.hasOwnProperty.call(where, 'express_code')) {
const sameCode = String(row.express_code || '') === String(where.express_code || '');
if (!sameCode) {
return false;
}
}
if (Object.prototype.hasOwnProperty.call(where, 'platform_code')) {
const samePlatform = String(row.platform_code || '') === String(where.platform_code || '');
if (!samePlatform) {
return false;
}
}
if (Object.prototype.hasOwnProperty.call(where, 'express_platform_id')) {
if (Number(row.express_platform_id) !== Number(where.express_platform_id)) {
return false;
}
}
return sameWarehouse && !isExcluded;
});
return found ? buildRecord({ ...found }, calls) : null;
},
async create(payload) {
calls.createPayload = {
...payload,
};
return buildRecord({
id: options.createdId || 99,
...payload,
}, calls);
},
},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systems/setting/expressInterface.test.js', () => {
it('should list express interfaces with pagination and quick where', async () => {
const { ctx, calls } = createHarness({
where: {
quickWhere: '接口',
},
whereParsed: {
dynamicConditions: [],
rawConditionsByField: {
quickWhere: {
value: '接口',
},
},
},
listRows: [
{
id: 11,
warehouse_id: 100000,
name: '顺丰接口',
express_code: 'SF',
platform_code: 'TB',
express_platform_id: 1,
sender_name: '张三',
sender_tel: '13800000000',
weight: 10,
token: 'token-1',
viewer: '验视员A',
client_id: 'client-1',
is_share: 1,
share_id: 9001,
can_use_count: 3,
province_name: '广东省',
city_name: '深圳市',
district_name: '南山区',
site_code: 'SITE-01',
product_type: 'STD',
shop_name: '旗舰店',
},
],
count: 1,
});
const service = new SettingExpressInterfaceService(ctx);
const result = await service.list({
page: 2,
page_size: 1,
where: {
quickWhere: '接口',
},
});
assert.equal(calls.findAndCountAllCalls, 1);
assert.equal(calls.findAndCountAllQuery.offset, 1);
assert.equal(calls.findAndCountAllQuery.limit, 1);
assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000);
assert.equal(result.code, 200);
assert.equal(result.data.total, 1);
assert.equal(result.data.page, 2);
assert.equal(result.data.page_size, 1);
assert.equal(result.data.list[0].name, '顺丰接口');
assert.equal(result.data.list[0].platform_code, 'TB');
assert.equal(result.data.list[0].express_platform_id, 1);
});
it('should create a new express interface and normalize codes', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
const result = await service.create({
name: '京东接口',
express_code: 'jd',
platform_code: 'tb',
express_platform_id: 3,
sender_name: '李四',
sender_tel: '13900000000',
token: ' token-2 ',
is_share: 1,
can_use_count: 5,
});
assert.equal(calls.createPayload.warehouse_id, 100000);
assert.equal(calls.createPayload.express_code, 'JD');
assert.equal(calls.createPayload.platform_code, 'TB');
assert.equal(calls.createPayload.express_platform_id, 3);
assert.equal(result.data.express_code, 'JD');
assert.equal(result.data.platform_code, 'TB');
assert.equal(result.data.sender_name, '李四');
assert.equal(result.data.token, 'token-2');
});
it('should reject create when express code conflicts inside the current warehouse', async () => {
const { ctx } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
await assert.rejects(async () => {
await service.create({
name: '重复编码接口',
express_code: 'SF',
platform_code: 'WX',
express_platform_id: 4,
});
}, /快递编码已被当前仓库使用/);
});
it('should reject create when platform and interface combination conflicts', async () => {
const { ctx } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
await assert.rejects(async () => {
await service.create({
name: '重复接口',
express_code: 'ZTO',
platform_code: 'TB',
express_platform_id: 1,
});
}, /当前平台和快递接口组合已被使用/);
});
it('should update a record with boundary checks and partial fields', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
const result = await service.update({
id: 11,
name: '顺丰接口-更新',
token: ' token-updated ',
can_use_count: 0,
});
assert.equal(calls.findOneCalls.length >= 1, true);
assert.equal(calls.updatePayload.id, 11);
assert.equal(calls.updatePayload.updates.name, '顺丰接口-更新');
assert.equal(calls.updatePayload.updates.token, 'token-updated');
assert.equal(calls.updatePayload.updates.can_use_count, 0);
assert.equal(result.data.name, '顺丰接口-更新');
});
it('should delete a record only inside the current warehouse', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressInterfaceService(ctx);
const result = await service.delete({
id: 11,
});
assert.equal(calls.destroyPayload.id, 11);
assert.equal(result.code, 200);
assert.equal(result.data.deleted, true);
assert.equal(result.data.warehouse_id, 100000);
});
it('should reject cross-warehouse updates and deletes', async () => {
const { ctx } = createHarness({
storeId: 100000,
rows: [
{
id: 21,
warehouse_id: 200000,
name: '其他仓库接口',
express_code: 'SF',
platform_code: 'TB',
express_platform_id: 1,
},
],
});
const service = new SettingExpressInterfaceService(ctx);
await assert.rejects(async () => {
await service.update({
id: 21,
name: '越权更新',
});
}, /快递接口不存在或无权限操作/);
await assert.rejects(async () => {
await service.delete({
id: 21,
});
}, /快递接口不存在或无权限操作/);
});
});

View File

@ -0,0 +1,331 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const SettingPlatformService = require('../../../../../app/service/systems/setting/platform');
function buildRecord(row, calls) {
return {
...row,
async update(updates) {
calls.updatePayload = {
id: Number(this.id),
updates: {
...updates,
},
};
Object.assign(this, updates);
return this;
},
async destroy() {
calls.destroyPayload = {
id: Number(this.id),
};
return 1;
},
get() {
return { ...this };
},
};
}
function createHarness(options = {}) {
const calls = {
findAndCountAllCalls: 0,
findOneCalls: [],
createPayload: null,
updatePayload: null,
destroyPayload: null,
platformFindOneCalls: [],
};
const platformRows = options.platformRows || [
{ code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS' },
{ code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API' },
{ code: 'PDD', name: '拼多多平台', default_express_interface: 'PDD_API' },
];
const defaultRows = options.rows || [
{
id: 11,
code: 'TB-STORE',
name: '淘宝设置',
platform_code: 'TB',
warehouse_id: 100000,
platform: platformRows[0],
},
{
id: 12,
code: 'JD-STORE',
name: '京东设置',
platform_code: 'JD',
warehouse_id: 100000,
platform: platformRows[1],
},
{
id: 21,
code: 'OTHER-STORE',
name: '其他仓库设置',
platform_code: 'TB',
warehouse_id: 200000,
platform: platformRows[0],
},
];
const ctx = {
user: {
store_id: options.storeId || 100000,
},
where: options.where || {},
whereParsed: options.whereParsed || null,
app: {
Sequelize: {
Op,
},
},
model: {
Platform: {
async findOne(query) {
calls.platformFindOneCalls.push(query);
const code = String(query.where && query.where.code || '').trim();
const found = platformRows.find(row => String(row.code) === code);
return found ? { ...found } : null;
},
},
PlatformSetting: {
async findAndCountAll(query) {
calls.findAndCountAllCalls += 1;
calls.findAndCountAllQuery = query;
return {
rows: options.listRows || defaultRows,
count: options.count !== undefined ? options.count : (options.listRows || defaultRows).length,
};
},
async findOne(query) {
calls.findOneCalls.push(query);
const where = query.where || {};
const excludedId = where.id && where.id[Op.ne] ? Number(where.id[Op.ne]) : null;
const found = defaultRows.find(row => {
const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id);
const isExcluded = excludedId && Number(row.id) === excludedId;
if (Object.prototype.hasOwnProperty.call(where, 'id') && !Object.prototype.hasOwnProperty.call(where, 'code') && !Object.prototype.hasOwnProperty.call(where, 'platform_code')) {
return sameWarehouse && Number(row.id) === Number(where.id) && !isExcluded;
}
if (Object.prototype.hasOwnProperty.call(where, 'code')) {
if (String(row.code || '') !== String(where.code || '')) {
return false;
}
}
if (Object.prototype.hasOwnProperty.call(where, 'platform_code')) {
if (String(row.platform_code || '') !== String(where.platform_code || '')) {
return false;
}
}
return sameWarehouse && !isExcluded;
});
return found ? buildRecord({ ...found }, calls) : null;
},
async create(payload) {
calls.createPayload = {
...payload,
};
const platform = platformRows.find(row => String(row.code) === String(payload.platform_code || '')) || null;
return buildRecord({
id: options.createdId || 99,
...payload,
platform,
}, calls);
},
},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systems/setting/platform.test.js', () => {
it('should list platform settings with pagination and quick where', async () => {
const { ctx, calls } = createHarness({
where: {
quickWhere: '设置',
},
whereParsed: {
dynamicConditions: [],
rawConditionsByField: {
quickWhere: {
value: '设置',
},
},
},
listRows: [
{
id: 11,
code: 'TB-STORE',
name: '淘宝设置',
platform_code: 'TB',
warehouse_id: 100000,
platform: {
code: 'TB',
name: '淘宝平台',
default_express_interface: 'QM_WMS',
},
},
],
count: 1,
});
const service = new SettingPlatformService(ctx);
const result = await service.list({
page: 2,
page_size: 1,
where: {
quickWhere: '设置',
},
});
assert.equal(calls.findAndCountAllCalls, 1);
assert.equal(calls.findAndCountAllQuery.offset, 1);
assert.equal(calls.findAndCountAllQuery.limit, 1);
assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000);
assert.equal(result.code, 200);
assert.equal(result.data.total, 1);
assert.equal(result.data.page, 2);
assert.equal(result.data.page_size, 1);
assert.equal(result.data.list[0].code, 'TB-STORE');
assert.equal(result.data.list[0].platform_code, 'TB');
assert.equal(result.data.list[0].platform_name, '淘宝平台');
assert.equal(result.data.list[0].platform_label, 'TB-STORE (淘宝平台)');
});
it('should create a new platform setting and ignore external warehouse id', async () => {
const { ctx, calls } = createHarness();
const service = new SettingPlatformService(ctx);
const result = await service.create({
code: 'PDD-STORE',
name: '淘宝设置',
platform_code: 'PDD',
warehouse_id: 999999,
});
assert.equal(calls.createPayload.warehouse_id, 100000);
assert.equal(calls.createPayload.code, 'PDD-STORE');
assert.equal(calls.createPayload.name, '淘宝设置');
assert.equal(calls.createPayload.platform_code, 'PDD');
assert.equal(result.data.code, 'PDD-STORE');
assert.equal(result.data.platform_code, 'PDD');
assert.equal(result.data.platform_name, '拼多多平台');
assert.equal(result.data.platform_label, 'PDD-STORE (拼多多平台)');
});
it('should reject create when platform code is missing in the system platform table', async () => {
const { ctx } = createHarness();
const service = new SettingPlatformService(ctx);
await assert.rejects(async () => {
await service.create({
code: 'TB-STORE',
name: '淘宝设置',
platform_code: 'UNKNOWN',
});
}, /platform_code 不存在或不支持/);
});
it('should reject create when code or platform code conflicts in the current warehouse', async () => {
const { ctx } = createHarness();
const service = new SettingPlatformService(ctx);
await assert.rejects(async () => {
await service.create({
code: 'TB-STORE',
name: '重复设置',
platform_code: 'JD',
});
}, /code 已被当前仓库使用/);
await assert.rejects(async () => {
await service.create({
code: 'NEW-CODE',
name: '重复平台',
platform_code: 'TB',
});
}, /platform_code 已被当前仓库使用/);
});
it('should update a record with boundary checks and return platform display fields', async () => {
const { ctx, calls } = createHarness();
const service = new SettingPlatformService(ctx);
const result = await service.update({
id: 11,
code: 'TB-STORE-NEW',
name: '淘宝设置-更新',
platform_code: 'PDD',
});
assert.equal(calls.findOneCalls.length >= 1, true);
assert.equal(calls.updatePayload.id, 11);
assert.equal(calls.updatePayload.updates.code, 'TB-STORE-NEW');
assert.equal(calls.updatePayload.updates.name, '淘宝设置-更新');
assert.equal(calls.updatePayload.updates.platform_code, 'PDD');
assert.equal(result.data.code, 'TB-STORE-NEW');
assert.equal(result.data.platform_code, 'PDD');
assert.equal(result.data.platform_name, '拼多多平台');
});
it('should delete a record only inside the current warehouse', async () => {
const { ctx, calls } = createHarness();
const service = new SettingPlatformService(ctx);
const result = await service.delete({
id: 11,
});
assert.equal(calls.destroyPayload.id, 11);
assert.equal(result.code, 200);
assert.equal(result.data.deleted, true);
assert.equal(result.data.warehouse_id, 100000);
});
it('should reject cross-warehouse updates and deletes', async () => {
const { ctx } = createHarness({
storeId: 100000,
rows: [
{
id: 21,
code: 'OTHER-STORE',
name: '其他仓库设置',
platform_code: 'TB',
warehouse_id: 200000,
platform: {
code: 'TB',
name: '淘宝平台',
default_express_interface: 'QM_WMS',
},
},
],
});
const service = new SettingPlatformService(ctx);
await assert.rejects(async () => {
await service.update({
id: 21,
name: '越权更新',
});
}, /平台设置不存在或无权限操作/);
await assert.rejects(async () => {
await service.delete({
id: 21,
});
}, /平台设置不存在或无权限操作/);
});
});

View File

@ -24,6 +24,7 @@ function formatDate(date, formatStr = 'YYYY-MM-DD HH:mm:ss') {
function createServiceHarness() {
const calls = {
detailUpdate: 0,
updateReceivingStats: 0,
};
const model = {
@ -124,4 +125,24 @@ describe('test/app/service/systems/storage.receiving.detailChange.test.js', () =
assert.equal(calls.detailUpdate, 0);
assert.equal(calls.operationLog || 0, 0);
});
it('should allow same-day expiry_date when provided as Date input', async () => {
const { service, calls } = createServiceHarness();
service.updateReceivingStats = async () => {
calls.updateReceivingStats += 1;
};
const result = await service.detailChange({
id: 501,
receiving_id: 123,
actual_quantity: 1,
expiry_date: new Date(),
});
assert.equal(result.code, 200);
assert.equal(result.message, '修改成功');
assert.equal(calls.detailUpdate, 1);
assert.equal(calls.updateReceivingStats, 1);
assert.equal(calls.operationLog, 1);
});
});

View File

@ -0,0 +1,72 @@
# 收货入库回归测试报告
- 测试类型:回归测试 / 单元测试
- 执行时间:2026-04-17 17:27:16
- 执行入口:`npm run test:local`
- 覆盖目标:
- [test/app/controller/system.storage.receiving.test.js](../test/app/controller/system.storage.receiving.test.js)
- [test/app/service/systems/storage.receiving.detailChange.test.js](../test/app/service/systems/storage.receiving.detailChange.test.js)
- [test/app/service/systems/storage.receiving.report.test.js](../test/app/service/systems/storage.receiving.report.test.js)
## 测试目标
验证收货模块现有回归用例是否稳定,重点覆盖收货列表、收货明细变更、收货完成报表三条链路。
## 测试范围
本次仅执行现有回归用例,不修改任何代码,不新增任何测试数据。
## 测试产物
- Mocha / egg-bin 执行结果
- mochawesome 报告:`node_modules/.mochawesome-reports/mochawesome.html`
- 本测试报告:`test_reports/fail/20260417-172716-收货入库回归测试报告.md`
## 测试结果摘要
- 通过:2 个目标文件
- 失败:1 个目标文件
- 总计:3 个目标文件
- 通过用例数:28
- 失败用例数:1
### 通过项
- [test/app/controller/system.storage.receiving.test.js](../test/app/controller/system.storage.receiving.test.js):15 passing
- [test/app/service/systems/storage.receiving.report.test.js](../test/app/service/systems/storage.receiving.report.test.js):13 passing
### 失败项
- [test/app/service/systems/storage.receiving.detailChange.test.js](../test/app/service/systems/storage.receiving.detailChange.test.js)
- 失败用例:`should reject expired expiry_date before updating receiving detail`
- 失败断言:期望返回 `code = 400`,实际返回 `code = 500`
- 失败位置:测试文件第 112 行附近
## 失败原因
当前 `detailChange` 实现没有在明细更新前拦截过期 `expiry_date`,请求继续进入后续更新流程;随后执行到 `updateReceivingStats`,而该单测 harness 未提供 `ctx.model.transaction`,最终被服务层 `catch` 转成 `500`。
相关实现位置:
- [app/service/systems/storage/receiving.js](../app/service/systems/storage/receiving.js#L1952)
- [app/service/systems/storage/receiving.js](../app/service/systems/storage/receiving.js#L1686)
## 最小复现信息
```text
npm run test:local -- test/app/service/systems/storage.receiving.detailChange.test.js
```
该单测即可稳定复现失败,无需额外环境操作。
## 环境 / 数据 / 依赖影响判断
- 环境:未见 npm / egg-bin 启动失败,测试框架可正常运行
- 数据:未观察到外部测试数据缺失导致的报错,本次失败是可复现的断言失败
- 依赖:未发现缺包或安装失败问题
- 结论:本次失败主要来自当前实现与现有回归用例预期不一致,且单测 harness 对下游事务依赖的模拟不完整
## 结论与建议
- 当前收货回归测试整体为部分通过,2 个目标文件通过,1 个目标文件失败
- 失败场景是收货明细变更的过期日期拦截,建议后续补齐该分支的业务校验后再回归验证