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