375 lines
11 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 {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'getI18nMessage,putI18nCollect';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace';
const _noNeedLog = '*';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace';
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(data) {
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 });
}
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 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 project
* @param 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, chineseText ] 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 getExpressList(data) {
return this.success('ok', { data: this.app.config.expressList, code: 200 });
}
}
module.exports = indexService;