1267 lines
38 KiB
JavaScript
1267 lines
38 KiB
JavaScript
// app/service/system/platform.js
|
||
const Service = require('egg').Service;
|
||
|
||
const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600;
|
||
const PLATFORM_OAUTH_BIND_SUCCESS_CACHE_PREFIX = 'bind_pdd_code:';
|
||
const PLATFORM_OAUTH_BIND_FAIL_CACHE_PREFIX = 'bind_pdd_code_fail:';
|
||
const PLATFORM_OAUTH_BIND_EVENT_CHANNEL_PREFIX = 'bind_pdd_code_event:';
|
||
const PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS = 60000;
|
||
|
||
class PlatformService extends Service {
|
||
/**
|
||
* 获取当前上下文中的仓库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 {*} code 原始业务编码
|
||
* @return {string} 规范化后的业务编码
|
||
*/
|
||
normalizePlatformOauthBindCode(code) {
|
||
return String(code || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 获取平台授权绑定成功缓存键。
|
||
*
|
||
* @param {string} code 业务编码
|
||
* @return {string} 成功缓存键
|
||
*/
|
||
getPlatformOauthBindSuccessCacheKey(code) {
|
||
const normalizedCode = this.normalizePlatformOauthBindCode(code);
|
||
return `${PLATFORM_OAUTH_BIND_SUCCESS_CACHE_PREFIX}${normalizedCode}`;
|
||
}
|
||
|
||
/**
|
||
* 获取平台授权绑定失败缓存键。
|
||
*
|
||
* @param {string} code 业务编码
|
||
* @return {string} 失败缓存键
|
||
*/
|
||
getPlatformOauthBindFailCacheKey(code) {
|
||
const normalizedCode = this.normalizePlatformOauthBindCode(code);
|
||
return `${PLATFORM_OAUTH_BIND_FAIL_CACHE_PREFIX}${normalizedCode}`;
|
||
}
|
||
|
||
/**
|
||
* 获取平台授权绑定事件频道。
|
||
*
|
||
* @param {string} code 业务编码
|
||
* @return {string} 事件频道名称
|
||
*/
|
||
getPlatformOauthBindEventChannel(code) {
|
||
const normalizedCode = this.normalizePlatformOauthBindCode(code);
|
||
return `${PLATFORM_OAUTH_BIND_EVENT_CHANNEL_PREFIX}${normalizedCode}`;
|
||
}
|
||
|
||
/**
|
||
* 获取平台授权长轮询超时时间。
|
||
*
|
||
* @param {*} timeoutMs 原始超时配置
|
||
* @return {number} 毫秒级超时时间
|
||
*/
|
||
getPlatformOauthLongPollTimeoutMs(timeoutMs = PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS) {
|
||
const waitMs = Number(timeoutMs);
|
||
if (Number.isFinite(waitMs) && waitMs > 0) {
|
||
return Math.floor(waitMs);
|
||
}
|
||
|
||
return PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS;
|
||
}
|
||
|
||
/**
|
||
* 判断是否启用平台授权长轮询。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @return {boolean} 是否启用长轮询
|
||
*/
|
||
shouldUsePlatformOauthLongPoll(data = {}) {
|
||
return [ true, 1, '1', 'true' ].includes(data.longPoll)
|
||
|| [ true, 1, '1', 'true' ].includes(data.long_poll)
|
||
|| [ true, 1, '1', 'true' ].includes(data.wait);
|
||
}
|
||
|
||
/**
|
||
* 查询平台授权绑定状态。
|
||
*
|
||
* @param {string} code 业务编码
|
||
* @return {Promise<Object>} 当前绑定状态
|
||
*/
|
||
async getPlatformOauthBindState(code) {
|
||
const normalizedCode = this.normalizePlatformOauthBindCode(code);
|
||
if (!normalizedCode) {
|
||
return {
|
||
status: 'failed',
|
||
message: 'code不能为空',
|
||
access_token: '',
|
||
};
|
||
}
|
||
|
||
const successCacheKey = this.getPlatformOauthBindSuccessCacheKey(normalizedCode);
|
||
const failCacheKey = this.getPlatformOauthBindFailCacheKey(normalizedCode);
|
||
|
||
let cachedToken = null;
|
||
try {
|
||
cachedToken = await this.app.getCacheAsync(successCacheKey);
|
||
} catch (error) {
|
||
this.ctx.logger.error(`[PlatformService.getPlatformOauthBindState] 查询成功缓存异常: ${error.message}`);
|
||
}
|
||
|
||
const accessToken = typeof cachedToken === 'string' ? cachedToken.trim() : '';
|
||
if (accessToken) {
|
||
return {
|
||
status: 'success',
|
||
message: '授权完成',
|
||
access_token: accessToken,
|
||
};
|
||
}
|
||
|
||
let failedCacheValue = null;
|
||
try {
|
||
failedCacheValue = await this.app.getCacheAsync(failCacheKey);
|
||
} catch (error) {
|
||
this.ctx.logger.error(`[PlatformService.getPlatformOauthBindState] 查询失败缓存异常: ${error.message}`);
|
||
}
|
||
|
||
if (failedCacheValue !== null && failedCacheValue !== undefined && failedCacheValue !== '') {
|
||
const failedMessage = failedCacheValue && typeof failedCacheValue === 'object' && failedCacheValue.message
|
||
? String(failedCacheValue.message).trim()
|
||
: '绑定失败,请重新授权';
|
||
return {
|
||
status: 'failed',
|
||
message: failedMessage || '绑定失败,请重新授权',
|
||
access_token: '',
|
||
};
|
||
}
|
||
|
||
return {
|
||
status: 'pending',
|
||
message: '等待授权完成',
|
||
access_token: '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 发布平台授权绑定结果事件。
|
||
*
|
||
* @param {string} code 业务编码
|
||
* @param {Object} payload 事件负载
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async publishPlatformOauthBindEvent(code, payload = {}) {
|
||
const normalizedCode = this.normalizePlatformOauthBindCode(code);
|
||
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
|
||
|
||
if (!cacheRedis || !normalizedCode) {
|
||
return;
|
||
}
|
||
|
||
const channel = this.getPlatformOauthBindEventChannel(normalizedCode);
|
||
const eventData = {
|
||
code: normalizedCode,
|
||
event_at: new Date().toISOString(),
|
||
...payload,
|
||
};
|
||
|
||
try {
|
||
await cacheRedis.publish(channel, JSON.stringify(eventData));
|
||
} catch (error) {
|
||
this.app.coreLogger.warn(`发布平台授权绑定事件失败: ${error.message}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 等待平台授权绑定事件。
|
||
*
|
||
* @param {string} code 业务编码
|
||
* @param {number} timeoutMs 超时时间,单位毫秒
|
||
* @return {Promise<Object>} 等待结果
|
||
*/
|
||
async waitForPlatformOauthBindEvent(code, timeoutMs = PLATFORM_OAUTH_BIND_LONG_POLL_TIMEOUT_MS) {
|
||
const normalizedCode = this.normalizePlatformOauthBindCode(code);
|
||
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
|
||
if (!cacheRedis || !normalizedCode || typeof cacheRedis.duplicate !== 'function') {
|
||
return {
|
||
timed_out: true,
|
||
reason: 'redis_not_available',
|
||
event: null,
|
||
};
|
||
}
|
||
|
||
const channel = this.getPlatformOauthBindEventChannel(normalizedCode);
|
||
const waitMs = this.getPlatformOauthLongPollTimeoutMs(timeoutMs);
|
||
const subscriber = cacheRedis.duplicate();
|
||
|
||
return await new Promise(resolve => {
|
||
let settled = false;
|
||
let timer = null;
|
||
|
||
function cleanup() {
|
||
subscriber.removeListener('message', onMessage);
|
||
subscriber.removeListener('error', onError);
|
||
Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => {
|
||
if (typeof subscriber.quit === 'function') {
|
||
Promise.resolve(subscriber.quit()).catch(() => {
|
||
if (typeof subscriber.disconnect === 'function') {
|
||
subscriber.disconnect();
|
||
}
|
||
});
|
||
return;
|
||
}
|
||
|
||
if (typeof subscriber.disconnect === 'function') {
|
||
subscriber.disconnect();
|
||
}
|
||
});
|
||
}
|
||
|
||
const finalize = result => {
|
||
if (settled) {
|
||
return;
|
||
}
|
||
|
||
settled = true;
|
||
if (timer) {
|
||
clearTimeout(timer);
|
||
}
|
||
cleanup();
|
||
resolve(result);
|
||
};
|
||
|
||
function onMessage(messageChannel, message) {
|
||
if (messageChannel !== channel) {
|
||
return;
|
||
}
|
||
|
||
let eventData = null;
|
||
try {
|
||
eventData = message ? JSON.parse(message) : null;
|
||
} catch (error) {
|
||
eventData = message;
|
||
}
|
||
|
||
finalize({
|
||
timed_out: false,
|
||
reason: 'event',
|
||
event: eventData,
|
||
});
|
||
}
|
||
|
||
function onError(error) {
|
||
this.app.coreLogger.warn(`订阅平台授权绑定事件失败: ${error.message}`);
|
||
finalize({
|
||
timed_out: true,
|
||
reason: 'subscribe_error',
|
||
event: null,
|
||
});
|
||
}
|
||
|
||
timer = setTimeout(() => {
|
||
finalize({
|
||
timed_out: true,
|
||
reason: 'timeout',
|
||
event: null,
|
||
});
|
||
}, waitMs);
|
||
|
||
subscriber.on('message', onMessage);
|
||
subscriber.on('error', onError);
|
||
|
||
Promise.resolve(subscriber.subscribe(channel)).catch(error => {
|
||
this.app.coreLogger.warn(`订阅平台授权绑定频道失败: ${error.message}`);
|
||
finalize({
|
||
timed_out: true,
|
||
reason: 'subscribe_failed',
|
||
event: null,
|
||
});
|
||
});
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 监听平台授权绑定结果。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {string} [data.code] 业务编码
|
||
* @param {string} [data.businessCode] 业务编码
|
||
* @param {boolean} [data.longPoll] 是否启用长轮询
|
||
* @param {number} [data.timeoutMs] 超时时间,单位毫秒
|
||
* @return {Promise<Object>} 监听结果
|
||
*/
|
||
async listenPlatformOauthBind(data = {}) {
|
||
const normalizedCode = this.normalizePlatformOauthBindCode(data.code || data.businessCode || data.business_code);
|
||
if (!normalizedCode) {
|
||
return {
|
||
success: false,
|
||
code: 0,
|
||
data: null,
|
||
message: 'code不能为空',
|
||
};
|
||
}
|
||
|
||
const useLongPoll = this.shouldUsePlatformOauthLongPoll(data);
|
||
let bindState = await this.getPlatformOauthBindState(normalizedCode);
|
||
|
||
if (bindState.status !== 'pending' || !useLongPoll) {
|
||
return {
|
||
success: true,
|
||
code: 200,
|
||
data: {
|
||
code: normalizedCode,
|
||
status: bindState.status,
|
||
access_token: bindState.access_token,
|
||
source: 'cache',
|
||
},
|
||
message: bindState.message,
|
||
};
|
||
}
|
||
|
||
const waitResult = await this.waitForPlatformOauthBindEvent(normalizedCode, data.timeoutMs || data.timeout_ms);
|
||
bindState = await this.getPlatformOauthBindState(normalizedCode);
|
||
|
||
if (bindState.status === 'pending') {
|
||
return {
|
||
success: true,
|
||
code: 200,
|
||
data: {
|
||
code: normalizedCode,
|
||
status: 'pending',
|
||
access_token: '',
|
||
source: waitResult.timed_out ? 'timeout' : 'event',
|
||
},
|
||
message: waitResult.timed_out ? '长轮询结束未检测到授权结果,请继续等待' : '授权状态暂未更新,请继续等待',
|
||
};
|
||
}
|
||
|
||
return {
|
||
success: true,
|
||
code: 200,
|
||
data: {
|
||
code: normalizedCode,
|
||
status: bindState.status,
|
||
access_token: bindState.access_token,
|
||
source: waitResult.timed_out ? 'cache' : 'event',
|
||
},
|
||
message: bindState.message,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取平台表的全量字段列表。
|
||
*
|
||
* @return {Array<string>} 平台表字段列表。
|
||
*/
|
||
getPlatformFullAttributes() {
|
||
const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.Platform && this.ctx.model.Platform.rawAttributes;
|
||
|
||
if (!rawAttributes || typeof rawAttributes !== 'object') {
|
||
return [];
|
||
}
|
||
|
||
return Object.keys(rawAttributes);
|
||
}
|
||
|
||
/**
|
||
* 获取平台设置表的全量字段列表。
|
||
*
|
||
* @return {Array<string>} 平台设置表字段列表。
|
||
*/
|
||
getPlatformSettingFullAttributes() {
|
||
const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.PlatformSetting && this.ctx.model.PlatformSetting.rawAttributes;
|
||
|
||
if (!rawAttributes || typeof rawAttributes !== 'object') {
|
||
return [];
|
||
}
|
||
|
||
return Object.keys(rawAttributes);
|
||
}
|
||
|
||
/**
|
||
* 获取打印平台模型。
|
||
*
|
||
* @return {Object|null} 打印平台模型,未注册时返回 null。
|
||
*/
|
||
getPrintPlatformModel() {
|
||
const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform;
|
||
|
||
if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function') {
|
||
return null;
|
||
}
|
||
|
||
return printPlatformModel;
|
||
}
|
||
|
||
/**
|
||
* 将 Sequelize 记录转换为普通对象。
|
||
*
|
||
* @param {Object} row 原始记录。
|
||
* @return {Object|null} 普通对象。
|
||
*/
|
||
toPlainRow(row) {
|
||
if (!row || typeof row !== 'object') {
|
||
return null;
|
||
}
|
||
|
||
if (typeof row.get === 'function') {
|
||
return row.get({ plain: true });
|
||
}
|
||
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* 规范化打印平台主键。
|
||
*
|
||
* @param {*} printPlatformId 打印平台主键。
|
||
* @return {number|null} 规范化后的主键。
|
||
*/
|
||
normalizePrintPlatformId(printPlatformId) {
|
||
const normalizedId = Number(printPlatformId || 0);
|
||
|
||
if (!Number.isFinite(normalizedId) || normalizedId <= 0) {
|
||
return null;
|
||
}
|
||
|
||
return normalizedId;
|
||
}
|
||
|
||
/**
|
||
* 批量加载打印平台编码映射。
|
||
*
|
||
* 仅以 `wms_platform.print_platform_id -> wms_print_platform.platform_code`
|
||
* 为准;缺少模型、主键或关联记录时返回空映射,避免继续误用 sys_platform_code 直连语义。
|
||
*
|
||
* @param {Array<Object>} platformRows 平台记录列表。
|
||
* @return {Promise<Map<number, string>>} 打印平台ID到打印平台编码的映射。
|
||
*/
|
||
async loadPrintPlatformCodeMap(platformRows = []) {
|
||
const printPlatformModel = this.getPrintPlatformModel();
|
||
if (!printPlatformModel) {
|
||
return new Map();
|
||
}
|
||
|
||
const idSet = new Set();
|
||
for (const platformRow of Array.isArray(platformRows) ? platformRows : []) {
|
||
const plainRow = this.toPlainRow(platformRow);
|
||
const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id);
|
||
if (printPlatformId) {
|
||
idSet.add(printPlatformId);
|
||
}
|
||
}
|
||
|
||
if (idSet.size <= 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const rows = await printPlatformModel.findAll({
|
||
attributes: [ 'id', 'platform_code' ],
|
||
where: {
|
||
id: Array.from(idSet),
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
const printPlatformCodeMap = new Map();
|
||
for (const row of Array.isArray(rows) ? rows : []) {
|
||
const printPlatformId = this.normalizePrintPlatformId(row && row.id);
|
||
const printPlatformCode = String(row && row.platform_code || '').trim();
|
||
if (!printPlatformId || !printPlatformCode) {
|
||
continue;
|
||
}
|
||
|
||
printPlatformCodeMap.set(printPlatformId, printPlatformCode);
|
||
}
|
||
|
||
return printPlatformCodeMap;
|
||
}
|
||
|
||
/**
|
||
* 批量加载打印平台 platid 映射。
|
||
*
|
||
* 仅以 `wms_platform.print_platform_id -> wms_print_platform.platid`
|
||
* 为准;缺少模型、主键或关联记录时返回空映射。
|
||
*
|
||
* @param {Array<Object>} platformRows 平台记录列表。
|
||
* @return {Promise<Map<number, number>>} 打印平台ID到 platid 的映射。
|
||
*/
|
||
async loadPrintPlatformPlatidMap(platformRows = []) {
|
||
const printPlatformModel = this.getPrintPlatformModel();
|
||
if (!printPlatformModel) {
|
||
return new Map();
|
||
}
|
||
|
||
const idSet = new Set();
|
||
for (const platformRow of Array.isArray(platformRows) ? platformRows : []) {
|
||
const plainRow = this.toPlainRow(platformRow);
|
||
const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id);
|
||
if (printPlatformId) {
|
||
idSet.add(printPlatformId);
|
||
}
|
||
}
|
||
|
||
if (idSet.size <= 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const rows = await printPlatformModel.findAll({
|
||
attributes: [ 'id', 'platid' ],
|
||
where: {
|
||
id: Array.from(idSet),
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
const printPlatformPlatidMap = new Map();
|
||
for (const row of Array.isArray(rows) ? rows : []) {
|
||
const printPlatformId = this.normalizePrintPlatformId(row && row.id);
|
||
const platid = Number(row && row.platid);
|
||
if (!printPlatformId || !Number.isFinite(platid)) {
|
||
continue;
|
||
}
|
||
|
||
printPlatformPlatidMap.set(printPlatformId, platid);
|
||
}
|
||
|
||
return printPlatformPlatidMap;
|
||
}
|
||
|
||
/**
|
||
* 解析平台对应的默认快递接口平台编码。
|
||
*
|
||
* 仅信任 `PrintPlatform.platform_code`;若模型未注册、主键缺失、
|
||
* 未匹配到记录或目标字段为空,返回空字符串作为清晰兜底,不再退回旧语义。
|
||
*
|
||
* @param {Object} row 平台记录。
|
||
* @param {Map<number, string>} [printPlatformCodeMap] 打印平台编码映射。
|
||
* @return {string} 默认快递接口平台编码。
|
||
*/
|
||
resolveDefaultExpressInterface(row, printPlatformCodeMap = new Map()) {
|
||
const plainRow = this.toPlainRow(row);
|
||
if (!plainRow) {
|
||
return '';
|
||
}
|
||
|
||
const nestedPrintPlatform = this.toPlainRow(plainRow.printPlatform);
|
||
const nestedPrintPlatformCode = String(nestedPrintPlatform && nestedPrintPlatform.platform_code || '').trim();
|
||
if (nestedPrintPlatformCode) {
|
||
return nestedPrintPlatformCode;
|
||
}
|
||
|
||
const printPlatformId = this.normalizePrintPlatformId(plainRow.print_platform_id);
|
||
if (!printPlatformId || !(printPlatformCodeMap instanceof Map)) {
|
||
return '';
|
||
}
|
||
|
||
const mappedPrintPlatformCode = String(printPlatformCodeMap.get(printPlatformId) || '').trim();
|
||
if (!mappedPrintPlatformCode) {
|
||
this.ctx.logger.warn(`[PlatformService.resolveDefaultExpressInterface] print_platform_id=${printPlatformId} 缺少 platform_code,默认快递接口返回空值`);
|
||
return '';
|
||
}
|
||
|
||
return mappedPrintPlatformCode;
|
||
}
|
||
|
||
/**
|
||
* 解析平台后处理路由编码。
|
||
*
|
||
* 路由语义统一使用 `wms_platform.print_platform_id -> wms_print_platform.platform_code`。
|
||
* 若未配置请求平台编码,则回退平台主编码,避免中断历史链路。
|
||
*
|
||
* @param {Object} row 平台记录。
|
||
* @param {Map<number, string>} [printPlatformCodeMap] 打印平台编码映射。
|
||
* @return {string} 平台后处理路由编码。
|
||
*/
|
||
resolveRoutePlatformCode(row, printPlatformCodeMap = new Map()) {
|
||
const plainRow = this.toPlainRow(row);
|
||
if (!plainRow) {
|
||
return '';
|
||
}
|
||
|
||
const routePlatformCode = this.resolveDefaultExpressInterface(plainRow, printPlatformCodeMap);
|
||
if (routePlatformCode) {
|
||
return routePlatformCode;
|
||
}
|
||
|
||
return String(plainRow.code || plainRow.value || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 生成平台列表缓存键。
|
||
*
|
||
* @param {number|string} warehouseId 仓库ID。
|
||
* @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。
|
||
* @param {boolean} [full=false] 是否返回全量字段。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getPlatformListCacheKey(warehouseId = 0, systemOnly = false, full = false) {
|
||
const isFull = [ true, 1, '1', 'true' ].includes(full);
|
||
|
||
if (systemOnly) {
|
||
return isFull ? 'platform:list:system:full' : 'platform:list:system';
|
||
}
|
||
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
|
||
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
||
return isFull ? `platform:list:${normalizedWarehouseId}:full` : `platform:list:${normalizedWarehouseId}`;
|
||
}
|
||
|
||
return isFull ? 'platform:list:full' : 'platform:list';
|
||
}
|
||
|
||
/**
|
||
* 判断全量平台缓存是否存在字段结构过期。
|
||
*
|
||
* 当缓存项中存在有效 print_platform_id,但缺少有效 platid 时,
|
||
* 认为缓存结构已过期,需要触发重建。
|
||
*
|
||
* @param {*} cachedList 缓存中的平台列表。
|
||
* @return {boolean} 是否结构过期。
|
||
*/
|
||
isFullPlatformCacheSchemaStale(cachedList) {
|
||
if (!Array.isArray(cachedList) || cachedList.length <= 0) {
|
||
return false;
|
||
}
|
||
|
||
return cachedList.some(item => {
|
||
if (!item || typeof item !== 'object') {
|
||
return false;
|
||
}
|
||
|
||
const printPlatformId = Number(item.print_platform_id);
|
||
if (!Number.isFinite(printPlatformId) || printPlatformId <= 0) {
|
||
return false;
|
||
}
|
||
|
||
return !Number.isFinite(Number(item.platid));
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 生成平台设置项展示名称。
|
||
*
|
||
* @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 数据库记录。
|
||
* @param {Map<number, string>} [printPlatformCodeMap] 打印平台编码映射。
|
||
* @return {Object|null} 规范化后的记录。
|
||
*/
|
||
normalizePlatformRow(row, printPlatformCodeMap = new Map()) {
|
||
if (!row || typeof row !== 'object') {
|
||
return null;
|
||
}
|
||
|
||
const code = String(row.code || '').trim();
|
||
if (!code) {
|
||
return null;
|
||
}
|
||
|
||
const name = String(row.name || '').trim();
|
||
const defaultExpressInterface = this.resolveDefaultExpressInterface(row, printPlatformCodeMap);
|
||
|
||
return {
|
||
code,
|
||
name,
|
||
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 {Object} row 数据库记录。
|
||
* @param {Map<number, string>} [printPlatformCodeMap] 打印平台编码映射。
|
||
* @param {Map<number, number>} [printPlatformPlatidMap] 打印平台 platid 映射。
|
||
* @return {Object|null} 规范化后的全量记录。
|
||
*/
|
||
normalizeFullPlatformRow(row, printPlatformCodeMap = new Map(), printPlatformPlatidMap = new Map()) {
|
||
const normalizedRow = this.normalizePlatformRow(row, printPlatformCodeMap);
|
||
|
||
if (!normalizedRow) {
|
||
return null;
|
||
}
|
||
|
||
const normalizedResult = {
|
||
...row,
|
||
...normalizedRow,
|
||
route_platform_code: this.resolveRoutePlatformCode(row, printPlatformCodeMap),
|
||
};
|
||
|
||
const plainRow = this.toPlainRow(row);
|
||
const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id);
|
||
if (printPlatformId && printPlatformPlatidMap instanceof Map) {
|
||
const platid = printPlatformPlatidMap.get(printPlatformId);
|
||
if (Number.isFinite(platid)) {
|
||
normalizedResult.platid = platid;
|
||
}
|
||
}
|
||
|
||
return normalizedResult;
|
||
}
|
||
|
||
/**
|
||
* 规范化平台设置全量记录。
|
||
*
|
||
* @param {Object} row 数据库记录。
|
||
* @param {Map<string, Object>} platformMap 系统平台映射。
|
||
* @return {Object|null} 规范化后的全量记录。
|
||
*/
|
||
normalizeFullPlatformSettingRow(row, platformMap) {
|
||
const normalizedRow = this.normalizePlatformSettingRow(row, platformMap);
|
||
|
||
if (!normalizedRow) {
|
||
return null;
|
||
}
|
||
|
||
const platformCode = String(row && row.platform_code || '').trim();
|
||
const platformItem = platformMap instanceof Map ? platformMap.get(platformCode) : null;
|
||
|
||
return {
|
||
...row,
|
||
...normalizedRow,
|
||
route_platform_code: String((platformItem && platformItem.route_platform_code) || '').trim(),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 合并基础平台列表和平台设置列表。
|
||
*
|
||
* @param {Array<Object>} platformList 系统平台列表。
|
||
* @param {Array<Object>} platformSettingList 平台设置列表。
|
||
* @param {boolean} [full=false] 是否合并全量字段。
|
||
* @return {Array<Object>} 合并后的平台列表。
|
||
*/
|
||
buildMergedPlatformList(platformList, platformSettingList, full = false) {
|
||
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 = full
|
||
? this.normalizeFullPlatformSettingRow(row, platformMap)
|
||
: this.normalizePlatformSettingRow(row, platformMap);
|
||
if (!mergedItem || seenCodeMap.has(mergedItem.code)) {
|
||
continue;
|
||
}
|
||
|
||
mergedList.push(mergedItem);
|
||
seenCodeMap.add(mergedItem.code);
|
||
}
|
||
|
||
return mergedList;
|
||
}
|
||
|
||
/**
|
||
* 从数据库加载系统平台列表。
|
||
*
|
||
* @param {boolean} [full=false] 是否返回全量字段。
|
||
* @return {Promise<Array<Object>>} 平台列表。
|
||
*/
|
||
async loadPlatformListFromDatabase(full = false) {
|
||
const query = {
|
||
order: [[ 'code', 'ASC' ]],
|
||
raw: true,
|
||
};
|
||
|
||
if (full) {
|
||
const attributes = this.getPlatformFullAttributes();
|
||
if (attributes.length > 0) {
|
||
query.attributes = attributes;
|
||
}
|
||
} else {
|
||
query.attributes = [ 'code', 'name', 'print_platform_id' ];
|
||
}
|
||
|
||
const rows = await this.ctx.model.Platform.findAll(query);
|
||
|
||
if (!Array.isArray(rows)) {
|
||
return [];
|
||
}
|
||
|
||
const printPlatformCodeMap = await this.loadPrintPlatformCodeMap(rows);
|
||
const printPlatformPlatidMap = full ? await this.loadPrintPlatformPlatidMap(rows) : new Map();
|
||
|
||
return rows
|
||
.map(row => (full
|
||
? this.normalizeFullPlatformRow(row, printPlatformCodeMap, printPlatformPlatidMap)
|
||
: this.normalizePlatformRow(row, printPlatformCodeMap)))
|
||
.filter(Boolean);
|
||
}
|
||
|
||
/**
|
||
* 获取系统平台列表。
|
||
*
|
||
* 该接口只返回系统基础平台数据,不合并仓库自定义映射。
|
||
*
|
||
* @return {Promise<Array>} 系统平台列表。
|
||
*/
|
||
async getSystemPlatformList() {
|
||
return await this.loadPlatformListFromDatabase();
|
||
}
|
||
|
||
/**
|
||
* 获取平台列表。
|
||
*
|
||
* 默认先读取系统平台,再按当前仓库合并平台设置;同一编码只保留一条记录。
|
||
* systemOnly 为 true 时仅返回系统平台列表。
|
||
*
|
||
* @param {boolean} [systemOnly=false] 是否仅返回系统基础平台列表。
|
||
* @param {boolean} [full=false] 是否返回全量字段。
|
||
* @return {Promise<Array>} 平台列表。
|
||
*/
|
||
async getPlatformList(systemOnly = false, full = false) {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly);
|
||
const isFull = [ true, 1, '1', 'true' ].includes(full);
|
||
const cacheKey = this.getPlatformListCacheKey(warehouseId, isSystemOnly, isFull);
|
||
|
||
try {
|
||
const cachedList = await this.app.getCacheAsync(cacheKey);
|
||
if (cachedList !== null && cachedList !== undefined) {
|
||
if (isFull && this.isFullPlatformCacheSchemaStale(cachedList)) {
|
||
this.ctx.logger.warn(`[PlatformService.getPlatformList] full缓存缺少有效platid,触发重建: ${cacheKey}`);
|
||
|
||
try {
|
||
await this.app.delCacheAsync(cacheKey);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(`[PlatformService.getPlatformList] 删除过期缓存失败,降级为setCacheAsync置空: ${cacheKey}, error: ${error.message}`);
|
||
await this.app.setCacheAsync(cacheKey, null, 0);
|
||
}
|
||
} else {
|
||
return Array.isArray(cachedList) ? cachedList : [];
|
||
}
|
||
}
|
||
|
||
if (isSystemOnly) {
|
||
const platformList = await this.loadPlatformListFromDatabase(isFull);
|
||
await this.app.setCacheAsync(cacheKey, platformList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS);
|
||
return platformList;
|
||
}
|
||
|
||
const [ platformList, platformSettingList ] = await Promise.all([
|
||
this.loadPlatformListFromDatabase(isFull),
|
||
this.loadPlatformSettingListFromDatabase(warehouseId, isFull),
|
||
]);
|
||
|
||
const mergedList = this.buildMergedPlatformList(platformList, platformSettingList, isFull);
|
||
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,
|
||
stack: error.stack,
|
||
});
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 检查平台是否存在
|
||
* 逻辑:
|
||
* 1. 先查询设置表,有对应的平台代码+仓库ID组合,返回关联的基础表的代码和名称
|
||
* 2. 如果没有,尝试基础表中的code是否匹配,存在匹配则直接返回基础表的代码和名称
|
||
* 3. 使用缓存优化性能
|
||
* @param {string} platformCode 平台代码
|
||
* @param {number} warehouseId 仓库ID
|
||
* @return {Promise<Object|null>} 平台信息或null
|
||
*/
|
||
async checkPlatformExists(platformCode, warehouseId) {
|
||
const { ctx, app } = this;
|
||
|
||
// 生成缓存key
|
||
const cacheKey = `platform:${platformCode}:${warehouseId}`;
|
||
|
||
try {
|
||
// 1. 先从缓存获取
|
||
const cachedData = await app.getCacheAsync(cacheKey);
|
||
if (cachedData) {
|
||
ctx.logger.info(`从缓存获取平台信息: ${cacheKey}`);
|
||
// 如果缓存中存的是"不存在"的特殊标记,返回null
|
||
if (cachedData === '__NOT_EXISTS__') {
|
||
return null;
|
||
}
|
||
return cachedData;
|
||
}
|
||
ctx.logger.info(`${cacheKey}无缓存`);
|
||
|
||
|
||
let platformInfo = null;
|
||
// 2. 先查询平台设置表(关联基础平台表)
|
||
const platformSetting = await app.model.PlatformSetting.findOne({
|
||
where: {
|
||
code: platformCode,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
include: [
|
||
{
|
||
model: this.app.model.Platform,
|
||
as: 'platform',
|
||
attributes: [ 'code', 'name', 'print_platform_id' ],
|
||
},
|
||
],
|
||
});
|
||
if (platformSetting && platformSetting.platform) {
|
||
const printPlatformCodeMap = await this.loadPrintPlatformCodeMap([ platformSetting.platform ]);
|
||
// 从设置表中找到,并且有关联的平台信息
|
||
platformInfo = {
|
||
code: platformSetting.platform.code,
|
||
name: platformSetting.platform.name,
|
||
default_express_interface: this.resolveDefaultExpressInterface(platformSetting.platform, printPlatformCodeMap),
|
||
source: 'setting', // 标记来源
|
||
setting_id: platformSetting.id,
|
||
warehouse_id: warehouseId,
|
||
};
|
||
} else {
|
||
// 3. 设置表中没有,直接查询基础平台表
|
||
const basePlatform = await app.model.Platform.findOne({
|
||
where: {
|
||
code: platformCode,
|
||
},
|
||
attributes: [ 'code', 'name', 'print_platform_id' ],
|
||
});
|
||
|
||
if (basePlatform) {
|
||
const printPlatformCodeMap = await this.loadPrintPlatformCodeMap([ basePlatform ]);
|
||
platformInfo = {
|
||
code: basePlatform.code,
|
||
name: basePlatform.name,
|
||
default_express_interface: this.resolveDefaultExpressInterface(basePlatform, printPlatformCodeMap),
|
||
source: 'base', // 标记来源
|
||
warehouse_id: warehouseId,
|
||
};
|
||
}
|
||
}
|
||
|
||
// 4. 设置缓存
|
||
if (platformInfo) {
|
||
// 平台存在,缓存5分钟
|
||
await app.setCacheAsync(cacheKey, platformInfo, 300);
|
||
ctx.logger.info(`平台信息已缓存: ${cacheKey}`);
|
||
} else {
|
||
// 平台不存在,缓存特殊标记,时间可以短一些(2分钟)
|
||
await app.setCacheAsync(cacheKey, '__NOT_EXISTS__', 120);
|
||
ctx.logger.info(`平台不存在标记已缓存: ${cacheKey}`);
|
||
}
|
||
|
||
return platformInfo;
|
||
|
||
} catch (error) {
|
||
ctx.logger.error(`检查平台存在性失败: ${error.message}`, {
|
||
platformCode,
|
||
warehouseId,
|
||
error: error.stack,
|
||
});
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取平台信息(带异常处理)
|
||
* @param {string} platformCode 平台代码
|
||
* @param {number} warehouseId 仓库ID
|
||
* @return {Promise<Object>} 平台信息
|
||
* @throws {Error} 平台不存在时抛出异常
|
||
*/
|
||
async getPlatformInfo(platformCode, warehouseId) {
|
||
const platformInfo = await this.checkPlatformExists(platformCode, warehouseId);
|
||
|
||
if (!platformInfo) {
|
||
throw new Error(`平台 ${platformCode} 在仓库 ${warehouseId} 中不存在`);
|
||
}
|
||
|
||
return platformInfo;
|
||
}
|
||
|
||
/**
|
||
* 清除平台缓存
|
||
* @param {string} platformCode 平台代码
|
||
* @param {number} warehouseId 仓库ID
|
||
*/
|
||
async clearPlatformCache(platformCode, warehouseId) {
|
||
const { app } = this;
|
||
const cacheKey = `platform:${platformCode}:${warehouseId}`;
|
||
await app.setCacheAsync(cacheKey, null, 0); // 立即过期
|
||
}
|
||
|
||
/**
|
||
* 获取平台设置详情(包括完整的设置信息)
|
||
* @param {string} platformCode 平台代码
|
||
* @param {number} warehouseId 仓库ID
|
||
* @return {Promise<Object|null>} 平台设置详情
|
||
*/
|
||
async getPlatformSettingDetail(platformCode, warehouseId) {
|
||
const cacheKey = `platform_setting_detail:${platformCode}:${warehouseId}`;
|
||
|
||
try {
|
||
// 从缓存获取
|
||
const cachedData = await this.app.getCacheAsync(cacheKey);
|
||
if (cachedData) {
|
||
return cachedData === '__NOT_EXISTS__' ? null : cachedData;
|
||
}
|
||
|
||
const setting = await this.app.model.PlatformSetting.findOne({
|
||
where: {
|
||
code: platformCode,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
include: [
|
||
{
|
||
model: this.app.model.Platform,
|
||
as: 'platform',
|
||
attributes: [ 'code', 'name', 'print_platform_id' ],
|
||
},
|
||
],
|
||
});
|
||
|
||
if (setting) {
|
||
const result = {
|
||
id: setting.id,
|
||
platform_code: setting.platform_code,
|
||
code: setting.code,
|
||
warehouse_id: setting.warehouse_id,
|
||
platform: setting.platform,
|
||
warehouse: setting.warehouse,
|
||
};
|
||
|
||
// 缓存10分钟
|
||
await this.app.setCacheAsync(cacheKey, result, 600);
|
||
return result;
|
||
}
|
||
// 缓存2分钟的不存在标记
|
||
await this.app.setCacheAsync(cacheKey, '__NOT_EXISTS__', 120);
|
||
return null;
|
||
|
||
|
||
} catch (error) {
|
||
this.ctx.logger.error(`获取平台设置详情失败: ${error.message}`);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量检查多个平台
|
||
* @param {Array} platformWarehouseList 平台和仓库列表 [{platformCode, warehouseId}, ...]
|
||
* @return {Promise<Array>} 存在的平台列表
|
||
*/
|
||
async batchCheckPlatforms(platformWarehouseList) {
|
||
const results = [];
|
||
|
||
for (const item of platformWarehouseList) {
|
||
const { platformCode, warehouseId } = item;
|
||
const exists = await this.checkPlatformExists(platformCode, warehouseId);
|
||
|
||
if (exists) {
|
||
results.push({
|
||
platformCode,
|
||
warehouseId,
|
||
exists: true,
|
||
info: exists,
|
||
});
|
||
} else {
|
||
results.push({
|
||
platformCode,
|
||
warehouseId,
|
||
exists: false,
|
||
info: null,
|
||
});
|
||
}
|
||
}
|
||
|
||
return results;
|
||
}
|
||
|
||
/**
|
||
* 创建平台设置
|
||
* @param {Object} data 平台设置数据
|
||
* @param {string} data.platform_code 平台代码
|
||
* @param {string} data.code 设置代码
|
||
* @param {number} data.warehouse_id 仓库ID
|
||
* @return {Promise<Object>} 创建的设置
|
||
*/
|
||
async createPlatformSetting(data) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
// 1. 验证平台是否存在
|
||
const platform = await this.app.model.Platform.findOne({
|
||
where: { code: data.platform_code },
|
||
});
|
||
|
||
if (!platform) {
|
||
throw new Error(`平台 ${data.platform_code} 不存在`);
|
||
}
|
||
|
||
// 2. 验证仓库是否存在
|
||
const warehouse = await this.app.model.Store.findOne({
|
||
where: { id: data.warehouse_id },
|
||
});
|
||
|
||
if (!warehouse) {
|
||
throw new Error(`仓库 ${data.warehouse_id} 不存在`);
|
||
}
|
||
|
||
// 3. 检查是否已存在相同的设置
|
||
const exists = await this.app.model.PlatformSetting.findOne({
|
||
where: {
|
||
platform_code: data.platform_code,
|
||
warehouse_id: data.warehouse_id,
|
||
},
|
||
});
|
||
|
||
if (exists) {
|
||
throw new Error(`平台 ${data.platform_code} 在仓库 ${data.warehouse_id} 中已存在设置`);
|
||
}
|
||
|
||
// 4. 创建设置
|
||
const setting = await this.app.model.PlatformSetting.create(data);
|
||
|
||
// 5. 清除相关缓存
|
||
await this.clearPlatformCache(data.platform_code, data.warehouse_id);
|
||
|
||
return setting;
|
||
|
||
} catch (error) {
|
||
ctx.logger.error(`创建平台设置失败: ${error.message}`);
|
||
throw error;
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = PlatformService;
|