This commit is contained in:
2025-09-27 17:41:43 +08:00
parent fe3e24b945
commit 96b396500e
10 changed files with 76 additions and 84 deletions

View File

@@ -201,7 +201,9 @@
"Bash(cnpm install:*)", "Bash(cnpm install:*)",
"Bash(cnpm uninstall:*)", "Bash(cnpm uninstall:*)",
"WebFetch(domain:www.electronjs.org)", "WebFetch(domain:www.electronjs.org)",
"Bash(test:*)" "Bash(test:*)",
"Bash(sqlite3:*)",
"Bash(npx electron:*)"
], ],
"deny": [], "deny": [],
"ask": [], "ask": [],

View File

@@ -1,5 +1,5 @@
import {app, BrowserWindow, ipcMain, Menu, screen, dialog} from 'electron'; 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 {join, dirname} from 'path';
import {spawn, ChildProcessWithoutNullStreams} from 'child_process'; import {spawn, ChildProcessWithoutNullStreams} from 'child_process';
import * as https from 'https'; import * as https from 'https';
@@ -17,10 +17,19 @@ let downloadedFilePath: string | null = null;
function openAppIfNotOpened() { function openAppIfNotOpened() {
if (appOpened) return; if (appOpened) return;
appOpened = true; appOpened = true;
// SpringBoot 启动完成,现在加载前端页面
if (mainWindow) { 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.show();
mainWindow.focus(); mainWindow.focus();
} }
if (splashWindow) { if (splashWindow) {
splashWindow.close(); splashWindow.close();
splashWindow = null; splashWindow = null;
@@ -28,36 +37,24 @@ function openAppIfNotOpened() {
} }
function startSpringBoot() { 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], { springProcess = spawn('java', ['-jar', jarPath], {
cwd: dirname(jarPath), cwd: dirname(jarPath),
detached: false detached: false
}); });
springProcess.stdout.on('data', (data) => { springProcess.stdout.on('data', (data) => {
console.log(`SpringBoot: ${data}`); if (data.toString().includes('Started Success')) {
if (data.toString().includes('Started RuoYiApplication')) {
openAppIfNotOpened(); 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) => { springProcess.on('close', (code) => {
console.log(`SpringBoot exited with code ${code}`);
mainWindow ? mainWindow.close() : app.quit(); mainWindow ? mainWindow.close() : app.quit();
}); });
} }
startSpringBoot();
function stopSpringBoot() { function stopSpringBoot() {
if (!springProcess) return; if (!springProcess) return;
try { try {
@@ -128,7 +125,6 @@ app.whenReady().then(() => {
splashWindow.loadFile(splashPath); splashWindow.loadFile(splashPath);
} }
setTimeout(() => openAppIfNotOpened(), 1000);
app.on('activate', () => { app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) { if (BrowserWindow.getAllWindows().length === 0) {
@@ -251,7 +247,8 @@ ipcMain.handle('download-update', async (event, downloadUrl: string) => {
const tempPath = join(app.getPath('temp'), 'app.asar.new'); const tempPath = join(app.getPath('temp'), 'app.asar.new');
if (existsSync(tempPath)) { 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 : '下载失败'};
@@ -388,7 +385,8 @@ async function downloadFile(url: string, filePath: string, onProgress: (progress
}); });
fileStream.on('error', (error) => { fileStream.on('error', (error) => {
fs.unlink(filePath).catch(() => {}); fs.unlink(filePath).catch(() => {
});
reject(error); reject(error);
}); });

View File

@@ -2,12 +2,9 @@
import {onMounted, ref, computed, defineAsyncComponent, type Component, onUnmounted} from 'vue' import {onMounted, ref, computed, defineAsyncComponent, type Component, onUnmounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus' import {ElMessage, ElMessageBox} from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn' import zhCn from 'element-plus/es/locale/lang/zh-cn'
// 图标已移至对应组件
import 'element-plus/dist/index.css' import 'element-plus/dist/index.css'
import {authApi} from './api/auth' import {authApi} from './api/auth'
import {deviceApi, type DeviceItem, type DeviceQuota} from './api/device' import {deviceApi, type DeviceItem, type DeviceQuota} from './api/device'
// 面板按需加载,互不影响且可缓存
const LoginDialog = defineAsyncComponent(() => import('./components/auth/LoginDialog.vue')) const LoginDialog = defineAsyncComponent(() => import('./components/auth/LoginDialog.vue'))
const RegisterDialog = defineAsyncComponent(() => import('./components/auth/RegisterDialog.vue')) const RegisterDialog = defineAsyncComponent(() => import('./components/auth/RegisterDialog.vue'))
const NavigationBar = defineAsyncComponent(() => import('./components/layout/NavigationBar.vue')) const NavigationBar = defineAsyncComponent(() => import('./components/layout/NavigationBar.vue'))
@@ -147,9 +144,15 @@ async function handleLoginSuccess(data: { token: string; permissions?: string })
// 建立SSE连接 // 建立SSE连接
SSEManager.connect() SSEManager.connect()
} catch (e) { } catch (e: any) {
// 设备注册失败不影响登录流程,静默处理 // 设备注册失败时回滚登录状态
console.warn('设备注册失败:', e) isAuthenticated.value = false
showAuthDialog.value = true
await authApi.deleteTokenCache()
ElMessage({
message: e?.message || '设备注册失败,请重试',
type: 'error'
})
} }
} }

View File

@@ -15,37 +15,37 @@ export interface DeviceItem {
lastActiveAt?: string lastActiveAt?: string
} }
// 统一处理AjaxResult格式
function handleAjaxResult(res: any) {
if (res?.code !== 200) {
throw new Error(res?.msg || '操作失败')
}
return res.data
}
export const deviceApi = { export const deviceApi = {
getQuota(username: string) { getQuota(username: string): Promise<DeviceQuota> {
return http.get<DeviceQuota | any>(`${base}/quota`, { username }).then((res: any) => { return http.get(`${base}/quota`, { username }).then(handleAjaxResult)
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 }
})
}, },
list(username: string) { list(username: string): Promise<DeviceItem[]> {
return http.get<DeviceItem[] | any>(`${base}/list`, { username }).then((res: any) => { return http.get(`${base}/list`, { username }).then(handleAjaxResult)
if (Array.isArray(res)) return res as DeviceItem[]
if (res && typeof res.code === 'number') return (res.data as DeviceItem[]) || []
return (res?.data as DeviceItem[]) || []
})
}, },
register(payload: { username: string }) { register(payload: { username: string }) {
return http.post(`${base}/register`, payload) return http.post(`${base}/register`, payload).then(handleAjaxResult)
}, },
remove(payload: { deviceId: string }) { 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 }) { 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 }) { offline(payload: { deviceId: string }) {
return http.postVoid(`${base}/offline`, payload) return http.post(`${base}/offline`, payload).then(handleAjaxResult)
}, },
} }

View File

@@ -3,6 +3,7 @@ import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue' import { User } from '@element-plus/icons-vue'
import { authApi } from '../../api/auth' import { authApi } from '../../api/auth'
import { deviceApi } from '../../api/device'
interface Props { interface Props {
modelValue: boolean modelValue: boolean
@@ -30,6 +31,10 @@ async function handleAuth() {
authLoading.value = true authLoading.value = true
try { try {
// 1. 先检查设备限制
await deviceApi.register({ username: authForm.value.username })
// 2. 设备检查通过,进行登录
const data = await authApi.login(authForm.value) const data = await authApi.login(authForm.value)
emit('loginSuccess', { emit('loginSuccess', {
token: data.token, token: data.token,

View File

@@ -4,7 +4,6 @@ import 'element-plus/dist/index.css'
import ElementPlus from 'element-plus' import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn' import zhCn from 'element-plus/es/locale/lang/zh-cn'
import App from './App.vue' import App from './App.vue'
const app = createApp(App) const app = createApp(App)
app.use(ElementPlus, { app.use(ElementPlus, {
locale: zhCn, locale: zhCn,

View File

@@ -12,7 +12,6 @@ import org.springframework.context.ConfigurableApplicationContext;
public class ErpClientSbApplication { public class ErpClientSbApplication {
public static void main(String[] args) { public static void main(String[] args) {
// 纯 Spring Boot 启动,不再依赖 JavaFX
ConfigurableApplicationContext applicationContext = SpringApplication.run(ErpClientSbApplication.class, args); ConfigurableApplicationContext applicationContext = SpringApplication.run(ErpClientSbApplication.class, args);
try { try {
ErrorReporter errorReporter = applicationContext.getBean(ErrorReporter.class); ErrorReporter errorReporter = applicationContext.getBean(ErrorReporter.class);
@@ -20,12 +19,11 @@ public class ErpClientSbApplication {
log.error("捕获到未处理异常: " + ex.getMessage(), ex); log.error("捕获到未处理异常: " + ex.getMessage(), ex);
errorReporter.reportSystemError("未捕获异常: " + thread.getName(), (Exception) ex); errorReporter.reportSystemError("未捕获异常: " + thread.getName(), (Exception) ex);
}); });
log.info("全局异常处理器已设置"); log.info("Started Success");
} catch (Exception e) { } catch (Exception e) {
log.warn("未设置 ErrorReporter继续启动: {}", e.getMessage()); log.warn("未设置 ErrorReporter继续启动: {}", e.getMessage());
} }
// 如需预加载资源,可按需保留
try { try {
ResourcePreloader.init(); ResourcePreloader.init();
ResourcePreloader.preloadErpDashboard(); ResourcePreloader.preloadErpDashboard();

View File

@@ -1,9 +1,7 @@
package com.tashow.erp.controller; package com.tashow.erp.controller;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*; import org.springframework.http.*;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import com.tashow.erp.utils.ApiForwarder; import com.tashow.erp.utils.ApiForwarder;
import com.tashow.erp.utils.DeviceUtils; import com.tashow.erp.utils.DeviceUtils;
import java.util.Map; import java.util.Map;
@@ -16,12 +14,6 @@ import java.util.HashMap;
@RestController @RestController
public class DeviceProxyController { 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()); deviceData.put("deviceId", DeviceUtils.generateDeviceId());
return apiForwarder.post("/monitor/device/register", deviceData, auth); return apiForwarder.post("/monitor/device/register", deviceData, auth);
} }
@PostMapping("/api/device/remove") @PostMapping("/api/device/remove")
public ResponseEntity<?> deviceRemove(@RequestBody Map<String, Object> body, @RequestHeader(value = "Authorization", required = false) String auth) { public ResponseEntity<?> deviceRemove(@RequestBody Map<String, Object> body, @RequestHeader(value = "Authorization", required = false) String auth) {
return apiForwarder.post("/monitor/device/remove", body, auth); return apiForwarder.post("/monitor/device/remove", body, auth);

View File

@@ -1,9 +1,7 @@
package com.ruoyi; package com.ruoyi;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
/** /**