762 lines
22 KiB
JavaScript

'use strict';
const Service = require('egg').Service;
const crypto = require('node:crypto');
const {
DELETED_SHOP_NAME_PREFIX,
buildNotDeletedShopWhere,
} = require('../../lib/shop_soft_delete');
/**
* 店铺业务服务。
*/
class ShopsService extends Service {
/**
* 生成待授权占位店铺名并校验唯一性(最多重试 5 次)。
*
* @param {Object} payload 入参
* @param {number} payload.warehouseId 仓库 ID
* @param {string} payload.platformCode 平台编码
* @return {Promise<string>} 可用的占位店铺名
*/
async generatePendingShopName(payload) {
const { app, ctx } = this;
const { Op } = app.Sequelize;
const { warehouseId, platformCode } = payload;
const maxRetryTimes = 5;
for (let attempt = 1; attempt <= maxRetryTimes; attempt++) {
const shopName = `PENDING_${this.generateAuthorizeRandomCode()}`;
const existed = await ctx.model.Shop.findOne({
where: {
[Op.and]: [
{
warehouse_id: warehouseId,
platform_code: platformCode,
shop_name: shopName,
},
buildNotDeletedShopWhere(app),
],
},
attributes: [ 'id' ],
});
if (!existed) {
return shopName;
}
}
throw this.createError('系统生成占位名冲突,请重试', 409);
}
/**
* 创建业务错误。
*
* @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
*/
getCurrentWarehouseId() {
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
throw this.createError('未识别到当前仓库', 400);
}
return warehouseId;
}
/**
* 规范化字符串参数。
*
* @param {*} value 原始值
* @param {string} fieldName 字段名
* @param {Object} [options={}] 选项
* @param {boolean} [options.required=false] 是否必填
* @param {number} [options.maxLength=255] 最大长度
* @return {string|null} 规范化结果
*/
normalizeText(value, fieldName, options = {}) {
const { required = false, maxLength = 255 } = options;
if (value === undefined || value === null) {
if (required) {
throw this.createError(`${fieldName} 不能为空`, 400);
}
return null;
}
const normalized = String(value).trim();
if (!normalized) {
if (required) {
throw this.createError(`${fieldName} 不能为空`, 400);
}
return null;
}
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化整数参数。
*
* @param {*} value 原始值
* @param {string} fieldName 字段名
* @param {Object} [options={}] 选项
* @param {boolean} [options.required=false] 是否必填
* @param {number|null} [options.min=null] 最小值
* @return {number|null} 规范化结果
*/
normalizeInteger(value, fieldName, options = {}) {
const { required = false, min = null } = options;
if (value === undefined || value === null || value === '') {
if (required) {
throw this.createError(`${fieldName} 不能为空`, 400);
}
return null;
}
const normalized = Number(value);
if (!Number.isInteger(normalized)) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (min !== null && normalized < min) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return normalized;
}
/**
* 校验并标准化平台编码。
*
* @param {*} platformCode 原始平台编码
* @return {Promise<string>} 标准化平台编码
*/
async ensureShopPrintPlatformExists(platformCode) {
const normalizedPlatformCode = this.normalizeText(platformCode, 'platform_code', {
required: true,
maxLength: 50,
}).toUpperCase();
const printPlatform = await this.ctx.model.PrintPlatform.findOne({
where: {
platform_code: normalizedPlatformCode,
deleted: 0,
status: 'ACTIVE',
},
attributes: [ 'platform_code', 'platform_name', 'auth_base_url' ],
});
if (!printPlatform) {
throw this.createError('platform_code 未匹配到打印平台编码', 400);
}
return normalizedPlatformCode;
}
/**
* 获取店铺列表字段过滤映射。
*
* @return {Object} specialFieldMap 映射
*/
getListWhereSpecialFieldMap() {
return {
id: { field: 'id' },
platform_code: { field: 'platform_code' },
custom_name: { field: 'custom_name' },
shop_name: { field: 'shop_name' },
status: { field: 'status' },
quickWhere: { bucket: 'quick' },
};
}
/**
* 构建店铺列表查询条件。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 查询 where
*/
async buildListWhere(data = {}) {
const { app, ctx } = this;
const { Op } = app.Sequelize;
const parsedResult = ctx.whereParsed || {
dynamicConditions: [],
rawConditionsByField: {},
};
const whereAndConditions = [
{
warehouse_id: this.getCurrentWarehouseId(),
},
buildNotDeletedShopWhere(app),
];
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions)
? parsedResult.dynamicConditions
: [];
if (dynamicConditions.length > 0) {
whereAndConditions.push({ [Op.and]: dynamicConditions });
}
const quickWhereCondition = parsedResult.rawConditionsByField
? parsedResult.rawConditionsByField.quickWhere
: null;
const quickWhereValue = quickWhereCondition && typeof quickWhereCondition === 'object'
? quickWhereCondition.value
: null;
const keyword = String(quickWhereValue || '').trim();
if (keyword) {
whereAndConditions.push({
[Op.or]: [
{ shop_name: { [Op.like]: `%${keyword}%` } },
{ custom_name: { [Op.like]: `%${keyword}%` } },
{ platform_code: { [Op.like]: `%${keyword.toUpperCase()}%` } },
],
});
}
const normalizedPlatformCode = data.platform_code !== undefined
? String(data.platform_code || '').trim()
: String(data.platformCode || '').trim();
if (normalizedPlatformCode) {
whereAndConditions.push({
platform_code: await this.ensureShopPrintPlatformExists(normalizedPlatformCode),
});
}
return {
[Op.and]: whereAndConditions,
};
}
/**
* 规范化分页参数。
*
* @param {Object} [data={}] 请求参数
* @return {{page:number,pageSize:number,offset:number}} 分页信息
*/
normalizePagination(data = {}) {
const pagination = data && typeof data.pagination === 'object' ? data.pagination : {};
const pageSource = pagination.page !== undefined ? pagination.page : (data.page !== undefined ? data.page : data.currentPage);
const pageSizeSource = pagination.pageSize !== undefined
? pagination.pageSize
: (pagination.page_size !== undefined ? pagination.page_size : (data.pageSize !== undefined ? data.pageSize : data.page_size));
const page = Math.max(Number.parseInt(pageSource, 10) || 1, 1);
const pageSize = Math.min(Math.max(Number.parseInt(pageSizeSource, 10) || 20, 1), 200);
return {
page,
pageSize,
offset: (page - 1) * pageSize,
};
}
/**
* 构建店铺关联打印平台查询。
*
* @return {Array<Object>} include 查询配置
*/
buildShopPrintPlatformInclude() {
return [{
model: this.ctx.model.PrintPlatform,
as: 'printPlatform',
required: false,
attributes: [ 'platform_code', 'platform_name', 'status' ],
where: {
deleted: 0,
status: 'ACTIVE',
},
}];
}
/**
* 规范化店铺列表输出。
*
* @param {Object} shopRow 店铺记录
* @return {Object} 输出结构
*/
formatShopRow(shopRow) {
const printPlatform = shopRow && typeof shopRow.printPlatform === 'object'
? shopRow.printPlatform
: null;
return {
id: shopRow.id,
warehouse_id: shopRow.warehouse_id,
platform_code: shopRow.platform_code,
platform_name: printPlatform ? printPlatform.platform_name || '' : '',
shop_name: shopRow.shop_name,
custom_name: shopRow.custom_name,
status: shopRow.status,
auth_expire_at: shopRow.auth_expire_at,
access_token: shopRow.access_token,
created_at: shopRow.created_at,
updated_at: shopRow.updated_at,
};
}
/**
* 查询店铺分页列表。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 列表结果
*/
async list(data = {}) {
const { ctx } = this;
const { page, pageSize, offset } = this.normalizePagination(data);
const where = await this.buildListWhere(data);
const result = await ctx.model.Shop.findAndCountAll({
where,
include: this.buildShopPrintPlatformInclude(),
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
});
const rows = Array.isArray(result && result.rows) ? result.rows : [];
const list = rows.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row))
.map(row => this.formatShopRow(row));
const total = Number(result && result.count ? result.count : 0);
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: pageSize > 0 ? Math.ceil(total / pageSize) : 0,
hasNext: page * pageSize < total,
hasPrevious: page > 1,
},
};
}
/**
* 校验店铺名唯一性。
*
* @param {Object} payload 入参
* @param {number} payload.warehouseId 仓库 ID
* @param {string} payload.platformCode 平台编码
* @param {string} payload.shopName 店铺名
* @param {number|null} [payload.excludeId=null] 排除店铺 ID
* @return {Promise<void>} 无返回
*/
async ensureShopNameUnique(payload) {
const { app, ctx } = this;
const { Op } = app.Sequelize;
const { warehouseId, platformCode, shopName, excludeId = null } = payload;
const where = {
warehouse_id: warehouseId,
platform_code: platformCode,
shop_name: {
[Op.eq]: shopName,
[Op.notLike]: `${DELETED_SHOP_NAME_PREFIX}%`,
},
};
if (excludeId !== null) {
where.id = { [Op.ne]: excludeId };
}
const existed = await ctx.model.Shop.findOne({ where, attributes: [ 'id' ] });
if (existed) {
throw this.createError('同仓同平台下 shop_name 已存在', 409);
}
}
/**
* 新增店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 新增结果
*/
async add(data = {}) {
const { ctx } = this;
const warehouseId = this.getCurrentWarehouseId();
const platformCode = await this.ensureShopPrintPlatformExists(data.platform_code !== undefined ? data.platform_code : data.platformCode);
const customName = this.normalizeText(data.custom_name !== undefined ? data.custom_name : data.customName, 'custom_name', {
required: true,
maxLength: 100,
});
const shopName = await this.generatePendingShopName({
warehouseId,
platformCode,
});
const created = await ctx.model.Shop.create({
warehouse_id: warehouseId,
platform_code: platformCode,
shop_name: shopName,
custom_name: customName,
status: 0,
auth_expire_at: null,
auth_random_code: null,
owner_id: null,
access_token: null,
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
});
const plainRow = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
return {
id: plainRow.id,
};
}
/**
* 读取店铺并校验仓库归属。
*
* @param {*} shopId 店铺 ID
* @param {Object} [options={}] 选项
* @param {boolean} [options.allowDeleted=false] 是否允许读取已软删除店铺
* @return {Promise<Object>} 店铺模型实例
*/
async findShopById(shopId, options = {}) {
const { app, ctx } = this;
const { allowDeleted = false } = options;
const where = {
id: this.normalizeInteger(shopId, 'shop_id', { required: true, min: 1 }),
warehouse_id: this.getCurrentWarehouseId(),
};
if (!allowDeleted) {
Object.assign(where, buildNotDeletedShopWhere(app));
}
const shop = await ctx.model.Shop.findOne({ where });
if (!shop) {
throw this.createError('店铺不存在', 404);
}
return shop;
}
/**
* 软删除店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 删除结果
*/
async del(data = {}) {
const { ctx } = this;
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
const shop = await this.findShopById(shopId);
const normalizedShopId = Number(shop.id);
const expressInterfaceCount = await ctx.model.ExpressInterface.count({
where: {
warehouse_id: this.getCurrentWarehouseId(),
shop_id: normalizedShopId,
},
});
if (expressInterfaceCount > 0) {
throw this.createError(
`该店铺已被 ${expressInterfaceCount} 个快递接口引用,请先解除绑定后再删除`,
409
);
}
const deletedSuffix = `${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
await shop.update({
shop_name: `${DELETED_SHOP_NAME_PREFIX}${normalizedShopId}_${deletedSuffix}`,
custom_name: null,
status: 0,
auth_expire_at: null,
auth_random_code: null,
owner_id: null,
access_token: null,
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
}, {
fields: [
'shop_name',
'custom_name',
'status',
'auth_expire_at',
'auth_random_code',
'owner_id',
'access_token',
'refresh_token',
'token_expires_at',
'refresh_token_expires_at',
'scope',
],
});
return {
deleted: true,
id: normalizedShopId,
};
}
/**
* 编辑店铺。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 编辑结果
*/
async edit(data = {}) {
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
const shop = await this.findShopById(shopId);
const updates = {};
const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code')
|| Object.prototype.hasOwnProperty.call(data, 'platformCode');
const hasCustomName = Object.prototype.hasOwnProperty.call(data, 'custom_name')
|| Object.prototype.hasOwnProperty.call(data, 'customName');
const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name')
|| Object.prototype.hasOwnProperty.call(data, 'shopName');
if (!hasPlatformCode && !hasCustomName && !hasShopName) {
throw this.createError('仅允许修改 platform_code、custom_name 或 shop_name', 400);
}
if (hasPlatformCode) {
updates.platform_code = await this.ensureShopPrintPlatformExists(
data.platform_code !== undefined ? data.platform_code : data.platformCode
);
}
if (hasCustomName) {
updates.custom_name = this.normalizeText(
data.custom_name !== undefined ? data.custom_name : data.customName,
'custom_name',
{ required: true, maxLength: 100 }
);
}
if (hasShopName) {
updates.shop_name = this.normalizeText(
data.shop_name !== undefined ? data.shop_name : data.shopName,
'shop_name',
{ required: true, maxLength: 100 }
);
}
const nextPlatformCode = updates.platform_code || shop.platform_code;
const nextShopName = updates.shop_name || shop.shop_name;
await this.ensureShopNameUnique({
warehouseId: this.getCurrentWarehouseId(),
platformCode: nextPlatformCode,
shopName: nextShopName,
excludeId: Number(shop.id),
});
await shop.update(updates, {
fields: Object.keys(updates),
});
return {
updated: true,
id: Number(shop.id),
};
}
/**
* 生成平台授权预占码。
*
* @return {string} 预占码
*/
generateAuthorizeRandomCode() {
return crypto.randomBytes(24).toString('hex');
}
/**
* 创建或复用授权预占店铺。
*
* @param {Object} payload 参数
* @param {number} payload.warehouseId 仓库 ID
* @param {string} payload.platformCode 平台编码
* @return {Promise<{shop:Object,authRandomCode:string}>} 预占结果
*/
async createOrReuseAuthorizeReservation(payload) {
const { ctx, app } = this;
const { warehouseId, platformCode } = payload;
const pendingShop = await ctx.model.Shop.findOne({
where: {
warehouse_id: warehouseId,
platform_code: platformCode,
status: 0,
...buildNotDeletedShopWhere(app),
},
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
});
if (pendingShop && String(pendingShop.auth_random_code || '').trim()) {
return {
shop: pendingShop,
authRandomCode: String(pendingShop.auth_random_code).trim(),
};
}
const maxRetryCount = 5;
for (let retryIndex = 0; retryIndex < maxRetryCount; retryIndex++) {
const authRandomCode = this.generateAuthorizeRandomCode();
try {
if (pendingShop) {
pendingShop.auth_random_code = authRandomCode;
await pendingShop.save({ fields: [ 'auth_random_code' ] });
return {
shop: pendingShop,
authRandomCode,
};
}
const createdShop = await ctx.model.Shop.create({
warehouse_id: warehouseId,
platform_code: platformCode,
shop_name: `PENDING_${authRandomCode}`,
custom_name: null,
status: 0,
auth_expire_at: null,
auth_random_code: authRandomCode,
owner_id: null,
access_token: null,
refresh_token: null,
token_expires_at: null,
refresh_token_expires_at: null,
scope: null,
});
return {
shop: createdShop,
authRandomCode,
};
} catch (error) {
const isUniqueConflict = error && error.name === 'SequelizeUniqueConstraintError';
if (isUniqueConflict && retryIndex < maxRetryCount - 1) {
continue;
}
if (isUniqueConflict) {
throw this.createError('生成唯一授权码失败,请稍后重试', 500);
}
throw error;
}
}
throw this.createError('生成唯一授权码失败,请稍后重试', 500);
}
/**
* 获取店铺授权会话。
*
* @param {Object} [data={}] 请求参数
* @return {Promise<Object>} 会话信息
*/
async getAuthorizeSessionKey(data = {}) {
const { ctx } = this;
const authUrl = 'http://61.160.223.183:3012/api';
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
const appId = data.appId || '';
const toUserName = data.toUserName || '';
const shop = await this.findShopById(shopId, { allowDeleted: false });
const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop;
const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code);
// 获取wms_print_platform.platid和request_platform_code
const printPlatform = await ctx.model.PrintPlatform.findOne({
where: {
platform_code: platformCode,
deleted: 0,
status: 'ACTIVE',
},
attributes: [ 'get_auth_platform_name' ],
});
const platName = printPlatform ? printPlatform.get_auth_platform_name : platformCode;
// 视频号授权不依赖回调地址,允许 callbackurl 为空;其他平台仍必填
const callbackUrl = this.normalizeText(
data.callbackurl !== undefined ? data.callbackurl : data.callback_url,
'callbackurl',
{ required: platName !== '视频号', maxLength: 500 }
);
const requestData = {
RedirectCodeUrl: callbackUrl,
command: 'saveShop',
platName,
shopName: shopPlain.shop_name,
};
if (platName === '电商京东') {
requestData.VenderID = shopPlain.id;
}
if (platName === '视频号') {
if (!appId || !toUserName) {
throw this.createError('视频号授权需要提供 appId 和 toUserName', 400);
}
requestData.appId = appId;
requestData.toUserName = toUserName;
delete requestData.RedirectCodeUrl;
}
// 缓存最后一次授权查询请求数据,便于排查问题
await this.app.setCacheAsync('last_query_auth_polo', JSON.stringify(requestData), 3600);
const respone = await ctx.curl(authUrl, {
method: 'POST',
dataType: 'json',
timeout: 15000,
data: requestData,
});
await this.app.setCacheAsync('last_respone_auth_polo', JSON.stringify(respone), 3600);
if (respone.data && respone.data.code === 0) {
const sessionKey = respone.data.data || null;
if (sessionKey) {
await shop.update({
access_token: sessionKey,
status: 1,
}, {
fields: [ 'access_token', 'status' ],
});
return { message: '获取授权成功' };
}
throw this.createError('获取授权失败,未返回 sessionKey', 500);
}
throw this.createError(`获取授权失败:${respone.data ? respone.data.msg : '接口请求异常'}`, 500);
}
}
module.exports = ShopsService;