feat(client): 实现用户数据隔离与设备绑定优化- 添加用户会话ID构建逻辑,确保数据按用户隔离- 优化设备绑定流程,支持设备状态更新和绑定时间同步- 实现用户缓存清理功能,仅清除当前用户的数据- 增强客户端账号删除逻辑,级联删除相关数据

- 调整设备在线查询逻辑,确保只返回活跃绑定的设备
- 优化试用期逻辑,精确计算过期时间和类型- 添加账号管理弹窗和相关状态注入
-修复跟卖精灵按钮加载状态显示问题
- 增强文件上传区域UI,显示选中文件名
- 调整分页组件样式,优化界面展示效果- 优化反馈日志存储路径逻辑,默认使用用户目录
- 移除冗余代码和无用导入,提升代码整洁度
This commit is contained in:
2025-10-24 13:43:46 +08:00
parent e2a438c84e
commit 3a76aaa3c0
50 changed files with 860 additions and 590 deletions

View File

@@ -1,5 +1,5 @@
{
"name": "electron-vue-template",
"name": "erpClient",
"version": "0.1.0",
"description": "A minimal Electron + Vue application",
"main": "main/main.js",

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 固定日志路径到系统公共数据目录 -->
<property name="LOG_HOME" value="C:/ProgramData/erp-logs" />
<!-- 使用 Spring Boot 传递的日志路径 -->
<property name="LOG_HOME" value="${LOG_PATH:-logs}" />
<!-- 控制台输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">

View File

@@ -82,6 +82,18 @@ function getDataDirectoryPath(): string {
return dataDir;
}
function getUpdateDirectoryPath(): string {
const updateDir = join(app.getPath('userData'), 'updates');
if (!existsSync(updateDir)) mkdirSync(updateDir, {recursive: true});
return updateDir;
}
function getLogDirectoryPath(): string {
const logDir = join(app.getPath('userData'), 'logs');
if (!existsSync(logDir)) mkdirSync(logDir, {recursive: true});
return logDir;
}
interface AppConfig {
closeAction?: 'quit' | 'minimize' | 'tray';
autoLaunch?: boolean;
@@ -135,12 +147,11 @@ function migrateDataFromPublic(): void {
function startSpringBoot() {
migrateDataFromPublic();
const jarPath = getJarFilePath();
const javaPath = getJavaExecutablePath();
const dataDir = getDataDirectoryPath();
const logDir = getLogDirectoryPath();
const logbackConfigPath = getLogbackConfigPath();
if (!existsSync(jarPath)) {
dialog.showErrorBox('启动失败', `JAR 文件不存在:\n${jarPath}`);
app.quit();
@@ -152,7 +163,8 @@ function startSpringBoot() {
'-jar', jarPath,
`--spring.datasource.url=jdbc:sqlite:${dataDir}/erp-cache.db`,
`--server.port=8081`,
`--logging.config=file:${logbackConfigPath}`
`--logging.config=file:${logbackConfigPath}`,
`--logging.file.path=${logDir}`
];
springProcess = spawn(javaPath, springArgs, {
@@ -212,9 +224,7 @@ function startSpringBoot() {
app.quit();
}
}
startSpringBoot();
function stopSpringBoot() {
if (!springProcess) return;
try {
@@ -390,49 +400,30 @@ ipcMain.handle('get-jar-version', () => {
function checkPendingUpdate() {
try {
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
const appAsarPath = join(process.resourcesPath, 'app.asar');
const updateDir = getUpdateDirectoryPath();
const asarUpdatePath = join(updateDir, 'app.asar.update');
const jarUpdatePath = readdirSync(updateDir).find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
// 查找jar更新文件
let jarUpdatePath = '';
if (process.resourcesPath && existsSync(process.resourcesPath)) {
const files = readdirSync(process.resourcesPath);
const jarUpdateFile = files.find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
if (jarUpdateFile) {
jarUpdatePath = join(process.resourcesPath, jarUpdateFile);
}
}
// 如果没有任何更新文件,直接返回
if (!existsSync(asarUpdatePath) && !jarUpdatePath) return;
const appDir = dirname(process.execPath);
const helperPath = join(appDir, 'update-helper.bat');
if (!existsSync(helperPath)) return;
if (!existsSync(helperPath)) {
console.error('[UPDATE] 更新助手不存在:', helperPath);
return;
}
const appAsarPath = join(process.resourcesPath, 'app.asar');
const vbsPath = join(app.getPath('temp'), 'update-silent.vbs');
const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${asarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${jarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${asarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${jarUpdatePath ? join(updateDir, jarUpdatePath).replace(/\\/g, '\\\\') : ''}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${updateDir.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
writeFileSync(vbsPath, vbsContent);
spawn('wscript.exe', [vbsPath], {
detached: true,
stdio: 'ignore',
shell: false
});
spawn('wscript.exe', [vbsPath], {detached: true, stdio: 'ignore', shell: false});
setTimeout(() => app.quit(), 1000);
} catch (error: unknown) {
console.error('[UPDATE] 更新失败:', error);
}
}
ipcMain.handle('download-update', async (event, downloadUrls: {asarUrl?: string, jarUrl?: string}) => {
ipcMain.handle('download-update', async (event, downloadUrls: {asarUrl?: string, jarUrl?: string, latestVersion?: string}) => {
if (isDownloading) return {success: false, error: '正在下载中'};
if (downloadedFilePath === 'completed') return {success: true, filePath: 'already-completed'};
@@ -454,8 +445,9 @@ ipcMain.handle('download-update', async (event, downloadUrls: {asarUrl?: string,
combinedTotalSize = asarSize + jarSize;
if (downloadUrls.asarUrl && !currentDownloadAbortController.signal.aborted) {
const tempAsarPath = join(app.getPath('temp'), 'app.asar.new');
await downloadFile(downloadUrls.asarUrl, tempAsarPath, (progress) => {
const updateDir = getUpdateDirectoryPath();
const asarUpdatePath = join(updateDir, 'app.asar.update');
await downloadFile(downloadUrls.asarUrl, asarUpdatePath, (progress) => {
const combinedProgress = {
percentage: combinedTotalSize > 0 ? Math.round(((totalDownloaded + progress.downloaded) / combinedTotalSize) * 100) : 0,
current: `${((totalDownloaded + progress.downloaded) / 1024 / 1024).toFixed(1)} MB`,
@@ -468,30 +460,17 @@ ipcMain.handle('download-update', async (event, downloadUrls: {asarUrl?: string,
});
if (currentDownloadAbortController.signal.aborted) throw new Error('下载已取消');
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
await fs.copyFile(tempAsarPath, asarUpdatePath);
await fs.unlink(tempAsarPath);
downloadedAsarPath = asarUpdatePath;
totalDownloaded = asarSize;
}
if (downloadUrls.jarUrl && !currentDownloadAbortController.signal.aborted) {
let jarFileName = basename(downloadUrls.jarUrl);
if (!jarFileName.match(/^erp_client_sb-[\d.]+\.jar$/)) {
const currentJar = getJarFilePath();
const versionMatch = currentJar ? basename(currentJar).match(/erp_client_sb-([\d.]+)\.jar/) : null;
if (versionMatch && versionMatch[1]) {
const versionParts = versionMatch[1].split('.');
versionParts[2] = String(Number(versionParts[2]) + 1);
jarFileName = `erp_client_sb-${versionParts.join('.')}.jar`;
} else {
jarFileName = 'erp_client_sb-2.4.7.jar';
}
}
const tempJarPath = join(app.getPath('temp'), jarFileName);
await downloadFile(downloadUrls.jarUrl, tempJarPath, (progress) => {
const jarFileName = downloadUrls.latestVersion
? `erp_client_sb-${downloadUrls.latestVersion}.jar`
: basename(downloadUrls.jarUrl);
const updateDir = getUpdateDirectoryPath();
const jarUpdatePath = join(updateDir, jarFileName + '.update');
await downloadFile(downloadUrls.jarUrl, jarUpdatePath, (progress) => {
const combinedProgress = {
percentage: combinedTotalSize > 0 ? Math.round(((totalDownloaded + progress.downloaded) / combinedTotalSize) * 100) : 0,
current: `${((totalDownloaded + progress.downloaded) / 1024 / 1024).toFixed(1)} MB`,
@@ -504,10 +483,6 @@ ipcMain.handle('download-update', async (event, downloadUrls: {asarUrl?: string,
});
if (currentDownloadAbortController.signal.aborted) throw new Error('下载已取消');
const jarUpdatePath = join(process.resourcesPath, jarFileName + '.update');
await fs.copyFile(tempJarPath, jarUpdatePath);
await fs.unlink(tempJarPath);
downloadedJarPath = jarUpdatePath;
}
@@ -533,43 +508,28 @@ ipcMain.handle('get-download-progress', () => {
ipcMain.handle('install-update', async () => {
try {
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
const hasAsarUpdate = existsSync(asarUpdatePath);
// 查找jar更新文件
let jarUpdatePath = '';
if (process.resourcesPath && existsSync(process.resourcesPath)) {
const files = readdirSync(process.resourcesPath);
const jarUpdateFile = files.find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
if (jarUpdateFile) {
jarUpdatePath = join(process.resourcesPath, jarUpdateFile);
}
}
const updateDir = getUpdateDirectoryPath();
const asarUpdatePath = join(updateDir, 'app.asar.update');
const jarUpdateFile = readdirSync(updateDir).find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
const jarUpdatePath = jarUpdateFile ? join(updateDir, jarUpdateFile) : '';
if (!hasAsarUpdate && !jarUpdatePath) {
if (!existsSync(asarUpdatePath) && !jarUpdatePath) {
return {success: false, error: '更新文件不存在'};
}
const appDir = dirname(process.execPath);
const helperPath = join(appDir, 'update-helper.bat');
if (!existsSync(helperPath)) {
return {success: false, error: '更新助手不存在'};
}
const appAsarPath = join(process.resourcesPath, 'app.asar');
const vbsPath = join(app.getPath('temp'), 'update-install.vbs');
const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${asarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${jarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${asarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${jarUpdatePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${updateDir.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
writeFileSync(vbsPath, vbsContent);
spawn('wscript.exe', [vbsPath], {
detached: true,
stdio: 'ignore',
shell: false
});
spawn('wscript.exe', [vbsPath], {detached: true, stdio: 'ignore', shell: false});
setTimeout(() => {
downloadedFilePath = null;
@@ -608,31 +568,18 @@ ipcMain.handle('get-update-status', () => {
ipcMain.handle('check-pending-update', () => {
try {
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
const hasAsarUpdate = existsSync(asarUpdatePath);
// 查找jar更新文件
let jarUpdatePath = '';
if (process.resourcesPath && existsSync(process.resourcesPath)) {
const files = readdirSync(process.resourcesPath);
const jarUpdateFile = files.find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
if (jarUpdateFile) {
jarUpdatePath = join(process.resourcesPath, jarUpdateFile);
}
}
const updateDir = getUpdateDirectoryPath();
const asarUpdatePath = join(updateDir, 'app.asar.update');
const jarUpdateFile = readdirSync(updateDir).find(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
const jarUpdatePath = jarUpdateFile ? join(updateDir, jarUpdateFile) : '';
return {
hasPendingUpdate: hasAsarUpdate || !!jarUpdatePath,
asarUpdatePath: hasAsarUpdate ? asarUpdatePath : null,
hasPendingUpdate: existsSync(asarUpdatePath) || !!jarUpdatePath,
asarUpdatePath: existsSync(asarUpdatePath) ? asarUpdatePath : null,
jarUpdatePath: jarUpdatePath || null
};
} catch (error) {
console.error('检查待安装更新失败:', error);
return {
hasPendingUpdate: false,
asarUpdatePath: null,
jarUpdatePath: null
};
return {hasPendingUpdate: false, asarUpdatePath: null, jarUpdatePath: null};
}
});
@@ -655,24 +602,10 @@ ipcMain.handle('clear-update-files', async () => {
async function cleanupDownloadFiles() {
try {
const tempAsarPath = join(app.getPath('temp'), 'app.asar.new');
if (existsSync(tempAsarPath)) await fs.unlink(tempAsarPath).catch(() => {});
const asarUpdatePath = join(process.resourcesPath, 'app.asar.update');
if (existsSync(asarUpdatePath)) await fs.unlink(asarUpdatePath).catch(() => {});
if (process.resourcesPath && existsSync(process.resourcesPath)) {
const files = readdirSync(process.resourcesPath);
const jarUpdateFiles = files.filter(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar.update'));
for (const file of jarUpdateFiles) {
await fs.unlink(join(process.resourcesPath, file)).catch(() => {});
}
const tempJarFiles = files.filter(f => f.startsWith('erp_client_sb-') && f.endsWith('.jar') && !f.includes('update'));
for (const file of tempJarFiles) {
const tempJarPath = join(app.getPath('temp'), file);
if (existsSync(tempJarPath)) await fs.unlink(tempJarPath).catch(() => {});
}
const updateDir = getUpdateDirectoryPath();
const files = readdirSync(updateDir);
for (const file of files) {
await fs.unlink(join(updateDir, file)).catch(() => {});
}
} catch (error) {}
}
@@ -696,34 +629,23 @@ ipcMain.handle('write-file', async (event, filePath: string, data: Uint8Array) =
// 获取日志日期列表
ipcMain.handle('get-log-dates', async () => {
try {
const logDir = 'C:/ProgramData/erp-logs';
if (!existsSync(logDir)) {
return { dates: [] };
}
const logDir = getLogDirectoryPath();
const files = await fs.readdir(logDir);
const dates: string[] = [];
// 获取今天的日期YYYY-MM-DD格式
const today = new Date().toISOString().split('T')[0];
files.forEach(file => {
if (file === 'spring-boot.log') {
// 当天的日志文件,使用今天的日期
dates.push(today);
} else if (file.startsWith('spring-boot-') && file.endsWith('.log')) {
// 历史日志文件,提取日期
const date = file.replace('spring-boot-', '').replace('.log', '');
dates.push(date);
}
});
// 排序,最新的在前面
dates.sort().reverse();
return { dates };
} catch (error) {
console.error('获取日志日期列表失败:', error);
return { dates: [] };
}
});
@@ -731,12 +653,10 @@ ipcMain.handle('get-log-dates', async () => {
// 读取指定日期的日志文件
ipcMain.handle('read-log-file', async (event, logDate: string) => {
try {
const logDir = 'C:/ProgramData/erp-logs';
const logDir = getLogDirectoryPath();
const today = new Date().toISOString().split('T')[0];
// 如果是今天的日期,读取 spring-boot.log否则读取带日期的文件
const fileName = logDate === today ? 'spring-boot.log' : `spring-boot-${logDate}.log`;
const logFilePath = `${logDir}/${fileName}`;
const logFilePath = join(logDir, fileName);
if (!existsSync(logFilePath)) {
return { success: false, error: '日志文件不存在' };
@@ -745,7 +665,6 @@ ipcMain.handle('read-log-file', async (event, logDate: string) => {
const content = await fs.readFile(logFilePath, 'utf-8');
return { success: true, content };
} catch (error) {
console.error('读取日志文件失败:', error);
return { success: false, error: error instanceof Error ? error.message : '读取失败' };
}
});

View File

@@ -18,6 +18,7 @@ import ZebraDashboard from './components/zebra/ZebraDashboard.vue'
import UpdateDialog from './components/common/UpdateDialog.vue'
import SettingsDialog from './components/common/SettingsDialog.vue'
import TrialExpiredDialog from './components/common/TrialExpiredDialog.vue'
import AccountManager from './components/common/AccountManager.vue'
const dashboardsMap: Record<string, Component> = {
rakuten: RakutenDashboard,
@@ -56,15 +57,36 @@ const vipExpireTime = ref<Date | null>(null)
const deviceTrialExpired = ref(false)
const accountType = ref<string>('trial')
const vipStatus = computed(() => {
if (!vipExpireTime.value) return { isVip: false, daysLeft: 0, status: 'expired' }
if (!vipExpireTime.value) return { isVip: false, daysLeft: 0, hoursLeft: 0, status: 'expired', expiredType: 'account' }
const now = new Date()
const expire = new Date(vipExpireTime.value)
const daysLeft = Math.ceil((expire.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
const msLeft = expire.getTime() - now.getTime()
if (daysLeft <= 0) return { isVip: false, daysLeft: 0, status: 'expired' }
if (daysLeft <= 7) return { isVip: true, daysLeft, status: 'warning' }
if (daysLeft <= 30) return { isVip: true, daysLeft, status: 'normal' }
return { isVip: true, daysLeft, status: 'active' }
// 精确判断:当前时间 >= 过期时间,则已过期(与后端逻辑一致)
if (msLeft <= 0) {
const accountExpired = true
const deviceExpired = deviceTrialExpired.value
let expiredType: 'device' | 'account' | 'both' | 'subscribe' = 'account'
if (deviceExpired && accountExpired) expiredType = 'both'
else if (accountExpired) expiredType = 'account'
else if (deviceExpired) expiredType = 'device'
return { isVip: false, daysLeft: 0, hoursLeft: 0, status: 'expired', expiredType }
}
const hoursLeft = Math.floor(msLeft / (1000 * 60 * 60))
const daysLeft = Math.floor(msLeft / (1000 * 60 * 60 * 24))
let expiredType: 'device' | 'account' | 'both' | 'subscribe' = 'subscribe'
if (accountType.value === 'trial' && deviceTrialExpired.value) {
expiredType = 'device' // 试用账号且设备过期
}
if (daysLeft === 0) return { isVip: true, daysLeft, hoursLeft, status: 'warning', expiredType }
if (daysLeft <= 7) return { isVip: true, daysLeft, hoursLeft, status: 'warning', expiredType }
if (daysLeft <= 30) return { isVip: true, daysLeft, hoursLeft, status: 'normal', expiredType }
return { isVip: true, daysLeft, hoursLeft, status: 'active', expiredType }
})
// 功能可用性账号VIP + 设备试用期)
@@ -86,6 +108,12 @@ const showSettingsDialog = ref(false)
const showTrialExpiredDialog = ref(false)
const trialExpiredType = ref<'device' | 'account' | 'both' | 'subscribe'>('device')
// 账号管理对话框状态
const showAccountManager = ref(false)
// 当前版本
const currentVersion = ref('')
// 菜单配置 - 复刻ERP客户端格式
const menuConfig = [
{key: 'rakuten', name: 'Rakuten', index: 'rakuten', icon: 'R'},
@@ -185,30 +213,20 @@ async function handleLoginSuccess(data: { token: string; permissions?: string; e
os: navigator.platform
})
SSEManager.connect()
// 根据不同场景显示提示
const accountExpired = vipExpireTime.value && new Date() > vipExpireTime.value
const deviceExpired = deviceTrialExpired.value
const isPaid = accountType.value === 'paid'
if (deviceExpired && accountExpired) {
// 场景4: 试用已到期,请订阅
trialExpiredType.value = 'both'
showTrialExpiredDialog.value = true
} else if (accountExpired) {
// 场景3: 账号试用已到期,请订阅
trialExpiredType.value = 'account'
showTrialExpiredDialog.value = true
} else if (deviceExpired) {
// 场景2: 设备试用已到期,请更换设备或订阅
trialExpiredType.value = 'device'
// 同步当前账号的设置到 Electron 主进程
syncSettingsToElectron()
// 根据VIP状态显示对应提示
if (!vipStatus.value.isVip || deviceTrialExpired.value) {
trialExpiredType.value = vipStatus.value.expiredType
showTrialExpiredDialog.value = true
}
} catch (e: any) {
isAuthenticated.value = false
showAuthDialog.value = true
removeToken()
ElMessage.error(e?.message || '设备注册失败')
}
}
@@ -228,7 +246,7 @@ function clearLocalAuth() {
async function logout() {
try {
const deviceId = getClientIdFromToken()
if (deviceId) await deviceApi.remove({ deviceId, username: currentUsername.value })
if (deviceId) await deviceApi.offline({ deviceId, username: currentUsername.value })
} catch (error) {
console.warn('离线通知失败:', error)
}
@@ -283,6 +301,9 @@ async function checkAuth() {
}
SSEManager.connect()
// 同步当前账号的设置到 Electron 主进程
syncSettingsToElectron()
} catch {
removeToken()
if (['rakuten', 'amazon', 'zebra', 'shopee'].includes(activeMenu.value)) {
@@ -309,31 +330,34 @@ async function refreshVipStatus() {
}
}
// 判断过期类型
function checkExpiredType(): 'device' | 'account' | 'both' | 'subscribe' {
const accountExpired = vipExpireTime.value && new Date() > vipExpireTime.value
const deviceExpired = deviceTrialExpired.value
if (deviceExpired && accountExpired) return 'both'
if (accountExpired) return 'account'
if (deviceExpired) return 'device'
return 'account' // 默认
}
// 打开订阅对话框
function openSubscriptionDialog() {
// 如果VIP有效显示订阅/续费提示;如果已过期,显示过期提示
if (vipStatus.value.isVip) {
trialExpiredType.value = 'subscribe'
} else {
trialExpiredType.value = checkExpiredType()
}
trialExpiredType.value = vipStatus.value.expiredType
showTrialExpiredDialog.value = true
}
// 同步设置到 Electron 主进程
async function syncSettingsToElectron() {
try {
const username = getUsernameFromToken()
const settings = getSettings(username)
// 同步关闭行为
await (window as any).electronAPI.setCloseAction(settings.closeAction || 'quit')
// 同步启动配置
await (window as any).electronAPI.setLaunchConfig({
autoLaunch: settings.autoLaunch || false,
launchMinimized: settings.launchMinimized || false
})
} catch (error) {
console.warn('同步设置到主进程失败:', error)
}
}
// 提供给子组件使用
provide('refreshVipStatus', refreshVipStatus)
provide('checkExpiredType', checkExpiredType)
provide('vipStatus', vipStatus)
const SSEManager = {
connection: null as EventSource | null,
@@ -427,6 +451,20 @@ function openSettings() {
showSettingsDialog.value = true
}
function openAccountManager() {
if (!isAuthenticated.value) {
showAuthDialog.value = true
return
}
showAccountManager.value = true
}
async function handleCheckUpdate() {
if (updateDialogRef.value) {
await updateDialogRef.value.checkForUpdatesNow()
}
}
async function fetchDeviceData() {
if (!currentUsername.value) {
ElMessage.warning('未获取到用户名,请重新登录')
@@ -479,6 +517,13 @@ onMounted(async () => {
// 检查是否有待安装的更新
await checkPendingUpdate()
// 加载当前版本
try {
currentVersion.value = await (window as any).electronAPI.getJarVersion()
} catch (error) {
console.warn('获取当前版本失败:', error)
}
// 全局阻止文件拖拽到窗口(避免意外打开文件)
// 只在指定的 dropzone 区域处理拖拽上传
document.addEventListener('dragover', (e) => {
@@ -557,9 +602,12 @@ onUnmounted(() => {
<span v-if="vipStatus.status === 'warning'">即将到期</span>
<span v-else>订阅中</span>
</template>
<template v-else>
<span>已过期</span>
</template>
</div>
<div class="vip-expire-date" v-if="vipExpireTime">
有效期至{{ vipExpireTime ? new Date(vipExpireTime).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' }) : '-' }}
有效期至{{ new Date(vipExpireTime).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' }) }}
</div>
</div>
</div>
@@ -571,12 +619,17 @@ onUnmounted(() => {
:can-go-back="canGoBack"
:can-go-forward="canGoForward"
:active-menu="activeMenu"
:is-authenticated="isAuthenticated"
:current-username="currentUsername"
:current-version="currentVersion"
@go-back="goBack"
@go-forward="goForward"
@reload="reloadPage"
@user-click="handleUserClick"
@logout="handleUserClick"
@open-device="openDeviceManager"
@open-settings="openSettings"/>
@open-settings="openSettings"
@open-account-manager="openAccountManager"
@check-update="handleCheckUpdate"/>
<div class="content-body">
<div
class="dashboard-home"
@@ -617,6 +670,9 @@ onUnmounted(() => {
<!-- 试用期过期弹框 -->
<TrialExpiredDialog v-model="showTrialExpiredDialog" :expired-type="trialExpiredType" />
<!-- 账号管理弹框 -->
<AccountManager v-model="showAccountManager" platform="zebra" />
<!-- 设备管理弹框 -->
<el-dialog
v-model="showDeviceDialog"

View File

@@ -4,6 +4,7 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import { amazonApi } from '../../api/amazon'
import { systemApi } from '../../api/system'
import { handlePlatformFileExport } from '../../utils/settings'
import { getUsernameFromToken } from '../../utils/token'
import { useFileDrop } from '../../composables/useFileDrop'
const TrialExpiredDialog = defineAsyncComponent(() => import('../common/TrialExpiredDialog.vue'))
@@ -34,7 +35,7 @@ const amazonUpload = ref<HTMLInputElement | null>(null)
const showTrialExpiredDialog = ref(false)
const trialExpiredType = ref<'device' | 'account' | 'both' | 'subscribe'>('account')
const checkExpiredType = inject<() => 'device' | 'account' | 'both' | 'subscribe'>('checkExpiredType')
const vipStatus = inject<any>('vipStatus')
// 计算属性 - 当前页数据
const paginatedData = computed(() => {
@@ -51,6 +52,7 @@ const regionOptions = [
{ label: '美国 (USA)', value: 'US', flag: '🇺🇸' },
]
const pendingAsins = ref<string[]>([])
const selectedFileName = ref('')
// 通用消息提示Element Plus
function showMessage(message: string, type: 'success' | 'warning' | 'error' | 'info' = 'info') {
@@ -73,6 +75,7 @@ async function processExcelFile(file: File) {
return
}
pendingAsins.value = asinList
selectedFileName.value = file.name
} catch (error: any) {
showMessage(error.message || '处理文件失败', 'error')
} finally {
@@ -102,7 +105,7 @@ async function batchGetProductInfo(asinList: string[]) {
// VIP检查
if (!props.isVip) {
if (checkExpiredType) trialExpiredType.value = checkExpiredType()
if (vipStatus) trialExpiredType.value = vipStatus.value.expiredType
showTrialExpiredDialog.value = true
return
}
@@ -158,6 +161,7 @@ async function batchGetProductInfo(asinList: string[]) {
// 处理完成状态更新
progressPercentage.value = 100
currentAsin.value = '处理完成'
selectedFileName.value = ''
@@ -165,6 +169,7 @@ async function batchGetProductInfo(asinList: string[]) {
if (error.name !== 'AbortError') {
showMessage(error.message || '批量获取产品信息失败', 'error')
currentAsin.value = '处理失败'
selectedFileName.value = ''
}
} finally {
tableLoading.value = false
@@ -217,7 +222,8 @@ async function exportToExcel() {
const blob = new Blob([html], { type: 'application/vnd.ms-excel' })
const fileName = `Amazon产品数据_${new Date().toISOString().slice(0, 10)}.xls`
const success = await handlePlatformFileExport('amazon', blob, fileName)
const username = getUsernameFromToken()
const success = await handlePlatformFileExport('amazon', blob, fileName, username)
if (success) {
showMessage('Excel文件导出成功', 'success')
@@ -246,6 +252,7 @@ function stopFetch() {
abortController = null
loading.value = false
currentAsin.value = '已停止'
selectedFileName.value = ''
showMessage('已停止获取产品数据', 'info')
}
@@ -326,9 +333,10 @@ onMounted(async () => {
<span class="tab-icon">📦</span>
<span class="tab-text">ASIN查询</span>
</div>
<div class="tab-item" @click="openGenmaiSpirit">
<span class="tab-icon">🔍</span>
<span class="tab-text">跟卖精灵</span>
<div class="tab-item" :class="{ loading: genmaiLoading }" @click="!genmaiLoading && openGenmaiSpirit()">
<span class="tab-icon" v-if="!genmaiLoading">🔍</span>
<span class="tab-icon spinner-icon" v-else></span>
<span class="tab-text">{{ genmaiLoading ? '启动中...' : '跟卖精灵' }}</span>
</div>
</div>
<div class="steps-title">操作流程</div>
@@ -350,6 +358,10 @@ onMounted(async () => {
<div class="dz-sub">支持 .xls .xlsx</div>
</div>
<input ref="amazonUpload" style="display:none" type="file" accept=".xls,.xlsx" @change="handleExcelUpload" :disabled="loading" />
<div v-if="selectedFileName" class="file-chip">
<span class="dot"></span>
<span class="name">{{ selectedFileName }}</span>
</div>
</div>
</div>
<!-- 2 网站地区 -->
@@ -375,7 +387,6 @@ onMounted(async () => {
<el-button size="small" class="w100 btn-blue" :disabled="!pendingAsins.length || loading" @click="startQueuedFetch">{{ loading ? '处理中...' : '获取数据' }}</el-button>
<el-button size="small" class="w100" :disabled="!loading" @click="stopFetch">停止获取</el-button>
</div>
<div class="mini-hint" v-if="pendingAsins.length">已导入 {{ pendingAsins.length }} ASIN</div>
</div>
</div>
<!-- 4 -->
@@ -462,9 +473,8 @@ onMounted(async () => {
</div>
</div>
</div>
<div class="pagination-fixed" >
<div class="pagination-fixed">
<el-pagination
background
:current-page="currentPage"
:page-sizes="[15,30,50,100]"
:page-size="pageSize"
@@ -492,7 +502,9 @@ onMounted(async () => {
.tab-item:last-child { border-radius: 0 3px 3px 0; border-left: none; }
.tab-item:hover { background: #e8f4ff; color: #409EFF; }
.tab-item.active { background: #1677FF; color: #fff; border-color: #1677FF; cursor: default; }
.tab-item.loading { background: #e8f4ff; color: #409EFF; cursor: not-allowed; opacity: 0.8; }
.tab-icon { font-size: 12px; }
.spinner-icon { animation: spin 1s linear infinite; display: inline-block; }
.tab-text { line-height: 1; }
.body-layout { display: flex; gap: 12px; flex: 1; overflow: hidden; }
@@ -501,7 +513,6 @@ onMounted(async () => {
.steps-flow { position: relative; }
.steps-flow:before { content: ''; position: absolute; left: 11px; top: 20px; bottom: 0; width: 1px; background: rgba(229, 231, 235, 0.6); }
.flow-item { position: relative; display: grid; grid-template-columns: 22px 1fr; gap: 10px; padding: 8px 0; }
.flow-item + .flow-item { border-top: 1px dashed #ebeef5; }
.flow-item .step-index { position: static; width: 22px; height: 22px; line-height: 22px; text-align: center; border-radius: 50%; background: #1677FF; color: #fff; font-size: 12px; font-weight: 600; margin-top: 2px; }
.flow-item:after { display: none; }
.step-card { border: none; border-radius: 0; padding: 0; background: transparent; }
@@ -520,6 +531,9 @@ onMounted(async () => {
.dz-icon { font-size: 20px; margin-bottom: 6px; }
.dz-text { color: #303133; font-size: 13px; }
.dz-sub { color: #909399; font-size: 12px; }
.file-chip { display: flex; align-items: center; gap: 6px; padding: 6px 8px; background: #f5f7fa; border-radius: 4px; font-size: 12px; color: #606266; margin-top: 6px; }
.file-chip .dot { width: 6px; height: 6px; background: #409EFF; border-radius: 50%; display: inline-block; }
.file-chip .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.single-input.left { display: flex; gap: 8px; }
.action-buttons.column { display: flex; flex-direction: column; gap: 8px; }
.form-row { margin-bottom: 10px; }
@@ -573,7 +587,8 @@ onMounted(async () => {
.table-loading { position: absolute; inset: 0; background: rgba(255, 255, 255, 0.95); display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 14px; color: #606266; }
.spinner { font-size: 24px; animation: spin 1s linear infinite; margin-bottom: 8px; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.pagination-fixed { flex-shrink: 0; padding: 8px 12px; background: #f9f9f9; border-radius: 4px; display: flex; justify-content: center; border-top: 1px solid #ebeef5; margin-top: 8px; }
.pagination-fixed { flex-shrink: 0; padding: 8px 12px; background: #fff; display: flex; justify-content: flex-end; margin-top: 8px; }
.pagination-fixed :deep(.el-pager li.is-active) { border: 1px solid #1677FF; border-radius: 4px; color: #1677FF; background: #fff; }
.empty-tip { text-align: center; color: #909399; padding: 16px 0; }
.import-section[draggable], .import-section.drag-active { border: 1px dashed #409EFF; border-radius: 6px; }
.empty-container { text-align: center; }

View File

@@ -110,6 +110,7 @@ function showRegister() {
size="large"
style="margin-bottom: 20px;"
:disabled="authLoading"
show-password
@keyup.enter="handleAuth">
</el-input>

View File

@@ -150,7 +150,8 @@ function backToLogin() {
type="password"
size="large"
style="margin-bottom: 15px;"
:disabled="registerLoading">
:disabled="registerLoading"
show-password>
</el-input>
<el-input
@@ -159,7 +160,8 @@ function backToLogin() {
type="password"
size="large"
style="margin-bottom: 20px;"
:disabled="registerLoading">
:disabled="registerLoading"
show-password>
</el-input>
<div>

View File

@@ -3,9 +3,7 @@ import { ref, onMounted, computed } from 'vue'
import { zebraApi, type BanmaAccount } from '../../api/zebra'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getUsernameFromToken } from '../../utils/token'
type PlatformKey = 'zebra' | 'shopee' | 'rakuten' | 'amazon'
const props = defineProps<{ modelValue: boolean; platform?: PlatformKey }>()
const emit = defineEmits(['update:modelValue', 'add', 'refresh'])
const visible = computed({ get: () => props.modelValue, set: v => emit('update:modelValue', v) })

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
getSettings,
@@ -73,6 +73,14 @@ const show = computed({
set: (value) => emit('update:modelValue', value)
})
// 监听对话框打开,重新加载当前用户的设置
watch(() => props.modelValue, (newVal) => {
if (newVal) {
loadAllSettings()
loadCurrentVersion()
}
})
// 选择导出路径
async function selectExportPath(platform: Platform) {
const result = await (window as any).electronAPI.showOpenDialog({
@@ -88,22 +96,21 @@ async function selectExportPath(platform: Platform) {
// 保存设置
async function saveAllSettings() {
Object.keys(platformSettings.value).forEach(platformKey => {
const platform = platformKey as Platform
const platformConfig = platformSettings.value[platform]
savePlatformSettings(platform, platformConfig)
})
// 保存自动更新配置
const oldSettings = getSettings()
const username = getUsernameFromToken()
const oldSettings = getSettings(username)
const autoUpdateChanged = oldSettings.autoUpdate !== autoUpdate.value
saveSettings({ autoUpdate: autoUpdate.value })
// 1. 保存到 localStorage按账号隔离
saveSettings({
platforms: platformSettings.value,
autoUpdate: autoUpdate.value,
closeAction: closeAction.value,
autoLaunch: autoLaunch.value,
launchMinimized: launchMinimized.value
}, username)
// 保存关闭行为配置
// 2. 同步到 Electron 主进程(控制应用行为)
await (window as any).electronAPI.setCloseAction(closeAction.value)
// 保存启动配置
await (window as any).electronAPI.setLaunchConfig({
autoLaunch: autoLaunch.value,
launchMinimized: launchMinimized.value
@@ -112,7 +119,6 @@ async function saveAllSettings() {
ElMessage({ message: '设置已保存', type: 'success' })
show.value = false
// 如果自动更新配置改变了,通知父组件
if (autoUpdateChanged) {
emit('autoUpdateChanged', autoUpdate.value)
}
@@ -120,13 +126,17 @@ async function saveAllSettings() {
// 加载设置
function loadAllSettings() {
const settings = getSettings()
const username = getUsernameFromToken()
const settings = getSettings(username)
platformSettings.value = {
amazon: { ...settings.platforms.amazon },
rakuten: { ...settings.platforms.rakuten },
zebra: { ...settings.platforms.zebra }
}
autoUpdate.value = settings.autoUpdate ?? false
closeAction.value = settings.closeAction ?? 'quit'
autoLaunch.value = settings.autoLaunch ?? false
launchMinimized.value = settings.launchMinimized ?? false
}
// 重置单个平台设置
@@ -149,20 +159,15 @@ async function resetAllSettings() {
}
)
// 重置所有平台设置
platforms.forEach(platform => {
resetPlatformSettings(platform.key)
})
// 重置自动更新配置
autoUpdate.value = false
// 重置关闭行为配置
closeAction.value = 'quit'
// 重置启动配置
autoLaunch.value = false
launchMinimized.value = false
ElMessage.success('所有设置已重置')
} catch {
// 用户取消操作
@@ -208,19 +213,6 @@ async function handleClearCache() {
}
}
// 加载启动配置
async function loadLaunchConfig() {
try {
const config = await (window as any).electronAPI.getLaunchConfig()
if (config) {
autoLaunch.value = config.autoLaunch || false
launchMinimized.value = config.launchMinimized || false
}
} catch (error) {
console.warn('获取启动配置失败:', error)
}
}
// 滚动到指定区域
function scrollToSection(sectionKey: string) {
if (isScrolling.value) return
@@ -277,16 +269,6 @@ async function loadLogDates() {
}
}
// 加载关闭行为配置
async function loadCloseAction() {
try {
const action = await (window as any).electronAPI.getCloseAction()
if (action) closeAction.value = action
} catch (error) {
console.warn('获取关闭行为配置失败:', error)
}
}
// 检查更新
async function checkForUpdates() {
try {
@@ -382,9 +364,7 @@ async function submitFeedback() {
onMounted(() => {
loadAllSettings()
loadLogDates()
loadCloseAction()
loadCurrentVersion()
loadLaunchConfig()
})
</script>

View File

@@ -1,9 +1,5 @@
<template>
<div>
<div class="version-info" @click="handleVersionClick">
v{{ version || '-' }}
<span v-if="hasNewVersion" class="update-badge"></span>
</div>
<el-dialog v-model="show" width="522px" :close-on-click-modal="false" align-center
:class="['update-dialog', `stage-${stage}`]"
:title="stage === 'downloading' ? `正在更新 ${appName}` : '软件更新'">
@@ -101,16 +97,12 @@ import {ref, computed, onMounted, onUnmounted, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {updateApi} from '../../api/update'
import {getSettings} from '../../utils/settings'
import {getUsernameFromToken} from '../../utils/token'
const props = defineProps<{
modelValue: boolean
}>()
const props = defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()
// 暴露方法给父组件调用
defineExpose({
checkForUpdatesNow
})
defineExpose({ checkForUpdatesNow })
const show = computed({
get: () => props.modelValue,
@@ -121,54 +113,40 @@ type Stage = 'check' | 'downloading' | 'completed'
const stage = ref<Stage>('check')
const appName = ref('我了个电商')
const version = ref('')
const hasNewVersion = ref(false) // 控制小红点显示
const prog = ref({percentage: 0, current: '0 MB', total: '0 MB'})
const info = ref({
latestVersion: '2.4.8',
downloadUrl: '',
latestVersion: '',
asarUrl: '',
jarUrl: '',
updateNotes: '',
currentVersion: '',
hasUpdate: false
currentVersion: ''
})
const SKIP_VERSION_KEY = 'skipped_version'
const REMIND_LATER_KEY = 'remind_later_time'
async function autoCheck(silent = false) {
async function checkUpdate(silent = false) {
try {
version.value = await (window as any).electronAPI.getJarVersion()
const checkRes: any = await updateApi.checkUpdate(version.value)
const result = checkRes?.data || checkRes
const result = (await updateApi.checkUpdate(version.value))?.data
info.value = {
currentVersion: result.currentVersion || version.value,
latestVersion: result.latestVersion || version.value,
asarUrl: result.asarUrl || '',
jarUrl: result.jarUrl || '',
updateNotes: result.updateNotes || ''
}
if (!result.needUpdate) {
hasNewVersion.value = false
if (!silent) ElMessage.info('当前已是最新版本')
return
}
if (localStorage.getItem('skipped_version') === result.latestVersion) return
// 发现新版本,更新信息并显示小红点
info.value = {
currentVersion: result.currentVersion,
latestVersion: result.latestVersion,
downloadUrl: result.downloadUrl || '',
asarUrl: result.asarUrl || '',
jarUrl: result.jarUrl || '',
updateNotes: result.updateNotes || '',
hasUpdate: true
}
hasNewVersion.value = true
const remindTime = localStorage.getItem('remind_later_time')
if (remindTime && Date.now() < parseInt(remindTime)) return
const skippedVersion = localStorage.getItem(SKIP_VERSION_KEY)
if (skippedVersion === result.latestVersion) return
const remindLater = localStorage.getItem(REMIND_LATER_KEY)
if (remindLater && Date.now() < parseInt(remindLater)) return
const settings = getSettings()
if (settings.autoUpdate) {
await startAutoDownload()
if (getSettings(getUsernameFromToken()).autoUpdate) {
await downloadUpdate()
return
}
@@ -180,95 +158,40 @@ async function autoCheck(silent = false) {
}
}
function handleVersionClick() {
async function checkForUpdatesNow() {
if (stage.value === 'downloading' || stage.value === 'completed') {
show.value = true
return
}
if (hasNewVersion.value) {
stage.value = 'check'
show.value = true
} else {
checkForUpdatesNow()
}
}
// 立即检查更新(供外部调用)
async function checkForUpdatesNow() {
await autoCheck(false)
await checkUpdate(false)
}
function skipVersion() {
localStorage.setItem(SKIP_VERSION_KEY, info.value.latestVersion)
localStorage.setItem('skipped_version', info.value.latestVersion)
show.value = false
}
function remindLater() {
// 24小时后再提醒
localStorage.setItem(REMIND_LATER_KEY, (Date.now() + 24 * 60 * 60 * 1000).toString())
localStorage.setItem('remind_later_time', (Date.now() + 24 * 60 * 60 * 1000).toString())
show.value = false
}
async function start() {
// 如果已经在下载或已完成,不重复执行
if (stage.value === 'downloading') {
if (stage.value !== 'check') {
show.value = true
return
}
if (stage.value === 'completed') {
show.value = true
return
}
if (!info.value.asarUrl && !info.value.jarUrl) {
ElMessage.error('下载链接不可用')
return
}
stage.value = 'downloading'
show.value = true
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
// 设置新的进度监听器(会自动清理旧的)
;(window as any).electronAPI.onDownloadProgress((progress: any) => {
prog.value = {
percentage: progress.percentage || 0,
current: progress.current || '0 MB',
total: progress.total || '0 MB'
}
})
try {
const response = await (window as any).electronAPI.downloadUpdate({
asarUrl: info.value.asarUrl,
jarUrl: info.value.jarUrl
})
if (response.success) {
stage.value = 'completed'
prog.value.percentage = 100
ElMessage.success('下载完成')
show.value = true
} else {
ElMessage.error('下载失败: ' + (response.error || '未知错误'))
stage.value = 'check'
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
;(window as any).electronAPI.removeDownloadProgressListener()
}
} catch (error) {
ElMessage.error('下载失败')
stage.value = 'check'
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
;(window as any).electronAPI.removeDownloadProgressListener()
}
await downloadUpdate(true)
}
async function startAutoDownload() {
if (!info.value.asarUrl && !info.value.jarUrl) return
async function downloadUpdate(showDialog = false) {
if (!info.value.asarUrl && !info.value.jarUrl) {
if (showDialog) ElMessage.error('下载链接不可用')
return
}
stage.value = 'downloading'
if (showDialog) show.value = true
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
;(window as any).electronAPI.onDownloadProgress((progress: any) => {
@@ -282,54 +205,45 @@ async function startAutoDownload() {
try {
const response = await (window as any).electronAPI.downloadUpdate({
asarUrl: info.value.asarUrl,
jarUrl: info.value.jarUrl
jarUrl: info.value.jarUrl,
latestVersion: info.value.latestVersion
})
if (response.success) {
stage.value = 'completed'
prog.value.percentage = 100
show.value = true
ElMessage.success('更新已下载完成,可以安装了')
ElMessage.success(showDialog ? '下载完成' : '更新已下载完成,可以安装了')
} else {
stage.value = 'check'
if (showDialog) ElMessage.error('下载失败: ' + (response.error || '未知错误'))
;(window as any).electronAPI.removeDownloadProgressListener()
}
} catch (error) {
stage.value = 'check'
if (showDialog) ElMessage.error('下载失败')
;(window as any).electronAPI.removeDownloadProgressListener()
}
}
async function cancelDownload() {
try {
;(window as any).electronAPI.removeDownloadProgressListener()
await (window as any).electronAPI.cancelDownload()
stage.value = 'check'
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
hasNewVersion.value = false
show.value = false
ElMessage.info('已取消下载')
} catch (error) {
stage.value = 'check'
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
hasNewVersion.value = false
show.value = false
}
;(window as any).electronAPI.removeDownloadProgressListener()
await (window as any).electronAPI.cancelDownload().catch(() => {})
stage.value = 'check'
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
show.value = false
ElMessage.info('已取消下载')
}
async function installUpdate() {
try {
await ElMessageBox.confirm(
'安装过程中程序将自动重启,请确保已保存所有工作。确定要立即安装更新吗?',
'确认安装',
{
confirmButtonText: '立即安装',
cancelButtonText: '取消',
type: 'warning'
}
)
await ElMessageBox.confirm('安装过程中程序将自动重启,请确保已保存所有工作。确定要立即安装更新吗?', '确认安装', {
confirmButtonText: '立即安装',
cancelButtonText: '取消',
type: 'warning'
})
const response = await (window as any).electronAPI.installUpdate()
if (response.success) {
ElMessage.success('应用即将重启')
@@ -342,25 +256,19 @@ async function installUpdate() {
async function clearDownloadedFiles() {
try {
await ElMessageBox.confirm(
'确定要清除已下载的更新文件吗?清除后需要重新下载。',
'确认清除',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}
)
await ElMessageBox.confirm('确定要清除已下载的更新文件吗?清除后需要重新下载。', '确认清除', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
const response = await (window as any).electronAPI.clearUpdateFiles()
if (response.success) {
ElMessage.success('已清除下载文件')
// 重置状态
stage.value = 'check'
prog.value = {percentage: 0, current: '0 MB', total: '0 MB'}
hasNewVersion.value = false
show.value = false
ElMessage.success('已清除下载文件')
} else {
ElMessage.error('清除失败: ' + (response.error || '未知错误'))
}
@@ -373,13 +281,13 @@ onMounted(async () => {
version.value = await (window as any).electronAPI.getJarVersion()
const pendingUpdate = await (window as any).electronAPI.checkPendingUpdate()
if (pendingUpdate && pendingUpdate.hasPendingUpdate) {
if (pendingUpdate?.hasPendingUpdate) {
stage.value = 'completed'
prog.value.percentage = 100
return
}
await autoCheck(true)
await checkUpdate(true)
})
onUnmounted(() => {
@@ -390,45 +298,6 @@ onUnmounted(() => {
</script>
<style scoped>
.version-info {
position: fixed;
right: 10px;
bottom: 10px;
background: rgba(255, 255, 255, 0.9);
padding: 5px 10px;
border-radius: 4px;
font-size: 12px;
color: #909399;
z-index: 1000;
cursor: pointer;
user-select: none;
transition: all 0.3s ease;
}
.update-badge {
position: absolute;
top: -2px;
right: -2px;
width: 8px;
height: 8px;
background: #f56c6c;
border-radius: 50%;
border: 2px solid #fff;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.1);
opacity: 0.8;
}
}
:deep(.update-dialog .el-dialog) {
border-radius: 16px;
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15);

View File

@@ -1,23 +1,53 @@
<script setup lang="ts">
import { ArrowLeft, ArrowRight, Refresh, Monitor, Setting, User } from '@element-plus/icons-vue'
import { computed } from 'vue'
import { ArrowLeft, ArrowRight, Refresh, Setting } from '@element-plus/icons-vue'
interface Props {
canGoBack: boolean
canGoForward: boolean
activeMenu: string
isAuthenticated: boolean
currentUsername: string
currentVersion: string
}
interface Emits {
(e: 'go-back'): void
(e: 'go-forward'): void
(e: 'reload'): void
(e: 'user-click'): void
(e: 'logout'): void
(e: 'open-device'): void
(e: 'open-settings'): void
(e: 'open-account-manager'): void
(e: 'check-update'): void
}
defineProps<Props>()
defineEmits<Emits>()
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const displayUsername = computed(() => {
return props.isAuthenticated ? props.currentUsername : '未登录'
})
function handleCommand(command: string) {
switch (command) {
case 'logout':
emit('logout')
break
case 'device':
emit('open-device')
break
case 'settings':
emit('open-settings')
break
case 'account-manager':
emit('open-account-manager')
break
case 'check-update':
emit('check-update')
break
}
}
</script>
<template>
@@ -43,15 +73,35 @@ defineEmits<Emits>()
<button class="nav-btn-round" title="刷新" @click="$emit('reload')">
<el-icon><Refresh /></el-icon>
</button>
<button class="nav-btn-round" title="设备管理" @click="$emit('open-device')">
<el-icon><Monitor /></el-icon>
</button>
<button class="nav-btn-round" title="设置" @click="$emit('open-settings')">
<el-icon><Setting /></el-icon>
</button>
<button class="nav-btn-round" title="用户" @click="$emit('user-click')">
<el-icon><User /></el-icon>
</button>
<!-- 设置下拉菜单 -->
<el-dropdown trigger="click" @command="handleCommand" placement="bottom-end">
<button class="nav-btn-round" title="设置">
<el-icon><Setting /></el-icon>
</button>
<template #dropdown>
<el-dropdown-menu class="settings-dropdown">
<el-dropdown-item disabled class="username-item">
{{ displayUsername }}
</el-dropdown-item>
<el-dropdown-item command="check-update" class="menu-item">
检查更新 v{{ currentVersion }}
</el-dropdown-item>
<el-dropdown-item command="account-manager" class="menu-item">
我的电商账号
</el-dropdown-item>
<el-dropdown-item command="device" class="menu-item">
我的设备
</el-dropdown-item>
<el-dropdown-item command="settings" class="menu-item">
设置
</el-dropdown-item>
<el-dropdown-item v-if="isAuthenticated" command="logout" class="menu-item logout-item">
退出
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
</div>
</template>
@@ -170,4 +220,49 @@ defineEmits<Emits>()
color: #c0c4cc;
font-size: 12px;
}
</style>
<style>
/* 设置下拉菜单样式 */
.settings-dropdown {
min-width: 180px !important;
padding: 4px 0 !important;
border-radius: 12px !important;
margin-top: 4px !important;
margin-right: 8px !important;
}
.settings-dropdown .username-item {
font-weight: 600 !important;
color: #000000 !important;
cursor: default !important;
padding: 8px 16px !important;
font-size: 14px !important;
}
.settings-dropdown .menu-item {
padding: 8px 16px !important;
font-size: 13px !important;
color: #000000 !important;
transition: all 0.2s ease !important;
}
.settings-dropdown .menu-item:hover {
background: #f5f7fa !important;
color: #409EFF !important;
}
.settings-dropdown .logout-item {
color: #000000 !important;
}
.settings-dropdown .logout-item:hover {
background: #f5f7fa !important;
color: #409EFF !important;
}
.settings-dropdown .el-dropdown-menu__item.is-disabled {
cursor: default !important;
opacity: 1 !important;
}
</style>

View File

@@ -4,6 +4,7 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import {rakutenApi} from '../../api/rakuten'
import { batchConvertImages } from '../../utils/imageProxy'
import { handlePlatformFileExport } from '../../utils/settings'
import { getUsernameFromToken } from '../../utils/token'
import { useFileDrop } from '../../composables/useFileDrop'
const TrialExpiredDialog = defineAsyncComponent(() => import('../common/TrialExpiredDialog.vue'))
@@ -58,7 +59,7 @@ const activeStep = computed(() => {
const showTrialExpiredDialog = ref(false)
const trialExpiredType = ref<'device' | 'account' | 'both' | 'subscribe'>('account')
const checkExpiredType = inject<() => 'device' | 'account' | 'both' | 'subscribe'>('checkExpiredType')
const vipStatus = inject<any>('vipStatus')
// 左侧:上传文件名与地区
const selectedFileName = ref('')
@@ -150,7 +151,7 @@ async function searchProductInternal(product: any) {
if (!product || !product.imgUrl) return false
if (!needsSearch(product)) return true
if (!props.isVip) {
if (checkExpiredType) trialExpiredType.value = checkExpiredType()
if (vipStatus) trialExpiredType.value = vipStatus.value.expiredType
showTrialExpiredDialog.value = true
return false
}
@@ -238,7 +239,7 @@ async function handleStartSearch() {
// VIP检查
if (!props.isVip) {
if (checkExpiredType) trialExpiredType.value = checkExpiredType()
if (vipStatus) trialExpiredType.value = vipStatus.value.expiredType
showTrialExpiredDialog.value = true
return
}
@@ -265,10 +266,14 @@ async function handleStartSearch() {
allProducts.value = products
pendingFile.value = null
selectedFileName.value = ''
} catch (e: any) {
if (e.name !== 'AbortError') {
statusType.value = 'error'
statusMessage.value = '解析失败,请重试'
// 失败后清空文件信息,让用户重新上传
pendingFile.value = null
selectedFileName.value = ''
}
} finally {
loading.value = false
@@ -304,6 +309,9 @@ function stopTask() {
statusMessage.value = '任务已停止'
// 保留进度条和当前进度
allProducts.value = allProducts.value.map(p => ({...p, searching1688: false}))
// 清空文件信息,让用户重新上传
pendingFile.value = null
selectedFileName.value = ''
}
async function startBatch1688Search(products: any[]) {
@@ -434,7 +442,8 @@ async function exportToExcel() {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const fileName = `乐天商品数据_${new Date().toISOString().slice(0, 10)}.xlsx`
const success = await handlePlatformFileExport('rakuten', blob, fileName)
const username = getUsernameFromToken()
const success = await handlePlatformFileExport('rakuten', blob, fileName, username)
if (success) {
showMessage('Excel文件导出成功', 'success')
}
@@ -620,9 +629,8 @@ onMounted(loadLatest)
</div>
</div>
<div class="pagination-fixed" >
<div class="pagination-fixed">
<el-pagination
background
:current-page="currentPage"
:page-sizes="[15,30,50,100]"
:page-size="pageSize"
@@ -666,7 +674,6 @@ onMounted(loadLatest)
.steps-flow { position: relative; }
.steps-flow:before { content: ''; position: absolute; left: 11px; top: 20px; bottom: 0; width: 1px; background: rgba(229, 231, 235, 0.6); }
.flow-item { position: relative; display: grid; grid-template-columns: 22px 1fr; gap: 10px; padding: 8px 0; }
.flow-item + .flow-item { border-top: 1px dashed #ebeef5; }
.flow-item .step-index { position: static; width: 22px; height: 22px; line-height: 22px; text-align: center; border-radius: 50%; background: #1677FF; color: #fff; font-size: 12px; font-weight: 600; margin-top: 2px; }
.flow-item:after { display: none; }
.step-card { border: none; border-radius: 0; padding: 0; background: transparent; }
@@ -853,14 +860,19 @@ onMounted(loadLatest)
.pagination-fixed {
flex-shrink: 0;
padding: 8px 12px;
background: #f9f9f9;
border-radius: 4px;
background: #fff;
display: flex;
justify-content: center;
border-top: 1px solid #ebeef5;
justify-content: flex-end;
margin-top: 8px;
}
.pagination-fixed :deep(.el-pager li.is-active) {
border: 1px solid #1677FF;
border-radius: 4px;
color: #1677FF;
background: #fff;
}
</style>
<script lang="ts">

View File

@@ -38,7 +38,7 @@ let abortController: AbortController | null = null
// 试用期过期弹框
const showTrialExpiredDialog = ref(false)
const trialExpiredType = ref<'device' | 'account' | 'both' | 'subscribe'>('account')
const checkExpiredType = inject<() => 'device' | 'account' | 'both' | 'subscribe'>('checkExpiredType')
const vipStatus = inject<any>('vipStatus')
function selectAccount(id: number) {
accountId.value = id
loadShops()
@@ -100,7 +100,7 @@ async function fetchData() {
if (refreshVipStatus) await refreshVipStatus()
// VIP检查
if (!props.isVip) {
if (checkExpiredType) trialExpiredType.value = checkExpiredType()
if (vipStatus) trialExpiredType.value = vipStatus.value.expiredType
showTrialExpiredDialog.value = true
return
}
@@ -114,7 +114,11 @@ async function fetchData() {
fetchCurrentPage.value = 1
fetchTotalItems.value = 0
currentBatchId.value = `ZEBRA_${Date.now()}`
const [startDate = '', endDate = ''] = dateRange.value || []
const [start, end] = dateRange.value || []
const startDate = start ? `${new Date(start).toLocaleDateString('sv-SE')} 00:00:00` : ''
const endDate = end ? `${new Date(end).toLocaleDateString('sv-SE')} 23:59:59` : ''
await fetchPageData(startDate, endDate)
}
async function fetchPageData(startDate: string, endDate: string) {
@@ -258,7 +262,8 @@ async function exportToExcel() {
})
const fileName = `斑马订单数据_${new Date().toISOString().slice(0, 10)}.xlsx`
const success = await handlePlatformFileExport('zebra', blob, fileName)
const username = getUsernameFromToken()
const success = await handlePlatformFileExport('zebra', blob, fileName, username)
if (success) {
showMessage('Excel文件导出成功', 'success')
@@ -403,8 +408,8 @@ async function removeCurrentAccount() {
<section class="step">
<div class="step-index">2</div>
<div class="step-body">
<div class="step-title">查询的日期</div>
<div class="tip">请选择查询数据的日期范围</div>
<div class="step-title">需查询的店铺与日期</div>
<div class="tip">请选择查询的店铺可多选与日期范围选项为空时默认获取全部数据</div>
<el-select v-model="selectedShops" multiple placeholder="选择店铺" :disabled="loading || !accounts.length" size="small" style="width: 100%">
<el-option v-for="shop in shopList" :key="shop.id" :label="shop.shopName" :value="shop.id" />
</el-select>
@@ -419,7 +424,7 @@ async function removeCurrentAccount() {
<div class="step-title">获取数据</div>
<div class="tip">点击下方按钮开始查询订单数据</div>
<div class="btn-col">
<el-button size="small" class="w100 btn-blue" :disabled="loading || !accounts.length" @click="fetchData">{{ loading ? '处理中...' : '获取数据' }}</el-button>
<el-button size="small" class="w100 btn-blue" :disabled="loading || exportLoading || !accounts.length" @click="fetchData">{{ loading ? '处理中...' : '获取数据' }}</el-button>
<el-button size="small" :disabled="!loading" @click="stopFetch" class="w100">停止获取</el-button>
</div>
</div>
@@ -431,7 +436,7 @@ async function removeCurrentAccount() {
<div class="step-title">导出数据</div>
<div class="tip">点击下方按钮导出所有订单数据到 Excel 文件</div>
<div class="btn-col">
<el-button size="small" type="success" :disabled="exportLoading || !allOrderData.length" :loading="exportLoading" @click="exportToExcel" class="w100">{{ exportLoading ? '导出中...' : '导出数据' }}</el-button>
<el-button size="small" :disabled="exportLoading || loading || !allOrderData.length" :loading="exportLoading" @click="exportToExcel" class="w100 btn-blue">{{ exportLoading ? '导出中...' : '导出数据' }}</el-button>
<!-- 导出进度条 -->
</div>
</div>
@@ -522,7 +527,6 @@ async function removeCurrentAccount() {
<!-- 底部区域分页器 -->
<div class="pagination-fixed">
<el-pagination
background
:current-page="currentPage"
:page-sizes="[15,30,50,100]"
:page-size="pageSize"
@@ -578,7 +582,6 @@ export default {
.aside-header { display: flex; justify-content: flex-start; align-items: center; font-weight: 600; color: #606266; margin-bottom: 8px; }
.aside-steps { position: relative; }
.step { display: grid; grid-template-columns: 22px 1fr; gap: 10px; position: relative; padding: 8px 0; }
.step + .step { border-top: 1px dashed #ebeef5; }
.step-index { width: 22px; height: 22px; background: #1677FF; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 600; margin-top: 2px; }
.step-body { min-width: 0; text-align: left; }
.step-title { font-size: 13px; color: #606266; margin-bottom: 6px; font-weight: 600; text-align: left; }
@@ -645,7 +648,8 @@ export default {
.table-loading { position: absolute; inset: 0; background: rgba(255, 255, 255, 0.95); display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 14px; color: #606266; }
.spinner { font-size: 24px; animation: spin 1s linear infinite; margin-bottom: 8px; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.pagination-fixed { position: sticky; bottom: 0; z-index: 2; padding: 8px 12px; background: #f9f9f9; border-radius: 4px; display: flex; justify-content: center; border-top: 1px solid #ebeef5; margin-top: 8px; }
.pagination-fixed { position: sticky; bottom: 0; z-index: 2; padding: 8px 12px; background: #fff; display: flex; justify-content: flex-end; margin-top: 8px; }
.pagination-fixed :deep(.el-pager li.is-active) { border: 1px solid #1677FF; border-radius: 4px; color: #1677FF; background: #fff; }
.tag { display: inline-block; padding: 0 6px; margin-left: 6px; font-size: 12px; background: #ecf5ff; color: #409EFF; border-radius: 3px; }
.empty-abs { position: absolute; left: 0; right: 0; top: 48px; bottom: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; }
.progress-section { margin: 0px 12px 0px 12px; }

View File

@@ -8,19 +8,15 @@ async function fetchDeviceIdFromClient(): Promise<string> {
credentials: 'omit',
cache: 'no-store'
})
if (!response.ok) throw new Error('获取设备ID失败')
const result = await response.json()
if (!result?.data) throw new Error('设备ID为空')
return result.data
}
export async function getOrCreateDeviceId(): Promise<string> {
const cached = localStorage.getItem(DEVICE_ID_KEY)
if (cached) return cached
const deviceId = await fetchDeviceIdFromClient()
localStorage.setItem(DEVICE_ID_KEY, deviceId)
return deviceId

View File

@@ -7,8 +7,6 @@ export interface PlatformExportSettings {
}
export interface AppSettings {
// 全局设置
global: PlatformExportSettings
// 平台特定设置
platforms: {
amazon: PlatformExportSettings
@@ -17,9 +15,22 @@ export interface AppSettings {
}
// 更新设置
autoUpdate?: boolean
// 关闭行为
closeAction?: 'quit' | 'minimize' | 'tray'
// 启动配置
autoLaunch?: boolean
launchMinimized?: boolean
}
const SETTINGS_KEY = 'app-settings'
const SETTINGS_KEY_PREFIX = 'app-settings'
// 获取带用户隔离的设置 key
function getSettingsKey(username?: string): string {
if (!username || username.trim() === '') {
return SETTINGS_KEY_PREFIX
}
return `${SETTINGS_KEY_PREFIX}-${username}`
}
// 默认平台设置
const defaultPlatformSettings: PlatformExportSettings = {
@@ -28,51 +39,59 @@ const defaultPlatformSettings: PlatformExportSettings = {
// 默认设置
const defaultSettings: AppSettings = {
global: { ...defaultPlatformSettings },
platforms: {
amazon: { ...defaultPlatformSettings },
rakuten: { ...defaultPlatformSettings },
zebra: { ...defaultPlatformSettings }
},
autoUpdate: false
autoUpdate: false,
closeAction: 'quit',
autoLaunch: false,
launchMinimized: false
}
// 获取设置
export function getSettings(): AppSettings {
const saved = localStorage.getItem(SETTINGS_KEY)
// 获取设置(按用户隔离)
export function getSettings(username?: string): AppSettings {
const settingsKey = getSettingsKey(username)
const saved = localStorage.getItem(settingsKey)
if (saved) {
const settings = JSON.parse(saved)
return {
global: { ...defaultSettings.global, ...settings.global },
platforms: {
amazon: { ...defaultSettings.platforms.amazon, ...settings.platforms?.amazon },
rakuten: { ...defaultSettings.platforms.rakuten, ...settings.platforms?.rakuten },
zebra: { ...defaultSettings.platforms.zebra, ...settings.platforms?.zebra }
},
autoUpdate: settings.autoUpdate ?? defaultSettings.autoUpdate
autoUpdate: settings.autoUpdate ?? defaultSettings.autoUpdate,
closeAction: settings.closeAction ?? defaultSettings.closeAction,
autoLaunch: settings.autoLaunch ?? defaultSettings.autoLaunch,
launchMinimized: settings.launchMinimized ?? defaultSettings.launchMinimized
}
}
return defaultSettings
}
// 保存设置
export function saveSettings(settings: Partial<AppSettings>): void {
const current = getSettings()
// 保存设置(按用户隔离)
export function saveSettings(settings: Partial<AppSettings>, username?: string): void {
const current = getSettings(username)
const updated = {
global: { ...current.global, ...settings.global },
platforms: {
amazon: { ...current.platforms.amazon, ...settings.platforms?.amazon },
rakuten: { ...current.platforms.rakuten, ...settings.platforms?.rakuten },
zebra: { ...current.platforms.zebra, ...settings.platforms?.zebra }
},
autoUpdate: settings.autoUpdate ?? current.autoUpdate
autoUpdate: settings.autoUpdate ?? current.autoUpdate,
closeAction: settings.closeAction ?? current.closeAction,
autoLaunch: settings.autoLaunch ?? current.autoLaunch,
launchMinimized: settings.launchMinimized ?? current.launchMinimized
}
localStorage.setItem(SETTINGS_KEY, JSON.stringify(updated))
const settingsKey = getSettingsKey(username)
localStorage.setItem(settingsKey, JSON.stringify(updated))
}
// 保存平台特定设置
export function savePlatformSettings(platform: Platform, settings: Partial<PlatformExportSettings>): void {
const current = getSettings()
// 保存平台特定设置(按用户隔离)
export function savePlatformSettings(platform: Platform, settings: Partial<PlatformExportSettings>, username?: string): void {
const current = getSettings(username)
const updated = {
...current,
platforms: {
@@ -80,23 +99,25 @@ export function savePlatformSettings(platform: Platform, settings: Partial<Platf
[platform]: { ...current.platforms[platform], ...settings }
}
}
localStorage.setItem(SETTINGS_KEY, JSON.stringify(updated))
const settingsKey = getSettingsKey(username)
localStorage.setItem(settingsKey, JSON.stringify(updated))
}
// 获取平台导出配置
export function getPlatformExportConfig(platform: Platform): PlatformExportSettings {
const settings = getSettings()
// 获取平台导出配置(按用户隔离)
export function getPlatformExportConfig(platform: Platform, username?: string): PlatformExportSettings {
const settings = getSettings(username)
return settings.platforms[platform]
}
// 处理平台特定文件导出
// 处理平台特定文件导出(按用户隔离)
export async function handlePlatformFileExport(
platform: Platform,
blob: Blob,
defaultFileName: string
defaultFileName: string,
username?: string
): Promise<boolean> {
const config = getPlatformExportConfig(platform)
const config = getPlatformExportConfig(platform, username)
if (!config.exportPath) {
const result = await (window as any).electronAPI.showSaveDialog({

View File

@@ -5,6 +5,7 @@ set APP_ASAR=%~1
set UPDATE_FILE=%~2
set JAR_UPDATE=%~3
set EXE_PATH=%~4
set UPDATE_DIR=%~5
if not exist "%UPDATE_FILE%" if "%JAR_UPDATE%"=="" exit /b 1
if not exist "%UPDATE_FILE%" if not exist "%JAR_UPDATE%" exit /b 1
@@ -75,5 +76,9 @@ if errorlevel 1 (
if exist "%JAR_UPDATE%" del /f /q "%JAR_UPDATE%" >nul 2>&1
:start_app
REM Clean up update directory
if exist "%UPDATE_DIR%" (
for %%F in ("%UPDATE_DIR%\*") do del /f /q "%%F" >nul 2>&1
)
start "" "%EXE_PATH%"
exit /b 0

View File

@@ -10,7 +10,7 @@
</parent>
<groupId>com.tashow.erp</groupId>
<artifactId>erp_client_sb</artifactId>
<version>2.4.9</version>
<version>2.5.2</version>
<name>erp_client_sb</name>
<description>erp客户端</description>
<properties>
@@ -95,11 +95,6 @@
<artifactId>selenium-java</artifactId>
<version>4.23.0</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.9.2</version>
</dependency>
<!-- JWT parsing for local RS256 verification -->
<dependency>

View File

@@ -4,11 +4,13 @@ import com.tashow.erp.repository.AmazonProductRepository;
import com.tashow.erp.service.AmazonScrapingService;
import com.tashow.erp.utils.ExcelParseUtil;
import com.tashow.erp.utils.JsonData;
import com.tashow.erp.utils.JwtUtil;
import com.tashow.erp.utils.LoggerUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@@ -22,18 +24,25 @@ public class AmazonController {
private AmazonProductRepository amazonProductRepository;
@PostMapping("/products/batch")
public JsonData batchGetProducts(@RequestBody Map<String, Object> request) {
public JsonData batchGetProducts(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
@SuppressWarnings("unchecked")
List<String> asinList = (List<String>) request.get("asinList");
String batchId = (String) request.get("batchId");
String region = (String) request.getOrDefault("region", "JP");
List<AmazonProductEntity> products = amazonScrapingService.batchGetProductInfo(asinList, batchId, region);
// 从 token 中获取 username
String username = JwtUtil.getUsernameFromRequest(httpRequest);
// 构建带用户隔离的 sessionId
String userSessionId = JwtUtil.buildUserSessionId(username, batchId);
List<AmazonProductEntity> products = amazonScrapingService.batchGetProductInfo(asinList, userSessionId, region);
return JsonData.buildSuccess(Map.of("products", products, "total", products.size()));
}
@GetMapping("/products/latest")
public JsonData getLatestProducts() {
List<AmazonProductEntity> products = amazonProductRepository.findLatestProducts();
public JsonData getLatestProducts(HttpServletRequest request) {
String username = JwtUtil.getUsernameFromRequest(request);
List<AmazonProductEntity> products = amazonProductRepository.findLatestProducts(username);
return JsonData.buildSuccess(Map.of("products", products, "total", products.size()));
}

View File

@@ -2,10 +2,12 @@ package com.tashow.erp.controller;
import com.tashow.erp.repository.BanmaOrderRepository;
import com.tashow.erp.service.BanmaOrderService;
import com.tashow.erp.utils.JsonData;
import com.tashow.erp.utils.JwtUtil;
import com.tashow.erp.utils.LoggerUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -27,9 +29,15 @@ public class BanmaOrderController {
@RequestParam(defaultValue = "1", name = "page") int page,
@RequestParam(defaultValue = "10", name = "pageSize") int pageSize,
@RequestParam("batchId") String batchId,
@RequestParam(required = false, name = "shopIds") String shopIds) {
@RequestParam(required = false, name = "shopIds") String shopIds,
HttpServletRequest request) {
// 从 token 中获取 username
String username = JwtUtil.getUsernameFromRequest(request);
// 构建带用户隔离的 sessionId
String userSessionId = JwtUtil.buildUserSessionId(username, batchId);
List<String> shopIdList = shopIds != null ? java.util.Arrays.asList(shopIds.split(",")) : null;
Map<String, Object> result = banmaOrderService.getOrdersByPage(accountId, startDate, endDate, page, pageSize, batchId, shopIdList);
Map<String, Object> result = banmaOrderService.getOrdersByPage(accountId, startDate, endDate, page, pageSize, userSessionId, shopIdList);
return result.containsKey("success") && !(Boolean)result.get("success")
? JsonData.buildError((String)result.get("message"))
: JsonData.buildSuccess(result);
@@ -41,9 +49,10 @@ public class BanmaOrderController {
}
@GetMapping("/orders/latest")
public JsonData getLatestOrders() {
public JsonData getLatestOrders(HttpServletRequest request) {
String username = JwtUtil.getUsernameFromRequest(request);
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
List<Map<String, Object>> orders = banmaOrderRepository.findLatestOrders()
List<Map<String, Object>> orders = banmaOrderRepository.findLatestOrders(username)
.parallelStream()
.map(entity -> {
try {

View File

@@ -1,5 +1,4 @@
package com.tashow.erp.controller;
import com.tashow.erp.model.RakutenProduct;
import com.tashow.erp.model.SearchResult;
import com.tashow.erp.service.Alibaba1688Service;
@@ -8,14 +7,14 @@ import com.tashow.erp.service.RakutenScrapingService;
import com.tashow.erp.utils.DataReportUtil;
import com.tashow.erp.utils.ExcelParseUtil;
import com.tashow.erp.utils.JsonData;
import com.tashow.erp.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/rakuten")
@Slf4j
@@ -30,8 +29,13 @@ public class RakutenController {
private DataReportUtil dataReportUtil;
@PostMapping(value = "/products")
public JsonData getProducts(@RequestParam("file") MultipartFile file, @RequestParam(value = "batchId", required = false) String batchId) {
public JsonData getProducts(@RequestParam("file") MultipartFile file, @RequestParam(value = "batchId", required = false) String batchId, HttpServletRequest request) {
try {
// 从 token 中获取 username
String username = JwtUtil.getUsernameFromRequest(request);
// 构建带用户隔离的 sessionId
String userSessionId = JwtUtil.buildUserSessionId(username, batchId);
List<String> shopNames = ExcelParseUtil.parseFirstColumn(file);
if (CollectionUtils.isEmpty(shopNames)) {
return JsonData.buildError("Excel文件中未解析到店铺名");
@@ -39,10 +43,10 @@ public class RakutenController {
List<RakutenProduct> allProducts = new ArrayList<>();
List<String> skippedShops = new ArrayList<>();
for (String currentShopName : shopNames) {
if (rakutenCacheService.hasRecentData(currentShopName)) {
if (rakutenCacheService.hasRecentData(currentShopName, username)) {
// 从缓存获取
List<RakutenProduct> cached = rakutenCacheService.getProductsByShopName(currentShopName).stream().filter(p -> currentShopName.equals(p.getOriginalShopName())).toList();
rakutenCacheService.updateSpecificProductsSessionId(cached, batchId);
List<RakutenProduct> cached = rakutenCacheService.getProductsByShopName(currentShopName, username).stream().filter(p -> currentShopName.equals(p.getOriginalShopName())).toList();
rakutenCacheService.updateSpecificProductsSessionId(cached, userSessionId);
allProducts.addAll(cached);
skippedShops.add(currentShopName);
log.info("使用缓存数据,店铺: {},数量: {}", currentShopName, cached.size());
@@ -57,7 +61,7 @@ public class RakutenController {
}
List<RakutenProduct> newProducts = allProducts.stream().filter(p -> !skippedShops.contains(p.getOriginalShopName())).toList();
if (!newProducts.isEmpty()) {
rakutenCacheService.saveProductsWithSessionId(newProducts, batchId);
rakutenCacheService.saveProductsWithSessionId(newProducts, userSessionId);
}
int cachedCount = allProducts.size() - newProducts.size();
if (cachedCount > 0) {
@@ -77,12 +81,17 @@ public class RakutenController {
}
@PostMapping("/search1688")
public JsonData search1688(@RequestBody Map<String, Object> params) {
public JsonData search1688(@RequestBody Map<String, Object> params, HttpServletRequest request) {
String imageUrl = (String) params.get("imageUrl");
String sessionId = (String) params.get("sessionId");
try {
// 从 token 中获取 username
String username = JwtUtil.getUsernameFromRequest(request);
// 构建带用户隔离的 sessionId
String userSessionId = JwtUtil.buildUserSessionId(username, sessionId);
SearchResult result = alibaba1688Service.get1688Detail(imageUrl);
rakutenScrapingService.update1688DataByImageUrl(result, sessionId, imageUrl);
rakutenScrapingService.update1688DataByImageUrl(result, userSessionId, imageUrl);
return JsonData.buildSuccess(result);
} catch (Exception e) {
log.error("1688识图搜索失败", e);
@@ -91,9 +100,10 @@ public class RakutenController {
}
@GetMapping("/products/latest")
public JsonData getLatestProducts() {
public JsonData getLatestProducts(HttpServletRequest request) {
try {
List<Map<String, Object>> products = rakutenScrapingService.getLatestProductsForDisplay();
String username = JwtUtil.getUsernameFromRequest(request);
List<Map<String, Object>> products = rakutenScrapingService.getLatestProductsForDisplay(username);
return JsonData.buildSuccess(Map.of("products", products, "total", products.size()));
} catch (Exception e) {
log.error("获取最新商品数据失败", e);

View File

@@ -1,11 +1,11 @@
package com.tashow.erp.controller;
import com.tashow.erp.entity.AuthTokenEntity;
import com.tashow.erp.repository.AuthTokenRepository;
import com.tashow.erp.service.CacheService;
import com.tashow.erp.service.impl.GenmaiServiceImpl;
import com.tashow.erp.utils.JsonData;
import com.tashow.erp.utils.LoggerUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -13,7 +13,6 @@ import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@RestController
@RequestMapping("/api/system")
public class SystemController {
@@ -68,7 +67,6 @@ public class SystemController {
public JsonData getLocalIp() throws Exception {
return JsonData.buildSuccess(java.net.InetAddress.getLocalHost().getHostAddress());
}
@GetMapping("/computer-name")
public JsonData getComputerName() {
return JsonData.buildSuccess(System.getenv("COMPUTERNAME"));
@@ -124,7 +122,6 @@ public class SystemController {
responseHeaders.setContentType(MediaType.IMAGE_JPEG);
}
responseHeaders.setCacheControl("max-age=3600");
return new ResponseEntity<>(response.getBody(), responseHeaders, HttpStatus.OK);
} catch (Exception e) {
logger.error("代理图片失败: {}", imageUrl, e);
@@ -133,8 +130,9 @@ public class SystemController {
}
@PostMapping("/cache/clear")
public JsonData clearCache() {
cacheService.clearCache();
public JsonData clearCache(HttpServletRequest request) {
String username = com.tashow.erp.utils.JwtUtil.getUsernameFromRequest(request);
cacheService.clearCache(username);
return JsonData.buildSuccess("缓存清理成功");
}
}

View File

@@ -62,6 +62,12 @@ public interface AmazonProductRepository extends JpaRepository<AmazonProductEnti
*/
@Query(value = "SELECT * FROM amazon_products WHERE session_id = (SELECT session_id FROM amazon_products GROUP BY session_id ORDER BY session_id DESC LIMIT 1) ORDER BY updated_at ", nativeQuery = true)
List<AmazonProductEntity> findLatestProducts();
/**
* 获取指定用户最新会话的产品数据(按用户隔离)
*/
@Query(value = "SELECT * FROM amazon_products WHERE session_id = (SELECT session_id FROM amazon_products WHERE session_id LIKE :username || '#%' GROUP BY session_id ORDER BY session_id DESC LIMIT 1) ORDER BY updated_at ", nativeQuery = true)
List<AmazonProductEntity> findLatestProducts(@Param("username") String username);
/**
* 删除指定ASIN在指定时间后的数据用于清理12小时内重复

View File

@@ -66,6 +66,12 @@ public interface BanmaOrderRepository extends JpaRepository<BanmaOrderEntity, Lo
*/
@Query(value = "SELECT * FROM banma_orders WHERE session_id = (SELECT session_id FROM banma_orders ORDER BY created_at DESC LIMIT 1) ORDER BY updated_at ASC, id ASC", nativeQuery = true)
List<BanmaOrderEntity> findLatestOrders();
/**
* 获取指定用户最新会话的订单数据(按用户隔离)
*/
@Query(value = "SELECT * FROM banma_orders WHERE session_id = (SELECT session_id FROM banma_orders WHERE session_id LIKE :username || '#%' ORDER BY created_at DESC LIMIT 1) ORDER BY updated_at ASC, id ASC", nativeQuery = true)
List<BanmaOrderEntity> findLatestOrders(@Param("username") String username);
/**
* 删除指定追踪号在指定时间后的数据用于清理12小时内重复

View File

@@ -52,6 +52,16 @@ public interface RakutenProductRepository extends JpaRepository<RakutenProductEn
* 检查指定店铺在指定时间后是否有数据
*/
boolean existsByOriginalShopNameAndCreatedAtAfter(String originalShopName, LocalDateTime sinceTime);
/**
* 检查指定店铺在指定时间后是否有数据(按用户隔离)
*/
boolean existsByOriginalShopNameAndSessionIdStartingWithAndCreatedAtAfter(String originalShopName, String sessionIdPrefix, LocalDateTime sinceTime);
/**
* 根据店铺名和 sessionId 前缀获取产品(按用户隔离)
*/
List<RakutenProductEntity> findByOriginalShopNameAndSessionIdStartingWithOrderByCreatedAtAscIdAsc(String originalShopName, String sessionIdPrefix);
/**
* 获取最新的会话ID
@@ -64,6 +74,12 @@ public interface RakutenProductRepository extends JpaRepository<RakutenProductEn
*/
@Query(value = "SELECT * FROM rakuten_products WHERE session_id = (SELECT session_id FROM rakuten_products ORDER BY created_at DESC LIMIT 1) ORDER BY created_at ASC, id ASC", nativeQuery = true)
List<RakutenProductEntity> findLatestProducts();
/**
* 获取指定用户最新会话的产品数据(按用户隔离)
*/
@Query(value = "SELECT * FROM rakuten_products WHERE session_id = (SELECT session_id FROM rakuten_products WHERE session_id LIKE :username || '#%' ORDER BY created_at DESC LIMIT 1) ORDER BY created_at ASC, id ASC", nativeQuery = true)
List<RakutenProductEntity> findLatestProducts(@Param("username") String username);
/**
* 删除指定商品URL在指定时间后的数据用于清理12小时内重复

View File

@@ -1,6 +1,9 @@
package com.tashow.erp.service;
import com.tashow.erp.entity.AuthTokenEntity;
import com.tashow.erp.entity.RakutenProductEntity;
import com.tashow.erp.entity.AmazonProductEntity;
import com.tashow.erp.entity.BanmaOrderEntity;
import com.tashow.erp.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -8,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Service
@@ -45,14 +49,39 @@ public class CacheService {
}
@Transactional
public void clearCache() {
rakutenProductRepository.deleteAll();
amazonProductRepository.deleteAll();
alibaba1688ProductRepository.deleteAll();
zebraOrderRepository.deleteAll();
banmaOrderRepository.deleteAll();
cacheDataRepository.deleteAll();
updateStatusRepository.deleteAll();
public void clearCache(String username) {
if (username == null || username.isEmpty()) {
logger.warn("尝试清理缓存但未提供用户名,操作已跳过");
return;
}
logger.info("开始清理用户缓存: {}", username);
// 清理当前用户的 Rakuten 产品数据
List<RakutenProductEntity> rakutenProducts = rakutenProductRepository.findAll();
List<RakutenProductEntity> userRakutenProducts = rakutenProducts.stream()
.filter(p -> p.getSessionId() != null && p.getSessionId().startsWith(username + "#"))
.toList();
rakutenProductRepository.deleteAll(userRakutenProducts);
logger.info("已清理 {} 条 Rakuten 产品数据", userRakutenProducts.size());
// 清理当前用户的 Amazon 产品数据
List<AmazonProductEntity> amazonProducts = amazonProductRepository.findAll();
List<AmazonProductEntity> userAmazonProducts = amazonProducts.stream()
.filter(p -> p.getSessionId() != null && p.getSessionId().startsWith(username + "#"))
.toList();
amazonProductRepository.deleteAll(userAmazonProducts);
logger.info("已清理 {} 条 Amazon 产品数据", userAmazonProducts.size());
// 清理当前用户的 Banma 订单数据
List<BanmaOrderEntity> banmaOrders = banmaOrderRepository.findAll();
List<BanmaOrderEntity> userBanmaOrders = banmaOrders.stream()
.filter(o -> o.getSessionId() != null && o.getSessionId().startsWith(username + "#"))
.toList();
banmaOrderRepository.deleteAll(userBanmaOrders);
logger.info("已清理 {} 条 Banma 订单数据", userBanmaOrders.size());
logger.info("用户 {} 的缓存清理完成", username);
}
}

View File

@@ -18,12 +18,12 @@ public interface RakutenCacheService {
/**
* 检查店铺是否有最近的数据12小时内
*/
boolean hasRecentData(String shopName);
boolean hasRecentData(String shopName, String username);
/**
* 根据店铺名获取已有数据
*/
List<RakutenProduct> getProductsByShopName(String shopName);
List<RakutenProduct> getProductsByShopName(String shopName, String username);
/**
* 更新指定店铺的产品sessionId

View File

@@ -32,9 +32,9 @@ public interface RakutenScrapingService {
void update1688DataByImageUrl(SearchResult searchResult, String sessionId, String imageUrl);
/**
* 获取最新产品数据并转换为前端格式
* 获取最新产品数据并转换为前端格式(按用户隔离)
*/
List<Map<String, Object>> getLatestProductsForDisplay();
List<Map<String, Object>> getLatestProductsForDisplay(String username);
}

View File

@@ -243,7 +243,6 @@ public class Alibaba1688ServiceImpl implements Alibaba1688Service {
return 0.0;
}
}
/**
* 上传图片并获取图片ID
* @return

View File

@@ -2,7 +2,6 @@ package com.tashow.erp.service.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.util.UrlUtils;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
@@ -30,7 +29,6 @@ public class GenmaiServiceImpl {
Runtime.getRuntime().exec("taskkill /f /im chrome.exe");
Thread.sleep(1000); // 等待进程关闭
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
String username = System.getProperty("user.name", "user");
String safeUsername;

View File

@@ -80,23 +80,30 @@ public class RakutenCacheServiceImpl implements RakutenCacheService {
}
/**
* 检查店铺是否有1小时内的缓存数据
* 检查店铺是否有1小时内的缓存数据(按用户隔离)
*/
@Override
public boolean hasRecentData(String shopName) {
boolean hasRecent = repository.existsByOriginalShopNameAndCreatedAtAfter(shopName, LocalDateTime.now().minusHours(1));
public boolean hasRecentData(String shopName, String username) {
if (username == null || username.isEmpty()) {
return false;
}
boolean hasRecent = repository.existsByOriginalShopNameAndSessionIdStartingWithAndCreatedAtAfter(
shopName, username + "#", LocalDateTime.now().minusHours(1));
if (hasRecent) {
log.info("店铺 {} 存在1小时内缓存数据将使用缓存", shopName);
log.info("店铺 {} 存在1小时内缓存数据(用户: {},将使用缓存", shopName, username);
}
return hasRecent;
}
/**
* 根据店铺名获取所有产品数据
* 根据店铺名获取所有产品数据(按用户隔离)
*/
@Override
public List<RakutenProduct> getProductsByShopName(String shopName) {
return repository.findByOriginalShopNameOrderByCreatedAtAscIdAsc(shopName).stream()
public List<RakutenProduct> getProductsByShopName(String shopName, String username) {
if (username == null || username.isEmpty()) {
return List.of();
}
return repository.findByOriginalShopNameAndSessionIdStartingWithOrderByCreatedAtAscIdAsc(shopName, username + "#").stream()
.map(entity -> {
RakutenProduct product = new RakutenProduct();
BeanUtils.copyProperties(entity, product);

View File

@@ -121,8 +121,9 @@ public class RakutenScrapingServiceImpl implements RakutenScrapingService {
public void update1688DataByImageUrl(SearchResult searchResult, String sessionId, String imageUrl) {
List<RakutenProductEntity> matchingProducts = rakutenProductRepository.findBySessionIdOrderByCreatedAtAscIdAsc(sessionId).stream().filter(product -> imageUrl.equals(product.getImgUrl())).peek(product -> {
product.setMapRecognitionLink(searchResult.getMapRecognitionLink());
product.setImage1688Url(searchResult.getMapRecognitionLink());
product.setDetailUrl1688(searchResult.getMapRecognitionLink());
product.setFreight(searchResult.getFreight());
product.setSkuPriceJson(searchResult.getSkuPrice().toString());
product.setMedian(searchResult.getMedian());
product.setWeight(searchResult.getWeight());
product.setSkuPriceJson(JSON.toJSONString(searchResult.getSkuPrice()));
@@ -133,8 +134,11 @@ public class RakutenScrapingServiceImpl implements RakutenScrapingService {
}
@Override
public List<Map<String, Object>> getLatestProductsForDisplay() {
return rakutenProductRepository.findLatestProducts().stream().map(entity -> {
public List<Map<String, Object>> getLatestProductsForDisplay(String username) {
if (username == null || username.isEmpty()) {
return List.of();
}
return rakutenProductRepository.findLatestProducts(username).stream().map(entity -> {
Map<String, Object> result = new HashMap<>();
result.put("originalShopName", entity.getOriginalShopName());
result.put("productUrl", entity.getProductUrl());
@@ -142,12 +146,14 @@ public class RakutenScrapingServiceImpl implements RakutenScrapingService {
result.put("productTitle", entity.getProductTitle());
result.put("price", entity.getPrice());
result.put("ranking", entity.getRanking());
result.put("price1688", entity.getPrice1688());
result.put("image1688Url", entity.getImage1688Url());
result.put("detailUrl1688", entity.getDetailUrl1688());
result.put("mapRecognitionLink", entity.getMapRecognitionLink());
result.put("freight", entity.getFreight());
result.put("median", entity.getMedian());
result.put("weight", entity.getWeight());
result.put("skuPriceJson", entity.getSkuPriceJson());
result.put("skuPrice", entity.getSkuPriceJson());
return result;
}).collect(Collectors.toList());

View File

@@ -0,0 +1,108 @@
package com.tashow.erp.utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Base64;
/**
* JWT 工具类
* 用于从 HTTP 请求中解析 JWT token 并提取用户信息
*/
public class JwtUtil {
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* 从 HTTP 请求中提取 username
* @param request HTTP 请求对象
* @return username如果解析失败返回空字符串
*/
public static String getUsernameFromRequest(HttpServletRequest request) {
try {
String token = extractToken(request);
if (token == null || token.isEmpty()) {
return "";
}
return extractUsernameFromToken(token);
} catch (Exception e) {
return "";
}
}
/**
* 从 token 字符串中提取 username
* @param token JWT token
* @return username
*/
public static String extractUsernameFromToken(String token) {
try {
String[] parts = token.split("\\.");
if (parts.length != 3) {
return "";
}
String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]));
JsonNode payload = objectMapper.readTree(payloadJson);
// 尝试从 username 或 sub 字段获取用户名
if (payload.has("username")) {
return payload.get("username").asText();
} else if (payload.has("sub")) {
return payload.get("sub").asText();
}
return "";
} catch (Exception e) {
return "";
}
}
/**
* 从 HTTP 请求中提取 token
*/
private static String extractToken(HttpServletRequest request) {
// 从 Authorization header 获取
String auth = request.getHeader("Authorization");
if (auth != null && auth.startsWith("Bearer ")) {
return auth.substring(7).trim();
}
// 从 Cookie 获取
if (request.getCookies() != null) {
for (jakarta.servlet.http.Cookie cookie : request.getCookies()) {
if ("FX_TOKEN".equals(cookie.getName()) && cookie.getValue() != null) {
return cookie.getValue().trim();
}
}
}
return null;
}
/**
* 构建带用户隔离的 sessionId
* @param username 用户名
* @param originalSessionId 原始 sessionId
* @return 格式化的 sessionId: username#originalSessionId
*/
public static String buildUserSessionId(String username, String originalSessionId) {
if (username == null || username.isEmpty()) {
return originalSessionId;
}
return username + "#" + originalSessionId;
}
/**
* 从 sessionId 中提取原始 sessionId去除用户前缀
* @param userSessionId 带用户前缀的 sessionId
* @return 原始 sessionId
*/
public static String extractOriginalSessionId(String userSessionId) {
if (userSessionId == null || !userSessionId.contains("#")) {
return userSessionId;
}
int idx = userSessionId.indexOf("#");
return userSessionId.substring(idx + 1);
}
}

View File

@@ -1,24 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 固定日志路径到系统公共数据目录 -->
<property name="LOG_HOME" value="C:/ProgramData/erp-logs" />
<!-- 使用 Spring Boot 传递的日志路径 -->
<property name="LOG_HOME" value="${LOG_PATH:-logs}" />
<!--
日志上报说明:
日志文件按天滚动存储在 ${LOG_HOME} 目录下
格式spring-boot-yyyy-MM-dd.log
用户反馈系统集成说明:
- 客户端应用Electron可以读取本地日志文件
- 用户在"设置-反馈"页面提交反馈时,可选择附带某一天的日志文件
- 日志文件将随反馈内容一起上传到服务器
- 服务器存储路径C:/ProgramData/erp-logs/feedback/ (Windows) 或 /opt/erp/feedback-logs/ (Linux)
- 管理员可在后台管理界面查看反馈并下载相应日志文件
日志保留策略:
- 本地日志保留30天
- 总大小限制1GB
- 超过限制时自动删除最旧的日志文件
日志说明:
- 日志文件按天滚动存储在 ${LOG_HOME} 目录下
- 格式spring-boot-yyyy-MM-dd.log
- 客户端应用可读取本地日志文件用于反馈
- 日志保留30天总大小限制1GB
-->
<!-- 控制台输出 -->

View File

@@ -3,6 +3,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.TimeZone;
/**
* 启动程序
@@ -15,6 +16,7 @@ public class RuoYiApplication
{
public static void main(String[] args)
{
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
// System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(RuoYiApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" +

View File

@@ -37,7 +37,7 @@ public class ClientFeedbackController extends BaseController {
@Autowired
private IClientFeedbackService feedbackService;
@Value("${feedback.log.path:C:/ProgramData/erp-logs/feedback/}")
@Value("${feedback.log.path:}")
private String feedbackLogPath;
/**
@@ -258,20 +258,21 @@ public class ClientFeedbackController extends BaseController {
* 保存日志文件
*/
private String saveLogFile(String username, String deviceId, MultipartFile file) throws IOException {
// 确保目录存在
Path uploadPath = Paths.get(feedbackLogPath);
String logPath = feedbackLogPath;
if (logPath == null || logPath.trim().isEmpty()) {
logPath = System.getProperty("user.home") + File.separator + "erp-feedback";
}
Path uploadPath = Paths.get(logPath).toAbsolutePath();
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 生成文件名: username_deviceId_timestamp.log
String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String fileName = String.format("%s_%s_%s.log", username, deviceId, timestamp);
Path filePath = uploadPath.resolve(fileName);
// 保存文件
file.transferTo(filePath.toFile());
return filePath.toString();
}
}

View File

@@ -10,7 +10,6 @@ import com.ruoyi.system.mapper.ClientAccountDeviceMapper;
import com.ruoyi.system.domain.ClientAccountDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Date;
@@ -22,7 +21,6 @@ public class ClientDeviceController {
@Autowired private ClientAccountMapper accountMapper;
@Autowired private ClientAccountDeviceMapper accountDeviceMapper;
@Autowired private SseHubService sseHubService;
private ClientAccount getAccount(String username) {
return accountMapper.selectClientAccountByUsername(username);
}
@@ -58,18 +56,18 @@ public class ClientDeviceController {
String deviceId = data.get("deviceId");
ClientAccount account = getAccount(username);
if (account == null) return AjaxResult.error("账号不存在");
int limit = getDeviceLimit(account);
if (exceedDeviceLimit(account.getId(), deviceId, limit)) {
return AjaxResult.error("设备数量已达上限(" + limit + "个)");
}
ClientDevice device = deviceMapper.selectByDeviceId(deviceId);
Date now = new Date();
ClientDevice device = deviceMapper.selectByDeviceId(deviceId);
if (device == null) {
device = new ClientDevice();
device.setDeviceId(deviceId);
device.setTrialExpireTime(new Date(System.currentTimeMillis() + 3 * 24L * 60 * 60 * 1000));
device.setStatus("online");
device.setTrialExpireTime(new Date(System.currentTimeMillis() + 7 * 24L * 60 * 60 * 1000));
deviceMapper.insert(device);
}
device.setName(username + "@" + data.get("computerName") + " (" + data.get("os") + ")");
@@ -84,12 +82,13 @@ public class ClientDeviceController {
binding = new ClientAccountDevice();
binding.setAccountId(account.getId());
binding.setDeviceId(deviceId);
binding.setBindTime(now);
binding.setStatus("active");
accountDeviceMapper.insert(binding);
} else if ("removed".equals(binding.getStatus())) {
accountDeviceMapper.updateStatus(account.getId(), deviceId, "active");
binding.setStatus("active");
accountDeviceMapper.update(binding);
}
binding.setBindTime(now);
return AjaxResult.success();
}

View File

@@ -5,6 +5,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.ClientAccount;
import com.ruoyi.system.mapper.ClientAccountMapper;
import com.ruoyi.system.mapper.BanmaAccountMapper;
import com.ruoyi.system.mapper.ClientFeedbackMapper;
import com.ruoyi.system.mapper.ClientMonitorMapper;
import com.ruoyi.system.mapper.ClientAccountDeviceMapper;
import com.ruoyi.system.mapper.RefreshTokenMapper;
import com.ruoyi.web.service.IClientAccountService;
/**
@@ -17,6 +22,16 @@ public class ClientAccountServiceImpl implements IClientAccountService
{
@Autowired
private ClientAccountMapper clientAccountMapper;
@Autowired
private BanmaAccountMapper banmaAccountMapper;
@Autowired
private ClientFeedbackMapper clientFeedbackMapper;
@Autowired
private ClientMonitorMapper clientMonitorMapper;
@Autowired
private ClientAccountDeviceMapper clientAccountDeviceMapper;
@Autowired
private RefreshTokenMapper refreshTokenMapper;
/**
* 查询客户端账号
@@ -65,10 +80,31 @@ public class ClientAccountServiceImpl implements IClientAccountService
/**
* 批量删除客户端账号
* 级联删除所有关联数据:斑马账号、反馈、错误报告、设备绑定、刷新令牌
*/
@Override
public int deleteClientAccountByIds(Long[] ids)
{
for (Long id : ids) {
// 查询账号信息获取username
ClientAccount account = clientAccountMapper.selectClientAccountById(id);
if (account != null) {
String username = account.getUsername();
// 根据username删除关联数据
if (username != null) {
banmaAccountMapper.deleteByClientUsername(username);
clientFeedbackMapper.deleteFeedbackByUsername(username);
clientMonitorMapper.deleteErrorReportByUsername(username);
}
// 根据accountId删除关联数据
clientAccountDeviceMapper.deleteByAccountId(id);
refreshTokenMapper.deleteByAccountId(id);
}
}
// 最后删除客户端账号本身
return clientAccountMapper.deleteClientAccountByIds(ids);
}

View File

@@ -3,6 +3,7 @@ package com.ruoyi.web.sse;
import com.ruoyi.system.domain.ClientDevice;
import com.ruoyi.system.mapper.ClientDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@@ -18,6 +19,14 @@ public class SseHubService {
@Autowired
private ClientDeviceMapper clientDeviceMapper;
@Scheduled(fixedRate = 30000)
public void heartbeat() {
sessionEmitters.forEach((key, emitter) -> {
String clientId = key.split(":")[1];
sendPing(key.split(":")[0], clientId);
});
}
public String buildSessionKey(String username, String clientId) {
return (username == null ? "" : username) + ":" + (clientId == null ? "" : clientId);

View File

@@ -1,8 +1,6 @@
package com.ruoyi.system.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.core.domain.BaseEntity;
import java.util.Date;
/**
@@ -10,7 +8,6 @@ import java.util.Date;
*/
public class ClientAccountDevice extends BaseEntity {
private static final long serialVersionUID = 1L;
private Long id;
private Long accountId;
private String deviceId;

View File

@@ -13,6 +13,7 @@ public interface BanmaAccountMapper {
int insert(BanmaAccount entity);
int update(BanmaAccount entity);
int deleteById(Long id);
int deleteByClientUsername(@Param("clientUsername") String clientUsername);
int clearDefault(@Param("clientUsername") String clientUsername);
}

View File

@@ -40,9 +40,19 @@ public interface ClientAccountDeviceMapper {
*/
int updateStatus(@Param("accountId") Long accountId, @Param("deviceId") String deviceId, @Param("status") String status);
/**
* 更新绑定信息
*/
int update(ClientAccountDevice binding);
/**
* 删除绑定
*/
int delete(@Param("accountId") Long accountId, @Param("deviceId") String deviceId);
/**
* 根据账号ID删除所有绑定
*/
int deleteByAccountId(@Param("accountId") Long accountId);
}

View File

@@ -45,5 +45,10 @@ public interface ClientFeedbackMapper {
* 更新反馈状态
*/
int updateFeedbackStatus(@Param("id") Long id, @Param("status") String status);
/**
* 根据用户名删除反馈
*/
int deleteFeedbackByUsername(@Param("username") String username);
}

View File

@@ -247,4 +247,12 @@ public interface ClientMonitorMapper {
* @return 在线设备列表
*/
public List<ClientDevice> selectOnlineDevices();
/**
* 根据用户名删除错误报告
*
* @param username 用户名
* @return 删除行数
*/
public int deleteErrorReportByUsername(@Param("username") String username);
}

View File

@@ -37,4 +37,9 @@ public interface RefreshTokenMapper {
* 更新令牌状态
*/
int updateRefreshToken(RefreshToken refreshToken);
/**
* 根据账号ID删除令牌
*/
int deleteByAccountId(Long accountId);
}

View File

@@ -97,6 +97,10 @@
delete from banma_account where id = #{id}
</delete>
<delete id="deleteByClientUsername">
delete from banma_account where client_username = #{clientUsername}
</delete>
</mapper>

View File

@@ -76,6 +76,18 @@
AND device_id = #{deviceId}
</update>
<!-- 更新绑定信息 -->
<update id="update" parameterType="com.ruoyi.system.domain.ClientAccountDevice">
UPDATE client_account_device
<set>
<if test="status != null">status = #{status},</if>
<if test="bindTime != null">bind_time = #{bindTime},</if>
update_time = now()
</set>
WHERE account_id = #{accountId}
AND device_id = #{deviceId}
</update>
<!-- 删除绑定 -->
<delete id="delete">
DELETE FROM client_account_device
@@ -83,5 +95,11 @@
AND device_id = #{deviceId}
</delete>
<!-- 根据账号ID删除所有绑定 -->
<delete id="deleteByAccountId">
DELETE FROM client_account_device
WHERE account_id = #{accountId}
</delete>
</mapper>

View File

@@ -44,7 +44,11 @@
</delete>
<select id="selectOnlineDevices" resultMap="ClientDeviceMap">
SELECT * FROM client_device WHERE status = 'online' ORDER BY last_active_at DESC
SELECT d.*
FROM client_device d
INNER JOIN client_account_device ad ON d.device_id = ad.device_id
WHERE ad.status = 'active' AND d.status = 'online'
ORDER BY d.last_active_at DESC
</select>
</mapper>

View File

@@ -102,5 +102,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where id = #{id}
</update>
<delete id="deleteFeedbackByUsername">
delete from client_feedback where username = #{username}
</delete>
</mapper>

View File

@@ -488,5 +488,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
collect_time = NOW()
WHERE id = #{id}
</update>
<delete id="deleteErrorReportByUsername">
DELETE FROM client_error_report WHERE username = #{username}
</delete>
</mapper>

View File

@@ -63,4 +63,8 @@
where id = #{id}
</update>
<delete id="deleteByAccountId" parameterType="Long">
delete from refresh_token where account_id = #{accountId}
</delete>
</mapper>