diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 590f315..c736a18 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -201,7 +201,9 @@ "Bash(cnpm install:*)", "Bash(cnpm uninstall:*)", "WebFetch(domain:www.electronjs.org)", - "Bash(test:*)" + "Bash(test:*)", + "Bash(sqlite3:*)", + "Bash(npx electron:*)" ], "deny": [], "ask": [], diff --git a/electron-vue-template/public/splash.html b/electron-vue-template/public/splash.html index c4abdbc..7b7897e 100644 --- a/electron-vue-template/public/splash.html +++ b/electron-vue-template/public/splash.html @@ -11,7 +11,7 @@ background-image: url('image/splash_screen.png'); background-repeat: no-repeat; background-position: center; - background-size: cover; + background-size: cover; } .box { position: fixed; left: 0; right: 0; bottom: 28px; padding: 0 0; } .progress { position: relative; width: 100vw; height: 6px; background: rgba(0,0,0,0.08); } diff --git a/electron-vue-template/src/main/main.ts b/electron-vue-template/src/main/main.ts index 1401919..f4e488d 100644 --- a/electron-vue-template/src/main/main.ts +++ b/electron-vue-template/src/main/main.ts @@ -1,5 +1,5 @@ import {app, BrowserWindow, ipcMain, Menu, screen, dialog} from 'electron'; -import { existsSync, createWriteStream, promises as fs, statSync } from 'fs'; +import {existsSync, createWriteStream, promises as fs} from 'fs'; import {join, dirname} from 'path'; import {spawn, ChildProcessWithoutNullStreams} from 'child_process'; import * as https from 'https'; @@ -10,17 +10,26 @@ let mainWindow: BrowserWindow | null = null; let splashWindow: BrowserWindow | null = null; let appOpened = false; -let downloadProgress = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' }; +let downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB', speed: ''}; let isDownloading = false; let downloadedFilePath: string | null = null; function openAppIfNotOpened() { if (appOpened) return; appOpened = true; + + // SpringBoot 启动完成,现在加载前端页面 if (mainWindow) { + if (process.env.NODE_ENV === 'development') { + const rendererPort = process.argv[2] || 8083; + mainWindow.loadURL(`http://localhost:${rendererPort}`); + } else { + mainWindow.loadFile(join(__dirname, '../renderer/index.html')); + } mainWindow.show(); mainWindow.focus(); } + if (splashWindow) { splashWindow.close(); splashWindow = null; @@ -28,36 +37,24 @@ function openAppIfNotOpened() { } function startSpringBoot() { - const jarPath = 'C:/Users/ZiJIe/Desktop/wox/RuoYi-Vue/ruoyi-admin/target/ruoyi-admin.jar'; - + const jarPath = join(__dirname, '../../public/erp_client_sb-2.4.7.jar'); springProcess = spawn('java', ['-jar', jarPath], { cwd: dirname(jarPath), detached: false }); - springProcess.stdout.on('data', (data) => { - console.log(`SpringBoot: ${data}`); - if (data.toString().includes('Started RuoYiApplication')) { + if (data.toString().includes('Started Success')) { openAppIfNotOpened(); } }); - springProcess.stderr.on('data', (data) => { - console.error(`SpringBoot ERROR: ${data}`); - const errorStr = data.toString(); - if (errorStr.includes('APPLICATION FAILED TO START') || - errorStr.includes('Port') && errorStr.includes('already in use') || - errorStr.includes('Unable to start embedded Tomcat')) { - app.quit(); - } - }); - springProcess.on('close', (code) => { - console.log(`SpringBoot exited with code ${code}`); mainWindow ? mainWindow.close() : app.quit(); }); } +startSpringBoot(); + function stopSpringBoot() { if (!springProcess) return; try { @@ -78,7 +75,7 @@ function stopSpringBoot() { } } -function createWindow () { +function createWindow() { mainWindow = new BrowserWindow({ width: 1280, height: 800, @@ -111,7 +108,7 @@ function createWindow () { app.whenReady().then(() => { createWindow(); - const { width: sw, height: sh } = screen.getPrimaryDisplay().workAreaSize; + const {width: sw, height: sh} = screen.getPrimaryDisplay().workAreaSize; splashWindow = new BrowserWindow({ width: Math.min(Math.floor(sw * 0.8), 1800), height: Math.min(Math.floor(sh * 0.8), 1200), @@ -128,7 +125,6 @@ app.whenReady().then(() => { splashWindow.loadFile(splashPath); } - setTimeout(() => openAppIfNotOpened(), 1000); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { @@ -184,8 +180,8 @@ WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & } ipcMain.handle('download-update', async (event, downloadUrl: string) => { - if (isDownloading) return { success: false, error: '正在下载中' }; - if (downloadedFilePath === 'completed') return { success: true, filePath: 'already-completed' }; + if (isDownloading) return {success: false, error: '正在下载中'}; + if (downloadedFilePath === 'completed') return {success: true, filePath: 'already-completed'}; isDownloading = true; @@ -212,7 +208,7 @@ ipcMain.handle('download-update', async (event, downloadUrl: string) => { isDownloading = false; }, 1100); - return { success: true, filePath: 'dev-mode-simulated', dev: true }; + return {success: true, filePath: 'dev-mode-simulated', dev: true}; } const tempPath = join(app.getPath('temp'), 'app.asar.new'); @@ -244,22 +240,23 @@ ipcMain.handle('download-update', async (event, downloadUrl: string) => { downloadedFilePath = 'completed'; isDownloading = false; - return { success: true, filePath: updateFilePath }; + return {success: true, filePath: updateFilePath}; } catch (error: unknown) { isDownloading = false; downloadedFilePath = null; const tempPath = join(app.getPath('temp'), 'app.asar.new'); if (existsSync(tempPath)) { - fs.unlink(tempPath).catch(() => {}); + fs.unlink(tempPath).catch(() => { + }); } - return { success: false, error: error instanceof Error ? error.message : '下载失败' }; + return {success: false, error: error instanceof Error ? error.message : '下载失败'}; } }); ipcMain.handle('get-download-progress', () => { - return { ...downloadProgress, isDownloading }; + return {...downloadProgress, isDownloading}; }); ipcMain.handle('install-update', async () => { @@ -268,14 +265,14 @@ ipcMain.handle('install-update', async () => { if (isRealDev) { downloadedFilePath = null; - return { success: true, message: '开发环境模拟重启' }; + return {success: true, message: '开发环境模拟重启'}; } const updateFilePath = join(process.resourcesPath, 'app.asar.update'); const hasUpdateFile = existsSync(updateFilePath); if (!downloadedFilePath || (downloadedFilePath !== 'completed' && !hasUpdateFile)) { - return { success: false, error: '更新文件不存在' }; + return {success: false, error: '更新文件不存在'}; } const appDir = dirname(process.execPath); @@ -283,7 +280,7 @@ ipcMain.handle('install-update', async () => { const appAsarPath = join(process.resourcesPath, 'app.asar'); if (!existsSync(helperPath)) { - return { success: false, error: '更新助手不存在' }; + return {success: false, error: '更新助手不存在'}; } const vbsPath = join(app.getPath('temp'), 'update-install.vbs'); @@ -303,28 +300,28 @@ WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & app.quit(); }, 500); - return { success: true }; + return {success: true}; } catch (error: unknown) { - return { success: false, error: error instanceof Error ? error.message : '重启失败' }; + return {success: false, error: error instanceof Error ? error.message : '重启失败'}; } }); ipcMain.handle('cancel-download', () => { isDownloading = false; - downloadProgress = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' }; + downloadProgress = {percentage: 0, current: '0 MB', total: '0 MB', speed: ''}; downloadedFilePath = null; - return { success: true }; + return {success: true}; }); ipcMain.handle('get-update-status', () => { const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged || process.defaultApp; - return { downloadedFilePath, isDownloading, downloadProgress, isPackaged: app.isPackaged, isDev }; + return {downloadedFilePath, isDownloading, downloadProgress, isPackaged: app.isPackaged, isDev}; }); // 添加文件保存对话框处理器 ipcMain.handle('show-save-dialog', async (event, options) => { if (!mainWindow) { - return { canceled: true }; + return {canceled: true}; } try { @@ -332,14 +329,14 @@ ipcMain.handle('show-save-dialog', async (event, options) => { return result; } catch (error) { console.error('文件保存对话框错误:', error); - return { canceled: true, error: error instanceof Error ? error.message : '对话框打开失败' }; + return {canceled: true, error: error instanceof Error ? error.message : '对话框打开失败'}; } }); // 添加文件夹选择对话框处理器 ipcMain.handle('show-open-dialog', async (event, options) => { if (!mainWindow) { - return { canceled: true }; + return {canceled: true}; } try { @@ -347,7 +344,7 @@ ipcMain.handle('show-open-dialog', async (event, options) => { return result; } catch (error) { console.error('文件夹选择对话框错误:', error); - return { canceled: true, error: error instanceof Error ? error.message : '对话框打开失败' }; + return {canceled: true, error: error instanceof Error ? error.message : '对话框打开失败'}; } }); @@ -377,7 +374,7 @@ async function downloadFile(url: string, filePath: string, onProgress: (progress const elapsed = (Date.now() - startTime) / 1000; const speed = elapsed > 0 ? `${((downloadedBytes / elapsed) / 1024 / 1024).toFixed(1)} MB/s` : ''; - onProgress({ percentage, current, total, speed }); + onProgress({percentage, current, total, speed}); }); response.pipe(fileStream); @@ -388,10 +385,11 @@ async function downloadFile(url: string, filePath: string, onProgress: (progress }); fileStream.on('error', (error) => { - fs.unlink(filePath).catch(() => {}); + fs.unlink(filePath).catch(() => { + }); reject(error); }); }).on('error', reject); }); -} \ No newline at end of file +} diff --git a/electron-vue-template/src/renderer/App.vue b/electron-vue-template/src/renderer/App.vue index a614251..9ea4692 100644 --- a/electron-vue-template/src/renderer/App.vue +++ b/electron-vue-template/src/renderer/App.vue @@ -2,12 +2,9 @@ import {onMounted, ref, computed, defineAsyncComponent, type Component, onUnmounted} from 'vue' import {ElMessage, ElMessageBox} from 'element-plus' import zhCn from 'element-plus/es/locale/lang/zh-cn' -// 图标已移至对应组件 import 'element-plus/dist/index.css' import {authApi} from './api/auth' import {deviceApi, type DeviceItem, type DeviceQuota} from './api/device' -// 面板按需加载,互不影响且可缓存 - const LoginDialog = defineAsyncComponent(() => import('./components/auth/LoginDialog.vue')) const RegisterDialog = defineAsyncComponent(() => import('./components/auth/RegisterDialog.vue')) const NavigationBar = defineAsyncComponent(() => import('./components/layout/NavigationBar.vue')) @@ -147,9 +144,15 @@ async function handleLoginSuccess(data: { token: string; permissions?: string }) // 建立SSE连接 SSEManager.connect() - } catch (e) { - // 设备注册失败不影响登录流程,静默处理 - console.warn('设备注册失败:', e) + } catch (e: any) { + // 设备注册失败时回滚登录状态 + isAuthenticated.value = false + showAuthDialog.value = true + await authApi.deleteTokenCache() + ElMessage({ + message: e?.message || '设备注册失败,请重试', + type: 'error' + }) } } diff --git a/electron-vue-template/src/renderer/api/device.ts b/electron-vue-template/src/renderer/api/device.ts index ff855f2..02c73ab 100644 --- a/electron-vue-template/src/renderer/api/device.ts +++ b/electron-vue-template/src/renderer/api/device.ts @@ -15,37 +15,37 @@ export interface DeviceItem { lastActiveAt?: string } +// 统一处理AjaxResult格式 +function handleAjaxResult(res: any) { + if (res?.code !== 200) { + throw new Error(res?.msg || '操作失败') + } + return res.data +} + export const deviceApi = { - getQuota(username: string) { - return http.get(`${base}/quota`, { username }).then((res: any) => { - if (res && typeof res.limit !== 'undefined') return res as DeviceQuota - if (res && typeof res.code === 'number') return (res.data as DeviceQuota) || { limit: 0, used: 0 } - return (res?.data as DeviceQuota) || { limit: 0, used: 0 } - }) + getQuota(username: string): Promise { + return http.get(`${base}/quota`, { username }).then(handleAjaxResult) }, - list(username: string) { - return http.get(`${base}/list`, { username }).then((res: any) => { - if (Array.isArray(res)) return res as DeviceItem[] - if (res && typeof res.code === 'number') return (res.data as DeviceItem[]) || [] - return (res?.data as DeviceItem[]) || [] - }) + list(username: string): Promise { + return http.get(`${base}/list`, { username }).then(handleAjaxResult) }, register(payload: { username: string }) { - return http.post(`${base}/register`, payload) + return http.post(`${base}/register`, payload).then(handleAjaxResult) }, remove(payload: { deviceId: string }) { - return http.postVoid(`${base}/remove`, payload) + return http.post(`${base}/remove`, payload).then(handleAjaxResult) }, heartbeat(payload: { username: string; deviceId: string; version?: string }) { - return http.postVoid(`${base}/heartbeat`, payload) + return http.post(`${base}/heartbeat`, payload).then(handleAjaxResult) }, offline(payload: { deviceId: string }) { - return http.postVoid(`${base}/offline`, payload) + return http.post(`${base}/offline`, payload).then(handleAjaxResult) }, } diff --git a/electron-vue-template/src/renderer/components/auth/LoginDialog.vue b/electron-vue-template/src/renderer/components/auth/LoginDialog.vue index 293a23d..e8ba3ee 100644 --- a/electron-vue-template/src/renderer/components/auth/LoginDialog.vue +++ b/electron-vue-template/src/renderer/components/auth/LoginDialog.vue @@ -3,6 +3,7 @@ import { ref, computed } from 'vue' import { ElMessage } from 'element-plus' import { User } from '@element-plus/icons-vue' import { authApi } from '../../api/auth' +import { deviceApi } from '../../api/device' interface Props { modelValue: boolean @@ -30,6 +31,10 @@ async function handleAuth() { authLoading.value = true try { + // 1. 先检查设备限制 + await deviceApi.register({ username: authForm.value.username }) + + // 2. 设备检查通过,进行登录 const data = await authApi.login(authForm.value) emit('loginSuccess', { token: data.token, diff --git a/electron-vue-template/src/renderer/main.ts b/electron-vue-template/src/renderer/main.ts index e3b2366..c32621c 100644 --- a/electron-vue-template/src/renderer/main.ts +++ b/electron-vue-template/src/renderer/main.ts @@ -4,7 +4,6 @@ import 'element-plus/dist/index.css' import ElementPlus from 'element-plus' import zhCn from 'element-plus/es/locale/lang/zh-cn' import App from './App.vue' - const app = createApp(App) app.use(ElementPlus, { locale: zhCn, diff --git a/erp_client_sb/src/main/java/com/tashow/erp/ErpClientSbApplication.java b/erp_client_sb/src/main/java/com/tashow/erp/ErpClientSbApplication.java index 9675cd2..3cc8a18 100644 --- a/erp_client_sb/src/main/java/com/tashow/erp/ErpClientSbApplication.java +++ b/erp_client_sb/src/main/java/com/tashow/erp/ErpClientSbApplication.java @@ -12,7 +12,6 @@ import org.springframework.context.ConfigurableApplicationContext; public class ErpClientSbApplication { public static void main(String[] args) { - // 纯 Spring Boot 启动,不再依赖 JavaFX ConfigurableApplicationContext applicationContext = SpringApplication.run(ErpClientSbApplication.class, args); try { ErrorReporter errorReporter = applicationContext.getBean(ErrorReporter.class); @@ -20,12 +19,11 @@ public class ErpClientSbApplication { log.error("捕获到未处理异常: " + ex.getMessage(), ex); errorReporter.reportSystemError("未捕获异常: " + thread.getName(), (Exception) ex); }); - log.info("全局异常处理器已设置"); + log.info("Started Success"); } catch (Exception e) { log.warn("未设置 ErrorReporter,继续启动: {}", e.getMessage()); } - // 如需预加载资源,可按需保留 try { ResourcePreloader.init(); ResourcePreloader.preloadErpDashboard(); diff --git a/erp_client_sb/src/main/java/com/tashow/erp/controller/DeviceProxyController.java b/erp_client_sb/src/main/java/com/tashow/erp/controller/DeviceProxyController.java index 1affdcb..1bb336d 100644 --- a/erp_client_sb/src/main/java/com/tashow/erp/controller/DeviceProxyController.java +++ b/erp_client_sb/src/main/java/com/tashow/erp/controller/DeviceProxyController.java @@ -1,9 +1,7 @@ package com.tashow.erp.controller; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; -import org.springframework.web.client.RestTemplate; import com.tashow.erp.utils.ApiForwarder; import com.tashow.erp.utils.DeviceUtils; import java.util.Map; @@ -16,12 +14,6 @@ import java.util.HashMap; @RestController public class DeviceProxyController { - @Autowired - private RestTemplate restTemplate; - - @Value("${api.server.base-url}") - private String serverBaseUrl; - /** * 注册设备 */ @@ -34,9 +26,6 @@ public class DeviceProxyController { deviceData.put("deviceId", DeviceUtils.generateDeviceId()); return apiForwarder.post("/monitor/device/register", deviceData, auth); } - - - @PostMapping("/api/device/remove") public ResponseEntity deviceRemove(@RequestBody Map body, @RequestHeader(value = "Authorization", required = false) String auth) { return apiForwarder.post("/monitor/device/remove", body, auth); diff --git a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java index bbd8cbf..41ce7c6 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java @@ -1,9 +1,7 @@ package com.ruoyi; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; /**