1272 lines
40 KiB
JavaScript
1272 lines
40 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
const crypto = require('crypto');
|
||
const PddClient = require('../../lib/pdd_client');
|
||
|
||
const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router';
|
||
const SHOP_MASK_PLACEHOLDER = `***`;
|
||
|
||
/**
|
||
* 脱敏通用敏感文本。
|
||
*
|
||
* @param {*} value 原始敏感值
|
||
* @return {string|null} 脱敏后的值;原值为空时返回 null
|
||
*/
|
||
function maskSensitiveText(value) {
|
||
if (value === null || value === undefined || String(value).trim() === '') {
|
||
return null;
|
||
}
|
||
|
||
return SHOP_MASK_PLACEHOLDER;
|
||
}
|
||
|
||
/**
|
||
* 脱敏店铺归属人标识。
|
||
*
|
||
* @param {*} ownerId 店铺归属人标识
|
||
* @return {string|null} 脱敏后的归属人标识;原值为空时返回 null
|
||
*/
|
||
function maskShopOwnerId(ownerId) {
|
||
if (ownerId === null || ownerId === undefined || String(ownerId).trim() === '') {
|
||
return null;
|
||
}
|
||
|
||
const ownerIdText = String(ownerId);
|
||
if (ownerIdText.length <= 5) {
|
||
return SHOP_MASK_PLACEHOLDER;
|
||
}
|
||
|
||
return `${ownerIdText.slice(0, 3)}${SHOP_MASK_PLACEHOLDER}${ownerIdText.slice(-2)}`;
|
||
}
|
||
|
||
/**
|
||
* 将店铺记录裁剪为安全的列表输出。
|
||
*
|
||
* @param {Object} shopItem 店铺记录或模型实例
|
||
* @return {Object} 脱敏后的店铺列表项
|
||
*/
|
||
function maskShopListItem(shopItem) {
|
||
const plainItem = shopItem && typeof shopItem.get === 'function'
|
||
? shopItem.get({ plain: true })
|
||
: shopItem || {};
|
||
|
||
return {
|
||
id: plainItem.id,
|
||
warehouse_id: plainItem.warehouse_id,
|
||
platform_code: plainItem.platform_code,
|
||
shop_name: plainItem.shop_name,
|
||
custom_name: plainItem.custom_name,
|
||
status: plainItem.status,
|
||
auth_expire_at: plainItem.auth_expire_at,
|
||
token_expires_at: plainItem.token_expires_at,
|
||
refresh_token_expires_at: plainItem.refresh_token_expires_at,
|
||
scope: plainItem.scope,
|
||
created_at: plainItem.created_at,
|
||
updated_at: plainItem.updated_at,
|
||
owner_id: maskShopOwnerId(plainItem.owner_id),
|
||
access_token: maskSensitiveText(plainItem.access_token),
|
||
refresh_token: maskSensitiveText(plainItem.refresh_token),
|
||
auth_random_code: maskSensitiveText(plainItem.auth_random_code),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将任意值标准化为空字符串。
|
||
*
|
||
* @param {*} value 原始值
|
||
* @return {string} 标准化后的字符串
|
||
*/
|
||
function normalizeText(value) {
|
||
if (value === null || value === undefined) {
|
||
return '';
|
||
}
|
||
|
||
return String(value);
|
||
}
|
||
|
||
/**
|
||
* 将任意值标准化为数组。
|
||
*
|
||
* @param {*} value 原始值
|
||
* @return {Array} 数组值;非数组时返回空数组
|
||
*/
|
||
function normalizeArray(value) {
|
||
return Array.isArray(value) ? value : [];
|
||
}
|
||
|
||
/**
|
||
* 根据平台编码构建平台侧快递编码到系统快递名称的映射。
|
||
*
|
||
* @param {Array} expressList 系统快递列表
|
||
* @param {string} platformCode 平台编码
|
||
* @return {Object} 平台侧快递编码到系统快递名称的映射
|
||
*/
|
||
function buildPlatformExpressNameMap(expressList, platformCode) {
|
||
const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase();
|
||
|
||
if (!normalizedPlatformCode) {
|
||
return {};
|
||
}
|
||
|
||
return normalizeArray(expressList).reduce((result, expressItem) => {
|
||
const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {};
|
||
const platformExpressCode = normalizeText(currentExpressItem[normalizedPlatformCode]).trim();
|
||
|
||
if (!platformExpressCode) {
|
||
return result;
|
||
}
|
||
|
||
result[platformExpressCode] = normalizeText(currentExpressItem.name);
|
||
return result;
|
||
}, {});
|
||
}
|
||
|
||
/**
|
||
* 解析拼多多电子面单网点查询响应,收敛为前端易消费的结构。
|
||
*
|
||
* @param {*} responseData 拼多多原始响应
|
||
* @param {Object} [expressNameMap={}] 平台快递编码到系统快递名称的映射
|
||
* @return {Object} 解析后的电子面单网点结构
|
||
*/
|
||
function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) {
|
||
const waybillResponse = responseData && typeof responseData === 'object'
|
||
? responseData.pdd_waybill_search_response || {}
|
||
: {};
|
||
const subscriptions = normalizeArray(waybillResponse.waybill_apply_subscription_cols);
|
||
|
||
const list = subscriptions.map(subscription => {
|
||
const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {};
|
||
const accounts = normalizeArray(subscriptionItem.branch_account_cols).map(account => {
|
||
const accountItem = account && typeof account === 'object' ? account : {};
|
||
const shipAddresses = normalizeArray(accountItem.shipp_address_cols).map(address => {
|
||
const addressItem = address && typeof address === 'object' ? address : {};
|
||
|
||
return {
|
||
country: normalizeText(addressItem.country),
|
||
province: normalizeText(addressItem.province),
|
||
city: normalizeText(addressItem.city),
|
||
district: normalizeText(addressItem.district),
|
||
detail: normalizeText(addressItem.detail),
|
||
full_address: normalizeText(addressItem.full_address),
|
||
};
|
||
});
|
||
const services = normalizeArray(accountItem.service_info_cols).map(service => {
|
||
const serviceItem = service && typeof service === 'object' ? service : {};
|
||
const attributes = normalizeArray(serviceItem.service_attributes).map(attribute => {
|
||
const attributeItem = attribute && typeof attribute === 'object' ? attribute : {};
|
||
|
||
return {
|
||
attribute_code: normalizeText(attributeItem.attribute_code),
|
||
attribute_name: normalizeText(attributeItem.attribute_name),
|
||
attribute_type: normalizeText(attributeItem.attribute_type),
|
||
type_desc: normalizeText(attributeItem.type_desc),
|
||
};
|
||
});
|
||
|
||
return {
|
||
service_code: normalizeText(serviceItem.service_code),
|
||
service_name: normalizeText(serviceItem.service_name),
|
||
service_desc: normalizeText(serviceItem.service_desc),
|
||
required: Boolean(serviceItem.required),
|
||
attributes,
|
||
};
|
||
});
|
||
|
||
return {
|
||
branch_code: normalizeText(accountItem.branch_code),
|
||
branch_name: normalizeText(accountItem.branch_name),
|
||
quantity: accountItem.quantity ?? 0,
|
||
cancel_quantity: accountItem.cancel_quantity ?? 0,
|
||
recycled_quantity: accountItem.recycled_quantity ?? 0,
|
||
allocated_quantity: accountItem.allocated_quantity ?? 0,
|
||
ship_addresses: shipAddresses,
|
||
services,
|
||
};
|
||
});
|
||
|
||
return {
|
||
wp_code: normalizeText(subscriptionItem.wp_code),
|
||
wp_name: normalizeText(expressNameMap[normalizeText(subscriptionItem.wp_code)]) || '',
|
||
wp_type: normalizeText(subscriptionItem.wp_type),
|
||
accounts,
|
||
};
|
||
});
|
||
|
||
return {
|
||
request_id: normalizeText(waybillResponse.request_id),
|
||
total: subscriptions.length,
|
||
list,
|
||
};
|
||
}
|
||
|
||
class indexService extends MainService {
|
||
/**
|
||
* 初始化基础方法的免登录、免权限、免鉴权和免日志配置。
|
||
*
|
||
* @param {Egg.Context} ctx 上下文对象
|
||
*/
|
||
constructor(ctx) {
|
||
super(ctx);
|
||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test';
|
||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPlatformOauthLink,recognizeLicensePlate';
|
||
const _noNeedLog = '*';
|
||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPlatformOauthLink,recognizeLicensePlate,test';
|
||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||
}
|
||
async fastWhereTree(data) {
|
||
const { service } = this;
|
||
const { type } = data;
|
||
const result = await service.systems.fastWhere.getTreeByType(type);
|
||
return this.success('ok', { presetTree: result, code: 200 });
|
||
}
|
||
async loadStores() {
|
||
const { service } = this;
|
||
const result = await service.systems.store.loadStores();
|
||
return this.success('ok', { stores: result, code: 200 });
|
||
}
|
||
async getCOSUploadConfig(datas) {
|
||
const { service } = this;
|
||
const { data } = datas;
|
||
const result = await service.systems.upload.getUploadParams(data);
|
||
return this.success('ok', { data: result, code: 200 });
|
||
}
|
||
async getImages(data) {
|
||
const { service } = this;
|
||
const result = await service.systems.file.getImages(data);
|
||
return this.success('ok', { data: result, code: 200 });
|
||
}
|
||
async uploadSuccessNotify(data) {
|
||
const { service } = this;
|
||
const result = await service.systems.upload.uploadSuccessNotify(data);
|
||
return this.success('ok', { data: result, code: 200 });
|
||
}
|
||
/**
|
||
* 识别车牌号码。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {string} data.base64 base64 图片
|
||
* @param {string} [data.imageBase64] 兼容的 base64 字段
|
||
* @param {string} [data.image_base64] 兼容的 base64 字段
|
||
* @return {Promise<Object>} 识别结果
|
||
*/
|
||
async recognizeLicensePlate(data) {
|
||
const { service, ctx } = this;
|
||
const { base64 = '', imageBase64 = '', image_base64 = '' } = data || {};
|
||
const imageBase64Value = String(base64 || imageBase64 || image_base64 || '').trim();
|
||
|
||
if (!imageBase64Value) {
|
||
return this.fail('base64 图片不能为空', { code: 400 });
|
||
}
|
||
|
||
try {
|
||
const result = await service.systems.licensePlate.recognizeLicensePlate(imageBase64Value);
|
||
return this.success('ok', { data: result, code: 200 });
|
||
} catch (error) {
|
||
ctx.logger.error('车牌识别失败:', error);
|
||
return this.fail(error.message || '车牌识别失败', { code: 500 });
|
||
}
|
||
}
|
||
async ReferenceFile(data) {
|
||
const { service } = this;
|
||
const result = await service.systems.file.ReferenceFile(data);
|
||
return this.success('ok', { data: result, code: 200 });
|
||
}
|
||
async getMessageDetail(data) {
|
||
const { service } = this;
|
||
const result = await service.systems.operationLog.getMessageDetail(data);
|
||
return this.success('ok', { data: result, code: 200 });
|
||
}
|
||
|
||
/**
|
||
* 后台专用的拼多多接口测试入口。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {string} data.type 拼多多接口名,例如 pdd.order.number.list.get
|
||
* @param {Object} [data.bizParams] 业务参数对象
|
||
* @param {Object} [data.request] 业务参数别名,兼容旧调用方式
|
||
* @param {string} [data.accessToken] 用户授权令牌
|
||
* @param {string} [data.dataType='JSON'] 响应格式
|
||
* @param {string} [data.version] API 版本
|
||
* @param {string|number} [data.timestamp] 时间戳
|
||
* @param {string} [data.clientId] client_id 覆盖值
|
||
* @param {string} [data.clientSecret] client_secret 覆盖值
|
||
* @param {string} [data.baseUrl] 请求地址
|
||
* @param {Object} [data.headers] 额外请求头
|
||
* @param {number} [data.timeout] 请求超时
|
||
* @return {Promise<Object>} 调用结果
|
||
*/
|
||
async test(data = {}) {
|
||
const { ctx } = this;
|
||
const input = data && typeof data === 'object' ? data : {};
|
||
const {
|
||
type,
|
||
access_token: accessTokenSnake,
|
||
accessToken,
|
||
data_type: dataTypeSnake,
|
||
dataType = 'JSON',
|
||
version,
|
||
timestamp,
|
||
client_id: clientIdSnake,
|
||
clientId,
|
||
client_secret: clientSecretSnake,
|
||
clientSecret,
|
||
base_url: baseUrlSnake,
|
||
baseUrl = DEFAULT_PDD_ROUTER_URL,
|
||
headers = {},
|
||
timeout,
|
||
bizParams,
|
||
biz_params: bizParamsSnake,
|
||
request,
|
||
...rest
|
||
} = input;
|
||
|
||
if (!String(type || '').trim()) {
|
||
return this.fail('type 不能为空', { code: 400 });
|
||
}
|
||
|
||
const requestParams = {};
|
||
if (rest && typeof rest === 'object' && !Array.isArray(rest)) {
|
||
Object.assign(requestParams, rest);
|
||
}
|
||
if (bizParams && typeof bizParams === 'object' && !Array.isArray(bizParams)) {
|
||
Object.assign(requestParams, bizParams);
|
||
}
|
||
if (request && typeof request === 'object' && !Array.isArray(request)) {
|
||
Object.assign(requestParams, request);
|
||
}
|
||
|
||
const normalizedAccessToken = accessToken !== undefined ? accessToken : accessTokenSnake;
|
||
const normalizedDataType = dataTypeSnake !== undefined ? dataTypeSnake : dataType;
|
||
const normalizedClientId = clientId !== undefined ? clientId : clientIdSnake;
|
||
const normalizedClientSecret = clientSecret !== undefined ? clientSecret : clientSecretSnake;
|
||
const normalizedBaseUrl = baseUrlSnake !== undefined ? baseUrlSnake : baseUrl;
|
||
if (bizParamsSnake && typeof bizParamsSnake === 'object' && !Array.isArray(bizParamsSnake)) {
|
||
Object.assign(requestParams, bizParamsSnake);
|
||
}
|
||
|
||
const pddClient = new PddClient(ctx);
|
||
const builtRequest = pddClient.buildRequest({
|
||
type,
|
||
accessToken: normalizedAccessToken,
|
||
dataType: normalizedDataType,
|
||
version,
|
||
timestamp,
|
||
clientId: normalizedClientId,
|
||
clientSecret: normalizedClientSecret,
|
||
bizParams: requestParams,
|
||
});
|
||
|
||
try {
|
||
const response = await ctx.curl(String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
...(headers && typeof headers === 'object' ? headers : {}),
|
||
},
|
||
dataType: String(normalizedDataType || 'json').toLowerCase() === 'xml' ? 'text' : 'json',
|
||
data: builtRequest.requestBody,
|
||
timeout,
|
||
});
|
||
|
||
const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data')
|
||
? response.data
|
||
: response;
|
||
const parsedResponse = type === 'pdd.waybill.search'
|
||
? formatPddWaybillSearchResponse(responseData)
|
||
: null;
|
||
|
||
return this.success('ok', {
|
||
data: {
|
||
requestBody: builtRequest.requestBody,
|
||
signText: builtRequest.signText,
|
||
sortedPairs: builtRequest.sortedPairs,
|
||
response: responseData,
|
||
parsed_response: parsedResponse,
|
||
baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL),
|
||
},
|
||
code: 200,
|
||
});
|
||
} catch (error) {
|
||
ctx.logger.error('PDD 测试接口调用失败:', error);
|
||
return this.fail(error.message || 'PDD 测试接口调用失败', {
|
||
code: 500,
|
||
data: {
|
||
requestBody: builtRequest.requestBody,
|
||
signText: builtRequest.signText,
|
||
sortedPairs: builtRequest.sortedPairs,
|
||
baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL),
|
||
},
|
||
});
|
||
}
|
||
}
|
||
|
||
// app/controller/i18n.js 中
|
||
async getI18nMessage(data) {
|
||
const { ctx } = this;
|
||
const { language = 'zh-CN' } = data || ctx.query;
|
||
|
||
try {
|
||
// 1. 查询当前项目的所有翻译(默认项目为 'wms')
|
||
const translations = await ctx.model.I18nTranslation.findAll({
|
||
include: [{
|
||
model: ctx.model.I18nKey,
|
||
as: 'key',
|
||
where: {
|
||
project: 'wms',
|
||
},
|
||
attributes: [ 'key_name' ],
|
||
}],
|
||
where: {
|
||
language,
|
||
},
|
||
});
|
||
|
||
// 2. 构建嵌套结构的翻译对象
|
||
const result = {};
|
||
translations.forEach(item => {
|
||
if (item.key && item.key.key_name) {
|
||
const keys = item.key.key_name.split('.');
|
||
let current = result;
|
||
|
||
// 构建嵌套路径
|
||
for (let i = 0; i < keys.length - 1; i++) {
|
||
const key = keys[i];
|
||
if (!current[key]) {
|
||
current[key] = {};
|
||
}
|
||
current = current[key];
|
||
}
|
||
|
||
// 设置翻译值
|
||
const lastKey = keys[keys.length - 1];
|
||
current[lastKey] = item.translation || item.key.key_name;
|
||
}
|
||
});
|
||
|
||
// 3. 获取统计信息
|
||
const totalKeys = await ctx.model.I18nKey.count({
|
||
where: { project: 'wms' },
|
||
});
|
||
|
||
const translatedCount = await ctx.model.I18nTranslation.count({
|
||
include: [{
|
||
model: ctx.model.I18nKey,
|
||
as: 'key',
|
||
where: { project: 'wms' },
|
||
}],
|
||
where: {
|
||
language,
|
||
translation: { [ctx.app.Sequelize.Op.ne]: null }, // 非空
|
||
},
|
||
});
|
||
|
||
return this.success('ok', {
|
||
data: {
|
||
success: true,
|
||
messages: result,
|
||
stats: {
|
||
language,
|
||
total: totalKeys,
|
||
translated: translatedCount,
|
||
untranslated: totalKeys - translatedCount,
|
||
progress: totalKeys > 0 ? Math.round((translatedCount / totalKeys) * 100) : 0,
|
||
timestamp: new Date().toISOString(),
|
||
},
|
||
},
|
||
code: 200,
|
||
});
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('获取翻译失败:', error);
|
||
// 失败时返回空结果
|
||
return this.success('ok', {
|
||
data: {
|
||
success: true,
|
||
messages: {},
|
||
stats: {
|
||
language,
|
||
total: 0,
|
||
translated: 0,
|
||
untranslated: 0,
|
||
progress: 0,
|
||
timestamp: new Date().toISOString(),
|
||
},
|
||
},
|
||
code: 200,
|
||
});
|
||
}
|
||
}
|
||
async putI18nCollect(data) {
|
||
const { ctx } = this;
|
||
const { keys = [], locale = 'zh-CN', project = 'wms', source = 'frontend-auto' } = data || ctx.request.body;
|
||
|
||
try {
|
||
const result = {
|
||
processed: 0,
|
||
createdKeys: 0,
|
||
createdTranslations: 0,
|
||
updatedKeys: 0,
|
||
details: [],
|
||
};
|
||
|
||
for (const keyData of keys) {
|
||
const { key, value, context, timestamp } = keyData;
|
||
|
||
try {
|
||
// 1. 查找或创建键值记录
|
||
let keyRecord = await ctx.model.I18nKey.findOne({
|
||
where: { key_name: key, project },
|
||
});
|
||
|
||
let keyAction = 'exists';
|
||
|
||
if (!keyRecord) {
|
||
// 创建新键值
|
||
keyRecord = await ctx.model.I18nKey.create({
|
||
key_name: key,
|
||
project,
|
||
module: this.extractModule(key),
|
||
description: context ? JSON.stringify(context) : null,
|
||
status: 1,
|
||
created_by: source,
|
||
});
|
||
keyAction = 'created';
|
||
result.createdKeys++;
|
||
} else {
|
||
// 更新使用次数(可以添加一个 usage_count 字段)
|
||
keyRecord.updated_at = new Date();
|
||
await keyRecord.save();
|
||
keyAction = 'updated';
|
||
result.updatedKeys++;
|
||
}
|
||
|
||
// 2. 创建或更新翻译记录
|
||
let translation = await ctx.model.I18nTranslation.findOne({
|
||
where: { key_id: keyRecord.id, language: locale },
|
||
});
|
||
|
||
if (!translation) {
|
||
// 创建翻译记录(默认未翻译)
|
||
translation = await ctx.model.I18nTranslation.create({
|
||
key_id: keyRecord.id,
|
||
language: locale,
|
||
translation: value || null, // 如果有值就保存,否则null
|
||
translation_status: value ? 1 : 0, // 有值设为待审核,没有就是未翻译
|
||
auto_generated: source.includes('auto') ? 1 : 0,
|
||
translator: source,
|
||
created_at: new Date(timestamp || Date.now()),
|
||
});
|
||
result.createdTranslations++;
|
||
} else if (value && !translation.translation) {
|
||
// 如果已有记录但没有翻译,现在有值了就更新
|
||
translation.translation = value;
|
||
translation.translation_status = 1; // 设为待审核
|
||
translation.updated_at = new Date();
|
||
await translation.save();
|
||
}
|
||
|
||
result.details.push({
|
||
key,
|
||
keyId: keyRecord.id,
|
||
keyAction,
|
||
translationExists: !!translation,
|
||
translationValue: translation?.translation || null,
|
||
});
|
||
|
||
} catch (error) {
|
||
ctx.logger.error(`处理键值 ${key} 失败:`, error);
|
||
result.details.push({
|
||
key,
|
||
error: error.message,
|
||
success: false,
|
||
});
|
||
}
|
||
}
|
||
|
||
result.processed = keys.length;
|
||
|
||
// 3. 尝试自动翻译(可选)
|
||
if (result.createdTranslations > 0) {
|
||
await this.tryAutoTranslateNewKeys(project, locale);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
data: {
|
||
success: true,
|
||
processed: result.processed,
|
||
stats: {
|
||
totalKeys: await ctx.model.I18nKey.count({ where: { project } }),
|
||
totalTranslations: await ctx.model.I18nTranslation.count({
|
||
include: [{
|
||
model: ctx.model.I18nKey,
|
||
as: 'key',
|
||
where: { project },
|
||
}],
|
||
where: { language: locale },
|
||
}),
|
||
newKeys: result.createdKeys,
|
||
newTranslations: result.createdTranslations,
|
||
},
|
||
details: result.details,
|
||
},
|
||
code: 200,
|
||
});
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('批量处理键值失败:', error);
|
||
return this.success('ok', {
|
||
data: {
|
||
success: false,
|
||
error: error.message,
|
||
processed: 0,
|
||
},
|
||
code: 500,
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 从键名提取模块
|
||
* @param {string} keyName 键名
|
||
*/
|
||
extractModule(keyName) {
|
||
if (!keyName) return 'common';
|
||
|
||
const parts = keyName.split('.');
|
||
if (parts.length > 1) {
|
||
const possibleModules = [ 'warehouse', 'inventory', 'order', 'shipment', 'user', 'system', 'common' ];
|
||
if (possibleModules.includes(parts[0])) {
|
||
return parts[0];
|
||
}
|
||
}
|
||
|
||
return 'common';
|
||
}
|
||
|
||
/**
|
||
* 尝试自动翻译新键值(可选功能)
|
||
* @param {string} project 项目
|
||
* @param {string} targetLanguage 目标语言
|
||
*/
|
||
async tryAutoTranslateNewKeys(project, targetLanguage) {
|
||
const { ctx } = this;
|
||
|
||
// 只有目标语言不是中文时才需要翻译
|
||
if (targetLanguage === 'zh-CN') return;
|
||
|
||
try {
|
||
// 查找需要翻译的记录(中文有翻译,但目标语言没有)
|
||
const needTranslate = await ctx.model.I18nTranslation.findAll({
|
||
include: [{
|
||
model: ctx.model.I18nKey,
|
||
as: 'key',
|
||
where: { project },
|
||
}],
|
||
where: {
|
||
language: 'zh-CN',
|
||
translation: { [ctx.app.Sequelize.Op.ne]: null },
|
||
},
|
||
});
|
||
|
||
const chineseTranslations = {};
|
||
needTranslate.forEach(item => {
|
||
if (item.key) {
|
||
chineseTranslations[item.key.id] = item.translation;
|
||
}
|
||
});
|
||
|
||
// 检查目标语言是否已有翻译
|
||
const existingTranslations = await ctx.model.I18nTranslation.findAll({
|
||
where: {
|
||
key_id: Object.keys(chineseTranslations).map(id => parseInt(id)),
|
||
language: targetLanguage,
|
||
translation: { [ctx.app.Sequelize.Op.ne]: null },
|
||
},
|
||
});
|
||
|
||
const existingKeyIds = new Set(existingTranslations.map(t => t.key_id));
|
||
|
||
// 批量创建未翻译的记录
|
||
const createPromises = [];
|
||
for (const [ keyId ] of Object.entries(chineseTranslations)) {
|
||
if (!existingKeyIds.has(parseInt(keyId))) {
|
||
createPromises.push(
|
||
ctx.model.I18nTranslation.create({
|
||
key_id: parseInt(keyId),
|
||
language: targetLanguage,
|
||
translation: null, // 这里可以调用翻译API自动填充
|
||
translation_status: 0,
|
||
auto_generated: 1,
|
||
translator: 'auto-translate',
|
||
})
|
||
);
|
||
}
|
||
}
|
||
|
||
if (createPromises.length > 0) {
|
||
await Promise.all(createPromises);
|
||
ctx.logger.info(`为 ${createPromises.length} 个键值创建了 ${targetLanguage} 的翻译占位`);
|
||
}
|
||
|
||
} catch (error) {
|
||
ctx.logger.error('自动翻译处理失败:', error);
|
||
}
|
||
}
|
||
async searchSpace(data) {
|
||
const { service } = this;
|
||
const result = await service.systems.space.searchSpace(data);
|
||
return this.success('ok', result);
|
||
}
|
||
async listInterfaceTypes() {
|
||
const { ctx } = this;
|
||
const rows = await ctx.model.InterfaceType.findAll({
|
||
where: { is_enabled: 1, is_store: 1 },
|
||
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'description', 'is_enabled' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
const list = rows.map(row => {
|
||
const item = row.get({ plain: true });
|
||
return {
|
||
id: Number(item.id || 0),
|
||
interface_code: item.interface_code || '',
|
||
interface_name: item.interface_name || '',
|
||
interface_category: item.interface_category || '',
|
||
description: item.description || '',
|
||
is_enabled: Number(item.is_enabled || 0),
|
||
};
|
||
});
|
||
return this.success('ok', { list, total: list.length, code: 200 });
|
||
}
|
||
async getLocationTypeList() {
|
||
const { ctx } = this;
|
||
const { Op } = this.app.Sequelize;
|
||
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null;
|
||
const cacheKey = `index:locationTypeList:${warehouseId || 'global'}`;
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
|
||
if (Array.isArray(cached)) {
|
||
return this.success('ok', { list: cached, total: cached.length, code: 200 });
|
||
}
|
||
|
||
const where = {
|
||
is_active: true,
|
||
};
|
||
|
||
if (warehouseId) {
|
||
where[Op.or] = [
|
||
{ warehouse_id: warehouseId },
|
||
{ warehouse_id: null },
|
||
];
|
||
} else {
|
||
where.warehouse_id = null;
|
||
}
|
||
|
||
const rows = await ctx.model.LocationType.findAll({
|
||
where,
|
||
attributes: [
|
||
'id',
|
||
'type_code',
|
||
'type_name',
|
||
'temperature_zone',
|
||
'allow_allocation',
|
||
'allow_transfer_out',
|
||
'description',
|
||
'warehouse_id',
|
||
],
|
||
order: [[ 'warehouse_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
const list = rows.map(item => ({
|
||
id: Number(item.id || 0),
|
||
type_code: item.type_code || '',
|
||
type_name: item.type_name || '',
|
||
temperature_zone: item.temperature_zone || '',
|
||
allow_allocation: Boolean(item.allow_allocation),
|
||
allow_transfer_out: Boolean(item.allow_transfer_out),
|
||
description: item.description || '',
|
||
warehouse_id: item.warehouse_id === null || item.warehouse_id === undefined ? null : Number(item.warehouse_id),
|
||
}));
|
||
|
||
await this.app.setCacheAsync(cacheKey, list, 300);
|
||
|
||
return this.success('ok', { list, total: list.length, code: 200 });
|
||
}
|
||
/**
|
||
* 获取奇门应用列表。
|
||
*
|
||
* @return {Promise<Object>} 返回奇门应用列表结果
|
||
*/
|
||
async getQimenAppList() {
|
||
const { ctx } = this;
|
||
const cacheKey = 'index:qimenAppList';
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
|
||
if (Array.isArray(cached)) {
|
||
return this.success('ok', { list: cached, total: cached.length, code: 200 });
|
||
}
|
||
|
||
const rows = await ctx.model.QimenApp.findAll({
|
||
attributes: [ 'id', 'name', 'app_key' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
const list = rows.map(row => {
|
||
const item = typeof row.get === 'function' ? row.get({ plain: true }) : row;
|
||
return {
|
||
id: Number(item.id || 0),
|
||
name: item.name || '',
|
||
app_key: item.app_key || '',
|
||
};
|
||
});
|
||
|
||
await this.app.setCacheAsync(cacheKey, list, 300);
|
||
|
||
return this.success('ok', { list, total: list.length, code: 200 });
|
||
}
|
||
/**
|
||
* 获取快递列表。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {boolean} [data.systemOnly] 是否仅返回系统基础快递列表
|
||
* @return {Promise<Object>} 返回结果
|
||
*/
|
||
async getExpressList(data) {
|
||
const { service } = this;
|
||
const { systemOnly } = data || {};
|
||
const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly);
|
||
const result = await service.systems.express.getExpressList(isSystemOnly);
|
||
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 });
|
||
}
|
||
|
||
/**
|
||
* 获取平台列表。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {boolean} [data.systemOnly] 是否仅返回系统基础平台列表
|
||
* @param {boolean} [data.full] 是否返回全量字段
|
||
* @return {Promise<Object>} 返回结果
|
||
*/
|
||
async getPlatformList(data) {
|
||
const { service } = this;
|
||
const { systemOnly, full } = data || {};
|
||
const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly);
|
||
const isFull = [ true, 1, '1', 'true' ].includes(full);
|
||
const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull);
|
||
return this.success('ok', { data: result, code: 200 });
|
||
}
|
||
|
||
/**
|
||
* 获取当前仓库下的店铺列表。
|
||
*
|
||
* @return {Promise<Object>} 返回店铺列表结果
|
||
*/
|
||
async getShopList() {
|
||
const { ctx } = this;
|
||
const warehouseId = Number(ctx.user?.store_id);
|
||
|
||
if (!warehouseId) {
|
||
return this.fail('未识别到当前仓库', { code: 400 });
|
||
}
|
||
|
||
const list = await ctx.model.Shop.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
status: 1,
|
||
},
|
||
order: [[ 'status', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||
});
|
||
|
||
const maskedList = list.map(maskShopListItem);
|
||
|
||
return this.success('ok', { data: { list: maskedList }, code: 200 });
|
||
}
|
||
|
||
/**
|
||
* 实时请求拼多多电子面单网点列表。
|
||
*
|
||
* @param {string} accessToken 店铺授权令牌
|
||
* @return {Promise<Object>} 拼多多原始响应数据
|
||
* @throws {Error} 拼多多返回错误结构或请求失败时抛出异常
|
||
*/
|
||
async requestPddWaybillSearch(accessToken) {
|
||
const { ctx } = this;
|
||
const pddClient = new PddClient(ctx);
|
||
const builtRequest = pddClient.buildRequest({
|
||
type: 'pdd.waybill.search',
|
||
accessToken,
|
||
dataType: 'JSON',
|
||
});
|
||
const response = await ctx.curl(DEFAULT_PDD_ROUTER_URL, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
dataType: 'json',
|
||
data: builtRequest.requestBody,
|
||
});
|
||
const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data')
|
||
? response.data
|
||
: response;
|
||
|
||
if (responseData && typeof responseData === 'object' && responseData.error_response) {
|
||
const errorResponse = responseData.error_response;
|
||
throw new Error(errorResponse.error_msg || '拼多多电子面单查询失败');
|
||
}
|
||
|
||
return responseData;
|
||
}
|
||
|
||
/**
|
||
* 获取指定店铺的快递签约列表。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {string|number} [data.shop_id] 店铺 ID
|
||
* @param {string|number} [data.shopId] 店铺 ID,兼容驼峰字段
|
||
* @return {Promise<Object>} 返回店铺对应的快递签约列表
|
||
*/
|
||
async getShopExpressList(data = {}) {
|
||
const { ctx } = this;
|
||
const { shop_id: shopIdSnake, shopId: shopIdCamel } = data || {};
|
||
const shopId = [ shopIdSnake, shopIdCamel ].find(item => item !== undefined && item !== null && String(item).trim() !== '');
|
||
|
||
if (shopId === undefined) {
|
||
return this.fail('shop_id 不能为空', { code: 400 });
|
||
}
|
||
|
||
const warehouseId = Number(ctx.user?.store_id);
|
||
|
||
if (!warehouseId) {
|
||
return this.fail('未识别到当前仓库', { code: 400 });
|
||
}
|
||
|
||
const shop = await ctx.model.Shop.findOne({
|
||
where: {
|
||
id: shopId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
if (!shop) {
|
||
return this.fail('店铺不存在', { code: 404 });
|
||
}
|
||
|
||
const shopPlain = typeof shop.get === 'function'
|
||
? shop.get({ plain: true })
|
||
: shop;
|
||
const platformCode = String(shopPlain.platform_code || '').trim().toUpperCase();
|
||
let list = [];
|
||
|
||
switch (platformCode) {
|
||
case 'PDD': {
|
||
const accessToken = String(shopPlain.access_token || '').trim();
|
||
|
||
if (!accessToken) {
|
||
return this.fail('店铺未授权', { code: 400 });
|
||
}
|
||
|
||
const expressList = await this.service.systems.express.getExpressList(true);
|
||
const expressNameMap = buildPlatformExpressNameMap(expressList, platformCode);
|
||
const responseData = await this.requestPddWaybillSearch(accessToken);
|
||
const parsed = formatPddWaybillSearchResponse(responseData, expressNameMap);
|
||
|
||
list = parsed.list;
|
||
break;
|
||
}
|
||
default:
|
||
list = [];
|
||
break;
|
||
}
|
||
|
||
return this.success('ok', {
|
||
data: {
|
||
shop_id: shopPlain.id,
|
||
platform_code: platformCode,
|
||
list,
|
||
},
|
||
code: 200,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 判断是否为店铺预占记录的唯一约束冲突。
|
||
*
|
||
* @param {Error} error 异常对象
|
||
* @return {boolean} 是否可重试的唯一约束冲突
|
||
*/
|
||
isPlatformOauthReservationDuplicateError(error) {
|
||
if (!error || error.name !== 'SequelizeUniqueConstraintError') {
|
||
return false;
|
||
}
|
||
|
||
const fields = Array.isArray(error.errors) ? error.errors.map(item => item && item.path).filter(Boolean) : [];
|
||
return fields.length === 0 || fields.includes('auth_random_code') || fields.includes('shop_name');
|
||
}
|
||
|
||
/**
|
||
* 获取平台授权预占码前缀配置。
|
||
*
|
||
* @return {string} 授权预占码前缀
|
||
*/
|
||
getPlatformOauthReservationCodePrefix() {
|
||
const { app } = this;
|
||
return String(app.config.platformOauthReservationCodePrefix || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 判断授权预占码是否已带当前前缀。
|
||
*
|
||
* @param {string} authRandomCode 授权预占码
|
||
* @param {string} prefix 授权预占码前缀
|
||
* @return {boolean} 是否已带前缀
|
||
*/
|
||
hasPlatformOauthReservationCodePrefix(authRandomCode, prefix) {
|
||
if (!prefix) {
|
||
return true;
|
||
}
|
||
|
||
return String(authRandomCode || '').startsWith(prefix);
|
||
}
|
||
|
||
/**
|
||
* 规范化平台授权预占码。
|
||
*
|
||
* @param {string} authRandomCode 授权预占码
|
||
* @param {string} prefix 授权预占码前缀
|
||
* @return {string} 去掉当前前缀后的裸码,若未带前缀则原样返回
|
||
*/
|
||
normalizePlatformOauthReservationCode(authRandomCode, prefix) {
|
||
const normalizedCode = String(authRandomCode || '').trim();
|
||
|
||
if (!normalizedCode) {
|
||
return '';
|
||
}
|
||
|
||
if (prefix && this.hasPlatformOauthReservationCodePrefix(normalizedCode, prefix)) {
|
||
return normalizedCode.slice(prefix.length);
|
||
}
|
||
|
||
return normalizedCode;
|
||
}
|
||
|
||
/**
|
||
* 生成平台授权预占裸码。
|
||
*
|
||
* @return {string} 新授权预占裸码
|
||
*/
|
||
generatePlatformOauthReservationCode() {
|
||
return crypto.randomBytes(24).toString('hex');
|
||
}
|
||
|
||
/**
|
||
* 创建平台授权的店铺预占记录。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {string|number} data.warehouseId 仓库 ID
|
||
* @param {string} data.platformCode 平台编码
|
||
* @return {Promise<{ shop: Object, authRandomCode: string }>} 预占结果
|
||
*/
|
||
async createPlatformOauthReservation(data) {
|
||
const { ctx } = this;
|
||
const { warehouseId, platformCode } = data;
|
||
const maxRetryCount = 5;
|
||
const prefix = this.getPlatformOauthReservationCodePrefix();
|
||
|
||
const shop = await ctx.model.Shop.findOne({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
platform_code: platformCode,
|
||
status: 0,
|
||
},
|
||
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||
});
|
||
|
||
if (shop) {
|
||
const storedAuthRandomCode = String(shop.auth_random_code || '').trim();
|
||
if (storedAuthRandomCode) {
|
||
const authRandomCode = this.normalizePlatformOauthReservationCode(storedAuthRandomCode, prefix);
|
||
|
||
if (authRandomCode !== storedAuthRandomCode) {
|
||
shop.auth_random_code = authRandomCode;
|
||
await shop.save();
|
||
}
|
||
|
||
return {
|
||
shop,
|
||
authRandomCode,
|
||
};
|
||
}
|
||
}
|
||
|
||
for (let retryIndex = 0; retryIndex < maxRetryCount; retryIndex++) {
|
||
const authRandomCode = this.generatePlatformOauthReservationCode();
|
||
|
||
try {
|
||
if (shop) {
|
||
shop.auth_random_code = authRandomCode;
|
||
await shop.save();
|
||
|
||
return {
|
||
shop,
|
||
authRandomCode,
|
||
};
|
||
}
|
||
|
||
const createdShop = await ctx.model.Shop.create({
|
||
warehouse_id: warehouseId,
|
||
platform_code: platformCode,
|
||
shop_name: `PENDING_${authRandomCode}`,
|
||
status: 0,
|
||
auth_expire_at: null,
|
||
auth_random_code: authRandomCode,
|
||
});
|
||
|
||
return {
|
||
shop: createdShop,
|
||
authRandomCode,
|
||
};
|
||
} catch (error) {
|
||
if (this.isPlatformOauthReservationDuplicateError(error) && retryIndex < maxRetryCount - 1) {
|
||
continue;
|
||
}
|
||
|
||
if (this.isPlatformOauthReservationDuplicateError(error)) {
|
||
throw new Error('生成唯一授权码失败,请稍后重试');
|
||
}
|
||
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
throw new Error('生成唯一授权码失败,请稍后重试');
|
||
}
|
||
|
||
/**
|
||
* 获取平台授权链接。
|
||
*
|
||
* @param {Object} data 请求参数
|
||
* @param {string} [data.code] 平台编码
|
||
* @param {string} [data.platform_code] 平台编码
|
||
* @param {string} [data.platformCode] 平台编码
|
||
* @return {Promise<Object>} 返回授权链接结果
|
||
*/
|
||
async getPlatformOauthLink(data) {
|
||
const { ctx } = this;
|
||
const {
|
||
code = '',
|
||
platform_code: platformCodeSnake = '',
|
||
platformCode = '',
|
||
} = data || {};
|
||
const platform_code = String(code || platformCodeSnake || platformCode || '').trim().toUpperCase();
|
||
const warehouseId = String(ctx.user?.store_id ?? '').trim();
|
||
|
||
if (!platform_code) {
|
||
return this.fail('平台编码不能为空', { code: 400 });
|
||
}
|
||
|
||
if (!warehouseId) {
|
||
return this.fail('未识别到当前仓库', { code: 400 });
|
||
}
|
||
|
||
const platform = await ctx.model.Platform.findOne({
|
||
where: {
|
||
code: platform_code,
|
||
},
|
||
});
|
||
|
||
if (!platform) {
|
||
return this.fail('平台不存在', { code: 400 });
|
||
}
|
||
|
||
const authBaseUrl = String(platform.auth_base_url || '').trim();
|
||
if (!authBaseUrl) {
|
||
return this.fail('平台授权基础地址未配置', { code: 400 });
|
||
}
|
||
|
||
let reservation;
|
||
try {
|
||
reservation = await this.createPlatformOauthReservation({ warehouseId, platformCode: platform_code });
|
||
} catch (error) {
|
||
ctx.logger.error('创建平台授权预占记录失败:', error);
|
||
return this.fail(error.message || '创建平台授权预占记录失败', { code: 500 });
|
||
}
|
||
|
||
const prefix = this.getPlatformOauthReservationCodePrefix();
|
||
const oauthLink = `${authBaseUrl}${encodeURIComponent(`${prefix}${platform_code}_${reservation.authRandomCode}`)}`;
|
||
|
||
return this.success('ok', {
|
||
data: {
|
||
platform_code,
|
||
oauth_link: oauthLink,
|
||
},
|
||
code: 200,
|
||
});
|
||
}
|
||
/**
|
||
* 前端请求生成唯一的登录码,后续可以通过这个登录码在IM系统中完成登录状态的绑定。登录码只写入到缓存中,不存储在数据库,具有较短的过期时间(如5分钟),并且只能使用一次。
|
||
*
|
||
* @return {Promise<Object>} 返回登录码及用户信息
|
||
*/
|
||
async loginToIm() {
|
||
const { ctx } = this;
|
||
const { user } = ctx;
|
||
if (!user || !user.id) {
|
||
return this.fail('用户未登录', { code: 401 });
|
||
}
|
||
|
||
const employeeId = String(user.employees_id ?? '').trim();
|
||
const employeeName = String(user.employees_name ?? '').trim();
|
||
const subjectId = String(user.store_id ?? '').trim();
|
||
const subjectName = String(user.store_name ?? '').trim();
|
||
const avatar = String(user.avatar ?? '').trim();
|
||
const storeType = String(user.store_type ?? '').trim();
|
||
|
||
if (!employeeId || !employeeName || !subjectId || !subjectName || !storeType) {
|
||
return this.fail('用户信息不完整', { code: 400 });
|
||
}
|
||
|
||
const keyName = crypto.randomBytes(32).toString('hex');
|
||
const cacheKey = `im:sso:code:${keyName}`;
|
||
const payload = {
|
||
employees_id: employeeId,
|
||
employees_name: employeeName,
|
||
subject: {
|
||
id: subjectId,
|
||
name: subjectName,
|
||
type: storeType,
|
||
},
|
||
avatar,
|
||
created_at: Date.now(),
|
||
};
|
||
|
||
await this.app.setCacheAsync(cacheKey, payload, 300);
|
||
|
||
return this.success('ok', {
|
||
data: {
|
||
code: keyName,
|
||
employees_id: employeeId,
|
||
employees_name: employeeName,
|
||
subject: payload.subject,
|
||
store_type: storeType,
|
||
avatar,
|
||
},
|
||
code: 200,
|
||
});
|
||
}
|
||
}
|
||
module.exports = indexService;
|