2026-04-17 19:21:57 +08:00

447 lines
14 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 MainService = require('../main');
class indexService extends MainService {
/**
* 初始化基础方法的免登录、免权限、免鉴权和免日志配置。
*
* @param {Egg.Context} ctx 上下文对象
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'getI18nMessage,putI18nCollect';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
const _noNeedLog = '*';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
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 });
}
// 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 getExpressList() {
const { service } = this;
const result = await service.systems.express.getExpressList();
return this.success('ok', { data: result, code: 200 });
}
/**
* 获取快递产品类型列表。
*
* @param {Object} data 请求参数
* @param {string} [data.express_code] 快递公司编码
* @return {Promise<Object>} 返回结果
*/
async getExpressProductTypeList(data) {
const { service } = this;
const { express_code: expressCode = '' } = data || {};
const result = await service.systems.express.getExpressProductTypeList(expressCode);
return this.success('ok', { data: result, code: 200 });
}
async getPlatformList() {
const { service } = this;
const result = await service.systems.platform.getPlatformList();
return this.success('ok', { data: result, code: 200 });
}
}
module.exports = indexService;