WMS_MAIN/app/service/systems/setting/expressInterface.js
liufumingren 5ce689d771 1
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 19:20:31 +08:00

1078 lines
35 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const DEFAULT_CACHE_TTL_SECONDS = 600;
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 {number|string} warehouseId 仓库 ID
* @param {string} platformCode 平台代码
* @return {string} 缓存键
*/
getWarehousePlatformCacheKey(warehouseId, platformCode) {
const normalizedWarehouseId = Number(warehouseId || 0);
const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase();
return `express_interface:warehouse:${normalizedWarehouseId}:platform:${normalizedPlatformCode}`;
}
/**
* 删除指定缓存键。
*
* @param {string} cacheKey 缓存键
* @return {Promise<void>}
*/
async deleteCacheByKey(cacheKey) {
if (!cacheKey) {
return;
}
const { app } = this;
if (app && typeof app.delCacheAsync === 'function') {
await app.delCacheAsync(cacheKey);
return;
}
if (app && typeof app.setCacheAsync === 'function') {
await app.setCacheAsync(cacheKey, null, 0);
}
}
/**
* 清理当前仓库与平台维度的快递接口缓存。
*
* @param {number|string} warehouseId 仓库 ID
* @param {string} platformCode 平台代码
* @return {Promise<void>}
*/
async clearWarehousePlatformCache(warehouseId, platformCode) {
await this.deleteCacheByKey(this.getWarehousePlatformCacheKey(warehouseId, platformCode));
}
/**
* 规范化平台代码。
*
* @param {string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} [maxLength=20] 最大长度
* @return {string} 规范化后的平台代码
*/
normalizePlatformCode(value, fieldName, maxLength = 20) {
const normalized = this.normalizeText(value, fieldName, maxLength).toUpperCase();
if (!normalized) {
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
return normalized;
}
/**
* 规范化文本值。
*
* @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',
},
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 options
* @return {Array<Object>} Sequelize 关联配置,仅保留系统快递关联。
*/
getInterfaceInclude(options = {}) {
const { ctx } = this;
const { full = false } = options;
const include = {
model: ctx.model.Express,
as: 'express',
required: false,
};
if (!full) {
include.attributes = [ 'code', 'name' ];
}
return [
include,
];
}
/**
* 获取快递接口模型的全量字段。
*
* @return {Array<string>} 模型字段列表
*/
getInterfaceFullAttributes() {
const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.ExpressInterface && this.ctx.model.ExpressInterface.rawAttributes;
if (!rawAttributes || typeof rawAttributes !== 'object') {
return [];
}
return Object.keys(rawAttributes);
}
/**
* 复制普通对象或数组,避免缓存对象被外部修改。
*
* @param {*} value 待复制的值
* @return {*} 复制后的值
*/
clonePlainValue(value) {
if (Array.isArray(value)) {
return value.map(item => this.clonePlainValue(item));
}
if (value && typeof value === 'object') {
const cloned = {};
for (const [ key, item ] of Object.entries(value)) {
cloned[key] = this.clonePlainValue(item);
}
return cloned;
}
return value;
}
/**
* 规范化系统快递记录。
*
* @param {Object} row 数据库记录
* @return {Object|null} 规范化后的系统快递信息
*/
normalizeExpressRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
return {
code: this.normalizeOptionalText(row.code, 'express.code', 50),
name: this.normalizeOptionalText(row.name, 'express.name', 255),
polyapi_extra_info: row.polyapi_extra_info === undefined ? null : row.polyapi_extra_info,
pdd_code: this.normalizeOptionalText(row.pdd_code, 'express.pdd_code', 255),
};
}
/**
* 规范化快递接口记录。
*
* @param {Object} row 数据库记录
* @return {Object|null} 规范化后的记录
*/
normalizeInterfaceRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
const express = this.normalizeExpressRow(row.express && typeof row.express === 'object' ? row.express : 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),
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),
express,
express_name: express ? express.name : null,
express_polyapi_extra_info: express ? express.polyapi_extra_info : null,
express_pdd_code: express ? express.pdd_code : null,
};
}
/**
* 规范化快递接口的全量记录。
*
* @param {Object} row 数据库记录
* @return {Object|null} 规范化后的全量记录
*/
normalizeFullInterfaceRow(row) {
if (!row || typeof row !== 'object') {
return null;
}
const attributes = this.getInterfaceFullAttributes();
const normalized = {};
const keys = attributes.length > 0 ? attributes : Object.keys(row);
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(row, key)) {
normalized[key] = this.clonePlainValue(row[key]);
}
}
if (Object.prototype.hasOwnProperty.call(row, 'express')) {
normalized.express = this.clonePlainValue(row.express);
}
return normalized;
}
/**
* 规范化快递接口的全量记录数组,并按 weight / id 排序。
*
* @param {Array|Object} rows 数据库记录数组或单条记录
* @return {Array<Object>} 规范化后的全量记录数组
*/
normalizeFullInterfaceRows(rows) {
const sourceRows = Array.isArray(rows)
? rows
: rows ? [ rows ] : [];
return sourceRows
.map(row => this.normalizeFullInterfaceRow(row))
.filter(row => row)
.sort((left, right) => {
const leftWeight = left.weight === undefined || left.weight === null
? Number.POSITIVE_INFINITY
: Number(left.weight);
const rightWeight = right.weight === undefined || right.weight === null
? Number.POSITIVE_INFINITY
: Number(right.weight);
if (leftWeight !== rightWeight) {
return leftWeight - rightWeight;
}
const leftId = left.id === undefined || left.id === null
? Number.POSITIVE_INFINITY
: Number(left.id);
const rightId = right.id === undefined || right.id === null
? Number.POSITIVE_INFINITY
: Number(right.id);
return leftId - rightId;
});
}
/**
* 解析仓库与平台代码查询条件。
*
* @param {Object} data 请求参数
* @return {Object} 归一化后的仓库与平台信息
*/
resolveWarehousePlatformTarget(data = {}) {
const warehouseValue = data.warehouse_id !== undefined
? data.warehouse_id
: data.warehouseId;
const platformValue = data.platform_code !== undefined
? data.platform_code
: data.platformCode;
const warehouseId = warehouseValue === undefined
? this.getCurrentStoreId()
: this.normalizeInteger(warehouseValue, 'warehouse_id', { min: 1 });
const platformCode = this.normalizePlatformCode(platformValue, 'platform_code', 20);
return {
warehouseId,
platformCode,
};
}
/**
* 查找当前仓库下的快递接口记录。
*
* @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,
},
include: this.getInterfaceInclude(),
});
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' ],
include: this.getInterfaceInclude(),
});
}
/**
* 查找同仓下的平台接口冲突记录。
*
* @param {string} platformCode 平台代码
* @param {number|null} [excludeId=null] 排除的记录 ID
* @return {Promise<Object|null>} 冲突记录
*/
async findInterfaceConflict(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.ExpressInterface.findOne({
where,
attributes: [ 'id', 'platform_code' ],
include: this.getInterfaceInclude(),
});
}
/**
* 校验快递编码是否可用。
*
* @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, excludeId = null) {
const conflict = await this.findInterfaceConflict(platformCode, 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,
},
include: this.getInterfaceInclude(),
attributes: [
'id', 'name', 'express_code', 'warehouse_id', 'platform_code',
'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,
distinct: true,
});
const list = Array.isArray(result && result.rows)
? result.rows.map(row => this.normalizeInterfaceRow(row && typeof row.get === 'function' ? row.get({ plain: true }) : 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>} 查询结果,data 为快递接口数组
*/
async listByWarehousePlatformCode(data = {}) {
const { ctx, app } = this;
const { warehouseId, platformCode } = this.resolveWarehousePlatformTarget(data);
const cacheKey = this.getWarehousePlatformCacheKey(warehouseId, platformCode);
if (app && typeof app.getCacheAsync === 'function') {
try {
const cachedValue = await app.getCacheAsync(cacheKey);
if (cachedValue !== null && cachedValue !== undefined) {
return {
code: 200,
data: this.normalizeFullInterfaceRows(cachedValue),
};
}
} catch (error) {
if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 读取缓存失败', {
error: error.message,
cacheKey,
});
}
}
}
const settings = await ctx.model.ExpressInterface.findAll({
where: {
warehouse_id: warehouseId,
platform_code: platformCode,
},
include: this.getInterfaceInclude({ full: true }),
attributes: this.getInterfaceFullAttributes(),
order: [[ 'weight', 'ASC' ], [ 'id', 'ASC' ]],
});
const plainSettings = Array.isArray(settings)
? settings.map(setting => (setting && typeof setting.get === 'function'
? setting.get({ plain: true })
: setting))
: [];
const normalized = this.normalizeFullInterfaceRows(plainSettings);
if (normalized && app && typeof app.setCacheAsync === 'function') {
try {
await app.setCacheAsync(cacheKey, normalized, DEFAULT_CACHE_TTL_SECONDS);
} catch (error) {
if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 写入缓存失败', {
error: error.message,
cacheKey,
});
}
}
}
return {
code: 200,
data: normalized,
};
}
/**
* 创建快递接口。
*
* @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();
if (!name) {
throw this.createError('name 参数不能为空', 400);
}
if (!expressCode) {
throw this.createError('express_code 参数不能为空', 400);
}
if (!platformCode) {
throw this.createError('platform_code 参数不能为空', 400);
}
await this.ensureCodeAvailable(expressCode);
await this.ensureInterfaceAvailable(platformCode);
const payload = {
warehouse_id: currentStoreId,
name,
express_code: expressCode,
platform_code: platformCode,
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 plainCreatedRow = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
const createdSetting = await this.findInterfaceById(Number(plainCreatedRow && plainCreatedRow.id));
const plainCreated = createdSetting && typeof createdSetting.get === 'function'
? createdSetting.get({ plain: true })
: createdSetting;
await this.clearWarehousePlatformCache(currentStoreId, payload.platform_code);
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 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 && !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 || '';
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 (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);
}
const previousWarehouseId = Number(setting.warehouse_id || this.getCurrentStoreId());
const previousPlatformCode = this.normalizePlatformCode(setting.platform_code, 'platform_code', 20);
const nextWarehouseId = previousWarehouseId;
const nextCachePlatformCode = Object.prototype.hasOwnProperty.call(updates, 'platform_code')
? this.normalizePlatformCode(updates.platform_code, 'platform_code', 20)
: previousPlatformCode;
await setting.update(updates);
await Promise.all(Array.from(new Set([
this.getWarehousePlatformCacheKey(previousWarehouseId, previousPlatformCode),
this.getWarehousePlatformCacheKey(nextWarehouseId, nextCachePlatformCode),
])).map(cacheKey => this.deleteCacheByKey(cacheKey)));
const refreshedSetting = await this.findInterfaceById(id);
const plainSetting = refreshedSetting && typeof refreshedSetting.get === 'function'
? refreshedSetting.get({ plain: true })
: refreshedSetting;
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();
await this.clearWarehousePlatformCache(plainSetting.warehouse_id, plainSetting.platform_code);
return {
code: 200,
data: {
id: Number(plainSetting.id),
warehouse_id: Number(plainSetting.warehouse_id),
deleted: true,
},
};
}
}
module.exports = SettingExpressInterfaceService;