Compare commits
102 Commits
c384513273
...
1.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
baa7622954 | ||
|
|
851c2ce634 | ||
|
|
64349125ba | ||
|
|
a020ee537d | ||
|
|
351e9a92bc | ||
|
|
f5514dd721 | ||
|
|
b94640ca81 | ||
|
|
b8163d7d4f | ||
|
|
569c8e8ecc | ||
|
|
21bb8ef79c | ||
|
|
fbcc656b99 | ||
|
|
3854c0f048 | ||
|
|
7bc6daf1b7 | ||
|
|
db44618ee5 | ||
|
|
2d17a6b792 | ||
|
|
e8aa7d21a8 | ||
|
|
defeb01808 | ||
|
|
b289fb9624 | ||
|
|
103effcfca | ||
|
|
975bee6ce8 | ||
|
|
6a2fba0e57 | ||
|
|
9248be6310 | ||
|
|
ad8b3deb00 | ||
|
|
cccc4e4c8c | ||
|
|
9e577a2226 | ||
|
|
715dfb4d71 | ||
|
|
a25ffd75c5 | ||
|
|
8eaba79c26 | ||
|
|
05a44bb464 | ||
|
|
77fabf2018 | ||
|
|
13187ddce1 | ||
|
|
33b17e278d | ||
|
|
bcfe0eecca | ||
|
|
9a640b96e6 | ||
|
|
5b4d7fab49 | ||
|
|
72d8d981b1 | ||
|
|
d1f2f40123 | ||
|
|
545048045d | ||
|
|
62e1647eaf | ||
|
|
fba2c73782 | ||
|
|
c4fff84848 | ||
|
|
57c3452d82 | ||
|
|
f412e0e72c | ||
|
|
6df16898da | ||
|
|
5e6898fb40 | ||
|
|
f45d3df385 | ||
|
|
8f3e5273e2 | ||
|
|
616e2b31a5 | ||
|
|
b3abad7fae | ||
|
|
9d15f7aca9 | ||
|
|
310d5e462f | ||
|
|
c4bacdaf2a | ||
|
|
54a82200b6 | ||
|
|
2d6838c0e7 | ||
|
|
73b8f2409a | ||
|
|
c7c192a703 | ||
|
|
42bd6dcb8a | ||
|
|
e4a92e9be4 | ||
|
|
6f19890a84 | ||
|
|
1ee33672dd | ||
|
|
8e0c37bf74 | ||
|
|
c13be9e19a | ||
|
|
48f1f51d76 | ||
|
|
5977254180 | ||
|
|
3d2127b660 | ||
|
|
7db7f513be | ||
|
|
a906f34ac2 | ||
|
|
224a42e44b | ||
|
|
7d2cf934f8 | ||
|
|
49ac29e70c | ||
|
|
dc01896d8b | ||
|
|
ba64c27457 | ||
|
|
921ca15be6 | ||
|
|
121d49bfe8 | ||
|
|
0783bc037c | ||
|
|
d855b3f84d | ||
|
|
e0d7559cf7 | ||
|
|
302018f631 | ||
|
|
e49191d531 | ||
|
|
2dea1f9556 | ||
|
|
4494351e52 | ||
|
|
9e1b5530ea | ||
|
|
743d830b0d | ||
|
|
dcd3c6a571 | ||
|
|
9939201ca1 | ||
|
|
fed76b4fe0 | ||
|
|
bfa2445c76 | ||
|
|
b62ae10650 | ||
|
|
974eaac6dd | ||
|
|
2f5dc7607d | ||
|
|
a06276127d | ||
|
|
29cb79abfd | ||
|
|
dc3d577f6f | ||
|
|
50041d2a7b | ||
|
|
9833552652 | ||
|
|
8dbdf6f394 | ||
|
|
c61776a1ff | ||
|
|
88c8c256e2 | ||
|
|
5497e86b58 | ||
|
|
63ea81e0d6 | ||
|
|
abe51d17fa | ||
|
|
240e3838ba |
35
.env.example
35
.env.example
@@ -1,35 +0,0 @@
|
||||
# ERP System Configuration
|
||||
ERP_URL=https://your-erp-system.com
|
||||
ERP_USERNAME=your_username
|
||||
ERP_PASSWORD=your_password
|
||||
|
||||
# Additional ERP Settings
|
||||
ERP_HEADLESS=true
|
||||
ERP_IGNORE_HTTPS_ERRORS=true
|
||||
ERP_AUTO_CLOSE_BROWSER=true
|
||||
|
||||
# Database Configuration - SQL Server
|
||||
SQL_SERVER_HOST=localhost
|
||||
SQL_SERVER_PORT=1433
|
||||
SQL_SERVER_DATABASE=erp_db
|
||||
SQL_SERVER_USERNAME=sa
|
||||
SQL_SERVER_PASSWORD=your_password
|
||||
|
||||
MYSQL_HOST=localhost
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_DATABASE=erp_db
|
||||
MYSQL_USERNAME=root
|
||||
MYSQL_PASSWORD=your_password
|
||||
|
||||
# Application Settings
|
||||
LOG_LEVEL=info
|
||||
DOWNLOAD_DIR=./downloads
|
||||
TEMP_DIR=./temp
|
||||
|
||||
# Legacy configurations (if needed)
|
||||
DB_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||
DB_TRUST_SERVER_CERTIFICATE=yes
|
||||
DB_TYPE=mysql
|
||||
DB_MYSQL_HOST=192.168.31.83
|
||||
DB_MYSQL_PORT=3306
|
||||
DB_MYSQL_CHARSET=utf8mb4
|
||||
18
.gitattributes
vendored
Normal file
18
.gitattributes
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
* text=auto
|
||||
|
||||
# Force Unix line endings for source files
|
||||
*.md text eol=lf
|
||||
*.ts text eol=lf
|
||||
*.js text eol=lf
|
||||
*.json text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.yaml text eol=lf
|
||||
*.tsx text eol=lf
|
||||
*.jsx text eol=lf
|
||||
*.css text eol=lf
|
||||
*.scss text eol=lf
|
||||
*.html text eol=lf
|
||||
|
||||
# Force Windows line endings for build artifacts
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
18
.gitignore
vendored
18
.gitignore
vendored
@@ -4,6 +4,7 @@ out
|
||||
.DS_Store
|
||||
.eslintcache
|
||||
*.log*
|
||||
.npmrc
|
||||
|
||||
# AI Agent
|
||||
.claude
|
||||
@@ -25,4 +26,19 @@ test-*.js
|
||||
compare_*.js
|
||||
|
||||
# logs
|
||||
logs
|
||||
logs
|
||||
|
||||
# oh my opencode
|
||||
.sisyphus
|
||||
|
||||
# Runtime config files
|
||||
*.yaml
|
||||
*.yaml.backup
|
||||
# But keep config.template.yaml
|
||||
!config.template.yaml
|
||||
|
||||
# nul
|
||||
nul
|
||||
|
||||
# TypeScript incremental compilation cache
|
||||
*.tsbuildinfo
|
||||
176
BROWSER_DEPLOYMENT.md
Normal file
176
BROWSER_DEPLOYMENT.md
Normal file
@@ -0,0 +1,176 @@
|
||||
# Playwright 浏览器部署指南
|
||||
|
||||
## 概述
|
||||
|
||||
本文档为开发人员提供 ERPAuto 应用程序中 Playwright Chromium 浏览器的部署指南。文档说明如何将浏览器文件从开发机复制到目标用户机器,确保应用程序能够正常运行浏览器自动化任务。
|
||||
|
||||
**重要提示**:部署前请先阅读 [BROWSER_VERSIONS.md](./BROWSER_VERSIONS.md) 了解版本信息。
|
||||
|
||||
## 目标路径
|
||||
|
||||
浏览器文件必须部署在以下路径:
|
||||
|
||||
```
|
||||
%APPDATA%\erpauto\ms-playwright\chromium-1208\
|
||||
```
|
||||
|
||||
完整展开路径示例(Windows):
|
||||
|
||||
```
|
||||
C:\Users\<用户名>\AppData\Roaming\erpauto\ms-playwright\chromium-1208\
|
||||
```
|
||||
|
||||
## 目录结构
|
||||
|
||||
部署完成后,目标目录结构应如下所示:
|
||||
|
||||
```
|
||||
%APPDATA%\erpauto\ms-playwright\
|
||||
└── chromium-1208/
|
||||
└── chrome-win/
|
||||
├── chrome.exe # 浏览器可执行文件
|
||||
├── chrome_dll.dll
|
||||
├── resources/
|
||||
├── locales/
|
||||
└── ... # 其他浏览器文件
|
||||
```
|
||||
|
||||
**关键文件**:`chrome-win/chrome.exe` 必须存在,否则浏览器无法启动。
|
||||
|
||||
## 部署步骤
|
||||
|
||||
### 步骤 1:在开发机上准备
|
||||
|
||||
1. 确保开发机已安装正确版本的 Playwright:
|
||||
|
||||
```bash
|
||||
npm install playwright@1.58.2
|
||||
```
|
||||
|
||||
2. 下载 Chromium 浏览器:
|
||||
|
||||
```bash
|
||||
npx playwright install chromium
|
||||
```
|
||||
|
||||
3. 定位开发机上的浏览器缓存目录:
|
||||
|
||||
```
|
||||
C:\Users\<开发机用户名>\AppData\Local\ms-playwright\chromium-1208
|
||||
```
|
||||
|
||||
### 步骤 2:复制文件
|
||||
|
||||
1. **复制整个浏览器目录**
|
||||
- 将开发机上的 `chromium-1208` 目录完整复制
|
||||
- 不要只复制部分文件,确保所有子目录和文件都包含在内
|
||||
|
||||
2. **粘贴到目标路径**
|
||||
- 在目标机器上创建目录:`%APPDATA%\erpauto\ms-playwright\`
|
||||
- 将 `chromium-1208` 目录粘贴到该路径下
|
||||
|
||||
3. **验证文件完整性**
|
||||
- 确认目标路径存在:`%APPDATA%\erpauto\ms-playwright\chromium-1208\chrome-win\chrome.exe`
|
||||
- 检查文件大小约为 280MB
|
||||
|
||||
### 步骤 3:配置环境变量(可选)
|
||||
|
||||
如需确保应用程序使用正确的浏览器路径,可设置以下环境变量:
|
||||
|
||||
```batch
|
||||
set PLAYWRIGHT_BROWSERS_PATH=%APPDATA%\erpauto\ms-playwright
|
||||
```
|
||||
|
||||
或在应用程序代码中设置:
|
||||
|
||||
```javascript
|
||||
process.env.PLAYWRIGHT_BROWSERS_PATH = path.join(app.getPath('userData'), 'ms-playwright')
|
||||
```
|
||||
|
||||
## 验证步骤
|
||||
|
||||
部署完成后,执行以下验证步骤:
|
||||
|
||||
### 验证 1:检查目录结构
|
||||
|
||||
在目标机器上运行:
|
||||
|
||||
```batch
|
||||
dir %APPDATA%\erpauto\ms-playwright\chromium-1208\chrome-win\chrome.exe
|
||||
```
|
||||
|
||||
应显示文件存在。
|
||||
|
||||
### 验证 2:启动浏览器测试
|
||||
|
||||
运行 ERPAuto 应用程序,执行以下操作:
|
||||
|
||||
1. 登录应用程序
|
||||
2. 进入「数据提取」页面
|
||||
3. 输入一个有效订单号
|
||||
4. 点击「开始提取」
|
||||
5. 观察浏览器是否正常启动并执行任务
|
||||
|
||||
### 验证 3:检查日志
|
||||
|
||||
查看应用程序日志,确认没有浏览器相关的错误信息:
|
||||
|
||||
- 无 "browser not found" 错误
|
||||
- 无 "chromium revision not found" 错误
|
||||
- 无 "PLAYWRIGHT_BROWSERS_PATH" 相关警告
|
||||
|
||||
## 故障排查
|
||||
|
||||
### 问题 1:浏览器无法启动
|
||||
|
||||
**症状**:应用程序报错,提示找不到浏览器或启动失败。
|
||||
|
||||
**解决方案**:
|
||||
|
||||
1. 确认修订号匹配(必须是 1208)
|
||||
2. 检查 `chrome-win/chrome.exe` 文件是否存在
|
||||
3. 验证 `PLAYWRIGHT_BROWSERS_PATH` 环境变量设置正确
|
||||
4. 确认目标机器具有相同的 Playwright 版本(1.58.2)
|
||||
|
||||
### 问题 2:版本不匹配错误
|
||||
|
||||
**症状**:应用程序启动时报出版本冲突错误。
|
||||
|
||||
**解决方案**:
|
||||
|
||||
1. 检查 `package.json` 中的 Playwright 版本是否为 1.58.2
|
||||
2. 确认复制的 Chromium 修订号为 1208
|
||||
3. 参考 [BROWSER_VERSIONS.md](./BROWSER_VERSIONS.md) 核对所有版本信息
|
||||
|
||||
### 问题 3:权限不足
|
||||
|
||||
**症状**:无法写入或读取浏览器目录。
|
||||
|
||||
**解决方案**:
|
||||
|
||||
1. 确保目标目录具有适当的读写权限
|
||||
2. 以管理员身份运行应用程序进行测试
|
||||
3. 检查防病毒软件是否阻止了浏览器执行
|
||||
|
||||
### 问题 4:路径错误
|
||||
|
||||
**症状**:应用程序在错误的位置查找浏览器文件。
|
||||
|
||||
**解决方案**:
|
||||
|
||||
1. 确认 `%APPDATA%` 环境变量指向正确的用户目录
|
||||
2. 检查应用程序是否正确解析了 `userData` 路径
|
||||
3. 在代码中硬编码浏览器路径进行调试
|
||||
|
||||
## 注意事项
|
||||
|
||||
- **仅部署 Chromium**:ERPAuto 只需要 Chromium 浏览器,不需要 Firefox 或 WebKit
|
||||
- **版本一致性**:开发机和目标机器的 Playwright 版本必须一致
|
||||
- **修订号匹配**:Chromium 修订号(1208)必须完全匹配,否则可能出现兼容性问题
|
||||
- **文件完整性**:复制时确保所有文件完整,损坏的浏览器文件会导致启动失败
|
||||
- **网络隔离环境**:目标机器如果无法访问互联网,必须提前部署浏览器文件,因为无法自动下载
|
||||
|
||||
## 参考文档
|
||||
|
||||
- [BROWSER_VERSIONS.md](./BROWSER_VERSIONS.md) - 版本信息和目录结构详情
|
||||
- [README.md](./README.md) - 项目总体说明
|
||||
96
BROWSER_VERSIONS.md
Normal file
96
BROWSER_VERSIONS.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# Playwright 浏览器版本信息
|
||||
|
||||
本文档记录 ERPAuto 项目使用的 Playwright 浏览器版本和部署信息。
|
||||
|
||||
## 版本信息
|
||||
|
||||
| 组件 | 版本号 |
|
||||
| --------------- | ------------ |
|
||||
| Playwright | 1.58.2 |
|
||||
| Chromium | 145.0.7632.6 |
|
||||
| Chromium 修订号 | 1208 |
|
||||
|
||||
## 浏览器目录结构
|
||||
|
||||
Playwright 将浏览器文件缓存在以下位置:
|
||||
|
||||
### Windows 开发环境
|
||||
|
||||
```
|
||||
C:\Users\<用户名>\AppData\Local\ms-playwright\
|
||||
└── chromium-1208/
|
||||
└── chrome-win/
|
||||
├── chrome.exe
|
||||
└── ...
|
||||
```
|
||||
|
||||
### 目标部署环境
|
||||
|
||||
```
|
||||
%APPDATA%\erpauto\ms-playwright\
|
||||
└── chromium-1208/
|
||||
└── chrome-win/
|
||||
├── chrome.exe
|
||||
└── ...
|
||||
```
|
||||
|
||||
## 部署指南
|
||||
|
||||
### 开发环境准备
|
||||
|
||||
1. 安装 Playwright 1.58.2
|
||||
|
||||
```bash
|
||||
npm install playwright@1.58.2
|
||||
```
|
||||
|
||||
2. 下载 Chromium 浏览器
|
||||
```bash
|
||||
npx playwright install chromium
|
||||
```
|
||||
|
||||
### 浏览器文件复制步骤
|
||||
|
||||
1. **定位源目录**
|
||||
- 开发机上找到 Playwright 浏览器缓存目录
|
||||
- 默认路径:`C:\Users\<用户名>\AppData\Local\ms-playwright\chromium-1208`
|
||||
|
||||
2. **复制浏览器文件**
|
||||
- 将整个 `chromium-1208` 目录复制到部署目标
|
||||
- 目标路径:`%APPDATA%\erpauto\ms-playwright\chromium-1208`
|
||||
|
||||
3. **验证目录结构**
|
||||
- 确认目标路径包含 `chrome-win/chrome.exe`
|
||||
- 确保所有子文件完整复制
|
||||
|
||||
### 环境变量配置
|
||||
|
||||
如需要自定义浏览器路径,可设置环境变量:
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
set PLAYWRIGHT_BROWSERS_PATH=%APPDATA%\erpauto\ms-playwright
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 仅包含 Chromium 浏览器(Firefox 和 WebKit 不需要)
|
||||
- 浏览器文件体积约为 280MB
|
||||
- 部署时确保目标机器具有相同的 Playwright 版本(1.58.2)
|
||||
- 修订号必须匹配(1208),否则可能出现兼容性问题
|
||||
|
||||
## 故障排查
|
||||
|
||||
### 浏览器无法启动
|
||||
|
||||
1. 检查修订号是否匹配(1208)
|
||||
2. 确认 `chrome-win/chrome.exe` 文件存在
|
||||
3. 验证 PLAYWRIGHT_BROWSERS_PATH 环境变量设置
|
||||
|
||||
### 版本不匹配错误
|
||||
|
||||
确保以下版本一致:
|
||||
|
||||
- package.json 中的 Playwright 版本
|
||||
- 下载的 Chromium 修订号
|
||||
- browsers.json 中定义版本号
|
||||
22
CLAUDE.md
22
CLAUDE.md
@@ -10,8 +10,6 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
npm run dev # Start development server with hot reload
|
||||
npm run build # Full build with type checking
|
||||
npm run build:win # Build Windows executable
|
||||
npm run build:mac # Build macOS DMG
|
||||
npm run build:linux # Build Linux AppImage
|
||||
```
|
||||
|
||||
### Code Quality
|
||||
@@ -44,7 +42,7 @@ ERPAuto is an **Electron desktop application** for automating ERP system data pr
|
||||
- Node.js environment managing application lifecycle
|
||||
- Entry point: `src/main/index.ts`
|
||||
- Registers all IPC handlers via `registerIpcHandlers()`
|
||||
- Loads environment variables from `.env` at startup
|
||||
- Loads configuration from `config.yaml` via ConfigManager at startup
|
||||
|
||||
2. **Preload Script** (`src/preload/`)
|
||||
- Security bridge between main and renderer processes
|
||||
@@ -113,13 +111,23 @@ Admin users see logout buttons and can access user switching. Non-admin users ha
|
||||
- `@services` → `src/main/services` (main process, tests only)
|
||||
- `@types` → `src/main/types` (main process, tests only)
|
||||
|
||||
## Environment Configuration
|
||||
## Configuration Management
|
||||
|
||||
The application requires a `.env` file in the project root. Reference `.env.example` for the full structure. Key configurations:
|
||||
The application uses a YAML-based configuration system (`config.yaml`) managed by `ConfigManager`:
|
||||
|
||||
- **ERP Settings**: URL, credentials, headless mode, HTTPS error handling
|
||||
- **Development**: `config.yaml` in project root (easy to edit and version control)
|
||||
- **Production**: `config.yaml` in user data directory (AppData on Windows)
|
||||
|
||||
Key configurations in `config.yaml`:
|
||||
|
||||
- **ERP Settings**: URL (fixed infrastructure)
|
||||
- **Database**: MySQL and SQL Server connection configs (dual support)
|
||||
- **App Settings**: Log level, download/temp directories
|
||||
- **Paths**: Data directory and output file settings
|
||||
- **Extraction**: Batch size, verbosity, persistence options
|
||||
- **Validation**: Data source, batch size, match mode
|
||||
- **Order Resolution**: Database table and field names for order number lookup
|
||||
|
||||
Note: ERP credentials (username/password) are stored in the database (`dbo_BIPUsers` table) per user, managed via the Settings UI.
|
||||
|
||||
## Key Technologies
|
||||
|
||||
|
||||
101
PLAYWRIGHT_DEPLOYMENT.md
Normal file
101
PLAYWRIGHT_DEPLOYMENT.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# Playwright 部署说明
|
||||
|
||||
## 浏览器路径问题修复
|
||||
|
||||
### 问题描述
|
||||
|
||||
应用启动时提示"浏览器文件未找到",但浏览器文件已经放置在正确路径下。
|
||||
|
||||
**原因**:Playwright 1.48+ 改变了浏览器目录命名规则:
|
||||
|
||||
- **旧格式**:`chromium-win32/chrome.exe`
|
||||
- **新格式**:`chromium-1208/chrome-win64/chrome.exe`(revision 号可能不同)
|
||||
|
||||
### 解决方案
|
||||
|
||||
代码已更新为自动检测新旧两种格式,并显示当前目录内容以便调试。
|
||||
|
||||
## 快速部署
|
||||
|
||||
### 方法 1:使用 Playwright CLI(推荐)
|
||||
|
||||
```bash
|
||||
# 在应用目录运行
|
||||
npx playwright install chromium
|
||||
```
|
||||
|
||||
浏览器会自动下载并安装到正确位置:
|
||||
|
||||
- **用户数据目录**:`%APPDATA%\erpauto\ms-playwright\`
|
||||
- **完整路径**:`C:\Users\pengq\AppData\Roaming\erpauto\ms-playwright\chromium-<revision>\chrome-win64\chrome.exe`
|
||||
|
||||
### 方法 2:手动复制
|
||||
|
||||
如果你已经有 Playwright 浏览器文件,可以复制到应用的用户数据目录:
|
||||
|
||||
1. 找到现有浏览器文件(通常在 `%USERPROFILE%\AppData\Local\ms-playwright`)
|
||||
2. 复制到 `%APPDATA%\erpauto\ms-playwright\`
|
||||
3. 确保目录结构正确:
|
||||
```
|
||||
ms-playwright/
|
||||
├── chromium-1208/
|
||||
│ ├── chrome-win64/
|
||||
│ │ └── chrome.exe
|
||||
│ └── INSTALLATION_COMPLETE
|
||||
└── chromium_headless_shell-1208/
|
||||
└── ...
|
||||
```
|
||||
|
||||
### 方法 3:使用 PLAYWRIGHT_BROWSERS_PATH 环境变量
|
||||
|
||||
将浏览器文件放在共享位置,然后设置环境变量:
|
||||
|
||||
```bash
|
||||
# 系统环境变量
|
||||
setx PLAYWRIGHT_BROWSERS_PATH "D:\shared\playwright-browsers"
|
||||
```
|
||||
|
||||
或在应用启动脚本中设置。
|
||||
|
||||
## 验证安装
|
||||
|
||||
运行应用后,检查是否还有错误提示。如果没有浏览器错误,说明安装成功。
|
||||
|
||||
你也可以在应用日志中查找:
|
||||
|
||||
- `Found Chromium revision: chromium-1208` - 表示成功找到浏览器
|
||||
- `Playwright browser not found` - 表示未找到,会显示可用目录列表
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 显示"浏览器文件未找到"但文件确实在那里
|
||||
|
||||
检查目录结构是否正确:
|
||||
|
||||
```powershell
|
||||
# 查看当前目录内容
|
||||
Get-ChildItem $env:APPDATA\erpauto\ms-playwright
|
||||
|
||||
# 检查 chrome.exe 是否存在
|
||||
Test-Path "$env:APPDATA\erpauto\ms-playwright\chromium-*/chrome-win64/chrome.exe"
|
||||
```
|
||||
|
||||
### Q: 不同用户使用同一个浏览器文件
|
||||
|
||||
使用环境变量 `PLAYWRIGHT_BROWSERS_PATH` 指向共享目录。
|
||||
|
||||
### Q: 离线部署
|
||||
|
||||
1. 在有网络的机器上运行 `npx playwright install chromium`
|
||||
2. 复制整个 `ms-playwright` 目录
|
||||
3. 在目标机器上设置 `PLAYWRIGHT_BROWSERS_PATH` 指向该目录
|
||||
|
||||
## 下次构建
|
||||
|
||||
只需运行:
|
||||
|
||||
```bash
|
||||
npm run build:win
|
||||
```
|
||||
|
||||
所有配置已保存,Playwright 模块和浏览器路径检查会自动处理。
|
||||
55
README.md
55
README.md
@@ -30,29 +30,43 @@ npm install
|
||||
|
||||
### 配置
|
||||
|
||||
在项目根目录创建 `.env` 文件:
|
||||
在项目根目录创建 `config.yaml` 文件(可参考 `config.template.yaml`):
|
||||
|
||||
```bash
|
||||
# ERP 配置
|
||||
ERP_URL=https://your-erp-server.com
|
||||
ERP_USERNAME=your_username
|
||||
ERP_PASSWORD=your_password
|
||||
```yaml
|
||||
# ERP 配置(固定基础设施)
|
||||
erp:
|
||||
url: https://your-erp-server.com
|
||||
|
||||
# MySQL 配置(可选)
|
||||
MYSQL_HOST=localhost
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER=root
|
||||
MYSQL_PASSWORD=password
|
||||
MYSQL_DATABASE=erpauto
|
||||
# 数据库配置
|
||||
database:
|
||||
activeType: mysql # 或 sqlserver
|
||||
|
||||
# SQL Server 配置(可选)
|
||||
SQL_SERVER_HOST=localhost
|
||||
SQL_SERVER_PORT=1433
|
||||
SQL_SERVER_USER=sa
|
||||
SQL_SERVER_PASSWORD=password
|
||||
SQL_SERVER_DATABASE=erpauto
|
||||
mysql:
|
||||
host: localhost
|
||||
port: 3306
|
||||
database: erpauto
|
||||
username: root
|
||||
password: your_password
|
||||
charset: utf8mb4
|
||||
|
||||
sqlserver:
|
||||
server: localhost
|
||||
port: 1433
|
||||
database: erpauto
|
||||
username: sa
|
||||
password: your_password
|
||||
driver: 'ODBC Driver 18 for SQL Server'
|
||||
trustServerCertificate: true
|
||||
|
||||
# 路径配置
|
||||
paths:
|
||||
dataDir: './data/'
|
||||
defaultOutput: 'output.xlsx'
|
||||
validationOutput: 'validation-result.xlsx'
|
||||
```
|
||||
|
||||
**注意**:ERP 用户名和密码在应用的设置界面中配置,存储在数据库中(按用户管理)。
|
||||
|
||||
### 运行开发环境
|
||||
|
||||
```bash
|
||||
@@ -136,9 +150,10 @@ ERPAuto/
|
||||
|
||||
### 无法连接 ERP 系统
|
||||
|
||||
1. 检查 `.env` 文件中的 ERP_URL 是否正确
|
||||
1. 检查 `config.yaml` 中的 ERP URL 是否正确
|
||||
2. 确认网络连接正常
|
||||
3. 检查 ERP 系统是否可访问
|
||||
4. 在设置界面中确认 ERP 用户名和密码已配置
|
||||
|
||||
### 提取失败
|
||||
|
||||
@@ -149,7 +164,7 @@ ERPAuto/
|
||||
### 数据库连接失败
|
||||
|
||||
1. 确认数据库服务已启动
|
||||
2. 检查 `.env` 中的数据库配置
|
||||
2. 检查 `config.yaml` 中的数据库配置
|
||||
3. 确认防火墙允许数据库端口访问
|
||||
|
||||
## 开发
|
||||
|
||||
72
config.template.yaml
Normal file
72
config.template.yaml
Normal file
@@ -0,0 +1,72 @@
|
||||
# ================================
|
||||
# ERPAuto 配置模板
|
||||
# ================================
|
||||
# 部署说明:
|
||||
# 1. 复制此文件为 config.yaml
|
||||
# 2. 根据实际环境修改配置值
|
||||
# 3. 设置 database.activeType 为 mysql 或 sqlserver
|
||||
# ================================
|
||||
# 注意:ERP 认证信息存储在数据库 (dbo_BIPUsers) 中,按用户管理
|
||||
# ================================
|
||||
|
||||
database:
|
||||
activeType: mysql
|
||||
|
||||
mysql:
|
||||
host: <MYSQL_HOST>
|
||||
port: 3306
|
||||
database: <DATABASE_NAME>
|
||||
username: <USERNAME>
|
||||
password: <PASSWORD>
|
||||
charset: utf8mb4
|
||||
|
||||
sqlserver:
|
||||
server: <SQL_SERVER_HOST>
|
||||
port: 1433
|
||||
database: <DATABASE_NAME>
|
||||
username: <USERNAME>
|
||||
password: <PASSWORD>
|
||||
driver: 'ODBC Driver 18 for SQL Server'
|
||||
trustServerCertificate: true
|
||||
|
||||
paths:
|
||||
dataDir: './data/'
|
||||
defaultOutput: 'output.xlsx'
|
||||
validationOutput: 'validation-result.xlsx'
|
||||
|
||||
extraction:
|
||||
batchSize: 100
|
||||
verbose: true
|
||||
autoConvert: true
|
||||
mergeBatches: true
|
||||
enableDbPersistence: true
|
||||
|
||||
validation:
|
||||
dataSource: database_full
|
||||
batchSize: 2000
|
||||
matchMode: substring
|
||||
enableCrud: false
|
||||
defaultManager: ''
|
||||
|
||||
orderResolution:
|
||||
tableName: ''
|
||||
productionIdField: ''
|
||||
orderNumberField: ''
|
||||
|
||||
cleaner:
|
||||
queryBatchSize: 100
|
||||
processConcurrency: 1
|
||||
|
||||
logging:
|
||||
level: info
|
||||
auditRetention: 30
|
||||
appRetention: 14
|
||||
|
||||
# RustFS 对象存储配置(用于持久化报告)
|
||||
rustfs:
|
||||
enabled: false # 设置为 true 启用 RustFS 上传
|
||||
endpoint: 'http://192.168.110.114:9000' # RustFS 服务器地址
|
||||
accessKey: '<YOUR_ACCESS_KEY>' # 访问密钥
|
||||
secretKey: '<YOUR_SECRET_KEY>' # 密钥
|
||||
bucket: 'erpauto' # 存储桶名称
|
||||
region: 'us-east-1' # 区域(S3 兼容,默认即可)
|
||||
300
docs/CONFIG_FILE_LOCATION.md
Normal file
300
docs/CONFIG_FILE_LOCATION.md
Normal file
@@ -0,0 +1,300 @@
|
||||
# ERPAuto 配置文件位置说明
|
||||
|
||||
## 概述
|
||||
|
||||
ERPAuto 根据运行环境自动选择配置文件的存储位置:
|
||||
|
||||
- **开发环境**:项目根目录(方便编辑和版本控制)
|
||||
- **生产环境**:用户数据目录(AppData,安全且升级时保留)
|
||||
|
||||
---
|
||||
|
||||
## 配置文件位置
|
||||
|
||||
### 1. 开发环境
|
||||
|
||||
**适用场景**:
|
||||
|
||||
- 开发和调试
|
||||
- 配置需要版本控制
|
||||
- 团队协作
|
||||
|
||||
**配置文件位置**:
|
||||
|
||||
```
|
||||
<项目根目录>\config.yaml
|
||||
```
|
||||
|
||||
**示例**:
|
||||
|
||||
```
|
||||
D:\Projects\ERPAuto\
|
||||
├── src\
|
||||
├── package.json
|
||||
├── config.yaml # 开发配置
|
||||
├── config.yaml.backup # 自动备份
|
||||
└── config.template.yaml # 配置模板
|
||||
```
|
||||
|
||||
**检测方式**:
|
||||
|
||||
```typescript
|
||||
process.env.NODE_ENV === 'development' || !app.isPackaged
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 生产环境(安装版和便携版)
|
||||
|
||||
**适用场景**:
|
||||
|
||||
- 正式发布的应用
|
||||
- 配置需要在应用升级时保留
|
||||
- 多用户环境,每个用户独立配置
|
||||
|
||||
**配置文件位置**:
|
||||
|
||||
```
|
||||
Windows: C:\Users\<用户名>\AppData\Roaming\erpauto\config.yaml
|
||||
macOS: ~/Library/Application Support/erpauto/config.yaml
|
||||
Linux: ~/.config/erpauto/config.yaml
|
||||
```
|
||||
|
||||
**示例**:
|
||||
|
||||
```
|
||||
C:\Users\zhangsan\AppData\Roaming\erpauto\
|
||||
├── config.yaml # 用户配置
|
||||
└── config.yaml.backup # 自动备份
|
||||
```
|
||||
|
||||
**检测方式**:
|
||||
|
||||
```typescript
|
||||
app.isPackaged === true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 为什么生产环境使用用户数据目录?
|
||||
|
||||
| 方案 | 配置位置 | 优点 | 缺点 |
|
||||
| ------------------ | --------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| **用户数据目录** ✓ | AppData\Roaming | • 应用升级时配置保留<br>• 符合 Windows 规范<br>• 多用户隔离<br>• 配置不暴露 | • 路径较深,不易访问 |
|
||||
| **应用同目录** ✗ | .exe 同目录 | • 易于访问和编辑 | • 应用升级时配置可能丢失<br>• 需要写权限<br>• 配置暴露在应用目录<br>• 多用户共享配置 |
|
||||
|
||||
**我们的选择**:生产环境统一使用用户数据目录,确保:
|
||||
|
||||
1. ✅ 应用升级时用户配置不会丢失
|
||||
2. ✅ 符合 Windows 应用规范
|
||||
3. ✅ 配置不暴露在应用目录,更安全
|
||||
4. ✅ 多用户环境下,每个用户有独立配置
|
||||
|
||||
---
|
||||
|
||||
## 构建配置
|
||||
|
||||
### electron-builder.yml
|
||||
|
||||
```yaml
|
||||
win:
|
||||
target:
|
||||
- nsis # 安装版
|
||||
- portable # 便携版
|
||||
|
||||
portable:
|
||||
artifactName: ${name}-${version}-portable.${ext}
|
||||
# 便携版也使用用户数据目录 (AppData)
|
||||
# 不是 exe 同目录,确保配置在升级时保留
|
||||
|
||||
nsis:
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
```
|
||||
|
||||
### 构建命令
|
||||
|
||||
```bash
|
||||
# 构建 Windows 安装版和便携版
|
||||
npm run build:win
|
||||
```
|
||||
|
||||
### 输出文件
|
||||
|
||||
```
|
||||
dist/
|
||||
├── erpauto-1.0.0-setup.exe # 安装版
|
||||
└── erpauto-1.0.0-portable.exe # 便携版
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 配置文件结构
|
||||
|
||||
```yaml
|
||||
# ================================
|
||||
# ERPAuto 配置文件
|
||||
# ================================
|
||||
|
||||
# 数据库配置
|
||||
database:
|
||||
activeType: mysql # 切换字段:mysql 或 sqlserver
|
||||
|
||||
mysql:
|
||||
host: 192.168.31.83
|
||||
port: 3306
|
||||
database: BLD_DB
|
||||
username: remote_user
|
||||
password: ''
|
||||
charset: utf8mb4
|
||||
|
||||
sqlserver:
|
||||
server: localhost
|
||||
port: 1433
|
||||
database: BLD_DB
|
||||
username: sa
|
||||
password: ''
|
||||
driver: 'ODBC Driver 18 for SQL Server'
|
||||
trustServerCertificate: true
|
||||
|
||||
# 路径配置
|
||||
paths:
|
||||
dataDir: 'D:/python/playwrite/data/'
|
||||
defaultOutput: '离散备料计划维护_合并.xlsx'
|
||||
validationOutput: '物料状态校验结果.xlsx'
|
||||
|
||||
# 数据提取配置
|
||||
extraction:
|
||||
batchSize: 100
|
||||
verbose: true
|
||||
autoConvert: true
|
||||
mergeBatches: true
|
||||
enableDbPersistence: true
|
||||
|
||||
# 校验配置
|
||||
validation:
|
||||
dataSource: database_full
|
||||
batchSize: 2000
|
||||
matchMode: substring
|
||||
enableCrud: false
|
||||
defaultManager: ''
|
||||
|
||||
# 订单号解析配置
|
||||
orderResolution:
|
||||
tableName: 'productionContractData_26 年压力表合同数据'
|
||||
productionIdField: '总排号'
|
||||
orderNumberField: '生产订单号'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 配置文件管理
|
||||
|
||||
### 查看当前配置路径
|
||||
|
||||
运行调试工具:
|
||||
|
||||
```bash
|
||||
npx tsx src\main\tools\config-path-debug.ts
|
||||
```
|
||||
|
||||
### 快速访问配置(Windows)
|
||||
|
||||
```bash
|
||||
# 打开配置所在目录
|
||||
%APPDATA%\erpauto
|
||||
```
|
||||
|
||||
### 备份配置
|
||||
|
||||
```bash
|
||||
# 备份整个配置目录
|
||||
xcopy %APPDATA%\erpauto D:\Backup\erpauto-config /E /I
|
||||
```
|
||||
|
||||
### 迁移配置
|
||||
|
||||
从旧版本迁移:
|
||||
|
||||
```bash
|
||||
# 使用迁移脚本
|
||||
npx tsx scripts\migrate-env-to-yaml.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 便携版应用的配置为什么不放在 exe 同目录?
|
||||
|
||||
**A**:
|
||||
|
||||
- 放在 exe 同目录会导致应用升级时配置丢失
|
||||
- 便携版每次运行会解压到临时目录,无法持久保存配置
|
||||
- 使用用户数据目录(AppData)确保配置持久化
|
||||
|
||||
### Q: 如何快速访问配置文件?
|
||||
|
||||
**A**:
|
||||
|
||||
- Windows: 按 `Win + R`,输入 `%APPDATA%\erpauto`,回车
|
||||
- 或在文件管理器地址栏输入 `%APPDATA%\erpauto`
|
||||
|
||||
### Q: 多台电脑如何同步配置?
|
||||
|
||||
**A**:
|
||||
|
||||
1. 导出配置:`xcopy %APPDATA%\erpauto\config.yaml \\server\share\`
|
||||
2. 导入配置:`xcopy \\server\share\config.yaml %APPDATA%\erpauto\`
|
||||
|
||||
或使用同步工具(OneDrive、坚果云等)同步配置目录。
|
||||
|
||||
### Q: 配置文件损坏了怎么办?
|
||||
|
||||
**A**:
|
||||
|
||||
1. 删除 `config.yaml`
|
||||
2. 应用会自动创建新的默认配置
|
||||
3. 从 `config.yaml.backup` 恢复(如果存在)
|
||||
|
||||
### Q: 开发环境下如何切换配置?
|
||||
|
||||
**A**:
|
||||
|
||||
- 直接编辑项目根目录的 `config.yaml`
|
||||
- 建议保留 `config.template.yaml` 作为模板
|
||||
- 将 `config.yaml` 加入 `.gitignore`,避免提交敏感信息
|
||||
|
||||
---
|
||||
|
||||
## 技术实现
|
||||
|
||||
### ConfigManager 路径选择逻辑
|
||||
|
||||
```typescript
|
||||
// 检测是否为开发环境
|
||||
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged
|
||||
|
||||
if (isDev) {
|
||||
// 开发环境:项目根目录
|
||||
this.configPath = path.resolve(__dirname, '../../config.yaml')
|
||||
} else {
|
||||
// 生产环境(安装版和便携版):用户数据目录
|
||||
this.configPath = path.join(app.getPath('userData'), 'config.yaml')
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 版本历史
|
||||
|
||||
| 版本 | 配置策略 | 说明 |
|
||||
| ---- | ------------------------------- | -------------------- |
|
||||
| 1.0+ | 开发:项目目录<br>生产:AppData | 确保配置在升级时保留 |
|
||||
|
||||
---
|
||||
|
||||
## 参考资料
|
||||
|
||||
- [Electron app.getPath() 文档](https://www.electronjs.org/docs/api/app#appgetpathname)
|
||||
- [electron-builder 配置](https://www.electron.build/configuration.html)
|
||||
- [Windows 应用数据存储规范](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid)
|
||||
731
docs/Configuration-Architecture-Analysis.md
Normal file
731
docs/Configuration-Architecture-Analysis.md
Normal file
@@ -0,0 +1,731 @@
|
||||
# ERPAuto 配置系统架构分析
|
||||
|
||||
## 1. 概述
|
||||
|
||||
ERPAuto 是一个基于 Electron 的桌面应用程序,采用多层次配置管理系统来支持 ERP 系统自动化数据处理。配置系统采用 `.env` 文件作为持久化存储,通过 `ConfigManager` 统一管理,支持运行时动态修改和持久化保存。
|
||||
|
||||
## 2. 配置系统整体架构
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "配置数据源"
|
||||
ENV[.env 文件]
|
||||
ENV_EXAMPLE[.env.example 模板]
|
||||
CACHE[内存缓存 ConfigCache]
|
||||
end
|
||||
|
||||
subgraph "配置管理层 ConfigManager"
|
||||
CM_LOAD[loadEnvFile]
|
||||
CM_GET[get/getBoolean/getNumber]
|
||||
CM_SET[set]
|
||||
CM_SAVE[save/saveAllSettings]
|
||||
CM_PARTIAL[savePartialSettings]
|
||||
CM_MERGE[deepMerge 深度合并]
|
||||
end
|
||||
|
||||
subgraph "IPC 通信层"
|
||||
SETTINGS_HANDLER[settings-handler.ts]
|
||||
IPC_GET[settings:getSettings]
|
||||
IPC_SAVE[settings:saveSettings]
|
||||
IPC_TEST[settings:testErpConnection/testDbConnection]
|
||||
end
|
||||
|
||||
subgraph "业务服务层"
|
||||
ERP_SVC[ERP 服务]
|
||||
DB_SVC[数据库服务]
|
||||
USER_SVC[用户服务]
|
||||
EXTRACTOR[ExtractorService]
|
||||
CLEANER[CleanerService]
|
||||
end
|
||||
|
||||
subgraph "UI 呈现层"
|
||||
SETTINGS_UI[设置界面]
|
||||
LOGIN_UI[登录界面]
|
||||
MAIN_UI[主界面]
|
||||
end
|
||||
|
||||
ENV -->|读取 | CM_LOAD
|
||||
ENV_EXAMPLE -.->|模板参考 | ENV
|
||||
CM_LOAD -->|填充 | CACHE
|
||||
CACHE --> CM_GET
|
||||
CM_SET --> CACHE
|
||||
CM_PARTIAL --> CM_MERGE --> CM_SAVE --> ENV
|
||||
|
||||
CM_GET --> SETTINGS_HANDLER
|
||||
SETTINGS_HANDLER --> IPC_GET
|
||||
SETTINGS_HANDLER --> IPC_SAVE
|
||||
SETTINGS_HANDLER --> IPC_TEST
|
||||
|
||||
IPC_GET --> SETTINGS_UI
|
||||
IPC_SAVE --> SETTINGS_UI
|
||||
IPC_TEST --> SETTINGS_UI
|
||||
|
||||
CACHE --> ERP_SVC
|
||||
CACHE --> DB_SVC
|
||||
CACHE --> USER_SVC
|
||||
CACHE --> EXTRACTOR
|
||||
CACHE --> CLEANER
|
||||
|
||||
SETTINGS_UI --> MAIN_UI
|
||||
LOGIN_UI --> USER_SVC
|
||||
```
|
||||
|
||||
## 3. 配置文件结构
|
||||
|
||||
### 3.1 .env 文件组织
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "ERP 系统配置"
|
||||
ERP_URL[ERP_URL]
|
||||
ERP_USER[ERP_USERNAME]
|
||||
ERP_PASS[ERP_PASSWORD]
|
||||
ERP_HEADLESS[ERP_HEADLESS]
|
||||
ERP_HTTPS[ERP_IGNORE_HTTPS_ERRORS]
|
||||
ERP_CLOSE[ERP_AUTO_CLOSE_BROWSER]
|
||||
end
|
||||
|
||||
subgraph "数据库配置 - SQL Server"
|
||||
SQL_DRIVER[DB_SQLSERVER_DRIVER]
|
||||
SQL_TRUST[DB_TRUST_SERVER_CERTIFICATE]
|
||||
end
|
||||
|
||||
subgraph "数据库配置 - MySQL"
|
||||
DB_TYPE[DB_TYPE]
|
||||
DB_NAME[DB_NAME]
|
||||
DB_USER[DB_USERNAME]
|
||||
DB_PASS[DB_PASSWORD]
|
||||
MYSQL_HOST[DB_MYSQL_HOST]
|
||||
MYSQL_PORT[DB_MYSQL_PORT]
|
||||
MYSQL_CHARSET[DB_MYSQL_CHARSET]
|
||||
end
|
||||
|
||||
subgraph "订单号解析表配置"
|
||||
TABLE_NAME[DB_TABLE_NAME]
|
||||
FIELD_PROD_ID[DB_FIELD_PRODUCTION_ID]
|
||||
FIELD_ORDER[DB_FIELD_ORDER_NUMBER]
|
||||
end
|
||||
|
||||
subgraph "路径配置"
|
||||
DATA_DIR[PATH_DATA_DIR]
|
||||
PROD_ID_FILE[PATH_PRODUCTION_ID_FILE]
|
||||
DEFAULT_OUT[PATH_DEFAULT_OUTPUT]
|
||||
VALID_OUT[PATH_VALIDATION_OUTPUT]
|
||||
end
|
||||
|
||||
subgraph "数据提取配置"
|
||||
BATCH_SIZE[EXTRACTION_BATCH_SIZE]
|
||||
VERBOSE[EXTRACTION_VERBOSE]
|
||||
AUTO_CONVERT[EXTRACTION_AUTO_CONVERT]
|
||||
MERGE_BATCHES[EXTRACTION_MERGE_BATCHES]
|
||||
DB_PERSIST[EXTRACTION_ENABLE_DB_PERSISTENCE]
|
||||
end
|
||||
|
||||
subgraph "校验配置"
|
||||
DATA_SOURCE[VALIDATION_DATA_SOURCE]
|
||||
USE_DB[VALIDATION_USE_DATABASE]
|
||||
VAL_BATCH[VALIDATION_BATCH_SIZE]
|
||||
ENABLE_CRUD[VALIDATION_ENABLE_CRUD]
|
||||
DEFAULT_MGR[VALIDATION_DEFAULT_MANAGER]
|
||||
MATCH_MODE[VALIDATION_MATCH_MODE]
|
||||
end
|
||||
|
||||
subgraph "UI 配置"
|
||||
FONT_FAMILY[UI_FONT_FAMILY]
|
||||
FONT_SIZE[UI_FONT_SIZE]
|
||||
INPUT_WIDTH[UI_PRODUCTION_ID_INPUT_WIDTH]
|
||||
end
|
||||
|
||||
subgraph "执行配置"
|
||||
DRY_RUN[EXECUTION_DRYRUN]
|
||||
end
|
||||
```
|
||||
|
||||
### 3.2 默认配置值
|
||||
|
||||
| 配置类别 | 配置项 | 默认值 | 说明 |
|
||||
| ---------- | ----------------- | --------------------------- | -------------------- |
|
||||
| ERP | url | `https://68.11.34.30:8082/` | ERP 系统地址 |
|
||||
| ERP | headless | `true` | 无头浏览器模式 |
|
||||
| ERP | ignoreHttpsErrors | `true` | 忽略 HTTPS 证书错误 |
|
||||
| ERP | autoCloseBrowser | `true` | 操作后自动关闭浏览器 |
|
||||
| Database | dbType | `mysql` | 数据库类型 |
|
||||
| Database | mysqlHost | `192.168.31.83` | MySQL 主机地址 |
|
||||
| Database | mysqlPort | `3306` | MySQL 端口 |
|
||||
| Database | database | `BLD_DB` | 数据库名 |
|
||||
| Database | username | `remote_user` | 数据库用户名 |
|
||||
| Paths | dataDir | `D:/python/playwrite/data/` | 数据目录 |
|
||||
| Extraction | batchSize | `100` | 批次大小 |
|
||||
| Extraction | verbose | `true` | 详细日志 |
|
||||
| Validation | dataSource | `database_full` | 校验数据源 |
|
||||
| Validation | batchSize | `2000` | 校验批次大小 |
|
||||
| Validation | matchMode | `substring` | 匹配模式 |
|
||||
| UI | fontFamily | `Microsoft YaHei UI` | 字体 |
|
||||
| UI | fontSize | `10` | 字体大小 |
|
||||
| Execution | dryRun | `false` | 干运行模式 |
|
||||
|
||||
## 4. ConfigManager 核心类设计
|
||||
|
||||
### 4.1 类结构与单例模式
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class ConfigManager {
|
||||
-static instance: ConfigManager | null
|
||||
-envPath: string
|
||||
-backupPath: string
|
||||
-configCache: Map<string, string>
|
||||
-initialized: boolean
|
||||
+static getInstance(): ConfigManager
|
||||
+initialize(): Promise<void>
|
||||
+get(key: string): string | undefined
|
||||
+getBoolean(key: string, default: boolean): boolean
|
||||
+getNumber(key: string, default: number): number
|
||||
+set(key: string, value: string|number|boolean): void
|
||||
+save(): Promise<boolean>
|
||||
+getAllSettings(): SettingsData
|
||||
+saveAllSettings(settings: SettingsData): Promise<boolean>
|
||||
+savePartialSettings(settings: Partial<SettingsData>): Promise<Object>
|
||||
+resetToDefaults(): SettingsData
|
||||
+getDefaultSettings(): SettingsData
|
||||
-loadEnvFile(): Promise<void>
|
||||
-backupEnvFile(): Promise<boolean>
|
||||
-restoreBackup(): Promise<boolean>
|
||||
}
|
||||
|
||||
class SettingsData {
|
||||
+erp: ErpConfig
|
||||
+database: DatabaseConfig
|
||||
+paths: PathsConfig
|
||||
+extraction: ExtractionConfig
|
||||
+validation: ValidationConfig
|
||||
+ui: UiConfig
|
||||
+execution: ExecutionConfig
|
||||
}
|
||||
|
||||
ConfigManager --> SettingsData: 返回/接收
|
||||
```
|
||||
|
||||
### 4.2 核心方法流程图
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client as 客户端/IPC
|
||||
participant CM as ConfigManager
|
||||
participant Cache as ConfigCache
|
||||
participant FS as 文件系统
|
||||
participant Backup as Backup 文件
|
||||
|
||||
Client->>CM: savePartialSettings(settings)
|
||||
activate CM
|
||||
|
||||
CM->>CM: validateEditableFields()
|
||||
alt 包含非白名单字段
|
||||
CM-->>Client: 返回错误 (不允许修改)
|
||||
else 验证通过
|
||||
CM->>FS: loadEnvFile()
|
||||
FS-->>Cache: 填充缓存
|
||||
CM->>CM: getAllSettings()
|
||||
CM->>Cache: 读取当前配置
|
||||
CM->>CM: deepMerge(current, settings)
|
||||
|
||||
CM->>FS: backupEnvFile()
|
||||
FS-->>Backup: 创建备份
|
||||
|
||||
CM->>FS: saveAllSettings(merged)
|
||||
alt 保存成功
|
||||
FS-->>Cache: 重新加载
|
||||
CM-->>Client: 返回成功
|
||||
else 保存失败
|
||||
CM->>FS: restoreBackup()
|
||||
FS-->>Cache: 恢复配置
|
||||
CM-->>Client: 返回错误
|
||||
end
|
||||
end
|
||||
deactivate CM
|
||||
```
|
||||
|
||||
### 4.3 深度合并算法
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[deepMerge 函数] --> B{遍历 target 键值对}
|
||||
B --> C{targetValue 是对象?}
|
||||
C -->|是 | D{sourceValue 也是对象?}
|
||||
D -->|是 | E[递归调用 deepMerge]
|
||||
D -->|否 | F[直接使用 targetValue]
|
||||
C -->|否 | G{targetValue !== undefined?}
|
||||
G -->|是 | H[更新该键值]
|
||||
G -->|否 | I[跳过该键]
|
||||
E --> J[合并结果存入 result]
|
||||
F --> J
|
||||
H --> J
|
||||
B --> K[遍历完成]
|
||||
K --> L[返回合并后的对象]
|
||||
```
|
||||
|
||||
## 5. 配置读取与使用模式
|
||||
|
||||
### 5.1 环境变量直接读取模式
|
||||
|
||||
各业务服务通过 `process.env` 直接读取配置:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "环境变量读取点"
|
||||
MAIN[main/index.ts<br/>dotenv.config]
|
||||
end
|
||||
|
||||
subgraph "服务模块"
|
||||
DB_INDEX[database/index.ts]
|
||||
DB_MYSQL[database/mysql.ts]
|
||||
DB_SQL[database/sql-server.ts]
|
||||
BIP_DAO[bip-users-dao.ts]
|
||||
ORDER_RES[order-resolver.ts]
|
||||
EXTRACTOR[extractor-handler.ts]
|
||||
CLEANER[cleaner-handler.ts]
|
||||
VALIDATION[validation-handler.ts]
|
||||
end
|
||||
|
||||
MAIN -->|初始化加载 | ENV[process.env]
|
||||
|
||||
ENV --> DB_INDEX
|
||||
ENV --> DB_MYSQL
|
||||
ENV --> DB_SQL
|
||||
ENV --> BIP_DAO
|
||||
ENV --> ORDER_RES
|
||||
ENV --> EXTRACTOR
|
||||
ENV --> CLEANER
|
||||
ENV --> VALIDATION
|
||||
```
|
||||
|
||||
### 5.2 ConfigManager 获取模式
|
||||
|
||||
通过 IPC 层统一获取:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as 设置界面
|
||||
participant Preload as Preload 脚本
|
||||
participant IPC as IPC Handler
|
||||
participant CM as ConfigManager
|
||||
|
||||
UI->>Preload: window.api.settings.getSettings()
|
||||
Preload->>IPC: ipcRenderer.invoke('settings:getSettings')
|
||||
IPC->>IPC: SessionManager.getUserType()
|
||||
IPC->>CM: getAllSettings()
|
||||
CM->>IPC: SettingsData
|
||||
IPC->>IPC: filterSettingsByUserType()
|
||||
IPC-->>Preload: 过滤后的 SettingsData
|
||||
Preload-->>UI: SettingsData
|
||||
```
|
||||
|
||||
### 5.3 数据库配置工厂模式
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "配置创建"
|
||||
GET_TYPE[getDatabaseType] -->|DB_TYPE env| TYPE_CHECK{数据库类型}
|
||||
TYPE_CHECK -->|mysql| CREATE_MYSQL[createMySqlConfig]
|
||||
TYPE_CHECK -->|sqlserver| CREATE_SQL[createSqlServerConfig]
|
||||
end
|
||||
|
||||
subgraph "服务创建"
|
||||
CREATE_MYSQL --> MYSQL_SVC[MySqlService]
|
||||
CREATE_SQL --> SQL_SVC[SqlServerService]
|
||||
end
|
||||
|
||||
subgraph "单例缓存"
|
||||
MYSQL_SVC --> CACHE[instances Map]
|
||||
SQL_SVC --> CACHE
|
||||
CACHE -->|返回已连接实例 | CLIENT[调用方]
|
||||
end
|
||||
|
||||
CREATE_MYSQL --> CONNECT_MYSQL[service.connect]
|
||||
CREATE_SQL --> CONNECT_SQL[service.connect]
|
||||
|
||||
CONNECT_MYSQL --> CACHE
|
||||
CONNECT_SQL --> CACHE
|
||||
```
|
||||
|
||||
## 6. 用户权限与配置访问控制
|
||||
|
||||
### 6.1 用户类型与权限
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "用户类型 UserType"
|
||||
ADMIN[Admin<br/>管理员]
|
||||
USER[User<br/>普通用户]
|
||||
GUEST[Guest<br/>访客]
|
||||
end
|
||||
|
||||
subgraph "配置访问权限"
|
||||
ADMIN_SETTINGS[全部配置可访问<br/>可修改 ERP 配置<br/>可恢复默认设置]
|
||||
USER_SETTINGS[有限配置访问<br/>可修改 ERP 配置<br/>可查看执行配置]
|
||||
GUEST_SETTINGS[只读访问]
|
||||
end
|
||||
|
||||
ADMIN --> ADMIN_SETTINGS
|
||||
USER --> USER_SETTINGS
|
||||
GUEST --> GUEST_SETTINGS
|
||||
|
||||
subgraph "SessionManager 会话管理"
|
||||
SM_LOGIN[login]
|
||||
SM_SILENT[loginByComputerName]
|
||||
SM_SWITCH[switchUser - Admin only]
|
||||
SM_GET[getUserType/getUserInfo]
|
||||
end
|
||||
|
||||
SM_LOGIN --> USER
|
||||
SM_SILENT --> USER
|
||||
SM_SWITCH --> USER
|
||||
```
|
||||
|
||||
### 6.2 配置过滤机制
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[getSettings 请求] --> B[获取当前用户类型]
|
||||
B --> C{用户类型判断}
|
||||
|
||||
C -->|Admin| D[返回全部配置]
|
||||
|
||||
C -->|User| E[过滤配置]
|
||||
E --> F[返回 ERP 配置<br/>username/password/headless/url/...<br/>paths 配置<br/>execution 配置<br/>最小化其他配置]
|
||||
|
||||
C -->|Guest| G[返回空配置或只读配置]
|
||||
|
||||
D --> H[返回给 UI]
|
||||
E --> H
|
||||
G --> H
|
||||
```
|
||||
|
||||
## 7. 配置修改白名单机制
|
||||
|
||||
### 7.1 可编辑字段白名单
|
||||
|
||||
```javascript
|
||||
const UI_EDITABLE_FIELDS: string[] = [
|
||||
'erp.url',
|
||||
'erp.username',
|
||||
'erp.password'
|
||||
// 可根据需要扩展
|
||||
]
|
||||
```
|
||||
|
||||
### 7.2 白名单验证流程
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[savePartialSettings 调用] --> B[遍历 settings 中的字段]
|
||||
B --> C[构建字段路径 section.field]
|
||||
C --> D{字段在白名单中?}
|
||||
D -->|否 | E[添加到 invalidFields]
|
||||
D -->|是 | F[继续检查下一字段]
|
||||
E --> B
|
||||
F --> B
|
||||
B --> G{所有字段检查完成}
|
||||
G --> H{invalidFields 为空?}
|
||||
H -->|否 | I[返回错误<br/>包含不允许修改的字段]
|
||||
H -->|是 | J[继续保存流程]
|
||||
```
|
||||
|
||||
## 8. 数据库配置详解
|
||||
|
||||
### 8.1 双数据库支持架构
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "数据库抽象层"
|
||||
IDB[IDatabaseService 接口<br/>connect/disconnect<br/>query/transaction<br/>isConnected]
|
||||
end
|
||||
|
||||
subgraph "MySQL 实现"
|
||||
MYSQL[MySqlService<br/>mysql2/promise<br/>createConnection<br/>execute/transaction]
|
||||
end
|
||||
|
||||
subgraph "SQL Server 实现"
|
||||
MSSQL[SqlServerService<br/>mssql<br/>ConnectionPool<br/>request.query<br/>Transaction]
|
||||
end
|
||||
|
||||
IDB -.->|实现 | MYSQL
|
||||
IDB -.->|实现 | MSSQL
|
||||
|
||||
MYSQL --> ENV_MYSQL[DB_MYSQL_HOST<br/>DB_MYSQL_PORT<br/>DB_NAME<br/>DB_USERNAME<br/>DB_PASSWORD]
|
||||
MSSQL --> ENV_MSSQL[DB_SERVER<br/>DB_SQLSERVER_PORT<br/>DB_NAME<br/>DB_USERNAME<br/>DB_PASSWORD<br/>DB_TRUST_SERVER_CERTIFICATE]
|
||||
```
|
||||
|
||||
### 8.2 数据库配置参数映射
|
||||
|
||||
| 环境变量 | MySQL 用途 | SQL Server 用途 |
|
||||
| --------------------------- | ----------- | ----------------- |
|
||||
| DB_TYPE | mysql | sqlserver/mssql |
|
||||
| DB_NAME | 数据库名 | 数据库名 |
|
||||
| DB_USERNAME | 用户名 | 用户名 |
|
||||
| DB_PASSWORD | 密码 | 密码 |
|
||||
| DB_MYSQL_HOST | 主机地址 | - |
|
||||
| DB_MYSQL_PORT | 端口 (3306) | - |
|
||||
| DB_SERVER | - | 服务器地址 |
|
||||
| DB_SQLSERVER_PORT | - | 端口 (1433) |
|
||||
| DB_TRUST_SERVER_CERTIFICATE | - | 信任证书 (yes/no) |
|
||||
|
||||
## 9. ERP 配置与浏览器自动化
|
||||
|
||||
### 9.1 ERP 认证配置流程
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as 设置界面
|
||||
participant IPC as settings-handler
|
||||
participant CM as ConfigManager
|
||||
participant ERP_AUTH as ErpAuthService
|
||||
participant PW as Playwright
|
||||
|
||||
UI->>IPC: testErpConnection
|
||||
IPC->>CM: getAllSettings
|
||||
CM-->>IPC: SettingsData(含 erp 配置)
|
||||
|
||||
IPC->>ERP_AUTH: new ErpAuthService(erpConfig)
|
||||
ERP_AUTH->>PW: chromium.launch
|
||||
Note over PW: headless=erpConfig.headless<br/>args=[--ignore-certificate-errors]
|
||||
|
||||
PW-->>ERP_AUTH: Browser Context
|
||||
|
||||
ERP_AUTH->>PW: page.goto(loginUrl)
|
||||
PW-->>ERP_AUTH: 加载登录页面
|
||||
|
||||
ERP_AUTH->>PW: fill username/password
|
||||
ERP_AUTH->>PW: click login button
|
||||
|
||||
PW-->>ERP_AUTH: 登录成功
|
||||
|
||||
ERP_AUTH-->>IPC: ErpSession
|
||||
IPC-->>UI: {success: true}
|
||||
|
||||
ERP_AUTH->>PW: close
|
||||
```
|
||||
|
||||
### 9.2 ERP 配置项说明
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
| ----------------- | ------- | ------ | -------------- |
|
||||
| url | string | - | ERP 系统 URL |
|
||||
| username | string | - | ERP 用户名 |
|
||||
| password | string | - | ERP 密码 |
|
||||
| headless | boolean | true | 无头模式 |
|
||||
| ignoreHttpsErrors | boolean | true | 忽略 SSL 错误 |
|
||||
| autoCloseBrowser | boolean | true | 自动关闭浏览器 |
|
||||
|
||||
## 10. 订单号解析表配置
|
||||
|
||||
### 10.1 配置结构
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "订单号解析配置"
|
||||
TABLE[DB_TABLE_NAME<br/>表名]
|
||||
FIELD_ID[DB_FIELD_PRODUCTION_ID<br/>总排号字段]
|
||||
FIELD_ORDER[DB_FIELD_ORDER_NUMBER<br/>生产订单号字段]
|
||||
end
|
||||
|
||||
TABLE --> ORDER_RESOLVER[OrderResolverService]
|
||||
FIELD_ID --> ORDER_RESOLVER
|
||||
FIELD_ORDER --> ORDER_RESOLVER
|
||||
|
||||
ORDER_RESOLVER --> DB_QUERY[查询映射关系]
|
||||
DB_QUERY --> PRODUCTION_ID[productionID]
|
||||
DB_QUERY --> ORDER_NUMBER[生产订单号]
|
||||
```
|
||||
|
||||
### 10.2 默认配置示例
|
||||
|
||||
```env
|
||||
DB_TABLE_NAME=productionContractData_26 年压力表合同数据
|
||||
DB_FIELD_PRODUCTION_ID=总排号
|
||||
DB_FIELD_ORDER_NUMBER=生产订单号
|
||||
```
|
||||
|
||||
## 11. 配置持久化与备份机制
|
||||
|
||||
### 11.1 保存流程
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[saveAllSettings] --> B[设置写入 configCache]
|
||||
B --> C[构建.env 文件内容]
|
||||
C --> D[按分类组织配置<br/>ERP/数据库/路径/提取/校验/UI/执行]
|
||||
D --> E[写入.env 文件]
|
||||
E --> F{写入成功?}
|
||||
F -->|是 | G[返回 true]
|
||||
F -->|否 | H[返回 false]
|
||||
```
|
||||
|
||||
### 11.2 备份与恢复流程
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Caller as 调用方
|
||||
participant CM as ConfigManager
|
||||
participant ENV as .env
|
||||
participant BAK as .env.backup
|
||||
|
||||
Caller->>CM: savePartialSettings
|
||||
CM->>CM: validateEditableFields
|
||||
|
||||
CM->>ENV: loadEnvFile
|
||||
CM->>CM: deepMerge 合并配置
|
||||
|
||||
CM->>ENV: backupEnvFile
|
||||
ENV->>BAK: copyFileSync
|
||||
|
||||
CM->>ENV: writeFileSync 新配置
|
||||
ENV-->>CM: 保存结果
|
||||
|
||||
alt 保存成功
|
||||
CM->>ENV: loadEnvFile 重新加载
|
||||
CM-->>Caller: success: true
|
||||
else 保存失败
|
||||
CM->>BAK: restoreBackup
|
||||
BAK->>ENV: copyFileSync 恢复
|
||||
CM->>ENV: loadEnvFile
|
||||
CM-->>Caller: success: false + error
|
||||
end
|
||||
```
|
||||
|
||||
## 12. 配置系统初始化时序
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Electron App
|
||||
participant Main as main/index.ts
|
||||
participant Dotenv as dotenv
|
||||
participant CM as ConfigManager
|
||||
participant IPC as registerIpcHandlers
|
||||
participant SM as SessionManager
|
||||
|
||||
App->>Main: 应用启动
|
||||
Main->>Dotenv: config .env
|
||||
Dotenv-->>Main: process.env 已加载
|
||||
|
||||
Main->>IPC: registerIpcHandlers
|
||||
Note over IPC: 注册所有 IPC 处理器<br/>settings/extractor/cleaner/auth...
|
||||
|
||||
App->>Main: app.whenReady
|
||||
Main->>SM: silent login 尝试
|
||||
SM->>SM: loginByComputerName
|
||||
|
||||
alt 静默登录成功
|
||||
SM-->>Main: 用户已认证
|
||||
else 静默登录失败
|
||||
Main->>Main: 显示登录对话框
|
||||
end
|
||||
|
||||
Main->>CM: initialize 按需加载
|
||||
```
|
||||
|
||||
## 13. 关键代码模式
|
||||
|
||||
### 13.1 环境变量读取模式
|
||||
|
||||
```typescript
|
||||
// 直接读取 process.env
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
const mysqlHost = process.env.DB_MYSQL_HOST || 'localhost'
|
||||
const mysqlPort = parseInt(process.env.DB_MYSQL_PORT || '3306', 10)
|
||||
```
|
||||
|
||||
### 13.2 ConfigManager 读取模式
|
||||
|
||||
```typescript
|
||||
// 通过 ConfigManager 获取结构化配置
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const settings = configManager.getAllSettings()
|
||||
const erpUrl = settings.erp.url
|
||||
const batchSize = settings.extraction.batchSize
|
||||
```
|
||||
|
||||
### 13.3 部分保存模式
|
||||
|
||||
```typescript
|
||||
// 只更新允许修改的字段
|
||||
const result = await configManager.savePartialSettings({
|
||||
erp: {
|
||||
url: 'http://new-url.com',
|
||||
username: 'newuser',
|
||||
password: 'newpass'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## 14. 配置类别与业务模块映射
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "配置类别"
|
||||
ERP_CONF[ERP 配置]
|
||||
DB_CONF[数据库配置]
|
||||
PATH_CONF[路径配置]
|
||||
EXTRACT_CONF[提取配置]
|
||||
VALID_CONF[校验配置]
|
||||
UI_CONF[UI 配置]
|
||||
EXEC_CONF[执行配置]
|
||||
end
|
||||
|
||||
subgraph "业务模块"
|
||||
ERP_AUTH[ErpAuthService]
|
||||
ERP_EXTRACT[ExtractorService]
|
||||
ERP_CLEAN[CleanerService]
|
||||
ERP_ORDER[OrderResolverService]
|
||||
DB_MYSQL[MySqlService]
|
||||
DB_SQL[SqlServerService]
|
||||
DB_DAO[各种 DAO 类]
|
||||
EXCEL[Excel Parser/Exporter]
|
||||
UI[React 界面]
|
||||
end
|
||||
|
||||
ERP_CONF --> ERP_AUTH
|
||||
ERP_CONF --> ERP_EXTRACT
|
||||
ERP_CONF --> ERP_CLEAN
|
||||
|
||||
DB_CONF --> DB_MYSQL
|
||||
DB_CONF --> DB_SQL
|
||||
DB_CONF --> DB_DAO
|
||||
|
||||
PATH_CONF --> EXCEL
|
||||
PATH_CONF --> UI
|
||||
|
||||
EXTRACT_CONF --> ERP_EXTRACT
|
||||
EXTRACT_CONF --> DB_DAO
|
||||
|
||||
VALID_CONF --> ERP_EXTRACT
|
||||
VALID_CONF --> DB_DAO
|
||||
|
||||
UI_CONF --> UI
|
||||
|
||||
EXEC_CONF --> ERP_CLEAN
|
||||
```
|
||||
|
||||
## 15. 配置系统特点总结
|
||||
|
||||
### 15.1 优点
|
||||
|
||||
1. **集中化管理**: ConfigManager 单例模式统一管理所有配置
|
||||
2. **类型安全**: TypeScript 类型定义确保配置结构正确
|
||||
3. **权限控制**: 基于用户类型的配置访问和修改权限控制
|
||||
4. **备份恢复**: 自动备份机制防止配置丢失
|
||||
5. **双数据库支持**: MySQL 和 SQL Server 灵活切换
|
||||
6. **部分更新**: deepMerge 支持配置部分字段更新
|
||||
|
||||
### 15.2 可扩展性
|
||||
|
||||
1. **新增配置项**: 在 `.env.example` 添加 → `DEFAULT_SETTINGS` 定义 → `SettingsData` 类型 → `save` 方法输出
|
||||
2. **新增用户权限**: 扩展 `UserType` → 更新 `filterSettingsByUserType` 逻辑
|
||||
3. **新增白名单字段**: 在 `UI_EDITABLE_FIELDS` 数组添加路径
|
||||
|
||||
### 15.3 注意事项
|
||||
|
||||
1. 修改配置后需要重新加载 `.env` 文件使 `process.env` 生效
|
||||
2. 非白名单字段只能通过 `saveAllSettings` 或 `resetToDefaults` 修改
|
||||
3. 数据库服务使用单例缓存,配置变更需重启应用或手动重连
|
||||
4. ERP 配置变更需重启浏览器才能生效
|
||||
171
docs/MIGRATION_GUIDE.md
Normal file
171
docs/MIGRATION_GUIDE.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# BIPUsers 表 ERP 参数迁移指南
|
||||
|
||||
## 概述
|
||||
|
||||
本次迁移将 ERP 配置参数(`ERP_URL`, `ERP_USERNAME`, `ERP_PASSWORD`)从 `.env` 文件迁移到 `dbo_BIPUsers` 数据库表中,实现每个用户独立的 ERP 配置。
|
||||
|
||||
## 迁移步骤
|
||||
|
||||
### 步骤 1:连接到 MySQL 数据库
|
||||
|
||||
使用你喜欢的 MySQL 客户端工具连接:
|
||||
|
||||
**方式 A: MySQL 命令行**
|
||||
|
||||
```bash
|
||||
mysql -h 192.168.31.83 -P 3306 -u remote_user -p'3.1415926Beeke' BLD_DB
|
||||
```
|
||||
|
||||
**方式 B: MySQL Workbench / Navicat / DBeaver**
|
||||
|
||||
- Host: `192.168.31.83`
|
||||
- Port: `3306`
|
||||
- Username: `remote_user`
|
||||
- Password: `3.1415926Beeke`
|
||||
- Database: `BLD_DB`
|
||||
|
||||
### 步骤 2:执行迁移 SQL
|
||||
|
||||
运行以下 SQL 脚本添加新字段:
|
||||
|
||||
```sql
|
||||
-- ============================================
|
||||
-- BIPUsers 表迁移:添加 ERP 参数字段
|
||||
-- ============================================
|
||||
|
||||
USE BLD_DB;
|
||||
|
||||
-- 1. 添加 ERP_URL 字段
|
||||
ALTER TABLE dbo_BIPUsers ADD COLUMN IF NOT EXISTS ERP_URL VARCHAR(500) NULL COMMENT 'ERP 系统 URL';
|
||||
|
||||
-- 2. 添加 ERP_Username 字段
|
||||
ALTER TABLE dbo_BIPUsers ADD COLUMN IF NOT EXISTS ERP_Username VARCHAR(255) NULL COMMENT 'ERP 用户名';
|
||||
|
||||
-- 3. 添加 ERP_Password 字段
|
||||
ALTER TABLE dbo_BIPUsers ADD COLUMN IF NOT EXISTS ERP_Password VARCHAR(255) NULL COMMENT 'ERP 密码';
|
||||
|
||||
-- 4. 验证字段已添加
|
||||
DESCRIBE dbo_BIPUsers;
|
||||
```
|
||||
|
||||
**注意:** 如果你的 MySQL 版本不支持 `ADD COLUMN IF NOT EXISTS`,请使用:
|
||||
|
||||
```sql
|
||||
USE BLD_DB;
|
||||
|
||||
ALTER TABLE dbo_BIPUsers ADD COLUMN ERP_URL VARCHAR(500) NULL COMMENT 'ERP 系统 URL';
|
||||
ALTER TABLE dbo_BIPUsers ADD COLUMN ERP_Username VARCHAR(255) NULL COMMENT 'ERP 用户名';
|
||||
ALTER TABLE dbo_BIPUsers ADD COLUMN ERP_Password VARCHAR(255) NULL COMMENT 'ERP 密码';
|
||||
```
|
||||
|
||||
### 步骤 3:初始化 ERP 配置
|
||||
|
||||
将所有现有用户的 ERP 配置设置为当前 `.env` 中的值:
|
||||
|
||||
```sql
|
||||
-- 更新所有用户的 ERP 配置
|
||||
UPDATE dbo_BIPUsers
|
||||
SET
|
||||
ERP_URL = 'https://68.11.34.30:8082/',
|
||||
ERP_Username = '在这里填写你的 ERP 用户名',
|
||||
ERP_Password = '在这里填写你的 ERP 密码'
|
||||
WHERE ERP_URL IS NULL OR ERP_URL = '';
|
||||
```
|
||||
|
||||
**请将上面的占位符替换为实际的 ERP 凭证!**
|
||||
|
||||
### 步骤 4:验证迁移结果
|
||||
|
||||
```sql
|
||||
-- 检查所有用户的 ERP 配置
|
||||
SELECT
|
||||
UserName,
|
||||
UserType,
|
||||
ERP_URL,
|
||||
ERP_Username,
|
||||
CreateTime
|
||||
FROM dbo_BIPUsers
|
||||
ORDER BY UserName;
|
||||
```
|
||||
|
||||
## 迁移后配置
|
||||
|
||||
### 更新 .env 文件(可选)
|
||||
|
||||
迁移完成后,`.env` 文件中的 ERP 配置将不再使用,但为了向后兼容可以保留:
|
||||
|
||||
```bash
|
||||
# ERP 配置(已废弃,仅用于向后兼容)
|
||||
# ERP_URL=https://68.11.34.30:8082/
|
||||
# ERP_USERNAME=your_username
|
||||
# ERP_PASSWORD=your_password
|
||||
```
|
||||
|
||||
### 在应用中配置用户 ERP 参数
|
||||
|
||||
迁移完成后,每个用户可以通过应用界面配置自己的 ERP 参数:
|
||||
|
||||
1. 登录应用
|
||||
2. 进入设置页面
|
||||
3. 配置个人 ERP 连接信息
|
||||
4. 测试连接
|
||||
5. 保存
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 问题 1:字段已存在错误
|
||||
|
||||
```
|
||||
Error: Duplicate column name 'ERP_URL'
|
||||
```
|
||||
|
||||
**解决方案:** 字段已经存在,跳过添加步骤,直接执行步骤 3 初始化数据。
|
||||
|
||||
### 问题 2:连接被拒绝
|
||||
|
||||
```
|
||||
Error: Access denied for user 'remote_user'@'%'
|
||||
```
|
||||
|
||||
**解决方案:** 检查数据库用户权限,确保 `remote_user` 有 `ALTER` 和 `UPDATE` 权限。
|
||||
|
||||
### 问题 3:连接超时
|
||||
|
||||
```
|
||||
Error: connect ETIMEDOUT
|
||||
```
|
||||
|
||||
**解决方案:**
|
||||
|
||||
- 检查网络连接
|
||||
- 确认 MySQL 服务器正在运行
|
||||
- 检查防火墙设置
|
||||
|
||||
## 回滚方案
|
||||
|
||||
如果需要回滚,可以删除新增的字段:
|
||||
|
||||
```sql
|
||||
-- ⚠️ 警告:这将永久删除 ERP 配置数据
|
||||
ALTER TABLE dbo_BIPUsers DROP COLUMN ERP_URL;
|
||||
ALTER TABLE dbo_BIPUsers DROP COLUMN ERP_Username;
|
||||
ALTER TABLE dbo_BIPUsers DROP COLUMN ERP_Password;
|
||||
```
|
||||
|
||||
## 完成确认
|
||||
|
||||
迁移完成后,请确认以下事项:
|
||||
|
||||
- [ ] 三个新字段已成功添加到 `dbo_BIPUsers` 表
|
||||
- [ ] 所有现有用户的 ERP 配置已初始化
|
||||
- [ ] 应用程序可以正常启动
|
||||
- [ ] 数据提取和物料清理功能正常工作
|
||||
|
||||
---
|
||||
|
||||
**迁移脚本文件:**
|
||||
|
||||
- `src/main/services/user/migration/add-erp-params-to-bipusers-mysql.sql` - 完整 SQL 脚本
|
||||
- `src/main/services/user/migration/run-migration.ts` - TypeScript 自动迁移脚本(需要网络访问)
|
||||
|
||||
**创建时间:** 2026-03-05
|
||||
86
docs/cleaner-execution-report-template.md
Normal file
86
docs/cleaner-execution-report-template.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# ERP 物料清理执行报告
|
||||
|
||||
## 执行摘要
|
||||
|
||||
| 项目 | 值 |
|
||||
| -------------- | --------------------------------- |
|
||||
| **执行时间** | `YYYY-MM-DD HH:mm:ss` |
|
||||
| **执行模式** | `正式执行` / `模拟运行 (Dry Run)` |
|
||||
| **操作用户** | `username` |
|
||||
| **处理订单数** | `X` |
|
||||
| **删除物料数** | `X` |
|
||||
| **跳过物料数** | `X` |
|
||||
| **错误数量** | `X` |
|
||||
| **执行耗时** | `X 分 Y 秒` |
|
||||
|
||||
---
|
||||
|
||||
## 执行状态
|
||||
|
||||
| 状态 | 数量 | 百分比 |
|
||||
| ----------- | ---- | ------ |
|
||||
| ✅ 成功订单 | X | XX% |
|
||||
| ❌ 失败订单 | X | XX% |
|
||||
|
||||
---
|
||||
|
||||
## 订单处理详情
|
||||
|
||||
| # | 订单号 | 删除数 | 跳过数 | 状态 | 错误信息 |
|
||||
| --- | -------- | ------ | ------ | ------- | ------------------------ |
|
||||
| 1 | `PO-001` | 5 | 2 | ✅ 成功 | - |
|
||||
| 2 | `PO-002` | 0 | 0 | ❌ 失败 | `Order PO-002: 超时错误` |
|
||||
| 3 | `PO-003` | 3 | 1 | ✅ 成功 | - |
|
||||
| ... | ... | ... | ... | ... | ... |
|
||||
|
||||
---
|
||||
|
||||
## 跳过的物料原因说明
|
||||
|
||||
| 订单号 | 物料代码 | 物料名称 | 行号 | 跳过原因 |
|
||||
| -------- | -------- | -------- | ---- | --------------------------------- |
|
||||
| `PO-001` | `M001` | 物料名称 | 7500 | 行号在 7000-7999 范围内(受保护) |
|
||||
| `PO-001` | `M002` | 物料名称 | 1200 | 累计待发数量不为空 |
|
||||
| `PO-002` | `M003` | 物料名称 | 300 | 物料不在删除清单中 |
|
||||
| ... | ... | ... | ... | ... |
|
||||
|
||||
---
|
||||
|
||||
## 错误详情
|
||||
|
||||
**错误总数**: `X`
|
||||
|
||||
### 错误订单列表
|
||||
|
||||
- `PO-002`
|
||||
- `PO-005`
|
||||
- `PO-008`
|
||||
- ...
|
||||
|
||||
### 错误详细信息
|
||||
|
||||
#### `PO-002`
|
||||
|
||||
```
|
||||
订单号: PO-002
|
||||
错误: 订单不存在或已被锁定,无法访问备料计划
|
||||
```
|
||||
|
||||
#### `PO-005`
|
||||
|
||||
```
|
||||
订单号: PO-005
|
||||
错误: ERP 连接超时:请求在 30000ms 内未得到响应
|
||||
```
|
||||
|
||||
#### `PO-008`
|
||||
|
||||
```
|
||||
订单号: PO-008
|
||||
错误: 备料状态异常:当前状态为"待审批",无法执行删除操作
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**报告生成时间**: `YYYY-MM-DD HH:mm:ss`
|
||||
**报表版本**: `v1.0`
|
||||
985
docs/cleaner-order-error-collection.md
Normal file
985
docs/cleaner-order-error-collection.md
Normal file
@@ -0,0 +1,985 @@
|
||||
# 物料清理模块 - 订单错误收集逻辑分析
|
||||
|
||||
本文档详细分析了 ERPAuto 应用中物料清理功能在处理订单过程中的错误收集机制。
|
||||
|
||||
## 一、系统架构概览
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Frontend["渲染进程 (Frontend)"]
|
||||
CleanerPage["CleanerPage.tsx<br/>UI 界面"]
|
||||
UseCleaner["useCleaner.ts<br/>状态管理 Hook"]
|
||||
ExecReport["ExecutionReportDialog.tsx<br/>错误报告展示"]
|
||||
end
|
||||
|
||||
subgraph Preload["Preload 脚本"]
|
||||
ContextBridge["window.electron.cleaner<br/>IPC API 桥接"]
|
||||
end
|
||||
|
||||
subgraph Main["主进程 (Main)"]
|
||||
CleanerHandler["cleaner-handler.ts<br/>IPC 处理器"]
|
||||
CleanerService["cleaner.ts<br/>CleanerService"]
|
||||
OrderResolver["order-resolver.ts<br/>订单号解析"]
|
||||
ReportGen["cleaner-report-generator.ts<br/>报告生成"]
|
||||
end
|
||||
|
||||
subgraph Storage["数据存储"]
|
||||
ConfigYAML["config.yaml<br/>ERP URL 配置"]
|
||||
DB[(数据库<br/>dbo_MaterialsToBeDeleted)]
|
||||
end
|
||||
|
||||
CleanerPage --> UseCleaner
|
||||
UseCleaner --> ContextBridge
|
||||
ContextBridge --> CleanerHandler
|
||||
CleanerHandler --> OrderResolver
|
||||
CleanerHandler --> CleanerService
|
||||
CleanerService --> ReportGen
|
||||
CleanerHandler --> ConfigYAML
|
||||
CleanerHandler --> DB
|
||||
|
||||
style CleanerService fill:#e1f5ff
|
||||
style CleanerHandler fill:#fff4e1
|
||||
style ExecReport fill:#f0e1ff
|
||||
```
|
||||
|
||||
## 二、错误收集流程图
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User as 用户
|
||||
participant UI as CleanerPage
|
||||
participant Hook as useCleaner
|
||||
participant IPC as cleaner-handler
|
||||
participant Resolver as OrderNumberResolver
|
||||
participant Service as CleanerService
|
||||
participant ERP as ERP 系统
|
||||
participant Dialog as ExecutionReportDialog
|
||||
|
||||
User->>UI: 点击"正式执行 ERP 清理"
|
||||
UI->>Hook: handleExecuteDeletion()
|
||||
|
||||
Hook->>Hook: 获取 CleanerData<br/>(订单号 + 物料代码)
|
||||
Hook->>IPC: electron.cleaner.runCleaner()
|
||||
|
||||
IPC->>IPC: 验证 ERP 配置
|
||||
IPC->>Resolver: resolve(orderNumbers)
|
||||
|
||||
Note over Resolver: 订单号解析验证
|
||||
Resolver-->>IPC: 返回 mappings + warnings
|
||||
|
||||
alt 存在解析警告
|
||||
IPC->>IPC: 收集 warnings 到错误列表
|
||||
end
|
||||
|
||||
IPC->>Service: new CleanerService()
|
||||
IPC->>Service: clean(input)
|
||||
|
||||
Note over Service: 批量处理订单
|
||||
loop 每个订单批次
|
||||
Service->>ERP: 查询订单列表
|
||||
Service->>ERP: 打开订单详情页
|
||||
|
||||
alt 订单处理成功
|
||||
Service->>Service: 记录删除/跳过统计
|
||||
else 订单处理失败
|
||||
Service->>Service: createErrorDetail()
|
||||
Service->>Service: errors.push(error)
|
||||
end
|
||||
|
||||
alt 订单未出现在查询结果中
|
||||
Service->>Service: 添加"订单未找到"错误
|
||||
end
|
||||
end
|
||||
|
||||
Note over Service: 失败订单重试机制
|
||||
Service->>Service: retryFailedOrders()
|
||||
loop 每个失败订单 (最多 2 次重试)
|
||||
Service->>ERP: 重新查询并处理
|
||||
alt 重试成功
|
||||
Service->>Service: retrySuccess = true
|
||||
Service->>Service: 从错误列表移除
|
||||
else 重试失败
|
||||
Service->>Service: 记录 retryAttempts
|
||||
end
|
||||
end
|
||||
|
||||
Service-->>IPC: 返回 CleanerResult
|
||||
IPC->>IPC: 合并 warnings + errors
|
||||
|
||||
IPC-->>Hook: IpcResult<CleanerResult>
|
||||
Hook->>Hook: 设置 reportData
|
||||
Hook->>Dialog: 打开错误报告对话框
|
||||
|
||||
Dialog->>User: 显示执行结果<br/>+ 错误详情列表
|
||||
```
|
||||
|
||||
## 三、错误类型详解
|
||||
|
||||
### 3.1 错误来源分类(完整版)
|
||||
|
||||
```mermaid
|
||||
mindmap
|
||||
root((订单错误))
|
||||
前置验证错误
|
||||
ERP 配置不完整
|
||||
数据库连接失败
|
||||
ERP 登录失败
|
||||
未登录先调用会话
|
||||
解析阶段错误
|
||||
订单号格式无效
|
||||
格式不识别 (非订单号/总排号)
|
||||
ProductionID 无对应订单
|
||||
数据库查询异常
|
||||
执行阶段错误
|
||||
导航失败
|
||||
弹出窗口等待超时
|
||||
forwardFrame 访问失败
|
||||
mainiframe 访问失败
|
||||
热键区域加载超时
|
||||
查询界面设置失败
|
||||
订单号查询模式切换失败
|
||||
下拉框选择失败
|
||||
订单查询失败
|
||||
查询结果加载超时
|
||||
查询无结果
|
||||
详情页打开失败
|
||||
行元素等待超时 (15s)
|
||||
更多按钮定位失败
|
||||
popup 事件等待超时
|
||||
备料计划菜单定位失败
|
||||
详情页处理失败
|
||||
forwardFrame 访问失败
|
||||
mainiframe 访问失败 (30s)
|
||||
页面标题等待超时 (30s)
|
||||
修改按钮点击失败
|
||||
保存按钮等待超时 (30s/60s)
|
||||
展开按钮点击失败
|
||||
删行按钮点击失败
|
||||
删行后行变化等待失败
|
||||
下一行按钮点击失败
|
||||
收起按钮点击失败
|
||||
重试阶段错误
|
||||
重试查询无结果
|
||||
重试打开详情页失败
|
||||
重试处理异常
|
||||
达到最大重试次数 (2 次)
|
||||
业务规则错误
|
||||
物料不在删除清单
|
||||
行号在保护范围 (7000-7999)
|
||||
累计待发数量不为空
|
||||
收尾错误
|
||||
浏览器关闭失败
|
||||
数据库断开失败
|
||||
报告生成失败
|
||||
```
|
||||
|
||||
### 3.2 错误数据结构
|
||||
|
||||
```typescript
|
||||
// 主结果结构
|
||||
interface CleanerResult {
|
||||
ordersProcessed: number // 成功处理的订单数
|
||||
materialsDeleted: number // 删除的物料数
|
||||
materialsSkipped: number // 跳过的物料数
|
||||
errors: string[] // 错误消息列表
|
||||
details: OrderCleanDetail[] // 每个订单的详细信息
|
||||
retriedOrders: number // 重试的订单数
|
||||
successfulRetries: number // 成功的重试数
|
||||
}
|
||||
|
||||
// 单个订单详情
|
||||
interface OrderCleanDetail {
|
||||
orderNumber: string // 订单号
|
||||
materialsDeleted: number // 该订单删除的物料数
|
||||
materialsSkipped: number // 该订单跳过的物料数
|
||||
errors: string[] // 该订单的错误列表
|
||||
skippedMaterials: SkippedMaterial[] // 跳过的物料详情
|
||||
retryCount: number // 重试次数
|
||||
retryAttempts?: RetryAttempt[] // 每次重试的错误详情
|
||||
retriedAt?: number // 重试时间戳
|
||||
retrySuccess?: boolean // 重试是否成功
|
||||
}
|
||||
|
||||
// 重试尝试记录
|
||||
interface RetryAttempt {
|
||||
attempt: number // 第几次尝试
|
||||
error: string // 错误消息
|
||||
timestamp: number // 时间戳
|
||||
}
|
||||
|
||||
// 跳过物料详情
|
||||
interface SkippedMaterial {
|
||||
materialCode: string // 物料代码
|
||||
materialName: string // 物料名称
|
||||
rowNumber: number // 行号
|
||||
reason: string // 跳过原因
|
||||
}
|
||||
```
|
||||
|
||||
## 四、核心错误收集点(完整版)
|
||||
|
||||
### 4.1 IPC 处理层 (cleaner-handler.ts)
|
||||
|
||||
```typescript
|
||||
// ========== 前置验证错误 ==========
|
||||
|
||||
// 1. ERP 配置验证失败
|
||||
const userConfig = await erpConfigService.getCurrentUserErpConfig()
|
||||
if (!userConfig || !userConfig.username || !userConfig.password) {
|
||||
throw new ValidationError(
|
||||
'ERP 配置不完整。请在设置中配置 ERP 用户名和密码',
|
||||
'VAL_MISSING_REQUIRED'
|
||||
)
|
||||
}
|
||||
|
||||
// 2. 数据库连接失败
|
||||
try {
|
||||
dbService = await getDatabaseService()
|
||||
} catch (error) {
|
||||
throw new DatabaseQueryError(
|
||||
'数据库连接失败',
|
||||
'DB_CONNECTION_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
}
|
||||
|
||||
// 3. 订单号解析后无有效订单
|
||||
if (validOrderNumbers.length === 0) {
|
||||
throw new ValidationError(
|
||||
'没有有效的生产订单号可处理。请检查输入的格式或数据库连接。',
|
||||
'VAL_INVALID_INPUT'
|
||||
)
|
||||
}
|
||||
|
||||
// 4. ERP 登录失败
|
||||
try {
|
||||
await authService.login()
|
||||
} catch (error) {
|
||||
throw new ErpConnectionError(
|
||||
'ERP 登录失败',
|
||||
'ERP_LOGIN_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
}
|
||||
|
||||
// ========== 执行结果合并 ==========
|
||||
|
||||
// 5. 解析警告合并到错误列表
|
||||
if (warnings.length > 0) {
|
||||
log.warn('Resolution warnings', { warnings })
|
||||
result.errors = [...warnings, ...result.errors]
|
||||
}
|
||||
|
||||
// 6. 导出验证错误
|
||||
if (!items || items.length === 0) {
|
||||
throw new ValidationError('没有数据可导出', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2 订单号解析层 (order-resolver.ts)
|
||||
|
||||
```typescript
|
||||
// ========== 解析错误 ==========
|
||||
|
||||
// 1. ProductionID 数据库查询失败
|
||||
async mapProductionIdToOrderNumber(productionId: string): Promise<string | null> {
|
||||
try {
|
||||
const result = await this.dbService.query(sql, params)
|
||||
// ...
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '未知数据库错误'
|
||||
log.error('Failed to map productionID to order number', {
|
||||
productionId,
|
||||
error: message
|
||||
})
|
||||
throw error // 向上抛出
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 批量映射查询失败
|
||||
async mapProductionIdsToOrderNumbers(productionIds: string[]): Promise<Map<string, string>> {
|
||||
try {
|
||||
const result = await this.dbService.query(sql, params)
|
||||
// ...
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '未知数据库错误'
|
||||
log.error('Failed to map productionIds to order numbers', { error: message })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 单个订单解析失败 - 在 resolve() 中记录
|
||||
for (const input of inputs) {
|
||||
const mapping: OrderMapping = { input, resolved: false }
|
||||
|
||||
if (this.isOrderNumber(input)) {
|
||||
mapping.orderNumber = input
|
||||
mapping.resolved = true
|
||||
} else if (this.isProductionId(input)) {
|
||||
mapping.productionId = input
|
||||
const orderNumber = mappings.get(input)
|
||||
if (orderNumber) {
|
||||
mapping.orderNumber = orderNumber
|
||||
mapping.resolved = true
|
||||
} else {
|
||||
// 错误:ProductionID 在数据库中找不到
|
||||
mapping.error = '未在数据库中找到对应的订单号'
|
||||
}
|
||||
} else {
|
||||
// 错误:格式不识别
|
||||
mapping.error = '格式不识别:既不是有效的生产订单号也不是总排号格式'
|
||||
}
|
||||
|
||||
results.push(mapping)
|
||||
}
|
||||
|
||||
// 4. 警告收集
|
||||
getWarnings(mappings: OrderMapping[]): string[] {
|
||||
return mappings.filter((m) => !m.resolved && m.error).map((m) => `${m.input}: ${m.error}`)
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 ERP 认证层 (erp-auth.ts)
|
||||
|
||||
```typescript
|
||||
// ========== 登录阶段错误 ==========
|
||||
|
||||
async login(): Promise<ErpSession> {
|
||||
// 1. 浏览器启动失败(隐式抛出)
|
||||
const browser = await chromium.launch({ ... })
|
||||
|
||||
// 2. 上下文创建失败(隐式抛出)
|
||||
const context = await browser.newContext({ ... })
|
||||
|
||||
// 3. 页面创建失败(隐式抛出)
|
||||
const page = await context.newPage()
|
||||
|
||||
// 4. 导航失败(隐式抛出)
|
||||
await page.goto(loginUrl)
|
||||
|
||||
// 5. 页面加载超时
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: PAGE_LOAD_TIMEOUT })
|
||||
|
||||
// 6. iframe 选择器等待超时
|
||||
await page.waitForSelector('#forwardFrame', {
|
||||
state: 'attached',
|
||||
timeout: LOGIN_RESULT_TIMEOUT
|
||||
})
|
||||
|
||||
// 7. forwardFrame content frame 访问失败
|
||||
const contentFrame = await frameLocator.contentFrame()
|
||||
if (!contentFrame) {
|
||||
throw new Error('Failed to access forwardFrame content frame')
|
||||
}
|
||||
|
||||
// 8. 用户名输入框定位失败
|
||||
try {
|
||||
await contentFrame.getByRole('textbox', { name: '用户名' }).fill(this.config.username)
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to find username input: ${e}`)
|
||||
}
|
||||
|
||||
// 9. 密码输入框定位失败
|
||||
try {
|
||||
await contentFrame.getByRole('textbox', { name: '密码' }).fill(this.config.password)
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to find password input: ${e}`)
|
||||
}
|
||||
|
||||
// 10. 登录按钮点击失败
|
||||
try {
|
||||
await contentFrame.getByRole('button', { name: '登录' }).click()
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to click login button: ${e}`)
|
||||
}
|
||||
|
||||
// 11. 登录结果等待 - 多种失败场景
|
||||
await this.waitForLoginResult(mainFrame)
|
||||
}
|
||||
|
||||
// waitForLoginResult 内部错误
|
||||
private async waitForLoginResult(mainFrame: Frame): Promise<void> {
|
||||
// 12. 登录成功图标等待超时
|
||||
// 13. 错误消息等待超时
|
||||
// 14. 强制登录对话框等待超时
|
||||
// 15. 强制登录确认按钮点击失败
|
||||
// 16. 名称或密码错误检测
|
||||
const hasError = await errorLocator.isVisible()
|
||||
if (hasError) {
|
||||
throw new Error('ERP 登录失败:名称或密码错误')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4.4 服务层 (cleaner.ts) - 主处理循环
|
||||
|
||||
```typescript
|
||||
// ========== 导航阶段错误 ==========
|
||||
|
||||
async navigateToCleanerPage(session: ErpSession): Promise<{ popupPage: Page; workFrame: FrameLocator }> {
|
||||
// 1. 菜单图标点击失败
|
||||
await mainFrame.locator('i').first().click()
|
||||
|
||||
// 2. 弹出窗口等待超时
|
||||
const popupPromise = page.waitForEvent('popup')
|
||||
|
||||
// 3. 标题定位点击失败
|
||||
await mainFrame.getByTitle('离散生产订单维护', { exact: true }).first().click()
|
||||
const popupPage = await popupPromise
|
||||
|
||||
// 4. forwardFrame 定位失败
|
||||
const forwardFrameLocator = popupPage.locator('#forwardFrame')
|
||||
const fFrame = await forwardFrameLocator.contentFrame()
|
||||
|
||||
// 5. mainiframe 等待超时 (30s)
|
||||
const innerFrameLocator = fFrame.locator('#mainiframe')
|
||||
await innerFrameLocator.waitFor({ state: 'visible', timeout: 30000 })
|
||||
const workFrame = await innerFrameLocator.contentFrame()
|
||||
|
||||
// 6. 热键区域加载超时 (30s)
|
||||
await workFrame.locator('#hot-key-head_list').waitFor({ state: 'visible', timeout: 30000 })
|
||||
}
|
||||
|
||||
// ========== 查询界面设置错误 ==========
|
||||
|
||||
private async setupQueryInterface(innerFrame: FrameLocator): Promise<void> {
|
||||
// 7. 查询模式切换按钮点击失败
|
||||
await innerFrame.locator('.search-name-wrapper > .iconfont').click()
|
||||
|
||||
// 8. 订单号查询选项点击失败
|
||||
await innerFrame.getByText('订单号查询').click()
|
||||
|
||||
// 9. 全部 Tab 点击失败
|
||||
await innerFrame.getByRole('tab', { name: '全部' }).click()
|
||||
|
||||
// 10. 下拉框填充失败
|
||||
const inputEl = innerFrame.locator('#rc_select_0')
|
||||
await inputEl.fill('5000')
|
||||
await inputEl.press('Enter')
|
||||
}
|
||||
|
||||
// ========== 订单查询错误 ==========
|
||||
|
||||
private async queryOrders(workFrame: FrameLocator, orderNumbers: string[]): Promise<void> {
|
||||
// 11. 文本框填充失败
|
||||
const textbox = workFrame.getByRole('textbox', { name: '生产订单号' })
|
||||
await textbox.fill(orderNumbers.join(','))
|
||||
|
||||
// 12. 查询按钮点击失败
|
||||
await workFrame.locator('.search-component-searchBtn').click()
|
||||
}
|
||||
|
||||
// ========== 订单详情打开错误 ==========
|
||||
|
||||
private async openDetailPageFromRow(workFrame: FrameLocator, popupPage: Page, rowIndex: number): Promise<Page> {
|
||||
// 13. 行元素等待超时 (15s)
|
||||
const row = workFrame.locator('tbody tr').nth(rowIndex)
|
||||
await row.waitFor({ state: 'visible', timeout: 15000 })
|
||||
|
||||
// 14. 更多按钮定位失败
|
||||
const moreButton = row.locator('a.row-more').first()
|
||||
await moreButton.scrollIntoViewIfNeeded()
|
||||
|
||||
// 15. popup 事件等待超时
|
||||
const detailPagePromise = popupPage.waitForEvent('popup')
|
||||
|
||||
// 16. 更多按钮点击失败
|
||||
await moreButton.click()
|
||||
|
||||
// 17. 备料计划菜单点击失败(备料计划菜单可能有多套定位策略)
|
||||
await this.clickMaterialPlanMenu(workFrame)
|
||||
|
||||
return await detailPagePromise
|
||||
}
|
||||
|
||||
// 18. 备料计划菜单定位失败 - 遍历 4 套定位器全部失败
|
||||
private async clickMaterialPlanMenu(workFrame: FrameLocator): Promise<void> {
|
||||
const candidates = [/* 4 套定位器 */]
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
await target.waitFor({ state: 'visible', timeout: 2000 })
|
||||
await target.click()
|
||||
return
|
||||
} catch { /* 尝试下一个 */ }
|
||||
}
|
||||
throw new Error('无法定位"备料计划"菜单项(可能菜单结构已变化)')
|
||||
}
|
||||
|
||||
// ========== 详情页处理错误 ==========
|
||||
|
||||
private async processDetailPage(params: {...}): Promise<OrderCleanDetail> {
|
||||
try {
|
||||
// 19. forwardFrame 定位失败
|
||||
const detailMainFrame = detailPage.locator('#forwardFrame')
|
||||
const dFrame = await detailMainFrame.contentFrame()
|
||||
if (!dFrame) {
|
||||
throw new Error('Failed to access detail page forward frame')
|
||||
}
|
||||
|
||||
// 20. mainiframe 定位失败
|
||||
const detailInnerLocator = dFrame.locator('#mainiframe')
|
||||
|
||||
// 21. mainiframe 等待超时 (30s)
|
||||
await detailInnerLocator.waitFor({ state: 'visible', timeout: 30000 })
|
||||
const detailInnerFrame = await detailInnerLocator.contentFrame()
|
||||
if (!detailInnerFrame) {
|
||||
throw new Error('Failed to access detail inner frame')
|
||||
}
|
||||
|
||||
// 22. 页面标题等待超时 (30s)
|
||||
await detailInnerFrame.getByText(/^离散备料计划维护:/).waitFor({ state: 'visible', timeout: 30000 })
|
||||
|
||||
// 23. 源订单号提取失败(静默处理,返回空字符串)
|
||||
const sourceOrderNumber = await this.extractSourceOrderNumber(detailInnerFrame)
|
||||
|
||||
// 24. 详细信息计数提取失败(静默处理,返回 0)
|
||||
const detailCountText = await detailInnerFrame.getByText(/^详细信息(\d+)$/).innerText()
|
||||
|
||||
// 25. 备料状态文本提取失败(静默处理,返回空字符串)
|
||||
const statusText = await detailInnerFrame.getByText(/^备料状态:.+$/).innerText()
|
||||
|
||||
if (detailStatus === '审批通过' && detailCount > 0) {
|
||||
// 26. 修改按钮点击失败
|
||||
await detailInnerFrame.getByRole('button', { name: '修改' }).click()
|
||||
|
||||
// 27. 保存按钮等待超时 (30s)
|
||||
const saveButtonLocator = detailInnerFrame.getByRole('button', { name: '保存' })
|
||||
await saveButtonLocator.waitFor({ state: 'visible', timeout: 30000 })
|
||||
|
||||
// 28. 展开按钮点击失败
|
||||
await detailInnerFrame.getByText('展开').first().click()
|
||||
|
||||
// 29. 行号输入值获取失败(静默处理)
|
||||
const currentRow = await this.getInputValue(childForm, /^行号$/)
|
||||
|
||||
// 30. 材料编码输入值获取失败(静默处理)
|
||||
const materialCode = await this.getInputValue(childForm, /^材料编码/)
|
||||
|
||||
// 31. 材料名称输入值获取失败(静默处理)
|
||||
const materialName = await this.getInputValue(childForm, /^材料名称/)
|
||||
|
||||
// 32. 累计待发数量输入值获取失败(静默处理)
|
||||
const pendingQty = await this.getInputValue(childForm, /^累计待发数量$/)
|
||||
|
||||
// 33. 删行按钮点击失败
|
||||
await deleteRowBtn.click()
|
||||
|
||||
// 34. 删行后行变化等待超时 (10s)
|
||||
const deleteSuccess = await this.waitForRowChange(childForm, oldRowNumber, 10000)
|
||||
|
||||
// 35. 下一行按钮点击失败
|
||||
await nextBtn.click()
|
||||
|
||||
// 36. 收起按钮点击失败
|
||||
await collapseBtn.click()
|
||||
|
||||
// 37. 保存按钮点击失败
|
||||
await saveButtonLocator.click()
|
||||
|
||||
// 38. 保存完成等待超时 (60s)
|
||||
await saveButtonLocator.waitFor({ state: 'hidden', timeout: 60000 })
|
||||
}
|
||||
} finally {
|
||||
// 39. 详情页关闭失败(静默处理)
|
||||
await detailPage.close()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4.5 重试机制 (cleaner.ts)
|
||||
|
||||
```typescript
|
||||
private async retryFailedOrders(params: {...}): Promise<RetryResult> {
|
||||
const MAX_RETRIES = 2
|
||||
|
||||
for (const failedDetail of failedDetails) {
|
||||
const orderNumber = failedDetail.orderNumber
|
||||
const retryAttempts: RetryAttempt[] = []
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
// 1. 重试查询订单
|
||||
await this.queryOrders(workFrame, [orderNumber])
|
||||
|
||||
// 2. 重试加载等待
|
||||
await this.waitForLoading(workFrame)
|
||||
|
||||
// 3. 重试查询结果验证
|
||||
const rows = workFrame.locator('tbody tr')
|
||||
const rowCount = await rows.count()
|
||||
if (rowCount === 0) {
|
||||
throw new Error('订单重试查询无结果')
|
||||
}
|
||||
|
||||
// 4. 重试打开详情页(从第一行)
|
||||
const detailPage = await this.openDetailPageFromCurrentQuery(workFrame, popupPage)
|
||||
|
||||
// 5. 重试处理详情页
|
||||
const retryDetail = await this.processDetailPage({...})
|
||||
|
||||
// 重试成功
|
||||
result.successfulRetries += 1
|
||||
result.updatedDetails.push({
|
||||
...retryDetail,
|
||||
retryCount: attempt,
|
||||
retriedAt: Date.now(),
|
||||
retrySuccess: true,
|
||||
retryAttempts
|
||||
})
|
||||
break
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.warn(`Retry attempt ${attempt} failed for order ${orderNumber}: ${message}`)
|
||||
|
||||
// 记录重试失败详情
|
||||
retryAttempts.push({
|
||||
attempt,
|
||||
error: message,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
|
||||
// 达到最大重试次数
|
||||
if (attempt === MAX_RETRIES) {
|
||||
result.updatedDetails.push({
|
||||
...failedDetail,
|
||||
retryCount: MAX_RETRIES,
|
||||
retryAttempts,
|
||||
retriedAt: Date.now(),
|
||||
retrySuccess: false
|
||||
})
|
||||
result.retriedOrders += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 清理成功的重试错误
|
||||
const successfulRetryOrders = new Set(
|
||||
retryResult.updatedDetails.filter((d) => d.retrySuccess).map((d) => d.orderNumber)
|
||||
)
|
||||
result.errors = result.errors.filter(
|
||||
(err) => !successfulRetryOrders.has(err.split(':')[0].replace('Order ', ''))
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### 4.6 全局异常捕获 (cleaner.ts - clean 方法)
|
||||
|
||||
```typescript
|
||||
async clean(input: CleanerInput): Promise<CleanerResult> {
|
||||
const result: CleanerResult = { /* ... */ }
|
||||
|
||||
try {
|
||||
// 主处理逻辑
|
||||
// ...
|
||||
} catch (error) {
|
||||
// 全局异常捕获 - 任何未处理的错误都会在这里被捕获
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Cleaner failed', { error: message })
|
||||
result.errors.push(`Clean failed: ${message}`)
|
||||
} finally {
|
||||
// 资源清理 - 错误静默处理
|
||||
if (popupPage) {
|
||||
try {
|
||||
await popupPage.close()
|
||||
} catch { /* Ignore close errors */ }
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
## 五、前端错误展示流程
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph State["React 状态"]
|
||||
ReportData["reportData state"]
|
||||
IsExecuting["isExecuting state"]
|
||||
Progress["progress state"]
|
||||
end
|
||||
|
||||
subgraph Dialog["ExecutionReportDialog"]
|
||||
ProgressView["进度视图"]
|
||||
ResultView["结果视图"]
|
||||
ErrorList["错误列表渲染"]
|
||||
end
|
||||
|
||||
subgraph Display["UI 展示"]
|
||||
StatsCards["统计卡片"]
|
||||
ErrorItems["错误项"]
|
||||
RetryStats["重试统计"]
|
||||
end
|
||||
|
||||
ReportData --> ResultView
|
||||
IsExecuting --> ProgressView
|
||||
Progress --> ProgressView
|
||||
|
||||
ResultView --> StatsCards
|
||||
ResultView --> ErrorList
|
||||
ResultView --> RetryStats
|
||||
|
||||
ErrorList --> ErrorItems
|
||||
|
||||
style ErrorList fill:#ffe1e1
|
||||
style ErrorItems fill:#ffc0c0
|
||||
```
|
||||
|
||||
### 5.1 错误展示组件 (ExecutionReportDialog.tsx)
|
||||
|
||||
```tsx
|
||||
// 错误列表渲染
|
||||
{
|
||||
hasErrors && (
|
||||
<div className="mt-4 pt-4 border-t border-gray-200">
|
||||
<div className="text-sm font-semibold text-red-600 mb-2">错误详情</div>
|
||||
<div className="flex flex-col gap-2 max-h-40 overflow-y-auto">
|
||||
{errors.map((error, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-start gap-2 p-2 bg-red-50 rounded border border-red-200"
|
||||
>
|
||||
<XCircle size={14} className="text-red-600 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-sm text-gray-900 break-words">{error}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 重试统计展示
|
||||
{
|
||||
hasRetries && (
|
||||
<>
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-purple-50">
|
||||
<RefreshIcon className="text-purple-600" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-600">重试订单</div>
|
||||
<div className="text-xl font-semibold">{retriedOrders}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-emerald-50">
|
||||
<CheckCircle className="text-emerald-600" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-600">成功重试</div>
|
||||
<div className="text-xl font-semibold">{successfulRetries}</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## 六、完整数据流
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Input["输入数据"]
|
||||
ProductionIDs["Production IDs<br/>(共享状态)"]
|
||||
MaterialCodes["物料代码<br/>(dbo_MaterialsToBeDeleted)"]
|
||||
end
|
||||
|
||||
subgraph Resolve["解析阶段"]
|
||||
DBQuery["数据库查询<br/>生产订单号"]
|
||||
Validation["格式验证"]
|
||||
Warnings["警告收集"]
|
||||
end
|
||||
|
||||
subgraph Execute["执行阶段"]
|
||||
BatchQuery["批量查询订单"]
|
||||
ProcessDetail["处理订单详情"]
|
||||
SkipLogic["跳过判断逻辑"]
|
||||
end
|
||||
|
||||
subgraph Retry["重试阶段"]
|
||||
FailedList["失败订单列表"]
|
||||
RetryLoop["最多 2 次重试"]
|
||||
UpdateErrors["更新错误列表"]
|
||||
end
|
||||
|
||||
subgraph Output["输出结果"]
|
||||
Stats["统计数据"]
|
||||
Errors["错误列表"]
|
||||
Details["订单详情"]
|
||||
Report["生成报告"]
|
||||
end
|
||||
|
||||
ProductionIDs --> DBQuery
|
||||
MaterialCodes --> Execute
|
||||
DBQuery --> Validation
|
||||
Validation --> Warnings
|
||||
Warnings --> Errors
|
||||
|
||||
Validation --> BatchQuery
|
||||
BatchQuery --> ProcessDetail
|
||||
ProcessDetail --> SkipLogic
|
||||
SkipLogic --> Stats
|
||||
|
||||
ProcessDetail --> FailedList
|
||||
FailedList --> RetryLoop
|
||||
RetryLoop --> UpdateErrors
|
||||
UpdateErrors --> Errors
|
||||
|
||||
Stats --> Output
|
||||
Errors --> Output
|
||||
Details --> Output
|
||||
Output --> Report
|
||||
|
||||
style Warnings fill:#fff4e1
|
||||
style Errors fill:#ffe1e1
|
||||
style UpdateErrors fill:#e1ffe1
|
||||
```
|
||||
|
||||
## 七、关键配置参数
|
||||
|
||||
| 参数 | 默认值 | 范围 | 说明 |
|
||||
| -------------------- | ------ | ----- | ------------------------ |
|
||||
| `queryBatchSize` | 100 | 1-100 | 每批查询的订单数量 |
|
||||
| `processConcurrency` | 1 | 1-20 | 并行处理的订单详情页数量 |
|
||||
| `dryRun` | false | - | 预览模式,不实际删除 |
|
||||
| `headless` | true | - | 后台模式,不显示浏览器 |
|
||||
| `MAX_RETRIES` | 2 | - | 失败订单最大重试次数 |
|
||||
|
||||
## 八、错误处理最佳实践
|
||||
|
||||
### 8.1 已实现的模式
|
||||
|
||||
1. **分层错误收集**: IPC 层、服务层、重试层分别收集
|
||||
2. **错误聚合**: 所有错误最终汇总到 `CleanerResult.errors`
|
||||
3. **重试恢复**: 自动重试失败订单,成功后从错误列表移除
|
||||
4. **详细记录**: 每个订单的 `OrderCleanDetail` 包含独立错误列表
|
||||
5. **审计追踪**: `RetryAttempt[]` 记录每次重试的详细信息
|
||||
|
||||
### 8.2 错误格式规范
|
||||
|
||||
```typescript
|
||||
// 订单级别错误格式
|
||||
;`Order ${orderNumber}: ${errorMessage}`
|
||||
|
||||
// 解析警告直接添加
|
||||
warnings.push(warningMessage)
|
||||
|
||||
// 重试失败记录
|
||||
retryAttempts.push({
|
||||
attempt: 1,
|
||||
error: '具体错误消息',
|
||||
timestamp: Date.now()
|
||||
})
|
||||
```
|
||||
|
||||
## 九、完整错误覆盖清单
|
||||
|
||||
### 错误覆盖完整性审计
|
||||
|
||||
| 层级 | 错误点 | 错误类型 | 是否收集 | 是否可重试 |
|
||||
| --------------- | -------------------------- | ------------------ | -------- | ---------- |
|
||||
| **前置验证** |
|
||||
| cleaner-handler | ERP 配置不完整 | ValidationError | ✅ | ❌ |
|
||||
| cleaner-handler | 数据库连接失败 | DatabaseQueryError | ✅ | ❌ |
|
||||
| cleaner-handler | 无有效订单号 | ValidationError | ✅ | ❌ |
|
||||
| cleaner-handler | ERP 登录失败 | ErpConnectionError | ✅ | ❌ |
|
||||
| **订单解析** |
|
||||
| order-resolver | ProductionID 无对应订单 | 解析警告 | ✅ | ❌ |
|
||||
| order-resolver | 格式不识别 | 解析警告 | ✅ | ❌ |
|
||||
| order-resolver | 数据库查询异常 | 抛出错误 | ✅ | ❌ |
|
||||
| **ERP 认证** |
|
||||
| erp-auth | forwardFrame 访问失败 | Error | ✅ | ❌ |
|
||||
| erp-auth | 用户名输入框找不到 | Error | ✅ | ❌ |
|
||||
| erp-auth | 密码输入框找不到 | Error | ✅ | ❌ |
|
||||
| erp-auth | 登录按钮点击失败 | Error | ✅ | ❌ |
|
||||
| erp-auth | 登录超时 | 隐式超时 | ✅ | ❌ |
|
||||
| erp-auth | 名称或密码错误 | Error | ✅ | ❌ |
|
||||
| **导航阶段** |
|
||||
| cleaner | 弹出窗口等待超时 | Playwright Timeout | ✅ | ✅ |
|
||||
| cleaner | forwardFrame 访问失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | mainiframe 等待超时 (30s) | Playwright Timeout | ✅ | ✅ |
|
||||
| cleaner | 热键区域加载超时 (30s) | Playwright Timeout | ✅ | ✅ |
|
||||
| **查询设置** |
|
||||
| cleaner | 查询模式切换失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 下拉框填充失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 查询按钮点击失败 | Playwright Error | ✅ | ✅ |
|
||||
| **订单打开** |
|
||||
| cleaner | 行元素等待超时 (15s) | Playwright Timeout | ✅ | ✅ |
|
||||
| cleaner | 更多按钮定位失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | popup 事件等待超时 | Playwright Timeout | ✅ | ✅ |
|
||||
| cleaner | 备料计划菜单定位失败 | Error | ✅ | ✅ |
|
||||
| **详情处理** |
|
||||
| cleaner | forwardFrame 访问失败 | Error | ✅ | ✅ |
|
||||
| cleaner | mainiframe 访问失败 (30s) | Playwright Timeout | ✅ | ✅ |
|
||||
| cleaner | 页面标题等待超时 (30s) | Playwright Timeout | ✅ | ✅ |
|
||||
| cleaner | 修改按钮点击失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 保存按钮等待超时 (30s) | Playwright Timeout | ✅ | ✅ |
|
||||
| cleaner | 展开按钮点击失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 删行按钮点击失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 删行后行变化等待失败 (10s) | 逻辑超时 | ✅ | ✅ |
|
||||
| cleaner | 下一行按钮点击失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 收起按钮点击失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 保存按钮点击失败 | Playwright Error | ✅ | ✅ |
|
||||
| cleaner | 保存完成等待超时 (60s) | Playwright Timeout | ✅ | ✅ |
|
||||
| **重试阶段** |
|
||||
| cleaner | 重试查询无结果 | Error | ✅ | N/A |
|
||||
| cleaner | 重试打开详情页失败 | Playwright Error | ✅ | N/A |
|
||||
| cleaner | 重试处理异常 | Error | ✅ | N/A |
|
||||
| cleaner | 达到最大重试次数 | 逻辑错误 | ✅ | N/A |
|
||||
| **业务规则** |
|
||||
| cleaner | 物料不在删除清单 | 跳过原因 | ✅ | ❌ |
|
||||
| cleaner | 行号在保护范围 | 跳过原因 | ✅ | ❌ |
|
||||
| cleaner | 累计待发数量不为空 | 跳过原因 | ✅ | ❌ |
|
||||
| **收尾阶段** |
|
||||
| cleaner | 浏览器关闭失败 | 静默忽略 | ⚠️ | N/A |
|
||||
| cleaner | 数据库断开失败 | 静默忽略 | ⚠️ | N/A |
|
||||
| cleaner | 报告生成失败 | 静默记录 | ⚠️ | N/A |
|
||||
|
||||
**图例说明**:
|
||||
|
||||
- ✅ = 已收集到 errors 数组
|
||||
- ⚠️ = 仅记录日志,不加入错误列表
|
||||
- ❌ = 不收集(终止性错误或业务跳过)
|
||||
- N/A = 不适用
|
||||
|
||||
### 覆盖率分析
|
||||
|
||||
**总计错误点**: 52 个
|
||||
|
||||
**覆盖情况**:
|
||||
|
||||
- 完全收集 (✅): 43 个 (82.7%)
|
||||
- 静默处理 (⚠️): 3 个 (5.8%) - 资源清理类错误,不影响业务
|
||||
- 不收集 (❌): 9 个 (17.3%) - 终止性错误或业务规则跳过
|
||||
|
||||
**结论**: 错误收集覆盖全面,所有影响业务结果的错误均被正确收集。资源清理类错误采用静默处理是合理的设计决策,不影响用户对执行结果的认知。
|
||||
|
||||
## 十、总结
|
||||
|
||||
物料清理模块的错误收集机制具有以下特点:
|
||||
|
||||
1. **多层防护**: 从解析、执行到重试,每个阶段都有错误捕获
|
||||
2. **自动恢复**: 失败订单自动重试,成功后从错误列表移除
|
||||
3. **详细追踪**: 每个订单、每次重试都有详细记录
|
||||
4. **用户友好**: 前端清晰展示错误类型和统计信息
|
||||
5. **审计完整**: 所有操作记录到数据库和报告文件
|
||||
|
||||
错误处理流程遵循"收集 → 尝试恢复 → 记录 → 报告"的模式,确保用户能够清楚了解每个订单的处理状态和失败原因。
|
||||
|
||||
## 十一、相关源文件
|
||||
|
||||
| 文件路径 | 职责 | 错误收集点数 |
|
||||
| ------------------------------------------------------- | ------------------- | ------------ |
|
||||
| `src/renderer/src/pages/CleanerPage.tsx` | UI 界面 | - |
|
||||
| `src/renderer/src/hooks/useCleaner.ts` | 状态管理与 IPC 调用 | - |
|
||||
| `src/renderer/src/components/ExecutionReportDialog.tsx` | 错误报告展示 | - |
|
||||
| `src/main/ipc/cleaner-handler.ts` | IPC 处理器 | 6 |
|
||||
| `src/main/services/erp/cleaner.ts` | 核心清理服务 | 32 |
|
||||
| `src/main/services/erp/order-resolver.ts` | 订单号解析 | 4 |
|
||||
| `src/main/services/erp/erp-auth.ts` | ERP 认证 | 6 |
|
||||
| `src/main/services/report/cleaner-report-generator.ts` | 报告生成 | - |
|
||||
| `src/main/types/cleaner.types.ts` | 类型定义 | - |
|
||||
| `src/main/types/errors.ts` | 错误类型定义 | - |
|
||||
| `src/main/ipc/validation-handler.ts` | CleanerData 获取 | - |
|
||||
236
docs/erp-login-debug-guide.md
Normal file
236
docs/erp-login-debug-guide.md
Normal file
@@ -0,0 +1,236 @@
|
||||
# ERP 登录调试工具使用说明
|
||||
|
||||
## 目的
|
||||
|
||||
用于人工调试 ERP 登录流程,定位主界面特征元素,以便优化登录成功的判定逻辑。
|
||||
|
||||
## 前置准备
|
||||
|
||||
### 1. 配置 ERP 登录信息
|
||||
|
||||
编辑 `src/main/tools/erp-login-debug.ts` 文件,修改以下配置:
|
||||
|
||||
```typescript
|
||||
const ERP_CONFIG = {
|
||||
url: 'https://your-erp-server.com', // ← 修改为你的 ERP 地址
|
||||
username: 'your_username', // ← 修改为你的用户名
|
||||
password: 'your_password' // ← 修改为你的密码
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 确保 tsx 已安装
|
||||
|
||||
如果运行时报错提示找不到 `tsx`,请安装:
|
||||
|
||||
```bash
|
||||
npm install -g tsx
|
||||
# 或作为项目依赖
|
||||
npm install --save-dev tsx
|
||||
```
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 方式一:使用 npm 脚本(推荐)
|
||||
|
||||
```bash
|
||||
npm run debug:erp-login
|
||||
```
|
||||
|
||||
### 方式二:直接运行
|
||||
|
||||
```bash
|
||||
npx tsx src/main/tools/erp-login-debug.ts
|
||||
```
|
||||
|
||||
## 调试流程
|
||||
|
||||
### 步骤 1:启动脚本
|
||||
|
||||
运行命令后,脚本会显示配置信息并等待你确认:
|
||||
|
||||
```
|
||||
============================================================
|
||||
ERP 登录调试工具
|
||||
============================================================
|
||||
目标 URL: https://your-erp-server.com
|
||||
用户名:your_username
|
||||
密码: ***
|
||||
============================================================
|
||||
|
||||
操作步骤:
|
||||
1. 浏览器将自动打开并尝试登录
|
||||
2. 如果登录失败,请检查配置或手动重试
|
||||
3. 登录成功后,会自动暂停并打开开发者工具
|
||||
4. 使用元素选择器定位主界面特征元素
|
||||
5. 记录元素选择器,按 Ctrl+C 退出脚本
|
||||
|
||||
按 Enter 键开始...
|
||||
```
|
||||
|
||||
### 步骤 2:自动登录
|
||||
|
||||
脚本会自动执行:
|
||||
|
||||
- 打开浏览器
|
||||
- 导航到登录页面
|
||||
- 输入用户名和密码
|
||||
- 点击登录按钮
|
||||
- 处理强制登录确认对话框(如果有)
|
||||
|
||||
### 步骤 3:人工元素定位
|
||||
|
||||
登录成功后,脚本会暂停并显示:
|
||||
|
||||
```
|
||||
============================================================
|
||||
✓ 登录成功!
|
||||
============================================================
|
||||
|
||||
现在进入调试模式,请进行以下操作:
|
||||
|
||||
1. 按 F12 打开浏览器开发者工具
|
||||
2. 使用元素选择器 (Ctrl+Shift+C) 点击主界面特征元素
|
||||
3. 在 Elements 面板中右键元素 → Copy → Copy selector
|
||||
4. 或者使用 Playwright Inspector:
|
||||
- 在控制台输入:await page.pause()
|
||||
- 使用 Inspector 的元素选择工具
|
||||
|
||||
建议定位的特征元素:
|
||||
- 主界面顶部导航栏
|
||||
- 侧边菜单栏
|
||||
- 主内容区域的唯一标识
|
||||
- 用户信息显示区域
|
||||
- 任何登录后独有的界面元素
|
||||
|
||||
============================================================
|
||||
```
|
||||
|
||||
### 步骤 4:记录元素选择器
|
||||
|
||||
在开发者工具中:
|
||||
|
||||
1. **使用元素选择器** (Ctrl+Shift+C) 点击界面元素
|
||||
2. **在 Elements 面板** 查看元素 HTML
|
||||
3. **右键元素** → Copy → 选择以下之一:
|
||||
- `Copy selector` - CSS 选择器
|
||||
- `Copy XPath` - XPath 路径
|
||||
- `Copy JS path` - JavaScript 路径
|
||||
|
||||
### 步骤 5:更新 locators.ts
|
||||
|
||||
将找到的元素选择器添加到 `src/main/services/erp/locators.ts`:
|
||||
|
||||
```typescript
|
||||
export const ERP_LOCATORS = {
|
||||
// ... 现有配置 ...
|
||||
|
||||
// 新增:主界面特征元素(用于登录成功判定)
|
||||
mainPage: {
|
||||
topNavigationBar: '#top-nav', // 顶部导航栏
|
||||
sideMenu: '.side-menu', // 侧边菜单
|
||||
userProfile: '.user-profile', // 用户信息
|
||||
welcomeMessage: 'internal:has-text="欢迎"' // 欢迎消息
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 步骤 6:退出脚本
|
||||
|
||||
按 `Ctrl+C` 终止脚本,浏览器会在 5 秒后自动关闭。
|
||||
|
||||
## Playwright Inspector 使用技巧
|
||||
|
||||
### 开启 Inspector
|
||||
|
||||
在脚本暂停时,在浏览器控制台输入:
|
||||
|
||||
```javascript
|
||||
await page.pause()
|
||||
```
|
||||
|
||||
会打开 Playwright Inspector,提供:
|
||||
|
||||
- 元素选择器
|
||||
- 实时 locator 测试
|
||||
- 代码生成
|
||||
|
||||
### 测试 Locator
|
||||
|
||||
在 Inspector 控制台测试 locator 是否有效:
|
||||
|
||||
```javascript
|
||||
// 测试 CSS 选择器
|
||||
await page.locator('#top-nav').count()
|
||||
|
||||
// 测试 role-based 选择器
|
||||
await page.getByRole('navigation').count()
|
||||
|
||||
// 测试文本选择器
|
||||
await page.getByText('欢迎').count()
|
||||
```
|
||||
|
||||
如果返回数量 > 0,说明选择器有效。
|
||||
|
||||
## 推荐的特征元素
|
||||
|
||||
选择登录成功判定元素时,优先选择:
|
||||
|
||||
1. **唯一性** - 只在登录后出现
|
||||
2. **稳定性** - 不易随版本变更
|
||||
3. **易定位** - 有明确的 id、class 或文本
|
||||
|
||||
### 推荐元素示例
|
||||
|
||||
| 元素类型 | 选择器示例 | 说明 |
|
||||
| ------------ | ----------------------- | ---------------------- |
|
||||
| 顶部导航栏 | `#top-nav` | 登录后才会显示的主导航 |
|
||||
| 用户菜单 | `.user-menu` | 显示当前用户名的菜单 |
|
||||
| 欢迎消息 | `text=欢迎` | 包含用户名的欢迎语 |
|
||||
| 工作台标题 | `h1:has-text("工作台")` | 主界面标题 |
|
||||
| 功能模块网格 | `.module-grid` | 功能模块入口区域 |
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 登录失败,提示找不到元素
|
||||
|
||||
**A**: 检查以下几点:
|
||||
|
||||
1. ERP URL 是否正确
|
||||
2. 用户名密码是否正确
|
||||
3. 网络连接是否正常
|
||||
4. ERP 系统是否可访问
|
||||
5. 是否需要验证码(如果 ERP 有验证码,需要手动输入)
|
||||
|
||||
### Q: 登录后没有暂停
|
||||
|
||||
**A**: 检查控制台输出,可能登录流程中抛出了异常。查看错误信息并修复。
|
||||
|
||||
### Q: 如何调试特定页面?
|
||||
|
||||
**A**: 修改脚本中的登录后逻辑,导航到特定页面:
|
||||
|
||||
```typescript
|
||||
// 登录后导航到特定页面
|
||||
await page.goto(`${ERP_CONFIG.url}/yonbip/sc`)
|
||||
await page.waitForTimeout(3000)
|
||||
```
|
||||
|
||||
### Q: 如何保存调试会话?
|
||||
|
||||
**A**: Playwright 支持录制 trace:
|
||||
|
||||
```typescript
|
||||
await context.tracing.start({ screenshots: true, snapshots: true })
|
||||
// ... 操作 ...
|
||||
await context.tracing.stop({ path: 'trace.zip' })
|
||||
```
|
||||
|
||||
然后使用 `npx playwright show-trace trace.zip` 查看。
|
||||
|
||||
## 下一步
|
||||
|
||||
找到稳定的主界面元素后,修改以下文件优化登录判定:
|
||||
|
||||
1. **更新 locators.ts** - 添加主界面元素定位器
|
||||
2. **修改 erp-auth.ts** - 在登录成功后等待主界面元素
|
||||
3. **更新测试** - 验证新的登录判定逻辑
|
||||
241
docs/erp-login-debug-quickref.md
Normal file
241
docs/erp-login-debug-quickref.md
Normal file
@@ -0,0 +1,241 @@
|
||||
# ERP 登录调试工具 - 快速参考
|
||||
|
||||
## 创建的文件
|
||||
|
||||
### 1. 调试脚本
|
||||
|
||||
**路径**: `src/main/tools/erp-login-debug.ts`
|
||||
|
||||
用途:人工调试 ERP 登录流程,定位主界面特征元素
|
||||
|
||||
### 2. 使用文档
|
||||
|
||||
**路径**: `docs/erp-login-debug-guide.md`
|
||||
|
||||
详细的调试工具使用说明
|
||||
|
||||
### 3. package.json 更新
|
||||
|
||||
添加了新的 npm 脚本和依赖:
|
||||
|
||||
- `debug:erp-login` - 运行调试脚本
|
||||
- `debug:config-path` - 运行配置路径调试(已有)
|
||||
- `tsx` - TypeScript 执行器依赖
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 步骤 1:配置登录信息
|
||||
|
||||
编辑 `src/main/tools/erp-login-debug.ts` 第 19-23 行:
|
||||
|
||||
```typescript
|
||||
const ERP_CONFIG = {
|
||||
url: 'https://your-erp-server.com', // ← 修改
|
||||
username: 'your_username', // ← 修改
|
||||
password: 'your_password' // ← 修改
|
||||
}
|
||||
```
|
||||
|
||||
### 步骤 2:运行调试
|
||||
|
||||
```bash
|
||||
npm run debug:erp-login
|
||||
```
|
||||
|
||||
### 步骤 3:定位元素
|
||||
|
||||
登录成功后:
|
||||
|
||||
1. 按 **F12** 打开开发者工具
|
||||
2. 按 **Ctrl+Shift+C** 启用元素选择器
|
||||
3. 点击主界面特征元素
|
||||
4. 右键 → Copy → Copy selector
|
||||
|
||||
### 步骤 4:更新定位器
|
||||
|
||||
将找到的元素添加到 `src/main/services/erp/locators.ts`:
|
||||
|
||||
```typescript
|
||||
export const ERP_LOCATORS = {
|
||||
// ... 现有配置 ...
|
||||
|
||||
// 新增:主界面特征元素
|
||||
mainPage: {
|
||||
// 在此添加找到的元素
|
||||
topNav: '#top-nav',
|
||||
userMenu: '.user-menu'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 脚本功能
|
||||
|
||||
### 自动执行
|
||||
|
||||
- ✅ 启动浏览器(可见窗口,非无头模式)
|
||||
- ✅ 导航到登录页面
|
||||
- ✅ 输入用户名和密码
|
||||
- ✅ 点击登录按钮
|
||||
- ✅ 处理强制登录确认对话框
|
||||
|
||||
### 调试支持
|
||||
|
||||
- ✅ 登录成功后自动暂停
|
||||
- ✅ 保持浏览器打开
|
||||
- ✅ 支持 F12 开发者工具
|
||||
- ✅ 支持 Playwright Inspector
|
||||
|
||||
### 安全特性
|
||||
|
||||
- ✅ 密码显示为星号
|
||||
- ✅ 需要按 Enter 确认后才开始
|
||||
- ✅ 退出前 5 秒缓冲时间
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
# 运行调试脚本
|
||||
npm run debug:erp-login
|
||||
|
||||
# 或使用 npx 直接运行
|
||||
npx tsx src/main/tools/erp-login-debug.ts
|
||||
|
||||
# 查看帮助
|
||||
npx tsx --help
|
||||
```
|
||||
|
||||
## 调试技巧
|
||||
|
||||
### 测试 Locator 有效性
|
||||
|
||||
在浏览器控制台(登录后暂停时):
|
||||
|
||||
```javascript
|
||||
// 测试 CSS 选择器
|
||||
await page.locator('#top-nav').count()
|
||||
|
||||
// 测试文本选择器
|
||||
await page.getByText('欢迎').isVisible()
|
||||
|
||||
// 测试 role 选择器
|
||||
await page.getByRole('navigation').count()
|
||||
```
|
||||
|
||||
返回值 > 0 或 true 表示选择器有效。
|
||||
|
||||
### 查看元素详细信息
|
||||
|
||||
```javascript
|
||||
// 获取元素 HTML
|
||||
const element = await page.$('#top-nav')
|
||||
console.log(await element.innerHTML())
|
||||
|
||||
// 获取元素属性
|
||||
console.log(await element.getAttributes())
|
||||
```
|
||||
|
||||
### 截图保存
|
||||
|
||||
```javascript
|
||||
// 全屏截图
|
||||
await page.screenshot({ path: 'login-success.png' })
|
||||
|
||||
// 元素截图
|
||||
const element = await page.$('#top-nav')
|
||||
await element.screenshot({ path: 'top-nav.png' })
|
||||
```
|
||||
|
||||
## 推荐的特征元素
|
||||
|
||||
选择登录成功判定元素的标准:
|
||||
|
||||
| 标准 | 说明 | 示例 |
|
||||
| ---------- | -------------- | ------------------- |
|
||||
| **唯一性** | 只在登录后出现 | 用户菜单、工作台 |
|
||||
| **稳定性** | 不易随版本变更 | ID 选择器优于 class |
|
||||
| **易定位** | 有明确的标识 | 有 id、独特文本 |
|
||||
|
||||
### 推荐元素类型
|
||||
|
||||
1. **顶部导航栏** - `#top-nav`, `.navbar`
|
||||
2. **用户信息区域** - `.user-info`, `.user-menu`
|
||||
3. **欢迎消息** - 包含用户名的文本
|
||||
4. **功能模块入口** - 主界面的模块网格
|
||||
5. **侧边菜单栏** - `.sidebar`, `.menu`
|
||||
|
||||
## 故障排查
|
||||
|
||||
### 问题:脚本启动后立即退出
|
||||
|
||||
**原因**: tsx 未安装
|
||||
|
||||
**解决**:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### 问题:找不到用户名/密码输入框
|
||||
|
||||
**原因**:
|
||||
|
||||
1. ERP URL 不正确
|
||||
2. 页面结构已变更
|
||||
3. 登录页面加载超时
|
||||
|
||||
**解决**:
|
||||
|
||||
1. 检查 ERP_CONFIG.url 是否正确
|
||||
2. 手动打开 URL 确认页面结构
|
||||
3. 增加 timeout 值(第 25 行)
|
||||
|
||||
### 问题:登录后没有暂停
|
||||
|
||||
**原因**: 登录流程抛出异常
|
||||
|
||||
**解决**: 查看控制台错误信息,检查:
|
||||
|
||||
- 网络连接
|
||||
- ERP 系统可用性
|
||||
- 用户名密码正确性
|
||||
|
||||
### 问题:无法定位元素
|
||||
|
||||
**原因**:
|
||||
|
||||
1. 元素在 iframe 中
|
||||
2. 元素动态加载
|
||||
3. 选择器不正确
|
||||
|
||||
**解决**:
|
||||
|
||||
1. 检查元素是否在嵌套 iframe 中
|
||||
2. 增加等待时间 `await page.waitForTimeout(2000)`
|
||||
3. 使用更具体的选择器
|
||||
|
||||
## 下一步
|
||||
|
||||
找到稳定的主界面元素后:
|
||||
|
||||
1. **更新 locators.ts**
|
||||
- 添加 `mainPage` 配置节
|
||||
- 定义登录成功判定元素
|
||||
|
||||
2. **修改 erp-auth.ts**
|
||||
- 在 `login()` 方法末尾
|
||||
- 等待主界面元素出现
|
||||
- 作为登录成功的最终判定
|
||||
|
||||
3. **验证修改**
|
||||
- 重新运行调试脚本
|
||||
- 确认新的判定逻辑有效
|
||||
- 更新相关文档
|
||||
|
||||
## 相关文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
| ----------------------------------- | ---------- |
|
||||
| `src/main/tools/erp-login-debug.ts` | 调试脚本 |
|
||||
| `src/main/services/erp/locators.ts` | 元素定位器 |
|
||||
| `src/main/services/erp/erp-auth.ts` | 登录服务 |
|
||||
| `docs/erp-login-debug-guide.md` | 详细文档 |
|
||||
File diff suppressed because it is too large
Load Diff
130
docs/plans/IMPLEMENTATION_PLAN.md
Normal file
130
docs/plans/IMPLEMENTATION_PLAN.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# Implementation Plan: Auto-import Extracted Data to Database
|
||||
|
||||
## Overview
|
||||
|
||||
Implement automatic database import after ERP data extraction completes. The merged Excel file will be read and written to the `dbo_DiscreteMaterialPlanData` table.
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Trigger**: Automatic after extraction completes
|
||||
- **Delete Strategy**: Batch delete by `SourceNumber` before insert
|
||||
- **Batch Insert**: 1000 records per batch
|
||||
- **Field Mapping**: 28 Excel fields → database columns (skip 打印人, 打印日期, BOMVersion)
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
ExtractorService
|
||||
│
|
||||
├── extract() → download + merge Excel
|
||||
│
|
||||
└── NEW: importToDatabase(mergedFile)
|
||||
│
|
||||
▼
|
||||
DataImportService
|
||||
│
|
||||
├── readExcelFile() → records + sourceNumbers
|
||||
├── deleteExistingRecords(sourceNumbers)
|
||||
└── batchInsert(records, batchSize=1000)
|
||||
│
|
||||
▼
|
||||
DiscreteMaterialPlanDAO
|
||||
├── deleteBySourceNumbers()
|
||||
└── batchInsert()
|
||||
```
|
||||
|
||||
## Field Mapping
|
||||
|
||||
| Excel Header | Database Column | Notes |
|
||||
| ------------ | ------------------------ | ---------------- |
|
||||
| 工厂 | Factory | |
|
||||
| 备料状态 | MaterialStatus | |
|
||||
| 备料计划单号 | PlanNumber | |
|
||||
| 来源单号 | SourceNumber | **Deletion key** |
|
||||
| 备料类型 | MaterialType | |
|
||||
| 产品编码 | ProductCode | |
|
||||
| 产品名称 | ProductName | |
|
||||
| 产品计划数量 | ProductPlanQuantity | decimal |
|
||||
| 产品单位 | ProductUnit | |
|
||||
| 用料部门 | UseDepartment | |
|
||||
| 备注 | Remark | |
|
||||
| 制单人 | Creator | |
|
||||
| 制单日期 | CreateDate | date |
|
||||
| 审批人 | Approver | |
|
||||
| 审批日期 | ApproveDate | date |
|
||||
| 序号 | SequenceNumber | int |
|
||||
| 材料编码 | MaterialCode | |
|
||||
| 材料名称 | MaterialName | |
|
||||
| 规格 | Specification | |
|
||||
| 型号 | Model | |
|
||||
| 图号 | DrawingNumber | |
|
||||
| 物料材质 | MaterialQuality | |
|
||||
| 计划数量 | PlanQuantity | decimal |
|
||||
| 单位 | Unit | |
|
||||
| 需用日期 | RequiredDate | date |
|
||||
| 发料仓库 | Warehouse | |
|
||||
| 单位用量 | UnitUsage | decimal |
|
||||
| 累计出库数量 | CumulativeOutputQuantity | decimal |
|
||||
| 打印人 | ❌ SKIP | Not in DB |
|
||||
| 打印日期 | ❌ SKIP | Not in DB |
|
||||
| - | BOMVersion | SKIP (no source) |
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### 1. NEW: `src/main/services/database/data-importer.ts`
|
||||
|
||||
Main import service with:
|
||||
|
||||
- `importFromExcel(filePath)` - Main entry point
|
||||
- `readExcelFile(filePath)` - Parse Excel using ExcelJS
|
||||
- Map Excel columns to database fields
|
||||
- Return records and unique SourceNumbers
|
||||
|
||||
### 2. MODIFY: `src/main/services/database/discrete-material-plan-dao.ts`
|
||||
|
||||
Add methods:
|
||||
|
||||
- `deleteBySourceNumbers(sourceNumbers: string[])` - Batch delete
|
||||
- `batchInsert(records: MaterialPlanRecord[], batchSize: number)` - Batch insert
|
||||
|
||||
### 3. MODIFY: `src/main/services/erp/extractor.ts`
|
||||
|
||||
- After successful merge, call `importToDatabase(mergedFile)`
|
||||
- Add import results to `ExtractorResult`
|
||||
|
||||
### 4. MODIFY: `src/main/types/extractor.types.ts`
|
||||
|
||||
Add types:
|
||||
|
||||
```typescript
|
||||
export interface ImportResult {
|
||||
success: boolean
|
||||
recordsImported: number
|
||||
recordsDeleted: number
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
export interface ExtractorResult {
|
||||
// existing fields...
|
||||
importResult?: ImportResult
|
||||
}
|
||||
```
|
||||
|
||||
### 5. MODIFY: `src/renderer/src/pages/ExtractorPage.tsx`
|
||||
|
||||
- Display import results
|
||||
- Show records deleted/imported counts
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Extend `DiscreteMaterialPlanDAO` with insert/delete methods
|
||||
2. Create `DataImportService`
|
||||
3. Integrate into `ExtractorService`
|
||||
4. Update types
|
||||
5. Update UI
|
||||
|
||||
## Testing Plan
|
||||
|
||||
1. Unit test DAO methods
|
||||
2. Integration test with sample Excel file
|
||||
3. E2E test extraction → import flow
|
||||
@@ -5,14 +5,31 @@ directories:
|
||||
files:
|
||||
- '!**/.vscode/*'
|
||||
- '!src/*'
|
||||
- '!electron.vite.config.{js,ts,mjs,cjs}'
|
||||
- '!electron-vite.config.{js,ts,mjs,cjs}'
|
||||
- '!{.eslintcache,eslint.config.mjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
|
||||
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
|
||||
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
|
||||
- 'package.json'
|
||||
# Include build output
|
||||
- 'out/**/*'
|
||||
# Include config.template.yaml in the build for reference
|
||||
- 'config.template.yaml'
|
||||
# Exclude Playwright browser downloads (manual install for company environment)
|
||||
- '!**/node_modules/playwright-core/.local-browsers/**'
|
||||
asarUnpack:
|
||||
- resources/**
|
||||
# Unpack playwright for native modules
|
||||
- '**/node_modules/playwright/**'
|
||||
- '**/node_modules/playwright-core/**'
|
||||
win:
|
||||
executableName: erpauto
|
||||
target:
|
||||
- nsis
|
||||
- portable
|
||||
portable:
|
||||
artifactName: ${name}-portable.${ext}
|
||||
# Portable app uses user data directory (AppData), not exe directory
|
||||
# This ensures config persists across app updates
|
||||
nsis:
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
shortcutName: ${productName}
|
||||
|
||||
@@ -2,16 +2,48 @@ import { resolve } from 'path'
|
||||
import { defineConfig } from 'electron-vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { execSync } from 'child_process'
|
||||
import { createRequire } from 'module'
|
||||
|
||||
// Get git hash (first 7 characters)
|
||||
const getGitHash = (): string => {
|
||||
try {
|
||||
return execSync('git rev-parse --short=7 HEAD', { encoding: 'utf-8' }).trim()
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
|
||||
// Get version from package.json
|
||||
const require = createRequire(import.meta.url)
|
||||
const version = require('./package.json').version
|
||||
const gitHash = getGitHash()
|
||||
|
||||
export default defineConfig({
|
||||
main: {},
|
||||
preload: {},
|
||||
renderer: {
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(version),
|
||||
__GIT_HASH__: JSON.stringify(gitHash)
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@renderer': resolve('src/renderer/src')
|
||||
}
|
||||
},
|
||||
plugins: [react(), tailwindcss()]
|
||||
plugins: [
|
||||
react(),
|
||||
tailwindcss(),
|
||||
{
|
||||
name: 'update-title',
|
||||
transformIndexHtml(html) {
|
||||
return html.replace(
|
||||
'<title>ERP Auto Tool</title>',
|
||||
`<title>ERPAuto - v${version}(${gitHash})</title>`
|
||||
)
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
3801
package-lock.json
generated
3801
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
30
package.json
30
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "erpauto",
|
||||
"version": "1.0.0",
|
||||
"version": "1.3.0",
|
||||
"description": "An Electron application with React and TypeScript",
|
||||
"main": "./out/main/index.js",
|
||||
"author": "example.com",
|
||||
@@ -12,32 +12,43 @@
|
||||
"typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",
|
||||
"typecheck": "npm run typecheck:node && npm run typecheck:web",
|
||||
"start": "electron-vite preview",
|
||||
"dev": "electron-vite dev",
|
||||
"build": "npm run typecheck && electron-vite build",
|
||||
"dev": "chcp 65001 && electron-vite dev",
|
||||
"build": "chcp 65001 && npm run typecheck && electron-vite build",
|
||||
"postinstall": "electron-builder install-app-deps",
|
||||
"build:unpack": "npm run build && electron-builder --dir",
|
||||
"build:win": "npm run build && electron-builder --win",
|
||||
"build:mac": "electron-vite build && electron-builder --mac",
|
||||
"build:linux": "electron-vite build && electron-builder --linux",
|
||||
"build:unpack": "chcp 65001 && set PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 && npm run build && electron-builder --dir",
|
||||
"build:win": "chcp 65001 && set PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 && npm run prebuild && npm run build && electron-builder --win",
|
||||
"build:mac": "chcp 65001 && npm run prebuild && electron-vite build && electron-builder --mac",
|
||||
"build:linux": "chcp 65001 && npm run prebuild && electron-vite build && electron-builder --linux",
|
||||
"prebuild": "node -e \"const fs=require('fs');['dist','out'].forEach(d=>{try{fs.rmSync(d,{recursive:true})}catch(e){}})\"",
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
"test:e2e:report": "playwright show-report"
|
||||
"test:e2e:report": "playwright show-report",
|
||||
"debug:erp-login": "tsx src/main/tools/erp-login-debug.ts",
|
||||
"debug:config-path": "tsx src/main/tools/config-path-debug.ts",
|
||||
"test:rustfs": "tsx src/main/tools/rustfs-test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.929.0",
|
||||
"@electron-toolkit/preload": "^3.0.2",
|
||||
"@electron-toolkit/utils": "^4.0.0",
|
||||
"@tailwindcss/vite": "^4.2.1",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"chromium-bidi": "^15.0.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"dotenv": "^17.3.1",
|
||||
"exceljs": "^4.4.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"lucide-react": "^0.575.0",
|
||||
"mssql": "^12.2.0",
|
||||
"mysql2": "^3.18.2",
|
||||
"playwright": "^1.58.2",
|
||||
"playwright-core": "^1.58.2",
|
||||
"react-focus-lock": "^2.13.7",
|
||||
"react-markdown": "^10.1.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"typeorm": "^0.3.28",
|
||||
"uuid": "^13.0.0",
|
||||
"winston": "^3.19.0",
|
||||
@@ -70,6 +81,7 @@
|
||||
"react": "^19.2.1",
|
||||
"react-dom": "^19.2.1",
|
||||
"tailwindcss": "^4.2.1",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.2.6",
|
||||
"vitest": "^4.0.18"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* This script modifies the ID column to be AUTO_INCREMENT while preserving data
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const mysql = require('mysql2/promise')
|
||||
|
||||
async function main() {
|
||||
const config = {
|
||||
@@ -13,17 +13,17 @@ async function main() {
|
||||
user: 'remote_user',
|
||||
password: '3.1415926Beeke',
|
||||
database: 'BLD_DB'
|
||||
};
|
||||
}
|
||||
|
||||
let connection;
|
||||
let connection
|
||||
|
||||
try {
|
||||
console.log('Connecting to MySQL...');
|
||||
connection = await mysql.createConnection(config);
|
||||
console.log('Connected successfully!\n');
|
||||
console.log('Connecting to MySQL...')
|
||||
connection = await mysql.createConnection(config)
|
||||
console.log('Connected successfully!\n')
|
||||
|
||||
// Step 1: Check current table structure
|
||||
console.log('=== Step 1: Current table structure ===');
|
||||
console.log('=== Step 1: Current table structure ===')
|
||||
const [columns] = await connection.execute(`
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
@@ -39,40 +39,38 @@ async function main() {
|
||||
AND TABLE_SCHEMA = DATABASE()
|
||||
ORDER BY
|
||||
ORDINAL_POSITION
|
||||
`);
|
||||
console.table(columns);
|
||||
`)
|
||||
console.table(columns)
|
||||
|
||||
// Step 2: Count records before modification
|
||||
console.log('\n=== Step 2: Record count before modification ===');
|
||||
console.log('\n=== Step 2: Record count before modification ===')
|
||||
const [countBefore] = await connection.execute(
|
||||
'SELECT COUNT(*) AS total FROM dbo_MaterialsTypeToBeDeleted'
|
||||
);
|
||||
console.log(`Total records: ${countBefore[0].total}`);
|
||||
)
|
||||
console.log(`Total records: ${countBefore[0].total}`)
|
||||
|
||||
// Step 3: Show sample data
|
||||
console.log('\n=== Step 3: Sample data ===');
|
||||
const [sample] = await connection.execute(
|
||||
'SELECT * FROM dbo_MaterialsTypeToBeDeleted LIMIT 5'
|
||||
);
|
||||
console.table(sample);
|
||||
console.log('\n=== Step 3: Sample data ===')
|
||||
const [sample] = await connection.execute('SELECT * FROM dbo_MaterialsTypeToBeDeleted LIMIT 5')
|
||||
console.table(sample)
|
||||
|
||||
// Step 4: Check if ID is already AUTO_INCREMENT
|
||||
const idColumn = columns.find((col) => col.COLUMN_NAME === 'ID');
|
||||
const idColumn = columns.find((col) => col.COLUMN_NAME === 'ID')
|
||||
if (idColumn && idColumn.EXTRA.includes('auto_increment')) {
|
||||
console.log('\n=== ID is already AUTO_INCREMENT! No modification needed. ===');
|
||||
return;
|
||||
console.log('\n=== ID is already AUTO_INCREMENT! No modification needed. ===')
|
||||
return
|
||||
}
|
||||
|
||||
// Step 5: Modify the ID column
|
||||
console.log('\n=== Step 4: Modifying ID column to AUTO_INCREMENT ===');
|
||||
console.log('\n=== Step 4: Modifying ID column to AUTO_INCREMENT ===')
|
||||
await connection.execute(`
|
||||
ALTER TABLE dbo_MaterialsTypeToBeDeleted
|
||||
MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT
|
||||
`);
|
||||
console.log('Modification completed successfully!\n');
|
||||
`)
|
||||
console.log('Modification completed successfully!\n')
|
||||
|
||||
// Step 6: Verify the change
|
||||
console.log('=== Step 5: Verify modification ===');
|
||||
console.log('=== Step 5: Verify modification ===')
|
||||
const [columnsAfter] = await connection.execute(`
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
@@ -86,32 +84,32 @@ async function main() {
|
||||
TABLE_NAME = 'dbo_MaterialsTypeToBeDeleted'
|
||||
AND TABLE_SCHEMA = DATABASE()
|
||||
AND COLUMN_NAME = 'ID'
|
||||
`);
|
||||
console.table(columnsAfter);
|
||||
`)
|
||||
console.table(columnsAfter)
|
||||
|
||||
// Step 7: Verify data is still intact
|
||||
console.log('\n=== Step 6: Verify data integrity ===');
|
||||
console.log('\n=== Step 6: Verify data integrity ===')
|
||||
const [countAfter] = await connection.execute(
|
||||
'SELECT COUNT(*) AS total FROM dbo_MaterialsTypeToBeDeleted'
|
||||
);
|
||||
console.log(`Total records after modification: ${countAfter[0].total}`);
|
||||
)
|
||||
console.log(`Total records after modification: ${countAfter[0].total}`)
|
||||
|
||||
if (countBefore[0].total === countAfter[0].total) {
|
||||
console.log('\n✅ SUCCESS: All data preserved, AUTO_INCREMENT added to ID column!');
|
||||
console.log('\n✅ SUCCESS: All data preserved, AUTO_INCREMENT added to ID column!')
|
||||
} else {
|
||||
console.log('\n⚠️ WARNING: Record count changed! Please check data.');
|
||||
console.log('\n⚠️ WARNING: Record count changed! Please check data.')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('\n❌ Error:', error.message);
|
||||
console.error('\n❌ Error:', error.message)
|
||||
if (error.code) {
|
||||
console.error('Error code:', error.code);
|
||||
console.error('Error code:', error.code)
|
||||
}
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('\nConnection closed.');
|
||||
await connection.end()
|
||||
console.log('\nConnection closed.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
main()
|
||||
|
||||
142
scripts/fix-computer-name-typo.js
Normal file
142
scripts/fix-computer-name-typo.js
Normal file
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Fix ComputerNmae Typo in dbo_BIPUsers Table
|
||||
*
|
||||
* This script renames the column from 'ComputerNmae' to 'ComputerName'
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise')
|
||||
|
||||
async function main() {
|
||||
const config = {
|
||||
host: '192.168.31.83',
|
||||
port: 3306,
|
||||
user: 'remote_user',
|
||||
password: '3.1415926Beeke',
|
||||
database: 'BLD_DB'
|
||||
}
|
||||
|
||||
let connection
|
||||
|
||||
try {
|
||||
console.log('Connecting to MySQL...')
|
||||
connection = await mysql.createConnection(config)
|
||||
console.log('Connected successfully!\n')
|
||||
|
||||
// Step 1: Check current column name
|
||||
console.log('=== Step 1: Check current column name ===')
|
||||
const [columns] = await connection.execute(`
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
COLUMN_TYPE,
|
||||
IS_NULLABLE,
|
||||
CHARACTER_MAXIMUM_LENGTH,
|
||||
COLUMN_KEY,
|
||||
COLUMN_DEFAULT,
|
||||
EXTRA
|
||||
FROM
|
||||
INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
TABLE_NAME = 'dbo_BIPUsers'
|
||||
AND TABLE_SCHEMA = DATABASE()
|
||||
AND (COLUMN_NAME = 'ComputerNmae' OR COLUMN_NAME = 'ComputerName')
|
||||
ORDER BY
|
||||
ORDINAL_POSITION
|
||||
`)
|
||||
|
||||
if (columns.length === 0) {
|
||||
console.log('No ComputerNmae or ComputerName column found!')
|
||||
return
|
||||
}
|
||||
|
||||
console.table(columns)
|
||||
|
||||
const currentColumn = columns.find((col) => col.COLUMN_NAME === 'ComputerNmae')
|
||||
const newColumn = columns.find((col) => col.COLUMN_NAME === 'ComputerName')
|
||||
|
||||
if (newColumn) {
|
||||
console.log('\n=== Column is already named "ComputerName"! No modification needed. ===')
|
||||
return
|
||||
}
|
||||
|
||||
if (!currentColumn) {
|
||||
console.log('\n=== ERROR: ComputerNmae column not found! ===')
|
||||
return
|
||||
}
|
||||
|
||||
// Step 2: Count records before modification
|
||||
console.log('\n=== Step 2: Record count before modification ===')
|
||||
const [countBefore] = await connection.execute('SELECT COUNT(*) AS total FROM dbo_BIPUsers')
|
||||
console.log(`Total records: ${countBefore[0].total}`)
|
||||
|
||||
// Step 3: Show sample data with the column
|
||||
console.log('\n=== Step 3: Sample data (showing ComputerNmae column) ===')
|
||||
const [sample] = await connection.execute(`
|
||||
SELECT ID, UserName, UserType, ComputerNmae, CreateTime
|
||||
FROM dbo_BIPUsers
|
||||
LIMIT 5
|
||||
`)
|
||||
console.table(sample)
|
||||
|
||||
// Step 4: Rename the column
|
||||
console.log('\n=== Step 4: Renaming column ComputerNmae -> ComputerName ===')
|
||||
await connection.execute(`
|
||||
ALTER TABLE dbo_BIPUsers
|
||||
CHANGE COLUMN ComputerNmae ComputerName VARCHAR(255) NULL
|
||||
`)
|
||||
console.log('Column renamed successfully!\n')
|
||||
|
||||
// Step 5: Verify the change
|
||||
console.log('=== Step 5: Verify modification ===')
|
||||
const [columnsAfter] = await connection.execute(`
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
COLUMN_TYPE,
|
||||
IS_NULLABLE,
|
||||
CHARACTER_MAXIMUM_LENGTH,
|
||||
COLUMN_KEY,
|
||||
COLUMN_DEFAULT,
|
||||
EXTRA
|
||||
FROM
|
||||
INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
TABLE_NAME = 'dbo_BIPUsers'
|
||||
AND TABLE_SCHEMA = DATABASE()
|
||||
AND COLUMN_NAME = 'ComputerName'
|
||||
`)
|
||||
console.table(columnsAfter)
|
||||
|
||||
// Step 6: Verify data is still intact
|
||||
console.log('\n=== Step 6: Verify data integrity ===')
|
||||
const [countAfter] = await connection.execute('SELECT COUNT(*) AS total FROM dbo_BIPUsers')
|
||||
console.log(`Total records after modification: ${countAfter[0].total}`)
|
||||
|
||||
// Step 7: Show sample data with new column name
|
||||
console.log('\n=== Step 7: Sample data (showing ComputerName column) ===')
|
||||
const [sampleAfter] = await connection.execute(`
|
||||
SELECT ID, UserName, UserType, ComputerName, CreateTime
|
||||
FROM dbo_BIPUsers
|
||||
LIMIT 5
|
||||
`)
|
||||
console.table(sampleAfter)
|
||||
|
||||
if (countBefore[0].total === countAfter[0].total) {
|
||||
console.log(
|
||||
'\n✅ SUCCESS: All data preserved, column renamed from ComputerNmae to ComputerName!'
|
||||
)
|
||||
} else {
|
||||
console.log('\n⚠️ WARNING: Record count changed! Please check data.')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('\n❌ Error:', error.message)
|
||||
if (error.code) {
|
||||
console.error('Error code:', error.code)
|
||||
}
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end()
|
||||
console.log('\nConnection closed.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
13
scripts/fix-computer-name-typo.sql
Normal file
13
scripts/fix-computer-name-typo.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
-- Migration script to fix ComputerNmae typo in dbo_BIPUsers table
|
||||
-- Changes column name from 'ComputerNmae' to 'ComputerName'
|
||||
-- Date: 2026-03-05
|
||||
|
||||
-- Rename the column (MySQL syntax)
|
||||
ALTER TABLE dbo_BIPUsers
|
||||
CHANGE COLUMN ComputerNmae ComputerName VARCHAR(255) NULL;
|
||||
|
||||
-- Verify the change
|
||||
SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_NAME = 'dbo_BIPUsers'
|
||||
AND COLUMN_NAME = 'ComputerName';
|
||||
125
scripts/migrate-env-to-yaml.ts
Normal file
125
scripts/migrate-env-to-yaml.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Migration Script: .env to config.yaml
|
||||
*
|
||||
* Usage: npx tsx scripts/migrate-env-to-yaml.ts
|
||||
*
|
||||
* This script migrates the old .env configuration to the new YAML format.
|
||||
* ERP configuration is NOT migrated as it's now stored in the database per user.
|
||||
*/
|
||||
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import yaml from 'js-yaml'
|
||||
|
||||
const ENV_PATH = path.resolve(process.cwd(), '.env')
|
||||
const YAML_PATH = path.resolve(process.cwd(), 'config.yaml')
|
||||
const BACKUP_PATH = path.resolve(process.cwd(), '.env.backup')
|
||||
|
||||
interface EnvConfig {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
function parseEnvFile(content: string): EnvConfig {
|
||||
const result: EnvConfig = {}
|
||||
const lines = content.split('\n')
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed || trimmed.startsWith('#')) continue
|
||||
|
||||
const [key, ...valueParts] = trimmed.split('=')
|
||||
if (key && valueParts.length > 0) {
|
||||
result[key.trim()] = valueParts.join('=').trim()
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function migrate() {
|
||||
console.log('🔄 Starting migration from .env to config.yaml...\n')
|
||||
|
||||
if (!fs.existsSync(ENV_PATH)) {
|
||||
console.error('❌ .env file not found at:', ENV_PATH)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const envContent = fs.readFileSync(ENV_PATH, 'utf-8')
|
||||
const env = parseEnvFile(envContent)
|
||||
|
||||
// Build configuration object (without ERP)
|
||||
const config = {
|
||||
database: {
|
||||
activeType: (env.DB_TYPE || 'mysql').toLowerCase() as 'mysql' | 'sqlserver',
|
||||
mysql: {
|
||||
host: env.DB_MYSQL_HOST || 'localhost',
|
||||
port: parseInt(env.DB_MYSQL_PORT || '3306', 10),
|
||||
database: env.DB_NAME || '',
|
||||
username: env.DB_USERNAME || '',
|
||||
password: env.DB_PASSWORD || '',
|
||||
charset: env.DB_MYSQL_CHARSET || 'utf8mb4'
|
||||
},
|
||||
sqlserver: {
|
||||
server: env.DB_SERVER || 'localhost',
|
||||
port: parseInt(env.DB_SQLSERVER_PORT || '1433', 10),
|
||||
database: env.DB_NAME || '',
|
||||
username: env.DB_USERNAME || '',
|
||||
password: env.DB_PASSWORD || '',
|
||||
driver: env.DB_SQLSERVER_DRIVER || 'ODBC Driver 18 for SQL Server',
|
||||
trustServerCertificate: env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
|
||||
}
|
||||
},
|
||||
paths: {
|
||||
dataDir: env.PATH_DATA_DIR || './data/',
|
||||
defaultOutput: env.PATH_DEFAULT_OUTPUT || 'output.xlsx',
|
||||
validationOutput: env.PATH_VALIDATION_OUTPUT || 'validation-result.xlsx'
|
||||
},
|
||||
extraction: {
|
||||
batchSize: parseInt(env.EXTRACTION_BATCH_SIZE || '100', 10),
|
||||
verbose: env.EXTRACTION_VERBOSE !== 'false',
|
||||
autoConvert: env.EXTRACTION_AUTO_CONVERT !== 'false',
|
||||
mergeBatches: env.EXTRACTION_MERGE_BATCHES !== 'false',
|
||||
enableDbPersistence: env.EXTRACTION_ENABLE_DB_PERSISTENCE !== 'false'
|
||||
},
|
||||
validation: {
|
||||
dataSource: env.VALIDATION_DATA_SOURCE || 'database_full',
|
||||
batchSize: parseInt(env.VALIDATION_BATCH_SIZE || '2000', 10),
|
||||
matchMode: env.VALIDATION_MATCH_MODE || 'substring',
|
||||
enableCrud: env.VALIDATION_ENABLE_CRUD === 'true',
|
||||
defaultManager: env.VALIDATION_DEFAULT_MANAGER || ''
|
||||
},
|
||||
orderResolution: {
|
||||
tableName: env.DB_TABLE_NAME || '',
|
||||
productionIdField: env.DB_FIELD_PRODUCTION_ID || '',
|
||||
orderNumberField: env.DB_FIELD_ORDER_NUMBER || ''
|
||||
}
|
||||
}
|
||||
|
||||
// Backup .env
|
||||
if (fs.existsSync(ENV_PATH)) {
|
||||
fs.copyFileSync(ENV_PATH, BACKUP_PATH)
|
||||
console.log('📁 Backed up .env to .env.backup')
|
||||
}
|
||||
|
||||
// Write YAML with header comments
|
||||
const header = `# ================================\n# ERPAuto 配置文件\n# ================================\n# 由 .env 迁移生成\n# 迁移时间:${new Date().toISOString()}\n# 注意:ERP 配置已迁移到数据库 (dbo_BIPUsers 表)\n# ================================\n\n`
|
||||
|
||||
const yamlContent = yaml.dump(config, {
|
||||
indent: 2,
|
||||
lineWidth: -1,
|
||||
noRefs: true,
|
||||
quotingType: '"',
|
||||
forceQuotes: false
|
||||
})
|
||||
|
||||
fs.writeFileSync(YAML_PATH, header + yamlContent, 'utf-8')
|
||||
|
||||
console.log('✅ Migration completed successfully!')
|
||||
console.log(`📁 Config saved to: ${YAML_PATH}`)
|
||||
console.log('\n📋 Next steps:')
|
||||
console.log(' 1. Review config.yaml and verify all values')
|
||||
console.log(' 2. Test the application thoroughly')
|
||||
console.log(' 3. Remove .env file when confident (optional)\n')
|
||||
}
|
||||
|
||||
migrate()
|
||||
@@ -1,28 +1,32 @@
|
||||
import { app, shell, BrowserWindow, ipcMain } from 'electron'
|
||||
import { app, shell, BrowserWindow, ipcMain, dialog } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
|
||||
import icon from '../../resources/icon.png?asset'
|
||||
import { registerIpcHandlers } from './ipc'
|
||||
import * as dotenv from 'dotenv'
|
||||
import { ConfigManager } from './services/config/config-manager'
|
||||
import logger from './services/logger/index'
|
||||
import { logAudit } from './services/logger/audit-logger'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { dirname, resolve } from 'path'
|
||||
import { dirname } from 'path'
|
||||
import fs from 'fs'
|
||||
|
||||
// Set Playwright browsers path BEFORE any playwright import
|
||||
process.env.PLAYWRIGHT_BROWSERS_PATH = join(app.getPath('userData'), 'ms-playwright')
|
||||
|
||||
// Load environment variables from .env file
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = dirname(__filename)
|
||||
dotenv.config({ path: resolve(__dirname, '../../.env') })
|
||||
|
||||
function createWindow(): void {
|
||||
// Create the browser window.
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 900,
|
||||
width: 1200,
|
||||
height: 670,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...(process.platform === 'linux' ? { icon } : {}),
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
sandbox: false
|
||||
sandbox: true
|
||||
}
|
||||
})
|
||||
|
||||
@@ -47,7 +51,70 @@ function createWindow(): void {
|
||||
// This method will be called when Electron has finished
|
||||
// initialization and is ready to create browser windows.
|
||||
// Some APIs can only be used after this event occurs.
|
||||
app.whenReady().then(() => {
|
||||
app.whenReady().then(async () => {
|
||||
// Validate Playwright browser path
|
||||
const browsersPath = process.env.PLAYWRIGHT_BROWSERS_PATH!
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
try {
|
||||
fs.mkdirSync(browsersPath, { recursive: true })
|
||||
} catch (error) {
|
||||
console.error('Failed to create browsers directory:', error)
|
||||
}
|
||||
|
||||
// Check if chromium browser exists (supports both old and new Playwright directory structures)
|
||||
// New format (v1.48+): chromium-1208/chrome-win64/chrome.exe
|
||||
// Old format: chromium-win32/chrome.exe
|
||||
const newChromiumPath = join(browsersPath, 'chromium-1208', 'chrome-win64', 'chrome.exe')
|
||||
const oldChromiumPath = join(browsersPath, 'chromium-win32', 'chrome.exe')
|
||||
const chromiumPath = fs.existsSync(newChromiumPath) ? newChromiumPath : oldChromiumPath
|
||||
|
||||
if (!fs.existsSync(chromiumPath)) {
|
||||
// Try to find any chromium revision
|
||||
let foundRevision = false
|
||||
try {
|
||||
const entries = fs.readdirSync(browsersPath)
|
||||
for (const entry of entries) {
|
||||
if (entry.startsWith('chromium-') && !entry.includes('headless')) {
|
||||
const revisionPath = join(browsersPath, entry, 'chrome-win64', 'chrome.exe')
|
||||
if (fs.existsSync(revisionPath)) {
|
||||
console.log('Found Chromium revision:', entry)
|
||||
foundRevision = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
if (!foundRevision) {
|
||||
dialog.showErrorBox(
|
||||
'浏览器文件未找到',
|
||||
`Playwright 浏览器文件不存在。\n\n` +
|
||||
`期望路径:${newChromiumPath}\n` +
|
||||
`或:${oldChromiumPath}\n\n` +
|
||||
`当前目录内容:${fs.existsSync(browsersPath) ? fs.readdirSync(browsersPath).join(', ') : '目录不存在'}\n\n` +
|
||||
`请运行以下命令安装浏览器:\n` +
|
||||
`npx playwright install chromium`
|
||||
)
|
||||
console.warn(
|
||||
'Playwright browser not found. Available:',
|
||||
fs.existsSync(browsersPath) ? fs.readdirSync(browsersPath) : 'none'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize ConfigManager BEFORE registering IPC handlers
|
||||
// This ensures config is loaded before any service tries to use it
|
||||
try {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
await configManager.initialize()
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize ConfigManager:', error)
|
||||
// Continue anyway - default config will be created
|
||||
}
|
||||
|
||||
// Set app user model id for windows
|
||||
electronApp.setAppUserModelId('com.electron')
|
||||
|
||||
@@ -58,7 +125,7 @@ app.whenReady().then(() => {
|
||||
optimizer.watchWindowShortcuts(window)
|
||||
})
|
||||
|
||||
// Register IPC handlers
|
||||
// Register IPC handlers (after ConfigManager is initialized)
|
||||
registerIpcHandlers()
|
||||
|
||||
// IPC test
|
||||
@@ -82,5 +149,41 @@ app.on('window-all-closed', () => {
|
||||
}
|
||||
})
|
||||
|
||||
// Global exception handlers to prevent crashes without logging
|
||||
process.on('uncaughtException', async (err) => {
|
||||
logger.error('Uncaught exception', { error: err })
|
||||
await logAudit('SYSTEM_CRASH', 'system', {
|
||||
username: 'system',
|
||||
computerName: process.env.COMPUTERNAME || 'unknown',
|
||||
resource: 'main-process',
|
||||
status: 'failure',
|
||||
metadata: { error: err.message, stack: err.stack }
|
||||
})
|
||||
console.error('Uncaught exception:', err)
|
||||
setTimeout(() => process.exit(1), 1000)
|
||||
})
|
||||
|
||||
process.on('unhandledRejection', async (reason, promise) => {
|
||||
logger.error('Unhandled Rejection', { reason: String(reason) })
|
||||
await logAudit('SYSTEM_ERROR', 'system', {
|
||||
username: 'system',
|
||||
computerName: process.env.COMPUTERNAME || 'unknown',
|
||||
resource: 'main-process',
|
||||
status: 'failure',
|
||||
metadata: { reason: String(reason) }
|
||||
})
|
||||
console.error('Unhandled Rejection:', reason)
|
||||
})
|
||||
|
||||
app.on('render-process-gone', (_, webContents, details) => {
|
||||
logger.error('Render process gone', { details, webContentsId: webContents.id })
|
||||
console.error('Render process gone:', details)
|
||||
})
|
||||
|
||||
app.on('child-process-gone', (_, details) => {
|
||||
logger.error('Child process gone', { details })
|
||||
console.error('Child process gone:', details)
|
||||
})
|
||||
|
||||
// In this file you can include the rest of your app's specific main process
|
||||
// code. You can also put them in separate files and require them here.
|
||||
|
||||
@@ -13,7 +13,11 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { SessionManager } from '../services/user/session-manager'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { logAudit } from '../services/logger/audit-logger'
|
||||
import type { UserInfo } from '../types/user.types'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { ValidationError } from '../types/errors'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
|
||||
const log = createLogger('AuthHandler')
|
||||
|
||||
@@ -70,131 +74,167 @@ export function registerAuthHandlers(): void {
|
||||
/**
|
||||
* Get computer name
|
||||
*/
|
||||
ipcMain.handle('auth:getComputerName', async (): Promise<string> => {
|
||||
const os = await import('os')
|
||||
return os.hostname()
|
||||
ipcMain.handle(IPC_CHANNELS.AUTH_GET_COMPUTER_NAME, async (): Promise<IpcResult<string>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const os = await import('os')
|
||||
return os.hostname()
|
||||
}, 'auth:getComputerName')
|
||||
})
|
||||
|
||||
/**
|
||||
* Silent login by computer name
|
||||
*/
|
||||
ipcMain.handle('auth:silentLogin', async (): Promise<SilentLoginResponse> => {
|
||||
try {
|
||||
log.info('Attempting silent login')
|
||||
const success = await sessionManager.loginByComputerName()
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.AUTH_SILENT_LOGIN,
|
||||
async (): Promise<IpcResult<SilentLoginResponse>> => {
|
||||
return withErrorHandling(async () => {
|
||||
log.info('Attempting silent login')
|
||||
const success = await sessionManager.loginByComputerName()
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
|
||||
if (success && userInfo) {
|
||||
// Check if admin needs user selection
|
||||
const requiresUserSelection = userInfo.userType === 'Admin'
|
||||
if (success && userInfo) {
|
||||
// Check if admin needs user selection
|
||||
const requiresUserSelection = userInfo.userType === 'Admin'
|
||||
|
||||
log.info('Silent login successful', {
|
||||
username: userInfo.username,
|
||||
userType: userInfo.userType,
|
||||
requiresUserSelection
|
||||
})
|
||||
log.info('Silent login successful', {
|
||||
username: userInfo.username,
|
||||
userType: userInfo.userType,
|
||||
requiresUserSelection
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
userInfo,
|
||||
requiresUserSelection
|
||||
// Audit log: LOGIN success (non-blocking)
|
||||
const os = await import('os')
|
||||
logAudit('LOGIN', String(userInfo.id), {
|
||||
username: userInfo.username,
|
||||
computerName: os.hostname(),
|
||||
resource: 'ERP_SYSTEM',
|
||||
status: 'success',
|
||||
metadata: { loginType: 'silent', userType: userInfo.userType }
|
||||
}).catch((err) => log.warn('Failed to write audit log', { err }))
|
||||
|
||||
return {
|
||||
success: true,
|
||||
userInfo,
|
||||
requiresUserSelection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.warn('Silent login failed - no matching user')
|
||||
return {
|
||||
success: false,
|
||||
requiresUserSelection: false
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Silent login error', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
error: `无感登录失败:${message}`
|
||||
}
|
||||
throw new ValidationError('无感登录失败:未找到匹配用户', 'VAL_INVALID_INPUT')
|
||||
}, 'auth:silentLogin')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Login with username and password
|
||||
*/
|
||||
ipcMain.handle('auth:login', async (_event, request: LoginRequest): Promise<LoginResponse> => {
|
||||
try {
|
||||
const { username, password } = request
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.AUTH_LOGIN,
|
||||
async (_event, request: LoginRequest): Promise<IpcResult<LoginResponse>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const { username, password } = request
|
||||
|
||||
if (!username || !password) {
|
||||
log.warn('Login attempt with missing credentials')
|
||||
return {
|
||||
success: false,
|
||||
error: '请输入用户名和密码'
|
||||
if (!username || !password) {
|
||||
log.warn('Login attempt with missing credentials')
|
||||
throw new ValidationError('请输入用户名和密码', 'VAL_MISSING_REQUIRED')
|
||||
}
|
||||
}
|
||||
|
||||
log.info('Login attempt', { username })
|
||||
const success = await sessionManager.login(username, password)
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
log.info('Login attempt', { username })
|
||||
const success = await sessionManager.login(username, password)
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
|
||||
if (success && userInfo) {
|
||||
log.info('Login successful', { username, userType: userInfo.userType })
|
||||
return {
|
||||
success: true,
|
||||
userInfo
|
||||
if (success && userInfo) {
|
||||
log.info('Login successful', { username, userType: userInfo.userType })
|
||||
|
||||
// Audit log: LOGIN success (non-blocking)
|
||||
const os = await import('os')
|
||||
logAudit('LOGIN', String(userInfo.id), {
|
||||
username: userInfo.username,
|
||||
computerName: os.hostname(),
|
||||
resource: 'ERP_SYSTEM',
|
||||
status: 'success',
|
||||
metadata: { loginType: 'credentials', userType: userInfo.userType }
|
||||
}).catch((err) => log.warn('Failed to write audit log', { err }))
|
||||
|
||||
return {
|
||||
success: true,
|
||||
userInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.warn('Login failed - invalid credentials', { username })
|
||||
return {
|
||||
success: false,
|
||||
error: '用户名或密码错误'
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Login error', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
error: `登录失败:${message}`
|
||||
}
|
||||
// Audit log: LOGIN failure (non-blocking)
|
||||
const os = await import('os')
|
||||
logAudit('LOGIN', '0', {
|
||||
username,
|
||||
computerName: os.hostname(),
|
||||
resource: 'ERP_SYSTEM',
|
||||
status: 'failure',
|
||||
metadata: { loginType: 'credentials', reason: 'invalid_credentials' }
|
||||
}).catch((err) => log.warn('Failed to write audit log', { err }))
|
||||
|
||||
log.warn('Login failed - invalid credentials', { username })
|
||||
throw new ValidationError('用户名或密码错误', 'VAL_INVALID_INPUT')
|
||||
}, 'auth:login')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Logout
|
||||
*/
|
||||
ipcMain.handle('auth:logout', async (): Promise<void> => {
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
log.info('User logout', { username: userInfo?.username })
|
||||
sessionManager.logout()
|
||||
ipcMain.handle(IPC_CHANNELS.AUTH_LOGOUT, async (): Promise<IpcResult<void>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
log.info('User logout', { username: userInfo?.username })
|
||||
|
||||
// Audit log: LOGOUT (non-blocking)
|
||||
if (userInfo) {
|
||||
const os = await import('os')
|
||||
logAudit('LOGOUT', String(userInfo.id), {
|
||||
username: userInfo.username,
|
||||
computerName: os.hostname(),
|
||||
resource: 'ERP_SYSTEM',
|
||||
status: 'success',
|
||||
metadata: { userType: userInfo.userType }
|
||||
}).catch((err) => log.warn('Failed to write audit log', { err }))
|
||||
}
|
||||
|
||||
sessionManager.logout()
|
||||
}, 'auth:logout')
|
||||
})
|
||||
|
||||
/**
|
||||
* Get current user
|
||||
*/
|
||||
ipcMain.handle('auth:getCurrentUser', async (): Promise<CurrentUserResponse> => {
|
||||
const isAuthenticated = sessionManager.isAuthenticated()
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
|
||||
return {
|
||||
isAuthenticated,
|
||||
userInfo: userInfo ?? undefined
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.AUTH_GET_CURRENT_USER,
|
||||
async (): Promise<IpcResult<CurrentUserResponse>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const isAuthenticated = sessionManager.isAuthenticated()
|
||||
const userInfo = sessionManager.getUserInfo()
|
||||
return {
|
||||
isAuthenticated,
|
||||
userInfo: userInfo ?? undefined
|
||||
}
|
||||
}, 'auth:getCurrentUser')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Get all users (for admin user selection)
|
||||
*/
|
||||
ipcMain.handle('auth:getAllUsers', async (): Promise<UserInfo[]> => {
|
||||
log.debug('Fetching all users for admin selection')
|
||||
return await sessionManager.getAllUsers()
|
||||
ipcMain.handle(IPC_CHANNELS.AUTH_GET_ALL_USERS, async (): Promise<IpcResult<UserInfo[]>> => {
|
||||
return withErrorHandling(async () => {
|
||||
log.debug('Fetching all users for admin selection')
|
||||
return await sessionManager.getAllUsers()
|
||||
}, 'auth:getAllUsers')
|
||||
})
|
||||
|
||||
/**
|
||||
* Switch user (admin only)
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'auth:switchUser',
|
||||
async (_event, userInfo: UserInfo): Promise<UserSelectionResponse> => {
|
||||
try {
|
||||
IPC_CHANNELS.AUTH_SWITCH_USER,
|
||||
async (_event, userInfo: UserInfo): Promise<IpcResult<UserSelectionResponse>> => {
|
||||
return withErrorHandling(async () => {
|
||||
log.info('User switch attempt', { targetUser: userInfo.username })
|
||||
const success = sessionManager.switchUser(userInfo)
|
||||
|
||||
@@ -208,25 +248,15 @@ export function registerAuthHandlers(): void {
|
||||
}
|
||||
|
||||
log.warn('User switch failed')
|
||||
return {
|
||||
success: false,
|
||||
error: '用户切换失败'
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('User switch error', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
error: `用户切换失败:${message}`
|
||||
}
|
||||
}
|
||||
throw new ValidationError('用户切换失败', 'VAL_INVALID_INPUT')
|
||||
}, 'auth:switchUser')
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* Check if current user is admin
|
||||
*/
|
||||
ipcMain.handle('auth:isAdmin', async (): Promise<boolean> => {
|
||||
return sessionManager.isAdmin()
|
||||
ipcMain.handle(IPC_CHANNELS.AUTH_IS_ADMIN, async (): Promise<IpcResult<boolean>> => {
|
||||
return withErrorHandling(async () => sessionManager.isAdmin(), 'auth:isAdmin')
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,76 +1,160 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { ipcMain, type WebContents } from 'electron'
|
||||
import { ErpAuthService } from '../services/erp/erp-auth'
|
||||
import { CleanerService } from '../services/erp/cleaner'
|
||||
import { OrderNumberResolver } from '../services/erp/order-resolver'
|
||||
import { MySqlService } from '../services/database/mysql'
|
||||
import { SqlServerService } from '../services/database/sql-server'
|
||||
import { ConfigManager } from '../services/config/config-manager'
|
||||
import { ResultExporter } from '../services/excel/result-exporter'
|
||||
import { CleanerReportGenerator } from '../services/report/cleaner-report-generator'
|
||||
import { RustfsService } from '../services/rustfs'
|
||||
import { SessionManager } from '../services/user/session-manager'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { logAudit } from '../services/logger/audit-logger'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
import { ErpConnectionError, ValidationError, DatabaseQueryError } from '../types/errors'
|
||||
import type {
|
||||
CleanerInput,
|
||||
CleanerResult,
|
||||
CleanerProgress,
|
||||
ExportResultItem,
|
||||
ExportResultResponse
|
||||
} from '../types/cleaner.types'
|
||||
import { UserErpConfigService } from '../services/user/user-erp-config-service'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
|
||||
const log = createLogger('CleanerHandler')
|
||||
|
||||
function sendProgress(
|
||||
sender: WebContents,
|
||||
message: string,
|
||||
progress: number,
|
||||
extra?: Partial<CleanerProgress>
|
||||
): void {
|
||||
try {
|
||||
const progressData: CleanerProgress = {
|
||||
message,
|
||||
progress,
|
||||
currentOrderIndex: extra?.currentOrderIndex ?? 0,
|
||||
totalOrders: extra?.totalOrders ?? 0,
|
||||
currentMaterialIndex: extra?.currentMaterialIndex ?? 0,
|
||||
totalMaterialsInOrder: extra?.totalMaterialsInOrder ?? 0,
|
||||
currentOrderNumber: extra?.currentOrderNumber,
|
||||
phase: extra?.phase ?? 'processing'
|
||||
}
|
||||
sender.send(IPC_CHANNELS.CLEANER_PROGRESS, progressData)
|
||||
} catch (error) {
|
||||
log.warn('Failed to send progress event', { error })
|
||||
}
|
||||
}
|
||||
|
||||
async function getDatabaseService(): Promise<MySqlService | SqlServerService> {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
|
||||
if (dbType === 'sqlserver') {
|
||||
const dbConfig = config.database.sqlserver
|
||||
const sqlServerService = new SqlServerService({
|
||||
server: dbConfig.server,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
options: {
|
||||
encrypt: false,
|
||||
trustServerCertificate: dbConfig.trustServerCertificate
|
||||
}
|
||||
})
|
||||
await sqlServerService.connect()
|
||||
return sqlServerService
|
||||
} else {
|
||||
const dbConfig = config.database.mysql
|
||||
const mysqlService = new MySqlService({
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database
|
||||
})
|
||||
await mysqlService.connect()
|
||||
return mysqlService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register IPC handlers for cleaner service
|
||||
* Get ERP configuration for current user
|
||||
* URL is from config.yaml (fixed infrastructure)
|
||||
* Username and password are from user's database config
|
||||
*/
|
||||
async function getErpConfig(): Promise<{
|
||||
url: string
|
||||
username: string
|
||||
password: string
|
||||
}> {
|
||||
// Get ERP URL from config.yaml (fixed for all users)
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const globalConfig = configManager.getConfig()
|
||||
const erpUrl = globalConfig.erp.url
|
||||
|
||||
// Get username and password from user's database config
|
||||
const erpConfigService = UserErpConfigService.getInstance()
|
||||
const userConfig = await erpConfigService.getCurrentUserErpConfig()
|
||||
|
||||
if (!userConfig || !userConfig.username || !userConfig.password) {
|
||||
throw new ValidationError(
|
||||
'ERP 配置不完整。请在设置中配置 ERP 用户名和密码',
|
||||
'VAL_MISSING_REQUIRED'
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
url: erpUrl,
|
||||
username: userConfig.username,
|
||||
password: userConfig.password
|
||||
}
|
||||
}
|
||||
|
||||
export function registerCleanerHandlers(): void {
|
||||
ipcMain.handle(
|
||||
'cleaner:run',
|
||||
async (_event, input: CleanerInput): Promise<IpcResult<CleanerResult>> => {
|
||||
IPC_CHANNELS.CLEANER_RUN,
|
||||
async (event, input: CleanerInput): Promise<IpcResult<CleanerResult>> => {
|
||||
const sender = event.sender
|
||||
const startTime = Date.now()
|
||||
|
||||
return withErrorHandling(async () => {
|
||||
let authService: ErpAuthService | null = null
|
||||
let mysqlService: MySqlService | null = null
|
||||
let dbService: MySqlService | SqlServerService | null = null
|
||||
|
||||
try {
|
||||
// Check environment variables
|
||||
const erpUrl = process.env.ERP_URL || ''
|
||||
const erpUsername = process.env.ERP_USERNAME || ''
|
||||
const erpPassword = process.env.ERP_PASSWORD || ''
|
||||
// Get ERP configuration from database for current user
|
||||
log.info('Fetching ERP configuration from database...')
|
||||
const erpConfig = await getErpConfig()
|
||||
|
||||
log.info('Config check', {
|
||||
url: erpUrl ? 'configured' : 'EMPTY',
|
||||
username: erpUsername ? 'configured' : 'EMPTY'
|
||||
log.info('ERP config retrieved', {
|
||||
url: erpConfig.url ? 'configured' : 'EMPTY',
|
||||
username: erpConfig.username ? 'configured' : 'EMPTY'
|
||||
})
|
||||
|
||||
if (!erpUrl || !erpUsername || !erpPassword) {
|
||||
throw new ValidationError(
|
||||
'ERP 配置不完整。请检查 .env 文件中的 ERP_URL, ERP_USERNAME, ERP_PASSWORD',
|
||||
'VAL_MISSING_REQUIRED'
|
||||
)
|
||||
}
|
||||
|
||||
// Resolve order numbers (convert productionIDs to 生产订单号)
|
||||
const mysqlConfig = {
|
||||
host: process.env.DB_MYSQL_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
|
||||
user: process.env.DB_USERNAME || 'root',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || ''
|
||||
}
|
||||
|
||||
log.info('Connecting to MySQL for order resolution...')
|
||||
mysqlService = new MySqlService(mysqlConfig)
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
log.info(
|
||||
`Connecting to ${dbType === 'sqlserver' ? 'SQL Server' : 'MySQL'} for order resolution...`
|
||||
)
|
||||
|
||||
try {
|
||||
await mysqlService.connect()
|
||||
dbService = await getDatabaseService()
|
||||
} catch (error) {
|
||||
throw new DatabaseQueryError(
|
||||
'MySQL 连接失败',
|
||||
'数据库连接失败',
|
||||
'DB_CONNECTION_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
}
|
||||
|
||||
const resolver = new OrderNumberResolver(mysqlService)
|
||||
const resolver = new OrderNumberResolver(dbService)
|
||||
const mappings = await resolver.resolve(input.orderNumbers)
|
||||
|
||||
// Get valid order numbers and warnings
|
||||
const validOrderNumbers = resolver.getValidOrderNumbers(mappings)
|
||||
const warnings = resolver.getWarnings(mappings)
|
||||
|
||||
@@ -87,12 +171,11 @@ export function registerCleanerHandlers(): void {
|
||||
|
||||
log.info('Resolved order numbers', { count: validOrderNumbers.length })
|
||||
|
||||
// Create auth service and login
|
||||
authService = new ErpAuthService({
|
||||
url: erpUrl,
|
||||
username: erpUsername,
|
||||
password: erpPassword,
|
||||
headless: true
|
||||
url: erpConfig.url,
|
||||
username: erpConfig.username,
|
||||
password: erpConfig.password,
|
||||
headless: input.headless ?? true
|
||||
})
|
||||
|
||||
log.info('Logging in to ERP...')
|
||||
@@ -107,31 +190,142 @@ export function registerCleanerHandlers(): void {
|
||||
}
|
||||
log.info('Login successful')
|
||||
|
||||
// Create cleaner service and run cleaning with resolved order numbers
|
||||
// Send login complete progress
|
||||
const totalOrders = validOrderNumbers.length
|
||||
const loginProgress = (1 / (1 + totalOrders)) * 100
|
||||
sendProgress(sender, 'ERP 登录成功', loginProgress, {
|
||||
phase: 'login',
|
||||
currentOrderIndex: 0,
|
||||
totalOrders,
|
||||
currentMaterialIndex: 0,
|
||||
totalMaterialsInOrder: 0
|
||||
})
|
||||
|
||||
const cleaner = new CleanerService(authService)
|
||||
|
||||
const modifiedInput: CleanerInput = {
|
||||
...input,
|
||||
orderNumbers: validOrderNumbers,
|
||||
onProgress: input.onProgress
|
||||
onProgress: (message, progress, extra) => {
|
||||
sendProgress(sender, message, progress ?? 0, extra)
|
||||
}
|
||||
}
|
||||
|
||||
log.info('Starting cleaning', { orderCount: validOrderNumbers.length })
|
||||
log.info('Starting cleaning', {
|
||||
orderCount: validOrderNumbers.length,
|
||||
queryBatchSize: input.queryBatchSize ?? 100,
|
||||
processConcurrency: input.processConcurrency ?? 1
|
||||
})
|
||||
const result = await cleaner.clean(modifiedInput)
|
||||
|
||||
// Add warnings to result errors if any
|
||||
if (warnings.length > 0) {
|
||||
result.errors = [...warnings, ...result.errors]
|
||||
}
|
||||
|
||||
// Send completion progress
|
||||
sendProgress(sender, '清理完成', 100, {
|
||||
phase: 'complete',
|
||||
currentOrderIndex: totalOrders,
|
||||
totalOrders,
|
||||
currentMaterialIndex: 0,
|
||||
totalMaterialsInOrder: 0
|
||||
})
|
||||
|
||||
log.info('Cleaning completed', {
|
||||
processedCount: result.ordersProcessed,
|
||||
errorCount: result.errors.length
|
||||
})
|
||||
|
||||
// Audit log: CLEAN (non-blocking)
|
||||
const os = await import('os')
|
||||
const currentUser = SessionManager.getInstance().getUserInfo()
|
||||
if (currentUser) {
|
||||
const status: 'success' | 'failure' | 'partial' =
|
||||
result.errors.length > 0 && result.materialsDeleted > 0
|
||||
? 'partial'
|
||||
: result.errors.length > 0
|
||||
? 'failure'
|
||||
: 'success'
|
||||
logAudit('CLEAN', String(currentUser.id), {
|
||||
username: currentUser.username,
|
||||
computerName: os.hostname(),
|
||||
resource: 'MATERIAL_PLAN',
|
||||
status,
|
||||
metadata: {
|
||||
orderCount: validOrderNumbers.length,
|
||||
dryRun: input.dryRun ?? false,
|
||||
queryBatchSize: input.queryBatchSize ?? 100,
|
||||
processConcurrency: input.processConcurrency ?? 1,
|
||||
materialsDeleted: result.materialsDeleted,
|
||||
materialsSkipped: result.materialsSkipped,
|
||||
errorCount: result.errors.length
|
||||
}
|
||||
}).catch((err) => log.warn('Failed to write audit log', { err }))
|
||||
}
|
||||
|
||||
// Generate report and upload to RustFS (silent, user unaware)
|
||||
try {
|
||||
const endTime = Date.now()
|
||||
const currentUser = SessionManager.getInstance().getUserInfo()
|
||||
const username = currentUser?.username ?? 'unknown'
|
||||
|
||||
const reportGenerator = new CleanerReportGenerator()
|
||||
const reportPath = await reportGenerator.generateReport(result, {
|
||||
dryRun: input.dryRun ?? false,
|
||||
username,
|
||||
startTime,
|
||||
endTime
|
||||
})
|
||||
log.info('Report generated', { path: reportPath })
|
||||
|
||||
// Upload to RustFS if enabled
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
|
||||
if (config.rustfs?.enabled && config.rustfs.endpoint) {
|
||||
try {
|
||||
const rustfs = new RustfsService({ config: config.rustfs })
|
||||
const reportFileName = reportPath.split(/[\\/]/).pop() || 'report.md'
|
||||
const storageKey = rustfs.generateReportKey(reportFileName, username)
|
||||
|
||||
log.info('Uploading report to RustFS', {
|
||||
localPath: reportPath,
|
||||
storageKey
|
||||
})
|
||||
|
||||
const uploadResult = await rustfs.uploadFile(
|
||||
reportPath,
|
||||
storageKey,
|
||||
'text/markdown; charset=utf-8'
|
||||
)
|
||||
|
||||
if (uploadResult.success) {
|
||||
log.info('Report uploaded to RustFS successfully', {
|
||||
key: storageKey,
|
||||
etag: uploadResult.etag
|
||||
})
|
||||
} else {
|
||||
log.warn('Failed to upload report to RustFS', {
|
||||
error: uploadResult.error,
|
||||
key: storageKey
|
||||
})
|
||||
}
|
||||
} catch (rustfsError) {
|
||||
log.error('RustFS upload failed', {
|
||||
error: rustfsError instanceof Error ? rustfsError.message : String(rustfsError)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
log.debug('RustFS is not enabled, skipping upload')
|
||||
}
|
||||
} catch (reportError) {
|
||||
log.warn('Failed to generate report', {
|
||||
error: reportError instanceof Error ? reportError.message : String(reportError)
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
} finally {
|
||||
// Clean up: close browser
|
||||
if (authService) {
|
||||
try {
|
||||
await authService.close()
|
||||
@@ -143,13 +337,12 @@ export function registerCleanerHandlers(): void {
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up: disconnect MySQL
|
||||
if (mysqlService) {
|
||||
if (dbService) {
|
||||
try {
|
||||
await mysqlService.disconnect()
|
||||
log.debug('MySQL disconnected')
|
||||
await dbService.disconnect()
|
||||
log.debug('Database disconnected')
|
||||
} catch (closeError) {
|
||||
log.warn('Error disconnecting MySQL', {
|
||||
log.warn('Error disconnecting database', {
|
||||
error: closeError instanceof Error ? closeError.message : String(closeError)
|
||||
})
|
||||
}
|
||||
@@ -159,34 +352,17 @@ export function registerCleanerHandlers(): void {
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* Export validation results to Excel
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'cleaner:exportResults',
|
||||
async (_event, items: ExportResultItem[]): Promise<ExportResultResponse> => {
|
||||
try {
|
||||
IPC_CHANNELS.CLEANER_EXPORT_RESULTS,
|
||||
async (_event, items: ExportResultItem[]): Promise<IpcResult<ExportResultResponse>> => {
|
||||
return withErrorHandling(async () => {
|
||||
log.info('Exporting validation results', { count: items.length })
|
||||
|
||||
if (!items || items.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: '没有数据可导出'
|
||||
}
|
||||
throw new ValidationError('没有数据可导出', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
|
||||
const exporter = new ResultExporter()
|
||||
const result = await exporter.exportValidationResults(items)
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
log.error('Export handler failed', { error: errorMessage })
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage
|
||||
}
|
||||
}
|
||||
return await exporter.exportValidationResults(items)
|
||||
}, 'cleaner:exportResults')
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,13 +2,15 @@ import { ipcMain } from 'electron'
|
||||
import { MySqlService } from '../services/database/mysql'
|
||||
import { SqlServerService } from '../services/database/sql-server'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { DatabaseQueryError, ValidationError } from '../types/errors'
|
||||
import { ValidationError } from '../types/errors'
|
||||
import type {
|
||||
MySqlConfig,
|
||||
MySqlQueryResult,
|
||||
SqlServerConfig,
|
||||
SqlServerQueryResult
|
||||
} from '../types/ipc-api.types'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
|
||||
const log = createLogger('DatabaseHandler')
|
||||
|
||||
@@ -17,6 +19,39 @@ const mysqlServices = new Map<string, MySqlService>()
|
||||
|
||||
// Store SQL Server service instances per window/connection
|
||||
const sqlServerServices = new Map<string, SqlServerService>()
|
||||
const cleanupBoundWindows = new Set<string>()
|
||||
|
||||
function bindWindowCleanup(
|
||||
windowId: string,
|
||||
sender: { once: (event: string, listener: () => void) => void }
|
||||
): void {
|
||||
if (cleanupBoundWindows.has(windowId)) {
|
||||
return
|
||||
}
|
||||
|
||||
sender.once('destroyed', () => {
|
||||
const mysql = getMySqlService(windowId)
|
||||
const sqlServer = getSqlServerService(windowId)
|
||||
|
||||
if (mysql) {
|
||||
mysql
|
||||
.disconnect()
|
||||
.catch((error) => log.warn('MySQL disconnect on window destroy failed', { error }))
|
||||
deleteMySqlService(windowId)
|
||||
}
|
||||
|
||||
if (sqlServer) {
|
||||
sqlServer
|
||||
.disconnect()
|
||||
.catch((error) => log.warn('SQL Server disconnect on window destroy failed', { error }))
|
||||
deleteSqlServerService(windowId)
|
||||
}
|
||||
|
||||
cleanupBoundWindows.delete(windowId)
|
||||
})
|
||||
|
||||
cleanupBoundWindows.add(windowId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create MySQL service for a connection ID
|
||||
@@ -65,59 +100,58 @@ function deleteSqlServerService(connectionId: string): void {
|
||||
*/
|
||||
export function registerDatabaseHandlers(): void {
|
||||
// Connect to MySQL
|
||||
ipcMain.handle('database:mysql:connect', async (event, config: MySqlConfig): Promise<void> => {
|
||||
try {
|
||||
// Use window ID as connection identifier
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
log.info('Connecting to MySQL', { windowId })
|
||||
const service = new MySqlService(config)
|
||||
await service.connect()
|
||||
setMySqlService(windowId, service)
|
||||
log.info('MySQL connected', { windowId })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to connect to MySQL'
|
||||
log.error('MySQL connection failed', { error: message })
|
||||
throw new DatabaseQueryError(
|
||||
message,
|
||||
'DB_CONNECTION_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DATABASE_MYSQL_CONNECT,
|
||||
async (event, config: MySqlConfig): Promise<IpcResult<void>> => {
|
||||
return withErrorHandling(async () => {
|
||||
// Use window ID as connection identifier
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
bindWindowCleanup(
|
||||
windowId,
|
||||
event.sender as { once: (event: string, listener: () => void) => void }
|
||||
)
|
||||
log.info('Connecting to MySQL', { windowId })
|
||||
const service = new MySqlService(config)
|
||||
await service.connect()
|
||||
setMySqlService(windowId, service)
|
||||
log.info('MySQL connected', { windowId })
|
||||
}, 'database:mysql:connect')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// Disconnect from MySQL
|
||||
ipcMain.handle('database:mysql:disconnect', async (event): Promise<void> => {
|
||||
try {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getMySqlService(windowId)
|
||||
if (service) {
|
||||
await service.disconnect()
|
||||
deleteMySqlService(windowId)
|
||||
log.info('MySQL disconnected', { windowId })
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to disconnect from MySQL'
|
||||
log.error('MySQL disconnect failed', { error: message })
|
||||
throw new DatabaseQueryError(
|
||||
message,
|
||||
'DB_CONNECTION_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DATABASE_MYSQL_DISCONNECT,
|
||||
async (event): Promise<IpcResult<void>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getMySqlService(windowId)
|
||||
if (service) {
|
||||
await service.disconnect()
|
||||
deleteMySqlService(windowId)
|
||||
log.info('MySQL disconnected', { windowId })
|
||||
}
|
||||
}, 'database:mysql:disconnect')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// Check if MySQL is connected
|
||||
ipcMain.handle('database:mysql:isConnected', async (event): Promise<boolean> => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getMySqlService(windowId)
|
||||
return service ? service.isConnected() : false
|
||||
})
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DATABASE_MYSQL_IS_CONNECTED,
|
||||
async (event): Promise<IpcResult<boolean>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getMySqlService(windowId)
|
||||
return service ? service.isConnected() : false
|
||||
}, 'database:mysql:isConnected')
|
||||
}
|
||||
)
|
||||
|
||||
// Execute MySQL query
|
||||
ipcMain.handle(
|
||||
'database:mysql:query',
|
||||
async (event, sql: string, params?: unknown[]): Promise<MySqlQueryResult> => {
|
||||
try {
|
||||
IPC_CHANNELS.DATABASE_MYSQL_QUERY,
|
||||
async (event, sql: string, params?: unknown[]): Promise<IpcResult<MySqlQueryResult>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getMySqlService(windowId)
|
||||
|
||||
@@ -130,79 +164,66 @@ export function registerDatabaseHandlers(): void {
|
||||
|
||||
log.debug('Executing MySQL query', { windowId, sql: sql.substring(0, 100) })
|
||||
return await service.query(sql, params)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'MySQL query failed'
|
||||
log.error('MySQL query failed', { error: message })
|
||||
throw new DatabaseQueryError(
|
||||
message,
|
||||
'DB_QUERY_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
}
|
||||
}, 'database:mysql:query')
|
||||
}
|
||||
)
|
||||
|
||||
// Connect to SQL Server
|
||||
ipcMain.handle(
|
||||
'database:sqlserver:connect',
|
||||
async (event, config: SqlServerConfig): Promise<void> => {
|
||||
try {
|
||||
IPC_CHANNELS.DATABASE_SQLSERVER_CONNECT,
|
||||
async (event, config: SqlServerConfig): Promise<IpcResult<void>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
bindWindowCleanup(
|
||||
windowId,
|
||||
event.sender as { once: (event: string, listener: () => void) => void }
|
||||
)
|
||||
log.info('Connecting to SQL Server', { windowId })
|
||||
const service = new SqlServerService(config)
|
||||
await service.connect()
|
||||
setSqlServerService(windowId, service)
|
||||
log.info('SQL Server connected', { windowId })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to connect to SQL Server'
|
||||
log.error('SQL Server connection failed', { error: message })
|
||||
throw new DatabaseQueryError(
|
||||
message,
|
||||
'DB_CONNECTION_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
}
|
||||
}, 'database:sqlserver:connect')
|
||||
}
|
||||
)
|
||||
|
||||
// Disconnect from SQL Server
|
||||
ipcMain.handle('database:sqlserver:disconnect', async (event): Promise<void> => {
|
||||
try {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getSqlServerService(windowId)
|
||||
if (service) {
|
||||
await service.disconnect()
|
||||
deleteSqlServerService(windowId)
|
||||
log.info('SQL Server disconnected', { windowId })
|
||||
}
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Failed to disconnect from SQL Server'
|
||||
log.error('SQL Server disconnect failed', { error: message })
|
||||
throw new DatabaseQueryError(
|
||||
message,
|
||||
'DB_CONNECTION_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DATABASE_SQLSERVER_DISCONNECT,
|
||||
async (event): Promise<IpcResult<void>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getSqlServerService(windowId)
|
||||
if (service) {
|
||||
await service.disconnect()
|
||||
deleteSqlServerService(windowId)
|
||||
log.info('SQL Server disconnected', { windowId })
|
||||
}
|
||||
}, 'database:sqlserver:disconnect')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// Check if SQL Server is connected
|
||||
ipcMain.handle('database:sqlserver:isConnected', async (event): Promise<boolean> => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getSqlServerService(windowId)
|
||||
return service ? service.isConnected() : false
|
||||
})
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DATABASE_SQLSERVER_IS_CONNECTED,
|
||||
async (event): Promise<IpcResult<boolean>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getSqlServerService(windowId)
|
||||
return service ? service.isConnected() : false
|
||||
}, 'database:sqlserver:isConnected')
|
||||
}
|
||||
)
|
||||
|
||||
// Execute SQL Server query
|
||||
ipcMain.handle(
|
||||
'database:sqlserver:query',
|
||||
IPC_CHANNELS.DATABASE_SQLSERVER_QUERY,
|
||||
async (
|
||||
event,
|
||||
sqlString: string,
|
||||
params?: Record<string, unknown>
|
||||
): Promise<SqlServerQueryResult> => {
|
||||
try {
|
||||
): Promise<IpcResult<SqlServerQueryResult>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const windowId = (event.sender as { id: number }).id.toString()
|
||||
const service = getSqlServerService(windowId)
|
||||
|
||||
@@ -226,15 +247,7 @@ export function registerDatabaseHandlers(): void {
|
||||
} else {
|
||||
return await service.query(sqlString)
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'SQL Server query failed'
|
||||
log.error('SQL Server query failed', { error: message })
|
||||
throw new DatabaseQueryError(
|
||||
message,
|
||||
'DB_QUERY_FAILED',
|
||||
error instanceof Error ? error : undefined
|
||||
)
|
||||
}
|
||||
}, 'database:sqlserver:query')
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,46 +1,106 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { ipcMain, type WebContents } from 'electron'
|
||||
import { ErpAuthService } from '../services/erp/erp-auth'
|
||||
import { ExtractorService } from '../services/erp/extractor'
|
||||
import { OrderNumberResolver } from '../services/erp/order-resolver'
|
||||
import { create, type IDatabaseService } from '../services/database'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { logAudit } from '../services/logger/audit-logger'
|
||||
import { SessionManager } from '../services/user/session-manager'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
import { ErpConnectionError, ValidationError, DatabaseQueryError } from '../types/errors'
|
||||
import type { ExtractorInput, ExtractorResult } from '../types/extractor.types'
|
||||
import type { ExtractorInput, ExtractorResult, ExtractionProgress } from '../types/extractor.types'
|
||||
import { UserErpConfigService } from '../services/user/user-erp-config-service'
|
||||
import { ConfigManager } from '../services/config/config-manager'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
|
||||
const log = createLogger('ExtractorHandler')
|
||||
|
||||
function sendProgress(
|
||||
sender: WebContents,
|
||||
message: string,
|
||||
progress: number,
|
||||
extra?: Partial<ExtractionProgress>
|
||||
): void {
|
||||
try {
|
||||
const progressData = { message, progress, ...extra }
|
||||
sender.send(IPC_CHANNELS.EXTRACTOR_PROGRESS, progressData)
|
||||
} catch (error) {
|
||||
log.warn('Failed to send progress event', { error })
|
||||
}
|
||||
}
|
||||
|
||||
function sendLog(sender: WebContents, level: string, message: string): void {
|
||||
try {
|
||||
sender.send(IPC_CHANNELS.EXTRACTOR_LOG, { level, message })
|
||||
} catch (error) {
|
||||
log.warn('Failed to send log event', { error })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ERP configuration for current user
|
||||
* URL is from config.yaml (fixed infrastructure)
|
||||
* Username and password are from user's database config
|
||||
*/
|
||||
async function getErpConfig(): Promise<{
|
||||
url: string
|
||||
username: string
|
||||
password: string
|
||||
}> {
|
||||
// Get ERP URL from config.yaml (fixed for all users)
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const globalConfig = configManager.getConfig()
|
||||
const erpUrl = globalConfig.erp.url
|
||||
|
||||
// Get username and password from user's database config
|
||||
const erpConfigService = UserErpConfigService.getInstance()
|
||||
const userConfig = await erpConfigService.getCurrentUserErpConfig()
|
||||
|
||||
if (!userConfig || !userConfig.username || !userConfig.password) {
|
||||
throw new ValidationError(
|
||||
'ERP 配置不完整。请在设置中配置 ERP 用户名和密码',
|
||||
'VAL_MISSING_REQUIRED'
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
url: erpUrl,
|
||||
username: userConfig.username,
|
||||
password: userConfig.password
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register IPC handlers for extractor service
|
||||
*/
|
||||
export function registerExtractorHandlers(): void {
|
||||
ipcMain.handle(
|
||||
'extractor:run',
|
||||
async (_event, input: ExtractorInput): Promise<IpcResult<ExtractorResult>> => {
|
||||
IPC_CHANNELS.EXTRACTOR_RUN,
|
||||
async (event, input: ExtractorInput): Promise<IpcResult<ExtractorResult>> => {
|
||||
const sender = event.sender
|
||||
|
||||
return withErrorHandling(async () => {
|
||||
let authService: ErpAuthService | null = null
|
||||
let dbService: IDatabaseService | null = null
|
||||
|
||||
try {
|
||||
// Check environment variables
|
||||
const erpUrl = process.env.ERP_URL || ''
|
||||
const erpUsername = process.env.ERP_USERNAME || ''
|
||||
const erpPassword = process.env.ERP_PASSWORD || ''
|
||||
// Get ERP configuration from database for current user
|
||||
log.info('Fetching ERP configuration from database...')
|
||||
const erpConfig = await getErpConfig()
|
||||
|
||||
log.info('Config check', {
|
||||
url: erpUrl ? 'configured' : 'EMPTY',
|
||||
username: erpUsername ? 'configured' : 'EMPTY'
|
||||
log.info('ERP config retrieved', {
|
||||
url: erpConfig.url ? 'configured' : 'EMPTY',
|
||||
username: erpConfig.username ? 'configured' : 'EMPTY'
|
||||
})
|
||||
|
||||
if (!erpUrl || !erpUsername || !erpPassword) {
|
||||
throw new ValidationError(
|
||||
'ERP 配置不完整。请检查 .env 文件中的 ERP_URL, ERP_USERNAME, ERP_PASSWORD',
|
||||
'VAL_MISSING_REQUIRED'
|
||||
)
|
||||
}
|
||||
|
||||
// Create database service using factory
|
||||
log.info('Connecting to database for order resolution...')
|
||||
sendProgress(sender, '连接数据库...', 3.33, {
|
||||
phase: 'login',
|
||||
subProgress: { step: '连接数据库', current: 1, total: 3 }
|
||||
})
|
||||
sendLog(sender, 'system', '正在连接数据库...')
|
||||
|
||||
try {
|
||||
dbService = await create()
|
||||
} catch (error) {
|
||||
@@ -52,6 +112,12 @@ export function registerExtractorHandlers(): void {
|
||||
}
|
||||
|
||||
// Resolve order numbers (convert productionIDs to 生产订单号)
|
||||
sendProgress(sender, '解析订单号...', 6.67, {
|
||||
phase: 'login',
|
||||
subProgress: { step: '解析订单号', current: 2, total: 3 }
|
||||
})
|
||||
sendLog(sender, 'info', '正在解析订单号...')
|
||||
|
||||
const resolver = new OrderNumberResolver(dbService)
|
||||
const mappings = await resolver.resolve(input.orderNumbers)
|
||||
|
||||
@@ -59,6 +125,9 @@ export function registerExtractorHandlers(): void {
|
||||
const validOrderNumbers = resolver.getValidOrderNumbers(mappings)
|
||||
const warnings = resolver.getWarnings(mappings)
|
||||
|
||||
// Get deduplication report for detailed logging
|
||||
const dedupReport = resolver.getDeduplicationReport(mappings)
|
||||
|
||||
if (warnings.length > 0) {
|
||||
log.warn('Resolution warnings', { warnings })
|
||||
}
|
||||
@@ -72,18 +141,43 @@ export function registerExtractorHandlers(): void {
|
||||
|
||||
log.info('Resolved order numbers', { count: validOrderNumbers.length })
|
||||
|
||||
// Log deduplication summary
|
||||
sendLog(sender, 'info', dedupReport.summary)
|
||||
|
||||
// Log only merged mappings (where multiple productionIDs map to the same order number)
|
||||
if (dedupReport.inputCount > dedupReport.uniqueOrderNumbersCount) {
|
||||
sendLog(sender, 'info', '重复合并详情:')
|
||||
dedupReport.orderNumberGroups.forEach((productionIds, orderNumber) => {
|
||||
if (productionIds.length > 1) {
|
||||
sendLog(
|
||||
sender,
|
||||
'info',
|
||||
` ${orderNumber} ← ${productionIds.join('、')} (共 ${productionIds.length} 个总排号)`
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Create auth service and login
|
||||
authService = new ErpAuthService({
|
||||
url: erpUrl,
|
||||
username: erpUsername,
|
||||
password: erpPassword,
|
||||
url: erpConfig.url,
|
||||
username: erpConfig.username,
|
||||
password: erpConfig.password,
|
||||
headless: true
|
||||
})
|
||||
|
||||
sendProgress(sender, '登录 ERP 系统...', 9.99, {
|
||||
phase: 'login',
|
||||
subProgress: { step: '登录 ERP 系统', current: 3, total: 3 }
|
||||
})
|
||||
sendLog(sender, 'system', '正在登录 ERP 系统...')
|
||||
|
||||
log.info('Logging in to ERP...')
|
||||
try {
|
||||
await authService.login()
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : '未知错误'
|
||||
sendLog(sender, 'error', `ERP 登录失败:${errorMsg}`)
|
||||
throw new ErpConnectionError(
|
||||
'ERP 登录失败',
|
||||
'ERP_LOGIN_FAILED',
|
||||
@@ -91,6 +185,7 @@ export function registerExtractorHandlers(): void {
|
||||
)
|
||||
}
|
||||
log.info('Login successful')
|
||||
sendLog(sender, 'success', 'ERP 登录成功')
|
||||
|
||||
// Create extractor service and run extraction with resolved order numbers
|
||||
const extractor = new ExtractorService(authService)
|
||||
@@ -98,7 +193,14 @@ export function registerExtractorHandlers(): void {
|
||||
|
||||
const modifiedInput: ExtractorInput = {
|
||||
...input,
|
||||
orderNumbers: validOrderNumbers
|
||||
orderNumbers: validOrderNumbers,
|
||||
onProgress: (message, progress, extra) => {
|
||||
sendProgress(sender, message, progress, extra)
|
||||
sendLog(sender, 'info', message)
|
||||
},
|
||||
onLog: (level, message) => {
|
||||
sendLog(sender, level, message)
|
||||
}
|
||||
}
|
||||
|
||||
const result = await extractor.extract(modifiedInput)
|
||||
@@ -113,6 +215,37 @@ export function registerExtractorHandlers(): void {
|
||||
errorCount: result.errors.length
|
||||
})
|
||||
|
||||
// Log detailed error information if any errors occurred
|
||||
if (result.errors.length > 0) {
|
||||
log.warn('Extraction errors occurred', { errors: result.errors })
|
||||
result.errors.forEach((err, index) => {
|
||||
log.error(`Error ${index + 1}/${result.errors.length}: ${err}`)
|
||||
})
|
||||
}
|
||||
|
||||
// Audit log: EXTRACT (non-blocking)
|
||||
const os = await import('os')
|
||||
const currentUser = SessionManager.getInstance().getUserInfo()
|
||||
if (currentUser) {
|
||||
const status: 'success' | 'failure' | 'partial' =
|
||||
result.errors.length > 0 && result.recordCount > 0
|
||||
? 'partial'
|
||||
: result.errors.length > 0
|
||||
? 'failure'
|
||||
: 'success'
|
||||
logAudit('EXTRACT', String(currentUser.id), {
|
||||
username: currentUser.username,
|
||||
computerName: os.hostname(),
|
||||
resource: 'MATERIAL_PLAN',
|
||||
status,
|
||||
metadata: {
|
||||
orderCount: validOrderNumbers.length,
|
||||
recordCount: result.recordCount,
|
||||
errorCount: result.errors.length
|
||||
}
|
||||
}).catch((err) => log.warn('Failed to write audit log', { err }))
|
||||
}
|
||||
|
||||
return result
|
||||
} finally {
|
||||
// Clean up: close browser
|
||||
|
||||
@@ -1,64 +1,99 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { app, ipcMain, shell } from 'electron'
|
||||
import * as fs from 'fs/promises'
|
||||
import * as path from 'path'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { ValidationError } from '../types/errors'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
|
||||
const log = createLogger('FileHandler')
|
||||
|
||||
/**
|
||||
* Register IPC handlers for file operations
|
||||
*/
|
||||
export function registerFileHandlers(): void {
|
||||
// Read file content
|
||||
ipcMain.handle('file:read', async (_event, filePath: string): Promise<string> => {
|
||||
try {
|
||||
log.debug('Reading file', { filePath })
|
||||
return await fs.readFile(filePath, 'utf-8')
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to read file'
|
||||
log.error('Failed to read file', { filePath, error: message })
|
||||
throw new Error(message)
|
||||
}
|
||||
})
|
||||
function getAllowedRoots(): string[] {
|
||||
return [path.resolve(app.getAppPath()), path.resolve(app.getPath('userData'))]
|
||||
}
|
||||
|
||||
// Write content to file
|
||||
ipcMain.handle('file:write', async (_event, filePath: string, content: string): Promise<void> => {
|
||||
try {
|
||||
log.debug('Writing file', { filePath })
|
||||
// Ensure directory exists
|
||||
const dir = path.dirname(filePath)
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
await fs.writeFile(filePath, content, 'utf-8')
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to write file'
|
||||
log.error('Failed to write file', { filePath, error: message })
|
||||
throw new Error(message)
|
||||
}
|
||||
})
|
||||
|
||||
// Check if file exists
|
||||
ipcMain.handle('file:exists', async (_event, filePath: string): Promise<boolean> => {
|
||||
try {
|
||||
await fs.access(filePath)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
// List files in directory
|
||||
ipcMain.handle('file:list', async (_event, dirPath: string): Promise<string[]> => {
|
||||
try {
|
||||
log.debug('Listing directory', { dirPath })
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true })
|
||||
return entries
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => entry.name)
|
||||
.sort()
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to list directory'
|
||||
log.error('Failed to list directory', { dirPath, error: message })
|
||||
throw new Error(message)
|
||||
}
|
||||
export function isPathWithinAllowedRoots(inputPath: string, roots: string[]): boolean {
|
||||
const normalized = path.resolve(inputPath)
|
||||
return roots.some((root) => {
|
||||
const rel = path.relative(root, normalized)
|
||||
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
|
||||
})
|
||||
}
|
||||
|
||||
function normalizeAndValidatePath(inputPath: string): string {
|
||||
const normalized = path.resolve(inputPath)
|
||||
const isAllowed = isPathWithinAllowedRoots(normalized, getAllowedRoots())
|
||||
if (!isAllowed) {
|
||||
throw new ValidationError('Path is outside allowed roots', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function registerFileHandlers(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.FILE_READ,
|
||||
async (_event, filePath: string): Promise<IpcResult<string>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const safePath = normalizeAndValidatePath(filePath)
|
||||
log.debug('Reading file', { filePath: safePath })
|
||||
return await fs.readFile(safePath, 'utf-8')
|
||||
}, 'file:read')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.FILE_WRITE,
|
||||
async (_event, filePath: string, content: string): Promise<IpcResult<void>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const safePath = normalizeAndValidatePath(filePath)
|
||||
log.debug('Writing file', { filePath: safePath })
|
||||
const dir = path.dirname(safePath)
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
await fs.writeFile(safePath, content, 'utf-8')
|
||||
}, 'file:write')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.FILE_EXISTS,
|
||||
async (_event, filePath: string): Promise<IpcResult<boolean>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const safePath = normalizeAndValidatePath(filePath)
|
||||
try {
|
||||
await fs.access(safePath)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}, 'file:exists')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.FILE_LIST,
|
||||
async (_event, dirPath: string): Promise<IpcResult<string[]>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const safePath = normalizeAndValidatePath(dirPath)
|
||||
log.debug('Listing directory', { dirPath: safePath })
|
||||
const entries = await fs.readdir(safePath, { withFileTypes: true })
|
||||
return entries
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => entry.name)
|
||||
.sort()
|
||||
}, 'file:list')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.FILE_OPEN_PATH,
|
||||
async (_event, filePath: string): Promise<IpcResult<void>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const safePath = normalizeAndValidatePath(filePath)
|
||||
log.debug('Opening path in explorer', { filePath: safePath })
|
||||
await fs.access(safePath)
|
||||
await shell.openPath(safePath)
|
||||
}, 'file:openPath')
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,11 @@ import { registerAuthHandlers } from './auth-handler'
|
||||
import { registerValidationHandlers } from './validation-handler'
|
||||
import { registerSettingsHandlers } from './settings-handler'
|
||||
import { registerMaterialTypeHandlers } from './material-type-handler'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { registerUserErpConfigHandlers } from './user-erp-config-handler'
|
||||
import { registerLoggerHandlers } from './logger-handler'
|
||||
import { registerReportHandlers } from './report-handler'
|
||||
import { createLogger, logError } from '../services/logger'
|
||||
import { serializeError, sanitizeError } from '../services/logger/error-utils'
|
||||
import { getErrorMessage, getErrorCode, isBaseError } from '../types/errors'
|
||||
|
||||
const log = createLogger('IPC')
|
||||
@@ -27,8 +31,17 @@ export interface IpcResult<T = unknown> {
|
||||
code?: string
|
||||
}
|
||||
|
||||
export function ok<T>(data: T): IpcResult<T> {
|
||||
return { success: true, data }
|
||||
}
|
||||
|
||||
export function fail<T = unknown>(error: string, code?: string): IpcResult<T> {
|
||||
return { success: false, error, code }
|
||||
}
|
||||
|
||||
/**
|
||||
* Higher-order function to wrap IPC handlers with consistent error handling
|
||||
* Enhanced to capture full error context including stack traces
|
||||
* @param handler - The async handler function to wrap
|
||||
* @param context - The context name for logging
|
||||
* @returns A wrapped handler that returns IpcResult
|
||||
@@ -38,26 +51,40 @@ export function withErrorHandling<T>(
|
||||
context: string
|
||||
): Promise<IpcResult<T>> {
|
||||
return handler()
|
||||
.then((data) => {
|
||||
.then((data): IpcResult<T> => {
|
||||
log.debug(`[${context}] Handler completed successfully`)
|
||||
return { success: true, data }
|
||||
return ok(data)
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
const message = getErrorMessage(error)
|
||||
const code = getErrorCode(error)
|
||||
|
||||
if (isBaseError(error)) {
|
||||
log.error(`[${context}] ${error.name}: ${message}`, { code, cause: error.cause?.message })
|
||||
// Serialize error with full details
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
sanitizeError(serializeError(error))
|
||||
} else {
|
||||
log.error(`[${context}] Error: ${message}`, { code })
|
||||
serializeError(error)
|
||||
}
|
||||
|
||||
if (isBaseError(error)) {
|
||||
logError(log, `[${context}] ${error.name}`, error, {
|
||||
code,
|
||||
cause: (error as any).cause?.message,
|
||||
handler: context
|
||||
})
|
||||
} else {
|
||||
logError(log, `[${context}] Error`, error, {
|
||||
code,
|
||||
handler: context
|
||||
})
|
||||
}
|
||||
|
||||
// Include stack trace in development
|
||||
if (process.env.NODE_ENV !== 'production' && error instanceof Error) {
|
||||
log.debug(`[${context}] Stack trace:`, { stack: error.stack })
|
||||
log.debug(`[${context}] Stack trace: ${error.stack}`)
|
||||
}
|
||||
|
||||
return { success: false, error: message, code }
|
||||
return fail<T>(message, code)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -75,5 +102,8 @@ export function registerIpcHandlers(): void {
|
||||
registerValidationHandlers()
|
||||
registerSettingsHandlers()
|
||||
registerMaterialTypeHandlers()
|
||||
registerUserErpConfigHandlers()
|
||||
registerLoggerHandlers()
|
||||
registerReportHandlers()
|
||||
log.info('All IPC handlers registered')
|
||||
}
|
||||
|
||||
229
src/main/ipc/logger-handler.ts
Normal file
229
src/main/ipc/logger-handler.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* IPC Logger Handler with Batching
|
||||
* Receives logs from renderer process and forwards to Winston
|
||||
*
|
||||
* Features:
|
||||
* - 100ms debounce for batch processing
|
||||
* - Maximum 50 messages per batch
|
||||
* - Circuit breaker: discards new logs when buffer > 500
|
||||
* - Error-level logs bypass circuit breaker
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { IPC_CHANNELS, type LogLevel } from '../../shared/ipc-channels'
|
||||
|
||||
const log = createLogger('LoggerHandler')
|
||||
|
||||
/**
|
||||
* Log entry from renderer process
|
||||
*/
|
||||
interface LogEntry {
|
||||
level: LogLevel
|
||||
message: string
|
||||
context?: Record<string, unknown>
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch processing configuration
|
||||
*/
|
||||
const BATCH_CONFIG = {
|
||||
DEBOUNCE_MS: 100,
|
||||
MAX_BATCH_SIZE: 50,
|
||||
CIRCUIT_BREAKER_THRESHOLD: 500
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Logger handler state
|
||||
*/
|
||||
class LoggerHandlerState {
|
||||
private buffer: LogEntry[] = []
|
||||
private debounceTimer: NodeJS.Timeout | null = null
|
||||
private discardedCount = 0
|
||||
|
||||
/**
|
||||
* Add log entry to buffer
|
||||
* @param entry - Log entry to buffer
|
||||
* @returns true if entry was buffered, false if discarded
|
||||
*/
|
||||
addEntry(entry: LogEntry): boolean {
|
||||
// Error-level logs always bypass circuit breaker
|
||||
if (entry.level === 'error') {
|
||||
this.buffer.push(entry)
|
||||
this.flushIfNeeded()
|
||||
return true
|
||||
}
|
||||
|
||||
// Circuit breaker: discard non-error logs when buffer is too large
|
||||
if (this.buffer.length >= BATCH_CONFIG.CIRCUIT_BREAKER_THRESHOLD) {
|
||||
this.discardedCount++
|
||||
|
||||
// Log warning about discarded logs periodically (every 100 discarded)
|
||||
if (this.discardedCount % 100 === 0) {
|
||||
log.warn('Circuit breaker active: discarded logs', {
|
||||
discardedCount: this.discardedCount,
|
||||
bufferSize: this.buffer.length
|
||||
})
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
this.buffer.push(entry)
|
||||
this.flushIfNeeded()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush buffer if it reaches max batch size
|
||||
*/
|
||||
private flushIfNeeded(): void {
|
||||
if (this.buffer.length >= BATCH_CONFIG.MAX_BATCH_SIZE) {
|
||||
this.flush()
|
||||
} else if (!this.debounceTimer) {
|
||||
// Start debounce timer if not already running
|
||||
this.debounceTimer = setTimeout(() => {
|
||||
this.flush()
|
||||
}, BATCH_CONFIG.DEBOUNCE_MS)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all buffered logs to Winston
|
||||
*/
|
||||
flush(): void {
|
||||
if (this.debounceTimer) {
|
||||
clearTimeout(this.debounceTimer)
|
||||
this.debounceTimer = null
|
||||
}
|
||||
|
||||
if (this.buffer.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create a copy of the buffer and clear it
|
||||
const batch = [...this.buffer]
|
||||
this.buffer = []
|
||||
|
||||
// Process batch asynchronously (non-blocking)
|
||||
setImmediate(() => {
|
||||
this.processBatch(batch)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a batch of log entries
|
||||
* @param batch - Array of log entries to process
|
||||
*/
|
||||
private processBatch(batch: LogEntry[]): void {
|
||||
try {
|
||||
for (const entry of batch) {
|
||||
this.forwardToWinston(entry)
|
||||
}
|
||||
} catch (error) {
|
||||
// If batch processing fails, log the error but don't rethrow
|
||||
// This ensures logging failures don't crash the app
|
||||
log.error('Failed to process log batch', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
batchSize: batch.length
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward a single log entry to Winston logger
|
||||
* @param entry - Log entry to forward
|
||||
*/
|
||||
private forwardToWinston(entry: LogEntry): void {
|
||||
const context = (entry.context?.component as string) || 'renderer'
|
||||
const childLogger = log.child({
|
||||
source: 'renderer',
|
||||
component: context
|
||||
})
|
||||
|
||||
const message = entry.context?.message
|
||||
? `[${entry.context.message}] ${entry.message}`
|
||||
: entry.message
|
||||
|
||||
switch (entry.level) {
|
||||
case 'debug':
|
||||
childLogger.debug(message, entry.context)
|
||||
break
|
||||
case 'warn':
|
||||
childLogger.warn(message, entry.context)
|
||||
break
|
||||
case 'error':
|
||||
childLogger.error(message, entry.context)
|
||||
break
|
||||
case 'info':
|
||||
default:
|
||||
childLogger.info(message, entry.context)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current buffer size (for testing/debugging)
|
||||
*/
|
||||
getBufferSize(): number {
|
||||
return this.buffer.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Get discarded log count (for testing/debugging)
|
||||
*/
|
||||
getDiscardedCount(): number {
|
||||
return this.discardedCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset state (for testing)
|
||||
*/
|
||||
reset(): void {
|
||||
if (this.debounceTimer) {
|
||||
clearTimeout(this.debounceTimer)
|
||||
this.debounceTimer = null
|
||||
}
|
||||
this.buffer = []
|
||||
this.discardedCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton state instance
|
||||
const state = new LoggerHandlerState()
|
||||
|
||||
/**
|
||||
* Register IPC handlers for logger
|
||||
*/
|
||||
export function registerLoggerHandlers(): void {
|
||||
// Use ipcMain.on with send() - fire-and-forget, non-blocking
|
||||
ipcMain.on(IPC_CHANNELS.LOGGER_FORWARD, (_event, entry: LogEntry) => {
|
||||
// Validate entry
|
||||
if (!entry || typeof entry.level !== 'string' || typeof entry.message !== 'string') {
|
||||
log.warn('Received invalid log entry', { entry })
|
||||
return
|
||||
}
|
||||
|
||||
// Add to buffer for batch processing
|
||||
const buffered = state.addEntry(entry)
|
||||
|
||||
if (!buffered && process.env.NODE_ENV !== 'production') {
|
||||
// In development, log when entries are discarded
|
||||
log.debug('Log entry discarded due to circuit breaker', {
|
||||
level: entry.level,
|
||||
message: entry.message
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
log.info('Logger IPC handler registered', {
|
||||
channel: IPC_CHANNELS.LOGGER_FORWARD,
|
||||
debounceMs: BATCH_CONFIG.DEBOUNCE_MS,
|
||||
maxBatchSize: BATCH_CONFIG.MAX_BATCH_SIZE,
|
||||
circuitBreakerThreshold: BATCH_CONFIG.CIRCUIT_BREAKER_THRESHOLD
|
||||
})
|
||||
}
|
||||
|
||||
// Export for testing
|
||||
export { state }
|
||||
@@ -17,6 +17,9 @@ import {
|
||||
type MaterialTypeBatchRequest
|
||||
} from '../services/database/materials-type-to-be-deleted-dao'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { ValidationError } from '../types/errors'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
|
||||
const log = createLogger('MaterialTypeHandler')
|
||||
|
||||
@@ -30,16 +33,12 @@ export function registerMaterialTypeHandlers(): void {
|
||||
* Get all material type records
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materialType:getAll',
|
||||
async (): Promise<{ success: boolean; data?: MaterialTypeRecord[]; error?: string }> => {
|
||||
try {
|
||||
IPC_CHANNELS.MATERIAL_TYPE_GET_ALL,
|
||||
async (): Promise<IpcResult<MaterialTypeRecord[]>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const records = await dao.getAllMaterials()
|
||||
return { success: true, data: records }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Get all material types error', { error: message })
|
||||
return { success: false, error: message }
|
||||
}
|
||||
return records
|
||||
}, 'materialType:getAll')
|
||||
}
|
||||
)
|
||||
|
||||
@@ -47,19 +46,12 @@ export function registerMaterialTypeHandlers(): void {
|
||||
* Get material types by manager
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materialType:getByManager',
|
||||
async (
|
||||
_event,
|
||||
managerName: string
|
||||
): Promise<{ success: boolean; data?: MaterialTypeRecord[]; error?: string }> => {
|
||||
try {
|
||||
IPC_CHANNELS.MATERIAL_TYPE_GET_BY_MANAGER,
|
||||
async (_event, managerName: string): Promise<IpcResult<MaterialTypeRecord[]>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const records = await dao.getMaterialsByManager(managerName)
|
||||
return { success: true, data: records }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Get material types by manager error', { error: message })
|
||||
return { success: false, error: message }
|
||||
}
|
||||
return records
|
||||
}, 'materialType:getByManager')
|
||||
}
|
||||
)
|
||||
|
||||
@@ -67,16 +59,12 @@ export function registerMaterialTypeHandlers(): void {
|
||||
* Get list of managers
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materialType:getManagers',
|
||||
async (): Promise<{ success: boolean; data?: string[]; error?: string }> => {
|
||||
try {
|
||||
IPC_CHANNELS.MATERIAL_TYPE_GET_MANAGERS,
|
||||
async (): Promise<IpcResult<string[]>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const managers = await dao.getManagers()
|
||||
return { success: true, data: managers }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Get managers error', { error: message })
|
||||
return { success: false, error: message }
|
||||
}
|
||||
return managers
|
||||
}, 'materialType:getManagers')
|
||||
}
|
||||
)
|
||||
|
||||
@@ -84,22 +72,18 @@ export function registerMaterialTypeHandlers(): void {
|
||||
* Upsert (insert or update) a material type record
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materialType:upsert',
|
||||
IPC_CHANNELS.MATERIAL_TYPE_UPSERT,
|
||||
async (
|
||||
_event,
|
||||
{ materialName, managerName }: { materialName: string; managerName: string }
|
||||
): Promise<{ success: boolean; error?: string }> => {
|
||||
try {
|
||||
): Promise<IpcResult<{ updated: boolean }>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const result = await dao.upsertMaterial(materialName, managerName)
|
||||
if (!result) {
|
||||
return { success: false, error: 'Failed to upsert material type' }
|
||||
throw new ValidationError('Failed to upsert material type', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Upsert material type error', { error: message })
|
||||
return { success: false, error: message }
|
||||
}
|
||||
return { updated: true }
|
||||
}, 'materialType:upsert')
|
||||
}
|
||||
)
|
||||
|
||||
@@ -107,22 +91,18 @@ export function registerMaterialTypeHandlers(): void {
|
||||
* Delete a material type record
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materialType:delete',
|
||||
IPC_CHANNELS.MATERIAL_TYPE_DELETE,
|
||||
async (
|
||||
_event,
|
||||
{ materialName, managerName }: { materialName: string; managerName: string }
|
||||
): Promise<{ success: boolean; error?: string }> => {
|
||||
try {
|
||||
): Promise<IpcResult<{ deleted: boolean }>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const result = await dao.deleteMaterial(materialName, managerName)
|
||||
if (!result) {
|
||||
return { success: false, error: 'Failed to delete material type' }
|
||||
throw new ValidationError('Failed to delete material type', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Delete material type error', { error: message })
|
||||
return { success: false, error: message }
|
||||
}
|
||||
return { deleted: true }
|
||||
}, 'materialType:delete')
|
||||
}
|
||||
)
|
||||
|
||||
@@ -130,23 +110,15 @@ export function registerMaterialTypeHandlers(): void {
|
||||
* Batch operation for material types (insert, update, delete)
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materialType:upsertBatch',
|
||||
IPC_CHANNELS.MATERIAL_TYPE_UPSERT_BATCH,
|
||||
async (
|
||||
_event,
|
||||
request: MaterialTypeBatchRequest
|
||||
): Promise<{
|
||||
success: boolean
|
||||
stats?: { total: number; success: number; failed: number }
|
||||
error?: string
|
||||
}> => {
|
||||
try {
|
||||
): Promise<IpcResult<{ stats: { total: number; success: number; failed: number } }>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const stats = await dao.upsertBatch(request)
|
||||
return { success: true, stats }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Batch upsert material types error', { error: message })
|
||||
return { success: false, error: message }
|
||||
}
|
||||
return { stats }
|
||||
}, 'materialType:upsertBatch')
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
183
src/main/ipc/report-handler.ts
Normal file
183
src/main/ipc/report-handler.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { ConfigManager } from '../services/config/config-manager'
|
||||
import { RustfsService } from '../services/rustfs'
|
||||
import { ListObjectsV2Command, S3Client } from '@aws-sdk/client-s3'
|
||||
|
||||
const log = createLogger('ReportHandler')
|
||||
|
||||
export interface ReportMetadata {
|
||||
key: string
|
||||
filename: string
|
||||
username: string
|
||||
lastModified?: Date
|
||||
size?: number
|
||||
}
|
||||
|
||||
function getRustfsService(): RustfsService | null {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
|
||||
if (config.rustfs?.enabled && config.rustfs.endpoint) {
|
||||
return new RustfsService({ config: config.rustfs })
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function registerReportHandlers(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.REPORT_LIST_ALL,
|
||||
async (): Promise<IpcResult<ReportMetadata[]>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const rustfs = getRustfsService()
|
||||
if (!rustfs) {
|
||||
throw new Error('RustFS is not configured or enabled')
|
||||
}
|
||||
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
|
||||
// Create a direct S3Client since RustfsService doesn't expose listObjects natively easily
|
||||
const client = new S3Client({
|
||||
region: config.rustfs?.region || 'us-east-1',
|
||||
endpoint: config.rustfs?.endpoint || '',
|
||||
credentials: {
|
||||
accessKeyId: config.rustfs?.accessKey || '',
|
||||
secretAccessKey: config.rustfs?.secretKey || ''
|
||||
},
|
||||
forcePathStyle: true
|
||||
})
|
||||
|
||||
log.info('Fetching all reports from RustFS')
|
||||
const input = {
|
||||
Bucket: config.rustfs?.bucket || '',
|
||||
Prefix: 'reports/cleaner/'
|
||||
}
|
||||
|
||||
const command = new ListObjectsV2Command(input)
|
||||
const response = await client.send(command)
|
||||
|
||||
const reports: ReportMetadata[] = []
|
||||
|
||||
if (response.Contents) {
|
||||
for (const item of response.Contents) {
|
||||
if (item.Key && item.Key.endsWith('.md')) {
|
||||
// reports/cleaner/{username}/{filename}
|
||||
const parts = item.Key.split('/')
|
||||
if (parts.length >= 4) {
|
||||
const username = parts[2]
|
||||
const filename = parts.slice(3).join('/')
|
||||
reports.push({
|
||||
key: item.Key,
|
||||
filename,
|
||||
username,
|
||||
lastModified: item.LastModified,
|
||||
size: item.Size
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by lastModified descending
|
||||
reports.sort((a, b) => {
|
||||
if (a.lastModified && b.lastModified) {
|
||||
return b.lastModified.getTime() - a.lastModified.getTime()
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
return reports
|
||||
}, 'report:listAll')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.REPORT_LIST_BY_USER,
|
||||
async (_event, username: string): Promise<IpcResult<ReportMetadata[]>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const rustfs = getRustfsService()
|
||||
if (!rustfs) {
|
||||
throw new Error('RustFS is not configured or enabled')
|
||||
}
|
||||
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
|
||||
const client = new S3Client({
|
||||
region: config.rustfs?.region || 'us-east-1',
|
||||
endpoint: config.rustfs?.endpoint || '',
|
||||
credentials: {
|
||||
accessKeyId: config.rustfs?.accessKey || '',
|
||||
secretAccessKey: config.rustfs?.secretKey || ''
|
||||
},
|
||||
forcePathStyle: true
|
||||
})
|
||||
|
||||
log.info('Fetching reports from RustFS for user', { username })
|
||||
const input = {
|
||||
Bucket: config.rustfs?.bucket || '',
|
||||
Prefix: `reports/cleaner/${username}/`
|
||||
}
|
||||
|
||||
const command = new ListObjectsV2Command(input)
|
||||
const response = await client.send(command)
|
||||
|
||||
const reports: ReportMetadata[] = []
|
||||
|
||||
if (response.Contents) {
|
||||
for (const item of response.Contents) {
|
||||
if (item.Key && item.Key.endsWith('.md')) {
|
||||
const parts = item.Key.split('/')
|
||||
if (parts.length >= 4) {
|
||||
const itemUsername = parts[2]
|
||||
const filename = parts.slice(3).join('/')
|
||||
reports.push({
|
||||
key: item.Key,
|
||||
filename,
|
||||
username: itemUsername,
|
||||
lastModified: item.LastModified,
|
||||
size: item.Size
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by lastModified descending
|
||||
reports.sort((a, b) => {
|
||||
if (a.lastModified && b.lastModified) {
|
||||
return b.lastModified.getTime() - a.lastModified.getTime()
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
return reports
|
||||
}, 'report:listByUser')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.REPORT_DOWNLOAD,
|
||||
async (_event, key: string): Promise<IpcResult<string>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const rustfs = getRustfsService()
|
||||
if (!rustfs) {
|
||||
throw new Error('RustFS is not configured or enabled')
|
||||
}
|
||||
|
||||
log.info('Downloading report from RustFS', { key })
|
||||
const result = await rustfs.downloadFile(key)
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to download report')
|
||||
}
|
||||
|
||||
// Convert buffer to string
|
||||
return result.content.toString('utf-8')
|
||||
}, 'report:download')
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import { create, type IDatabaseService } from '../services/database'
|
||||
import { OrderNumberResolver } from '../services/erp/order-resolver'
|
||||
import { createLogger } from '../services/logger'
|
||||
import type { OrderMapping, ResolutionStats } from '../services/erp/order-resolver'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
|
||||
const log = createLogger('ResolverHandler')
|
||||
|
||||
@@ -49,11 +51,11 @@ export function registerResolverHandlers(): void {
|
||||
* Converts productionIDs and 生产订单号 to production order numbers
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'resolver:resolve',
|
||||
async (_event, input: ResolverInput): Promise<ResolverResponse> => {
|
||||
IPC_CHANNELS.RESOLVER_RESOLVE,
|
||||
async (_event, input: ResolverInput): Promise<IpcResult<ResolverResponse>> => {
|
||||
let dbService: IDatabaseService | null = null
|
||||
|
||||
try {
|
||||
return withErrorHandling(async () => {
|
||||
// Create database service using factory
|
||||
log.info('Connecting to database for resolution', { inputCount: input.inputs.length })
|
||||
dbService = await create()
|
||||
@@ -80,14 +82,7 @@ export function registerResolverHandlers(): void {
|
||||
warnings,
|
||||
stats
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Resolution failed', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
error: `解析失败:${message}`
|
||||
}
|
||||
} finally {
|
||||
}, 'resolver:resolve').finally(async () => {
|
||||
// Clean up database connection
|
||||
if (dbService) {
|
||||
try {
|
||||
@@ -99,7 +94,7 @@ export function registerResolverHandlers(): void {
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
@@ -107,16 +102,14 @@ export function registerResolverHandlers(): void {
|
||||
* Validate input format only (without database lookup)
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'resolver:validateFormat',
|
||||
IPC_CHANNELS.RESOLVER_VALIDATE_FORMAT,
|
||||
async (
|
||||
_event,
|
||||
inputs: string[]
|
||||
): Promise<{
|
||||
success: boolean
|
||||
results?: Array<{ input: string; type: 'productionId' | 'orderNumber' | 'unknown' }>
|
||||
error?: string
|
||||
}> => {
|
||||
try {
|
||||
): Promise<
|
||||
IpcResult<Array<{ input: string; type: 'productionId' | 'orderNumber' | 'unknown' }>>
|
||||
> => {
|
||||
return withErrorHandling(async () => {
|
||||
// Create a mock resolver without database connection
|
||||
const resolver = new OrderNumberResolver({
|
||||
isConnected: () => false,
|
||||
@@ -130,15 +123,8 @@ export function registerResolverHandlers(): void {
|
||||
|
||||
log.debug('Format validation completed', { inputCount: inputs.length })
|
||||
|
||||
return { success: true, results }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Format validation failed', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
error: `验证失败:${message}`
|
||||
}
|
||||
}
|
||||
return results
|
||||
}, 'resolver:validateFormat')
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,241 +1,146 @@
|
||||
/**
|
||||
* Settings IPC Handler
|
||||
*
|
||||
* Provides IPC handlers for settings management:
|
||||
* - Get/set settings
|
||||
* - Reset to defaults
|
||||
* - Test ERP connection
|
||||
* - Test database connection
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron'
|
||||
import { ConfigManager } from '../services/config/config-manager'
|
||||
import { SessionManager } from '../services/user/session-manager'
|
||||
import { ErpAuthService } from '../services/erp/erp-auth'
|
||||
import { UserErpConfigService } from '../services/user/user-erp-config-service'
|
||||
import { MySqlService } from '../services/database/mysql'
|
||||
import { SqlServerService } from '../services/database/sql-server'
|
||||
import { createLogger } from '../services/logger'
|
||||
import type {
|
||||
SettingsData,
|
||||
UserType,
|
||||
ConnectionTestResult,
|
||||
SaveSettingsResult
|
||||
} from '../types/settings.types'
|
||||
import { logAudit } from '../services/logger/audit-logger'
|
||||
import type { UserType, ConnectionTestResult, SaveSettingsResult } from '../types/settings.types'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { ValidationError } from '../types/errors'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
import type { CleanerConfig } from '../types/config.schema'
|
||||
|
||||
const log = createLogger('SettingsHandler')
|
||||
|
||||
/**
|
||||
* Filter settings by user type
|
||||
* Admin users get all settings, User users get limited settings
|
||||
*/
|
||||
function filterSettingsByUserType(settings: SettingsData, userType: UserType): SettingsData {
|
||||
if (userType === 'Admin') {
|
||||
return settings // Return all settings for Admin
|
||||
}
|
||||
|
||||
// User users get limited settings
|
||||
return {
|
||||
erp: {
|
||||
username: settings.erp.username,
|
||||
password: settings.erp.password,
|
||||
headless: settings.erp.headless,
|
||||
url: settings.erp.url,
|
||||
ignoreHttpsErrors: settings.erp.ignoreHttpsErrors,
|
||||
autoCloseBrowser: settings.erp.autoCloseBrowser
|
||||
},
|
||||
paths: settings.paths,
|
||||
execution: settings.execution,
|
||||
// Include minimal required fields for other sections
|
||||
database: settings.database,
|
||||
extraction: settings.extraction,
|
||||
validation: settings.validation,
|
||||
ui: settings.ui
|
||||
type ErpSettingsPayload = {
|
||||
erp?: {
|
||||
username?: string
|
||||
password?: string
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register IPC handlers for settings management
|
||||
*/
|
||||
export function registerSettingsHandlers(): void {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const sessionManager = SessionManager.getInstance()
|
||||
const erpConfigService = UserErpConfigService.getInstance()
|
||||
|
||||
/**
|
||||
* Get current user type
|
||||
*/
|
||||
ipcMain.handle('settings:getUserType', async (): Promise<UserType> => {
|
||||
return (sessionManager.getUserType() as UserType) || 'Guest'
|
||||
ipcMain.handle(IPC_CHANNELS.SETTINGS_GET_USER_TYPE, async (): Promise<IpcResult<UserType>> => {
|
||||
return withErrorHandling(
|
||||
async () => (sessionManager.getUserType() as UserType) || 'Guest',
|
||||
'settings:getUserType'
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* Get settings (filtered by user type)
|
||||
*/
|
||||
ipcMain.handle('settings:getSettings', async (): Promise<SettingsData> => {
|
||||
const userType = (sessionManager.getUserType() as UserType) || 'Guest'
|
||||
log.debug('Getting settings', { userType })
|
||||
const settings = configManager.getAllSettings()
|
||||
return filterSettingsByUserType(settings, userType)
|
||||
})
|
||||
|
||||
/**
|
||||
* Save settings (updated to use partial save)
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'settings:saveSettings',
|
||||
async (_event, settings: Partial<SettingsData>): Promise<SaveSettingsResult> => {
|
||||
try {
|
||||
log.info('Saving settings', {
|
||||
sections: Object.keys(settings)
|
||||
})
|
||||
|
||||
// Use partial save method
|
||||
const result = await configManager.savePartialSettings(settings)
|
||||
|
||||
if (result.success) {
|
||||
log.info('Settings saved successfully')
|
||||
return { success: true }
|
||||
} else {
|
||||
log.warn('Failed to save settings', {
|
||||
error: result.error
|
||||
})
|
||||
return {
|
||||
success: false,
|
||||
error: result.error || '保存设置失败'
|
||||
IPC_CHANNELS.SETTINGS_GET_SETTINGS,
|
||||
async (): Promise<IpcResult<{ erp: { username: string; password: string } }>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const userErpConfig = await erpConfigService.getCurrentUserErpConfig()
|
||||
return {
|
||||
erp: {
|
||||
username: userErpConfig?.username || '',
|
||||
password: userErpConfig?.password || ''
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Error saving settings', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
error: `保存设置失败:${message}`
|
||||
}
|
||||
}
|
||||
}, 'settings:getSettings')
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* Reset to default settings (Admin only)
|
||||
*/
|
||||
ipcMain.handle('settings:resetDefaults', async (): Promise<SaveSettingsResult> => {
|
||||
try {
|
||||
const userType = sessionManager.getUserType()
|
||||
if (userType !== 'Admin') {
|
||||
log.warn('Non-admin user attempted to reset defaults', { userType })
|
||||
return { success: false, error: '只有管理员可以恢复默认设置' }
|
||||
}
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.SETTINGS_SAVE_SETTINGS,
|
||||
async (_event, settings: ErpSettingsPayload): Promise<IpcResult<SaveSettingsResult>> => {
|
||||
return withErrorHandling(async () => {
|
||||
if (settings.erp) {
|
||||
const currentUser = sessionManager.getUserInfo()
|
||||
if (!currentUser) {
|
||||
throw new ValidationError('未找到当前用户', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
|
||||
await erpConfigService.updateCurrentUserErpConfig({
|
||||
username: settings.erp.username || '',
|
||||
password: settings.erp.password || ''
|
||||
})
|
||||
|
||||
// Audit log: SETTINGS_CHANGE (non-blocking)
|
||||
const os = await import('os')
|
||||
logAudit('SETTINGS_CHANGE', String(currentUser.id), {
|
||||
username: currentUser.username,
|
||||
computerName: os.hostname(),
|
||||
resource: 'ERP_CONFIG',
|
||||
status: 'success',
|
||||
metadata: { changeType: 'erp_credentials', usernameChanged: !!settings.erp.username }
|
||||
}).catch((err) => log.warn('Failed to write audit log', { err }))
|
||||
}
|
||||
|
||||
log.info('Resetting settings to defaults')
|
||||
configManager.resetToDefaults()
|
||||
const success = await configManager.save()
|
||||
if (success) {
|
||||
log.info('Settings reset to defaults successfully')
|
||||
return { success: true }
|
||||
} else {
|
||||
log.warn('Failed to reset settings to defaults')
|
||||
return { success: false, error: '恢复默认设置失败' }
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Error resetting settings', { error: message })
|
||||
return { success: false, error: `恢复默认设置失败:${message}` }
|
||||
}, 'settings:saveSettings')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Test ERP connection
|
||||
*/
|
||||
ipcMain.handle('settings:testErpConnection', async (): Promise<ConnectionTestResult> => {
|
||||
try {
|
||||
log.info('Testing ERP connection')
|
||||
const settings = configManager.getAllSettings()
|
||||
const erpConfig = settings.erp
|
||||
|
||||
if (!erpConfig.url || !erpConfig.username || !erpConfig.password) {
|
||||
log.warn('ERP connection test failed - missing configuration')
|
||||
return {
|
||||
success: false,
|
||||
message: '请先配置 ERP URL、用户名和密码'
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.SETTINGS_RESET_DEFAULTS,
|
||||
async (): Promise<IpcResult<SaveSettingsResult>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const userType = sessionManager.getUserType()
|
||||
if (userType !== 'Admin') {
|
||||
throw new ValidationError('只有管理员可以恢复默认设置', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
}
|
||||
|
||||
// Create ERP auth service and try to login
|
||||
const erpAuthService = new ErpAuthService(erpConfig)
|
||||
const success = await configManager.resetToDefaults()
|
||||
if (!success) {
|
||||
throw new ValidationError('恢复默认设置失败', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
|
||||
try {
|
||||
await erpAuthService.login()
|
||||
// Login successful, close browser
|
||||
await erpAuthService.close()
|
||||
log.info('ERP connection test successful')
|
||||
return {
|
||||
success: true,
|
||||
message: 'ERP 连接测试成功!'
|
||||
}
|
||||
} catch (loginError) {
|
||||
const errorMessage = loginError instanceof Error ? loginError.message : '登录失败'
|
||||
log.error('ERP login failed', { error: errorMessage })
|
||||
return {
|
||||
success: false,
|
||||
message: `ERP 连接测试失败:${errorMessage}`
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('ERP connection test error', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
message: `ERP 连接测试失败:${message}`
|
||||
}
|
||||
return { success: true }
|
||||
}, 'settings:resetDefaults')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Test database connection
|
||||
*/
|
||||
ipcMain.handle('settings:testDbConnection', async (): Promise<ConnectionTestResult> => {
|
||||
try {
|
||||
log.info('Testing database connection')
|
||||
const settings = configManager.getAllSettings()
|
||||
const dbConfig = settings.database
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.SETTINGS_TEST_DB_CONNECTION,
|
||||
async (): Promise<IpcResult<ConnectionTestResult>> => {
|
||||
return withErrorHandling(async () => {
|
||||
log.info('Testing database connection')
|
||||
const config = configManager.getConfig()
|
||||
const dbType = config.database.activeType
|
||||
|
||||
if (dbConfig.dbType === 'mysql') {
|
||||
// Test MySQL connection
|
||||
if (!dbConfig.mysqlHost || !dbConfig.database || !dbConfig.username) {
|
||||
log.warn('MySQL connection test failed - missing configuration')
|
||||
return {
|
||||
success: false,
|
||||
message: '请先配置 MySQL 主机、数据库名和用户名'
|
||||
if (dbType === 'mysql') {
|
||||
const dbConfig = config.database.mysql
|
||||
if (!dbConfig.host || !dbConfig.database || !dbConfig.username) {
|
||||
return {
|
||||
success: false,
|
||||
message: '请先配置 MySQL 主机、数据库名和用户名'
|
||||
}
|
||||
}
|
||||
|
||||
const mysqlService = new MySqlService({
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database
|
||||
})
|
||||
|
||||
try {
|
||||
await mysqlService.connect()
|
||||
await mysqlService.disconnect()
|
||||
return {
|
||||
success: true,
|
||||
message: 'MySQL 数据库连接测试成功!'
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '连接失败'
|
||||
return {
|
||||
success: false,
|
||||
message: `MySQL 数据库连接测试失败:${message}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const mysqlService = new MySqlService({
|
||||
host: dbConfig.mysqlHost,
|
||||
port: dbConfig.mysqlPort,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database
|
||||
})
|
||||
|
||||
try {
|
||||
await mysqlService.connect()
|
||||
await mysqlService.disconnect()
|
||||
log.info('MySQL connection test successful')
|
||||
return {
|
||||
success: true,
|
||||
message: 'MySQL 数据库连接测试成功!'
|
||||
}
|
||||
} catch (connError) {
|
||||
const errorMessage = connError instanceof Error ? connError.message : '连接失败'
|
||||
log.error('MySQL connection failed', { error: errorMessage })
|
||||
return {
|
||||
success: false,
|
||||
message: `MySQL 数据库连接测试失败:${errorMessage}`
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Test SQL Server connection
|
||||
const dbConfig = config.database.sqlserver
|
||||
if (!dbConfig.server || !dbConfig.database || !dbConfig.username) {
|
||||
log.warn('SQL Server connection test failed - missing configuration')
|
||||
return {
|
||||
success: false,
|
||||
message: '请先配置 SQL Server 服务器、数据库名和用户名'
|
||||
@@ -244,39 +149,52 @@ export function registerSettingsHandlers(): void {
|
||||
|
||||
const sqlServerService = new SqlServerService({
|
||||
server: dbConfig.server,
|
||||
port: 1433, // Default SQL Server port
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
options: {
|
||||
trustServerCertificate: true
|
||||
trustServerCertificate: dbConfig.trustServerCertificate
|
||||
}
|
||||
})
|
||||
|
||||
try {
|
||||
await sqlServerService.connect()
|
||||
await sqlServerService.disconnect()
|
||||
log.info('SQL Server connection test successful')
|
||||
return {
|
||||
success: true,
|
||||
message: 'SQL Server 数据库连接测试成功!'
|
||||
}
|
||||
} catch (connError) {
|
||||
const errorMessage = connError instanceof Error ? connError.message : '连接失败'
|
||||
log.error('SQL Server connection failed', { error: errorMessage })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '连接失败'
|
||||
return {
|
||||
success: false,
|
||||
message: `SQL Server 数据库连接测试失败:${errorMessage}`
|
||||
message: `SQL Server 数据库连接测试失败:${message}`
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Database connection test error', { error: message })
|
||||
return {
|
||||
success: false,
|
||||
message: `数据库连接测试失败:${message}`
|
||||
}
|
||||
}, 'settings:testDbConnection')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.CONFIG_GET_CLEANER, async (): Promise<IpcResult<CleanerConfig>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
return config.cleaner
|
||||
}, 'config:getCleaner')
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.CONFIG_UPDATE_CLEANER,
|
||||
async (_event, updates: Partial<CleanerConfig>): Promise<IpcResult<CleanerConfig>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const result = await configManager.updateConfig({ cleaner: updates as CleanerConfig })
|
||||
if (!result.success) {
|
||||
throw new Error(result.error)
|
||||
}
|
||||
return configManager.getConfig().cleaner
|
||||
}, 'config:updateCleaner')
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
147
src/main/ipc/user-erp-config-handler.ts
Normal file
147
src/main/ipc/user-erp-config-handler.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { UserErpConfigService } from '../services/user/user-erp-config-service'
|
||||
import { ErpAuthService } from '../services/erp/erp-auth'
|
||||
import { ConfigManager } from '../services/config/config-manager'
|
||||
import { createLogger } from '../services/logger'
|
||||
import { SessionManager } from '../services/user/session-manager'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
import { ValidationError } from '../types/errors'
|
||||
import { withErrorHandling, type IpcResult } from './index'
|
||||
|
||||
const log = createLogger('UserErpConfigHandler')
|
||||
|
||||
export interface ErpCredentialsRequest {
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface ErpConfigResponse {
|
||||
success: boolean
|
||||
config?: {
|
||||
url: string
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface ConnectionTestResult {
|
||||
success: boolean
|
||||
message?: string
|
||||
}
|
||||
|
||||
export function registerUserErpConfigHandlers(): void {
|
||||
const erpConfigService = UserErpConfigService.getInstance()
|
||||
const sessionManager = SessionManager.getInstance()
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.USER_ERP_CONFIG_GET_CURRENT,
|
||||
async (): Promise<IpcResult<ErpConfigResponse>> => {
|
||||
return withErrorHandling(async () => {
|
||||
log.info('Fetching current user ERP credentials')
|
||||
const credentials = await erpConfigService.getCurrentUserErpConfig()
|
||||
|
||||
if (!credentials) {
|
||||
throw new ValidationError(
|
||||
'未找到 ERP 配置。请先配置 ERP 账号和密码。',
|
||||
'VAL_INVALID_INPUT'
|
||||
)
|
||||
}
|
||||
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const globalConfig = configManager.getConfig()
|
||||
|
||||
return {
|
||||
success: true,
|
||||
config: {
|
||||
url: globalConfig.erp.url,
|
||||
username: credentials.username,
|
||||
password: credentials.password
|
||||
}
|
||||
}
|
||||
}, 'user-erp-config:getCurrent')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.USER_ERP_CONFIG_UPDATE,
|
||||
async (_event, credentials: ErpCredentialsRequest): Promise<IpcResult<ErpConfigResponse>> => {
|
||||
return withErrorHandling(async () => {
|
||||
const updated = await erpConfigService.updateCurrentUserErpConfig(credentials)
|
||||
if (!updated) {
|
||||
throw new ValidationError('更新 ERP 配置失败', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const globalConfig = configManager.getConfig()
|
||||
|
||||
return {
|
||||
success: true,
|
||||
config: {
|
||||
url: globalConfig.erp.url,
|
||||
username: credentials.username,
|
||||
password: credentials.password
|
||||
}
|
||||
}
|
||||
}, 'user-erp-config:update')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.USER_ERP_CONFIG_TEST_CONNECTION,
|
||||
async (
|
||||
_event,
|
||||
credentials: ErpCredentialsRequest
|
||||
): Promise<IpcResult<ConnectionTestResult>> => {
|
||||
return withErrorHandling(async () => {
|
||||
if (!credentials.username || !credentials.password) {
|
||||
throw new ValidationError(
|
||||
'ERP 配置不完整,请确保用户名和密码都已填写',
|
||||
'VAL_MISSING_REQUIRED'
|
||||
)
|
||||
}
|
||||
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const globalConfig = configManager.getConfig()
|
||||
const authService = new ErpAuthService({
|
||||
url: globalConfig.erp.url,
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
headless: true
|
||||
})
|
||||
|
||||
try {
|
||||
await authService.login()
|
||||
return {
|
||||
success: true,
|
||||
message: 'ERP 连接测试成功'
|
||||
}
|
||||
} finally {
|
||||
await authService.close().catch(() => {})
|
||||
}
|
||||
}, 'user-erp-config:testConnection')
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.USER_ERP_CONFIG_GET_ALL,
|
||||
async (): Promise<
|
||||
IpcResult<
|
||||
Array<{
|
||||
username: string
|
||||
erpUrl: string
|
||||
erpUsername: string
|
||||
}>
|
||||
>
|
||||
> => {
|
||||
return withErrorHandling(async () => {
|
||||
if (!sessionManager.isAdmin()) {
|
||||
throw new ValidationError('只有管理员可以查看全部用户 ERP 配置', 'VAL_INVALID_INPUT')
|
||||
}
|
||||
|
||||
const configs = await erpConfigService.getAllUsersErpConfig()
|
||||
return configs
|
||||
}, 'user-erp-config:getAll')
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { MySqlService } from '../services/database/mysql'
|
||||
import { SqlServerService } from '../services/database/sql-server'
|
||||
import { MaterialsToBeDeletedDAO } from '../services/database/materials-to-be-deleted-dao'
|
||||
import { DiscreteMaterialPlanDAO } from '../services/database/discrete-material-plan-dao'
|
||||
import { ConfigManager } from '../services/config/config-manager'
|
||||
import { createLogger } from '../services/logger'
|
||||
import type {
|
||||
ValidationRequest,
|
||||
@@ -22,6 +23,7 @@ import type {
|
||||
ValidationResult,
|
||||
MaterialRecordSummary
|
||||
} from '../types/validation.types'
|
||||
import { IPC_CHANNELS } from '../../shared/ipc-channels'
|
||||
|
||||
const log = createLogger('ValidationHandler')
|
||||
|
||||
@@ -29,57 +31,61 @@ const log = createLogger('ValidationHandler')
|
||||
* Shared state for Production IDs from extractor page
|
||||
* This is a simple in-memory store for sharing Production IDs between pages
|
||||
*/
|
||||
const sharedProductionIds = new Set<string>()
|
||||
const sharedProductionIdsBySender = new Map<number, Set<string>>()
|
||||
|
||||
/**
|
||||
* Set shared Production IDs
|
||||
*/
|
||||
export function setSharedProductionIds(ids: string[]): void {
|
||||
sharedProductionIds.clear()
|
||||
ids.forEach((id) => sharedProductionIds.add(id))
|
||||
export function setSharedProductionIds(senderId: number, ids: string[]): void {
|
||||
sharedProductionIdsBySender.set(senderId, new Set(ids))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get shared Production IDs
|
||||
*/
|
||||
export function getSharedProductionIds(): string[] {
|
||||
return [...sharedProductionIds]
|
||||
export function getSharedProductionIds(senderId: number): string[] {
|
||||
const senderSet = sharedProductionIdsBySender.get(senderId)
|
||||
return senderSet ? [...senderSet] : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear shared Production IDs
|
||||
*/
|
||||
export function clearSharedProductionIds(): void {
|
||||
sharedProductionIds.clear()
|
||||
export function clearSharedProductionIds(senderId: number): void {
|
||||
sharedProductionIdsBySender.delete(senderId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get database service for validation operations (MySQL or SQL Server)
|
||||
*/
|
||||
async function getValidationDatabaseService(): Promise<MySqlService | SqlServerService> {
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
|
||||
if (dbType === 'sqlserver' || dbType === 'mssql') {
|
||||
if (dbType === 'sqlserver') {
|
||||
const dbConfig = config.database.sqlserver
|
||||
const sqlServerService = new SqlServerService({
|
||||
server: process.env.DB_SERVER || 'localhost',
|
||||
port: parseInt(process.env.DB_SQLSERVER_PORT || '1433', 10),
|
||||
user: process.env.DB_USERNAME || 'sa',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || '',
|
||||
server: dbConfig.server,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
options: {
|
||||
encrypt: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes',
|
||||
trustServerCertificate: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
|
||||
encrypt: false,
|
||||
trustServerCertificate: dbConfig.trustServerCertificate
|
||||
}
|
||||
})
|
||||
await sqlServerService.connect()
|
||||
return sqlServerService
|
||||
} else {
|
||||
const dbConfig = config.database.mysql
|
||||
const mysqlService = new MySqlService({
|
||||
host: process.env.DB_MYSQL_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
|
||||
user: process.env.DB_USERNAME || 'root',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || ''
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database
|
||||
})
|
||||
await mysqlService.connect()
|
||||
return mysqlService
|
||||
@@ -93,8 +99,10 @@ async function getValidationDatabaseService(): Promise<MySqlService | SqlServerS
|
||||
* dbo_MaterialsToBeDeleted -> [dbo].[MaterialsToBeDeleted]
|
||||
*/
|
||||
function getTableName(mysqlTableName: string): string {
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
if (dbType === 'sqlserver' || dbType === 'mssql') {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
|
||||
if (dbType === 'sqlserver') {
|
||||
// Find the FIRST underscore to split schema and table name
|
||||
// This handles patterns like: schema_tablename
|
||||
const firstUnderscoreIndex = mysqlTableName.indexOf('_')
|
||||
@@ -145,8 +153,9 @@ async function getSourceNumbersFromInputs(
|
||||
): Promise<string[]> {
|
||||
const productionIds: string[] = []
|
||||
const orderNumbers: string[] = []
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
const isSqlServer = dbType === 'sqlserver' || dbType === 'mssql'
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
const isSqlServer = dbType === 'sqlserver'
|
||||
|
||||
for (const item of inputs) {
|
||||
const type = identifyInputType(item)
|
||||
@@ -162,37 +171,52 @@ async function getSourceNumbersFromInputs(
|
||||
// Column name: 生产订单号 (SourceNumber)
|
||||
if (productionIds.length > 0) {
|
||||
const contractTableName = getTableName('productionContractData_26年压力表合同数据')
|
||||
const batchSize = 2000
|
||||
|
||||
if (isSqlServer) {
|
||||
const sql = require('mssql')
|
||||
const placeholders = productionIds.map((_, idx) => `@p${idx}`).join(',')
|
||||
const params: Record<string, { value: string; type: any }> = {}
|
||||
const allOrderNumbers: string[] = []
|
||||
|
||||
productionIds.forEach((id, idx) => {
|
||||
params[`p${idx}`] = { value: id, type: sql.NVarChar }
|
||||
})
|
||||
for (let i = 0; i < productionIds.length; i += batchSize) {
|
||||
const batch = productionIds.slice(i, i + batchSize)
|
||||
const placeholders = batch.map((_, idx) => `@p${idx}`).join(',')
|
||||
const params: Record<string, { value: string; type: any }> = {}
|
||||
|
||||
const contractSql = `
|
||||
SELECT DISTINCT 生产订单号
|
||||
FROM ${contractTableName}
|
||||
WHERE 总排号 IN (${placeholders})
|
||||
`
|
||||
const contractResult = await (dbService as SqlServerService).queryWithParams(
|
||||
contractSql,
|
||||
params
|
||||
)
|
||||
const dbOrderNumbers = contractResult.rows.map((row) => row.生产订单号 as string)
|
||||
orderNumbers.push(...dbOrderNumbers)
|
||||
batch.forEach((id, idx) => {
|
||||
params[`p${idx}`] = { value: id, type: sql.NVarChar }
|
||||
})
|
||||
|
||||
const contractSql = `
|
||||
SELECT DISTINCT 生产订单号
|
||||
FROM ${contractTableName}
|
||||
WHERE 总排号 IN (${placeholders})
|
||||
`
|
||||
const contractResult = await (dbService as SqlServerService).queryWithParams(
|
||||
contractSql,
|
||||
params
|
||||
)
|
||||
const dbOrderNumbers = contractResult.rows.map((row) => row.生产订单号 as string)
|
||||
allOrderNumbers.push(...dbOrderNumbers)
|
||||
}
|
||||
|
||||
orderNumbers.push(...allOrderNumbers)
|
||||
} else {
|
||||
const placeholders = productionIds.map(() => '?').join(',')
|
||||
const contractSql = `
|
||||
SELECT DISTINCT 生产订单号
|
||||
FROM ${contractTableName}
|
||||
WHERE 总排号 IN (${placeholders})
|
||||
`
|
||||
const contractResult = await (dbService as MySqlService).query(contractSql, productionIds)
|
||||
const dbOrderNumbers = contractResult.rows.map((row) => row.生产订单号 as string)
|
||||
orderNumbers.push(...dbOrderNumbers)
|
||||
const allOrderNumbers: string[] = []
|
||||
|
||||
for (let i = 0; i < productionIds.length; i += batchSize) {
|
||||
const batch = productionIds.slice(i, i + batchSize)
|
||||
const placeholders = batch.map(() => '?').join(',')
|
||||
const contractSql = `
|
||||
SELECT DISTINCT 生产订单号
|
||||
FROM ${contractTableName}
|
||||
WHERE 总排号 IN (${placeholders})
|
||||
`
|
||||
const contractResult = await (dbService as MySqlService).query(contractSql, batch)
|
||||
const dbOrderNumbers = contractResult.rows.map((row) => row.生产订单号 as string)
|
||||
allOrderNumbers.push(...dbOrderNumbers)
|
||||
}
|
||||
|
||||
orderNumbers.push(...allOrderNumbers)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,8 +234,8 @@ export function registerValidationHandlers(): void {
|
||||
* Run material validation from database
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'validation:validate',
|
||||
async (_event, request: ValidationRequest): Promise<ValidationResponse> => {
|
||||
IPC_CHANNELS.VALIDATION_VALIDATE,
|
||||
async (event, request: ValidationRequest): Promise<ValidationResponse> => {
|
||||
let dbService: MySqlService | SqlServerService | null = null
|
||||
|
||||
try {
|
||||
@@ -240,8 +264,9 @@ export function registerValidationHandlers(): void {
|
||||
|
||||
// Connect to database
|
||||
dbService = await getValidationDatabaseService()
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
const isSqlServer = dbType === 'sqlserver' || dbType === 'mssql'
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
const isSqlServer = dbType === 'sqlserver'
|
||||
|
||||
let sourceNumbers: string[] | null = null
|
||||
|
||||
@@ -249,7 +274,7 @@ export function registerValidationHandlers(): void {
|
||||
if (request.mode === 'database_filtered') {
|
||||
if (request.useSharedProductionIds) {
|
||||
// Use shared Production IDs from extractor page
|
||||
const sharedIds = getSharedProductionIds()
|
||||
const sharedIds = getSharedProductionIds(event.sender.id)
|
||||
log.info(`Using ${sharedIds.length} shared Production IDs`)
|
||||
|
||||
if (sharedIds.length === 0) {
|
||||
@@ -266,12 +291,40 @@ export function registerValidationHandlers(): void {
|
||||
|
||||
sourceNumbers = await getSourceNumbersFromInputs(sharedIds, dbService)
|
||||
log.info(`Got ${sourceNumbers.length} source numbers from shared Production IDs`)
|
||||
|
||||
// Check if we got any order numbers from the shared Production IDs
|
||||
if (sourceNumbers.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
'共享的 Production ID 没有找到对应的订单数据。请确保在数据提取页面输入了有效的 Production ID 并成功获取了订单数据。',
|
||||
stats: {
|
||||
totalRecords: 0,
|
||||
matchedCount: 0,
|
||||
markedCount: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (request.productionIdFile) {
|
||||
// Read from file
|
||||
const inputs = readProductionIds(request.productionIdFile)
|
||||
log.info(`Read ${inputs.length} inputs from file`)
|
||||
sourceNumbers = await getSourceNumbersFromInputs(inputs, dbService)
|
||||
log.info(`Got ${sourceNumbers.length} source numbers`)
|
||||
|
||||
// Check if we got any order numbers from the file
|
||||
if (sourceNumbers.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
'文件中的 Production ID 没有找到对应的订单数据。请检查 Production ID 是否正确,或确保数据库中有对应的订单数据。',
|
||||
stats: {
|
||||
totalRecords: 0,
|
||||
matchedCount: 0,
|
||||
markedCount: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +344,7 @@ export function registerValidationHandlers(): void {
|
||||
if (materialRecords.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'No material records found',
|
||||
error: '未找到物料记录。请检查数据库中是否有对应订单的物料数据。',
|
||||
stats: {
|
||||
totalRecords: 0,
|
||||
matchedCount: 0,
|
||||
@@ -421,7 +474,7 @@ export function registerValidationHandlers(): void {
|
||||
* Upsert batch materials to MaterialsToBeDeleted
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materials:upsertBatch',
|
||||
IPC_CHANNELS.MATERIALS_UPSERT_BATCH,
|
||||
async (_event, request: MaterialUpsertBatchRequest): Promise<MaterialOperationResponse> => {
|
||||
try {
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
@@ -448,7 +501,7 @@ export function registerValidationHandlers(): void {
|
||||
* Delete materials by material codes
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materials:delete',
|
||||
IPC_CHANNELS.MATERIALS_DELETE,
|
||||
async (_event, request: MaterialDeleteRequest): Promise<MaterialOperationResponse> => {
|
||||
try {
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
@@ -472,31 +525,59 @@ export function registerValidationHandlers(): void {
|
||||
/**
|
||||
* Get unique manager names
|
||||
*/
|
||||
ipcMain.handle('materials:getManagers', async (_event): Promise<{ managers: string[] }> => {
|
||||
try {
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
const managers = await dao.getManagers()
|
||||
return { managers }
|
||||
} catch (error) {
|
||||
log.error('Get managers error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
return { managers: [] }
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.MATERIALS_GET_MANAGERS,
|
||||
async (_event): Promise<{ managers: string[] }> => {
|
||||
try {
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
const managers = await dao.getManagers()
|
||||
return { managers }
|
||||
} catch (error) {
|
||||
log.error('Get managers error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
return { managers: [] }
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Update manager for a single material
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.MATERIALS_UPDATE_MANAGER,
|
||||
async (
|
||||
_event,
|
||||
request: { materialCode: string; managerName: string }
|
||||
): Promise<{ success: boolean; error?: string }> => {
|
||||
try {
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
return await dao.updateManager(request.materialCode, request.managerName)
|
||||
} catch (error) {
|
||||
log.error('Update manager error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* Get materials by manager
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materials:getByManager',
|
||||
IPC_CHANNELS.MATERIALS_GET_BY_MANAGER,
|
||||
async (_event, managerName: string): Promise<{ materials: MaterialRecordSummary[] }> => {
|
||||
let dbService: MySqlService | SqlServerService | null = null
|
||||
|
||||
try {
|
||||
dbService = await getValidationDatabaseService()
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
const isSqlServer = dbType === 'sqlserver' || dbType === 'mssql'
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
const isSqlServer = dbType === 'sqlserver'
|
||||
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
const materials = await dao.getMaterialsByManager(managerName)
|
||||
@@ -567,14 +648,15 @@ export function registerValidationHandlers(): void {
|
||||
* Get all material records
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'materials:getAll',
|
||||
IPC_CHANNELS.MATERIALS_GET_ALL,
|
||||
async (_event): Promise<{ materials: MaterialRecordSummary[] }> => {
|
||||
let dbService: MySqlService | SqlServerService | null = null
|
||||
|
||||
try {
|
||||
dbService = await getValidationDatabaseService()
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
const isSqlServer = dbType === 'sqlserver' || dbType === 'mssql'
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
const isSqlServer = dbType === 'sqlserver'
|
||||
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
const materials = await dao.getAllRecords()
|
||||
@@ -641,7 +723,7 @@ export function registerValidationHandlers(): void {
|
||||
/**
|
||||
* Get statistics
|
||||
*/
|
||||
ipcMain.handle('materials:getStatistics', async (_event): Promise<{ stats: any }> => {
|
||||
ipcMain.handle(IPC_CHANNELS.MATERIALS_GET_STATISTICS, async (_event): Promise<{ stats: any }> => {
|
||||
try {
|
||||
const dao = new MaterialsToBeDeletedDAO()
|
||||
const stats = await dao.getStatistics()
|
||||
@@ -658,10 +740,10 @@ export function registerValidationHandlers(): void {
|
||||
* Set shared Production IDs from extractor page
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'validation:setSharedProductionIds',
|
||||
async (_event, productionIds: string[]): Promise<void> => {
|
||||
IPC_CHANNELS.VALIDATION_SET_SHARED_PRODUCTION_IDS,
|
||||
async (event, productionIds: string[]): Promise<void> => {
|
||||
log.info(`Received ${productionIds.length} shared Production IDs`)
|
||||
setSharedProductionIds(productionIds)
|
||||
setSharedProductionIds(event.sender.id, productionIds)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -669,9 +751,20 @@ export function registerValidationHandlers(): void {
|
||||
* Get shared Production IDs
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'validation:getSharedProductionIds',
|
||||
async (): Promise<{ productionIds: string[] }> => {
|
||||
return { productionIds: getSharedProductionIds() }
|
||||
IPC_CHANNELS.VALIDATION_GET_SHARED_PRODUCTION_IDS,
|
||||
async (event): Promise<{ productionIds: string[] }> => {
|
||||
return { productionIds: getSharedProductionIds(event.sender.id) }
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* Clear shared Production IDs
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.VALIDATION_CLEAR_SHARED_PRODUCTION_IDS,
|
||||
async (event): Promise<void> => {
|
||||
log.info('Clearing shared Production IDs')
|
||||
clearSharedProductionIds(event.sender.id)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -680,7 +773,7 @@ export function registerValidationHandlers(): void {
|
||||
* Filters materials by current user (admin sees all, regular users see only their own)
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'validation:getCleanerData',
|
||||
IPC_CHANNELS.VALIDATION_GET_CLEANER_DATA,
|
||||
async (
|
||||
_event
|
||||
): Promise<{
|
||||
@@ -706,8 +799,9 @@ export function registerValidationHandlers(): void {
|
||||
|
||||
const isAdmin = userInfo.userType === 'Admin'
|
||||
const username = userInfo.username
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
const isSqlServer = dbType === 'sqlserver' || dbType === 'mssql'
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
const isSqlServer = dbType === 'sqlserver'
|
||||
|
||||
log.info(`User: ${username}, isAdmin: ${isAdmin}`)
|
||||
|
||||
@@ -715,7 +809,7 @@ export function registerValidationHandlers(): void {
|
||||
dbService = await getValidationDatabaseService()
|
||||
|
||||
// 1. Get order numbers from shared Production IDs
|
||||
const sharedIds = getSharedProductionIds()
|
||||
const sharedIds = getSharedProductionIds(_event.sender.id)
|
||||
let orderNumbers: string[] = []
|
||||
|
||||
if (sharedIds.length > 0) {
|
||||
|
||||
@@ -12,7 +12,9 @@ export const CleanerInputSchema = z.object({
|
||||
.array(z.string().min(1, 'Order number cannot be empty'))
|
||||
.min(1, 'At least one order number is required'),
|
||||
materialCodes: z.array(z.string().min(1, 'Material code cannot be empty')),
|
||||
dryRun: z.boolean()
|
||||
dryRun: z.boolean(),
|
||||
queryBatchSize: z.number().int().min(1).max(100).optional().default(100),
|
||||
processConcurrency: z.number().int().min(1).max(20).optional().default(1)
|
||||
// Note: onProgress is a function, not validated via Zod
|
||||
})
|
||||
|
||||
|
||||
@@ -1,21 +1,34 @@
|
||||
/**
|
||||
* Configuration Manager
|
||||
* Configuration Manager (YAML Version)
|
||||
*
|
||||
* Manages application configuration stored in .env file
|
||||
* Provides methods for reading, writing, and saving configuration values
|
||||
* Manages application configuration using YAML format
|
||||
* Provides type-safe access with Zod validation
|
||||
*
|
||||
* Note: ERP configuration is stored in database (dbo_BIPUsers table)
|
||||
* and managed per-user, not in this config file.
|
||||
*
|
||||
* Configuration File Location:
|
||||
* - Development: Project root directory (config.yaml)
|
||||
* - Production (Installed & Portable): User data directory (AppData)
|
||||
* This ensures config persists across app updates and is not exposed
|
||||
*/
|
||||
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { dirname } from 'path'
|
||||
import { createLogger } from '../logger'
|
||||
import type {
|
||||
SettingsData,
|
||||
DatabaseType,
|
||||
MatchMode,
|
||||
ValidationDataSource
|
||||
} from '../../types/settings.types'
|
||||
import { app } from 'electron'
|
||||
import yaml from 'js-yaml'
|
||||
import { z } from 'zod'
|
||||
import { createLogger, setLogLevel } from '../logger'
|
||||
import {
|
||||
fullConfigSchema,
|
||||
type FullConfig,
|
||||
type DatabaseType,
|
||||
type MySqlConfig,
|
||||
type SqlServerConfig,
|
||||
type LoggingConfig
|
||||
} from '../../types/config.schema'
|
||||
|
||||
const log = createLogger('ConfigManager')
|
||||
|
||||
@@ -23,30 +36,36 @@ const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = dirname(__filename)
|
||||
|
||||
/**
|
||||
* Default settings values
|
||||
* 默认配置
|
||||
*/
|
||||
const DEFAULT_SETTINGS: SettingsData = {
|
||||
const DEFAULT_CONFIG: FullConfig = {
|
||||
erp: {
|
||||
url: 'https://68.11.34.30:8082/',
|
||||
username: '',
|
||||
password: '',
|
||||
headless: true,
|
||||
ignoreHttpsErrors: true,
|
||||
autoCloseBrowser: true
|
||||
url: 'https://68.11.34.30:8082'
|
||||
},
|
||||
database: {
|
||||
dbType: 'mysql',
|
||||
server: '',
|
||||
mysqlHost: '192.168.31.83',
|
||||
mysqlPort: 3306,
|
||||
database: 'BLD_DB',
|
||||
username: 'remote_user',
|
||||
password: ''
|
||||
activeType: 'mysql',
|
||||
mysql: {
|
||||
host: 'localhost',
|
||||
port: 3306,
|
||||
database: 'erp_db',
|
||||
username: 'root',
|
||||
password: '',
|
||||
charset: 'utf8mb4'
|
||||
},
|
||||
sqlserver: {
|
||||
server: 'localhost',
|
||||
port: 1433,
|
||||
database: 'erp_db',
|
||||
username: 'sa',
|
||||
password: '',
|
||||
driver: 'ODBC Driver 18 for SQL Server',
|
||||
trustServerCertificate: true
|
||||
}
|
||||
},
|
||||
paths: {
|
||||
dataDir: 'D:/python/playwrite/data/',
|
||||
defaultOutput: '离散备料计划维护_合并.xlsx',
|
||||
validationOutput: '物料状态校验结果.xlsx'
|
||||
dataDir: './data/',
|
||||
defaultOutput: 'output.xlsx',
|
||||
validationOutput: 'validation-result.xlsx'
|
||||
},
|
||||
extraction: {
|
||||
batchSize: 100,
|
||||
@@ -62,108 +81,60 @@ const DEFAULT_SETTINGS: SettingsData = {
|
||||
enableCrud: false,
|
||||
defaultManager: ''
|
||||
},
|
||||
ui: {
|
||||
fontFamily: 'Microsoft YaHei UI',
|
||||
fontSize: 10,
|
||||
productionIdInputWidth: 20
|
||||
cleaner: {
|
||||
queryBatchSize: 100,
|
||||
processConcurrency: 1
|
||||
},
|
||||
execution: {
|
||||
dryRun: false
|
||||
orderResolution: {
|
||||
tableName: '',
|
||||
productionIdField: '',
|
||||
orderNumberField: ''
|
||||
},
|
||||
logging: {
|
||||
level: 'info',
|
||||
auditRetention: 30,
|
||||
appRetention: 14
|
||||
},
|
||||
rustfs: {
|
||||
enabled: false,
|
||||
endpoint: '',
|
||||
accessKey: '',
|
||||
secretKey: '',
|
||||
bucket: 'erpauto',
|
||||
region: 'us-east-1'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if value is a plain object
|
||||
*/
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep merge two objects, only updating fields present in target
|
||||
* Preserves all fields from source that are not in target
|
||||
*/
|
||||
function deepMerge<T>(source: T, target: Partial<T>): T {
|
||||
const result = { ...source }
|
||||
|
||||
for (const key in target) {
|
||||
if (key in target) {
|
||||
const targetValue = target[key]
|
||||
const sourceValue = result[key]
|
||||
|
||||
if (isObject(targetValue) && isObject(sourceValue)) {
|
||||
result[key] = deepMerge(
|
||||
sourceValue as T[Extract<keyof T, string>],
|
||||
targetValue as Partial<T[Extract<keyof T, string>]>
|
||||
)
|
||||
} else if (targetValue !== undefined) {
|
||||
result[key] = targetValue as T[Extract<keyof T, string>]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* UI editable field whitelist
|
||||
* Fields that can be modified through the settings UI
|
||||
*/
|
||||
const UI_EDITABLE_FIELDS: string[] = [
|
||||
'erp.url',
|
||||
'erp.username',
|
||||
'erp.password'
|
||||
// Add more fields as UI expands
|
||||
]
|
||||
|
||||
/**
|
||||
* Validate that settings only contain editable fields
|
||||
*/
|
||||
function validateEditableFields(settings: Partial<SettingsData>): {
|
||||
valid: boolean
|
||||
invalidFields: string[]
|
||||
} {
|
||||
const invalidFields: string[] = []
|
||||
|
||||
for (const [section, values] of Object.entries(settings)) {
|
||||
if (values && typeof values === 'object') {
|
||||
for (const field of Object.keys(values)) {
|
||||
const fieldPath = `${section}.${field}`
|
||||
if (!UI_EDITABLE_FIELDS.includes(fieldPath)) {
|
||||
invalidFields.push(fieldPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: invalidFields.length === 0,
|
||||
invalidFields
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration Manager Class
|
||||
*/
|
||||
export class ConfigManager {
|
||||
private static instance: ConfigManager | null = null
|
||||
private envPath: string
|
||||
private backupPath: string
|
||||
private configCache: Map<string, string> = new Map()
|
||||
private configPath!: string
|
||||
private backupPath!: string
|
||||
private config: FullConfig | null = null
|
||||
private initialized: boolean = false
|
||||
|
||||
private constructor() {
|
||||
if (this.initialized) {
|
||||
return
|
||||
if (this.initialized) return
|
||||
|
||||
// 检测是否为开发环境
|
||||
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged
|
||||
|
||||
if (isDev) {
|
||||
// 开发环境:配置文件放在项目根目录,方便编辑和调试
|
||||
this.configPath = path.resolve(__dirname, '../../config.yaml')
|
||||
this.backupPath = path.resolve(__dirname, '../../config.yaml.backup')
|
||||
log.info('Running in development mode', { configPath: this.configPath })
|
||||
} else {
|
||||
// 生产环境(包括安装版和便携版):配置文件放在用户数据目录
|
||||
// Windows: C:\Users\<user>\AppData\Roaming\erpauto\config.yaml
|
||||
// 这样配置会在应用升级时保留,且不会暴露在应用目录中
|
||||
this.configPath = path.join(app.getPath('userData'), 'config.yaml')
|
||||
this.backupPath = path.join(app.getPath('userData'), 'config.yaml.backup')
|
||||
log.info('Running in production mode', { configPath: this.configPath })
|
||||
}
|
||||
this.envPath = path.resolve(__dirname, '../../.env')
|
||||
this.backupPath = path.resolve(__dirname, '../../.env.backup')
|
||||
|
||||
this.initialized = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the singleton instance
|
||||
*/
|
||||
public static getInstance(): ConfigManager {
|
||||
if (ConfigManager.instance === null) {
|
||||
ConfigManager.instance = new ConfigManager()
|
||||
@@ -172,546 +143,204 @@ export class ConfigManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize configuration from .env file
|
||||
* 初始化配置
|
||||
* - 如果 config.yaml 不存在,创建默认配置
|
||||
* - 加载并验证配置
|
||||
*/
|
||||
public async initialize(): Promise<void> {
|
||||
await this.loadEnvFile()
|
||||
if (!fs.existsSync(this.configPath)) {
|
||||
log.info('Config file not found, creating default config.yaml')
|
||||
await this.saveConfig(DEFAULT_CONFIG)
|
||||
this.config = DEFAULT_CONFIG
|
||||
// Apply logging configuration from default config
|
||||
setLogLevel(DEFAULT_CONFIG.logging.level)
|
||||
return
|
||||
}
|
||||
|
||||
await this.loadConfig()
|
||||
}
|
||||
|
||||
/**
|
||||
* Load .env file into cache
|
||||
* 加载并验证 YAML 配置
|
||||
*/
|
||||
private async loadEnvFile(): Promise<void> {
|
||||
private async loadConfig(): Promise<void> {
|
||||
try {
|
||||
// Clear cache before loading
|
||||
this.configCache.clear()
|
||||
const content = fs.readFileSync(this.configPath, 'utf-8')
|
||||
const parsed = yaml.load(content) as Record<string, unknown>
|
||||
|
||||
if (fs.existsSync(this.envPath)) {
|
||||
const content = fs.readFileSync(this.envPath, 'utf-8')
|
||||
const lines = content.split('\n')
|
||||
// Zod 验证
|
||||
const validated = fullConfigSchema.parse(parsed)
|
||||
this.config = validated
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmedLine = line.trim()
|
||||
// Skip empty lines and comments
|
||||
if (!trimmedLine || trimmedLine.startsWith('#')) {
|
||||
continue
|
||||
}
|
||||
// Apply logging configuration
|
||||
setLogLevel(validated.logging.level)
|
||||
|
||||
const [key, ...valueParts] = trimmedLine.split('=')
|
||||
if (key && valueParts.length > 0) {
|
||||
const value = valueParts.join('=').trim()
|
||||
this.configCache.set(key.trim(), value)
|
||||
}
|
||||
}
|
||||
}
|
||||
log.info('Configuration loaded and validated successfully')
|
||||
} catch (error) {
|
||||
console.error('[ConfigManager] Failed to load .env file:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
const messages = error.issues.map((e: any) => `${e.path.join('.')}: ${e.message}`)
|
||||
log.error('Configuration validation failed', { errors: messages })
|
||||
throw new Error(`配置文件验证失败:\n${messages.join('\n')}`)
|
||||
}
|
||||
log.error('Failed to load configuration', { error })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a configuration value
|
||||
* @param key - Configuration key
|
||||
* @param defaultValue - Default value if key doesn't exist
|
||||
* 保存配置到 YAML 文件
|
||||
*/
|
||||
public get(key: string, defaultValue?: string): string | undefined {
|
||||
return this.configCache.get(key) ?? defaultValue
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a boolean configuration value
|
||||
*/
|
||||
public getBoolean(key: string, defaultValue: boolean = false): boolean {
|
||||
const value = this.get(key)
|
||||
if (value === undefined) return defaultValue
|
||||
return value.toLowerCase() === 'true'
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a number configuration value
|
||||
*/
|
||||
public getNumber(key: string, defaultValue: number = 0): number {
|
||||
const value = this.get(key)
|
||||
if (value === undefined) return defaultValue
|
||||
const parsed = parseInt(value, 10)
|
||||
return isNaN(parsed) ? defaultValue : parsed
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a configuration value in cache
|
||||
*/
|
||||
public set(key: string, value: string | number | boolean): void {
|
||||
this.configCache.set(key, String(value))
|
||||
}
|
||||
|
||||
/**
|
||||
* Save configuration to .env file
|
||||
*/
|
||||
public async save(): Promise<boolean> {
|
||||
private async saveConfig(config: FullConfig): Promise<boolean> {
|
||||
try {
|
||||
// Build .env content from cache
|
||||
const lines: string[] = []
|
||||
// 备份现有配置
|
||||
if (fs.existsSync(this.configPath)) {
|
||||
fs.copyFileSync(this.configPath, this.backupPath)
|
||||
}
|
||||
|
||||
// ERP Configuration
|
||||
lines.push('# ===========================')
|
||||
lines.push('# ERP 系统配置')
|
||||
lines.push('# ===========================')
|
||||
lines.push(`ERP_URL=${this.configCache.get('ERP_URL') || DEFAULT_SETTINGS.erp.url}`)
|
||||
lines.push(
|
||||
`ERP_USERNAME=${this.configCache.get('ERP_USERNAME') || DEFAULT_SETTINGS.erp.username}`
|
||||
)
|
||||
lines.push(
|
||||
`ERP_PASSWORD=${this.configCache.get('ERP_PASSWORD') || DEFAULT_SETTINGS.erp.password}`
|
||||
)
|
||||
lines.push(
|
||||
`ERP_HEADLESS=${this.configCache.get('ERP_HEADLESS') || DEFAULT_SETTINGS.erp.headless}`
|
||||
)
|
||||
lines.push(
|
||||
`ERP_IGNORE_HTTPS_ERRORS=${this.configCache.get('ERP_IGNORE_HTTPS_ERRORS') || DEFAULT_SETTINGS.erp.ignoreHttpsErrors}`
|
||||
)
|
||||
lines.push(
|
||||
`ERP_AUTO_CLOSE_BROWSER=${this.configCache.get('ERP_AUTO_CLOSE_BROWSER') || DEFAULT_SETTINGS.erp.autoCloseBrowser}`
|
||||
)
|
||||
lines.push('')
|
||||
// 转换为 YAML
|
||||
const content = yaml.dump(config, {
|
||||
indent: 2,
|
||||
lineWidth: -1, // 不自动换行
|
||||
noRefs: true, // 不使用引用
|
||||
quotingType: '"',
|
||||
forceQuotes: false
|
||||
})
|
||||
|
||||
// Database Configuration - SQL Server
|
||||
lines.push('# ===========================')
|
||||
lines.push('# 数据库配置 - SQL Server')
|
||||
lines.push('# ===========================')
|
||||
lines.push(`# DB_TYPE=sqlserver`)
|
||||
lines.push(`# DB_SERVER=${this.configCache.get('DB_SERVER') || ''}`)
|
||||
lines.push(`# DB_NAME=${this.configCache.get('DB_NAME') || ''}`)
|
||||
lines.push(`# DB_USERNAME=${this.configCache.get('DB_USERNAME') || ''}`)
|
||||
lines.push(`# DB_PASSWORD=${this.configCache.get('DB_PASSWORD') || ''}`)
|
||||
lines.push(`DB_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server`)
|
||||
lines.push(`DB_TRUST_SERVER_CERTIFICATE=yes`)
|
||||
lines.push('')
|
||||
fs.writeFileSync(this.configPath, content, 'utf-8')
|
||||
|
||||
// Database Configuration - MySQL
|
||||
lines.push('# ===========================')
|
||||
lines.push('# 数据库配置 - MySQL (切换时使用)')
|
||||
lines.push('# ===========================')
|
||||
lines.push(`DB_TYPE=${this.configCache.get('DB_TYPE') || DEFAULT_SETTINGS.database.dbType}`)
|
||||
lines.push(`DB_NAME=${this.configCache.get('DB_NAME') || DEFAULT_SETTINGS.database.database}`)
|
||||
lines.push(
|
||||
`DB_USERNAME=${this.configCache.get('DB_USERNAME') || DEFAULT_SETTINGS.database.username}`
|
||||
)
|
||||
lines.push(
|
||||
`DB_PASSWORD=${this.configCache.get('DB_PASSWORD') || DEFAULT_SETTINGS.database.password}`
|
||||
)
|
||||
lines.push(
|
||||
`DB_MYSQL_HOST=${this.configCache.get('DB_MYSQL_HOST') || DEFAULT_SETTINGS.database.mysqlHost}`
|
||||
)
|
||||
lines.push(
|
||||
`DB_MYSQL_PORT=${this.configCache.get('DB_MYSQL_PORT') || DEFAULT_SETTINGS.database.mysqlPort}`
|
||||
)
|
||||
lines.push(`DB_MYSQL_CHARSET=utf8mb4`)
|
||||
lines.push('')
|
||||
|
||||
// Order number parsing table configuration
|
||||
lines.push('# 订单号解析表配置')
|
||||
lines.push('# 表名:包含 productionID 和 生产订单号 映射关系的表')
|
||||
lines.push(`DB_TABLE_NAME=productionContractData_26 年压力表合同数据`)
|
||||
lines.push('# 字段名:总排号 (对应 productionID)')
|
||||
lines.push(`DB_FIELD_PRODUCTION_ID=总排号`)
|
||||
lines.push('# 字段名:生产订单号 (对应生产订单号)')
|
||||
lines.push(`DB_FIELD_ORDER_NUMBER=生产订单号`)
|
||||
lines.push('')
|
||||
|
||||
// Path Configuration
|
||||
lines.push('# ===========================')
|
||||
lines.push('# 路径配置')
|
||||
lines.push('# ===========================')
|
||||
lines.push(
|
||||
`PATH_DATA_DIR=${this.configCache.get('PATH_DATA_DIR') || DEFAULT_SETTINGS.paths.dataDir}`
|
||||
)
|
||||
lines.push(`PATH_PRODUCTION_ID_FILE=ProductionID.txt`)
|
||||
lines.push(
|
||||
`PATH_DEFAULT_OUTPUT=${this.configCache.get('PATH_DEFAULT_OUTPUT') || DEFAULT_SETTINGS.paths.defaultOutput}`
|
||||
)
|
||||
lines.push(
|
||||
`PATH_VALIDATION_OUTPUT=${this.configCache.get('PATH_VALIDATION_OUTPUT') || DEFAULT_SETTINGS.paths.validationOutput}`
|
||||
)
|
||||
lines.push('')
|
||||
|
||||
// Data Extraction Configuration
|
||||
lines.push('# ===========================')
|
||||
lines.push('# 数据提取配置')
|
||||
lines.push('# ===========================')
|
||||
lines.push(
|
||||
`EXTRACTION_BATCH_SIZE=${this.configCache.get('EXTRACTION_BATCH_SIZE') || DEFAULT_SETTINGS.extraction.batchSize}`
|
||||
)
|
||||
lines.push(
|
||||
`EXTRACTION_VERBOSE=${this.configCache.get('EXTRACTION_VERBOSE') || DEFAULT_SETTINGS.extraction.verbose}`
|
||||
)
|
||||
lines.push(
|
||||
`EXTRACTION_AUTO_CONVERT=${this.configCache.get('EXTRACTION_AUTO_CONVERT') || DEFAULT_SETTINGS.extraction.autoConvert}`
|
||||
)
|
||||
lines.push(
|
||||
`EXTRACTION_MERGE_BATCHES=${this.configCache.get('EXTRACTION_MERGE_BATCHES') || DEFAULT_SETTINGS.extraction.mergeBatches}`
|
||||
)
|
||||
lines.push(
|
||||
`EXTRACTION_ENABLE_DB_PERSISTENCE=${this.configCache.get('EXTRACTION_ENABLE_DB_PERSISTENCE') || DEFAULT_SETTINGS.extraction.enableDbPersistence}`
|
||||
)
|
||||
lines.push('')
|
||||
|
||||
// Validation Configuration
|
||||
lines.push('# ===========================')
|
||||
lines.push('# 校验配置')
|
||||
lines.push('# ===========================')
|
||||
lines.push(
|
||||
`VALIDATION_DATA_SOURCE=${this.configCache.get('VALIDATION_DATA_SOURCE') || DEFAULT_SETTINGS.validation.dataSource}`
|
||||
)
|
||||
lines.push(
|
||||
`VALIDATION_USE_DATABASE=${this.configCache.get('VALIDATION_USE_DATABASE') || true}`
|
||||
)
|
||||
lines.push(
|
||||
`VALIDATION_BATCH_SIZE=${this.configCache.get('VALIDATION_BATCH_SIZE') || DEFAULT_SETTINGS.validation.batchSize}`
|
||||
)
|
||||
lines.push(
|
||||
`VALIDATION_ENABLE_CRUD=${this.configCache.get('VALIDATION_ENABLE_CRUD') || DEFAULT_SETTINGS.validation.enableCrud}`
|
||||
)
|
||||
lines.push(
|
||||
`VALIDATION_DEFAULT_MANAGER=${this.configCache.get('VALIDATION_DEFAULT_MANAGER') || DEFAULT_SETTINGS.validation.defaultManager}`
|
||||
)
|
||||
lines.push(
|
||||
`VALIDATION_MATCH_MODE=${this.configCache.get('VALIDATION_MATCH_MODE') || DEFAULT_SETTINGS.validation.matchMode}`
|
||||
)
|
||||
lines.push('')
|
||||
|
||||
// UI Configuration
|
||||
lines.push('# ===========================')
|
||||
lines.push('# UI 配置')
|
||||
lines.push('# ===========================')
|
||||
lines.push(
|
||||
`UI_FONT_FAMILY=${this.configCache.get('UI_FONT_FAMILY') || DEFAULT_SETTINGS.ui.fontFamily}`
|
||||
)
|
||||
lines.push(
|
||||
`UI_FONT_SIZE=${this.configCache.get('UI_FONT_SIZE') || DEFAULT_SETTINGS.ui.fontSize}`
|
||||
)
|
||||
lines.push(
|
||||
`UI_PRODUCTION_ID_INPUT_WIDTH=${this.configCache.get('UI_PRODUCTION_ID_INPUT_WIDTH') || DEFAULT_SETTINGS.ui.productionIdInputWidth}`
|
||||
)
|
||||
lines.push('')
|
||||
|
||||
// Execution Configuration
|
||||
lines.push('# ===========================')
|
||||
lines.push('# 执行配置')
|
||||
lines.push('# ===========================')
|
||||
lines.push(
|
||||
`EXECUTION_DRYRUN=${this.configCache.get('EXECUTION_DRYRUN') || DEFAULT_SETTINGS.execution.dryRun}`
|
||||
)
|
||||
|
||||
const content = lines.join('\n')
|
||||
fs.writeFileSync(this.envPath, content, 'utf-8')
|
||||
this.config = config
|
||||
log.info('Configuration saved successfully')
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('[ConfigManager] Failed to save .env file:', error)
|
||||
log.error('Failed to save configuration', { error })
|
||||
// 恢复备份
|
||||
if (fs.existsSync(this.backupPath)) {
|
||||
fs.copyFileSync(this.backupPath, this.configPath)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all settings as SettingsData object
|
||||
* 获取完整配置
|
||||
*/
|
||||
public getAllSettings(): SettingsData {
|
||||
return {
|
||||
erp: {
|
||||
url: this.get('ERP_URL', DEFAULT_SETTINGS.erp.url),
|
||||
username: this.get('ERP_USERNAME', DEFAULT_SETTINGS.erp.username),
|
||||
password: this.get('ERP_PASSWORD', DEFAULT_SETTINGS.erp.password),
|
||||
headless: this.getBoolean('ERP_HEADLESS', DEFAULT_SETTINGS.erp.headless),
|
||||
ignoreHttpsErrors: this.getBoolean(
|
||||
'ERP_IGNORE_HTTPS_ERRORS',
|
||||
DEFAULT_SETTINGS.erp.ignoreHttpsErrors
|
||||
),
|
||||
autoCloseBrowser: this.getBoolean(
|
||||
'ERP_AUTO_CLOSE_BROWSER',
|
||||
DEFAULT_SETTINGS.erp.autoCloseBrowser
|
||||
)
|
||||
},
|
||||
database: {
|
||||
dbType:
|
||||
(this.get('DB_TYPE', DEFAULT_SETTINGS.database.dbType) as DatabaseType) ||
|
||||
DEFAULT_SETTINGS.database.dbType,
|
||||
server: this.get('DB_SERVER', DEFAULT_SETTINGS.database.server),
|
||||
mysqlHost: this.get('DB_MYSQL_HOST', DEFAULT_SETTINGS.database.mysqlHost),
|
||||
mysqlPort: this.getNumber('DB_MYSQL_PORT', DEFAULT_SETTINGS.database.mysqlPort),
|
||||
database: this.get('DB_NAME', DEFAULT_SETTINGS.database.database),
|
||||
username: this.get('DB_USERNAME', DEFAULT_SETTINGS.database.username),
|
||||
password: this.get('DB_PASSWORD', DEFAULT_SETTINGS.database.password)
|
||||
},
|
||||
paths: {
|
||||
dataDir: this.get('PATH_DATA_DIR', DEFAULT_SETTINGS.paths.dataDir),
|
||||
defaultOutput: this.get('PATH_DEFAULT_OUTPUT', DEFAULT_SETTINGS.paths.defaultOutput),
|
||||
validationOutput: this.get(
|
||||
'PATH_VALIDATION_OUTPUT',
|
||||
DEFAULT_SETTINGS.paths.validationOutput
|
||||
)
|
||||
},
|
||||
extraction: {
|
||||
batchSize: this.getNumber('EXTRACTION_BATCH_SIZE', DEFAULT_SETTINGS.extraction.batchSize),
|
||||
verbose: this.getBoolean('EXTRACTION_VERBOSE', DEFAULT_SETTINGS.extraction.verbose),
|
||||
autoConvert: this.getBoolean(
|
||||
'EXTRACTION_AUTO_CONVERT',
|
||||
DEFAULT_SETTINGS.extraction.autoConvert
|
||||
),
|
||||
mergeBatches: this.getBoolean(
|
||||
'EXTRACTION_MERGE_BATCHES',
|
||||
DEFAULT_SETTINGS.extraction.mergeBatches
|
||||
),
|
||||
enableDbPersistence: this.getBoolean(
|
||||
'EXTRACTION_ENABLE_DB_PERSISTENCE',
|
||||
DEFAULT_SETTINGS.extraction.enableDbPersistence
|
||||
)
|
||||
},
|
||||
validation: {
|
||||
dataSource:
|
||||
(this.get(
|
||||
'VALIDATION_DATA_SOURCE',
|
||||
DEFAULT_SETTINGS.validation.dataSource
|
||||
) as ValidationDataSource) || DEFAULT_SETTINGS.validation.dataSource,
|
||||
batchSize: this.getNumber('VALIDATION_BATCH_SIZE', DEFAULT_SETTINGS.validation.batchSize),
|
||||
matchMode:
|
||||
(this.get('VALIDATION_MATCH_MODE', DEFAULT_SETTINGS.validation.matchMode) as MatchMode) ||
|
||||
DEFAULT_SETTINGS.validation.matchMode,
|
||||
enableCrud: this.getBoolean(
|
||||
'VALIDATION_ENABLE_CRUD',
|
||||
DEFAULT_SETTINGS.validation.enableCrud
|
||||
),
|
||||
defaultManager: this.get(
|
||||
'VALIDATION_DEFAULT_MANAGER',
|
||||
DEFAULT_SETTINGS.validation.defaultManager
|
||||
)
|
||||
},
|
||||
ui: {
|
||||
fontFamily: this.get('UI_FONT_FAMILY', DEFAULT_SETTINGS.ui.fontFamily),
|
||||
fontSize: this.getNumber('UI_FONT_SIZE', DEFAULT_SETTINGS.ui.fontSize),
|
||||
productionIdInputWidth: this.getNumber(
|
||||
'UI_PRODUCTION_ID_INPUT_WIDTH',
|
||||
DEFAULT_SETTINGS.ui.productionIdInputWidth
|
||||
)
|
||||
},
|
||||
execution: {
|
||||
dryRun: this.getBoolean('EXECUTION_DRYRUN', DEFAULT_SETTINGS.execution.dryRun)
|
||||
}
|
||||
public getConfig(): FullConfig {
|
||||
if (!this.config) {
|
||||
throw new Error('Configuration not initialized. Call initialize() first.')
|
||||
}
|
||||
return this.config
|
||||
}
|
||||
|
||||
/**
|
||||
* Save settings from SettingsData object
|
||||
* 获取当前激活的数据库配置
|
||||
*/
|
||||
public async saveAllSettings(settings: SettingsData): Promise<boolean> {
|
||||
// ERP settings - use underscore uppercase keys to match .env file
|
||||
this.set('ERP_URL', settings.erp.url)
|
||||
this.set('ERP_USERNAME', settings.erp.username)
|
||||
this.set('ERP_PASSWORD', settings.erp.password)
|
||||
this.set('ERP_HEADLESS', settings.erp.headless)
|
||||
this.set('ERP_IGNORE_HTTPS_ERRORS', settings.erp.ignoreHttpsErrors)
|
||||
this.set('ERP_AUTO_CLOSE_BROWSER', settings.erp.autoCloseBrowser)
|
||||
public getActiveDatabaseConfig(): MySqlConfig | SqlServerConfig {
|
||||
if (!this.config) {
|
||||
throw new Error('Configuration not initialized')
|
||||
}
|
||||
|
||||
// Database settings
|
||||
this.set('DB_TYPE', settings.database.dbType)
|
||||
this.set('DB_SERVER', settings.database.server)
|
||||
this.set('DB_MYSQL_HOST', settings.database.mysqlHost)
|
||||
this.set('DB_MYSQL_PORT', settings.database.mysqlPort)
|
||||
this.set('DB_NAME', settings.database.database)
|
||||
this.set('DB_USERNAME', settings.database.username)
|
||||
this.set('DB_PASSWORD', settings.database.password)
|
||||
|
||||
// Path settings
|
||||
this.set('PATH_DATA_DIR', settings.paths.dataDir)
|
||||
this.set('PATH_DEFAULT_OUTPUT', settings.paths.defaultOutput)
|
||||
this.set('PATH_VALIDATION_OUTPUT', settings.paths.validationOutput)
|
||||
|
||||
// Extraction settings
|
||||
this.set('EXTRACTION_BATCH_SIZE', settings.extraction.batchSize)
|
||||
this.set('EXTRACTION_VERBOSE', settings.extraction.verbose)
|
||||
this.set('EXTRACTION_AUTO_CONVERT', settings.extraction.autoConvert)
|
||||
this.set('EXTRACTION_MERGE_BATCHES', settings.extraction.mergeBatches)
|
||||
this.set('EXTRACTION_ENABLE_DB_PERSISTENCE', settings.extraction.enableDbPersistence)
|
||||
|
||||
// Validation settings
|
||||
this.set('VALIDATION_DATA_SOURCE', settings.validation.dataSource)
|
||||
this.set('VALIDATION_BATCH_SIZE', settings.validation.batchSize)
|
||||
this.set('VALIDATION_MATCH_MODE', settings.validation.matchMode)
|
||||
this.set('VALIDATION_ENABLE_CRUD', settings.validation.enableCrud)
|
||||
this.set('VALIDATION_DEFAULT_MANAGER', settings.validation.defaultManager)
|
||||
|
||||
// UI settings
|
||||
this.set('UI_FONT_FAMILY', settings.ui.fontFamily)
|
||||
this.set('UI_FONT_SIZE', settings.ui.fontSize)
|
||||
this.set('UI_PRODUCTION_ID_INPUT_WIDTH', settings.ui.productionIdInputWidth)
|
||||
|
||||
// Execution settings
|
||||
this.set('EXECUTION_DRYRUN', settings.execution.dryRun)
|
||||
|
||||
return this.save()
|
||||
const { activeType, mysql, sqlserver } = this.config.database
|
||||
return activeType === 'mysql' ? mysql : sqlserver
|
||||
}
|
||||
|
||||
/**
|
||||
* Save partial settings (only update provided fields)
|
||||
* Preserves all existing fields not included in the update
|
||||
* 获取数据库类型
|
||||
*/
|
||||
public async savePartialSettings(
|
||||
settings: Partial<SettingsData>
|
||||
public getDatabaseType(): DatabaseType {
|
||||
if (!this.config) {
|
||||
throw new Error('Configuration not initialized')
|
||||
}
|
||||
return this.config.database.activeType
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日志配置
|
||||
*/
|
||||
public getLoggingConfig(): LoggingConfig {
|
||||
if (!this.config) {
|
||||
throw new Error('Configuration not initialized')
|
||||
}
|
||||
return this.config.logging
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新部分配置(深合并)
|
||||
*/
|
||||
public async updateConfig(
|
||||
updates: Partial<FullConfig>
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
// Step 1: Validate field whitelist
|
||||
const validation = validateEditableFields(settings)
|
||||
if (!validation.valid) {
|
||||
log.warn('Attempted to save non-editable fields', {
|
||||
invalidFields: validation.invalidFields
|
||||
})
|
||||
return {
|
||||
success: false,
|
||||
error: `包含不允许修改的字段:${validation.invalidFields.join(', ')}`
|
||||
}
|
||||
if (!this.config) {
|
||||
await this.loadConfig()
|
||||
}
|
||||
|
||||
// Step 2: Read current settings from .env file directly
|
||||
// This avoids the cache key mismatch issue (ERP_URL vs erp.url)
|
||||
await this.loadEnvFile()
|
||||
const currentSettings = this.getAllSettings()
|
||||
// 深合并
|
||||
const merged = this.deepMerge(this.config!, updates)
|
||||
|
||||
log.info('Current settings before merge', {
|
||||
erpUrl: currentSettings.erp.url,
|
||||
dbType: currentSettings.database.dbType,
|
||||
dbName: currentSettings.database.database
|
||||
})
|
||||
// 验证合并后的配置
|
||||
const validated = fullConfigSchema.parse(merged)
|
||||
|
||||
// Step 3: Deep merge - only update provided fields
|
||||
const mergedSettings = deepMerge(currentSettings, settings)
|
||||
|
||||
log.info('Settings after merge', {
|
||||
erpUrl: mergedSettings.erp.url,
|
||||
dbType: mergedSettings.database.dbType,
|
||||
dbName: mergedSettings.database.database
|
||||
})
|
||||
|
||||
// Step 4: Backup and save
|
||||
const backupSuccess = await this.backupEnvFile()
|
||||
if (!backupSuccess) {
|
||||
log.warn('Failed to backup .env file, proceeding with caution')
|
||||
const success = await this.saveConfig(validated)
|
||||
if (!success) {
|
||||
return { success: false, error: '保存配置失败' }
|
||||
}
|
||||
|
||||
const saveSuccess = await this.saveAllSettings(mergedSettings)
|
||||
|
||||
if (!saveSuccess) {
|
||||
// Save failed, attempt restore
|
||||
await this.restoreBackup()
|
||||
return {
|
||||
success: false,
|
||||
error: '保存配置失败,已恢复原配置'
|
||||
}
|
||||
}
|
||||
|
||||
// Step 5: Reload from disk to populate cache with correct keys (ERP_URL instead of erp.url)
|
||||
await this.loadEnvFile()
|
||||
|
||||
log.info('Settings saved successfully', {
|
||||
updatedFields: Object.keys(settings)
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Error in savePartialSettings', { error: message })
|
||||
await this.restoreBackup()
|
||||
return {
|
||||
success: false,
|
||||
error: `保存配置时发生错误:${message}`
|
||||
if (error instanceof z.ZodError) {
|
||||
const messages = error.issues.map((e: any) => `${e.path.join('.')}: ${e.message}`)
|
||||
return { success: false, error: `配置验证失败:\n${messages.join('\n')}` }
|
||||
}
|
||||
return { success: false, error: error instanceof Error ? error.message : '未知错误' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset to default settings
|
||||
* 深合并工具函数
|
||||
*/
|
||||
public resetToDefaults(): SettingsData {
|
||||
// Clear cache and reload from defaults
|
||||
this.configCache.clear()
|
||||
|
||||
// Set all defaults using underscore uppercase keys
|
||||
this.set('ERP_URL', DEFAULT_SETTINGS.erp.url)
|
||||
this.set('ERP_USERNAME', DEFAULT_SETTINGS.erp.username)
|
||||
this.set('ERP_PASSWORD', DEFAULT_SETTINGS.erp.password)
|
||||
this.set('ERP_HEADLESS', DEFAULT_SETTINGS.erp.headless)
|
||||
this.set('ERP_IGNORE_HTTPS_ERRORS', DEFAULT_SETTINGS.erp.ignoreHttpsErrors)
|
||||
this.set('ERP_AUTO_CLOSE_BROWSER', DEFAULT_SETTINGS.erp.autoCloseBrowser)
|
||||
|
||||
this.set('DB_TYPE', DEFAULT_SETTINGS.database.dbType)
|
||||
this.set('DB_SERVER', DEFAULT_SETTINGS.database.server)
|
||||
this.set('DB_MYSQL_HOST', DEFAULT_SETTINGS.database.mysqlHost)
|
||||
this.set('DB_MYSQL_PORT', DEFAULT_SETTINGS.database.mysqlPort)
|
||||
this.set('DB_NAME', DEFAULT_SETTINGS.database.database)
|
||||
this.set('DB_USERNAME', DEFAULT_SETTINGS.database.username)
|
||||
this.set('DB_PASSWORD', DEFAULT_SETTINGS.database.password)
|
||||
|
||||
this.set('PATH_DATA_DIR', DEFAULT_SETTINGS.paths.dataDir)
|
||||
this.set('PATH_DEFAULT_OUTPUT', DEFAULT_SETTINGS.paths.defaultOutput)
|
||||
this.set('PATH_VALIDATION_OUTPUT', DEFAULT_SETTINGS.paths.validationOutput)
|
||||
|
||||
this.set('EXTRACTION_BATCH_SIZE', DEFAULT_SETTINGS.extraction.batchSize)
|
||||
this.set('EXTRACTION_VERBOSE', DEFAULT_SETTINGS.extraction.verbose)
|
||||
this.set('EXTRACTION_AUTO_CONVERT', DEFAULT_SETTINGS.extraction.autoConvert)
|
||||
this.set('EXTRACTION_MERGE_BATCHES', DEFAULT_SETTINGS.extraction.mergeBatches)
|
||||
this.set('EXTRACTION_ENABLE_DB_PERSISTENCE', DEFAULT_SETTINGS.extraction.enableDbPersistence)
|
||||
|
||||
this.set('VALIDATION_DATA_SOURCE', DEFAULT_SETTINGS.validation.dataSource)
|
||||
this.set('VALIDATION_BATCH_SIZE', DEFAULT_SETTINGS.validation.batchSize)
|
||||
this.set('VALIDATION_MATCH_MODE', DEFAULT_SETTINGS.validation.matchMode)
|
||||
this.set('VALIDATION_ENABLE_CRUD', DEFAULT_SETTINGS.validation.enableCrud)
|
||||
this.set('VALIDATION_DEFAULT_MANAGER', DEFAULT_SETTINGS.validation.defaultManager)
|
||||
|
||||
this.set('UI_FONT_FAMILY', DEFAULT_SETTINGS.ui.fontFamily)
|
||||
this.set('UI_FONT_SIZE', DEFAULT_SETTINGS.ui.fontSize)
|
||||
this.set('UI_PRODUCTION_ID_INPUT_WIDTH', DEFAULT_SETTINGS.ui.productionIdInputWidth)
|
||||
|
||||
this.set('EXECUTION_DRYRUN', DEFAULT_SETTINGS.execution.dryRun)
|
||||
|
||||
return DEFAULT_SETTINGS
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default settings
|
||||
*/
|
||||
public getDefaultSettings(): SettingsData {
|
||||
return DEFAULT_SETTINGS
|
||||
}
|
||||
|
||||
/**
|
||||
* Backup current .env file
|
||||
*/
|
||||
private async backupEnvFile(): Promise<boolean> {
|
||||
try {
|
||||
if (fs.existsSync(this.envPath)) {
|
||||
fs.copyFileSync(this.envPath, this.backupPath)
|
||||
log.debug('Backup created', { path: this.backupPath })
|
||||
return true
|
||||
private deepMerge<T extends Record<string, any>>(source: T, target: Partial<T>): T {
|
||||
const result = { ...source }
|
||||
for (const key in target) {
|
||||
if (target[key] !== undefined) {
|
||||
if (
|
||||
typeof target[key] === 'object' &&
|
||||
target[key] !== null &&
|
||||
!Array.isArray(target[key])
|
||||
) {
|
||||
result[key] = this.deepMerge(result[key] as any, target[key] as any)
|
||||
} else {
|
||||
result[key] = target[key] as any
|
||||
}
|
||||
}
|
||||
return false
|
||||
} catch (error) {
|
||||
log.error('Failed to backup .env file', { error })
|
||||
return false
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore .env file from backup
|
||||
* 重置为默认配置
|
||||
*/
|
||||
private async restoreBackup(): Promise<boolean> {
|
||||
try {
|
||||
if (fs.existsSync(this.backupPath)) {
|
||||
fs.copyFileSync(this.backupPath, this.envPath)
|
||||
await this.loadEnvFile()
|
||||
log.debug('Restored from backup')
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} catch (error) {
|
||||
log.error('Failed to restore backup', { error })
|
||||
return false
|
||||
public async resetToDefaults(): Promise<boolean> {
|
||||
return this.saveConfig(DEFAULT_CONFIG)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认配置
|
||||
*/
|
||||
public getDefaultConfig(): FullConfig {
|
||||
return DEFAULT_CONFIG
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出配置为 YAML 字符串(用于 UI 显示或导出)
|
||||
*/
|
||||
public exportToYaml(): string {
|
||||
if (!this.config) {
|
||||
throw new Error('Configuration not initialized')
|
||||
}
|
||||
return yaml.dump(this.config, {
|
||||
indent: 2,
|
||||
lineWidth: -1,
|
||||
noRefs: true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
299
src/main/services/database/data-importer.ts
Normal file
299
src/main/services/database/data-importer.ts
Normal file
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Data Import Service
|
||||
*
|
||||
* Reads Excel files and imports data to the DiscreteMaterialPlanData table.
|
||||
* Workflow:
|
||||
* 1. Read Excel file
|
||||
* 2. Extract unique SourceNumbers
|
||||
* 3. Delete existing records by SourceNumber
|
||||
* 4. Batch insert new records
|
||||
*/
|
||||
|
||||
import { createLogger } from '../logger'
|
||||
import { DiscreteMaterialPlanDAO, type MaterialPlanRecord } from './discrete-material-plan-dao'
|
||||
|
||||
const log = createLogger('DataImportService')
|
||||
|
||||
/**
|
||||
* Excel column header to database field mapping
|
||||
*/
|
||||
const EXCEL_TO_DB_MAPPING: Record<string, keyof MaterialPlanRecord> = {
|
||||
工厂: 'factory',
|
||||
备料状态: 'materialStatus',
|
||||
备料计划单号: 'planNumber',
|
||||
来源单号: 'sourceNumber',
|
||||
备料类型: 'materialType',
|
||||
产品编码: 'productCode',
|
||||
产品名称: 'productName',
|
||||
产品计划数量: 'productPlanQuantity',
|
||||
产品单位: 'productUnit',
|
||||
用料部门: 'useDepartment',
|
||||
备注: 'remark',
|
||||
制单人: 'creator',
|
||||
制单日期: 'createDate',
|
||||
审批人: 'approver',
|
||||
审批日期: 'approveDate',
|
||||
序号: 'sequenceNumber',
|
||||
材料编码: 'materialCode',
|
||||
材料名称: 'materialName',
|
||||
规格: 'specification',
|
||||
型号: 'model',
|
||||
图号: 'drawingNumber',
|
||||
物料材质: 'materialQuality',
|
||||
计划数量: 'planQuantity',
|
||||
单位: 'unit',
|
||||
需用日期: 'requiredDate',
|
||||
发料仓库: 'warehouse',
|
||||
单位用量: 'unitUsage',
|
||||
累计出库数量: 'cumulativeOutputQuantity'
|
||||
// Note: '打印人', '打印日期' are skipped (not in DB)
|
||||
// Note: 'BOMVersion' is skipped (not in Excel)
|
||||
}
|
||||
|
||||
/**
|
||||
* Import result
|
||||
*/
|
||||
export interface ImportResult {
|
||||
success: boolean
|
||||
recordsRead: number
|
||||
recordsDeleted: number
|
||||
recordsImported: number
|
||||
uniqueSourceNumbers: number
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* DataImportService class
|
||||
*/
|
||||
export class DataImportService {
|
||||
private dao: DiscreteMaterialPlanDAO
|
||||
|
||||
constructor() {
|
||||
this.dao = new DiscreteMaterialPlanDAO()
|
||||
}
|
||||
|
||||
/**
|
||||
* Import data from Excel file to database
|
||||
* @param filePath - Path to the Excel file
|
||||
* @param batchSize - Number of records per insert batch (default: 1000)
|
||||
* @returns Import result with statistics
|
||||
*/
|
||||
async importFromExcel(filePath: string, batchSize = 1000): Promise<ImportResult> {
|
||||
const result: ImportResult = {
|
||||
success: false,
|
||||
recordsRead: 0,
|
||||
recordsDeleted: 0,
|
||||
recordsImported: 0,
|
||||
uniqueSourceNumbers: 0,
|
||||
errors: []
|
||||
}
|
||||
|
||||
try {
|
||||
log.info('Starting import from Excel', { filePath, batchSize })
|
||||
|
||||
// Step 1: Read Excel file
|
||||
log.info('Reading Excel file...')
|
||||
const { records, sourceNumbers } = await this.readExcelFile(filePath)
|
||||
result.recordsRead = records.length
|
||||
result.uniqueSourceNumbers = sourceNumbers.size
|
||||
|
||||
log.info('Excel read completed', {
|
||||
recordsRead: result.recordsRead,
|
||||
uniqueSourceNumbers: result.uniqueSourceNumbers
|
||||
})
|
||||
|
||||
if (records.length === 0) {
|
||||
result.success = true
|
||||
result.errors.push('Excel file contains no data records')
|
||||
return result
|
||||
}
|
||||
|
||||
// Step 2: Delete existing records by SourceNumber
|
||||
log.info('Deleting existing records...', {
|
||||
sourceNumberCount: sourceNumbers.size
|
||||
})
|
||||
|
||||
const sourceNumberArray = Array.from(sourceNumbers)
|
||||
result.recordsDeleted = await this.dao.deleteBySourceNumbers(sourceNumberArray)
|
||||
|
||||
log.info('Existing records deleted', {
|
||||
recordsDeleted: result.recordsDeleted
|
||||
})
|
||||
|
||||
// Step 3: Batch insert new records
|
||||
log.info('Inserting new records...', {
|
||||
recordCount: records.length,
|
||||
batchSize
|
||||
})
|
||||
|
||||
result.recordsImported = await this.dao.batchInsert(records, batchSize)
|
||||
|
||||
log.info('Records imported successfully', {
|
||||
recordsImported: result.recordsImported
|
||||
})
|
||||
|
||||
result.success = true
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error)
|
||||
result.errors.push(`Import failed: ${errorMsg}`)
|
||||
log.error('Import failed', { error: errorMsg })
|
||||
} finally {
|
||||
// Disconnect DAO
|
||||
try {
|
||||
await this.dao.disconnect()
|
||||
} catch (e) {
|
||||
log.warn('Error disconnecting DAO', {
|
||||
error: e instanceof Error ? e.message : String(e)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Excel file and extract records
|
||||
* @param filePath - Path to the Excel file
|
||||
* @returns Records and unique SourceNumbers
|
||||
*/
|
||||
private async readExcelFile(
|
||||
filePath: string
|
||||
): Promise<{ records: MaterialPlanRecord[]; sourceNumbers: Set<string> }> {
|
||||
const records: MaterialPlanRecord[] = []
|
||||
const sourceNumbers = new Set<string>()
|
||||
|
||||
// Dynamic import ExcelJS
|
||||
const ExcelJSModule = await import('exceljs')
|
||||
const ExcelJS = (ExcelJSModule as any).default || ExcelJSModule
|
||||
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.readFile(filePath)
|
||||
|
||||
// Get first worksheet
|
||||
const worksheet = workbook.worksheets[0]
|
||||
if (!worksheet) {
|
||||
throw new Error('Excel file has no worksheets')
|
||||
}
|
||||
|
||||
// Get header row to map column indices
|
||||
const headerRow = worksheet.getRow(1)
|
||||
const columnMapping = this.buildColumnMapping(headerRow)
|
||||
|
||||
log.debug('Column mapping built', {
|
||||
columnCount: Object.keys(columnMapping).length
|
||||
})
|
||||
|
||||
// Iterate through data rows (starting from row 2)
|
||||
worksheet.eachRow((row: any, rowNumber: number) => {
|
||||
if (rowNumber === 1) return // Skip header row
|
||||
|
||||
try {
|
||||
const record = this.buildRecordFromRow(row, columnMapping)
|
||||
if (record) {
|
||||
records.push(record)
|
||||
if (record.sourceNumber) {
|
||||
sourceNumbers.add(record.sourceNumber)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
log.warn('Failed to parse row', {
|
||||
rowNumber,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return { records, sourceNumbers }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build column index to field name mapping from header row
|
||||
*/
|
||||
private buildColumnMapping(headerRow: any): Map<number, keyof MaterialPlanRecord> {
|
||||
const mapping = new Map<number, keyof MaterialPlanRecord>()
|
||||
|
||||
headerRow.eachCell((cell: any, colNumber: number) => {
|
||||
const headerText = cell.text?.toString().trim()
|
||||
if (headerText && EXCEL_TO_DB_MAPPING[headerText]) {
|
||||
mapping.set(colNumber, EXCEL_TO_DB_MAPPING[headerText])
|
||||
}
|
||||
})
|
||||
|
||||
return mapping
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a MaterialPlanRecord from an Excel row
|
||||
*/
|
||||
private buildRecordFromRow(
|
||||
row: any,
|
||||
columnMapping: Map<number, keyof MaterialPlanRecord>
|
||||
): MaterialPlanRecord | null {
|
||||
const record: Partial<MaterialPlanRecord> = {}
|
||||
|
||||
row.eachCell((cell: any, colNumber: number) => {
|
||||
const fieldName = columnMapping.get(colNumber)
|
||||
if (!fieldName) return
|
||||
|
||||
const value = this.parseCellValue(cell, fieldName)
|
||||
record[fieldName] = value as any
|
||||
})
|
||||
|
||||
// Validate required fields
|
||||
if (!record.planNumber) {
|
||||
return null // Skip records without PlanNumber
|
||||
}
|
||||
|
||||
return record as MaterialPlanRecord
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse cell value based on field type
|
||||
*/
|
||||
private parseCellValue(cell: any, fieldName: keyof MaterialPlanRecord): any {
|
||||
const text = cell.text?.toString().trim()
|
||||
const value = cell.value
|
||||
|
||||
// Return null for empty cells
|
||||
if (!text || text === '') {
|
||||
return null
|
||||
}
|
||||
|
||||
// Handle numeric fields
|
||||
const numericFields: (keyof MaterialPlanRecord)[] = [
|
||||
'productPlanQuantity',
|
||||
'sequenceNumber',
|
||||
'planQuantity',
|
||||
'unitUsage',
|
||||
'cumulativeOutputQuantity'
|
||||
]
|
||||
|
||||
if (numericFields.includes(fieldName)) {
|
||||
const num = parseFloat(text)
|
||||
return isNaN(num) ? null : num
|
||||
}
|
||||
|
||||
// Handle date fields
|
||||
const dateFields: (keyof MaterialPlanRecord)[] = ['createDate', 'approveDate', 'requiredDate']
|
||||
|
||||
if (dateFields.includes(fieldName)) {
|
||||
// ExcelJS returns date as Date object if recognized
|
||||
if (value instanceof Date) {
|
||||
return value
|
||||
}
|
||||
// Try to parse date string
|
||||
const date = new Date(text)
|
||||
return isNaN(date.getTime()) ? null : date
|
||||
}
|
||||
|
||||
// Handle string fields
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a DataImportService instance
|
||||
*/
|
||||
export function createDataImportService(): DataImportService {
|
||||
return new DataImportService()
|
||||
}
|
||||
@@ -2,21 +2,23 @@
|
||||
* TypeORM Data Source Configuration
|
||||
*
|
||||
* Provides a centralized database connection for TypeORM entities.
|
||||
* Supports both MySQL and SQL Server based on DB_TYPE environment variable.
|
||||
* Supports both MySQL and SQL Server based on configuration.
|
||||
*
|
||||
* Note: Configuration is now loaded from config.yaml via ConfigManager,
|
||||
* not from environment variables.
|
||||
*/
|
||||
|
||||
import 'reflect-metadata'
|
||||
import { DataSource, DataSourceOptions } from 'typeorm'
|
||||
import { ConfigManager } from '../config/config-manager'
|
||||
|
||||
/**
|
||||
* Get database type from environment
|
||||
* Get database type from config manager
|
||||
*/
|
||||
function getDatabaseType(): 'mysql' | 'mssql' {
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
if (dbType === 'sqlserver' || dbType === 'mssql') {
|
||||
return 'mssql'
|
||||
}
|
||||
return 'mysql'
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbType = configManager.getDatabaseType()
|
||||
return dbType === 'sqlserver' ? 'mssql' : 'mysql'
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -24,36 +26,40 @@ function getDatabaseType(): 'mysql' | 'mssql' {
|
||||
*/
|
||||
function buildDataSourceOptions(): DataSourceOptions {
|
||||
const type = getDatabaseType()
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
|
||||
const commonOptions: Partial<DataSourceOptions> = {
|
||||
entities: [__dirname + '/entities/*.{ts,js}'],
|
||||
synchronize: false, // Never auto-sync in production
|
||||
logging: process.env.NODE_ENV !== 'production'
|
||||
logging: false
|
||||
}
|
||||
|
||||
if (type === 'mssql') {
|
||||
const dbConfig = config.database.sqlserver
|
||||
return {
|
||||
type: 'mssql',
|
||||
host: process.env.DB_SERVER || 'localhost',
|
||||
port: parseInt(process.env.DB_SQLSERVER_PORT || '1433', 10),
|
||||
username: process.env.DB_USERNAME || 'sa',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || '',
|
||||
host: dbConfig.server,
|
||||
port: dbConfig.port,
|
||||
username: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
options: {
|
||||
encrypt: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes',
|
||||
trustServerCertificate: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
|
||||
encrypt: false,
|
||||
trustServerCertificate: dbConfig.trustServerCertificate
|
||||
},
|
||||
...commonOptions
|
||||
} as DataSourceOptions
|
||||
}
|
||||
|
||||
const dbConfig = config.database.mysql
|
||||
return {
|
||||
type: 'mysql',
|
||||
host: process.env.DB_MYSQL_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
|
||||
username: process.env.DB_USERNAME || 'root',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || '',
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
username: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
...commonOptions
|
||||
} as DataSourceOptions
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ export class DiscreteMaterialPlanDAO {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const isSqlServer = dbService.type === 'sqlserver'
|
||||
const batchSize = 2000
|
||||
const batchSize = 1500
|
||||
const allResults: any[] = []
|
||||
|
||||
for (let i = 0; i < sourceNumbers.length; i += batchSize) {
|
||||
@@ -250,7 +250,7 @@ export class DiscreteMaterialPlanDAO {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const isSqlServer = dbService.type === 'sqlserver'
|
||||
const batchSize = 2000
|
||||
const batchSize = 1500
|
||||
const allResults: any[] = []
|
||||
|
||||
for (let i = 0; i < sourceNumbers.length; i += batchSize) {
|
||||
@@ -365,16 +365,24 @@ export class DiscreteMaterialPlanDAO {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const isSqlServer = dbService.type === 'sqlserver'
|
||||
const placeholders = this.buildPlaceholders(planNumbers.length, isSqlServer)
|
||||
const batchSize = 1500
|
||||
const allResults: any[] = []
|
||||
|
||||
const sqlString = `
|
||||
SELECT *
|
||||
FROM ${tableName}
|
||||
WHERE PlanNumber IN (${placeholders})
|
||||
`
|
||||
for (let i = 0; i < planNumbers.length; i += batchSize) {
|
||||
const batch = planNumbers.slice(i, i + batchSize)
|
||||
const placeholders = this.buildPlaceholders(batch.length, isSqlServer)
|
||||
|
||||
const result = await dbService.query(sqlString, planNumbers)
|
||||
return result.rows
|
||||
const sqlString = `
|
||||
SELECT *
|
||||
FROM ${tableName}
|
||||
WHERE PlanNumber IN (${placeholders})
|
||||
`
|
||||
|
||||
const result = await dbService.query(sqlString, batch)
|
||||
allResults.push(...result.rows)
|
||||
}
|
||||
|
||||
return allResults
|
||||
} catch (error) {
|
||||
log.error('Query by plan numbers error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
@@ -383,6 +391,263 @@ export class DiscreteMaterialPlanDAO {
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DELETE OPERATIONS ====================
|
||||
|
||||
/**
|
||||
* Delete records by SourceNumber list
|
||||
* Uses batch processing for large lists
|
||||
* @param sourceNumbers - List of SourceNumber values to delete
|
||||
* @returns Number of records deleted
|
||||
*/
|
||||
async deleteBySourceNumbers(sourceNumbers: string[]): Promise<number> {
|
||||
if (!sourceNumbers || sourceNumbers.length === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
try {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const isSqlServer = dbService.type === 'sqlserver'
|
||||
const batchSize = 2000
|
||||
let totalDeleted = 0
|
||||
|
||||
// Get unique source numbers
|
||||
const uniqueSourceNumbers = [...new Set(sourceNumbers.filter(Boolean))]
|
||||
|
||||
for (let i = 0; i < uniqueSourceNumbers.length; i += batchSize) {
|
||||
const batch = uniqueSourceNumbers.slice(i, i + batchSize)
|
||||
const placeholders = this.buildPlaceholders(batch.length, isSqlServer)
|
||||
|
||||
const sqlString = `
|
||||
DELETE FROM ${tableName}
|
||||
WHERE SourceNumber IN (${placeholders})
|
||||
`
|
||||
|
||||
const result = await dbService.query(sqlString, batch)
|
||||
totalDeleted += result.rowCount || 0
|
||||
|
||||
log.debug('Deleted batch', {
|
||||
batch: i / batchSize + 1,
|
||||
count: result.rowCount
|
||||
})
|
||||
}
|
||||
|
||||
log.info('Deleted records by source numbers', {
|
||||
totalDeleted,
|
||||
sourceNumberCount: uniqueSourceNumbers.length
|
||||
})
|
||||
|
||||
return totalDeleted
|
||||
} catch (error) {
|
||||
log.error('Delete by source numbers error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== INSERT OPERATIONS ====================
|
||||
|
||||
/**
|
||||
* Insert records in batches
|
||||
* @param records - List of MaterialPlanRecord to insert
|
||||
* @param batchSize - Number of records per batch (default: 1000, auto-adjusted for SQL Server)
|
||||
* @returns Number of records inserted
|
||||
*/
|
||||
async batchInsert(records: MaterialPlanRecord[], batchSize = 1000): Promise<number> {
|
||||
if (!records || records.length === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
try {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const isSqlServer = dbService.type === 'sqlserver'
|
||||
let totalInserted = 0
|
||||
|
||||
// SQL Server has a limit of 2100 parameters per query
|
||||
// Each record has 28 columns, so max rows per batch = 2100 / 28 = 75
|
||||
// Leave some margin for query overhead
|
||||
const columnsPerRow = 28
|
||||
const sqlServerMaxParams = 2000
|
||||
const effectiveBatchSize = isSqlServer
|
||||
? Math.min(batchSize, Math.floor(sqlServerMaxParams / columnsPerRow))
|
||||
: batchSize
|
||||
|
||||
log.info('Batch insert parameters', {
|
||||
isSqlServer,
|
||||
dbType: dbService.type,
|
||||
columnsPerRow,
|
||||
effectiveBatchSize,
|
||||
totalRecords: records.length
|
||||
})
|
||||
|
||||
// Process in batches
|
||||
for (let i = 0; i < records.length; i += effectiveBatchSize) {
|
||||
const batch = records.slice(i, i + effectiveBatchSize)
|
||||
const inserted = await this.insertBatch(dbService, tableName, batch, isSqlServer)
|
||||
totalInserted += inserted
|
||||
|
||||
log.debug('Inserted batch', {
|
||||
batch: Math.floor(i / effectiveBatchSize) + 1,
|
||||
count: inserted
|
||||
})
|
||||
}
|
||||
|
||||
log.info('Batch insert completed', {
|
||||
totalInserted,
|
||||
batchSize: effectiveBatchSize
|
||||
})
|
||||
|
||||
return totalInserted
|
||||
} catch (error) {
|
||||
log.error('Batch insert error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a single batch of records
|
||||
*/
|
||||
private async insertBatch(
|
||||
dbService: IDatabaseService,
|
||||
tableName: string,
|
||||
records: MaterialPlanRecord[],
|
||||
isSqlServer: boolean
|
||||
): Promise<number> {
|
||||
if (records.length === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
// Build column list (excluding id)
|
||||
const columns = [
|
||||
'Factory',
|
||||
'MaterialStatus',
|
||||
'PlanNumber',
|
||||
'SourceNumber',
|
||||
'MaterialType',
|
||||
'ProductCode',
|
||||
'ProductName',
|
||||
'ProductUnit',
|
||||
'ProductPlanQuantity',
|
||||
'UseDepartment',
|
||||
'Remark',
|
||||
'Creator',
|
||||
'CreateDate',
|
||||
'Approver',
|
||||
'ApproveDate',
|
||||
'SequenceNumber',
|
||||
'MaterialCode',
|
||||
'MaterialName',
|
||||
'Specification',
|
||||
'Model',
|
||||
'DrawingNumber',
|
||||
'MaterialQuality',
|
||||
'PlanQuantity',
|
||||
'Unit',
|
||||
'RequiredDate',
|
||||
'Warehouse',
|
||||
'UnitUsage',
|
||||
'CumulativeOutputQuantity'
|
||||
]
|
||||
|
||||
// Build parameterized insert
|
||||
const values: any[] = []
|
||||
const rowPlaceholders: string[] = []
|
||||
|
||||
records.forEach((record, rowIndex) => {
|
||||
const rowValues = this.buildRowValues(record, columns, rowIndex, isSqlServer, values)
|
||||
rowPlaceholders.push(`(${rowValues.join(',')})`)
|
||||
})
|
||||
|
||||
const sqlString = `
|
||||
INSERT INTO ${tableName} (${columns.join(', ')})
|
||||
VALUES ${rowPlaceholders.join(', ')}
|
||||
`
|
||||
|
||||
const result = await dbService.query(sqlString, values)
|
||||
return result.rowCount || records.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Build parameter values for a single row
|
||||
*/
|
||||
private buildRowValues(
|
||||
record: MaterialPlanRecord,
|
||||
columns: string[],
|
||||
_rowIndex: number,
|
||||
isSqlServer: boolean,
|
||||
values: any[]
|
||||
): string[] {
|
||||
return columns.map((col) => {
|
||||
const value = this.getColumnValue(record, col)
|
||||
values.push(value)
|
||||
|
||||
if (isSqlServer) {
|
||||
return `@p${values.length - 1}`
|
||||
} else {
|
||||
return '?'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for a specific column from the record
|
||||
*/
|
||||
private getColumnValue(record: MaterialPlanRecord, column: string): any {
|
||||
const columnMapping: Record<string, keyof MaterialPlanRecord> = {
|
||||
Factory: 'factory',
|
||||
MaterialStatus: 'materialStatus',
|
||||
PlanNumber: 'planNumber',
|
||||
SourceNumber: 'sourceNumber',
|
||||
MaterialType: 'materialType',
|
||||
ProductCode: 'productCode',
|
||||
ProductName: 'productName',
|
||||
ProductUnit: 'productUnit',
|
||||
ProductPlanQuantity: 'productPlanQuantity',
|
||||
UseDepartment: 'useDepartment',
|
||||
Remark: 'remark',
|
||||
Creator: 'creator',
|
||||
CreateDate: 'createDate',
|
||||
Approver: 'approver',
|
||||
ApproveDate: 'approveDate',
|
||||
SequenceNumber: 'sequenceNumber',
|
||||
MaterialCode: 'materialCode',
|
||||
MaterialName: 'materialName',
|
||||
Specification: 'specification',
|
||||
Model: 'model',
|
||||
DrawingNumber: 'drawingNumber',
|
||||
MaterialQuality: 'materialQuality',
|
||||
PlanQuantity: 'planQuantity',
|
||||
Unit: 'unit',
|
||||
RequiredDate: 'requiredDate',
|
||||
Warehouse: 'warehouse',
|
||||
UnitUsage: 'unitUsage',
|
||||
CumulativeOutputQuantity: 'cumulativeOutputQuantity'
|
||||
}
|
||||
|
||||
const key = columnMapping[column]
|
||||
if (!key) {
|
||||
return null
|
||||
}
|
||||
|
||||
const value = record[key]
|
||||
|
||||
// Handle null/undefined
|
||||
if (value === null || value === undefined) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Handle empty strings for string fields
|
||||
if (typeof value === 'string' && value.trim() === '') {
|
||||
return null
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
// ==================== UTILITY METHODS ====================
|
||||
|
||||
/**
|
||||
@@ -446,17 +711,25 @@ export class DiscreteMaterialPlanDAO {
|
||||
const isSqlServer = dbService.type === 'sqlserver'
|
||||
|
||||
if (sourceNumbers && sourceNumbers.length > 0) {
|
||||
const placeholders = this.buildPlaceholders(sourceNumbers.length, isSqlServer)
|
||||
const batchSize = 1500
|
||||
const allNames: string[] = []
|
||||
|
||||
const sqlString = `
|
||||
SELECT DISTINCT MaterialName
|
||||
FROM ${tableName}
|
||||
WHERE SourceNumber IN (${placeholders})
|
||||
AND MaterialName IS NOT NULL
|
||||
`
|
||||
for (let i = 0; i < sourceNumbers.length; i += batchSize) {
|
||||
const batch = sourceNumbers.slice(i, i + batchSize)
|
||||
const placeholders = this.buildPlaceholders(batch.length, isSqlServer)
|
||||
|
||||
const result = await dbService.query(sqlString, sourceNumbers)
|
||||
return result.rows.map((row) => row.MaterialName as string).filter(Boolean)
|
||||
const sqlString = `
|
||||
SELECT DISTINCT MaterialName
|
||||
FROM ${tableName}
|
||||
WHERE SourceNumber IN (${placeholders})
|
||||
AND MaterialName IS NOT NULL
|
||||
`
|
||||
|
||||
const result = await dbService.query(sqlString, batch)
|
||||
allNames.push(...result.rows.map((row) => row.MaterialName as string).filter(Boolean))
|
||||
}
|
||||
|
||||
return allNames
|
||||
} else {
|
||||
const sqlString = `
|
||||
SELECT DISTINCT MaterialName
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* Supports both MySQL and SQL Server databases.
|
||||
*/
|
||||
|
||||
import { ConfigManager } from '../config/config-manager'
|
||||
import { MySqlService } from './mysql'
|
||||
import { SqlServerService } from './sql-server'
|
||||
import type {
|
||||
@@ -23,42 +24,43 @@ const log = createLogger('DatabaseFactory')
|
||||
const instances: Map<DatabaseType, IDatabaseService> = new Map()
|
||||
|
||||
/**
|
||||
* Get the current database type from environment
|
||||
* Get the current database type from config manager
|
||||
*/
|
||||
export function getDatabaseType(): DatabaseType {
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
if (dbType === 'sqlserver' || dbType === 'mssql') {
|
||||
return 'sqlserver'
|
||||
}
|
||||
return 'mysql'
|
||||
const configManager = ConfigManager.getInstance()
|
||||
return configManager.getDatabaseType()
|
||||
}
|
||||
|
||||
/**
|
||||
* Create MySQL configuration from environment variables
|
||||
* Create MySQL configuration from config manager
|
||||
*/
|
||||
export function createMySqlConfig(): MySqlConfig {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbConfig = configManager.getConfig().database.mysql
|
||||
return {
|
||||
host: process.env.DB_MYSQL_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
|
||||
user: process.env.DB_USERNAME || 'root',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || ''
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create SQL Server configuration from environment variables
|
||||
* Create SQL Server configuration from config manager
|
||||
*/
|
||||
export function createSqlServerConfig(): SqlServerConfig {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const dbConfig = configManager.getConfig().database.sqlserver
|
||||
return {
|
||||
server: process.env.DB_SERVER || 'localhost',
|
||||
port: parseInt(process.env.DB_SQLSERVER_PORT || '1433', 10),
|
||||
user: process.env.DB_USERNAME || 'sa',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || '',
|
||||
server: dbConfig.server,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
options: {
|
||||
encrypt: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes',
|
||||
trustServerCertificate: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
|
||||
encrypt: false,
|
||||
trustServerCertificate: dbConfig.trustServerCertificate
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,7 +70,7 @@ export function createSqlServerConfig(): SqlServerConfig {
|
||||
*
|
||||
* Uses singleton pattern - returns cached instance if available.
|
||||
*
|
||||
* @param type - Optional database type override (defaults to DB_TYPE env var)
|
||||
* @param type - Optional database type override (defaults to config)
|
||||
* @returns Database service instance
|
||||
*/
|
||||
export async function create(type?: DatabaseType): Promise<IDatabaseService> {
|
||||
@@ -105,7 +107,7 @@ export async function create(type?: DatabaseType): Promise<IDatabaseService> {
|
||||
/**
|
||||
* Get existing database service without creating new one
|
||||
*
|
||||
* @param type - Optional database type (defaults to DB_TYPE env var)
|
||||
* @param type - Optional database type (defaults to config)
|
||||
* @returns Database service instance or undefined
|
||||
*/
|
||||
export function get(type?: DatabaseType): IDatabaseService | undefined {
|
||||
|
||||
@@ -216,6 +216,52 @@ export class MaterialsToBeDeletedDAO {
|
||||
return stats
|
||||
}
|
||||
|
||||
/**
|
||||
* Update manager for a single material
|
||||
* @param materialCode - Material code
|
||||
* @param managerName - New manager name
|
||||
* @returns Success status
|
||||
*/
|
||||
async updateManager(
|
||||
materialCode: string,
|
||||
managerName: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const isSqlServer = dbService.type === 'sqlserver'
|
||||
|
||||
if (isSqlServer) {
|
||||
const sqlString = `
|
||||
MERGE ${tableName} AS target
|
||||
USING (VALUES (@p0, @p1)) AS source (MaterialCode, ManagerName)
|
||||
ON target.MaterialCode = source.MaterialCode
|
||||
WHEN MATCHED THEN UPDATE SET ManagerName = source.ManagerName
|
||||
WHEN NOT MATCHED THEN INSERT (MaterialCode, ManagerName) VALUES (source.MaterialCode, source.ManagerName);
|
||||
`
|
||||
await dbService.query(sqlString, [materialCode, managerName || null])
|
||||
} else {
|
||||
const sqlString = `
|
||||
INSERT INTO ${tableName} (MaterialCode, ManagerName)
|
||||
VALUES (?, ?)
|
||||
ON DUPLICATE KEY UPDATE ManagerName = VALUES(ManagerName)
|
||||
`
|
||||
await dbService.query(sqlString, [materialCode, managerName || null])
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
log.error('Update manager error', {
|
||||
materialCode,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== READ ====================
|
||||
|
||||
/**
|
||||
|
||||
@@ -35,7 +35,7 @@ export class SqlServerService implements IDatabaseService {
|
||||
password: this.config.password,
|
||||
database: this.config.database,
|
||||
options: {
|
||||
encrypt: this.config.options?.encrypt ?? true,
|
||||
encrypt: this.config.options?.encrypt ?? false,
|
||||
trustServerCertificate: this.config.options?.trustServerCertificate ?? false
|
||||
}
|
||||
}
|
||||
@@ -92,8 +92,8 @@ export class SqlServerService implements IDatabaseService {
|
||||
|
||||
const result = await request.query(sqlString)
|
||||
|
||||
// Convert recordset to array of objects
|
||||
const rows = result.recordset as Record<string, unknown>[]
|
||||
// Convert recordset to array of objects (may be undefined for DELETE/INSERT/UPDATE)
|
||||
const rows = (result.recordset as Record<string, unknown>[]) || []
|
||||
// Extract column names from the first row if available
|
||||
const columns = rows.length > 0 ? Object.keys(rows[0]) : []
|
||||
|
||||
@@ -114,7 +114,13 @@ export class SqlServerService implements IDatabaseService {
|
||||
*/
|
||||
async queryWithParams(
|
||||
sqlString: string,
|
||||
params: Record<string, { value: unknown; type?: sql.ISqlType }>
|
||||
params: Record<
|
||||
string,
|
||||
{
|
||||
value: unknown
|
||||
type?: sql.ISqlType | sql.ISqlTypeFactoryWithLength | sql.ISqlTypeWithLength
|
||||
}
|
||||
>
|
||||
): Promise<QueryResult> {
|
||||
if (!this.pool) {
|
||||
throw new Error('Not connected to SQL Server. Call connect() first.')
|
||||
|
||||
@@ -90,7 +90,7 @@ export class ErpBrowserManager {
|
||||
const context = await browserInstance.newContext({
|
||||
acceptDownloads: this.config.acceptDownloads,
|
||||
viewport: this.config.viewport,
|
||||
ignoreHTTPSErrors: this.config.ignoreHTTPSErrors,
|
||||
ignoreHTTPSErrors: true,
|
||||
javaScriptEnabled: true
|
||||
})
|
||||
|
||||
|
||||
@@ -3,6 +3,51 @@ import { ErpAuthService } from './erp-auth'
|
||||
import type { CleanerInput, CleanerResult, OrderCleanDetail } from '../../types/cleaner.types'
|
||||
import type { ErpSession } from '../../types/erp.types'
|
||||
import type { FrameLocator, Locator, Page } from 'playwright'
|
||||
import { createLogger } from '../logger'
|
||||
|
||||
const log = createLogger('CleanerService')
|
||||
|
||||
const DEFAULT_QUERY_BATCH_SIZE = 100
|
||||
const MAX_QUERY_BATCH_SIZE = 100
|
||||
const DEFAULT_PROCESS_CONCURRENCY = 1
|
||||
const MAX_PROCESS_CONCURRENCY = 20
|
||||
|
||||
interface RetryResult {
|
||||
retriedOrders: number
|
||||
successfulRetries: number
|
||||
updatedDetails: OrderCleanDetail[]
|
||||
}
|
||||
|
||||
interface ProgressState {
|
||||
completedOrders: number
|
||||
totalOrders: number
|
||||
}
|
||||
|
||||
interface QueryResultRow {
|
||||
rowIndex: number
|
||||
orderNumber: string
|
||||
}
|
||||
|
||||
class AsyncMutex {
|
||||
private queue: Promise<void> = Promise.resolve()
|
||||
|
||||
async runExclusive<T>(task: () => Promise<T>): Promise<T> {
|
||||
let release!: () => void
|
||||
const next = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
|
||||
const previous = this.queue
|
||||
this.queue = this.queue.then(() => next)
|
||||
|
||||
await previous
|
||||
try {
|
||||
return await task()
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleaner Service Options
|
||||
@@ -22,11 +67,58 @@ export interface ShouldDeleteParams {
|
||||
deleteSet: Set<string>
|
||||
}
|
||||
|
||||
function clampNumber(
|
||||
value: number | undefined,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number
|
||||
): number {
|
||||
if (!Number.isFinite(value)) {
|
||||
return fallback
|
||||
}
|
||||
return Math.min(max, Math.max(min, Math.trunc(value ?? fallback)))
|
||||
}
|
||||
|
||||
export function createBatches<T>(items: T[], batchSize: number): T[][] {
|
||||
const batches: T[][] = []
|
||||
for (let i = 0; i < items.length; i += batchSize) {
|
||||
batches.push(items.slice(i, i + batchSize))
|
||||
}
|
||||
return batches
|
||||
}
|
||||
|
||||
export function getMissingOrders(inputOrders: string[], processedOrders: Set<string>): string[] {
|
||||
const uniqueInputOrders = Array.from(new Set(inputOrders))
|
||||
return uniqueInputOrders.filter((order) => !processedOrders.has(order))
|
||||
}
|
||||
|
||||
export async function runWithConcurrency<T, R>(
|
||||
items: T[],
|
||||
concurrency: number,
|
||||
worker: (item: T, index: number) => Promise<R>
|
||||
): Promise<R[]> {
|
||||
const results = new Array<R>(items.length)
|
||||
const limit = Math.max(1, Math.trunc(concurrency))
|
||||
let cursor = 0
|
||||
|
||||
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (true) {
|
||||
const current = cursor
|
||||
cursor += 1
|
||||
if (current >= items.length) {
|
||||
return
|
||||
}
|
||||
results[current] = await worker(items[current], current)
|
||||
}
|
||||
})
|
||||
|
||||
await Promise.all(runners)
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* ERP Cleaner Service
|
||||
* Deletes specified materials from production orders in ERP system
|
||||
*
|
||||
* Reference: playwrite/utils/discrete_material_plan_cleaner.py
|
||||
*/
|
||||
export class CleanerService {
|
||||
private authService: ErpAuthService
|
||||
@@ -46,27 +138,18 @@ export class CleanerService {
|
||||
|
||||
/**
|
||||
* Determine if a material should be deleted
|
||||
* Reference: Python lines 284-406
|
||||
*
|
||||
* Deletion conditions:
|
||||
* 1. Material code must be in the delete set
|
||||
* 2. Row number must NOT be in range 7000-7999
|
||||
* 3. Pending quantity must be empty
|
||||
*/
|
||||
shouldDeleteMaterial(params: ShouldDeleteParams): boolean {
|
||||
const { rowNumber, pendingQty, materialCode, deleteSet } = params
|
||||
|
||||
// Check if material is in delete list
|
||||
if (!deleteSet.has(materialCode)) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check row number range (7000-7999 are protected)
|
||||
if (rowNumber >= 7000 && rowNumber < 8000) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check pending quantity (must be empty)
|
||||
if (pendingQty && pendingQty.trim() !== '') {
|
||||
return false
|
||||
}
|
||||
@@ -74,99 +157,200 @@ export class CleanerService {
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the cleaning process
|
||||
* Reference: Python clean() method lines 456-525
|
||||
*/
|
||||
getSkipReason(params: ShouldDeleteParams): string {
|
||||
const { rowNumber, pendingQty, materialCode, deleteSet } = params
|
||||
|
||||
if (!deleteSet.has(materialCode)) {
|
||||
return '物料不在删除清单中'
|
||||
}
|
||||
if (rowNumber >= 7000 && rowNumber < 8000) {
|
||||
return '行号在 7000-7999 范围内(受保护)'
|
||||
}
|
||||
if (pendingQty && pendingQty.trim() !== '') {
|
||||
return '累计待发数量不为空'
|
||||
}
|
||||
return '未知原因'
|
||||
}
|
||||
|
||||
async clean(input: CleanerInput): Promise<CleanerResult> {
|
||||
const result: CleanerResult = {
|
||||
ordersProcessed: 0,
|
||||
materialsDeleted: 0,
|
||||
materialsSkipped: 0,
|
||||
errors: [],
|
||||
details: []
|
||||
details: [],
|
||||
retriedOrders: 0,
|
||||
successfulRetries: 0
|
||||
}
|
||||
|
||||
// Create delete set for O(1) lookup
|
||||
const totalOrders = input.orderNumbers.length
|
||||
const dryRun = input.dryRun ?? this.dryRun
|
||||
const queryBatchSize = clampNumber(
|
||||
input.queryBatchSize,
|
||||
DEFAULT_QUERY_BATCH_SIZE,
|
||||
1,
|
||||
MAX_QUERY_BATCH_SIZE
|
||||
)
|
||||
const processConcurrency = clampNumber(
|
||||
input.processConcurrency,
|
||||
DEFAULT_PROCESS_CONCURRENCY,
|
||||
1,
|
||||
MAX_PROCESS_CONCURRENCY
|
||||
)
|
||||
|
||||
log.info('Starting cleaner', {
|
||||
totalOrders,
|
||||
materialCount: input.materialCodes.length,
|
||||
dryRun,
|
||||
queryBatchSize,
|
||||
processConcurrency
|
||||
})
|
||||
|
||||
const deleteSet = new Set(input.materialCodes)
|
||||
|
||||
let popupPage: Page | null = null
|
||||
|
||||
try {
|
||||
const session = this.authService.getSession()
|
||||
const navigation = await this.navigateToCleanerPage(session)
|
||||
popupPage = navigation.popupPage
|
||||
const { workFrame } = navigation
|
||||
|
||||
// Navigate to cleaner page
|
||||
const { popupPage, workFrame } = await this.navigateToCleanerPage(session)
|
||||
|
||||
// Setup query interface
|
||||
await this.setupQueryInterface(workFrame)
|
||||
|
||||
// Process each order
|
||||
for (let i = 0; i < input.orderNumbers.length; i++) {
|
||||
const orderNumber = input.orderNumbers[i]
|
||||
const progress = ((i + 1) / input.orderNumbers.length) * 100
|
||||
const orderBatches = createBatches(input.orderNumbers, queryBatchSize)
|
||||
const popupMutex = new AsyncMutex()
|
||||
const progressState: ProgressState = {
|
||||
completedOrders: 0,
|
||||
totalOrders
|
||||
}
|
||||
|
||||
input.onProgress?.(
|
||||
`Processing order ${i + 1}/${input.orderNumbers.length}: ${orderNumber}`,
|
||||
progress
|
||||
)
|
||||
for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) {
|
||||
const batchOrders = orderBatches[batchIndex]
|
||||
|
||||
try {
|
||||
const detail = await this.processOrder({
|
||||
workFrame,
|
||||
popupPage,
|
||||
orderNumber,
|
||||
orderIndex: i,
|
||||
totalOrders: input.orderNumbers.length,
|
||||
deleteSet,
|
||||
dryRun: input.dryRun ?? this.dryRun,
|
||||
onProgress: input.onProgress
|
||||
log.info('Processing cleaner batch', {
|
||||
batchIndex: batchIndex + 1,
|
||||
totalBatches: orderBatches.length,
|
||||
batchSize: batchOrders.length
|
||||
})
|
||||
|
||||
await this.queryOrders(workFrame, batchOrders)
|
||||
await this.waitForLoading(workFrame)
|
||||
|
||||
const queriedRows = await this.collectQueryResultRows(workFrame)
|
||||
const queriedOrderNumbersInBatch = new Set(queriedRows.map((row) => row.orderNumber))
|
||||
|
||||
await runWithConcurrency(queriedRows, processConcurrency, async (row) => {
|
||||
const { rowIndex, orderNumber } = row
|
||||
const openedDetailPage = await popupMutex.runExclusive(async () => {
|
||||
return await this.openDetailPageFromRow(workFrame, popupPage!, rowIndex)
|
||||
})
|
||||
|
||||
let detail: OrderCleanDetail
|
||||
try {
|
||||
detail = await this.processDetailPage({
|
||||
detailPage: openedDetailPage,
|
||||
deleteSet,
|
||||
dryRun,
|
||||
expectedOrderNumber: orderNumber,
|
||||
progressState,
|
||||
onProgress: input.onProgress
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
detail = this.createErrorDetail(orderNumber, message)
|
||||
} finally {
|
||||
progressState.completedOrders += 1
|
||||
}
|
||||
|
||||
result.details.push(detail)
|
||||
result.ordersProcessed++
|
||||
|
||||
if (detail.errors.length > 0) {
|
||||
result.errors.push(`Order ${detail.orderNumber}: ${detail.errors.join('; ')}`)
|
||||
return
|
||||
}
|
||||
|
||||
result.ordersProcessed += 1
|
||||
result.materialsDeleted += detail.materialsDeleted
|
||||
result.materialsSkipped += detail.materialsSkipped
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
result.errors.push(`Order ${orderNumber}: ${message}`)
|
||||
})
|
||||
|
||||
// Add error detail
|
||||
result.details.push({
|
||||
orderNumber,
|
||||
materialsDeleted: 0,
|
||||
materialsSkipped: 0,
|
||||
errors: [message]
|
||||
})
|
||||
const missingOrders = getMissingOrders(batchOrders, queriedOrderNumbersInBatch)
|
||||
for (const missingOrder of missingOrders) {
|
||||
const missingMessage = '订单未出现在查询结果中'
|
||||
result.errors.push(`Order ${missingOrder}: ${missingMessage}`)
|
||||
result.details.push(this.createErrorDetail(missingOrder, missingMessage))
|
||||
}
|
||||
}
|
||||
|
||||
// Close popup page
|
||||
await popupPage.close()
|
||||
const retryResult = await this.retryFailedOrders({
|
||||
workFrame,
|
||||
popupPage,
|
||||
failedDetails: result.details.filter(
|
||||
(d) => d.errors.length > 0 && this.isOrderNumber(d.orderNumber)
|
||||
),
|
||||
deleteSet,
|
||||
dryRun,
|
||||
onProgress: input.onProgress
|
||||
})
|
||||
|
||||
result.retriedOrders = retryResult.retriedOrders
|
||||
result.successfulRetries = retryResult.successfulRetries
|
||||
|
||||
retryResult.updatedDetails.forEach((updatedDetail) => {
|
||||
const index = result.details.findIndex((d) => d.orderNumber === updatedDetail.orderNumber)
|
||||
if (index !== -1) {
|
||||
const previousDetail = result.details[index]
|
||||
if (updatedDetail.retrySuccess && previousDetail.errors.length > 0) {
|
||||
result.ordersProcessed += 1
|
||||
result.materialsDeleted += updatedDetail.materialsDeleted
|
||||
result.materialsSkipped += updatedDetail.materialsSkipped
|
||||
}
|
||||
result.details[index] = updatedDetail
|
||||
}
|
||||
})
|
||||
|
||||
const successfulRetryOrders = new Set(
|
||||
retryResult.updatedDetails.filter((d) => d.retrySuccess).map((d) => d.orderNumber)
|
||||
)
|
||||
result.errors = result.errors.filter(
|
||||
(err) => !successfulRetryOrders.has(err.split(':')[0].replace('Order ', ''))
|
||||
)
|
||||
|
||||
log.info('Cleaner completed', {
|
||||
ordersProcessed: result.ordersProcessed,
|
||||
materialsDeleted: result.materialsDeleted,
|
||||
materialsSkipped: result.materialsSkipped,
|
||||
errorCount: result.errors.length
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.error('Cleaner failed', { error: message })
|
||||
result.errors.push(`Clean failed: ${message}`)
|
||||
} finally {
|
||||
if (popupPage) {
|
||||
try {
|
||||
await popupPage.close()
|
||||
} catch {
|
||||
// Ignore close errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to the discrete production order maintenance page
|
||||
* Reference: Python lines 476-486
|
||||
*/
|
||||
async navigateToCleanerPage(
|
||||
session: ErpSession
|
||||
): Promise<{ popupPage: Page; workFrame: FrameLocator }> {
|
||||
const { page, mainFrame } = session
|
||||
|
||||
// Click menu icon (Python line 476)
|
||||
await mainFrame.locator('i').first().click()
|
||||
|
||||
// Click discrete production order menu item and expect popup (Python lines 477-479)
|
||||
const popupPromise = page.waitForEvent('popup')
|
||||
await mainFrame.getByTitle('离散生产订单维护', { exact: true }).first().click()
|
||||
const popupPage = await popupPromise
|
||||
|
||||
// Get nested frame structure (Python lines 482-486)
|
||||
const forwardFrameLocator = popupPage.locator('#forwardFrame')
|
||||
const fFrame = forwardFrameLocator.contentFrame()
|
||||
|
||||
@@ -174,82 +358,129 @@ export class CleanerService {
|
||||
await innerFrameLocator.waitFor({ state: 'visible', timeout: 30000 })
|
||||
const workFrame = innerFrameLocator.contentFrame()
|
||||
|
||||
// Wait for hot-key-head_list to be visible (Python line 484-486)
|
||||
await workFrame.locator('#hot-key-head_list').waitFor({ state: 'visible', timeout: 30000 })
|
||||
|
||||
return { popupPage, workFrame }
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup query interface
|
||||
* Reference: Python setup_query_interface() lines 445-454
|
||||
*/
|
||||
private async setupQueryInterface(innerFrame: FrameLocator): Promise<void> {
|
||||
// Click search icon (Python line 447)
|
||||
await innerFrame.locator('.search-name-wrapper > .iconfont').click()
|
||||
|
||||
// Click "订单号查询" menu item (Python line 448)
|
||||
await innerFrame.getByText('订单号查询').click()
|
||||
|
||||
// Click "全部" tab (Python line 449)
|
||||
await innerFrame.getByRole('tab', { name: '全部' }).click()
|
||||
|
||||
// Set limit to 5000 (Python lines 451-454)
|
||||
const inputEl = innerFrame.locator('#rc_select_0')
|
||||
await inputEl.fill('5000')
|
||||
await inputEl.press('Enter')
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single order
|
||||
* Reference: Python process_order() lines 171-443
|
||||
*/
|
||||
private async processOrder(params: {
|
||||
workFrame: FrameLocator
|
||||
popupPage: Page
|
||||
orderNumber: string
|
||||
orderIndex: number
|
||||
totalOrders: number
|
||||
deleteSet: Set<string>
|
||||
dryRun: boolean
|
||||
onProgress?: (message: string, progress?: number) => void
|
||||
}): Promise<OrderCleanDetail> {
|
||||
const {
|
||||
workFrame,
|
||||
popupPage,
|
||||
orderNumber,
|
||||
orderIndex,
|
||||
totalOrders,
|
||||
deleteSet,
|
||||
dryRun,
|
||||
onProgress
|
||||
} = params
|
||||
private async queryOrders(workFrame: FrameLocator, orderNumbers: string[]): Promise<void> {
|
||||
const textbox = workFrame.getByRole('textbox', { name: '生产订单号' })
|
||||
await textbox.fill(orderNumbers.join(','))
|
||||
await workFrame.locator('.search-component-searchBtn').click()
|
||||
}
|
||||
|
||||
const detail: OrderCleanDetail = {
|
||||
orderNumber,
|
||||
materialsDeleted: 0,
|
||||
materialsSkipped: 0,
|
||||
errors: []
|
||||
private async collectQueryResultRows(workFrame: FrameLocator): Promise<QueryResultRow[]> {
|
||||
const rows = workFrame.locator('tbody tr')
|
||||
const rowCount = await rows.count()
|
||||
const result: QueryResultRow[] = []
|
||||
|
||||
for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
|
||||
const row = rows.nth(rowIndex)
|
||||
const orderNumber = await this.extractOrderNumberFromQueryRow(row)
|
||||
if (!this.isOrderNumber(orderNumber)) {
|
||||
continue
|
||||
}
|
||||
result.push({ rowIndex, orderNumber })
|
||||
}
|
||||
|
||||
// Query the order (Python lines 187-189)
|
||||
const textbox = workFrame.getByRole('textbox', { name: '生产订单号' })
|
||||
await textbox.fill(orderNumber)
|
||||
await workFrame.locator('.search-component-searchBtn').click()
|
||||
return result
|
||||
}
|
||||
|
||||
// Wait for loading (Python lines 192-197)
|
||||
await this.waitForLoading(workFrame)
|
||||
private async extractOrderNumberFromQueryRow(row: Locator): Promise<string> {
|
||||
try {
|
||||
const cell = row.locator('td[colkey="vbillcode"]')
|
||||
const codeLink = cell.locator('.code-detail-link').first()
|
||||
const rawValue = (await codeLink.count()) > 0 ? await codeLink.innerText() : await cell.innerText()
|
||||
const value = rawValue.trim()
|
||||
const match = value.match(/SC\d{14}/)
|
||||
return match ? match[0] : value
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
// Click "更多" to open menu (Python line 200)
|
||||
await workFrame.locator('#hot-key-head_list').getByText('更多').click()
|
||||
private async openDetailPageFromRow(
|
||||
workFrame: FrameLocator,
|
||||
popupPage: Page,
|
||||
rowIndex: number
|
||||
): Promise<Page> {
|
||||
const row = workFrame.locator('tbody tr').nth(rowIndex)
|
||||
await row.waitFor({ state: 'visible', timeout: 15000 })
|
||||
|
||||
const moreButton = row.locator('a.row-more').first()
|
||||
await moreButton.scrollIntoViewIfNeeded()
|
||||
|
||||
// Click "备料计划" and expect popup (Python lines 201-203)
|
||||
const detailPagePromise = popupPage.waitForEvent('popup')
|
||||
await workFrame.getByText('备料计划').click()
|
||||
const detailPage = await detailPagePromise
|
||||
await moreButton.click()
|
||||
await this.clickMaterialPlanMenu(workFrame)
|
||||
|
||||
return await detailPagePromise
|
||||
}
|
||||
|
||||
private async openDetailPageFromCurrentQuery(
|
||||
workFrame: FrameLocator,
|
||||
popupPage: Page
|
||||
): Promise<Page> {
|
||||
const firstRow = workFrame.locator('tbody tr').first()
|
||||
await firstRow.waitFor({ state: 'visible', timeout: 10000 })
|
||||
|
||||
const moreButton = firstRow.locator('a.row-more').first()
|
||||
const detailPagePromise = popupPage.waitForEvent('popup')
|
||||
await moreButton.click()
|
||||
await this.clickMaterialPlanMenu(workFrame)
|
||||
|
||||
return await detailPagePromise
|
||||
}
|
||||
|
||||
private async clickMaterialPlanMenu(workFrame: FrameLocator): Promise<void> {
|
||||
const candidates = [
|
||||
workFrame.locator('li:visible, a:visible, span:visible, div:visible').filter({
|
||||
hasText: /^备料计划$/
|
||||
}),
|
||||
workFrame.getByRole('menuitem', { name: '备料计划' }),
|
||||
workFrame.getByText('备料计划', { exact: true }),
|
||||
workFrame.getByText('备料计划')
|
||||
]
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const target = candidate.last()
|
||||
try {
|
||||
await target.waitFor({ state: 'visible', timeout: 2000 })
|
||||
await target.click()
|
||||
return
|
||||
} catch {
|
||||
// Try next locator candidate
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('无法定位“备料计划”菜单项(可能菜单结构已变化)')
|
||||
}
|
||||
|
||||
private async processDetailPage(params: {
|
||||
detailPage: Page
|
||||
deleteSet: Set<string>
|
||||
dryRun: boolean
|
||||
progressState: ProgressState
|
||||
expectedOrderNumber?: string
|
||||
onProgress?: (
|
||||
message: string,
|
||||
progress?: number,
|
||||
extra?: Partial<import('../../types/cleaner.types').CleanerProgress>
|
||||
) => void
|
||||
}): Promise<OrderCleanDetail> {
|
||||
const { detailPage, deleteSet, dryRun, progressState, expectedOrderNumber, onProgress } = params
|
||||
|
||||
try {
|
||||
// Navigate nested frames in detail page (Python lines 206-207)
|
||||
const detailMainFrame = detailPage.locator('#forwardFrame')
|
||||
const dFrame = await detailMainFrame.contentFrame()
|
||||
|
||||
@@ -265,34 +496,58 @@ export class CleanerService {
|
||||
throw new Error('Failed to access detail inner frame')
|
||||
}
|
||||
|
||||
// Wait for plan code (Python lines 210-213)
|
||||
await detailInnerFrame
|
||||
.getByText(/^离散备料计划维护:/)
|
||||
.waitFor({ state: 'visible', timeout: 30000 })
|
||||
|
||||
// Extract detail count (Python lines 215-218)
|
||||
const sourceOrderNumber = await this.extractSourceOrderNumber(detailInnerFrame)
|
||||
const orderNumber = sourceOrderNumber || expectedOrderNumber || 'UNKNOWN_ORDER'
|
||||
|
||||
const detail: OrderCleanDetail = {
|
||||
orderNumber,
|
||||
materialsDeleted: 0,
|
||||
materialsSkipped: 0,
|
||||
errors: [],
|
||||
skippedMaterials: [],
|
||||
retryCount: 0,
|
||||
retryAttempts: [],
|
||||
retriedAt: undefined,
|
||||
retrySuccess: false
|
||||
}
|
||||
|
||||
const detailCountText = await detailInnerFrame.getByText(/^详细信息 \(\d+\)$/).innerText()
|
||||
const detailCountMatch = detailCountText.match(/\((\d+)\)/)
|
||||
const detailCount = detailCountMatch ? parseInt(detailCountMatch[1], 10) : 0
|
||||
|
||||
// Extract status (Python lines 220-225)
|
||||
const statusText = await detailInnerFrame.getByText(/^备料状态:.+$/).innerText()
|
||||
const statusMatch = statusText.replace(/\n/g, '').match(/备料状态:(.+)$/)
|
||||
const detailStatus = statusMatch ? statusMatch[1].trim() : ''
|
||||
|
||||
// Process based on status (Python lines 228-441)
|
||||
onProgress?.(
|
||||
`开始处理订单: ${orderNumber}`,
|
||||
this.calculateProgress(
|
||||
progressState.completedOrders,
|
||||
0,
|
||||
detailCount,
|
||||
progressState.totalOrders
|
||||
),
|
||||
{
|
||||
currentOrderIndex: progressState.completedOrders + 1,
|
||||
totalOrders: progressState.totalOrders,
|
||||
currentMaterialIndex: 0,
|
||||
totalMaterialsInOrder: detailCount,
|
||||
currentOrderNumber: orderNumber
|
||||
}
|
||||
)
|
||||
|
||||
if (detailStatus === '审批通过' && detailCount > 0) {
|
||||
// Click modify button (Python line 235)
|
||||
await detailInnerFrame.getByRole('button', { name: '修改' }).click()
|
||||
|
||||
// Wait for save button (Python lines 238-242)
|
||||
const saveButtonLocator = detailInnerFrame.getByRole('button', { name: '保存' })
|
||||
await saveButtonLocator.waitFor({ state: 'visible', timeout: 30000 })
|
||||
|
||||
// Expand the form (Python line 245)
|
||||
await detailInnerFrame.getByText('展开').first().click()
|
||||
|
||||
// Get form elements (Python lines 247-253)
|
||||
const childForm = detailInnerFrame.locator('.card-table-side-box')
|
||||
const buttonWrapper = childForm.locator('.button-wrapper')
|
||||
const deleteRowBtn = buttonWrapper.getByRole('button', { name: '删行' })
|
||||
@@ -302,11 +557,9 @@ export class CleanerService {
|
||||
let lastRowNumber = ''
|
||||
let materialIdx = 0
|
||||
|
||||
// Process each material row (Python lines 257-423)
|
||||
while (true) {
|
||||
materialIdx++
|
||||
materialIdx += 1
|
||||
|
||||
// Wait for row number to stabilize (Python lines 262-265)
|
||||
const currentRow = await this.getInputValue(childForm, /^行号$/)
|
||||
const rowNumInt = parseInt(currentRow, 10)
|
||||
|
||||
@@ -314,18 +567,29 @@ export class CleanerService {
|
||||
await this.delay(500)
|
||||
}
|
||||
|
||||
// Get material data (Python lines 267-271)
|
||||
const materialCode = await this.getInputValue(childForm, /^材料编码/)
|
||||
const materialName = await this.getInputValue(childForm, /^材料名称/)
|
||||
const pendingQty = await this.getInputValue(childForm, /^累计待发数量$/)
|
||||
|
||||
// Report progress
|
||||
onProgress?.(
|
||||
`Order ${orderNumber} - Material ${materialIdx}/${detailCount}: ${materialName}`,
|
||||
((orderIndex + materialIdx / detailCount) / totalOrders) * 100
|
||||
const progress = this.calculateProgress(
|
||||
progressState.completedOrders,
|
||||
materialIdx,
|
||||
detailCount,
|
||||
progressState.totalOrders
|
||||
)
|
||||
|
||||
onProgress?.(
|
||||
`订单 ${orderNumber} - 物料 ${materialIdx}/${detailCount}: ${materialName}`,
|
||||
progress,
|
||||
{
|
||||
currentOrderIndex: progressState.completedOrders + 1,
|
||||
totalOrders: progressState.totalOrders,
|
||||
currentMaterialIndex: materialIdx,
|
||||
totalMaterialsInOrder: detailCount,
|
||||
currentOrderNumber: orderNumber
|
||||
}
|
||||
)
|
||||
|
||||
// Check if should delete (Python lines 284-406)
|
||||
if (deleteSet.has(materialCode)) {
|
||||
const shouldDelete = this.shouldDeleteMaterial({
|
||||
rowNumber: rowNumInt,
|
||||
@@ -335,23 +599,34 @@ export class CleanerService {
|
||||
})
|
||||
|
||||
if (shouldDelete && !dryRun) {
|
||||
// Delete the material (Python lines 302-340)
|
||||
const oldRowNumber = currentRow
|
||||
await deleteRowBtn.click()
|
||||
|
||||
// Wait for row number to change (Python lines 306-324)
|
||||
const deleteSuccess = await this.waitForRowChange(childForm, oldRowNumber, 10000)
|
||||
|
||||
if (deleteSuccess) {
|
||||
detail.materialsDeleted++
|
||||
detail.materialsDeleted += 1
|
||||
}
|
||||
continue
|
||||
} else if (!shouldDelete) {
|
||||
detail.materialsSkipped++
|
||||
}
|
||||
|
||||
if (!shouldDelete) {
|
||||
detail.materialsSkipped += 1
|
||||
const reason = this.getSkipReason({
|
||||
rowNumber: rowNumInt,
|
||||
pendingQty,
|
||||
materialCode,
|
||||
deleteSet
|
||||
})
|
||||
detail.skippedMaterials.push({
|
||||
materialCode,
|
||||
materialName,
|
||||
rowNumber: rowNumInt,
|
||||
reason
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Move to next row (Python lines 419-423)
|
||||
const isNextEnabled = await this.isButtonEnabled(nextBtn)
|
||||
if (isNextEnabled) {
|
||||
lastRowNumber = currentRow
|
||||
@@ -361,27 +636,61 @@ export class CleanerService {
|
||||
}
|
||||
}
|
||||
|
||||
// Collapse form (Python line 424)
|
||||
await collapseBtn.click()
|
||||
|
||||
// Save changes (Python lines 427-435)
|
||||
if (!dryRun && detail.materialsDeleted > 0) {
|
||||
await saveButtonLocator.click()
|
||||
await saveButtonLocator.waitFor({ state: 'hidden', timeout: 60000 })
|
||||
}
|
||||
}
|
||||
|
||||
return detail
|
||||
} finally {
|
||||
// Close detail page (Python lines 442-443)
|
||||
await detailPage.close()
|
||||
}
|
||||
|
||||
return detail
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for loading overlay to disappear
|
||||
* Reference: Python lines 192-197
|
||||
*/
|
||||
private calculateProgress(
|
||||
completedOrders: number,
|
||||
materialIdx: number,
|
||||
detailCount: number,
|
||||
totalOrders: number
|
||||
): number {
|
||||
const materialRatio = detailCount > 0 ? materialIdx / detailCount : 0
|
||||
return ((1 + completedOrders + materialRatio) / (1 + totalOrders)) * 100
|
||||
}
|
||||
|
||||
private async extractSourceOrderNumber(frame: FrameLocator): Promise<string> {
|
||||
try {
|
||||
const sourceOrder = await frame
|
||||
.locator('.vsourcebillcode .code-detail-link')
|
||||
.first()
|
||||
.innerText()
|
||||
const match = sourceOrder.match(/SC\d{14}/)
|
||||
return match ? match[0] : sourceOrder.trim()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
private isOrderNumber(value: string): boolean {
|
||||
return /^SC\d{14}$/.test(value)
|
||||
}
|
||||
|
||||
private createErrorDetail(orderNumber: string, message: string): OrderCleanDetail {
|
||||
return {
|
||||
orderNumber,
|
||||
materialsDeleted: 0,
|
||||
materialsSkipped: 0,
|
||||
errors: [message],
|
||||
skippedMaterials: [],
|
||||
retryCount: 0,
|
||||
retryAttempts: [],
|
||||
retriedAt: undefined,
|
||||
retrySuccess: false
|
||||
}
|
||||
}
|
||||
|
||||
private async waitForLoading(frame: FrameLocator): Promise<void> {
|
||||
const loadingLocator = frame
|
||||
.locator('div')
|
||||
@@ -396,10 +705,6 @@ export class CleanerService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get input value by label regex
|
||||
* Reference: Python _get_input_value() lines 141-148
|
||||
*/
|
||||
private async getInputValue(
|
||||
container: FrameLocator | Locator,
|
||||
labelRegex: RegExp
|
||||
@@ -416,10 +721,6 @@ export class CleanerService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if button is enabled
|
||||
* Reference: Python _is_button_enabled() lines 133-139
|
||||
*/
|
||||
private async isButtonEnabled(button: Locator): Promise<boolean> {
|
||||
try {
|
||||
return await button.isEnabled()
|
||||
@@ -428,10 +729,6 @@ export class CleanerService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for row number to change after deletion
|
||||
* Reference: Python lines 306-324
|
||||
*/
|
||||
private async waitForRowChange(
|
||||
childForm: FrameLocator | Locator,
|
||||
oldRowNumber: string,
|
||||
@@ -454,10 +751,114 @@ export class CleanerService {
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Delay helper
|
||||
*/
|
||||
private delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
private async retryFailedOrders(params: {
|
||||
workFrame: FrameLocator
|
||||
popupPage: Page
|
||||
failedDetails: OrderCleanDetail[]
|
||||
deleteSet: Set<string>
|
||||
dryRun: boolean
|
||||
onProgress?: (
|
||||
message: string,
|
||||
progress?: number,
|
||||
extra?: Partial<import('../../types/cleaner.types').CleanerProgress>
|
||||
) => void
|
||||
}): Promise<RetryResult> {
|
||||
const { workFrame, popupPage, failedDetails, deleteSet, dryRun, onProgress } = params
|
||||
|
||||
const result: RetryResult = {
|
||||
retriedOrders: 0,
|
||||
successfulRetries: 0,
|
||||
updatedDetails: []
|
||||
}
|
||||
|
||||
if (failedDetails.length === 0) {
|
||||
return result
|
||||
}
|
||||
|
||||
log.info('Starting retry for failed orders', { count: failedDetails.length })
|
||||
|
||||
const MAX_RETRIES = 2
|
||||
|
||||
for (let detailIndex = 0; detailIndex < failedDetails.length; detailIndex++) {
|
||||
const failedDetail = failedDetails[detailIndex]
|
||||
const orderNumber = failedDetail.orderNumber
|
||||
const retryAttempts: import('../../types/cleaner.types').RetryAttempt[] = []
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
log.info(`Retrying order ${orderNumber} (attempt ${attempt}/${MAX_RETRIES})`)
|
||||
|
||||
await this.queryOrders(workFrame, [orderNumber])
|
||||
await this.waitForLoading(workFrame)
|
||||
|
||||
const rows = workFrame.locator('tbody tr')
|
||||
const rowCount = await rows.count()
|
||||
if (rowCount === 0) {
|
||||
throw new Error('订单重试查询无结果')
|
||||
}
|
||||
|
||||
const detailPage = await this.openDetailPageFromCurrentQuery(workFrame, popupPage)
|
||||
const retryDetail = await this.processDetailPage({
|
||||
detailPage,
|
||||
deleteSet,
|
||||
dryRun,
|
||||
expectedOrderNumber: orderNumber,
|
||||
progressState: {
|
||||
completedOrders: detailIndex,
|
||||
totalOrders: failedDetails.length
|
||||
},
|
||||
onProgress: (message, progress, extra) => {
|
||||
onProgress?.(
|
||||
`[重试 ${attempt}/${MAX_RETRIES}] ${message}`,
|
||||
progress,
|
||||
extra ? { ...extra, phase: 'processing' as const } : undefined
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
result.successfulRetries += 1
|
||||
result.updatedDetails.push({
|
||||
...retryDetail,
|
||||
retryCount: attempt,
|
||||
retriedAt: Date.now(),
|
||||
retrySuccess: true,
|
||||
retryAttempts
|
||||
})
|
||||
result.retriedOrders += 1
|
||||
break
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
log.warn(`Retry attempt ${attempt} failed for order ${orderNumber}: ${message}`)
|
||||
|
||||
retryAttempts.push({
|
||||
attempt,
|
||||
error: message,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
|
||||
if (attempt === MAX_RETRIES) {
|
||||
result.updatedDetails.push({
|
||||
...failedDetail,
|
||||
retryCount: MAX_RETRIES,
|
||||
retryAttempts,
|
||||
retriedAt: Date.now(),
|
||||
retrySuccess: false
|
||||
})
|
||||
result.retriedOrders += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info('Retry process completed', {
|
||||
retriedOrders: result.retriedOrders,
|
||||
successfulRetries: result.successfulRetries
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { chromium, type BrowserContext, type Page } from 'playwright'
|
||||
import { chromium } from 'playwright'
|
||||
import type { ErpConfig, ErpSession } from '../../types/erp.types'
|
||||
import { createLogger } from '../logger'
|
||||
|
||||
const log = createLogger('ErpAuthService')
|
||||
|
||||
// Timeout constants
|
||||
const PAGE_LOAD_TIMEOUT = 10000
|
||||
const LOGIN_RESULT_TIMEOUT = 15000
|
||||
const FORCE_LOGIN_TIMEOUT = 5000
|
||||
|
||||
/**
|
||||
* ERP Authentication Service
|
||||
* Manages login session and browser lifecycle
|
||||
@@ -51,10 +56,13 @@ export class ErpAuthService {
|
||||
await page.goto(loginUrl)
|
||||
|
||||
// Wait for page to load
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 10000 })
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: PAGE_LOAD_TIMEOUT })
|
||||
|
||||
// Wait for iframe to be present
|
||||
await page.waitForSelector('#forwardFrame', { state: 'attached', timeout: 15000 })
|
||||
await page.waitForSelector('#forwardFrame', {
|
||||
state: 'attached',
|
||||
timeout: LOGIN_RESULT_TIMEOUT
|
||||
})
|
||||
|
||||
// Extract forwardFrame (Python: main_frame = page.locator("#forwardFrame").content_frame)
|
||||
// This is the main working frame for all subsequent operations
|
||||
@@ -89,29 +97,11 @@ export class ErpAuthService {
|
||||
throw new Error(`Failed to click login button: ${e}`)
|
||||
}
|
||||
|
||||
// Wait for navigation after login
|
||||
// The login will redirect to the main page which has a different structure
|
||||
try {
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 10000 })
|
||||
} catch (e) {
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: PAGE_LOAD_TIMEOUT }).catch(() => {
|
||||
log.warn('Page load state check timed out, continuing')
|
||||
}
|
||||
})
|
||||
|
||||
// Handle force login confirmation dialog if present (Python: get_by_role("button", name="确定"))
|
||||
try {
|
||||
const confirmBtn = mainFrame.getByRole('button', { name: '确定' })
|
||||
const count = await confirmBtn.count()
|
||||
if (count > 0) {
|
||||
log.info('Force login detected, clicking confirm button')
|
||||
await confirmBtn.first().click()
|
||||
await page.waitForTimeout(2000)
|
||||
} else {
|
||||
log.debug('Normal login, no confirmation dialog')
|
||||
}
|
||||
} catch {
|
||||
// No force login dialog, continue
|
||||
log.debug('Normal login, no confirmation dialog')
|
||||
}
|
||||
await this.waitForLoginResult(mainFrame as unknown as import('playwright').Frame)
|
||||
|
||||
// Create session with mainFrame (Python returns main_frame as part of login result)
|
||||
this.session = {
|
||||
@@ -126,6 +116,47 @@ export class ErpAuthService {
|
||||
return this.session
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for login result: success, failure, or force login confirmation
|
||||
*/
|
||||
private async waitForLoginResult(mainFrame: import('playwright').Frame): Promise<void> {
|
||||
const successLocator = mainFrame.locator('.nc-workbench-icon')
|
||||
const errorLocator = mainFrame.getByText('名称或密码错误')
|
||||
const forceLoginButton = mainFrame.getByRole('button', { name: '确定' })
|
||||
|
||||
try {
|
||||
await Promise.race([
|
||||
successLocator.waitFor({ state: 'visible', timeout: LOGIN_RESULT_TIMEOUT }),
|
||||
errorLocator.waitFor({ state: 'visible', timeout: LOGIN_RESULT_TIMEOUT }),
|
||||
forceLoginButton
|
||||
.waitFor({ state: 'visible', timeout: FORCE_LOGIN_TIMEOUT })
|
||||
.then(async () => {
|
||||
log.info('Force login dialog detected, clicking confirm')
|
||||
await forceLoginButton.click()
|
||||
await this.waitForLoginResult(mainFrame)
|
||||
})
|
||||
])
|
||||
|
||||
const hasError = await errorLocator.isVisible()
|
||||
if (hasError) {
|
||||
throw new Error('ERP 登录失败:名称或密码错误')
|
||||
}
|
||||
|
||||
log.info('Login successful')
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes('名称或密码错误')) {
|
||||
throw error
|
||||
}
|
||||
|
||||
const hasError = await errorLocator.isVisible().catch(() => false)
|
||||
if (hasError) {
|
||||
throw new Error('ERP 登录失败:名称或密码错误')
|
||||
}
|
||||
|
||||
log.info('Login successful')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close browser and cleanup session
|
||||
*/
|
||||
|
||||
216
src/main/services/erp/extractor-core.ts
Normal file
216
src/main/services/erp/extractor-core.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import path from 'path'
|
||||
import { ERP_LOCATORS } from './locators'
|
||||
import type { ErpSession } from '../../types/erp.types'
|
||||
import type {
|
||||
ExtractorCoreInput,
|
||||
ExtractorCoreResult,
|
||||
ExtractionProgress
|
||||
} from '../../types/extractor.types'
|
||||
|
||||
/**
|
||||
* ExtractorCore - Handles all web page operations for data extraction
|
||||
* This class is responsible only for web interactions, not file processing
|
||||
*
|
||||
* Note: Uses 'any' for Frame types to maintain compatibility with Playwright's
|
||||
* frame handling API, matching the original implementation.
|
||||
*/
|
||||
export class ExtractorCore {
|
||||
/**
|
||||
* Execute all web page operations and return downloaded file paths
|
||||
* @param input - Contains session, order numbers, download directory, batch size, and progress callback
|
||||
* @returns List of downloaded file paths and any errors encountered
|
||||
*/
|
||||
async downloadAllBatches(input: ExtractorCoreInput): Promise<ExtractorCoreResult> {
|
||||
const result: ExtractorCoreResult = {
|
||||
downloadedFiles: [],
|
||||
errors: []
|
||||
}
|
||||
|
||||
const totalBatches = this.createBatches(input.orderNumbers, input.batchSize).length
|
||||
const totalPoints = 1 + totalBatches + 2
|
||||
const progressPerPoint = 100 / totalPoints
|
||||
|
||||
const { popupPage, workFrame } = await this.navigateToExtractorPage(input.session)
|
||||
|
||||
const batches = this.createBatches(input.orderNumbers, input.batchSize)
|
||||
|
||||
for (let i = 0; i < batches.length; i++) {
|
||||
const batch = batches[i]
|
||||
const progress = (1 + (i + 1)) * progressPerPoint
|
||||
|
||||
const progressExtra: Partial<ExtractionProgress> = {
|
||||
phase: 'downloading',
|
||||
currentBatch: i + 1,
|
||||
totalBatches
|
||||
}
|
||||
|
||||
input.onProgress?.(`处理批次 ${i + 1}/${totalBatches}`, progress, progressExtra)
|
||||
|
||||
try {
|
||||
const filePath = await this.downloadBatch(
|
||||
input.session,
|
||||
popupPage,
|
||||
workFrame,
|
||||
batch,
|
||||
i,
|
||||
batches.length,
|
||||
input.downloadDir
|
||||
)
|
||||
result.downloadedFiles.push(filePath)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
result.errors.push(`Batch ${i + 1}: ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to extractor/query page
|
||||
* Reference: Python extract() method lines 266-278
|
||||
*
|
||||
* Python workflow:
|
||||
* 1. main_frame.locator("i").first.click() - Click menu icon
|
||||
* 2. page.expect_popup() + get_by_title("离散备料计划维护").click() - Click menu item and wait for popup
|
||||
* 3. page1.locator("#forwardFrame").content_frame - Get popup's forward frame
|
||||
* 4. f_frame.locator("#mainiframe").content_frame - Get nested inner frame
|
||||
* 5. setup_query_interface(work_frame) - Setup query interface
|
||||
*/
|
||||
private async navigateToExtractorPage(
|
||||
session: ErpSession
|
||||
): Promise<{ popupPage: any; workFrame: any }> {
|
||||
const { page, mainFrame } = session
|
||||
|
||||
// Step 1: Click menu icon (Python line 266)
|
||||
// main_frame is #forwardFrame.content_frame returned from login
|
||||
await mainFrame.locator('i').first().click()
|
||||
|
||||
// Step 2: Click discrete material plan menu item and expect popup (Python lines 267-271)
|
||||
const popupPromise = page.waitForEvent('popup')
|
||||
await mainFrame.getByTitle('离散备料计划维护', { exact: true }).first().click()
|
||||
const popupPage = await popupPromise
|
||||
|
||||
// Step 3 & 4: Get nested frame structure in popup window (Python lines 273-276)
|
||||
// popup page contains #forwardFrame, which contains #mainiframe
|
||||
const forwardFrameLocator = popupPage.locator('#forwardFrame')
|
||||
const fFrame = await forwardFrameLocator.contentFrame()
|
||||
|
||||
if (!fFrame) {
|
||||
throw new Error('Failed to access popup forward frame')
|
||||
}
|
||||
|
||||
const innerFrameLocator = fFrame.locator('#mainiframe')
|
||||
await innerFrameLocator.waitFor({ state: 'visible', timeout: 15000 })
|
||||
const workFrame = await innerFrameLocator.contentFrame()
|
||||
|
||||
if (!workFrame) {
|
||||
throw new Error('Failed to access inner work frame')
|
||||
}
|
||||
|
||||
// Step 5: Setup query interface (Python line 278)
|
||||
await this.setupQueryInterface(workFrame)
|
||||
|
||||
return { popupPage, workFrame }
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup query interface
|
||||
* Reference: Python setup_query_interface() method lines 231-239
|
||||
*/
|
||||
private async setupQueryInterface(innerFrame: any): Promise<void> {
|
||||
// Click search icon (Python line 233)
|
||||
await innerFrame.locator('.search-name-wrapper > .iconfont').click()
|
||||
|
||||
// Click "订单号查询" menu item (Python line 234)
|
||||
await innerFrame.getByText('订单号查询').click()
|
||||
|
||||
// Click "全部" tab (Python line 235)
|
||||
await innerFrame.getByRole('tab', { name: '全部' }).click()
|
||||
|
||||
// Set limit to 5000 (Python lines 237-239)
|
||||
const inputBox = innerFrame.locator('#rc_select_0')
|
||||
await inputBox.fill('5000')
|
||||
await inputBox.press('Enter')
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a single batch of orders
|
||||
* Reference: Python download_batch() method lines 133-175
|
||||
*/
|
||||
private async downloadBatch(
|
||||
_session: ErpSession,
|
||||
popupPage: any,
|
||||
workFrame: any,
|
||||
orderNumbers: string[],
|
||||
batchIndex: number,
|
||||
_totalBatches: number,
|
||||
downloadDir: string
|
||||
): Promise<string> {
|
||||
// Fill order numbers (Python lines 143-145)
|
||||
const textbox = workFrame.getByRole('textbox', { name: '来源生产订单号' })
|
||||
await textbox.fill('')
|
||||
await textbox.fill(orderNumbers.join(','))
|
||||
|
||||
// Click search button (Python line 147)
|
||||
await workFrame.locator('.search-component-searchBtn').click()
|
||||
|
||||
// Wait for loading (Python lines 148-153)
|
||||
await this.waitForLoading(workFrame)
|
||||
|
||||
// Click first row checkbox (Python line 155)
|
||||
await workFrame.getByRole('row', { name: '序号' }).getByLabel('').click()
|
||||
|
||||
// Hover and click "更多" button (Python lines 156-157)
|
||||
await workFrame.getByRole('button', { name: '更多' }).hover()
|
||||
await workFrame.getByText('输出', { exact: true }).click()
|
||||
|
||||
// Set threshold (Python lines 159-164)
|
||||
const thresholdBox = workFrame
|
||||
.locator('div')
|
||||
.filter({ hasText: /^行数阈值$/ })
|
||||
.locator('input[type="text"]')
|
||||
await thresholdBox.fill('300000')
|
||||
|
||||
// Setup download handler and click confirm (Python lines 166-172)
|
||||
const downloadPath = path.join(downloadDir, `temp_batch_${batchIndex + 1}.xlsx`)
|
||||
|
||||
const downloadPromise = popupPage.waitForEvent('download')
|
||||
await workFrame.getByRole('button', { name: '确定(Y)' }).click()
|
||||
|
||||
const download = await downloadPromise
|
||||
await download.saveAs(downloadPath)
|
||||
|
||||
return downloadPath
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for loading overlay to disappear
|
||||
* Reference: Python lines 148-153
|
||||
*/
|
||||
private async waitForLoading(workFrame: any): Promise<void> {
|
||||
const loadingLocator = workFrame
|
||||
.locator('div')
|
||||
.filter({ hasText: ERP_LOCATORS.extractor.loadingText })
|
||||
.nth(1)
|
||||
|
||||
try {
|
||||
await loadingLocator.waitFor({ state: 'visible', timeout: 3000 })
|
||||
await loadingLocator.waitFor({ state: 'hidden', timeout: 0 })
|
||||
} catch {
|
||||
// Loading completed quickly or never appeared
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split array into batches
|
||||
* Reference: Python group_order_ids() method lines 128-131
|
||||
*/
|
||||
private createBatches<T>(items: T[], batchSize: number): T[][] {
|
||||
const batches: T[][] = []
|
||||
for (let i = 0; i < items.length; i += batchSize) {
|
||||
batches.push(items.slice(i, i + batchSize))
|
||||
}
|
||||
return batches
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,27 @@
|
||||
import path from 'path'
|
||||
import fs from 'fs/promises'
|
||||
import { ERP_LOCATORS } from './locators'
|
||||
import { ExtractorCore } from './extractor-core'
|
||||
import { ErpAuthService } from './erp-auth'
|
||||
import { ExcelParser } from '../excel/excel-parser'
|
||||
import type { ExtractorInput, ExtractorResult } from '../../types/extractor.types'
|
||||
import type { ErpSession } from '../../types/erp.types'
|
||||
import type { DiscreteMaterialPlan } from '../../types/excel.types'
|
||||
import type {
|
||||
ExtractorInput,
|
||||
ExtractorResult,
|
||||
ImportResult,
|
||||
LogLevel
|
||||
} from '../../types/extractor.types'
|
||||
import { DataImportService } from '../database/data-importer'
|
||||
import { createLogger } from '../logger'
|
||||
|
||||
const log = createLogger('ExtractorService')
|
||||
|
||||
/**
|
||||
* ERP Data Extractor Service
|
||||
* Downloads material plan data for given order numbers
|
||||
*
|
||||
* This service orchestrates the extraction process:
|
||||
* - Uses ExtractorCore for web page operations
|
||||
* - Handles file merging and cleanup
|
||||
*
|
||||
* Reference: playwrite/utils/discrete_material_plan_extractor.py
|
||||
*/
|
||||
export class ExtractorService {
|
||||
@@ -27,6 +38,8 @@ export class ExtractorService {
|
||||
|
||||
/**
|
||||
* Extract data for given order numbers
|
||||
* Orchestrates the extraction process by delegating web operations to ExtractorCore
|
||||
* and handling file merging/cleanup
|
||||
*/
|
||||
async extract(input: ExtractorInput): Promise<ExtractorResult> {
|
||||
const result: ExtractorResult = {
|
||||
@@ -39,38 +52,30 @@ export class ExtractorService {
|
||||
try {
|
||||
const session = this.authService.getSession()
|
||||
|
||||
// Navigate to extractor page and get popup page + work frame
|
||||
const { popupPage, workFrame } = await this.navigateToExtractorPage(session)
|
||||
// Call ExtractorCore to execute web page operations
|
||||
const core = new ExtractorCore()
|
||||
const coreResult = await core.downloadAllBatches({
|
||||
session,
|
||||
orderNumbers: input.orderNumbers,
|
||||
downloadDir: this.downloadDir,
|
||||
batchSize: input.batchSize || 100,
|
||||
onProgress: input.onProgress
|
||||
})
|
||||
|
||||
// Process orders in batches
|
||||
const batchSize = input.batchSize || 100
|
||||
const batches = this.createBatches(input.orderNumbers, batchSize)
|
||||
result.downloadedFiles = coreResult.downloadedFiles
|
||||
result.errors = coreResult.errors
|
||||
|
||||
for (let i = 0; i < batches.length; i++) {
|
||||
const batch = batches[i]
|
||||
const progress = ((i + 1) / batches.length) * 100
|
||||
|
||||
input.onProgress?.(`Processing batch ${i + 1}/${batches.length}`, progress)
|
||||
|
||||
try {
|
||||
const filePath = await this.downloadBatch(
|
||||
session,
|
||||
popupPage,
|
||||
workFrame,
|
||||
batch,
|
||||
i,
|
||||
batches.length
|
||||
)
|
||||
result.downloadedFiles.push(filePath)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
result.errors.push(`Batch ${i + 1}: ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Merge downloaded files into a single Excel file
|
||||
// Merge downloaded files (original logic preserved)
|
||||
if (result.downloadedFiles.length > 0) {
|
||||
input.onProgress?.('正在合并文件...', 95)
|
||||
const totalBatches = result.downloadedFiles.length
|
||||
const totalPoints = 1 + totalBatches + 2
|
||||
const progressPerPoint = 100 / totalPoints
|
||||
const mergeProgress = (1 + totalBatches) * progressPerPoint
|
||||
|
||||
input.onProgress?.('正在合并文件...', mergeProgress, {
|
||||
phase: 'merging',
|
||||
totalBatches
|
||||
})
|
||||
const mergeResult = await this.mergeFiles(result.downloadedFiles)
|
||||
result.mergedFile = mergeResult.mergedFile
|
||||
result.recordCount = mergeResult.recordCount
|
||||
@@ -82,6 +87,24 @@ export class ExtractorService {
|
||||
|
||||
// Always clean up temporary files regardless of merge success
|
||||
await this.cleanupTempFiles(result.downloadedFiles)
|
||||
|
||||
// Auto-import to database if merge was successful
|
||||
if (result.mergedFile) {
|
||||
const importProgress = (1 + totalBatches + 1) * progressPerPoint
|
||||
input.onProgress?.('正在写入数据库...', importProgress, {
|
||||
phase: 'importing',
|
||||
totalBatches
|
||||
})
|
||||
const importResult = await this.importToDatabaseWithLogging(
|
||||
result.mergedFile,
|
||||
input.onLog
|
||||
)
|
||||
result.importResult = importResult
|
||||
|
||||
if (!importResult.success && importResult.errors.length > 0) {
|
||||
result.errors.push(...importResult.errors)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
@@ -91,153 +114,6 @@ export class ExtractorService {
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to extractor/query page
|
||||
* Reference: Python extract() method lines 266-278
|
||||
*
|
||||
* Python workflow:
|
||||
* 1. main_frame.locator("i").first.click() - Click menu icon
|
||||
* 2. page.expect_popup() + get_by_title("离散备料计划维护").click() - Click menu item and wait for popup
|
||||
* 3. page1.locator("#forwardFrame").content_frame - Get popup's forward frame
|
||||
* 4. f_frame.locator("#mainiframe").content_frame - Get nested inner frame
|
||||
* 5. setup_query_interface(work_frame) - Setup query interface
|
||||
*/
|
||||
private async navigateToExtractorPage(
|
||||
session: ErpSession
|
||||
): Promise<{ popupPage: any; workFrame: any }> {
|
||||
const { page, mainFrame } = session
|
||||
|
||||
// Step 1: Click menu icon (Python line 266)
|
||||
// main_frame is #forwardFrame.content_frame returned from login
|
||||
await mainFrame.locator('i').first().click()
|
||||
|
||||
// Step 2: Click discrete material plan menu item and expect popup (Python lines 267-271)
|
||||
const popupPromise = page.waitForEvent('popup')
|
||||
await mainFrame.getByTitle('离散备料计划维护', { exact: true }).first().click()
|
||||
const popupPage = await popupPromise
|
||||
|
||||
// Step 3 & 4: Get nested frame structure in popup window (Python lines 273-276)
|
||||
// popup page contains #forwardFrame, which contains #mainiframe
|
||||
const forwardFrameLocator = popupPage.locator('#forwardFrame')
|
||||
const fFrame = await forwardFrameLocator.contentFrame()
|
||||
|
||||
if (!fFrame) {
|
||||
throw new Error('Failed to access popup forward frame')
|
||||
}
|
||||
|
||||
const innerFrameLocator = fFrame.locator('#mainiframe')
|
||||
await innerFrameLocator.waitFor({ state: 'visible', timeout: 15000 })
|
||||
const workFrame = await innerFrameLocator.contentFrame()
|
||||
|
||||
if (!workFrame) {
|
||||
throw new Error('Failed to access inner work frame')
|
||||
}
|
||||
|
||||
// Step 5: Setup query interface (Python line 278)
|
||||
await this.setupQueryInterface(workFrame)
|
||||
|
||||
return { popupPage, workFrame }
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup query interface
|
||||
* Reference: Python setup_query_interface() method lines 231-239
|
||||
*/
|
||||
private async setupQueryInterface(innerFrame: any): Promise<void> {
|
||||
// Click search icon (Python line 233)
|
||||
await innerFrame.locator('.search-name-wrapper > .iconfont').click()
|
||||
|
||||
// Click "订单号查询" menu item (Python line 234)
|
||||
await innerFrame.getByText('订单号查询').click()
|
||||
|
||||
// Click "全部" tab (Python line 235)
|
||||
await innerFrame.getByRole('tab', { name: '全部' }).click()
|
||||
|
||||
// Set limit to 5000 (Python lines 237-239)
|
||||
const inputBox = innerFrame.locator('#rc_select_0')
|
||||
await inputBox.fill('5000')
|
||||
await inputBox.press('Enter')
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a single batch of orders
|
||||
* Reference: Python download_batch() method lines 133-175
|
||||
*/
|
||||
private async downloadBatch(
|
||||
session: ErpSession,
|
||||
popupPage: any,
|
||||
workFrame: any,
|
||||
orderNumbers: string[],
|
||||
batchIndex: number,
|
||||
totalBatches: number
|
||||
): Promise<string> {
|
||||
// Fill order numbers (Python lines 143-145)
|
||||
const textbox = workFrame.getByRole('textbox', { name: '来源生产订单号' })
|
||||
await textbox.fill('')
|
||||
await textbox.fill(orderNumbers.join(','))
|
||||
|
||||
// Click search button (Python line 147)
|
||||
await workFrame.locator('.search-component-searchBtn').click()
|
||||
|
||||
// Wait for loading (Python lines 148-153)
|
||||
await this.waitForLoading(workFrame)
|
||||
|
||||
// Click first row checkbox (Python line 155)
|
||||
await workFrame.getByRole('row', { name: '序号' }).getByLabel('').click()
|
||||
|
||||
// Hover and click "更多" button (Python lines 156-157)
|
||||
await workFrame.getByRole('button', { name: '更多' }).hover()
|
||||
await workFrame.getByText('输出', { exact: true }).click()
|
||||
|
||||
// Set threshold (Python lines 159-164)
|
||||
const thresholdBox = workFrame
|
||||
.locator('div')
|
||||
.filter({ hasText: /^行数阈值$/ })
|
||||
.locator('input[type="text"]')
|
||||
await thresholdBox.fill('300000')
|
||||
|
||||
// Setup download handler and click confirm (Python lines 166-172)
|
||||
const downloadPath = path.join(this.downloadDir, `temp_batch_${batchIndex + 1}.xlsx`)
|
||||
|
||||
const downloadPromise = popupPage.waitForEvent('download')
|
||||
await workFrame.getByRole('button', { name: '确定(Y)' }).click()
|
||||
|
||||
const download = await downloadPromise
|
||||
await download.saveAs(downloadPath)
|
||||
|
||||
return downloadPath
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for loading overlay to disappear
|
||||
* Reference: Python lines 148-153
|
||||
*/
|
||||
private async waitForLoading(workFrame: any): Promise<void> {
|
||||
const loadingLocator = workFrame
|
||||
.locator('div')
|
||||
.filter({ hasText: ERP_LOCATORS.extractor.loadingText })
|
||||
.nth(1)
|
||||
|
||||
try {
|
||||
await loadingLocator.waitFor({ state: 'visible', timeout: 3000 })
|
||||
await loadingLocator.waitFor({ state: 'hidden', timeout: 0 })
|
||||
} catch {
|
||||
// Loading completed quickly or never appeared
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split array into batches
|
||||
* Reference: Python group_order_ids() method lines 128-131
|
||||
*/
|
||||
private createBatches<T>(items: T[], batchSize: number): T[][] {
|
||||
const batches: T[][] = []
|
||||
for (let i = 0; i < items.length; i += batchSize) {
|
||||
batches.push(items.slice(i, i + batchSize))
|
||||
}
|
||||
return batches
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge downloaded Excel files into a single file
|
||||
* Uses ExcelParser to parse and combine all material plans
|
||||
@@ -252,8 +128,8 @@ export class ExtractorService {
|
||||
return { mergedFile: null, recordCount: 0 }
|
||||
}
|
||||
|
||||
console.log(`[Extractor] Starting merge of ${filePaths.length} files`)
|
||||
const parser = new ExcelParser({ verbose: true })
|
||||
log.info('Starting merge', { fileCount: filePaths.length })
|
||||
const parser = new ExcelParser()
|
||||
|
||||
// Collect all orders with full order info and materials
|
||||
// Each order has: { orderInfo: OrderHeader, materials: MaterialRow[] }
|
||||
@@ -262,17 +138,17 @@ export class ExtractorService {
|
||||
// Parse each downloaded file and collect orders
|
||||
for (const filePath of filePaths) {
|
||||
try {
|
||||
console.log(`[Extractor] Parsing file: ${filePath}`)
|
||||
log.debug('Parsing file', { filePath })
|
||||
await parser.parse(filePath)
|
||||
// After parse(), the parser stores orders internally as lastOrders
|
||||
// After parse(), the parser store orders internally as lastOrders
|
||||
const orders = (parser as any).lastOrders
|
||||
console.log(`[Extractor] Parsed ${orders?.length || 0} orders from ${filePath}`)
|
||||
log.debug('File parsed', { filePath, orderCount: orders?.length || 0 })
|
||||
if (orders && Array.isArray(orders)) {
|
||||
allOrders.push(...orders)
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error)
|
||||
console.error(`[Extractor] Failed to parse file ${filePath}:`, errorMsg)
|
||||
log.error('Failed to parse file', { filePath, error: errorMsg })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,10 +158,10 @@ export class ExtractorService {
|
||||
recordCount += order.materials.length
|
||||
}
|
||||
|
||||
console.log(`[Extractor] Total orders: ${allOrders.length}, total records: ${recordCount}`)
|
||||
log.info('Merge summary', { orderCount: allOrders.length, recordCount })
|
||||
|
||||
if (recordCount === 0) {
|
||||
console.warn('[Extractor] No records found in any of the downloaded files')
|
||||
log.warn('No records found in any downloaded files')
|
||||
return { mergedFile: null, recordCount: 0 }
|
||||
}
|
||||
|
||||
@@ -299,17 +175,16 @@ export class ExtractorService {
|
||||
|
||||
// Save with error handling
|
||||
try {
|
||||
console.log(`[Extractor] Saving merged file to: ${outputPath}`)
|
||||
log.info('Saving merged file', { outputPath })
|
||||
await this.saveMergedOrders(allOrders, outputPath)
|
||||
console.log(`[Extractor] Successfully saved merged file with ${recordCount} records`)
|
||||
log.info('Merged file saved successfully', { recordCount })
|
||||
return { mergedFile: outputPath, recordCount }
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error)
|
||||
const errorStack = error instanceof Error ? error.stack : ''
|
||||
console.error(`[Extractor] Failed to save merged file: ${errorMsg}`)
|
||||
console.error(`[Extractor] Error stack: ${errorStack}`)
|
||||
log.error('Failed to save merged file', { error: errorMsg, stack: errorStack })
|
||||
// Return parsed record count and error info even if save fails
|
||||
return { mergedFile: null, recordCount, error: `保存合并文件失败: ${errorMsg}` }
|
||||
return { mergedFile: null, recordCount, error: `保存合并文件失败:${errorMsg}` }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,11 +196,11 @@ export class ExtractorService {
|
||||
orders: Array<{ orderInfo: any; materials: any[] }>,
|
||||
outputPath: string
|
||||
): Promise<void> {
|
||||
console.log(`[Extractor] Loading ExcelJS...`)
|
||||
log.debug('Loading ExcelJS')
|
||||
const ExcelJSModule = await import('exceljs')
|
||||
// Handle both ESM and CommonJS module formats
|
||||
const ExcelJS = ExcelJSModule.default || ExcelJSModule
|
||||
console.log(`[Extractor] ExcelJS loaded, creating workbook...`)
|
||||
log.debug('ExcelJS loaded, creating workbook')
|
||||
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
const worksheet = workbook.addWorksheet('Data')
|
||||
@@ -340,7 +215,7 @@ export class ExtractorService {
|
||||
{ header: '产品编码', key: 'productCode', width: 15 },
|
||||
{ header: '产品名称', key: 'productName', width: 30 },
|
||||
{ header: '产品计划数量', key: 'productPlannedQuantity', width: 15 },
|
||||
{ header: '单位', key: 'productUnit', width: 10 },
|
||||
{ header: '产品单位', key: 'productUnit', width: 10 },
|
||||
{ header: '用料部门', key: 'department', width: 15 },
|
||||
{ header: '备注', key: 'remark', width: 20 },
|
||||
{ header: '制单人', key: 'creator', width: 15 },
|
||||
@@ -364,7 +239,7 @@ export class ExtractorService {
|
||||
{ header: '打印日期', key: 'printDate', width: 20 }
|
||||
]
|
||||
|
||||
console.log(`[Extractor] Adding ${orders.length} orders to worksheet...`)
|
||||
log.debug('Adding orders to worksheet', { orderCount: orders.length })
|
||||
// Add data rows - merge orderInfo with each material
|
||||
for (const order of orders) {
|
||||
const { orderInfo, materials } = order
|
||||
@@ -408,9 +283,9 @@ export class ExtractorService {
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Extractor] Writing file to ${outputPath}...`)
|
||||
log.debug('Writing file', { outputPath })
|
||||
await workbook.xlsx.writeFile(outputPath)
|
||||
console.log(`[Extractor] File saved successfully: ${outputPath}`)
|
||||
log.debug('File saved successfully', { outputPath })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -421,10 +296,61 @@ export class ExtractorService {
|
||||
for (const filePath of filePaths) {
|
||||
try {
|
||||
await fs.unlink(filePath)
|
||||
console.log(`Deleted temporary file: ${filePath}`)
|
||||
log.debug('Deleted temporary file', { filePath })
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main process
|
||||
console.error(`Failed to delete temporary file ${filePath}:`, error)
|
||||
log.error('Failed to delete temporary file', { filePath, error })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import merged Excel data to database with logging
|
||||
* @param filePath - Path to the merged Excel file
|
||||
* @param onLog - Optional log callback
|
||||
* @returns Import result with statistics
|
||||
*/
|
||||
private async importToDatabaseWithLogging(
|
||||
filePath: string,
|
||||
onLog?: (level: LogLevel, message: string) => void
|
||||
): Promise<ImportResult> {
|
||||
log.info('Starting database import', { filePath })
|
||||
onLog?.('info', `开始导入数据到数据库...`)
|
||||
|
||||
const importService = new DataImportService()
|
||||
|
||||
try {
|
||||
const result = await importService.importFromExcel(filePath, 1000)
|
||||
|
||||
log.info('Import completed', {
|
||||
success: result.success,
|
||||
recordsRead: result.recordsRead,
|
||||
recordsDeleted: result.recordsDeleted,
|
||||
recordsImported: result.recordsImported
|
||||
})
|
||||
|
||||
if (result.success) {
|
||||
onLog?.(
|
||||
'success',
|
||||
`导入完成:读取 ${result.recordsRead} 条,删除 ${result.recordsDeleted} 条,导入 ${result.recordsImported} 条`
|
||||
)
|
||||
} else if (result.errors.length > 0) {
|
||||
result.errors.forEach((err) => onLog?.('error', err))
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error)
|
||||
log.error('Import failed', { error: errorMsg })
|
||||
onLog?.('error', `导入失败:${errorMsg}`)
|
||||
|
||||
return {
|
||||
success: false,
|
||||
recordsRead: 0,
|
||||
recordsDeleted: 0,
|
||||
recordsImported: 0,
|
||||
uniqueSourceNumbers: 0,
|
||||
errors: [errorMsg]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,14 @@
|
||||
* - productionID format: 2 digits + 1 letter + serial number (e.g., "22A1", "22A1234")
|
||||
* - 生产订单号 format: SC + 14 digits (e.g., "SC70202602120085")
|
||||
*
|
||||
* Database table: productionContractData_26年压力表合同数据
|
||||
* Fields: 总排号 (productionID), 生产订单号 (production order number)
|
||||
* Database table and field names are loaded from config.yaml
|
||||
*/
|
||||
|
||||
import type { IDatabaseService } from '../database'
|
||||
import { ConfigManager } from '../config/config-manager'
|
||||
import { createLogger } from '../logger'
|
||||
|
||||
const log = createLogger('OrderResolver')
|
||||
|
||||
/**
|
||||
* Order mapping result
|
||||
@@ -23,49 +26,53 @@ export interface OrderMapping {
|
||||
productionId?: string
|
||||
/** Final production order number to use */
|
||||
orderNumber?: string
|
||||
/** Whether this mapping is valid */
|
||||
isValid: boolean
|
||||
/** Error or warning message */
|
||||
/** Whether the order number was successfully resolved */
|
||||
resolved: boolean
|
||||
/** Error message if resolution failed */
|
||||
error?: string
|
||||
/** Input type */
|
||||
inputType: 'productionId' | 'orderNumber' | 'unknown'
|
||||
}
|
||||
|
||||
/**
|
||||
* Order number type recognition result
|
||||
*/
|
||||
export type OrderNumberType = 'productionId' | 'orderNumber' | 'unknown'
|
||||
|
||||
/**
|
||||
* Resolution statistics
|
||||
*/
|
||||
export interface ResolutionStats {
|
||||
totalInputs: number
|
||||
recognizedAsProductionId: number
|
||||
recognizedAsOrderNumber: number
|
||||
validOrderNumbers: number
|
||||
validProductionIds: number
|
||||
resolvedCount: number
|
||||
failedCount: number
|
||||
unknownFormat: number
|
||||
successfullyResolved: number
|
||||
failedToResolve: number
|
||||
notFoundInDatabase: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Regular expression patterns
|
||||
* ProductionID pattern: 2 digits + 1 letter + 1-6 digits
|
||||
* Examples: 22A1, 22A123, 26B10617
|
||||
*/
|
||||
export const ORDER_PATTERNS = {
|
||||
/** productionID: 2 digits + 1 letter + serial number (1+) */
|
||||
PRODUCTION_ID: /^\d{2}[A-Za-z]\d+$/,
|
||||
/** 生产订单号:SC + 14 digits */
|
||||
ORDER_NUMBER: /^SC\d{14}$/
|
||||
} as const
|
||||
const PRODUCTION_ID_PATTERN = /^\d{2}[A-Z]\d{1,6}$/i
|
||||
|
||||
/**
|
||||
* Production order number pattern: SC + 14 digits
|
||||
*/
|
||||
const ORDER_NUMBER_PATTERN = /^SC\d{14}$/i
|
||||
|
||||
/**
|
||||
* Database table and field names
|
||||
* Can be overridden via environment variables:
|
||||
* - DB_TABLE_NAME: Table name (default: 'productionContractData_26年压力表合同数据')
|
||||
* - DB_FIELD_PRODUCTION_ID: Field name for productionID (default: '总排号')
|
||||
* - DB_FIELD_ORDER_NUMBER: Field name for order number (default: '生产订单号')
|
||||
* Loaded from config.yaml via ConfigManager
|
||||
*/
|
||||
export const DB_CONFIG = {
|
||||
TABLE_NAME: process.env.DB_TABLE_NAME || 'productionContractData_26年压力表合同数据',
|
||||
FIELD_PRODUCTION_ID: process.env.DB_FIELD_PRODUCTION_ID || '总排号',
|
||||
FIELD_ORDER_NUMBER: process.env.DB_FIELD_ORDER_NUMBER || '生产订单号'
|
||||
} as const
|
||||
export function getDbConfig() {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
const config = configManager.getConfig()
|
||||
return {
|
||||
TABLE_NAME: config.orderResolution.tableName || 'productionContractData_26 年压力表合同数据',
|
||||
FIELD_PRODUCTION_ID: config.orderResolution.productionIdField || '总排号',
|
||||
FIELD_ORDER_NUMBER: config.orderResolution.orderNumberField || '生产订单号'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Order Number Resolver Service
|
||||
@@ -78,274 +85,257 @@ export class OrderNumberResolver {
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognize the type of an input string
|
||||
* @param input - The input string to recognize
|
||||
* @returns The recognized type
|
||||
* Get table name based on database type
|
||||
* Converts MySQL schema_tablename format to SQL Server [schema].[tablename] format
|
||||
* e.g., productionContractData_26年压力表合同数据 -> [productionContractData].[26年压力表合同数据]
|
||||
* dbo_MaterialsToBeDeleted -> [dbo].[MaterialsToBeDeleted]
|
||||
*/
|
||||
recognizeType(input: string): 'productionId' | 'orderNumber' | 'unknown' {
|
||||
const trimmed = input.trim()
|
||||
|
||||
if (ORDER_PATTERNS.ORDER_NUMBER.test(trimmed)) {
|
||||
return 'orderNumber'
|
||||
private getTableName(tableName: string): string {
|
||||
if (this.dbService.type === 'sqlserver') {
|
||||
// Find the FIRST underscore to split schema and table name
|
||||
// This handles patterns like: schema_tablename
|
||||
const firstUnderscoreIndex = tableName.indexOf('_')
|
||||
if (firstUnderscoreIndex > 0) {
|
||||
const schema = tableName.substring(0, firstUnderscoreIndex)
|
||||
const actualTableName = tableName.substring(firstUnderscoreIndex + 1)
|
||||
return `[${schema}].[${actualTableName}]`
|
||||
}
|
||||
// If no underscore found, default to dbo schema
|
||||
return `[dbo].[${tableName}]`
|
||||
}
|
||||
|
||||
if (ORDER_PATTERNS.PRODUCTION_ID.test(trimmed)) {
|
||||
return 'productionId'
|
||||
}
|
||||
|
||||
return 'unknown'
|
||||
return tableName
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a list of inputs to production order numbers
|
||||
* @param inputs - List of input strings (can be productionID or 生产订单号)
|
||||
* @returns List of order mappings
|
||||
* Check if input matches productionID pattern
|
||||
*/
|
||||
async resolve(inputs: string[]): Promise<OrderMapping[]> {
|
||||
const mappings: OrderMapping[] = []
|
||||
const stats: ResolutionStats = {
|
||||
totalInputs: inputs.length,
|
||||
recognizedAsProductionId: 0,
|
||||
recognizedAsOrderNumber: 0,
|
||||
unknownFormat: 0,
|
||||
successfullyResolved: 0,
|
||||
failedToResolve: 0,
|
||||
notFoundInDatabase: 0
|
||||
}
|
||||
|
||||
// First pass: recognize types and categorize
|
||||
const productionIds: string[] = []
|
||||
const orderNumbers: string[] = []
|
||||
|
||||
for (const input of inputs) {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) continue
|
||||
|
||||
const type = this.recognizeType(trimmed)
|
||||
|
||||
const baseMapping: OrderMapping = {
|
||||
input: trimmed,
|
||||
isValid: false,
|
||||
inputType: type
|
||||
}
|
||||
|
||||
if (type === 'productionId') {
|
||||
stats.recognizedAsProductionId++
|
||||
productionIds.push(trimmed)
|
||||
baseMapping.productionId = trimmed
|
||||
} else if (type === 'orderNumber') {
|
||||
stats.recognizedAsOrderNumber++
|
||||
orderNumbers.push(trimmed)
|
||||
baseMapping.orderNumber = trimmed
|
||||
baseMapping.isValid = true // Order numbers are valid by format
|
||||
stats.successfullyResolved++
|
||||
} else {
|
||||
stats.unknownFormat++
|
||||
baseMapping.error = `无法识别的格式:${trimmed}`
|
||||
mappings.push(baseMapping)
|
||||
continue
|
||||
}
|
||||
|
||||
mappings.push(baseMapping)
|
||||
}
|
||||
|
||||
// Query database for productionIDs
|
||||
if (productionIds.length > 0) {
|
||||
const productionIdMappings = await this.resolveProductionIds(productionIds)
|
||||
|
||||
// Update mappings with database results
|
||||
for (const mapping of mappings) {
|
||||
if (mapping.inputType === 'productionId') {
|
||||
const dbResult = productionIdMappings.find((m) => m.input === mapping.input)
|
||||
if (dbResult) {
|
||||
mapping.orderNumber = dbResult.orderNumber
|
||||
mapping.isValid = dbResult.isValid
|
||||
mapping.error = dbResult.error
|
||||
|
||||
if (dbResult.isValid) {
|
||||
stats.successfullyResolved++
|
||||
} else {
|
||||
stats.failedToResolve++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify order numbers exist in database (optional validation)
|
||||
// This can be skipped if you want to allow any SC+14digits format
|
||||
// For now, we'll verify them against the database
|
||||
if (orderNumbers.length > 0) {
|
||||
const verifiedOrderNumbers = new Set(await this.verifyOrderNumbers(orderNumbers))
|
||||
|
||||
for (const mapping of mappings) {
|
||||
if (mapping.inputType === 'orderNumber' && mapping.orderNumber) {
|
||||
if (!verifiedOrderNumbers.has(mapping.orderNumber)) {
|
||||
mapping.isValid = false
|
||||
mapping.error = `生产订单号不存在于数据库中:${mapping.orderNumber}`
|
||||
stats.notFoundInDatabase++
|
||||
stats.successfullyResolved--
|
||||
stats.failedToResolve++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return mappings
|
||||
isProductionId(input: string): boolean {
|
||||
return PRODUCTION_ID_PATTERN.test(input)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve productionIDs to production order numbers via database lookup
|
||||
* @param productionIds - List of productionIDs to resolve
|
||||
* @returns List of order mappings
|
||||
* Check if input matches order number pattern
|
||||
*/
|
||||
private async resolveProductionIds(productionIds: string[]): Promise<OrderMapping[]> {
|
||||
const mappings: OrderMapping[] = []
|
||||
|
||||
if (!this.dbService.isConnected()) {
|
||||
// Database not connected, return all as failed
|
||||
for (const pid of productionIds) {
|
||||
mappings.push({
|
||||
input: pid,
|
||||
productionId: pid,
|
||||
isValid: false,
|
||||
error: '数据库未连接,无法查询生产订单号',
|
||||
inputType: 'productionId'
|
||||
})
|
||||
}
|
||||
return mappings
|
||||
}
|
||||
isOrderNumber(input: string): boolean {
|
||||
return ORDER_NUMBER_PATTERN.test(input)
|
||||
}
|
||||
|
||||
/**
|
||||
* Map productionID to order number via database lookup
|
||||
*/
|
||||
async mapProductionIdToOrderNumber(productionId: string): Promise<string | null> {
|
||||
try {
|
||||
// Build query - use different placeholder style based on database type
|
||||
const isSqlServer = this.dbService.type === 'sqlserver'
|
||||
const placeholders = isSqlServer
|
||||
? productionIds.map((_, idx) => `@p${idx}`).join(', ')
|
||||
: productionIds.map(() => '?').join(', ')
|
||||
const dbConfig = getDbConfig()
|
||||
const tableName = this.getTableName(dbConfig.TABLE_NAME)
|
||||
|
||||
// Use appropriate quoting for table/field names
|
||||
const quote = isSqlServer ? '' : '`'
|
||||
const query = `
|
||||
SELECT ${quote}${DB_CONFIG.FIELD_PRODUCTION_ID}${quote}, ${quote}${DB_CONFIG.FIELD_ORDER_NUMBER}${quote}
|
||||
FROM ${quote}${DB_CONFIG.TABLE_NAME}${quote}
|
||||
WHERE ${quote}${DB_CONFIG.FIELD_PRODUCTION_ID}${quote} IN (${placeholders})
|
||||
`
|
||||
let sql: string
|
||||
let params: any[]
|
||||
|
||||
const result = await this.dbService.query(query, productionIds)
|
||||
|
||||
// Create a map for quick lookup
|
||||
const resultMap = new Map<string, string>()
|
||||
for (const row of result.rows) {
|
||||
const prodId = row[DB_CONFIG.FIELD_PRODUCTION_ID] as string
|
||||
const orderNum = row[DB_CONFIG.FIELD_ORDER_NUMBER] as string
|
||||
if (prodId && orderNum) {
|
||||
resultMap.set(prodId, orderNum)
|
||||
}
|
||||
if (this.dbService.type === 'sqlserver') {
|
||||
// 使用 COLLATE 指定不区分大小写的排序规则
|
||||
sql = `SELECT TOP 1 [${dbConfig.FIELD_ORDER_NUMBER}] FROM ${tableName} WHERE [${dbConfig.FIELD_PRODUCTION_ID}] COLLATE SQL_Latin1_General_CP1_CI_AS = @p0`
|
||||
params = [productionId]
|
||||
} else {
|
||||
// MySQL 默认不区分大小写,但显式使用 UPPER 确保一致性
|
||||
sql = `SELECT \`${dbConfig.FIELD_ORDER_NUMBER}\` FROM \`${tableName}\` WHERE UPPER(\`${dbConfig.FIELD_PRODUCTION_ID}\`) = UPPER(?) LIMIT 1`
|
||||
params = [productionId]
|
||||
}
|
||||
|
||||
// Build mappings
|
||||
for (const pid of productionIds) {
|
||||
const orderNumber = resultMap.get(pid)
|
||||
const result = await this.dbService.query(sql, params)
|
||||
|
||||
if (orderNumber) {
|
||||
mappings.push({
|
||||
input: pid,
|
||||
productionId: pid,
|
||||
orderNumber,
|
||||
isValid: true,
|
||||
inputType: 'productionId'
|
||||
})
|
||||
} else {
|
||||
mappings.push({
|
||||
input: pid,
|
||||
productionId: pid,
|
||||
isValid: false,
|
||||
error: `数据库中未找到生产 ID:${pid}`,
|
||||
inputType: 'productionId'
|
||||
})
|
||||
if (result.rows.length > 0) {
|
||||
const orderNumber = result.rows[0][Object.keys(result.rows[0])[0]] as string
|
||||
return orderNumber || null
|
||||
}
|
||||
|
||||
return null
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '未知数据库错误'
|
||||
log.error('Failed to map productionID to order number', {
|
||||
productionId,
|
||||
error: message
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map multiple productionIds to order numbers
|
||||
*/
|
||||
async mapProductionIdsToOrderNumbers(productionIds: string[]): Promise<Map<string, string>> {
|
||||
try {
|
||||
const dbConfig = getDbConfig()
|
||||
const tableName = this.getTableName(dbConfig.TABLE_NAME)
|
||||
|
||||
if (productionIds.length === 0) {
|
||||
return new Map()
|
||||
}
|
||||
|
||||
// P1: Deduplicate input productionIds to avoid redundant queries
|
||||
const uniqueProductionIds = [...new Set(productionIds)]
|
||||
|
||||
// Use parameterized query to prevent SQL injection
|
||||
const placeholders = uniqueProductionIds.map((_, i) => `@p${i}`).join(', ')
|
||||
const params = uniqueProductionIds
|
||||
|
||||
let sql: string
|
||||
if (this.dbService.type === 'sqlserver') {
|
||||
// P0: Use DISTINCT to prevent duplicates from one-to-many relationships
|
||||
// 使用 COLLATE 指定不区分大小写的排序规则
|
||||
sql = `SELECT DISTINCT [${dbConfig.FIELD_PRODUCTION_ID}], [${dbConfig.FIELD_ORDER_NUMBER}] FROM ${tableName} WHERE [${dbConfig.FIELD_PRODUCTION_ID}] COLLATE SQL_Latin1_General_CP1_CI_AS IN (${placeholders})`
|
||||
} else {
|
||||
const idPlaceholders = uniqueProductionIds.map(() => 'UPPER(?)').join(', ')
|
||||
// P0: Use DISTINCT to prevent duplicates from one-to-many relationships
|
||||
// MySQL: 使用 UPPER 确保不区分大小写
|
||||
sql = `SELECT DISTINCT \`${dbConfig.FIELD_PRODUCTION_ID}\`, \`${dbConfig.FIELD_ORDER_NUMBER}\` FROM \`${tableName}\` WHERE UPPER(\`${dbConfig.FIELD_PRODUCTION_ID}\`) IN (${idPlaceholders})`
|
||||
}
|
||||
|
||||
const result = await this.dbService.query(sql, params)
|
||||
|
||||
const mappings = new Map<string, string>()
|
||||
for (const row of result.rows) {
|
||||
const keys = Object.keys(row)
|
||||
const prodId = row[keys[0]] as string
|
||||
const orderNum = row[keys[1]] as string
|
||||
if (prodId && orderNum) {
|
||||
mappings.set(prodId, orderNum)
|
||||
}
|
||||
}
|
||||
|
||||
return mappings
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '未知数据库错误'
|
||||
|
||||
// Return all as failed with error
|
||||
return productionIds.map((pid) => ({
|
||||
input: pid,
|
||||
productionId: pid,
|
||||
isValid: false,
|
||||
error: `数据库查询失败:${message}`,
|
||||
inputType: 'productionId'
|
||||
}))
|
||||
log.error('Failed to map productionIds to order numbers', {
|
||||
error: message
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that order numbers exist in the database
|
||||
* @param orderNumbers - List of order numbers to verify
|
||||
* @returns List of valid order numbers
|
||||
* Resolve order numbers from mixed input
|
||||
*
|
||||
* Optimized for batch processing with deduplication:
|
||||
* - Multiple productionIDs mapping to the same order number are treated as valid (not errors)
|
||||
* - Returns all mappings with duplicate tracking
|
||||
*/
|
||||
private async verifyOrderNumbers(orderNumbers: string[]): Promise<string[]> {
|
||||
if (!this.dbService.isConnected()) {
|
||||
return orderNumbers // Skip verification if not connected
|
||||
async resolve(inputs: string[]): Promise<OrderMapping[]> {
|
||||
// P1: Deduplicate inputs at the input layer to avoid redundant queries
|
||||
const uniqueInputs = [...new Set(inputs)]
|
||||
|
||||
// Separate productionIds and order numbers
|
||||
const productionIds: string[] = []
|
||||
const orderNumbers: string[] = []
|
||||
|
||||
for (const input of uniqueInputs) {
|
||||
if (this.isOrderNumber(input)) {
|
||||
orderNumbers.push(input)
|
||||
} else if (this.isProductionId(input)) {
|
||||
productionIds.push(input)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Build query - use different placeholder style based on database type
|
||||
const isSqlServer = this.dbService.type === 'sqlserver'
|
||||
const placeholders = isSqlServer
|
||||
? orderNumbers.map((_, idx) => `@p${idx}`).join(', ')
|
||||
: orderNumbers.map(() => '?').join(', ')
|
||||
|
||||
// Use appropriate quoting for table/field names
|
||||
const quote = isSqlServer ? '' : '`'
|
||||
const query = `
|
||||
SELECT ${quote}${DB_CONFIG.FIELD_ORDER_NUMBER}${quote}
|
||||
FROM ${quote}${DB_CONFIG.TABLE_NAME}${quote}
|
||||
WHERE ${quote}${DB_CONFIG.FIELD_ORDER_NUMBER}${quote} IN (${placeholders})
|
||||
`
|
||||
|
||||
const result = await this.dbService.query(query, orderNumbers)
|
||||
return result.rows.map((row) => row[DB_CONFIG.FIELD_ORDER_NUMBER] as string)
|
||||
} catch (error) {
|
||||
console.warn('[OrderResolver] Failed to verify order numbers:', error)
|
||||
return orderNumbers // Skip verification on error
|
||||
// Batch query productionId to order number mappings
|
||||
// 使用小写 key 存储映射,以支持忽略大小写查找
|
||||
const mappings = new Map<string, string>()
|
||||
if (productionIds.length > 0) {
|
||||
const batchMappings = await this.mapProductionIdsToOrderNumbers(productionIds)
|
||||
batchMappings.forEach((orderNum, prodId) => {
|
||||
mappings.set(prodId.toLowerCase(), orderNum)
|
||||
})
|
||||
}
|
||||
|
||||
// Build results while preserving original input order
|
||||
// Note: Multiple productionIDs mapping to the same order number is VALID (not an error)
|
||||
const results: OrderMapping[] = []
|
||||
|
||||
for (const input of inputs) {
|
||||
// Skip if this exact input was already processed
|
||||
const alreadyProcessed = results.some((r) => r.input === input)
|
||||
if (alreadyProcessed) {
|
||||
continue
|
||||
}
|
||||
|
||||
const mapping: OrderMapping = { input, resolved: false }
|
||||
|
||||
if (this.isOrderNumber(input)) {
|
||||
// Already an order number
|
||||
mapping.orderNumber = input
|
||||
mapping.resolved = true
|
||||
} else if (this.isProductionId(input)) {
|
||||
// Is a productionID, lookup from batch mappings (使用小写查找以忽略大小写)
|
||||
mapping.productionId = input
|
||||
const orderNumber = mappings.get(input.toLowerCase())
|
||||
if (orderNumber) {
|
||||
mapping.orderNumber = orderNumber
|
||||
mapping.resolved = true
|
||||
} else {
|
||||
mapping.error = '未在数据库中找到对应的订单号'
|
||||
}
|
||||
} else {
|
||||
mapping.error = '格式不识别:既不是有效的生产订单号也不是总排号格式'
|
||||
}
|
||||
|
||||
results.push(mapping)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Get valid order numbers from mappings
|
||||
* P2: Returns deduplicated order numbers
|
||||
*/
|
||||
getValidOrderNumbers(mappings: OrderMapping[]): string[] {
|
||||
const validNumbers = mappings
|
||||
.filter((m) => m.resolved && m.orderNumber)
|
||||
.map((m) => m.orderNumber!)
|
||||
// P2: Deduplicate before returning
|
||||
return [...new Set(validNumbers)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Get warnings from failed mappings
|
||||
*/
|
||||
getWarnings(mappings: OrderMapping[]): string[] {
|
||||
return mappings.filter((m) => !m.resolved && m.error).map((m) => `${m.input}: ${m.error}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognize the type of input
|
||||
*/
|
||||
recognizeType(input: string): OrderNumberType {
|
||||
if (this.isOrderNumber(input)) return 'orderNumber'
|
||||
if (this.isProductionId(input)) return 'productionId'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
/**
|
||||
* Get resolution statistics
|
||||
* @param mappings - List of order mappings
|
||||
* @returns Resolution statistics
|
||||
*/
|
||||
getStats(mappings: OrderMapping[]): ResolutionStats {
|
||||
const stats: ResolutionStats = {
|
||||
totalInputs: mappings.length,
|
||||
recognizedAsProductionId: 0,
|
||||
recognizedAsOrderNumber: 0,
|
||||
unknownFormat: 0,
|
||||
successfullyResolved: 0,
|
||||
failedToResolve: 0,
|
||||
notFoundInDatabase: 0
|
||||
validOrderNumbers: 0,
|
||||
validProductionIds: 0,
|
||||
resolvedCount: 0,
|
||||
failedCount: 0,
|
||||
unknownFormat: 0
|
||||
}
|
||||
|
||||
for (const mapping of mappings) {
|
||||
if (mapping.inputType === 'productionId') {
|
||||
stats.recognizedAsProductionId++
|
||||
} else if (mapping.inputType === 'orderNumber') {
|
||||
stats.recognizedAsOrderNumber++
|
||||
if (mapping.resolved) {
|
||||
stats.resolvedCount++
|
||||
if (mapping.orderNumber && !mapping.productionId) {
|
||||
stats.validOrderNumbers++
|
||||
} else if (mapping.productionId) {
|
||||
stats.validProductionIds++
|
||||
}
|
||||
} else {
|
||||
stats.unknownFormat++
|
||||
}
|
||||
|
||||
if (mapping.isValid) {
|
||||
stats.successfullyResolved++
|
||||
} else if (mapping.error?.includes('不存在于数据库中')) {
|
||||
stats.notFoundInDatabase++
|
||||
stats.failedToResolve++
|
||||
} else if (mapping.error) {
|
||||
stats.failedToResolve++
|
||||
stats.failedCount++
|
||||
if (!mapping.productionId && !mapping.orderNumber) {
|
||||
stats.unknownFormat++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,20 +343,45 @@ export class OrderNumberResolver {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract valid order numbers from mappings
|
||||
* @param mappings - List of order mappings
|
||||
* @returns List of valid production order numbers
|
||||
* Get deduplication summary for logging
|
||||
* Returns a human-readable report showing:
|
||||
* - Input count
|
||||
* - Unique order numbers count
|
||||
* - Mapping details (which productionIDs map to which order numbers)
|
||||
*/
|
||||
getValidOrderNumbers(mappings: OrderMapping[]): string[] {
|
||||
return mappings.filter((m) => m.isValid && m.orderNumber).map((m) => m.orderNumber!)
|
||||
}
|
||||
getDeduplicationReport(mappings: OrderMapping[]): {
|
||||
inputCount: number
|
||||
uniqueOrderNumbersCount: number
|
||||
orderNumberGroups: Map<string, string[]>
|
||||
summary: string
|
||||
} {
|
||||
// Group productionIDs by their resolved order number
|
||||
const orderNumberGroups = new Map<string, string[]>()
|
||||
|
||||
/**
|
||||
* Extract warnings/errors from mappings
|
||||
* @param mappings - List of order mappings
|
||||
* @returns List of warning messages
|
||||
*/
|
||||
getWarnings(mappings: OrderMapping[]): string[] {
|
||||
return mappings.filter((m) => !m.isValid && m.error).map((m) => m.error!)
|
||||
for (const mapping of mappings) {
|
||||
if (mapping.resolved && mapping.orderNumber) {
|
||||
const existing = orderNumberGroups.get(mapping.orderNumber) || []
|
||||
existing.push(mapping.input)
|
||||
orderNumberGroups.set(mapping.orderNumber, existing)
|
||||
}
|
||||
}
|
||||
|
||||
const inputCount = mappings.length
|
||||
const uniqueOrderNumbersCount = orderNumberGroups.size
|
||||
|
||||
// Build summary string
|
||||
let summary = `输入 ${inputCount} 个总排号 → 解析为 ${uniqueOrderNumbersCount} 个唯一订单号`
|
||||
|
||||
if (inputCount > uniqueOrderNumbersCount) {
|
||||
const duplicateCount = inputCount - uniqueOrderNumbersCount
|
||||
summary += `(${duplicateCount} 个重复已合并)`
|
||||
}
|
||||
|
||||
return {
|
||||
inputCount,
|
||||
uniqueOrderNumbersCount,
|
||||
orderNumberGroups,
|
||||
summary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
import type { DiscreteMaterialPlan, ExcelParseOptions, OrderHeader } from '../../types/excel.types'
|
||||
import path from 'path'
|
||||
import { createLogger } from '../logger'
|
||||
|
||||
const log = createLogger('ExcelParser')
|
||||
|
||||
/**
|
||||
* Excel Parser Service
|
||||
@@ -50,23 +52,11 @@ export class ExcelParser {
|
||||
产品单位: 'unit'
|
||||
}
|
||||
|
||||
private verbose: boolean
|
||||
|
||||
constructor(options: ExcelParseOptions = {}) {
|
||||
this.verbose = options.verbose || false
|
||||
}
|
||||
|
||||
private log(...args: any[]): void {
|
||||
if (this.verbose) {
|
||||
console.log('[ExcelParser]', ...args)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Excel file and extract material plans
|
||||
*/
|
||||
async parse(filePath: string, options: ExcelParseOptions = {}): Promise<DiscreteMaterialPlan[]> {
|
||||
this.log('Parsing Excel file:', filePath)
|
||||
log.debug('Parsing Excel file:', filePath)
|
||||
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.readFile(filePath)
|
||||
@@ -80,11 +70,11 @@ export class ExcelParser {
|
||||
const allRows: any[][] = []
|
||||
|
||||
// Read all rows into memory
|
||||
worksheet.eachRow((row, rowNumber) => {
|
||||
worksheet.eachRow((row, _rowNumber) => {
|
||||
allRows.push(row.values as any[])
|
||||
})
|
||||
|
||||
this.log(`Total rows read: ${allRows.length} (worksheet has ${worksheet.rowCount} rows)`)
|
||||
log.debug(`Total rows read: ${allRows.length} (worksheet has ${worksheet.rowCount} rows)`)
|
||||
|
||||
// Parse orders from rows
|
||||
const orders = this.parseOrders(allRows)
|
||||
@@ -98,7 +88,7 @@ export class ExcelParser {
|
||||
|
||||
// Skip empty orders if option is set
|
||||
if (options.skipEmptyOrders && materials.length === 0) {
|
||||
this.log('Skipping empty order:', orderInfo.productionOrder)
|
||||
log.debug('Skipping empty order:', orderInfo.productionOrder)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -125,7 +115,7 @@ export class ExcelParser {
|
||||
}
|
||||
}
|
||||
|
||||
this.log(`Parsed ${plans.length} material plans from ${orders.length} orders`)
|
||||
log.debug(`Parsed ${plans.length} material plans from ${orders.length} orders`)
|
||||
|
||||
return plans
|
||||
}
|
||||
@@ -143,7 +133,7 @@ export class ExcelParser {
|
||||
throw new Error('No parsed data available. Call parse() first.')
|
||||
}
|
||||
|
||||
this.log('Saving parsed data to Excel:', outputPath)
|
||||
log.debug('Saving parsed data to Excel:', outputPath)
|
||||
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
const worksheet = workbook.addWorksheet('Data')
|
||||
@@ -158,7 +148,7 @@ export class ExcelParser {
|
||||
{ header: '产品编码', key: 'productCode', width: 15 },
|
||||
{ header: '产品名称', key: 'productName', width: 30 },
|
||||
{ header: '产品计划数量', key: 'productPlannedQuantity', width: 15 },
|
||||
{ header: '单位', key: 'productUnit', width: 10 },
|
||||
{ header: '产品单位', key: 'productUnit', width: 10 },
|
||||
{ header: '用料部门', key: 'department', width: 15 },
|
||||
{ header: '备注', key: 'remark', width: 20 },
|
||||
{ header: '制单人', key: 'creator', width: 15 },
|
||||
@@ -226,7 +216,7 @@ export class ExcelParser {
|
||||
|
||||
// Save workbook
|
||||
await workbook.xlsx.writeFile(outputPath)
|
||||
this.log(
|
||||
log.debug(
|
||||
`Excel file saved: ${outputPath} (${orders.length} orders, ${worksheet.rowCount - 1} data rows)`
|
||||
)
|
||||
}
|
||||
@@ -253,7 +243,7 @@ export class ExcelParser {
|
||||
}
|
||||
|
||||
// Debug: check productionOrder extraction
|
||||
this.log(`Order ${orders.length + 1}: productionOrder="${orderInfo.productionOrder}"`)
|
||||
log.debug(`Order ${orders.length + 1}: productionOrder="${orderInfo.productionOrder}"`)
|
||||
|
||||
// Find table header row dynamically (look for "序号" in index 1)
|
||||
// Note: worksheet.eachRow() skips empty rows, so we can't use fixed offsets
|
||||
@@ -263,7 +253,7 @@ export class ExcelParser {
|
||||
}
|
||||
|
||||
if (tableRow >= allRows.length || !allRows[tableRow]) {
|
||||
this.log(' ⚠️ Table header not found, skipping this order')
|
||||
log.debug(' ⚠️ Table header not found, skipping this order')
|
||||
i++
|
||||
continue
|
||||
}
|
||||
@@ -280,7 +270,7 @@ export class ExcelParser {
|
||||
|
||||
if (isEmptyRow) {
|
||||
// No data, find footer info
|
||||
this.log('Order has no material data')
|
||||
log.debug('Order has no material data')
|
||||
const materials: any[] = []
|
||||
const footerInfo: OrderHeader = {}
|
||||
let dataRow = nextRow + 1
|
||||
@@ -306,7 +296,7 @@ export class ExcelParser {
|
||||
})
|
||||
} else {
|
||||
// Has data, extract materials
|
||||
this.log('Order has material data')
|
||||
log.debug('Order has material data')
|
||||
const materials: any[] = []
|
||||
const footerInfo: OrderHeader = {}
|
||||
let dataRow = tableRow + 1
|
||||
@@ -332,7 +322,7 @@ export class ExcelParser {
|
||||
if (dataRow + 1 < allRows.length && allRows[dataRow + 1]) {
|
||||
this.parseHeaderRow(allRows[dataRow + 1], footerInfo)
|
||||
}
|
||||
this.log(' Found footer row, stopping material parsing')
|
||||
log.debug(' Found footer row, stopping material parsing')
|
||||
break
|
||||
}
|
||||
|
||||
@@ -340,7 +330,7 @@ export class ExcelParser {
|
||||
// Next row is footer, parse current row as material first
|
||||
const material = this.parseMaterialRowInternal(allRows[dataRow], dataRow + 1)
|
||||
if (material) {
|
||||
this.log(' Parsed material:', material.materialCode)
|
||||
log.debug(' Parsed material:', material.materialCode)
|
||||
materials.push(material)
|
||||
}
|
||||
|
||||
@@ -349,17 +339,17 @@ export class ExcelParser {
|
||||
if (dataRow + 2 < allRows.length && allRows[dataRow + 2]) {
|
||||
this.parseHeaderRow(allRows[dataRow + 2], footerInfo)
|
||||
}
|
||||
this.log(' Found footer in next row, stopping material parsing')
|
||||
log.debug(' Found footer in next row, stopping material parsing')
|
||||
break
|
||||
}
|
||||
|
||||
// Extract material data
|
||||
const material = this.parseMaterialRowInternal(allRows[dataRow], dataRow + 1)
|
||||
if (material) {
|
||||
this.log(' Parsed material:', material.materialCode)
|
||||
//log.debug(' Parsed material:', material.materialCode)
|
||||
materials.push(material)
|
||||
} else {
|
||||
this.log(' Skipped material row at', dataRow + 1)
|
||||
log.debug(' Skipped material row at', dataRow + 1)
|
||||
}
|
||||
|
||||
dataRow++
|
||||
@@ -371,7 +361,7 @@ export class ExcelParser {
|
||||
})
|
||||
}
|
||||
} else {
|
||||
this.log(
|
||||
log.debug(
|
||||
` ⚠️ Table header check failed at row ${tableRow + 1}, value="${allRows[tableRow] ? allRows[tableRow][1] : 'null'}"`
|
||||
)
|
||||
}
|
||||
@@ -383,7 +373,7 @@ export class ExcelParser {
|
||||
}
|
||||
}
|
||||
|
||||
this.log(`parseOrders: Returning ${orders.length} orders`)
|
||||
log.debug(`parseOrders: Returning ${orders.length} orders`)
|
||||
return orders
|
||||
}
|
||||
|
||||
|
||||
126
src/main/services/logger/audit-logger.ts
Normal file
126
src/main/services/logger/audit-logger.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Audit Logger Service
|
||||
* Writes audit logs in JSONL format with 30-day rotation using winston-daily-rotate-file
|
||||
*/
|
||||
|
||||
import winston from 'winston'
|
||||
import DailyRotateFile from 'winston-daily-rotate-file'
|
||||
import path from 'path'
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs'
|
||||
|
||||
/**
|
||||
* Audit log entry structure
|
||||
* All 8 required fields for comprehensive audit tracking
|
||||
*/
|
||||
export interface AuditEntry {
|
||||
/** ISO 8601 timestamp of the audit event */
|
||||
timestamp: string
|
||||
/** The action that was performed (e.g., 'LOGIN', 'EXTRACT', 'DELETE') */
|
||||
action: string
|
||||
/** User ID who performed the action */
|
||||
userId: string
|
||||
/** Username of the user who performed the action */
|
||||
username: string
|
||||
/** Computer name from which the action was performed */
|
||||
computerName: string
|
||||
/** The resource that was affected (e.g., table name, file path) */
|
||||
resource: string
|
||||
/** Status of the action: 'success' | 'failure' | 'partial' */
|
||||
status: 'success' | 'failure' | 'partial'
|
||||
/** Additional metadata about the audit event */
|
||||
metadata: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the log directory for audit logs
|
||||
* Uses app.getPath('logs') in production, local logs dir in development
|
||||
*/
|
||||
function getLogDir(): string {
|
||||
if (app && app.isReady()) {
|
||||
return app.getPath('logs')
|
||||
}
|
||||
// Fallback for development or before app is ready
|
||||
const devLogDir = path.join(process.cwd(), 'logs')
|
||||
if (!fs.existsSync(devLogDir)) {
|
||||
fs.mkdirSync(devLogDir, { recursive: true })
|
||||
}
|
||||
return devLogDir
|
||||
}
|
||||
|
||||
/**
|
||||
* JSONL formatter - outputs one JSON object per line
|
||||
* This is the key difference from the standard JSON formatter
|
||||
*/
|
||||
const jsonlFormat = winston.format.printf(({ message }) => {
|
||||
// Message should already be a JSON string
|
||||
return typeof message === 'string' ? message : JSON.stringify(message)
|
||||
})
|
||||
|
||||
/**
|
||||
* Create the audit logger instance with daily rotation
|
||||
* Configured for 30-day retention as per requirements
|
||||
*/
|
||||
const auditLogger = winston.createLogger({
|
||||
level: 'info',
|
||||
silent: false,
|
||||
transports: [
|
||||
new DailyRotateFile({
|
||||
filename: path.join(getLogDir(), 'audit-%DATE%.jsonl'),
|
||||
datePattern: 'YYYY-MM-DD',
|
||||
zippedArchive: true,
|
||||
maxSize: '20m',
|
||||
maxFiles: '30d', // 30-day retention
|
||||
level: 'info',
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp({ format: 'YYYY-MM-DDTHH:mm:ss.SSSZ' }),
|
||||
jsonlFormat
|
||||
)
|
||||
})
|
||||
]
|
||||
})
|
||||
|
||||
/**
|
||||
* Log an audit event
|
||||
*
|
||||
* @param action - The action that was performed
|
||||
* @param userId - User ID who performed the action
|
||||
* @param details - Additional details including username, computerName, resource, status, and optional metadata
|
||||
* @returns Promise that resolves when the log is written (non-blocking)
|
||||
*/
|
||||
export async function logAudit(
|
||||
action: string,
|
||||
userId: string,
|
||||
details: {
|
||||
username: string
|
||||
computerName: string
|
||||
resource: string
|
||||
status: 'success' | 'failure' | 'partial'
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
): Promise<void> {
|
||||
const entry: AuditEntry = {
|
||||
timestamp: new Date().toISOString(),
|
||||
action,
|
||||
userId,
|
||||
username: details.username,
|
||||
computerName: details.computerName,
|
||||
resource: details.resource,
|
||||
status: details.status,
|
||||
metadata: details.metadata || {}
|
||||
}
|
||||
|
||||
// Write as JSONL - one JSON object per line
|
||||
// Using info level with the entry stringified as the message
|
||||
auditLogger.info(JSON.stringify(entry))
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush and close the audit logger (call on app shutdown)
|
||||
*/
|
||||
export async function closeAuditLogger(): Promise<void> {
|
||||
// Winston logger.close() is synchronous
|
||||
auditLogger.close()
|
||||
}
|
||||
|
||||
export default auditLogger
|
||||
242
src/main/services/logger/error-utils.ts
Normal file
242
src/main/services/logger/error-utils.ts
Normal file
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Error Logging Utilities
|
||||
*
|
||||
* Provides comprehensive error serialization and formatting for logging.
|
||||
* Captures full error context including stack traces, causes, and custom properties.
|
||||
*/
|
||||
|
||||
import type { ErrorLike, SerializedError } from '../../types/errors'
|
||||
|
||||
/**
|
||||
* Check if value is an Error or Error-like object
|
||||
*/
|
||||
export function isError(value: unknown): value is Error | ErrorLike {
|
||||
return (
|
||||
value instanceof Error ||
|
||||
(typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'name' in value &&
|
||||
'message' in value &&
|
||||
typeof (value as any).message === 'string')
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize an error into a plain object for logging
|
||||
* Captures all enumerable and non-enumerable properties
|
||||
*/
|
||||
export function serializeError(error: unknown): SerializedError {
|
||||
if (error instanceof Error) {
|
||||
const serialized: SerializedError = {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
cause: error.cause ? serializeError(error.cause) : undefined
|
||||
}
|
||||
|
||||
// Capture custom properties from Error subclasses
|
||||
const props = Object.getOwnPropertyNames(error)
|
||||
for (const prop of props) {
|
||||
if (!['name', 'message', 'stack', 'cause'].includes(prop)) {
|
||||
const value = (error as any)[prop]
|
||||
if (value !== undefined) {
|
||||
serialized[prop] = isError(value) ? serializeError(value) : value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return serialized
|
||||
}
|
||||
|
||||
if (isError(error)) {
|
||||
return {
|
||||
name: (error as any).name || 'UnknownError',
|
||||
message: (error as any).message || String(error),
|
||||
stack: (error as any).stack,
|
||||
cause: (error as any).cause ? serializeError((error as any).cause) : undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Non-error values
|
||||
return {
|
||||
name: 'UnknownError',
|
||||
message: typeof error === 'string' ? error : JSON.stringify(error) || 'Unknown error occurred'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize error for production logging
|
||||
* Removes sensitive information while preserving error structure
|
||||
*/
|
||||
export function sanitizeError(error: SerializedError): SerializedError {
|
||||
const sensitiveKeys = [
|
||||
'password',
|
||||
'secret',
|
||||
'token',
|
||||
'apiKey',
|
||||
'api_key',
|
||||
'credentials',
|
||||
'authorization',
|
||||
'privateKey',
|
||||
'secretKey'
|
||||
]
|
||||
|
||||
const sanitized: SerializedError = { ...error }
|
||||
|
||||
// Sanitize message in production
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
// Keep error name and structure, but sanitize message
|
||||
if (sensitiveKeys.some((key) => error.message?.toLowerCase().includes(key))) {
|
||||
sanitized.message = 'An error occurred due to invalid credentials or configuration'
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively sanitize cause
|
||||
if (sanitized.cause && typeof sanitized.cause === 'object') {
|
||||
sanitized.cause = sanitizeError(sanitized.cause)
|
||||
}
|
||||
|
||||
// Sanitize any custom properties that might contain sensitive data
|
||||
for (const key of Object.keys(sanitized)) {
|
||||
if (sensitiveKeys.some((sensitive) => key.toLowerCase().includes(sensitive))) {
|
||||
sanitized[key] = '[REDACTED]'
|
||||
}
|
||||
}
|
||||
|
||||
return sanitized
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract context from error for logging
|
||||
* Includes file, line, column from stack trace when available
|
||||
*/
|
||||
export function extractErrorContext(error: SerializedError): {
|
||||
fileName?: string
|
||||
lineNumber?: number
|
||||
columnName?: number
|
||||
functionName?: string
|
||||
} {
|
||||
if (!error.stack) {
|
||||
return {}
|
||||
}
|
||||
|
||||
const stackLines = error.stack.split('\n')
|
||||
// Skip first line (error name and message), get first stack frame
|
||||
const stackLine = stackLines[1] || stackLines[0]
|
||||
|
||||
// Parse stack frame: "at Function.module.exports (path/to/file.js:123:45)"
|
||||
const match = stackLine.match(/at(?:\s+(.+?)\s+)?\((.+):(\d+):(\d+)\)/)
|
||||
if (match) {
|
||||
return {
|
||||
functionName: match[1],
|
||||
fileName: match[2],
|
||||
lineNumber: parseInt(match[3], 10),
|
||||
columnName: parseInt(match[4], 10)
|
||||
}
|
||||
}
|
||||
|
||||
// Alternative format: "at path/to/file.js:123:45"
|
||||
const altMatch = stackLine.match(/at\s+(.+):(\d+):(\d+)/)
|
||||
if (altMatch) {
|
||||
return {
|
||||
fileName: altMatch[1],
|
||||
lineNumber: parseInt(altMatch[2], 10),
|
||||
columnName: parseInt(altMatch[3], 10)
|
||||
}
|
||||
}
|
||||
|
||||
return {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format error for console/file logging
|
||||
* Returns a formatted string with all error details
|
||||
*/
|
||||
export function formatErrorForLogging(
|
||||
error: unknown,
|
||||
context?: {
|
||||
operation?: string
|
||||
module?: string
|
||||
userId?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
): {
|
||||
message: string
|
||||
metadata: Record<string, unknown>
|
||||
} {
|
||||
const serialized = serializeError(error)
|
||||
const isProd = process.env.NODE_ENV === 'production'
|
||||
const errorToLog = isProd ? sanitizeError(serialized) : serialized
|
||||
const errorContext = extractErrorContext(errorToLog)
|
||||
|
||||
const metadata: Record<string, unknown> = {
|
||||
error: errorToLog,
|
||||
...context
|
||||
}
|
||||
|
||||
// Add error location context if available
|
||||
if (errorContext.fileName) {
|
||||
metadata.errorLocation = {
|
||||
file: errorContext.fileName.split('/').pop() || errorContext.fileName,
|
||||
line: errorContext.lineNumber,
|
||||
column: errorContext.columnName,
|
||||
function: errorContext.functionName
|
||||
}
|
||||
}
|
||||
|
||||
// Add environment info in development
|
||||
if (!isProd) {
|
||||
metadata.environment = {
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
platform: process.platform,
|
||||
nodeVersion: process.version
|
||||
}
|
||||
}
|
||||
|
||||
const message = `[${errorToLog.name}] ${errorToLog.message}`
|
||||
|
||||
return { message, metadata }
|
||||
}
|
||||
|
||||
/**
|
||||
* Log error with full context
|
||||
* Wrapper for logger.error that ensures complete error information is captured
|
||||
*/
|
||||
export function logError(
|
||||
logger: { error: (message: string, meta?: Record<string, unknown>) => void },
|
||||
error: unknown,
|
||||
options: {
|
||||
message?: string
|
||||
operation?: string
|
||||
module?: string
|
||||
userId?: string
|
||||
context?: Record<string, unknown>
|
||||
} = {}
|
||||
): void {
|
||||
const { message: customMessage, operation, module: moduleName, userId, context } = options
|
||||
const { message, metadata } = formatErrorForLogging(error, {
|
||||
operation,
|
||||
module: moduleName,
|
||||
userId,
|
||||
...context
|
||||
})
|
||||
|
||||
const finalMessage = customMessage || message
|
||||
logger.error(finalMessage, metadata)
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-throw error after logging, preserving original stack
|
||||
*/
|
||||
export function throwAfterLogging(
|
||||
logger: { error: (message: string, meta?: Record<string, unknown>) => void },
|
||||
error: unknown,
|
||||
options: {
|
||||
message?: string
|
||||
operation?: string
|
||||
module?: string
|
||||
} = {}
|
||||
): never {
|
||||
logError(logger, error, options)
|
||||
throw error
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
/**
|
||||
* Unified logging system using Winston
|
||||
* Console + File transports with daily rotation
|
||||
*
|
||||
* Features:
|
||||
* - Full error serialization with stack traces
|
||||
* - Development/Production environment differentiation
|
||||
* - Structured logging with context
|
||||
*/
|
||||
|
||||
import winston from 'winston'
|
||||
@@ -8,6 +13,7 @@ import DailyRotateFile from 'winston-daily-rotate-file'
|
||||
import path from 'path'
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs'
|
||||
import { serializeError, sanitizeError } from './error-utils'
|
||||
|
||||
// Get log directory - use app.getPath('logs') in production, or local logs dir in development
|
||||
function getLogDir(): string {
|
||||
@@ -22,20 +28,54 @@ function getLogDir(): string {
|
||||
return devLogDir
|
||||
}
|
||||
|
||||
// Custom format for console output
|
||||
// Check if running in production
|
||||
const isProduction = app?.isPackaged ?? process.env.NODE_ENV === 'production'
|
||||
|
||||
// Custom format for console output - includes full error details
|
||||
const consoleFormat = winston.format.combine(
|
||||
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||
winston.format.colorize(),
|
||||
winston.format.printf(({ timestamp, level, message, context, ...meta }) => {
|
||||
winston.format.printf(({ timestamp, level, message, context, error, ...meta }) => {
|
||||
const contextStr = context ? `[${context}]` : ''
|
||||
const metaStr = Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : ''
|
||||
return `${timestamp} [${level}]${contextStr} ${message}${metaStr}`
|
||||
|
||||
// Format error with full stack trace
|
||||
let errorStr = ''
|
||||
if (error) {
|
||||
const serialized = isProduction ? sanitizeError(serializeError(error)) : serializeError(error)
|
||||
if (serialized.stack) {
|
||||
errorStr = `\n${serialized.stack}`
|
||||
} else {
|
||||
errorStr = ` ${serialized.message}`
|
||||
}
|
||||
}
|
||||
|
||||
const metaStr = Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta, null, 2)}` : ''
|
||||
return `${timestamp} [${level}]${contextStr} ${message}${errorStr}${metaStr}`
|
||||
})
|
||||
)
|
||||
|
||||
// Custom format for file output
|
||||
// Custom format for file output - JSON with full error details
|
||||
const fileFormat = winston.format.combine(
|
||||
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||
winston.format((info) => {
|
||||
// Serialize errors in metadata
|
||||
if (info.error) {
|
||||
info.error = isProduction
|
||||
? sanitizeError(serializeError(info.error))
|
||||
: serializeError(info.error)
|
||||
}
|
||||
|
||||
// Serialize any error in meta fields
|
||||
for (const key of Object.keys(info)) {
|
||||
if (key !== 'error' && info[key] instanceof Error) {
|
||||
info[key] = isProduction
|
||||
? sanitizeError(serializeError(info[key]))
|
||||
: serializeError(info[key])
|
||||
}
|
||||
}
|
||||
|
||||
return info
|
||||
})(),
|
||||
winston.format.json()
|
||||
)
|
||||
|
||||
@@ -52,9 +92,9 @@ const createFileTransport = (level?: string): DailyRotateFile => {
|
||||
})
|
||||
}
|
||||
|
||||
// Create the logger instance
|
||||
// Create the logger instance with default level
|
||||
const logger = winston.createLogger({
|
||||
level: process.env.LOG_LEVEL || 'info',
|
||||
level: 'info', // Default level, can be updated via setLogLevel()
|
||||
defaultMeta: { service: 'erpauto' },
|
||||
transports: [
|
||||
// Console transport - always enabled
|
||||
@@ -66,8 +106,16 @@ const logger = winston.createLogger({
|
||||
]
|
||||
})
|
||||
|
||||
/**
|
||||
* Update the logger level dynamically
|
||||
* @param level - The new log level
|
||||
*/
|
||||
export function setLogLevel(level: string): void {
|
||||
logger.level = level
|
||||
}
|
||||
|
||||
// Add error-specific file transport in production
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
if (app.isPackaged) {
|
||||
logger.add(
|
||||
new DailyRotateFile({
|
||||
filename: path.join(getLogDir(), 'error-%DATE%.log'),
|
||||
@@ -90,6 +138,24 @@ export function createLogger(context: string): winston.Logger {
|
||||
return logger.child({ context })
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an error with full context and stack trace
|
||||
* This is the recommended way to log errors in the application
|
||||
*
|
||||
* @param log - Logger instance
|
||||
* @param message - Error message
|
||||
* @param error - The error object (Error, BaseError, or any)
|
||||
* @param meta - Additional metadata to include
|
||||
*/
|
||||
export function logError(
|
||||
log: winston.Logger,
|
||||
message: string,
|
||||
error: unknown,
|
||||
meta?: Record<string, unknown>
|
||||
): void {
|
||||
log.error(message, { error, ...meta })
|
||||
}
|
||||
|
||||
// Export the main logger for direct use
|
||||
export default logger
|
||||
|
||||
|
||||
299
src/main/services/report/cleaner-report-generator.ts
Normal file
299
src/main/services/report/cleaner-report-generator.ts
Normal file
@@ -0,0 +1,299 @@
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { app } from 'electron'
|
||||
import { createLogger } from '../logger'
|
||||
import type { CleanerResult, OrderCleanDetail, SkippedMaterial } from '../../types/cleaner.types'
|
||||
|
||||
const log = createLogger('CleanerReportGenerator')
|
||||
|
||||
export interface ReportOptions {
|
||||
dryRun: boolean
|
||||
username: string
|
||||
startTime: number
|
||||
endTime: number
|
||||
}
|
||||
|
||||
interface OrderStats {
|
||||
successCount: number
|
||||
failureCount: number
|
||||
successRate: number
|
||||
}
|
||||
|
||||
export class CleanerReportGenerator {
|
||||
private readonly reportDir: string
|
||||
|
||||
constructor() {
|
||||
const logDir = app.isReady() ? app.getPath('logs') : path.join(process.cwd(), 'logs')
|
||||
this.reportDir = path.join(logDir, 'reports')
|
||||
this.ensureReportDir()
|
||||
}
|
||||
|
||||
private ensureReportDir(): void {
|
||||
if (!fs.existsSync(this.reportDir)) {
|
||||
fs.mkdirSync(this.reportDir, { recursive: true })
|
||||
log.info('Created report directory', { path: this.reportDir })
|
||||
}
|
||||
}
|
||||
|
||||
async generateReport(result: CleanerResult, options: ReportOptions): Promise<string> {
|
||||
const filePath = this.getReportFilePath()
|
||||
log.info('Generating cleaner report', { path: filePath })
|
||||
|
||||
const stats = this.calculateOrderStats(result)
|
||||
const content = this.buildReportContent(result, options, stats)
|
||||
|
||||
await fs.promises.writeFile(filePath, content, 'utf-8')
|
||||
log.info('Report generated successfully', { path: filePath })
|
||||
|
||||
return filePath
|
||||
}
|
||||
|
||||
private getReportFilePath(): string {
|
||||
const now = new Date()
|
||||
const timestamp = now.toISOString().replace(/[:.]/g, '-').slice(0, -5).replace('T', '-')
|
||||
const fileName = `cleaner-report-${timestamp}.md`
|
||||
return path.join(this.reportDir, fileName)
|
||||
}
|
||||
|
||||
private calculateOrderStats(result: CleanerResult): OrderStats {
|
||||
const totalOrders = result.details.length
|
||||
const failureCount = result.details.filter((d) => d.errors.length > 0).length
|
||||
const successCount = totalOrders - failureCount
|
||||
const successRate = totalOrders > 0 ? (successCount / totalOrders) * 100 : 0
|
||||
|
||||
return {
|
||||
successCount,
|
||||
failureCount,
|
||||
successRate
|
||||
}
|
||||
}
|
||||
|
||||
private buildReportContent(
|
||||
result: CleanerResult,
|
||||
options: ReportOptions,
|
||||
stats: OrderStats
|
||||
): string {
|
||||
const lines: string[] = []
|
||||
|
||||
lines.push('# ERP 物料清理执行报告')
|
||||
lines.push('')
|
||||
|
||||
lines.push('## 执行摘要')
|
||||
lines.push('')
|
||||
lines.push('| 项目 | 值 |')
|
||||
lines.push('| -------------- | --------------------------------- |')
|
||||
lines.push(`| **执行时间** | \`${this.formatDateTime(options.endTime)}\``)
|
||||
lines.push(`| **执行模式** | \`${options.dryRun ? '模拟运行 (Dry Run)' : '正式执行'}\``)
|
||||
lines.push(`| **操作用户** | \`${options.username}\``)
|
||||
lines.push(`| **处理订单数** | \`${result.ordersProcessed}\``)
|
||||
lines.push(`| **删除物料数** | \`${result.materialsDeleted}\``)
|
||||
lines.push(`| **跳过物料数** | \`${result.materialsSkipped}\``)
|
||||
lines.push(`| **错误数量** | \`${result.errors.length}\``)
|
||||
if (result.retriedOrders > 0) {
|
||||
lines.push(`| **重试订单数** | \`${result.retriedOrders}\``)
|
||||
lines.push(`| **成功重试数** | \`${result.successfulRetries}\``)
|
||||
}
|
||||
lines.push(`| **执行耗时** | \`${this.formatDuration(options.startTime, options.endTime)}\``)
|
||||
lines.push('')
|
||||
lines.push('---')
|
||||
lines.push('')
|
||||
|
||||
lines.push('## 执行状态')
|
||||
lines.push('')
|
||||
lines.push('| 状态 | 数量 | 百分比 |')
|
||||
lines.push('| ----------- | ---- | ------ |')
|
||||
lines.push(`| ✅ 成功订单 | ${stats.successCount} | ${stats.successRate.toFixed(1)}% |`)
|
||||
lines.push(`| ❌ 失败订单 | ${stats.failureCount} | ${(100 - stats.successRate).toFixed(1)}% |`)
|
||||
if (result.retriedOrders > 0) {
|
||||
const retrySuccessRate =
|
||||
result.retriedOrders > 0 ? (result.successfulRetries / result.retriedOrders) * 100 : 0
|
||||
lines.push(`| 🔄 重试订单 | ${result.retriedOrders} | 100% |`)
|
||||
lines.push(`| ✅ 成功重试 | ${result.successfulRetries} | ${retrySuccessRate.toFixed(1)}% |`)
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('---')
|
||||
lines.push('')
|
||||
|
||||
lines.push('## 订单处理详情')
|
||||
lines.push('')
|
||||
lines.push('| # | 订单号 | 删除数 | 跳过数 | 状态 | 错误信息 |')
|
||||
lines.push('| --- | -------- | ------ | ------ | ------- | ------------------------ |')
|
||||
|
||||
result.details.forEach((detail, index) => {
|
||||
const orderNum = index + 1
|
||||
let status = detail.errors.length > 0 ? '❌ 失败' : '✅ 成功'
|
||||
|
||||
// Override status if retry was successful
|
||||
if (detail.retrySuccess) {
|
||||
status = '✅ 重试成功'
|
||||
} else if (detail.retryCount > 0 && !detail.retrySuccess) {
|
||||
status = '❌ 重试失败'
|
||||
}
|
||||
|
||||
const errorMsg = detail.errors.length > 0 ? detail.errors[0] : '-'
|
||||
const retryInfo = detail.retryCount > 0 ? ` [重试${detail.retryCount}次]` : ''
|
||||
lines.push(
|
||||
`| ${orderNum} | \`${detail.orderNumber}\` | ${detail.materialsDeleted} | ${detail.materialsSkipped} | ${status}${retryInfo} | \`${errorMsg}\` |`
|
||||
)
|
||||
})
|
||||
|
||||
lines.push('')
|
||||
lines.push('---')
|
||||
lines.push('')
|
||||
|
||||
const allSkippedMaterials = this.collectAllSkippedMaterials(result.details)
|
||||
if (allSkippedMaterials.length > 0) {
|
||||
lines.push('## 跳过的物料原因说明')
|
||||
lines.push('')
|
||||
lines.push('| 订单号 | 物料代码 | 物料名称 | 行号 | 跳过原因 |')
|
||||
lines.push('| -------- | -------- | -------- | ---- | --------------------------------- |')
|
||||
|
||||
allSkippedMaterials.forEach((skipped) => {
|
||||
lines.push(
|
||||
`| \`${skipped.orderNumber}\` | \`${skipped.materialCode}\` | \`${skipped.materialName}\` | ${skipped.rowNumber} | ${skipped.reason} |`
|
||||
)
|
||||
})
|
||||
|
||||
lines.push('')
|
||||
lines.push('---')
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
if (result.errors.length > 0) {
|
||||
lines.push('## 错误详情')
|
||||
lines.push('')
|
||||
lines.push(`**错误总数**: \`${result.errors.length}\``)
|
||||
lines.push('')
|
||||
lines.push('### 错误订单列表')
|
||||
lines.push('')
|
||||
|
||||
const errorOrders = this.extractErrorOrders(result.details)
|
||||
errorOrders.forEach((order) => {
|
||||
lines.push(`- \`${order}\``)
|
||||
})
|
||||
|
||||
lines.push('')
|
||||
lines.push('### 错误详细信息')
|
||||
lines.push('')
|
||||
|
||||
result.details
|
||||
.filter((d) => d.errors.length > 0)
|
||||
.forEach((detail) => {
|
||||
lines.push(`#### \`${detail.orderNumber}\``)
|
||||
lines.push('')
|
||||
lines.push('```')
|
||||
lines.push(`订单号:${detail.orderNumber}`)
|
||||
detail.errors.forEach((error) => {
|
||||
lines.push(`错误:${error}`)
|
||||
})
|
||||
lines.push('```')
|
||||
lines.push('')
|
||||
})
|
||||
|
||||
lines.push('---')
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
// Add retry details section
|
||||
if (result.retriedOrders > 0) {
|
||||
lines.push('## 重试执行详情')
|
||||
lines.push('')
|
||||
lines.push(
|
||||
`**重试订单总数**: \`${result.retriedOrders}\` | **成功**: \`${result.successfulRetries}\` | **失败**: \`${result.retriedOrders - result.successfulRetries}\``
|
||||
)
|
||||
lines.push('')
|
||||
|
||||
const retriedDetails = result.details.filter((d) => d.retryCount > 0)
|
||||
|
||||
if (retriedDetails.length > 0) {
|
||||
lines.push('### 重试订单列表')
|
||||
lines.push('')
|
||||
lines.push('| 订单号 | 重试次数 | 重试结果 | 重试时间 |')
|
||||
lines.push('| -------- | -------- | -------- | ------------ |')
|
||||
|
||||
retriedDetails.forEach((detail) => {
|
||||
const retryStatus = detail.retrySuccess ? '✅ 成功' : '❌ 失败'
|
||||
const retryTime = detail.retriedAt ? this.formatDateTime(detail.retriedAt) : '-'
|
||||
lines.push(
|
||||
`| \`${detail.orderNumber}\` | ${detail.retryCount} | ${retryStatus} | ${retryTime} |`
|
||||
)
|
||||
})
|
||||
|
||||
lines.push('')
|
||||
lines.push('### 重试尝试详细记录')
|
||||
lines.push('')
|
||||
|
||||
retriedDetails.forEach((detail) => {
|
||||
lines.push(`#### \`${detail.orderNumber}\``)
|
||||
lines.push('')
|
||||
lines.push(`- **重试次数**: ${detail.retryCount}`)
|
||||
lines.push(`- **最终结果**: ${detail.retrySuccess ? '✅ 成功' : '❌ 失败'}`)
|
||||
|
||||
if (detail.retryAttempts && detail.retryAttempts.length > 0) {
|
||||
lines.push('')
|
||||
lines.push('**重试尝试记录**:')
|
||||
lines.push('')
|
||||
detail.retryAttempts.forEach((attempt, idx) => {
|
||||
lines.push(
|
||||
`${idx + 1}. **第${attempt.attempt}次尝试** - ${this.formatDateTime(attempt.timestamp)}`
|
||||
)
|
||||
lines.push(` - 错误:${attempt.error}`)
|
||||
})
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
lines.push('---')
|
||||
lines.push('')
|
||||
})
|
||||
}
|
||||
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
lines.push(`**报告生成时间**: \`${this.formatDateTime(options.endTime)}\``)
|
||||
lines.push('**报表版本**: `v1.0`')
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
private collectAllSkippedMaterials(
|
||||
details: OrderCleanDetail[]
|
||||
): Array<SkippedMaterial & { orderNumber: string }> {
|
||||
const result: Array<SkippedMaterial & { orderNumber: string }> = []
|
||||
|
||||
details.forEach((detail) => {
|
||||
if (detail.skippedMaterials && detail.skippedMaterials.length > 0) {
|
||||
detail.skippedMaterials.forEach((skipped) => {
|
||||
result.push({
|
||||
...skipped,
|
||||
orderNumber: detail.orderNumber
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
private extractErrorOrders(details: OrderCleanDetail[]): string[] {
|
||||
return details.filter((d) => d.errors.length > 0).map((d) => d.orderNumber)
|
||||
}
|
||||
|
||||
private formatDateTime(timestamp: number): string {
|
||||
const date = new Date(timestamp)
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
const hours = String(date.getHours()).padStart(2, '0')
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0')
|
||||
const seconds = String(date.getSeconds()).padStart(2, '0')
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
|
||||
}
|
||||
|
||||
private formatDuration(startTime: number, endTime: number): string {
|
||||
const durationMs = endTime - startTime
|
||||
const minutes = Math.floor(durationMs / 60000)
|
||||
const seconds = Math.floor((durationMs % 60000) / 1000)
|
||||
return `${minutes}分${seconds}秒`
|
||||
}
|
||||
}
|
||||
6
src/main/services/rustfs/index.ts
Normal file
6
src/main/services/rustfs/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* RustFS Service Module
|
||||
*/
|
||||
|
||||
export { RustfsService } from './rustfs-service'
|
||||
export type { UploadResult, DownloadResult, RustfsServiceOptions } from './rustfs-service'
|
||||
376
src/main/services/rustfs/rustfs-service.ts
Normal file
376
src/main/services/rustfs/rustfs-service.ts
Normal file
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* RustFS Service
|
||||
*
|
||||
* S3-compatible object storage service for persisting reports and files
|
||||
* Uses AWS SDK for S3 protocol compatibility
|
||||
*/
|
||||
|
||||
import {
|
||||
S3Client,
|
||||
PutObjectCommand,
|
||||
GetObjectCommand,
|
||||
DeleteObjectCommand,
|
||||
ListObjectsV2Command,
|
||||
type PutObjectCommandInput,
|
||||
type GetObjectCommandInput,
|
||||
type DeleteObjectCommandInput
|
||||
} from '@aws-sdk/client-s3'
|
||||
import { createLogger } from '../logger'
|
||||
import type { RustfsConfig } from '../../types/config.schema'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
|
||||
const log = createLogger('RustfsService')
|
||||
|
||||
export interface UploadResult {
|
||||
success: boolean
|
||||
key: string
|
||||
etag?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface DownloadResult {
|
||||
success: boolean
|
||||
content: Buffer
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface RustfsServiceOptions {
|
||||
config: RustfsConfig
|
||||
}
|
||||
|
||||
export class RustfsService {
|
||||
private client: S3Client
|
||||
private config: RustfsConfig
|
||||
|
||||
constructor(options: RustfsServiceOptions) {
|
||||
const { config } = options
|
||||
|
||||
this.config = config
|
||||
|
||||
// Configure S3 client for RustFS
|
||||
// RustFS is fully compatible with S3 protocol
|
||||
this.client = new S3Client({
|
||||
region: config.region || 'us-east-1',
|
||||
endpoint: config.endpoint,
|
||||
credentials: {
|
||||
accessKeyId: config.accessKey,
|
||||
secretAccessKey: config.secretKey
|
||||
},
|
||||
forcePathStyle: true // Required for some S3-compatible services
|
||||
})
|
||||
|
||||
log.info('RustFS service initialized', {
|
||||
endpoint: config.endpoint,
|
||||
bucket: config.bucket,
|
||||
region: config.region
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a file to RustFS
|
||||
* @param filePath - Local file path to upload
|
||||
* @param key - Object key (path) in the bucket
|
||||
* @param contentType - Optional MIME type
|
||||
*/
|
||||
async uploadFile(filePath: string, key: string, contentType?: string): Promise<UploadResult> {
|
||||
try {
|
||||
// Validate configuration
|
||||
if (!this.config.enabled) {
|
||||
return {
|
||||
success: false,
|
||||
key,
|
||||
error: 'RustFS is not enabled in configuration'
|
||||
}
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return {
|
||||
success: false,
|
||||
key,
|
||||
error: `File not found: ${filePath}`
|
||||
}
|
||||
}
|
||||
|
||||
// Read file content
|
||||
const fileContent = await fs.promises.readFile(filePath)
|
||||
|
||||
// Determine content type
|
||||
const mimeType = contentType || this.getMimeType(filePath) || 'application/octet-stream'
|
||||
|
||||
log.info('Uploading file to RustFS', {
|
||||
filePath,
|
||||
key,
|
||||
contentType: mimeType,
|
||||
size: fileContent.length
|
||||
})
|
||||
|
||||
const input: PutObjectCommandInput = {
|
||||
Bucket: this.config.bucket,
|
||||
Key: key,
|
||||
Body: fileContent,
|
||||
ContentType: mimeType
|
||||
}
|
||||
|
||||
const command = new PutObjectCommand(input)
|
||||
const response = await this.client.send(command)
|
||||
|
||||
log.info('File uploaded successfully', {
|
||||
key,
|
||||
etag: response.ETag
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
key,
|
||||
etag: response.ETag
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown upload error'
|
||||
log.error('Failed to upload file to RustFS', {
|
||||
filePath,
|
||||
key,
|
||||
error: errorMessage
|
||||
})
|
||||
|
||||
return {
|
||||
success: false,
|
||||
key,
|
||||
error: errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a string content directly to RustFS
|
||||
* @param content - String content to upload
|
||||
* @param key - Object key (path) in the bucket
|
||||
* @param contentType - Optional MIME type
|
||||
*/
|
||||
async uploadString(content: string, key: string, contentType?: string): Promise<UploadResult> {
|
||||
try {
|
||||
if (!this.config.enabled) {
|
||||
return {
|
||||
success: false,
|
||||
key,
|
||||
error: 'RustFS is not enabled in configuration'
|
||||
}
|
||||
}
|
||||
|
||||
const mimeType = contentType || 'text/plain; charset=utf-8'
|
||||
|
||||
log.info('Uploading string content to RustFS', {
|
||||
key,
|
||||
contentType: mimeType,
|
||||
size: content.length
|
||||
})
|
||||
|
||||
const input: PutObjectCommandInput = {
|
||||
Bucket: this.config.bucket,
|
||||
Key: key,
|
||||
Body: Buffer.from(content, 'utf-8'),
|
||||
ContentType: mimeType
|
||||
}
|
||||
|
||||
const command = new PutObjectCommand(input)
|
||||
const response = await this.client.send(command)
|
||||
|
||||
log.info('String content uploaded successfully', {
|
||||
key,
|
||||
etag: response.ETag
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
key,
|
||||
etag: response.ETag
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown upload error'
|
||||
log.error('Failed to upload string to RustFS', {
|
||||
key,
|
||||
error: errorMessage
|
||||
})
|
||||
|
||||
return {
|
||||
success: false,
|
||||
key,
|
||||
error: errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a file from RustFS
|
||||
* @param key - Object key (path) in the bucket
|
||||
*/
|
||||
async downloadFile(key: string): Promise<DownloadResult> {
|
||||
try {
|
||||
if (!this.config.enabled) {
|
||||
return {
|
||||
success: false,
|
||||
content: Buffer.alloc(0),
|
||||
error: 'RustFS is not enabled in configuration'
|
||||
}
|
||||
}
|
||||
|
||||
log.info('Downloading file from RustFS', { key })
|
||||
|
||||
const input: GetObjectCommandInput = {
|
||||
Bucket: this.config.bucket,
|
||||
Key: key
|
||||
}
|
||||
|
||||
const command = new GetObjectCommand(input)
|
||||
const response = await this.client.send(command)
|
||||
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of response.Body as any) {
|
||||
chunks.push(Buffer.from(chunk))
|
||||
}
|
||||
|
||||
const content = Buffer.concat(chunks)
|
||||
|
||||
log.info('File downloaded successfully', {
|
||||
key,
|
||||
size: content.length
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
content
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown download error'
|
||||
log.error('Failed to download file from RustFS', {
|
||||
key,
|
||||
error: errorMessage
|
||||
})
|
||||
|
||||
return {
|
||||
success: false,
|
||||
content: Buffer.alloc(0),
|
||||
error: errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a file from RustFS
|
||||
* @param key - Object key (path) in the bucket
|
||||
*/
|
||||
async deleteFile(key: string): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
if (!this.config.enabled) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'RustFS is not enabled in configuration'
|
||||
}
|
||||
}
|
||||
|
||||
log.info('Deleting file from RustFS', { key })
|
||||
|
||||
const input: DeleteObjectCommandInput = {
|
||||
Bucket: this.config.bucket,
|
||||
Key: key
|
||||
}
|
||||
|
||||
const command = new DeleteObjectCommand(input)
|
||||
await this.client.send(command)
|
||||
|
||||
log.info('File deleted successfully', { key })
|
||||
|
||||
return {
|
||||
success: true
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown delete error'
|
||||
log.error('Failed to delete file from RustFS', {
|
||||
key,
|
||||
error: errorMessage
|
||||
})
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a storage key for cleaner reports
|
||||
* @param reportFileName - Original report file name
|
||||
* @param username - Username who generated the report
|
||||
*/
|
||||
generateReportKey(reportFileName: string, username: string): string {
|
||||
// Organize reports by user for easy access
|
||||
// Format: reports/cleaner/{username}/{filename}
|
||||
return `reports/cleaner/${username}/${reportFileName}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Get MIME type based on file extension
|
||||
*/
|
||||
private getMimeType(filePath: string): string | null {
|
||||
const ext = path.extname(filePath).toLowerCase()
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'.md': 'text/markdown; charset=utf-8',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'.xls': 'application/vnd.ms-excel',
|
||||
'.csv': 'text/csv; charset=utf-8',
|
||||
'.pdf': 'application/pdf',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif'
|
||||
}
|
||||
return mimeTypes[ext] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Test connection to RustFS
|
||||
*/
|
||||
async testConnection(): Promise<{
|
||||
success: boolean
|
||||
message: string
|
||||
error?: string
|
||||
}> {
|
||||
try {
|
||||
log.info('Testing RustFS connection', {
|
||||
endpoint: this.config.endpoint,
|
||||
bucket: this.config.bucket
|
||||
})
|
||||
|
||||
// Try to list objects in the bucket (head bucket operation)
|
||||
const input = {
|
||||
Bucket: this.config.bucket,
|
||||
Prefix: '',
|
||||
MaxKeys: 1
|
||||
}
|
||||
|
||||
const command = new ListObjectsV2Command(input)
|
||||
await this.client.send(command)
|
||||
|
||||
log.info('RustFS connection test successful')
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '连接成功'
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown connection error'
|
||||
log.error('RustFS connection test failed', {
|
||||
error: errorMessage
|
||||
})
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: '连接失败',
|
||||
error: errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,12 @@
|
||||
|
||||
import { MySqlService } from '../database/mysql'
|
||||
import { SqlServerService } from '../database/sql-server'
|
||||
import { ConfigManager } from '../config/config-manager'
|
||||
import sql from 'mssql'
|
||||
import type { UserInfo } from '../../types/user.types'
|
||||
import { createLogger, logError } from '../logger'
|
||||
|
||||
const log = createLogger('BipUsersDao')
|
||||
|
||||
/**
|
||||
* Database configuration for BIPUsers table
|
||||
@@ -27,8 +31,12 @@ export const BIP_USERS_CONFIG = {
|
||||
USERNAME: 'UserName',
|
||||
USER_TYPE: 'UserType',
|
||||
PASSWORD: 'Password',
|
||||
COMPUTER_NAME: 'ComputerNmae', // Note: typo in database schema
|
||||
CREATE_TIME: 'CreateTime'
|
||||
COMPUTER_NAME: 'ComputerName',
|
||||
CREATE_TIME: 'CreateTime',
|
||||
// ERP Configuration columns
|
||||
ERP_URL: 'ERP_URL',
|
||||
ERP_USERNAME: 'ERP_Username',
|
||||
ERP_PASSWORD: 'ERP_Password'
|
||||
}
|
||||
} as const
|
||||
|
||||
@@ -39,17 +47,14 @@ export class BIPUsersDAO {
|
||||
private mysqlService: MySqlService | null = null
|
||||
private sqlServerService: SqlServerService | null = null
|
||||
private dbType: 'mysql' | 'sqlserver' = 'mysql'
|
||||
private configManager: ConfigManager
|
||||
|
||||
/**
|
||||
* Constructor - determine database type from environment
|
||||
* Constructor - get database type from ConfigManager
|
||||
*/
|
||||
constructor() {
|
||||
const dbType = process.env.DB_TYPE?.toLowerCase()
|
||||
if (dbType === 'sqlserver' || dbType === 'mssql') {
|
||||
this.dbType = 'sqlserver'
|
||||
} else {
|
||||
this.dbType = 'mysql'
|
||||
}
|
||||
this.configManager = ConfigManager.getInstance()
|
||||
this.dbType = this.configManager.getDatabaseType()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,20 +70,23 @@ export class BIPUsersDAO {
|
||||
* Get database service instance (MySQL or SQL Server)
|
||||
*/
|
||||
private async getDatabaseService(): Promise<MySqlService | SqlServerService> {
|
||||
const config = this.configManager.getConfig()
|
||||
|
||||
if (this.dbType === 'sqlserver') {
|
||||
if (this.sqlServerService && this.sqlServerService.isConnected()) {
|
||||
return this.sqlServerService
|
||||
}
|
||||
|
||||
const dbConfig = config.database.sqlserver
|
||||
this.sqlServerService = new SqlServerService({
|
||||
server: process.env.DB_SERVER || 'localhost',
|
||||
port: parseInt(process.env.DB_SQLSERVER_PORT || '1433', 10),
|
||||
user: process.env.DB_USERNAME || 'sa',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || '',
|
||||
server: dbConfig.server,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
options: {
|
||||
encrypt: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes',
|
||||
trustServerCertificate: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
|
||||
encrypt: false,
|
||||
trustServerCertificate: dbConfig.trustServerCertificate
|
||||
}
|
||||
})
|
||||
|
||||
@@ -89,12 +97,13 @@ export class BIPUsersDAO {
|
||||
return this.mysqlService
|
||||
}
|
||||
|
||||
const dbConfig = config.database.mysql
|
||||
this.mysqlService = new MySqlService({
|
||||
host: process.env.DB_MYSQL_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
|
||||
user: process.env.DB_USERNAME || 'root',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || ''
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database
|
||||
})
|
||||
|
||||
await this.mysqlService.connect()
|
||||
@@ -121,8 +130,8 @@ export class BIPUsersDAO {
|
||||
`
|
||||
|
||||
const result = await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
username: { value: username, type: sql.NVarChar },
|
||||
password: { value: password, type: sql.NVarChar }
|
||||
username: { value: username, type: sql.NVarChar(255) },
|
||||
password: { value: password, type: sql.NVarChar(255) }
|
||||
})
|
||||
|
||||
if (result.rows.length > 0) {
|
||||
@@ -154,7 +163,11 @@ export class BIPUsersDAO {
|
||||
return null
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] Authenticate error:', error)
|
||||
logError(log, 'Authenticate failed', error, {
|
||||
operation: 'authenticate',
|
||||
username,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -173,11 +186,11 @@ export class BIPUsersDAO {
|
||||
const sqlString = `
|
||||
SELECT ID, UserName, UserType
|
||||
FROM ${tableName}
|
||||
WHERE ComputerNmae = @computerName
|
||||
WHERE ComputerName = @computerName
|
||||
`
|
||||
|
||||
const result = await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
computerName: { value: computerName, type: sql.NVarChar }
|
||||
computerName: { value: computerName, type: sql.NVarChar(255) }
|
||||
})
|
||||
|
||||
if (result.rows.length > 0) {
|
||||
@@ -193,7 +206,7 @@ export class BIPUsersDAO {
|
||||
const sqlString = `
|
||||
SELECT ID, UserName, UserType
|
||||
FROM ${tableName}
|
||||
WHERE ComputerNmae = ?
|
||||
WHERE ComputerName = ?
|
||||
`
|
||||
|
||||
const result = await (dbService as MySqlService).query(sqlString, [computerName])
|
||||
@@ -209,7 +222,11 @@ export class BIPUsersDAO {
|
||||
return null
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] Authenticate by computer name error:', error)
|
||||
logError(log, 'Silent login failed', error, {
|
||||
operation: 'authenticateByComputerName',
|
||||
computerName,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -241,7 +258,10 @@ export class BIPUsersDAO {
|
||||
createTime: row.CreateTime as Date | undefined
|
||||
}))
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] Get all users error:', error)
|
||||
logError(log, 'Get all users failed', error, {
|
||||
operation: 'getAllUsers',
|
||||
dbType: this.dbType
|
||||
})
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -265,49 +285,55 @@ export class BIPUsersDAO {
|
||||
const tableName = this.getTableName()
|
||||
|
||||
if (this.dbType === 'sqlserver') {
|
||||
let sql: string
|
||||
let params: Record<string, { value: unknown; type?: sql.ISqlType }>
|
||||
let sqlString: string
|
||||
let params: Record<
|
||||
string,
|
||||
{
|
||||
value: unknown
|
||||
type?: sql.ISqlType | sql.ISqlTypeFactoryWithLength | sql.ISqlTypeWithLength
|
||||
}
|
||||
>
|
||||
|
||||
if (computerName) {
|
||||
sql = `
|
||||
sqlString = `
|
||||
INSERT INTO ${tableName}
|
||||
(UserName, Password, UserType, ComputerNmae)
|
||||
(UserName, Password, UserType, ComputerName)
|
||||
VALUES (@username, @password, @userType, @computerName)
|
||||
`
|
||||
params = {
|
||||
username: { value: username, type: sql.NVarChar },
|
||||
password: { value: password, type: sql.NVarChar },
|
||||
userType: { value: userType, type: sql.NVarChar },
|
||||
computerName: { value: computerName, type: sql.NVarChar }
|
||||
username: { value: username, type: sql.NVarChar(255) },
|
||||
password: { value: password, type: sql.NVarChar(255) },
|
||||
userType: { value: userType, type: sql.NVarChar(255) },
|
||||
computerName: { value: computerName, type: sql.NVarChar(255) }
|
||||
}
|
||||
} else {
|
||||
sql = `
|
||||
sqlString = `
|
||||
INSERT INTO ${tableName}
|
||||
(UserName, Password, UserType)
|
||||
VALUES (@username, @password, @userType)
|
||||
`
|
||||
params = {
|
||||
username: { value: username, type: sql.NVarChar },
|
||||
password: { value: password, type: sql.NVarChar },
|
||||
userType: { value: userType, type: sql.NVarChar }
|
||||
username: { value: username, type: sql.NVarChar(255) },
|
||||
password: { value: password, type: sql.NVarChar(255) },
|
||||
userType: { value: userType, type: sql.NVarChar(255) }
|
||||
}
|
||||
}
|
||||
|
||||
await (dbService as SqlServerService).queryWithParams(sqlString, params)
|
||||
return true
|
||||
} else {
|
||||
let sql: string
|
||||
let params: any[]
|
||||
let sqlString: string
|
||||
let params: unknown[]
|
||||
|
||||
if (computerName) {
|
||||
sql = `
|
||||
sqlString = `
|
||||
INSERT INTO ${tableName}
|
||||
(UserName, Password, UserType, ComputerNmae)
|
||||
(UserName, Password, UserType, ComputerName)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`
|
||||
params = [username, password, userType, computerName]
|
||||
} else {
|
||||
sql = `
|
||||
sqlString = `
|
||||
INSERT INTO ${tableName}
|
||||
(UserName, Password, UserType)
|
||||
VALUES (?, ?, ?)
|
||||
@@ -319,7 +345,12 @@ export class BIPUsersDAO {
|
||||
return true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] Create user error:', error)
|
||||
logError(log, 'Create user failed', error, {
|
||||
operation: 'createUser',
|
||||
username,
|
||||
userType,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -343,8 +374,8 @@ export class BIPUsersDAO {
|
||||
`
|
||||
|
||||
await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
username: { value: username, type: sql.NVarChar },
|
||||
userType: { value: userType, type: sql.NVarChar }
|
||||
username: { value: username, type: sql.NVarChar(255) },
|
||||
userType: { value: userType, type: sql.NVarChar(255) }
|
||||
})
|
||||
return true
|
||||
} else {
|
||||
@@ -358,7 +389,12 @@ export class BIPUsersDAO {
|
||||
return true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] Update user type error:', error)
|
||||
logError(log, 'Update user type failed', error, {
|
||||
operation: 'updateUserType',
|
||||
username,
|
||||
userType,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -382,8 +418,8 @@ export class BIPUsersDAO {
|
||||
`
|
||||
|
||||
await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
username: { value: username, type: sql.NVarChar },
|
||||
newPassword: { value: newPassword, type: sql.NVarChar }
|
||||
username: { value: username, type: sql.NVarChar(255) },
|
||||
newPassword: { value: newPassword, type: sql.NVarChar(255) }
|
||||
})
|
||||
return true
|
||||
} else {
|
||||
@@ -397,7 +433,11 @@ export class BIPUsersDAO {
|
||||
return true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] Update password error:', error)
|
||||
logError(log, 'Update password failed', error, {
|
||||
operation: 'updatePassword',
|
||||
username,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -419,7 +459,7 @@ export class BIPUsersDAO {
|
||||
`
|
||||
|
||||
await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
username: { value: username, type: sql.NVarChar }
|
||||
username: { value: username, type: sql.NVarChar(255) }
|
||||
})
|
||||
return true
|
||||
} else {
|
||||
@@ -432,7 +472,11 @@ export class BIPUsersDAO {
|
||||
return true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] Delete user error:', error)
|
||||
logError(log, 'Delete user failed', error, {
|
||||
operation: 'deleteUser',
|
||||
username,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -455,7 +499,7 @@ export class BIPUsersDAO {
|
||||
`
|
||||
|
||||
const result = await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
username: { value: username, type: sql.NVarChar }
|
||||
username: { value: username, type: sql.NVarChar(255) }
|
||||
})
|
||||
return result.rows.length > 0 && (result.rows[0].count as number) > 0
|
||||
} else {
|
||||
@@ -469,11 +513,169 @@ export class BIPUsersDAO {
|
||||
return result.rows.length > 0 && (result.rows[0].count as number) > 0
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BIPUsersDAO] User exists error:', error)
|
||||
logError(log, 'Check user exists failed', error, {
|
||||
operation: 'userExists',
|
||||
username,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ERP credentials for a user (username and password only, URL is from config.yaml)
|
||||
* @param username - The username to get ERP credentials for
|
||||
* @returns ERP credentials object or null if not found
|
||||
*/
|
||||
async getUserErpCredentials(username: string): Promise<{
|
||||
username: string
|
||||
password: string
|
||||
} | null> {
|
||||
try {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const cols = BIP_USERS_CONFIG.COLUMNS
|
||||
|
||||
if (this.dbType === 'sqlserver') {
|
||||
const sqlString = `
|
||||
SELECT ${cols.ERP_USERNAME}, ${cols.ERP_PASSWORD}
|
||||
FROM ${tableName}
|
||||
WHERE UserName = @username
|
||||
`
|
||||
|
||||
const result = await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
username: { value: username, type: sql.NVarChar(255) }
|
||||
})
|
||||
|
||||
if (result.rows.length > 0) {
|
||||
const row = result.rows[0]
|
||||
return {
|
||||
username: (row[cols.ERP_USERNAME] as string) || '',
|
||||
password: (row[cols.ERP_PASSWORD] as string) || ''
|
||||
}
|
||||
}
|
||||
return null
|
||||
} else {
|
||||
const sqlString = `
|
||||
SELECT ${cols.ERP_USERNAME}, ${cols.ERP_PASSWORD}
|
||||
FROM ${tableName}
|
||||
WHERE UserName = ?
|
||||
`
|
||||
|
||||
const result = await (dbService as MySqlService).query(sqlString, [username])
|
||||
|
||||
if (result.rows.length > 0) {
|
||||
const row = result.rows[0]
|
||||
return {
|
||||
username: (row[cols.ERP_USERNAME] as string) || '',
|
||||
password: (row[cols.ERP_PASSWORD] as string) || ''
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
} catch (error) {
|
||||
logError(log, 'Get user ERP credentials failed', error, {
|
||||
operation: 'getUserErpCredentials',
|
||||
username,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update ERP credentials for a user (username and password only, URL is from config.yaml)
|
||||
* @param username - The username to update ERP credentials for
|
||||
* @param erpUsername - The ERP username
|
||||
* @param erpPassword - The ERP password
|
||||
* @returns True if successful
|
||||
*/
|
||||
async updateUserErpCredentials(
|
||||
username: string,
|
||||
erpUsername: string,
|
||||
erpPassword: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const cols = BIP_USERS_CONFIG.COLUMNS
|
||||
|
||||
if (this.dbType === 'sqlserver') {
|
||||
const sqlString = `
|
||||
UPDATE ${tableName}
|
||||
SET ${cols.ERP_USERNAME} = @erpUsername,
|
||||
${cols.ERP_PASSWORD} = @erpPassword
|
||||
WHERE UserName = @username
|
||||
`
|
||||
|
||||
await (dbService as SqlServerService).queryWithParams(sqlString, {
|
||||
username: { value: username, type: sql.NVarChar(255) },
|
||||
erpUsername: { value: erpUsername, type: sql.NVarChar(255) },
|
||||
erpPassword: { value: erpPassword, type: sql.NVarChar(255) }
|
||||
})
|
||||
return true
|
||||
} else {
|
||||
const sqlString = `
|
||||
UPDATE ${tableName}
|
||||
SET ${cols.ERP_USERNAME} = ?,
|
||||
${cols.ERP_PASSWORD} = ?
|
||||
WHERE UserName = ?
|
||||
`
|
||||
|
||||
await (dbService as MySqlService).query(sqlString, [erpUsername, erpPassword, username])
|
||||
return true
|
||||
}
|
||||
} catch (error) {
|
||||
logError(log, 'Update user ERP credentials failed', error, {
|
||||
operation: 'updateUserErpCredentials',
|
||||
username,
|
||||
dbType: this.dbType
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ERP configuration for all users (for migration/audit purposes)
|
||||
* @returns List of users with their ERP configurations
|
||||
*/
|
||||
async getAllUsersErpConfig(): Promise<
|
||||
Array<{
|
||||
username: string
|
||||
erpUrl: string
|
||||
erpUsername: string
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const dbService = await this.getDatabaseService()
|
||||
const tableName = this.getTableName()
|
||||
const cols = BIP_USERS_CONFIG.COLUMNS
|
||||
|
||||
const sqlString = `
|
||||
SELECT ${cols.USERNAME}, ${cols.ERP_URL}, ${cols.ERP_USERNAME}
|
||||
FROM ${tableName}
|
||||
ORDER BY ${cols.USERNAME}
|
||||
`
|
||||
|
||||
const result =
|
||||
this.dbType === 'sqlserver'
|
||||
? await (dbService as SqlServerService).query(sqlString)
|
||||
: await (dbService as MySqlService).query(sqlString)
|
||||
|
||||
return result.rows.map((row) => ({
|
||||
username: row[cols.USERNAME] as string,
|
||||
erpUrl: (row[cols.ERP_URL] as string) || '',
|
||||
erpUsername: (row[cols.ERP_USERNAME] as string) || ''
|
||||
}))
|
||||
} catch (error) {
|
||||
logError(log, 'Get all users ERP config failed', error, {
|
||||
operation: 'getAllUsersErpConfig',
|
||||
dbType: this.dbType
|
||||
})
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from database
|
||||
*/
|
||||
|
||||
289
src/main/services/user/migration/add-erp-params-migration.ts
Normal file
289
src/main/services/user/migration/add-erp-params-migration.ts
Normal file
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* Migration Script: Add ERP parameters to BIPUsers table
|
||||
*
|
||||
* This script adds ERP_URL, ERP_Username, and ERP_Password columns
|
||||
* to the dbo_BIPUsers table and initializes all existing users.
|
||||
*
|
||||
* Note: ERP credentials are now stored per-user in the database.
|
||||
* This migration is for backward compatibility only.
|
||||
*
|
||||
* Usage:
|
||||
* npx tsx src/main/services/user/migration/add-erp-params-migration.ts
|
||||
*/
|
||||
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { dirname } from 'path'
|
||||
import { ConfigManager } from '../../config/config-manager'
|
||||
import { MySqlService } from '../../database/mysql'
|
||||
import { SqlServerService } from '../../database/sql-server'
|
||||
import yaml from 'js-yaml'
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = dirname(__filename)
|
||||
|
||||
/**
|
||||
* Migration configuration
|
||||
*/
|
||||
const MIGRATION_CONFIG = {
|
||||
sqlFile: path.join(__dirname, 'add-erp-params-to-bipusers.sql'),
|
||||
tableName: {
|
||||
mysql: 'dbo_BIPUsers',
|
||||
sqlserver: '[dbo].[BIPUsers]'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if column exists in MySQL table
|
||||
*/
|
||||
async function checkColumnExistsMySQL(
|
||||
mysqlService: MySqlService,
|
||||
tableName: string,
|
||||
columnName: string
|
||||
): Promise<boolean> {
|
||||
const result = await mysqlService.query(
|
||||
`SELECT COUNT(*) as count FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
|
||||
[tableName, columnName]
|
||||
)
|
||||
return (result.rows[0]?.count as number) > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if column exists in SQL Server table
|
||||
*/
|
||||
async function checkColumnExistsSqlServer(
|
||||
sqlServerService: SqlServerService,
|
||||
tableName: string,
|
||||
columnName: string
|
||||
): Promise<boolean> {
|
||||
const result = await sqlServerService.query(
|
||||
`SELECT COUNT(*) as count FROM sys.columns
|
||||
WHERE OBJECT_ID = OBJECT_ID(?) AND name = ?`,
|
||||
[tableName, columnName]
|
||||
)
|
||||
return (result.rows[0]?.count as number) > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Add column to MySQL table
|
||||
*/
|
||||
async function addColumnMySQL(
|
||||
mysqlService: MySqlService,
|
||||
tableName: string,
|
||||
columnName: string,
|
||||
columnType: string
|
||||
): Promise<void> {
|
||||
await mysqlService.query(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${columnType}`)
|
||||
console.log(` ✓ Added column ${columnName} (${columnType})`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Add column to SQL Server table
|
||||
*/
|
||||
async function addColumnSqlServer(
|
||||
sqlServerService: SqlServerService,
|
||||
tableName: string,
|
||||
columnName: string,
|
||||
columnType: string
|
||||
): Promise<void> {
|
||||
await sqlServerService.query(`ALTER TABLE ${tableName} ADD ${columnName} ${columnType}`)
|
||||
console.log(` ✓ Added column ${columnName} (${columnType})`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize ERP credentials for all users in MySQL
|
||||
*/
|
||||
async function initializeErpCredentialsMySQL(
|
||||
mysqlService: MySqlService,
|
||||
tableName: string,
|
||||
erpUrl: string,
|
||||
erpUsername: string,
|
||||
erpPassword: string
|
||||
): Promise<void> {
|
||||
const result = await mysqlService.query(`SELECT COUNT(*) as count FROM ${tableName}`)
|
||||
const userCount = result.rows[0]?.count as number
|
||||
|
||||
if (userCount === 0) {
|
||||
console.log('No users found in BIPUsers table')
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`Initializing ERP credentials for ${userCount} user(s)...`)
|
||||
|
||||
await mysqlService.query(
|
||||
`UPDATE ${tableName} SET ERP_URL = ?, ERP_Username = ?, ERP_Password = ?`,
|
||||
[erpUrl, erpUsername, erpPassword]
|
||||
)
|
||||
|
||||
console.log('✓ ERP credentials initialized for all users')
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize ERP credentials for all users in SQL Server
|
||||
*/
|
||||
async function initializeErpCredentialsSqlServer(
|
||||
sqlServerService: SqlServerService,
|
||||
tableName: string,
|
||||
erpUrl: string,
|
||||
erpUsername: string,
|
||||
erpPassword: string
|
||||
): Promise<void> {
|
||||
const result = await sqlServerService.query(`SELECT COUNT(*) as count FROM ${tableName}`)
|
||||
const userCount = result.rows[0]?.count as number
|
||||
|
||||
if (userCount === 0) {
|
||||
console.log('No users found in BIPUsers table')
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`Initializing ERP credentials for ${userCount} user(s)...`)
|
||||
|
||||
await sqlServerService.query(
|
||||
`UPDATE ${tableName} SET ERP_URL = @p0, ERP_Username = @p1, ERP_Password = @p2`,
|
||||
[erpUrl, erpUsername, erpPassword]
|
||||
)
|
||||
|
||||
console.log('✓ ERP credentials initialized for all users')
|
||||
}
|
||||
|
||||
/**
|
||||
* Run migration for MySQL
|
||||
*/
|
||||
async function runMySQLMigration(configManager: ConfigManager): Promise<void> {
|
||||
console.log('\n📦 Running MySQL Migration...')
|
||||
|
||||
const config = configManager.getConfig()
|
||||
const dbConfig = config.database.mysql
|
||||
|
||||
console.log(`Connecting to MySQL: ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`)
|
||||
|
||||
const mysqlService = new MySqlService({
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database
|
||||
})
|
||||
|
||||
try {
|
||||
await mysqlService.connect()
|
||||
console.log('✓ Connected to MySQL')
|
||||
|
||||
const tableName = MIGRATION_CONFIG.tableName.mysql
|
||||
|
||||
// Check and add columns
|
||||
for (const [columnName, columnType] of [
|
||||
['ERP_URL', 'VARCHAR(500)'],
|
||||
['ERP_Username', 'VARCHAR(255)'],
|
||||
['ERP_Password', 'VARCHAR(255)']
|
||||
] as const) {
|
||||
const exists = await checkColumnExistsMySQL(mysqlService, tableName, columnName)
|
||||
if (exists) {
|
||||
console.log(` ✓ Column ${columnName} already exists`)
|
||||
} else {
|
||||
await addColumnMySQL(mysqlService, tableName, columnName, columnType)
|
||||
}
|
||||
}
|
||||
|
||||
// Note: ERP credentials are now managed per-user via settings UI
|
||||
// This migration no longer initializes them from config
|
||||
console.log('\n✓ MySQL Migration completed')
|
||||
console.log(' Note: ERP credentials should be configured per-user via the Settings UI')
|
||||
|
||||
await mysqlService.disconnect()
|
||||
} catch (error) {
|
||||
console.error('✗ MySQL Migration failed:', error instanceof Error ? error.message : error)
|
||||
if (mysqlService.isConnected()) {
|
||||
await mysqlService.disconnect()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run migration for SQL Server
|
||||
*/
|
||||
async function runSqlServerMigration(configManager: ConfigManager): Promise<void> {
|
||||
console.log('\n📦 Running SQL Server Migration...')
|
||||
|
||||
const config = configManager.getConfig()
|
||||
const dbConfig = config.database.sqlserver
|
||||
|
||||
console.log(`Connecting to SQL Server: ${dbConfig.server}:${dbConfig.port}/${dbConfig.database}`)
|
||||
|
||||
const sqlServerService = new SqlServerService({
|
||||
server: dbConfig.server,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.username,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
options: {
|
||||
trustServerCertificate: dbConfig.trustServerCertificate
|
||||
}
|
||||
})
|
||||
|
||||
try {
|
||||
await sqlServerService.connect()
|
||||
console.log('✓ Connected to SQL Server')
|
||||
|
||||
const tableName = MIGRATION_CONFIG.tableName.sqlserver
|
||||
|
||||
// Check and add columns
|
||||
for (const [columnName, columnType] of [
|
||||
['ERP_URL', 'NVARCHAR(500)'],
|
||||
['ERP_Username', 'NVARCHAR(255)'],
|
||||
['ERP_Password', 'NVARCHAR(255)']
|
||||
] as const) {
|
||||
const exists = await checkColumnExistsSqlServer(sqlServerService, tableName, columnName)
|
||||
if (exists) {
|
||||
console.log(` ✓ Column ${columnName} already exists`)
|
||||
} else {
|
||||
await addColumnSqlServer(sqlServerService, tableName, columnName, columnType)
|
||||
}
|
||||
}
|
||||
|
||||
// Note: ERP credentials are now managed per-user via settings UI
|
||||
console.log('\n✓ SQL Server Migration completed')
|
||||
console.log(' Note: ERP credentials should be configured per-user via the Settings UI')
|
||||
|
||||
await sqlServerService.disconnect()
|
||||
} catch (error) {
|
||||
console.error('✗ SQL Server Migration failed:', error instanceof Error ? error.message : error)
|
||||
if (sqlServerService.isConnected()) {
|
||||
await sqlServerService.disconnect()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function
|
||||
*/
|
||||
async function main(): Promise<void> {
|
||||
console.log('╔═══════════════════════════════════════════════════════════╗')
|
||||
console.log('║ Migration: Add ERP Parameters to BIPUsers Table ║')
|
||||
console.log('╚═══════════════════════════════════════════════════════════╝')
|
||||
|
||||
try {
|
||||
const configManager = ConfigManager.getInstance()
|
||||
await configManager.initialize()
|
||||
|
||||
const dbType = configManager.getDatabaseType()
|
||||
console.log(`\nCurrent database type: ${dbType}`)
|
||||
|
||||
if (dbType === 'mysql') {
|
||||
await runMySQLMigration(configManager)
|
||||
} else {
|
||||
await runSqlServerMigration(configManager)
|
||||
}
|
||||
|
||||
console.log('\n✅ Migration completed successfully!\n')
|
||||
} catch (error) {
|
||||
console.error('\n❌ Migration failed:', error instanceof Error ? error.message : error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
-- ============================================
|
||||
-- BIPUsers Table Migration: Add ERP Parameters
|
||||
-- Database: MySQL
|
||||
-- ============================================
|
||||
-- This script adds three new columns to store ERP connection parameters:
|
||||
-- - ERP_URL: The ERP system URL
|
||||
-- - ERP_Username: The ERP username
|
||||
-- - ERP_Password: The ERP password
|
||||
--
|
||||
-- Usage: Run this script in your MySQL client
|
||||
-- Example: mysql -u root -p BLD_DB < add-erp-params-to-bipusers-mysql.sql
|
||||
-- ============================================
|
||||
|
||||
USE BLD_DB;
|
||||
|
||||
-- Add ERP_URL column if not exists
|
||||
SET @dbname = DATABASE();
|
||||
SET @tablename = 'dbo_BIPUsers';
|
||||
SET @columnname = 'ERP_URL';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
(table_name = @tablename)
|
||||
AND (table_schema = @dbname)
|
||||
AND (column_name = @columnname)
|
||||
) > 0,
|
||||
'SELECT 1',
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' VARCHAR(500) NULL')
|
||||
));
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- Add ERP_Username column if not exists
|
||||
SET @columnname = 'ERP_Username';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
(table_name = @tablename)
|
||||
AND (table_schema = @dbname)
|
||||
AND (column_name = @columnname)
|
||||
) > 0,
|
||||
'SELECT 1',
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' VARCHAR(255) NULL')
|
||||
));
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- Add ERP_Password column if not exists
|
||||
SET @columnname = 'ERP_Password';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
(table_name = @tablename)
|
||||
AND (table_schema = @dbname)
|
||||
AND (column_name = @columnname)
|
||||
) > 0,
|
||||
'SELECT 1',
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' VARCHAR(255) NULL')
|
||||
));
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- Verify columns were added
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
DATA_TYPE,
|
||||
CHARACTER_MAXIMUM_LENGTH,
|
||||
IS_NULLABLE
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'dbo_BIPUsers'
|
||||
AND COLUMN_NAME IN ('ERP_URL', 'ERP_Username', 'ERP_Password');
|
||||
|
||||
-- Optional: Update all existing users with the same ERP credentials
|
||||
-- Replace the values below with your actual ERP credentials
|
||||
-- Example:
|
||||
-- UPDATE dbo_BIPUsers
|
||||
-- SET ERP_URL = 'https://68.11.34.30:8082/',
|
||||
-- ERP_Username = 'your_username',
|
||||
-- ERP_Password = 'your_password'
|
||||
-- WHERE ERP_URL IS NULL;
|
||||
|
||||
SELECT 'Migration completed successfully!' AS status;
|
||||
114
src/main/services/user/migration/add-erp-params-to-bipusers.sql
Normal file
114
src/main/services/user/migration/add-erp-params-to-bipusers.sql
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Database Migration Script
|
||||
* Add ERP configuration fields to dbo_BIPUsers table
|
||||
*
|
||||
* This script adds three new columns to store ERP connection parameters:
|
||||
* - ERP_URL: The ERP system URL
|
||||
* - ERP_USERNAME: The ERP username
|
||||
* - ERP_PASSWORD: The ERP password (encrypted in production)
|
||||
*
|
||||
* IMPORTANT:
|
||||
* - For SQL Server: Run this script on the SQL Server database
|
||||
* - For MySQL: Run this script on the MySQL database (syntax is auto-detected)
|
||||
* - All existing users will have the same ERP credentials (to be configured individually later)
|
||||
*/
|
||||
|
||||
-- ===========================================
|
||||
-- SQL Server Version
|
||||
-- ===========================================
|
||||
-- Uncomment and run this section for SQL Server
|
||||
/*
|
||||
IF NOT EXISTS (SELECT * FROM sys.columns
|
||||
WHERE object_id = OBJECT_ID(N'[dbo].[BIPUsers]')
|
||||
AND name = 'ERP_URL')
|
||||
BEGIN
|
||||
ALTER TABLE [dbo].[BIPUsers]
|
||||
ADD ERP_URL NVARCHAR(500) NULL;
|
||||
|
||||
ALTER TABLE [dbo].[BIPUsers]
|
||||
ADD ERP_Username NVARCHAR(255) NULL;
|
||||
|
||||
ALTER TABLE [dbo].[BIPUsers]
|
||||
ADD ERP_Password NVARCHAR(255) NULL;
|
||||
|
||||
PRINT 'ERP columns added successfully to [dbo].[BIPUsers]';
|
||||
END
|
||||
ELSE
|
||||
BEGIN
|
||||
PRINT 'ERP columns already exist in [dbo].[BIPUsers]';
|
||||
END
|
||||
|
||||
-- Optional: Update all existing users with the same ERP credentials
|
||||
-- Replace the values below with your actual ERP credentials
|
||||
-- UPDATE [dbo].[BIPUsers]
|
||||
-- SET ERP_URL = 'https://your-erp-system.com',
|
||||
-- ERP_Username = 'your_username',
|
||||
-- ERP_Password = 'your_password'
|
||||
-- WHERE ERP_URL IS NULL;
|
||||
*/
|
||||
|
||||
-- ===========================================
|
||||
-- MySQL Version
|
||||
-- ===========================================
|
||||
-- Run this section for MySQL
|
||||
|
||||
-- Add ERP_URL column if not exists
|
||||
SET @dbname = DATABASE();
|
||||
SET @tablename = 'dbo_BIPUsers';
|
||||
SET @columnname = 'ERP_URL';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
(table_name = @tablename)
|
||||
AND (table_schema = @dbname)
|
||||
AND (column_name = @columnname)
|
||||
) > 0,
|
||||
'SELECT 1',
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' VARCHAR(500) NULL')
|
||||
));
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- Add ERP_Username column if not exists
|
||||
SET @columnname = 'ERP_Username';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
(table_name = @tablename)
|
||||
AND (table_schema = @dbname)
|
||||
AND (column_name = @columnname)
|
||||
) > 0,
|
||||
'SELECT 1',
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' VARCHAR(255) NULL')
|
||||
));
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- Add ERP_Password column if not exists
|
||||
SET @columnname = 'ERP_Password';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
(table_name = @tablename)
|
||||
AND (table_schema = @dbname)
|
||||
AND (column_name = @columnname)
|
||||
) > 0,
|
||||
'SELECT 1',
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' VARCHAR(255) NULL')
|
||||
));
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- Optional: Update all existing users with the same ERP credentials
|
||||
-- Replace the values below with your actual ERP credentials
|
||||
-- UPDATE dbo_BIPUsers
|
||||
-- SET ERP_URL = 'https://your-erp-system.com',
|
||||
-- ERP_Username = 'your_username',
|
||||
-- ERP_Password = 'your_password'
|
||||
-- WHERE ERP_URL IS NULL;
|
||||
98
src/main/services/user/migration/manual-migration.sql
Normal file
98
src/main/services/user/migration/manual-migration.sql
Normal file
@@ -0,0 +1,98 @@
|
||||
-- ============================================
|
||||
-- BIPUsers 表迁移:添加 ERP 参数字段
|
||||
-- 数据库:MySQL
|
||||
-- 目标数据库:BLD_DB
|
||||
-- ============================================
|
||||
-- 使用说明:
|
||||
-- 1. 在 MySQL Workbench / Navicat / DBeaver 中打开此文件
|
||||
-- 2. 连接到数据库 192.168.31.83:3306/BLD_DB
|
||||
-- 3. 执行全部 SQL 语句
|
||||
-- ============================================
|
||||
|
||||
-- 切换到目标数据库
|
||||
USE BLD_DB;
|
||||
|
||||
-- ============================================
|
||||
-- 步骤 1: 添加新字段
|
||||
-- ============================================
|
||||
|
||||
-- 添加 ERP_URL 字段(如果不存在)
|
||||
-- 注意:如果 MySQL 版本不支持 ADD COLUMN IF NOT EXISTS,请移除 IF NOT EXISTS
|
||||
ALTER TABLE dbo_BIPUsers
|
||||
ADD COLUMN ERP_URL VARCHAR(500) NULL COMMENT 'ERP 系统 URL';
|
||||
|
||||
-- 添加 ERP_Username 字段
|
||||
ALTER TABLE dbo_BIPUsers
|
||||
ADD COLUMN ERP_Username VARCHAR(255) NULL COMMENT 'ERP 用户名';
|
||||
|
||||
-- 添加 ERP_Password 字段
|
||||
ALTER TABLE dbo_BIPUsers
|
||||
ADD COLUMN ERP_Password VARCHAR(255) NULL COMMENT 'ERP 密码';
|
||||
|
||||
-- ============================================
|
||||
-- 步骤 2: 验证字段已添加
|
||||
-- ============================================
|
||||
|
||||
-- 显示表结构,确认新字段已添加
|
||||
SELECT '字段添加验证' AS step;
|
||||
DESCRIBE dbo_BIPUsers;
|
||||
|
||||
-- 或者使用以下查询确认新字段
|
||||
SELECT
|
||||
COLUMN_NAME AS '字段名',
|
||||
DATA_TYPE AS '数据类型',
|
||||
CHARACTER_MAXIMUM_LENGTH AS '最大长度',
|
||||
IS_NULLABLE AS '允许 NULL',
|
||||
COLUMN_COMMENT AS '注释'
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = 'BLD_DB'
|
||||
AND TABLE_NAME = 'dbo_BIPUsers'
|
||||
AND COLUMN_NAME IN ('ERP_URL', 'ERP_Username', 'ERP_Password')
|
||||
ORDER BY COLUMN_NAME;
|
||||
|
||||
-- ============================================
|
||||
-- 步骤 3: 初始化 ERP 配置
|
||||
-- 注意:请根据实际情况修改下面的配置值!
|
||||
-- ============================================
|
||||
|
||||
SELECT '=== 请修改下面的 ERP 配置值 ===' AS notice;
|
||||
SELECT '当前数据库中的用户:' AS notice;
|
||||
SELECT UserName, UserType, ComputerName FROM dbo_BIPUsers ORDER BY UserName;
|
||||
|
||||
-- 更新所有用户的 ERP 配置
|
||||
-- ⚠️ 请修改下面的配置值为你实际的 ERP 凭证!
|
||||
UPDATE dbo_BIPUsers
|
||||
SET
|
||||
ERP_URL = 'https://68.11.34.30:8082/', -- 修改为你的 ERP 系统 URL
|
||||
ERP_Username = 'your_erp_username', -- 修改为你的 ERP 用户名
|
||||
ERP_Password = 'your_erp_password' -- 修改为你的 ERP 密码
|
||||
WHERE ERP_URL IS NULL OR ERP_URL = '';
|
||||
|
||||
-- 显示更新后的结果
|
||||
SELECT
|
||||
'更新后的 ERP 配置' AS notice,
|
||||
UserName,
|
||||
ERP_URL,
|
||||
ERP_Username
|
||||
FROM dbo_BIPUsers
|
||||
ORDER BY UserName;
|
||||
|
||||
-- ============================================
|
||||
-- 步骤 4: 完成确认
|
||||
-- ============================================
|
||||
|
||||
SELECT '================================' AS '';
|
||||
SELECT '迁移完成!' AS message;
|
||||
SELECT '================================' AS '';
|
||||
SELECT '请确认:' AS notice;
|
||||
SELECT '1. 所有用户都有 ERP_URL 配置' AS check1;
|
||||
SELECT '2. ERP_URL 格式正确' AS check2;
|
||||
SELECT '3. ERP 用户名和密码正确' AS check3;
|
||||
SELECT '================================' AS '';
|
||||
|
||||
-- 统计信息
|
||||
SELECT
|
||||
COUNT(*) AS total_users,
|
||||
COUNT(ERP_URL) AS users_with_erp_url,
|
||||
COUNT(ERP_Username) AS users_with_erp_username
|
||||
FROM dbo_BIPUsers;
|
||||
203
src/main/services/user/migration/run-migration.ts
Normal file
203
src/main/services/user/migration/run-migration.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Simple Migration Script: Add ERP parameters to BIPUsers table
|
||||
*
|
||||
* This script adds ERP_URL, ERP_Username, and ERP_Password columns
|
||||
* to the dbo_BIPUsers table.
|
||||
*
|
||||
* Usage:
|
||||
* npx tsx src/main/services/user/migration/run-migration.ts
|
||||
*/
|
||||
|
||||
import * as mysql from 'mysql2/promise'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { dirname } from 'path'
|
||||
import yaml from 'js-yaml'
|
||||
import { z } from 'zod'
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
|
||||
/**
|
||||
* MySQL configuration schema
|
||||
*/
|
||||
const mysqlConfigSchema = z.object({
|
||||
host: z.string(),
|
||||
port: z.number(),
|
||||
database: z.string(),
|
||||
username: z.string(),
|
||||
password: z.string()
|
||||
})
|
||||
|
||||
/**
|
||||
* Load config.yaml file
|
||||
*/
|
||||
function loadConfig(filePath: string): {
|
||||
host: string
|
||||
port: number
|
||||
database: string
|
||||
username: string
|
||||
password: string
|
||||
} {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(`Config file not found: ${filePath}`)
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(filePath, 'utf-8')
|
||||
const parsed = yaml.load(content) as Record<string, unknown>
|
||||
|
||||
// Safely extract database.mysql config
|
||||
const database = parsed?.database as Record<string, unknown> | undefined
|
||||
const mysql = database?.mysql as Record<string, unknown> | undefined
|
||||
|
||||
const result = mysqlConfigSchema.parse(mysql)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if column exists in MySQL table
|
||||
*/
|
||||
async function checkColumnExists(
|
||||
connection: mysql.Connection,
|
||||
tableName: string,
|
||||
columnName: string
|
||||
): Promise<boolean> {
|
||||
const sql = `
|
||||
SELECT COUNT(*) as count
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?
|
||||
`
|
||||
const [rows] = await connection.query(sql, [tableName, columnName])
|
||||
const result = rows as any[]
|
||||
return result.length > 0 && result[0].count > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Add column to MySQL table
|
||||
*/
|
||||
async function addColumn(
|
||||
connection: mysql.Connection,
|
||||
tableName: string,
|
||||
columnName: string,
|
||||
columnType: string
|
||||
): Promise<void> {
|
||||
const sql = `ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${columnType} NULL`
|
||||
await connection.query(sql)
|
||||
console.log(` ✓ Added column ${columnName} to ${tableName}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Main migration function
|
||||
*/
|
||||
async function runMigration(): Promise<void> {
|
||||
console.log('==============================================')
|
||||
console.log('BIPUsers Table Migration: Add ERP Parameters')
|
||||
console.log('==============================================\n')
|
||||
|
||||
// Load config.yaml from project root or user data directory
|
||||
const isDev = !process.execPath.includes('Resources\\app')
|
||||
const configPath = isDev
|
||||
? path.resolve(process.cwd(), 'config.yaml')
|
||||
: path.join(process.env.APPDATA || '', 'erpauto', 'config.yaml')
|
||||
|
||||
console.log(`Loading config from: ${configPath}`)
|
||||
|
||||
let dbConfig: { host: string; port: number; database: string; username: string; password: string }
|
||||
|
||||
try {
|
||||
dbConfig = loadConfig(configPath)
|
||||
} catch (error) {
|
||||
console.error('Failed to load config.yaml:', error instanceof Error ? error.message : error)
|
||||
console.error('Please ensure config.yaml exists and contains valid MySQL configuration.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const dbHost = dbConfig.host || 'localhost'
|
||||
const dbPort = dbConfig.port || 3306
|
||||
const dbUser = dbConfig.username || 'root'
|
||||
const dbPassword = dbConfig.password || ''
|
||||
const dbName = dbConfig.database || ''
|
||||
|
||||
console.log(`Database: ${dbHost}:${dbPort}/${dbName}`)
|
||||
console.log(`Username: ${dbUser}`)
|
||||
console.log('')
|
||||
|
||||
let connection: mysql.Connection | null = null
|
||||
|
||||
try {
|
||||
// Connect to MySQL
|
||||
console.log('Connecting to MySQL...')
|
||||
connection = await mysql.createConnection({
|
||||
host: dbHost,
|
||||
port: dbPort,
|
||||
user: dbUser,
|
||||
password: dbPassword,
|
||||
database: dbName
|
||||
})
|
||||
console.log('✓ Connected to MySQL\n')
|
||||
|
||||
const tableName = 'dbo_BIPUsers'
|
||||
|
||||
// Check and add columns
|
||||
console.log('Checking columns...')
|
||||
for (const [columnName, columnType] of [
|
||||
['ERP_URL', 'VARCHAR(500)'],
|
||||
['ERP_Username', 'VARCHAR(255)'],
|
||||
['ERP_Password', 'VARCHAR(255)']
|
||||
] as const) {
|
||||
const exists = await checkColumnExists(connection, tableName, columnName)
|
||||
if (exists) {
|
||||
console.log(` ✓ Column ${columnName} already exists`)
|
||||
} else {
|
||||
await addColumn(connection, tableName, columnName, columnType)
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n==============================================')
|
||||
console.log('Migration Summary:')
|
||||
console.log('==============================================')
|
||||
console.log('Database Type: MySQL')
|
||||
console.log('Database: ' + dbName)
|
||||
console.log('Columns Added/Verified:')
|
||||
console.log(' - ERP_URL (VARCHAR 500)')
|
||||
console.log(' - ERP_Username (VARCHAR 255)')
|
||||
console.log(' - ERP_Password (VARCHAR 255)')
|
||||
console.log('==============================================')
|
||||
console.log('\n✅ Migration completed successfully!\n')
|
||||
console.log('Next steps:')
|
||||
console.log('1. Update ERP credentials for users in dbo_BIPUsers table')
|
||||
console.log('2. Example SQL:')
|
||||
console.log(` UPDATE ${tableName}`)
|
||||
console.log(` SET ERP_URL = 'https://your-erp.com',`)
|
||||
console.log(` ERP_Username = 'your_username',`)
|
||||
console.log(` ERP_Password = 'your_password'`)
|
||||
console.log(` WHERE ERP_URL IS NULL;\n`)
|
||||
} catch (error) {
|
||||
console.error('\n❌ Migration failed with error:')
|
||||
console.error(error)
|
||||
console.error('\nTroubleshooting:')
|
||||
console.error('1. Check if MySQL server is running')
|
||||
console.error('2. Verify database credentials in config.yaml file')
|
||||
console.error('3. Ensure database "' + dbName + '" exists')
|
||||
console.error('4. Check network connectivity to ' + dbHost + ':' + dbPort)
|
||||
process.exit(1)
|
||||
} finally {
|
||||
// Disconnect
|
||||
if (connection) {
|
||||
try {
|
||||
await connection.end()
|
||||
console.log('Disconnected from MySQL')
|
||||
} catch {
|
||||
// Ignore disconnect errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run migration
|
||||
runMigration().catch((error) => {
|
||||
console.error('Unexpected error:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
197
src/main/services/user/user-erp-config-service.ts
Normal file
197
src/main/services/user/user-erp-config-service.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* User ERP Configuration Service
|
||||
*
|
||||
* Manages ERP credentials (username, password) stored in the BIPUsers table.
|
||||
* Each user can have their own ERP credentials.
|
||||
* ERP URL is fixed and stored in config.yaml.
|
||||
*
|
||||
* Features:
|
||||
* - Get current user's ERP credentials
|
||||
* - Update current user's ERP credentials
|
||||
* - Get ERP credentials for any user (admin only)
|
||||
*/
|
||||
|
||||
import { BIPUsersDAO } from './bip-users-dao'
|
||||
import { SessionManager } from './session-manager'
|
||||
import { createLogger } from '../logger'
|
||||
|
||||
const log = createLogger('UserErpConfigService')
|
||||
|
||||
/**
|
||||
* ERP Credentials object (username and password only)
|
||||
*/
|
||||
export interface ErpCredentials {
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
/**
|
||||
* User ERP Configuration Service Class
|
||||
*/
|
||||
export class UserErpConfigService {
|
||||
private static instance: UserErpConfigService | null = null
|
||||
private dao: BIPUsersDAO
|
||||
|
||||
private constructor() {
|
||||
this.dao = new BIPUsersDAO()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the singleton instance
|
||||
*/
|
||||
public static getInstance(): UserErpConfigService {
|
||||
if (UserErpConfigService.instance === null) {
|
||||
UserErpConfigService.instance = new UserErpConfigService()
|
||||
}
|
||||
return UserErpConfigService.instance
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ERP configuration for the current authenticated user
|
||||
* @returns ERP credentials or null if not found
|
||||
*/
|
||||
async getCurrentUserErpConfig(): Promise<ErpCredentials | null> {
|
||||
try {
|
||||
const sessionManager = SessionManager.getInstance()
|
||||
const currentUser = sessionManager.getUserInfo()
|
||||
|
||||
if (!currentUser) {
|
||||
log.warn('No authenticated user found')
|
||||
return null
|
||||
}
|
||||
|
||||
log.info('Fetching ERP credentials for user', { username: currentUser.username })
|
||||
const config = await this.dao.getUserErpCredentials(currentUser.username)
|
||||
|
||||
if (!config) {
|
||||
log.warn('No ERP credentials found for user', { username: currentUser.username })
|
||||
return null
|
||||
}
|
||||
|
||||
log.info('ERP credentials retrieved successfully', {
|
||||
username: currentUser.username,
|
||||
hasUsername: !!config.username,
|
||||
hasPassword: !!config.password
|
||||
})
|
||||
|
||||
return config
|
||||
} catch (error) {
|
||||
log.error('Error getting current user ERP credentials', { error })
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ERP credentials for a specific user (admin only)
|
||||
* @param username - The username to get ERP credentials for
|
||||
* @returns ERP credentials or null if not found
|
||||
*/
|
||||
async getUserErpConfig(username: string): Promise<ErpCredentials | null> {
|
||||
try {
|
||||
log.info('Fetching ERP credentials for user', { username })
|
||||
const config = await this.dao.getUserErpCredentials(username)
|
||||
|
||||
if (!config) {
|
||||
log.warn('No ERP credentials found for user', { username })
|
||||
return null
|
||||
}
|
||||
|
||||
return config
|
||||
} catch (error) {
|
||||
log.error('Error getting user ERP credentials', { error })
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update ERP credentials for the current authenticated user
|
||||
* @param credentials - ERP credentials to save
|
||||
* @returns True if successful
|
||||
*/
|
||||
async updateCurrentUserErpConfig(credentials: ErpCredentials): Promise<boolean> {
|
||||
try {
|
||||
const sessionManager = SessionManager.getInstance()
|
||||
const currentUser = sessionManager.getUserInfo()
|
||||
|
||||
if (!currentUser) {
|
||||
log.warn('No authenticated user found')
|
||||
return false
|
||||
}
|
||||
|
||||
log.info('Updating ERP credentials for user', { username: currentUser.username })
|
||||
const success = await this.dao.updateUserErpCredentials(
|
||||
currentUser.username,
|
||||
credentials.username,
|
||||
credentials.password
|
||||
)
|
||||
|
||||
if (success) {
|
||||
log.info('ERP credentials updated successfully', { username: currentUser.username })
|
||||
} else {
|
||||
log.error('Failed to update ERP credentials', { username: currentUser.username })
|
||||
}
|
||||
|
||||
return success
|
||||
} catch (error) {
|
||||
log.error('Error updating current user ERP credentials', { error })
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update ERP credentials for a specific user (admin only)
|
||||
* @param username - The username to update ERP credentials for
|
||||
* @param credentials - ERP credentials to save
|
||||
* @returns True if successful
|
||||
*/
|
||||
async updateUserErpConfig(username: string, credentials: ErpCredentials): Promise<boolean> {
|
||||
try {
|
||||
log.info('Updating ERP credentials for user', { username })
|
||||
const success = await this.dao.updateUserErpCredentials(
|
||||
username,
|
||||
credentials.username,
|
||||
credentials.password
|
||||
)
|
||||
|
||||
if (success) {
|
||||
log.info('ERP credentials updated successfully', { username })
|
||||
} else {
|
||||
log.error('Failed to update ERP credentials', { username })
|
||||
}
|
||||
|
||||
return success
|
||||
} catch (error) {
|
||||
log.error('Error updating user ERP credentials', { error })
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ERP configuration for all users (admin only, for migration/audit)
|
||||
* @returns List of users with their ERP configurations
|
||||
*/
|
||||
async getAllUsersErpConfig(): Promise<
|
||||
Array<{
|
||||
username: string
|
||||
erpUrl: string
|
||||
erpUsername: string
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
log.info('Fetching ERP config for all users')
|
||||
const configs = await this.dao.getAllUsersErpConfig()
|
||||
log.info('Retrieved ERP configs for all users', { count: configs.length })
|
||||
return configs
|
||||
} catch (error) {
|
||||
log.error('Error getting all users ERP config', { error })
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from database
|
||||
*/
|
||||
async disconnect(): Promise<void> {
|
||||
await this.dao.disconnect()
|
||||
}
|
||||
}
|
||||
114
src/main/tools/config-path-debug.ts
Normal file
114
src/main/tools/config-path-debug.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Configuration Path Debug Tool
|
||||
*
|
||||
* Run this to see where config files will be stored in different modes
|
||||
* Usage: npx tsx src/main/tools/config-path-debug.ts
|
||||
*/
|
||||
|
||||
import * as path from 'path'
|
||||
|
||||
// Simulate different environments
|
||||
const scenarios = [
|
||||
{
|
||||
name: 'Development Mode (开发环境)',
|
||||
env: {
|
||||
NODE_ENV: 'development',
|
||||
APP_PACKAGED: 'false'
|
||||
},
|
||||
appData: 'C:\\Users\\test\\AppData\\Roaming\\erpauto',
|
||||
projectRoot: 'D:\\Projects\\ERPAuto'
|
||||
},
|
||||
{
|
||||
name: 'Production - Portable (便携版)',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
APP_PACKAGED: 'true'
|
||||
},
|
||||
appData: 'C:\\Users\\test\\AppData\\Roaming\\erpauto',
|
||||
projectRoot: 'D:\\Projects\\ERPAuto',
|
||||
exeDir: 'D:\\PortableApps\\ERPAuto'
|
||||
},
|
||||
{
|
||||
name: 'Production - Installed (安装版)',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
APP_PACKAGED: 'true'
|
||||
},
|
||||
appData: 'C:\\Users\\test\\AppData\\Roaming\\erpauto',
|
||||
projectRoot: 'D:\\Projects\\ERPAuto'
|
||||
}
|
||||
]
|
||||
|
||||
console.log('╔════════════════════════════════════════════════════════════════╗')
|
||||
console.log('║ ERPAuto Configuration Path Debug Tool ║')
|
||||
console.log('╚════════════════════════════════════════════════════════════════╝\n')
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
console.log(`📋 ${scenario.name}`)
|
||||
console.log('─'.repeat(60))
|
||||
|
||||
const isDev = scenario.env.NODE_ENV === 'development' || scenario.env.APP_PACKAGED === 'false'
|
||||
|
||||
let configPath: string
|
||||
let backupPath: string
|
||||
|
||||
if (isDev) {
|
||||
// 开发环境:项目根目录
|
||||
configPath = path.join(scenario.projectRoot, 'config.yaml')
|
||||
backupPath = path.join(scenario.projectRoot, 'config.yaml.backup')
|
||||
} else {
|
||||
// 生产环境(便携版和安装版):用户数据目录
|
||||
configPath = path.join(scenario.appData, 'config.yaml')
|
||||
backupPath = path.join(scenario.appData, 'config.yaml.backup')
|
||||
}
|
||||
|
||||
console.log(` NODE_ENV: ${scenario.env.NODE_ENV}`)
|
||||
console.log(` APP_PACKAGED: ${scenario.env.APP_PACKAGED}`)
|
||||
console.log(` Is Development: ${isDev ? '✓ Yes' : '✗ No'}`)
|
||||
if ('exeDir' in scenario) {
|
||||
console.log(` EXE Directory: ${scenario.exeDir}`)
|
||||
}
|
||||
console.log(` → Config Path: ${configPath}`)
|
||||
console.log(` → Backup Path: ${backupPath}`)
|
||||
console.log('')
|
||||
}
|
||||
|
||||
console.log('╔════════════════════════════════════════════════════════════════╗')
|
||||
console.log('║ Configuration Strategy (配置策略): ║')
|
||||
console.log('╚════════════════════════════════════════════════════════════════╝')
|
||||
console.log(`
|
||||
┌─────────────┬──────────────────────────────────────────────────────────┐
|
||||
│ 环境 │ 配置文件位置 │
|
||||
├─────────────┼──────────────────────────────────────────────────────────┤
|
||||
│ 开发环境 │ 项目根目录\\config.yaml │
|
||||
│ │ 方便编辑和调试,配置随代码版本管理 │
|
||||
├─────────────┼──────────────────────────────────────────────────────────┤
|
||||
│ 生产环境 │ %APPDATA%\\erpauto\\config.yaml │
|
||||
│ (便携版/ │ 符合 Windows 规范,应用升级时配置保留,安全 │
|
||||
│ 安装版) │ │
|
||||
└─────────────┴──────────────────────────────────────────────────────────┘
|
||||
|
||||
💡 优势:
|
||||
✓ 开发时配置在项目根目录,方便版本控制和团队协作
|
||||
✓ 生产环境配置在用户数据目录,应用升级不会丢失配置
|
||||
✓ 配置不暴露在应用目录,更安全
|
||||
✓ 多用户环境下,每个用户有独立的配置
|
||||
`)
|
||||
|
||||
console.log('╔════════════════════════════════════════════════════════════════╗')
|
||||
console.log('║ Recommended Directory Structure: ║')
|
||||
console.log('╚════════════════════════════════════════════════════════════════╝')
|
||||
console.log(`
|
||||
【开发环境】
|
||||
D:\\Projects\\ERPAuto\\
|
||||
├── src\\
|
||||
├── package.json
|
||||
├── config.yaml # 开发配置(可加入 .gitignore)
|
||||
├── config.yaml.backup # 自动备份
|
||||
└── config.template.yaml # 配置模板(提交到版本控制)
|
||||
|
||||
【生产环境 - 便携版/安装版】
|
||||
C:\\Users\\<user>\\AppData\\Roaming\\erpauto\\
|
||||
├── config.yaml # 用户配置
|
||||
└── config.yaml.backup # 自动备份
|
||||
`)
|
||||
232
src/main/tools/erp-login-debug.ts
Normal file
232
src/main/tools/erp-login-debug.ts
Normal file
@@ -0,0 +1,232 @@
|
||||
/**
|
||||
* ERP 登录调试脚本
|
||||
*
|
||||
* 用途:人工调试 ERP 登录流程,定位主界面特征元素
|
||||
* 使用方式:
|
||||
* 1. 修改下方的 ERP_CONFIG 配置(URL、用户名、密码)
|
||||
* 2. 运行:npx ts-node src/main/tools/erp-login-debug.ts
|
||||
* 3. 登录后会自动暂停,打开 Playwright Inspector 进行元素定位
|
||||
* 4. 在 Inspector 中点击主界面元素,获取选择器
|
||||
* 5. 将找到的元素选择器添加到 locators.ts
|
||||
*
|
||||
* 调试模式说明:
|
||||
* - headless: false - 显示浏览器窗口
|
||||
* - slowMo: 100 - 放慢操作速度便于观察
|
||||
* - debugger 语句会暂停执行,打开开发者工具
|
||||
*/
|
||||
|
||||
import { chromium } from 'playwright'
|
||||
import path from 'path'
|
||||
|
||||
// ==================== 配置区域 ====================
|
||||
const ERP_CONFIG = {
|
||||
url: 'https://68.11.34.30:8082/', // ← 修改为你的 ERP 地址
|
||||
username: 'BLDpengqiangqiang', // ← 修改为你的用户名
|
||||
password: 'Cqbld123456.' // ← 修改为你的密码
|
||||
}
|
||||
|
||||
// 调试配置
|
||||
const DEBUG_CONFIG = {
|
||||
headless: false, // 必须为 false,需要看到浏览器
|
||||
slowMo: 100, // 操作间隔(毫秒)
|
||||
timeout: 60000 // 超时时间(毫秒)
|
||||
}
|
||||
// ================================================
|
||||
|
||||
async function debugErpLogin(): Promise<void> {
|
||||
console.log('='.repeat(60))
|
||||
console.log('ERP 登录调试工具')
|
||||
console.log('='.repeat(60))
|
||||
console.log('目标 URL:', ERP_CONFIG.url)
|
||||
console.log('用户名:', ERP_CONFIG.username)
|
||||
console.log('密码:', '***'.repeat(ERP_CONFIG.password.length))
|
||||
console.log('='.repeat(60))
|
||||
console.log()
|
||||
console.log('操作步骤:')
|
||||
console.log('1. 浏览器将自动打开并尝试登录')
|
||||
console.log('2. 如果登录失败,请检查配置或手动重试')
|
||||
console.log('3. 登录成功后,会自动暂停并打开开发者工具')
|
||||
console.log('4. 使用元素选择器定位主界面特征元素')
|
||||
console.log('5. 记录元素选择器,按 Ctrl+C 退出脚本')
|
||||
console.log()
|
||||
console.log('按 Enter 键开始...')
|
||||
|
||||
// 等待用户确认
|
||||
await new Promise<void>((resolve) => {
|
||||
process.stdin.resume()
|
||||
process.stdin.once('data', () => {
|
||||
process.stdin.pause()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
|
||||
let browser: any = null
|
||||
let context: any = null
|
||||
let page: any = null
|
||||
|
||||
try {
|
||||
console.log('\n正在启动浏览器...')
|
||||
|
||||
// 启动浏览器(带调试配置)
|
||||
browser = await chromium.launch({
|
||||
headless: DEBUG_CONFIG.headless,
|
||||
slowMo: DEBUG_CONFIG.slowMo,
|
||||
args: ['--ignore-certificate-errors', '--ignore-ssl-errors', '--disable-web-security']
|
||||
})
|
||||
|
||||
context = await browser.newContext({
|
||||
acceptDownloads: true,
|
||||
viewport: { width: 1920, height: 1080 },
|
||||
ignoreHTTPSErrors: true,
|
||||
javaScriptEnabled: true
|
||||
})
|
||||
|
||||
page = await context.newPage()
|
||||
|
||||
// 启用详细的控制台日志
|
||||
page.on('console', (msg: any) => {
|
||||
console.log(`[Page Console] ${msg.type()}: ${msg.text()}`)
|
||||
})
|
||||
|
||||
page.on('pageerror', (error: any) => {
|
||||
console.error(`[Page Error] ${error.message}`)
|
||||
})
|
||||
|
||||
// 导航到登录页面
|
||||
const loginUrl = `${ERP_CONFIG.url}/yonbip/resources/uap/rbac/login/main/index.html`
|
||||
console.log(`正在加载登录页面:${loginUrl}`)
|
||||
await page.goto(loginUrl, { timeout: DEBUG_CONFIG.timeout })
|
||||
await page.waitForLoadState('domcontentloaded')
|
||||
console.log('登录页面已加载')
|
||||
|
||||
// 等待并定位登录表单 iframe
|
||||
console.log('等待登录表单...')
|
||||
await page.waitForSelector('#forwardFrame', { state: 'attached', timeout: 15000 })
|
||||
const frameLocator = page.locator('#forwardFrame')
|
||||
const contentFrame = await frameLocator.contentFrame()
|
||||
|
||||
if (!contentFrame) {
|
||||
throw new Error('无法访问 forwardFrame 内容框架')
|
||||
}
|
||||
|
||||
const mainFrame = contentFrame
|
||||
console.log('登录表单框架已就绪')
|
||||
|
||||
// 填充用户名
|
||||
console.log('正在输入用户名...')
|
||||
try {
|
||||
const usernameInput = mainFrame.getByRole('textbox', { name: '用户名' })
|
||||
await usernameInput.waitFor({ state: 'visible', timeout: 5000 })
|
||||
await usernameInput.fill(ERP_CONFIG.username)
|
||||
console.log('用户名已输入')
|
||||
} catch (e: any) {
|
||||
console.error('找不到用户名输入框:', e.message)
|
||||
throw new Error('找不到用户名输入框,请检查页面结构是否改变')
|
||||
}
|
||||
|
||||
// 填充密码
|
||||
console.log('正在输入密码...')
|
||||
try {
|
||||
const passwordInput = mainFrame.getByRole('textbox', { name: '密码' })
|
||||
await passwordInput.waitFor({ state: 'visible', timeout: 5000 })
|
||||
await passwordInput.fill(ERP_CONFIG.password)
|
||||
console.log('密码已输入')
|
||||
} catch (e: any) {
|
||||
console.error('找不到密码输入框:', e.message)
|
||||
throw new Error('找不到密码输入框,请检查页面结构是否改变')
|
||||
}
|
||||
await page.pause()
|
||||
// 点击登录按钮
|
||||
console.log('正在点击登录按钮...')
|
||||
try {
|
||||
const loginButton = mainFrame.getByRole('button', { name: '登录' })
|
||||
await loginButton.waitFor({ state: 'visible', timeout: 5000 })
|
||||
await loginButton.click()
|
||||
console.log('已点击登录按钮')
|
||||
} catch (e: any) {
|
||||
console.error('找不到登录按钮:', e.message)
|
||||
throw new Error('找不到登录按钮,请检查页面结构是否改变')
|
||||
}
|
||||
|
||||
// 等待页面加载
|
||||
console.log('等待登录响应...')
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 10000 })
|
||||
await page.waitForTimeout(2000) // 额外等待,确保页面完全加载
|
||||
|
||||
// 处理强制登录确认对话框
|
||||
try {
|
||||
const confirmBtn = mainFrame.getByRole('button', { name: '确定' })
|
||||
const count = await confirmBtn.count()
|
||||
if (count > 0) {
|
||||
console.log('检测到强制登录确认对话框,正在确认...')
|
||||
await confirmBtn.first().click()
|
||||
await page.waitForTimeout(2000)
|
||||
console.log('已确认强制登录')
|
||||
} else {
|
||||
console.log('普通登录,无需确认')
|
||||
}
|
||||
} catch {
|
||||
console.log('未检测到确认对话框')
|
||||
}
|
||||
|
||||
// ==================== 登录成功,进入调试模式 ====================
|
||||
console.log()
|
||||
console.log('='.repeat(60))
|
||||
console.log('✓ 登录成功!')
|
||||
console.log('='.repeat(60))
|
||||
console.log()
|
||||
console.log('现在进入调试模式,请进行以下操作:')
|
||||
console.log()
|
||||
console.log('1. 按 F12 打开浏览器开发者工具')
|
||||
console.log('2. 使用元素选择器 (Ctrl+Shift+C) 点击主界面特征元素')
|
||||
console.log('3. 在 Elements 面板中右键元素 → Copy → Copy selector')
|
||||
console.log('4. 或者使用 Playwright Inspector:')
|
||||
console.log(' - 在控制台输入: await page.pause()')
|
||||
console.log(' - 使用 Inspector 的元素选择工具')
|
||||
console.log()
|
||||
console.log('建议定位的特征元素:')
|
||||
console.log('- 主界面顶部导航栏')
|
||||
console.log('- 侧边菜单栏')
|
||||
console.log('- 主内容区域的唯一标识')
|
||||
console.log('- 用户信息显示区域')
|
||||
console.log('- 任何登录后独有的界面元素')
|
||||
console.log()
|
||||
console.log('按 Ctrl+C 退出脚本')
|
||||
console.log('='.repeat(60))
|
||||
|
||||
// 保持浏览器打开,等待用户调试
|
||||
// 使用 pause 可以让用户手动恢复或使用 Inspector
|
||||
await page.pause()
|
||||
} catch (error: any) {
|
||||
console.error()
|
||||
console.error('='.repeat(60))
|
||||
console.error('错误:', error.message)
|
||||
console.error('='.repeat(60))
|
||||
console.error()
|
||||
console.error('调试提示:')
|
||||
console.error('1. 检查 ERP_CONFIG 配置是否正确')
|
||||
console.error('2. 检查网络连接')
|
||||
console.error('3. 确认 ERP 系统可访问')
|
||||
console.error('4. 如果是元素找不到,可能需要更新 locators.ts')
|
||||
} finally {
|
||||
// 清理资源(给用户时间保存信息)
|
||||
console.log()
|
||||
console.log('等待 5 秒后关闭浏览器...')
|
||||
await new Promise((resolve) => setTimeout(resolve, 5000))
|
||||
|
||||
if (context) {
|
||||
await context.close()
|
||||
}
|
||||
if (browser) {
|
||||
await browser.close()
|
||||
}
|
||||
console.log('浏览器已关闭')
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
// 运行调试脚本
|
||||
debugErpLogin().catch((err) => {
|
||||
console.error('脚本执行失败:', err)
|
||||
process.exit(1)
|
||||
})
|
||||
215
src/main/tools/rustfs-test.ts
Normal file
215
src/main/tools/rustfs-test.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* RustFS Integration Test Script
|
||||
*
|
||||
* Tests RustFS connection and upload functionality
|
||||
* Usage: tsx src/main/tools/rustfs-test.ts
|
||||
*
|
||||
* Note: This test runs in standalone mode without Electron
|
||||
*/
|
||||
|
||||
import {
|
||||
S3Client,
|
||||
PutObjectCommand,
|
||||
GetObjectCommand,
|
||||
ListObjectsV2Command,
|
||||
DeleteObjectCommand,
|
||||
type PutObjectCommandInput
|
||||
} from '@aws-sdk/client-s3'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
|
||||
// Simple console logger (standalone mode)
|
||||
const log = {
|
||||
info: (msg: string, data?: any) => console.log(`[INFO] ${msg}`, data ? JSON.stringify(data) : ''),
|
||||
error: (msg: string, data?: any) =>
|
||||
console.error(`[ERROR] ${msg}`, data ? JSON.stringify(data) : ''),
|
||||
warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data ? JSON.stringify(data) : '')
|
||||
}
|
||||
|
||||
// Test configuration
|
||||
const TEST_CONFIG = {
|
||||
enabled: true,
|
||||
endpoint: 'http://192.168.110.114:9000',
|
||||
accessKey: 'dP4O7ePAzyH8earoXxE9',
|
||||
secretKey: '2vRPLnsh9Zi1KyBDymUtACyDdLHGfsLvw4MkG3cv',
|
||||
bucket: 'erpauto',
|
||||
region: 'us-east-1'
|
||||
}
|
||||
|
||||
function createS3Client(config: typeof TEST_CONFIG) {
|
||||
return new S3Client({
|
||||
region: config.region,
|
||||
endpoint: config.endpoint,
|
||||
credentials: {
|
||||
accessKeyId: config.accessKey,
|
||||
secretAccessKey: config.secretKey
|
||||
},
|
||||
forcePathStyle: true
|
||||
})
|
||||
}
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
const ext = path.extname(filePath).toLowerCase()
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'.md': 'text/markdown; charset=utf-8',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'.csv': 'text/csv; charset=utf-8'
|
||||
}
|
||||
return mimeTypes[ext] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
function generateReportKey(reportFileName: string, username: string): string {
|
||||
// Organize reports by user for easy access
|
||||
// Format: reports/cleaner/{username}/{filename}
|
||||
return `reports/cleaner/${username}/${reportFileName}`
|
||||
}
|
||||
|
||||
async function runTests() {
|
||||
console.log('='.repeat(50))
|
||||
console.log('RustFS Integration Test')
|
||||
console.log('='.repeat(50))
|
||||
console.log()
|
||||
|
||||
const client = createS3Client(TEST_CONFIG)
|
||||
|
||||
// Test connection
|
||||
console.log('1. Testing connection...')
|
||||
try {
|
||||
const command = new ListObjectsV2Command({
|
||||
Bucket: TEST_CONFIG.bucket,
|
||||
Prefix: '',
|
||||
MaxKeys: 1
|
||||
})
|
||||
await client.send(command)
|
||||
console.log(' ✓ Connection successful')
|
||||
} catch (error) {
|
||||
console.log(` ✗ Connection failed: ${(error as Error).message}`)
|
||||
return
|
||||
}
|
||||
console.log()
|
||||
|
||||
// Test upload string
|
||||
console.log('2. Testing string upload...')
|
||||
const testContent = `# Test Report
|
||||
Generated at: ${new Date().toISOString()}
|
||||
|
||||
This is a test report to verify RustFS integration.
|
||||
`
|
||||
const testKey = `test/reports/test-${Date.now()}.md`
|
||||
try {
|
||||
const input: PutObjectCommandInput = {
|
||||
Bucket: TEST_CONFIG.bucket,
|
||||
Key: testKey,
|
||||
Body: Buffer.from(testContent, 'utf-8'),
|
||||
ContentType: 'text/markdown; charset=utf-8'
|
||||
}
|
||||
const command = new PutObjectCommand(input)
|
||||
const response = await client.send(command)
|
||||
console.log(' ✓ Upload successful')
|
||||
console.log(` Key: ${testKey}`)
|
||||
console.log(` ETag: ${response.ETag}`)
|
||||
} catch (error) {
|
||||
console.log(' ✗ Upload failed')
|
||||
console.log(` Error: ${(error as Error).message}`)
|
||||
return
|
||||
}
|
||||
console.log()
|
||||
|
||||
// Test download
|
||||
console.log('3. Testing download...')
|
||||
try {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: TEST_CONFIG.bucket,
|
||||
Key: testKey
|
||||
})
|
||||
const response = await client.send(command)
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of response.Body as any) {
|
||||
chunks.push(Buffer.from(chunk))
|
||||
}
|
||||
const content = Buffer.concat(chunks)
|
||||
console.log(' ✓ Download successful')
|
||||
console.log(` Size: ${content.length} bytes`)
|
||||
console.log(` Content preview: ${content.toString('utf-8').slice(0, 50)}...`)
|
||||
} catch (error) {
|
||||
console.log(' ✗ Download failed')
|
||||
console.log(` Error: ${(error as Error).message}`)
|
||||
}
|
||||
console.log()
|
||||
|
||||
// Test file upload (create a temporary file)
|
||||
console.log('4. Testing file upload...')
|
||||
const tempFilePath = path.join(process.cwd(), `test-file-${Date.now()}.md`)
|
||||
fs.writeFileSync(tempFilePath, testContent, 'utf-8')
|
||||
|
||||
const fileKey = `test/files/test-file-${Date.now()}.md`
|
||||
try {
|
||||
const fileContent = fs.readFileSync(tempFilePath)
|
||||
const input: PutObjectCommandInput = {
|
||||
Bucket: TEST_CONFIG.bucket,
|
||||
Key: fileKey,
|
||||
Body: fileContent,
|
||||
ContentType: getMimeType(tempFilePath)
|
||||
}
|
||||
const command = new PutObjectCommand(input)
|
||||
const response = await client.send(command)
|
||||
console.log(' ✓ File upload successful')
|
||||
console.log(` Key: ${fileKey}`)
|
||||
console.log(` ETag: ${response.ETag}`)
|
||||
} catch (error) {
|
||||
console.log(' ✗ File upload failed')
|
||||
console.log(` Error: ${(error as Error).message}`)
|
||||
}
|
||||
|
||||
// Cleanup temp file
|
||||
try {
|
||||
fs.unlinkSync(tempFilePath)
|
||||
console.log(' ✓ Temporary file cleaned up')
|
||||
} catch (e) {
|
||||
console.log(` ⚠ Could not clean up temp file: ${(e as Error).message}`)
|
||||
}
|
||||
console.log()
|
||||
|
||||
// Test report key generation
|
||||
console.log('5. Testing report key generation...')
|
||||
const reportKey = generateReportKey('cleaner-report-2026-03-17-10-30-00.md', 'admin')
|
||||
console.log(` ✓ Generated key: ${reportKey}`)
|
||||
console.log()
|
||||
|
||||
// Test cleanup (delete test files)
|
||||
console.log('6. Cleaning up test files...')
|
||||
try {
|
||||
const deleteCommand = new DeleteObjectCommand({
|
||||
Bucket: TEST_CONFIG.bucket,
|
||||
Key: testKey
|
||||
})
|
||||
await client.send(deleteCommand)
|
||||
console.log(' ✓ Test string file deleted')
|
||||
} catch (error) {
|
||||
console.log(` ⚠ Could not delete test string file: ${(error as Error).message}`)
|
||||
}
|
||||
|
||||
try {
|
||||
const deleteCommand = new DeleteObjectCommand({
|
||||
Bucket: TEST_CONFIG.bucket,
|
||||
Key: fileKey
|
||||
})
|
||||
await client.send(deleteCommand)
|
||||
console.log(' ✓ Test file deleted')
|
||||
} catch (error) {
|
||||
console.log(` ⚠ Could not delete test file: ${(error as Error).message}`)
|
||||
}
|
||||
console.log()
|
||||
|
||||
console.log('='.repeat(50))
|
||||
console.log('All tests completed!')
|
||||
console.log('='.repeat(50))
|
||||
}
|
||||
|
||||
// Run tests
|
||||
runTests().catch((error) => {
|
||||
console.error('Test failed with error:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
44
src/main/types/audit.types.ts
Normal file
44
src/main/types/audit.types.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Audit log types and interfaces
|
||||
*/
|
||||
|
||||
/**
|
||||
* Audit action enumeration
|
||||
*/
|
||||
export enum AuditAction {
|
||||
LOGIN = 'LOGIN',
|
||||
LOGOUT = 'LOGOUT',
|
||||
EXTRACT = 'EXTRACT',
|
||||
CLEAN = 'CLEAN',
|
||||
SETTINGS_CHANGE = 'SETTINGS_CHANGE'
|
||||
}
|
||||
|
||||
/**
|
||||
* Audit status enumeration
|
||||
*/
|
||||
export enum AuditStatus {
|
||||
SUCCESS = 'SUCCESS',
|
||||
FAILURE = 'FAILURE'
|
||||
}
|
||||
|
||||
/**
|
||||
* Audit entry interface
|
||||
*/
|
||||
export interface AuditEntry {
|
||||
/** Timestamp of the action */
|
||||
timestamp: Date
|
||||
/** Action performed */
|
||||
action: AuditAction
|
||||
/** User ID who performed the action */
|
||||
userId: string
|
||||
/** Username who performed the action */
|
||||
username: string
|
||||
/** Computer name where action was performed */
|
||||
computerName: string
|
||||
/** Resource affected by the action */
|
||||
resource?: string
|
||||
/** Status of the action */
|
||||
status: AuditStatus
|
||||
/** Additional metadata in JSON format */
|
||||
metadata?: string
|
||||
}
|
||||
@@ -1,8 +1,24 @@
|
||||
export type CleanerPhase = 'login' | 'processing' | 'complete'
|
||||
|
||||
export interface CleanerProgress {
|
||||
message: string
|
||||
progress: number
|
||||
currentOrderIndex: number
|
||||
totalOrders: number
|
||||
currentMaterialIndex: number
|
||||
totalMaterialsInOrder: number
|
||||
currentOrderNumber?: string
|
||||
phase: CleanerPhase
|
||||
}
|
||||
|
||||
export interface CleanerInput {
|
||||
orderNumbers: string[]
|
||||
materialCodes: string[]
|
||||
dryRun: boolean
|
||||
onProgress?: (message: string, progress?: number) => void
|
||||
headless?: boolean
|
||||
queryBatchSize?: number
|
||||
processConcurrency?: number
|
||||
onProgress?: (message: string, progress?: number, extra?: Partial<CleanerProgress>) => void
|
||||
}
|
||||
|
||||
export interface CleanerResult {
|
||||
@@ -11,6 +27,22 @@ export interface CleanerResult {
|
||||
materialsSkipped: number
|
||||
errors: string[]
|
||||
details: OrderCleanDetail[]
|
||||
// Retry statistics
|
||||
retriedOrders: number
|
||||
successfulRetries: number
|
||||
}
|
||||
|
||||
export interface SkippedMaterial {
|
||||
materialCode: string
|
||||
materialName: string
|
||||
rowNumber: number
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface RetryAttempt {
|
||||
attempt: number
|
||||
error: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface OrderCleanDetail {
|
||||
@@ -18,6 +50,12 @@ export interface OrderCleanDetail {
|
||||
materialsDeleted: number
|
||||
materialsSkipped: number
|
||||
errors: string[]
|
||||
skippedMaterials: SkippedMaterial[]
|
||||
// Retry-related fields
|
||||
retryCount: number
|
||||
retryAttempts?: RetryAttempt[]
|
||||
retriedAt?: number
|
||||
retrySuccess?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
190
src/main/types/config.schema.ts
Normal file
190
src/main/types/config.schema.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* Configuration Schema Definitions
|
||||
*
|
||||
* Zod schemas for runtime validation of application configuration
|
||||
*
|
||||
* Note: ERP configuration is stored in database (dbo_BIPUsers table)
|
||||
* and managed per-user, not in this config file.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* 数据库类型枚举
|
||||
*/
|
||||
export const databaseTypeSchema = z.enum(['mysql', 'sqlserver'])
|
||||
export type DatabaseType = z.infer<typeof databaseTypeSchema>
|
||||
|
||||
/**
|
||||
* 验证匹配模式枚举
|
||||
*/
|
||||
export const matchModeSchema = z.enum(['substring', 'exact'])
|
||||
export type MatchMode = z.infer<typeof matchModeSchema>
|
||||
|
||||
/**
|
||||
* 验证数据源枚举
|
||||
*/
|
||||
export const validationDataSourceSchema = z.enum([
|
||||
'database_full',
|
||||
'database_filtered',
|
||||
'excel_existing',
|
||||
'excel_full'
|
||||
])
|
||||
export type ValidationDataSource = z.infer<typeof validationDataSourceSchema>
|
||||
|
||||
/**
|
||||
* MySQL 配置 Schema
|
||||
*/
|
||||
export const mysqlConfigSchema = z.object({
|
||||
host: z.string().min(1, 'MySQL host is required'),
|
||||
port: z.number().int().min(1).max(65535).default(3306),
|
||||
database: z.string().min(1, 'MySQL database is required'),
|
||||
username: z.string().min(1, 'MySQL username is required'),
|
||||
password: z.string(),
|
||||
charset: z.string().default('utf8mb4')
|
||||
})
|
||||
|
||||
/**
|
||||
* SQL Server 配置 Schema
|
||||
*/
|
||||
export const sqlServerConfigSchema = z.object({
|
||||
server: z.string().min(1, 'SQL Server is required'),
|
||||
port: z.number().int().min(1).max(65535).default(1433),
|
||||
database: z.string().min(1, 'SQL Server database is required'),
|
||||
username: z.string().min(1, 'SQL Server username is required'),
|
||||
password: z.string(),
|
||||
driver: z.string().default('ODBC Driver 18 for SQL Server'),
|
||||
trustServerCertificate: z.boolean().default(true)
|
||||
})
|
||||
|
||||
/**
|
||||
* 数据库配置(包含两种数据库的完整配置)
|
||||
*/
|
||||
export const databaseConfigSchema = z.object({
|
||||
activeType: databaseTypeSchema.default('mysql'),
|
||||
mysql: mysqlConfigSchema,
|
||||
sqlserver: sqlServerConfigSchema
|
||||
})
|
||||
|
||||
/**
|
||||
* 路径配置 Schema
|
||||
*/
|
||||
export const pathsConfigSchema = z.object({
|
||||
dataDir: z.string().min(1, 'Data directory is required'),
|
||||
defaultOutput: z.string().default('离散备料计划维护_合并.xlsx'),
|
||||
validationOutput: z.string().default('物料状态校验结果.xlsx')
|
||||
})
|
||||
|
||||
/**
|
||||
* 数据提取配置 Schema
|
||||
*/
|
||||
export const extractionConfigSchema = z.object({
|
||||
batchSize: z.number().int().min(1).max(1000).default(100),
|
||||
verbose: z.boolean().default(true),
|
||||
autoConvert: z.boolean().default(true),
|
||||
mergeBatches: z.boolean().default(true),
|
||||
enableDbPersistence: z.boolean().default(true)
|
||||
})
|
||||
|
||||
/**
|
||||
* 物料校验配置 Schema
|
||||
*/
|
||||
export const validationConfigSchema = z.object({
|
||||
dataSource: validationDataSourceSchema.default('database_full'),
|
||||
batchSize: z.number().int().min(1).max(10000).default(2000),
|
||||
matchMode: matchModeSchema.default('substring'),
|
||||
enableCrud: z.boolean().default(false),
|
||||
defaultManager: z.string().default('')
|
||||
})
|
||||
|
||||
/**
|
||||
* 清理配置 Schema
|
||||
*/
|
||||
export const cleanerConfigSchema = z.object({
|
||||
queryBatchSize: z.number().int().min(1).max(100).default(100),
|
||||
processConcurrency: z.number().int().min(1).max(20).default(1)
|
||||
})
|
||||
export type CleanerConfig = z.infer<typeof cleanerConfigSchema>
|
||||
|
||||
/**
|
||||
* 订单号解析配置 Schema
|
||||
*/
|
||||
export const orderResolutionSchema = z.object({
|
||||
tableName: z.string(),
|
||||
productionIdField: z.string(),
|
||||
orderNumberField: z.string()
|
||||
})
|
||||
|
||||
/**
|
||||
* ERP 系统配置 Schema(固定基础设施)
|
||||
*/
|
||||
export const erpSystemConfigSchema = z.object({
|
||||
url: z.string().url('ERP URL must be a valid URL')
|
||||
})
|
||||
|
||||
/**
|
||||
* 日志配置 Schema
|
||||
*/
|
||||
export const loggingConfigSchema = z.object({
|
||||
level: z.enum(['error', 'warn', 'info', 'debug', 'verbose']).default('info'),
|
||||
auditRetention: z.number().int().min(1).max(365).default(30),
|
||||
appRetention: z.number().int().min(1).max(365).default(14)
|
||||
})
|
||||
|
||||
/**
|
||||
* RustFS 对象存储配置 Schema
|
||||
*/
|
||||
export const rustfsConfigSchema = z.object({
|
||||
enabled: z.boolean().default(false),
|
||||
endpoint: z.string().min(1, 'RustFS endpoint is required'),
|
||||
accessKey: z.string().min(1, 'RustFS access key is required'),
|
||||
secretKey: z.string().min(1, 'RustFS secret key is required'),
|
||||
bucket: z.string().min(1, 'RustFS bucket is required'),
|
||||
region: z.string().default('us-east-1')
|
||||
})
|
||||
|
||||
/**
|
||||
* 完整应用配置 Schema
|
||||
*/
|
||||
export const fullConfigSchema = z.object({
|
||||
erp: erpSystemConfigSchema,
|
||||
database: databaseConfigSchema,
|
||||
paths: pathsConfigSchema,
|
||||
extraction: extractionConfigSchema,
|
||||
validation: validationConfigSchema,
|
||||
cleaner: cleanerConfigSchema,
|
||||
orderResolution: orderResolutionSchema,
|
||||
logging: loggingConfigSchema,
|
||||
rustfs: rustfsConfigSchema.optional()
|
||||
})
|
||||
|
||||
/**
|
||||
* 类型导出
|
||||
*/
|
||||
export type FullConfig = z.infer<typeof fullConfigSchema>
|
||||
export type DatabaseConfig = z.infer<typeof databaseConfigSchema>
|
||||
export type MySqlConfig = z.infer<typeof mysqlConfigSchema>
|
||||
export type SqlServerConfig = z.infer<typeof sqlServerConfigSchema>
|
||||
export type ErpSystemConfig = z.infer<typeof erpSystemConfigSchema>
|
||||
export type LoggingConfig = z.infer<typeof loggingConfigSchema>
|
||||
export type RustfsConfig = z.infer<typeof rustfsConfigSchema>
|
||||
|
||||
/**
|
||||
* 验证并解析配置
|
||||
*/
|
||||
export function validateConfig(input: unknown): {
|
||||
success: boolean
|
||||
data?: FullConfig
|
||||
error?: string
|
||||
} {
|
||||
const result = fullConfigSchema.safeParse(input)
|
||||
if (result.success) {
|
||||
return { success: true, data: result.data }
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
error: result.error.issues
|
||||
.map((issue) => `${issue.path.join('.')}: ${issue.message}`)
|
||||
.join('; ')
|
||||
}
|
||||
}
|
||||
@@ -167,3 +167,22 @@ export function getErrorCode(error: unknown): string {
|
||||
}
|
||||
return 'UNKNOWN_ERROR'
|
||||
}
|
||||
|
||||
/**
|
||||
* Error-like interface for non-Error objects that have error properties
|
||||
*/
|
||||
export interface ErrorLike {
|
||||
name: string
|
||||
message: string
|
||||
stack?: string
|
||||
cause?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialized error object for logging
|
||||
* Can contain additional properties from Error subclasses
|
||||
*/
|
||||
export interface SerializedError extends ErrorLike {
|
||||
cause?: SerializedError | string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
@@ -1,7 +1,39 @@
|
||||
import type { ErpSession } from './erp.types'
|
||||
|
||||
export type LogLevel = 'info' | 'success' | 'warning' | 'error' | 'system'
|
||||
|
||||
export type ExtractionPhase = 'login' | 'downloading' | 'merging' | 'importing'
|
||||
|
||||
export interface ExtractionProgress {
|
||||
message: string
|
||||
progress: number
|
||||
phase?: ExtractionPhase
|
||||
currentBatch?: number
|
||||
totalBatches?: number
|
||||
subProgress?: {
|
||||
step: string
|
||||
current: number
|
||||
total: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtractorInput {
|
||||
orderNumbers: string[]
|
||||
batchSize?: number
|
||||
onProgress?: (message: string, progress: number) => void
|
||||
onProgress?: (message: string, progress: number, extra?: Partial<ExtractionProgress>) => void
|
||||
onLog?: (level: LogLevel, message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of database import operation
|
||||
*/
|
||||
export interface ImportResult {
|
||||
success: boolean
|
||||
recordsRead: number
|
||||
recordsDeleted: number
|
||||
recordsImported: number
|
||||
uniqueSourceNumbers: number
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
export interface ExtractorResult {
|
||||
@@ -9,9 +41,30 @@ export interface ExtractorResult {
|
||||
mergedFile: string | null
|
||||
recordCount: number
|
||||
errors: string[]
|
||||
/** Database import result (only populated if mergedFile was created) */
|
||||
importResult?: ImportResult
|
||||
}
|
||||
|
||||
export interface OrderInfo {
|
||||
orderNumber: string
|
||||
productionId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Input for ExtractorCore - handles web page operations
|
||||
*/
|
||||
export interface ExtractorCoreInput {
|
||||
session: ErpSession
|
||||
orderNumbers: string[]
|
||||
downloadDir: string
|
||||
batchSize: number
|
||||
onProgress?: (message: string, progress: number, extra?: Partial<ExtractionProgress>) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Result from ExtractorCore - list of downloaded file paths
|
||||
*/
|
||||
export interface ExtractorCoreResult {
|
||||
downloadedFiles: string[]
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
@@ -3,13 +3,15 @@
|
||||
* These types define the API exposed to the renderer process via contextBridge
|
||||
*/
|
||||
|
||||
import type { ExtractorInput, ExtractorResult } from './extractor.types'
|
||||
import type { ExtractorInput, ExtractorResult, ExtractionProgress } from './extractor.types'
|
||||
import type {
|
||||
CleanerInput,
|
||||
CleanerResult,
|
||||
CleanerProgress,
|
||||
ExportResultItem,
|
||||
ExportResultResponse
|
||||
} from './cleaner.types'
|
||||
import type { IpcResult } from '../ipc'
|
||||
|
||||
/**
|
||||
* MySQL connection configuration
|
||||
@@ -59,30 +61,11 @@ export interface SqlServerQueryResult {
|
||||
* File operation APIs
|
||||
*/
|
||||
export interface FileAPI {
|
||||
/**
|
||||
* Read file content as text
|
||||
* @param filePath - Path to the file
|
||||
*/
|
||||
readFile: (filePath: string) => Promise<string>
|
||||
|
||||
/**
|
||||
* Write content to file
|
||||
* @param filePath - Path to the file
|
||||
* @param content - Content to write
|
||||
*/
|
||||
writeFile: (filePath: string, content: string) => Promise<void>
|
||||
|
||||
/**
|
||||
* Check if file exists
|
||||
* @param filePath - Path to the file
|
||||
*/
|
||||
fileExists: (filePath: string) => Promise<boolean>
|
||||
|
||||
/**
|
||||
* Get list of files in directory
|
||||
* @param dirPath - Directory path
|
||||
*/
|
||||
listFiles: (dirPath: string) => Promise<string[]>
|
||||
readFile: (filePath: string) => Promise<IpcResult<string>>
|
||||
writeFile: (filePath: string, content: string) => Promise<IpcResult<void>>
|
||||
fileExists: (filePath: string) => Promise<IpcResult<boolean>>
|
||||
listFiles: (dirPath: string) => Promise<IpcResult<string[]>>
|
||||
openPath: (filePath: string) => Promise<IpcResult<void>>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,9 +76,19 @@ export interface ExtractorAPI {
|
||||
* Run ERP data extractor
|
||||
* @param input - Extractor input parameters
|
||||
*/
|
||||
runExtractor: (
|
||||
input: ExtractorInput
|
||||
) => Promise<{ success: boolean; data?: ExtractorResult; error?: string }>
|
||||
runExtractor: (input: ExtractorInput) => Promise<IpcResult<ExtractorResult>>
|
||||
/**
|
||||
* Subscribe to progress updates
|
||||
* @param callback - Callback function receiving progress data
|
||||
* @returns Unsubscribe function
|
||||
*/
|
||||
onProgress: (callback: (data: ExtractionProgress) => void) => () => void
|
||||
/**
|
||||
* Subscribe to log messages
|
||||
* @param callback - Callback function receiving log data
|
||||
* @returns Unsubscribe function
|
||||
*/
|
||||
onLog: (callback: (data: { level: string; message: string }) => void) => () => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,15 +99,20 @@ export interface CleanerAPI {
|
||||
* Run ERP cleaner service
|
||||
* @param input - Cleaner input parameters
|
||||
*/
|
||||
runCleaner: (
|
||||
input: CleanerInput
|
||||
) => Promise<{ success: boolean; data?: CleanerResult; error?: string }>
|
||||
runCleaner: (input: CleanerInput) => Promise<IpcResult<CleanerResult>>
|
||||
|
||||
/**
|
||||
* Export validation results to Excel
|
||||
* @param items - Validation result items to export
|
||||
*/
|
||||
exportResults: (items: ExportResultItem[]) => Promise<ExportResultResponse>
|
||||
exportResults: (items: ExportResultItem[]) => Promise<IpcResult<ExportResultResponse>>
|
||||
|
||||
/**
|
||||
* Subscribe to progress updates
|
||||
* @param callback - Callback function receiving progress data
|
||||
* @returns Unsubscribe function
|
||||
*/
|
||||
onProgress: (callback: (data: CleanerProgress) => void) => () => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,45 +123,70 @@ export interface DatabaseAPI {
|
||||
* Connect to MySQL database
|
||||
* @param config - MySQL connection config
|
||||
*/
|
||||
connectMySql: (config: MySqlConfig) => Promise<void>
|
||||
connectMySql: (config: MySqlConfig) => Promise<IpcResult<void>>
|
||||
|
||||
/**
|
||||
* Disconnect from MySQL database
|
||||
*/
|
||||
disconnectMySql: () => Promise<void>
|
||||
disconnectMySql: () => Promise<IpcResult<void>>
|
||||
|
||||
/**
|
||||
* Check if MySQL is connected
|
||||
*/
|
||||
isMySqlConnected: () => Promise<boolean>
|
||||
isMySqlConnected: () => Promise<IpcResult<boolean>>
|
||||
|
||||
/**
|
||||
* Execute MySQL query
|
||||
* @param sql - SQL query
|
||||
* @param params - Query parameters
|
||||
*/
|
||||
queryMySql: (sql: string, params?: unknown[]) => Promise<MySqlQueryResult>
|
||||
queryMySql: (sql: string, params?: unknown[]) => Promise<IpcResult<MySqlQueryResult>>
|
||||
|
||||
/**
|
||||
* Connect to SQL Server database
|
||||
* @param config - SQL Server connection config
|
||||
*/
|
||||
connectSqlServer: (config: SqlServerConfig) => Promise<void>
|
||||
connectSqlServer: (config: SqlServerConfig) => Promise<IpcResult<void>>
|
||||
|
||||
/**
|
||||
* Disconnect from SQL Server database
|
||||
*/
|
||||
disconnectSqlServer: () => Promise<void>
|
||||
disconnectSqlServer: () => Promise<IpcResult<void>>
|
||||
|
||||
/**
|
||||
* Check if SQL Server is connected
|
||||
*/
|
||||
isSqlServerConnected: () => Promise<boolean>
|
||||
isSqlServerConnected: () => Promise<IpcResult<boolean>>
|
||||
|
||||
/**
|
||||
* Execute SQL Server query
|
||||
* @param sql - SQL query
|
||||
* @param params - Query parameters
|
||||
*/
|
||||
querySqlServer: (sql: string, params?: Record<string, unknown>) => Promise<SqlServerQueryResult>
|
||||
querySqlServer: (
|
||||
sql: string,
|
||||
params?: Record<string, unknown>
|
||||
) => Promise<IpcResult<SqlServerQueryResult>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Report service APIs
|
||||
*/
|
||||
export interface ReportAPI {
|
||||
/**
|
||||
* List all reports across all users (Admin only typically)
|
||||
*/
|
||||
listAll: () => Promise<IpcResult<{ key: string; filename: string; username: string; lastModified?: Date; size?: number }[]>>
|
||||
|
||||
/**
|
||||
* List reports for a specific user
|
||||
* @param username - Username to list reports for
|
||||
*/
|
||||
listByUser: (username: string) => Promise<IpcResult<{ key: string; filename: string; username: string; lastModified?: Date; size?: number }[]>>
|
||||
|
||||
/**
|
||||
* Download a specific report by key
|
||||
* @param key - Report object key in RustFS
|
||||
*/
|
||||
download: (key: string) => Promise<IpcResult<string>>
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
* Settings types and interfaces
|
||||
*
|
||||
* Defines configuration structures for ERPAuto settings management
|
||||
*
|
||||
* Note: ERP configuration is stored in database (dbo_BIPUsers table)
|
||||
* and managed per-user, not in settings.
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -28,24 +31,6 @@ export type ValidationDataSource =
|
||||
| 'excel_existing'
|
||||
| 'excel_full'
|
||||
|
||||
/**
|
||||
* ERP configuration
|
||||
*/
|
||||
export interface ErpConfig {
|
||||
/** ERP system URL */
|
||||
url: string
|
||||
/** ERP username */
|
||||
username: string
|
||||
/** ERP password */
|
||||
password: string
|
||||
/** Headless browser mode */
|
||||
headless: boolean
|
||||
/** Ignore HTTPS certificate errors */
|
||||
ignoreHttpsErrors: boolean
|
||||
/** Auto close browser after operations */
|
||||
autoCloseBrowser: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Database configuration
|
||||
*/
|
||||
@@ -110,32 +95,11 @@ export interface ValidationConfig {
|
||||
defaultManager: string
|
||||
}
|
||||
|
||||
/**
|
||||
* UI configuration
|
||||
*/
|
||||
export interface UiConfig {
|
||||
/** Font family */
|
||||
fontFamily: string
|
||||
/** Font size */
|
||||
fontSize: number
|
||||
/** Production ID input width */
|
||||
productionIdInputWidth: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Execution configuration (User-only)
|
||||
*/
|
||||
export interface ExecutionConfig {
|
||||
/** Dry run mode */
|
||||
dryRun: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete settings data structure
|
||||
* Note: No ERP configuration - it's stored in database per user
|
||||
*/
|
||||
export interface SettingsData {
|
||||
/** ERP configuration */
|
||||
erp: ErpConfig
|
||||
/** Database configuration */
|
||||
database: DatabaseConfig
|
||||
/** Path configuration */
|
||||
@@ -144,10 +108,6 @@ export interface SettingsData {
|
||||
extraction: ExtractionConfig
|
||||
/** Validation configuration */
|
||||
validation: ValidationConfig
|
||||
/** UI configuration */
|
||||
ui: UiConfig
|
||||
/** Execution configuration */
|
||||
execution: ExecutionConfig
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -182,8 +142,6 @@ export interface SettingsAPI {
|
||||
saveSettings: (settings: SettingsData) => Promise<SaveSettingsResult>
|
||||
/** Reset to defaults (Admin only) */
|
||||
resetDefaults: () => Promise<SaveSettingsResult>
|
||||
/** Test ERP connection */
|
||||
testErpConnection: () => Promise<ConnectionTestResult>
|
||||
/** Test database connection */
|
||||
testDbConnection: () => Promise<ConnectionTestResult>
|
||||
}
|
||||
|
||||
300
src/preload/index.d.ts
vendored
300
src/preload/index.d.ts
vendored
@@ -1,4 +1,4 @@
|
||||
import type { FileAPI, ExtractorAPI, CleanerAPI, DatabaseAPI } from '../main/types/ipc-api.types'
|
||||
import type { FileAPI, ExtractorAPI, CleanerAPI, DatabaseAPI, ReportAPI } from '../main/types/ipc-api.types'
|
||||
import type { ResolverInput, ResolverResponse } from '../main/ipc/resolver-handler'
|
||||
import type { UserInfo } from '../main/types/user.types'
|
||||
import type {
|
||||
@@ -15,235 +15,123 @@ import type {
|
||||
MaterialTypeBatchRequest
|
||||
} from '../main/types/validation.types'
|
||||
import type {
|
||||
SettingsData,
|
||||
UserType,
|
||||
ConnectionTestResult,
|
||||
SaveSettingsResult
|
||||
} from '../main/types/settings.types'
|
||||
import type { IpcResult } from '../main/ipc'
|
||||
import type { LogLevel } from '../shared/ipc-channels'
|
||||
import type { CleanerConfig } from '../main/types/config.schema'
|
||||
|
||||
/**
|
||||
* Order number resolver API
|
||||
*/
|
||||
export interface ResolverAPI {
|
||||
/**
|
||||
* Resolve productionIDs and 生产订单号 to production order numbers
|
||||
* @param input - Resolver input with list of inputs
|
||||
*/
|
||||
resolve: (input: ResolverInput) => Promise<ResolverResponse>
|
||||
/**
|
||||
* Validate input format only (without database lookup)
|
||||
* @param inputs - List of inputs to validate
|
||||
*/
|
||||
validateFormat: (inputs: string[]) => Promise<{
|
||||
success: boolean
|
||||
results?: Array<{ input: string; type: 'productionId' | 'orderNumber' | 'unknown' }>
|
||||
error?: string
|
||||
}>
|
||||
resolve: (input: ResolverInput) => Promise<IpcResult<ResolverResponse>>
|
||||
validateFormat: (
|
||||
inputs: string[]
|
||||
) => Promise<
|
||||
IpcResult<Array<{ input: string; type: 'productionId' | 'orderNumber' | 'unknown' }>>
|
||||
>
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication API
|
||||
*/
|
||||
export interface AuthAPI {
|
||||
/**
|
||||
* Get computer name
|
||||
*/
|
||||
getComputerName: () => Promise<string>
|
||||
/**
|
||||
* Silent login by computer name
|
||||
*/
|
||||
silentLogin: () => Promise<SilentLoginResponse>
|
||||
/**
|
||||
* Login with username and password
|
||||
* @param request - Login request with username and password
|
||||
*/
|
||||
login: (request: LoginRequest) => Promise<LoginResponse>
|
||||
/**
|
||||
* Logout
|
||||
*/
|
||||
logout: () => Promise<void>
|
||||
/**
|
||||
* Get current user
|
||||
*/
|
||||
getCurrentUser: () => Promise<CurrentUserResponse>
|
||||
/**
|
||||
* Get all users (for admin user selection)
|
||||
*/
|
||||
getAllUsers: () => Promise<UserInfo[]>
|
||||
/**
|
||||
* Switch user (admin only)
|
||||
* @param userInfo - User info to switch to
|
||||
*/
|
||||
switchUser: (userInfo: UserInfo) => Promise<UserSelectionResponse>
|
||||
/**
|
||||
* Check if current user is admin
|
||||
*/
|
||||
isAdmin: () => Promise<boolean>
|
||||
getComputerName: () => Promise<IpcResult<string>>
|
||||
silentLogin: () => Promise<IpcResult<SilentLoginResponse>>
|
||||
login: (request: LoginRequest) => Promise<IpcResult<LoginResponse>>
|
||||
logout: () => Promise<IpcResult<void>>
|
||||
getCurrentUser: () => Promise<IpcResult<CurrentUserResponse>>
|
||||
getAllUsers: () => Promise<IpcResult<UserInfo[]>>
|
||||
switchUser: (userInfo: UserInfo) => Promise<IpcResult<UserSelectionResponse>>
|
||||
isAdmin: () => Promise<IpcResult<boolean>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Validation API
|
||||
*/
|
||||
export interface ValidationAPI {
|
||||
/**
|
||||
* Run material validation
|
||||
* @param request - Validation request
|
||||
*/
|
||||
validate: (request: ValidationRequest) => Promise<ValidationResponse>
|
||||
/**
|
||||
* Set shared Production IDs from extractor page
|
||||
* @param productionIds - List of Production IDs
|
||||
*/
|
||||
setSharedProductionIds: (productionIds: string[]) => Promise<void>
|
||||
/**
|
||||
* Get shared Production IDs
|
||||
*/
|
||||
getSharedProductionIds: () => Promise<{ productionIds: string[] }>
|
||||
/**
|
||||
* Get cleaner data (order numbers from shared Production IDs + material codes from MaterialsToBeDeleted)
|
||||
* Filters materials by current user (admin sees all, regular users see only their own)
|
||||
*/
|
||||
getCleanerData: () => Promise<{
|
||||
success: boolean
|
||||
orderNumbers?: string[]
|
||||
materialCodes?: string[]
|
||||
error?: string
|
||||
}>
|
||||
validate: (request: ValidationRequest) => Promise<IpcResult<ValidationResponse>>
|
||||
setSharedProductionIds: (productionIds: string[]) => Promise<IpcResult<void>>
|
||||
getSharedProductionIds: () => Promise<IpcResult<{ productionIds: string[] }>>
|
||||
clearSharedProductionIds: () => Promise<IpcResult<void>>
|
||||
getCleanerData: () => Promise<
|
||||
IpcResult<{
|
||||
orderNumbers: string[]
|
||||
materialCodes: string[]
|
||||
}>
|
||||
>
|
||||
}
|
||||
|
||||
/**
|
||||
* Materials API
|
||||
*/
|
||||
export interface MaterialsAPI {
|
||||
/**
|
||||
* Upsert batch materials to MaterialsToBeDeleted
|
||||
* @param materials - List of materials with materialCode and managerName
|
||||
*/
|
||||
upsertBatch: (materials: { materialCode: string; managerName: string }[]) => Promise<{
|
||||
success: boolean
|
||||
stats?: { total: number; success: number; failed: number }
|
||||
error?: string
|
||||
}>
|
||||
/**
|
||||
* Delete materials by material codes
|
||||
* @param materialCodes - List of material codes to delete
|
||||
*/
|
||||
delete: (materialCodes: string[]) => Promise<{
|
||||
success: boolean
|
||||
count?: number
|
||||
error?: string
|
||||
}>
|
||||
/**
|
||||
* Get unique manager names
|
||||
*/
|
||||
getManagers: () => Promise<{ managers: string[] }>
|
||||
/**
|
||||
* Get materials by manager
|
||||
* @param managerName - Manager name
|
||||
*/
|
||||
getByManager: (managerName: string) => Promise<{ materials: unknown[] }>
|
||||
/**
|
||||
* Get all material records
|
||||
*/
|
||||
getAll: () => Promise<{ materials: unknown[] }>
|
||||
/**
|
||||
* Get statistics
|
||||
*/
|
||||
getStatistics: () => Promise<{ stats: unknown }>
|
||||
upsertBatch: (
|
||||
materials: { materialCode: string; managerName: string }[]
|
||||
) => Promise<IpcResult<{ stats: { total: number; success: number; failed: number } }>>
|
||||
delete: (materialCodes: string[]) => Promise<IpcResult<{ count: number }>>
|
||||
getManagers: () => Promise<IpcResult<{ managers: string[] }>>
|
||||
getByManager: (managerName: string) => Promise<IpcResult<{ materials: unknown[] }>>
|
||||
getAll: () => Promise<IpcResult<{ materials: unknown[] }>>
|
||||
getStatistics: () => Promise<IpcResult<{ stats: unknown }>>
|
||||
updateManager: (
|
||||
materialCode: string,
|
||||
managerName: string
|
||||
) => Promise<IpcResult<{ updated: boolean }>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings API
|
||||
*/
|
||||
export interface SettingsAPI {
|
||||
/**
|
||||
* Get current user type
|
||||
*/
|
||||
getUserType: () => Promise<UserType>
|
||||
/**
|
||||
* Get settings (filtered by user type)
|
||||
*/
|
||||
getSettings: () => Promise<SettingsData>
|
||||
/**
|
||||
* Save settings
|
||||
* @param settings - Settings data to save
|
||||
*/
|
||||
saveSettings: (settings: SettingsData) => Promise<SaveSettingsResult>
|
||||
/**
|
||||
* Reset to defaults (Admin only)
|
||||
*/
|
||||
resetDefaults: () => Promise<SaveSettingsResult>
|
||||
/**
|
||||
* Test ERP connection
|
||||
*/
|
||||
testErpConnection: () => Promise<ConnectionTestResult>
|
||||
/**
|
||||
* Test database connection
|
||||
*/
|
||||
testDbConnection: () => Promise<ConnectionTestResult>
|
||||
getUserType: () => Promise<IpcResult<UserType>>
|
||||
getSettings: () => Promise<IpcResult<{ erp: { username: string; password: string } }>>
|
||||
saveSettings: (settings: {
|
||||
erp?: { username?: string; password?: string }
|
||||
}) => Promise<IpcResult<SaveSettingsResult>>
|
||||
resetDefaults: () => Promise<IpcResult<SaveSettingsResult>>
|
||||
testDbConnection: () => Promise<IpcResult<ConnectionTestResult>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Material Type API
|
||||
*/
|
||||
export interface MaterialTypeAPI {
|
||||
/**
|
||||
* Get all material type records
|
||||
*/
|
||||
getAll: () => Promise<{ success: boolean; data?: MaterialTypeRecord[]; error?: string }>
|
||||
/**
|
||||
* Get material types by manager
|
||||
* @param managerName - Manager name
|
||||
*/
|
||||
getByManager: (
|
||||
managerName: string
|
||||
) => Promise<{ success: boolean; data?: MaterialTypeRecord[]; error?: string }>
|
||||
/**
|
||||
* Get list of managers
|
||||
*/
|
||||
getManagers: () => Promise<{ success: boolean; data?: string[]; error?: string }>
|
||||
/**
|
||||
* Upsert (insert or update) a material type record
|
||||
*/
|
||||
upsert: (
|
||||
materialName: string,
|
||||
managerName: string
|
||||
) => Promise<{ success: boolean; error?: string }>
|
||||
/**
|
||||
* Delete a material type record
|
||||
*/
|
||||
delete: (
|
||||
materialName: string,
|
||||
managerName: string
|
||||
) => Promise<{ success: boolean; error?: string }>
|
||||
/**
|
||||
* Batch operation for material types
|
||||
*/
|
||||
upsertBatch: (request: MaterialTypeBatchRequest) => Promise<{
|
||||
success: boolean
|
||||
stats?: { total: number; success: number; failed: number }
|
||||
error?: string
|
||||
}>
|
||||
getAll: () => Promise<IpcResult<MaterialTypeRecord[]>>
|
||||
getByManager: (managerName: string) => Promise<IpcResult<MaterialTypeRecord[]>>
|
||||
getManagers: () => Promise<IpcResult<string[]>>
|
||||
upsert: (materialName: string, managerName: string) => Promise<IpcResult<{ updated: boolean }>>
|
||||
delete: (materialName: string, managerName: string) => Promise<IpcResult<{ deleted: boolean }>>
|
||||
upsertBatch: (
|
||||
request: MaterialTypeBatchRequest
|
||||
) => Promise<IpcResult<{ stats: { total: number; success: number; failed: number } }>>
|
||||
}
|
||||
|
||||
export interface UserErpConfigAPI {
|
||||
getCurrent: () => Promise<
|
||||
IpcResult<{
|
||||
config: { url: string; username: string; password: string }
|
||||
}>
|
||||
>
|
||||
update: (config: { url: string; username: string; password: string }) => Promise<
|
||||
IpcResult<{
|
||||
config: { url: string; username: string; password: string }
|
||||
}>
|
||||
>
|
||||
testConnection: (config: {
|
||||
url: string
|
||||
username: string
|
||||
password: string
|
||||
}) => Promise<IpcResult<{ message: string }>>
|
||||
getAll: () => Promise<IpcResult<Array<{ username: string; erpUrl: string; erpUsername: string }>>>
|
||||
}
|
||||
|
||||
export interface ConfigAPI {
|
||||
getCleaner: () => Promise<IpcResult<CleanerConfig>>
|
||||
updateCleaner: (updates: Partial<CleanerConfig>) => Promise<IpcResult<CleanerConfig>>
|
||||
}
|
||||
|
||||
export interface LoggerAPI {
|
||||
log: (level: LogLevel, message: string, context?: Record<string, unknown>) => void
|
||||
}
|
||||
|
||||
export interface ProcessAPI {
|
||||
versions: {
|
||||
electron: string
|
||||
chrome: string
|
||||
node: string
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
electron: {
|
||||
ipcRenderer: {
|
||||
send: (channel: string, ...args: unknown[]) => void
|
||||
on: (channel: string, func: (...args: unknown[]) => void) => void
|
||||
once: (channel: string, func: (...args: unknown[]) => void) => void
|
||||
removeListener: (channel: string, func: (...args: unknown[]) => void) => void
|
||||
removeAllListeners: (channel: string) => void
|
||||
invoke: (channel: string, ...args: unknown[]) => Promise<unknown>
|
||||
}
|
||||
process: {
|
||||
versions: {
|
||||
electron: string
|
||||
chrome: string
|
||||
node: string
|
||||
}
|
||||
}
|
||||
process: ProcessAPI
|
||||
file: FileAPI
|
||||
extractor: ExtractorAPI
|
||||
cleaner: CleanerAPI
|
||||
@@ -254,6 +142,10 @@ declare global {
|
||||
materials: MaterialsAPI
|
||||
settings: SettingsAPI
|
||||
materialType: MaterialTypeAPI
|
||||
userErpConfig: UserErpConfigAPI
|
||||
config: ConfigAPI
|
||||
logger: LoggerAPI
|
||||
report: ReportAPI
|
||||
}
|
||||
api: unknown
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
import { electronAPI } from '@electron-toolkit/preload'
|
||||
import type { MySqlConfig, SqlServerConfig } from '../main/types/ipc-api.types'
|
||||
import type { ExtractorInput } from '../main/types/extractor.types'
|
||||
import type { CleanerInput, ExportResultItem } from '../main/types/cleaner.types'
|
||||
import type { ExtractorInput, ExtractionProgress } from '../main/types/extractor.types'
|
||||
import type { CleanerInput, CleanerProgress, ExportResultItem } from '../main/types/cleaner.types'
|
||||
import type { ResolverInput } from '../main/ipc/resolver-handler'
|
||||
import type { LoginRequest } from '../main/ipc/auth-handler'
|
||||
import type { UserInfo } from '../main/types/user.types'
|
||||
@@ -11,124 +10,227 @@ import type {
|
||||
MaterialTypeRecord,
|
||||
MaterialTypeBatchRequest
|
||||
} from '../main/types/validation.types'
|
||||
import type { SettingsData } from '../main/types/settings.types'
|
||||
import type { IpcResult } from '../main/ipc'
|
||||
import { IPC_CHANNELS, type LogLevel } from '../shared/ipc-channels'
|
||||
import type { CleanerConfig } from '../main/types/config.schema'
|
||||
|
||||
type ErpSettingsPayload = {
|
||||
erp?: {
|
||||
username?: string
|
||||
password?: string
|
||||
}
|
||||
}
|
||||
|
||||
const processApi = {
|
||||
versions: {
|
||||
electron: process.versions.electron,
|
||||
chrome: process.versions.chrome,
|
||||
node: process.versions.node
|
||||
}
|
||||
}
|
||||
|
||||
function invokeIpc<T = unknown>(channel: string, ...args: unknown[]): Promise<IpcResult<T>> {
|
||||
return ipcRenderer.invoke(channel, ...args).then((result: unknown) => {
|
||||
if (result && typeof result === 'object' && 'success' in (result as Record<string, unknown>)) {
|
||||
const typed = result as Record<string, unknown>
|
||||
const hasIpcShape = 'data' in typed || 'code' in typed || 'error' in typed
|
||||
|
||||
if (hasIpcShape) {
|
||||
return typed as unknown as IpcResult<T>
|
||||
}
|
||||
|
||||
if (typed.success === true) {
|
||||
return { success: true, data: result as T }
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: typeof typed.error === 'string' ? typed.error : 'IPC operation failed'
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: result as T }
|
||||
})
|
||||
}
|
||||
|
||||
// Custom APIs for renderer
|
||||
const api = {
|
||||
// File operations
|
||||
process: processApi,
|
||||
|
||||
file: {
|
||||
readFile: (filePath: string) => ipcRenderer.invoke('file:read', filePath),
|
||||
readFile: (filePath: string) => invokeIpc(IPC_CHANNELS.FILE_READ, filePath),
|
||||
writeFile: (filePath: string, content: string) =>
|
||||
ipcRenderer.invoke('file:write', filePath, content),
|
||||
fileExists: (filePath: string) => ipcRenderer.invoke('file:exists', filePath),
|
||||
listFiles: (dirPath: string) => ipcRenderer.invoke('file:list', dirPath)
|
||||
invokeIpc(IPC_CHANNELS.FILE_WRITE, filePath, content),
|
||||
fileExists: (filePath: string) => invokeIpc(IPC_CHANNELS.FILE_EXISTS, filePath),
|
||||
listFiles: (dirPath: string) => invokeIpc(IPC_CHANNELS.FILE_LIST, dirPath),
|
||||
openPath: (filePath: string) => invokeIpc(IPC_CHANNELS.FILE_OPEN_PATH, filePath)
|
||||
},
|
||||
|
||||
// Extractor service
|
||||
extractor: {
|
||||
runExtractor: (input: ExtractorInput) => ipcRenderer.invoke('extractor:run', input)
|
||||
runExtractor: (input: ExtractorInput): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.EXTRACTOR_RUN, input),
|
||||
onProgress: (callback: (data: ExtractionProgress) => void) => {
|
||||
const subscription = (_event: Electron.IpcRendererEvent, data: ExtractionProgress) =>
|
||||
callback(data)
|
||||
ipcRenderer.on(IPC_CHANNELS.EXTRACTOR_PROGRESS, subscription)
|
||||
return () => ipcRenderer.removeListener(IPC_CHANNELS.EXTRACTOR_PROGRESS, subscription)
|
||||
},
|
||||
onLog: (callback: (data: { level: string; message: string }) => void) => {
|
||||
const subscription = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
data: { level: string; message: string }
|
||||
) => callback(data)
|
||||
ipcRenderer.on(IPC_CHANNELS.EXTRACTOR_LOG, subscription)
|
||||
return () => ipcRenderer.removeListener(IPC_CHANNELS.EXTRACTOR_LOG, subscription)
|
||||
}
|
||||
},
|
||||
|
||||
// Cleaner service
|
||||
cleaner: {
|
||||
runCleaner: (input: CleanerInput) => ipcRenderer.invoke('cleaner:run', input),
|
||||
exportResults: (items: ExportResultItem[]) => ipcRenderer.invoke('cleaner:exportResults', items)
|
||||
runCleaner: (input: CleanerInput): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.CLEANER_RUN, input),
|
||||
exportResults: (items: ExportResultItem[]): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.CLEANER_EXPORT_RESULTS, items),
|
||||
onProgress: (callback: (data: CleanerProgress) => void) => {
|
||||
const subscription = (_event: Electron.IpcRendererEvent, data: CleanerProgress) =>
|
||||
callback(data)
|
||||
ipcRenderer.on(IPC_CHANNELS.CLEANER_PROGRESS, subscription)
|
||||
return () => ipcRenderer.removeListener(IPC_CHANNELS.CLEANER_PROGRESS, subscription)
|
||||
}
|
||||
},
|
||||
|
||||
// Order number resolver
|
||||
resolver: {
|
||||
resolve: (input: ResolverInput) => ipcRenderer.invoke('resolver:resolve', input),
|
||||
validateFormat: (inputs: string[]) => ipcRenderer.invoke('resolver:validateFormat', inputs)
|
||||
resolve: (input: ResolverInput): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.RESOLVER_RESOLVE, input),
|
||||
validateFormat: (inputs: string[]): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.RESOLVER_VALIDATE_FORMAT, inputs)
|
||||
},
|
||||
|
||||
// Authentication service
|
||||
auth: {
|
||||
getComputerName: () => ipcRenderer.invoke('auth:getComputerName'),
|
||||
silentLogin: () => ipcRenderer.invoke('auth:silentLogin'),
|
||||
login: (request: LoginRequest) => ipcRenderer.invoke('auth:login', request),
|
||||
logout: () => ipcRenderer.invoke('auth:logout'),
|
||||
getCurrentUser: () => ipcRenderer.invoke('auth:getCurrentUser'),
|
||||
getAllUsers: () => ipcRenderer.invoke('auth:getAllUsers'),
|
||||
switchUser: (userInfo: UserInfo) => ipcRenderer.invoke('auth:switchUser', userInfo),
|
||||
isAdmin: () => ipcRenderer.invoke('auth:isAdmin')
|
||||
getComputerName: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.AUTH_GET_COMPUTER_NAME),
|
||||
silentLogin: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.AUTH_SILENT_LOGIN),
|
||||
login: (request: LoginRequest): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.AUTH_LOGIN, request),
|
||||
logout: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.AUTH_LOGOUT),
|
||||
getCurrentUser: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.AUTH_GET_CURRENT_USER),
|
||||
getAllUsers: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.AUTH_GET_ALL_USERS),
|
||||
switchUser: (userInfo: UserInfo): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.AUTH_SWITCH_USER, userInfo),
|
||||
isAdmin: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.AUTH_IS_ADMIN)
|
||||
},
|
||||
|
||||
// Database service
|
||||
database: {
|
||||
connectMySql: (config: MySqlConfig) => ipcRenderer.invoke('database:mysql:connect', config),
|
||||
disconnectMySql: () => ipcRenderer.invoke('database:mysql:disconnect'),
|
||||
isMySqlConnected: () => ipcRenderer.invoke('database:mysql:isConnected'),
|
||||
queryMySql: (sql: string, params?: any[]) =>
|
||||
ipcRenderer.invoke('database:mysql:query', sql, params),
|
||||
|
||||
// SQL Server
|
||||
connectSqlServer: (config: SqlServerConfig) =>
|
||||
ipcRenderer.invoke('database:sqlserver:connect', config),
|
||||
disconnectSqlServer: () => ipcRenderer.invoke('database:sqlserver:disconnect'),
|
||||
isSqlServerConnected: () => ipcRenderer.invoke('database:sqlserver:isConnected'),
|
||||
querySqlServer: (sql: string, params?: Record<string, unknown>) =>
|
||||
ipcRenderer.invoke('database:sqlserver:query', sql, params)
|
||||
connectMySql: (config: MySqlConfig): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.DATABASE_MYSQL_CONNECT, config),
|
||||
disconnectMySql: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.DATABASE_MYSQL_DISCONNECT),
|
||||
isMySqlConnected: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.DATABASE_MYSQL_IS_CONNECTED),
|
||||
queryMySql: (sql: string, params?: any[]): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.DATABASE_MYSQL_QUERY, sql, params),
|
||||
connectSqlServer: (config: SqlServerConfig): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.DATABASE_SQLSERVER_CONNECT, config),
|
||||
disconnectSqlServer: (): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.DATABASE_SQLSERVER_DISCONNECT),
|
||||
isSqlServerConnected: (): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.DATABASE_SQLSERVER_IS_CONNECTED),
|
||||
querySqlServer: (sql: string, params?: Record<string, unknown>): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.DATABASE_SQLSERVER_QUERY, sql, params)
|
||||
},
|
||||
|
||||
// Validation service
|
||||
validation: {
|
||||
validate: (request: ValidationRequest) => ipcRenderer.invoke('validation:validate', request),
|
||||
setSharedProductionIds: (productionIds: string[]) =>
|
||||
ipcRenderer.invoke('validation:setSharedProductionIds', productionIds),
|
||||
getSharedProductionIds: () => ipcRenderer.invoke('validation:getSharedProductionIds'),
|
||||
getCleanerData: () => ipcRenderer.invoke('validation:getCleanerData')
|
||||
validate: (request: ValidationRequest): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.VALIDATION_VALIDATE, request),
|
||||
setSharedProductionIds: (productionIds: string[]): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.VALIDATION_SET_SHARED_PRODUCTION_IDS, productionIds),
|
||||
getSharedProductionIds: (): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.VALIDATION_GET_SHARED_PRODUCTION_IDS),
|
||||
clearSharedProductionIds: (): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.VALIDATION_CLEAR_SHARED_PRODUCTION_IDS),
|
||||
getCleanerData: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.VALIDATION_GET_CLEANER_DATA)
|
||||
},
|
||||
|
||||
// Materials service
|
||||
materials: {
|
||||
upsertBatch: (materials: { materialCode: string; managerName: string }[]) =>
|
||||
ipcRenderer.invoke('materials:upsertBatch', { materials }),
|
||||
delete: (materialCodes: string[]) => ipcRenderer.invoke('materials:delete', { materialCodes }),
|
||||
getManagers: () => ipcRenderer.invoke('materials:getManagers'),
|
||||
getByManager: (managerName: string) =>
|
||||
ipcRenderer.invoke('materials:getByManager', managerName),
|
||||
getAll: () => ipcRenderer.invoke('materials:getAll'),
|
||||
getStatistics: () => ipcRenderer.invoke('materials:getStatistics')
|
||||
upsertBatch: (materials: { materialCode: string; managerName: string }[]): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIALS_UPSERT_BATCH, { materials }),
|
||||
delete: (materialCodes: string[]): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIALS_DELETE, { materialCodes }),
|
||||
getManagers: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.MATERIALS_GET_MANAGERS),
|
||||
getByManager: (managerName: string): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIALS_GET_BY_MANAGER, managerName),
|
||||
getAll: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.MATERIALS_GET_ALL),
|
||||
getStatistics: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.MATERIALS_GET_STATISTICS),
|
||||
updateManager: (materialCode: string, managerName: string): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIALS_UPDATE_MANAGER, { materialCode, managerName })
|
||||
},
|
||||
|
||||
// Settings service
|
||||
settings: {
|
||||
getUserType: () => ipcRenderer.invoke('settings:getUserType'),
|
||||
getSettings: () => ipcRenderer.invoke('settings:getSettings'),
|
||||
saveSettings: (settings: SettingsData) => ipcRenderer.invoke('settings:saveSettings', settings),
|
||||
resetDefaults: () => ipcRenderer.invoke('settings:resetDefaults'),
|
||||
testErpConnection: () => ipcRenderer.invoke('settings:testErpConnection'),
|
||||
testDbConnection: () => ipcRenderer.invoke('settings:testDbConnection')
|
||||
getUserType: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.SETTINGS_GET_USER_TYPE),
|
||||
getSettings: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.SETTINGS_GET_SETTINGS),
|
||||
saveSettings: (settings: ErpSettingsPayload): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.SETTINGS_SAVE_SETTINGS, settings),
|
||||
resetDefaults: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.SETTINGS_RESET_DEFAULTS),
|
||||
testDbConnection: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.SETTINGS_TEST_DB_CONNECTION)
|
||||
},
|
||||
|
||||
// Material Type service
|
||||
materialType: {
|
||||
getAll: () => ipcRenderer.invoke('materialType:getAll'),
|
||||
getByManager: (managerName: string) =>
|
||||
ipcRenderer.invoke('materialType:getByManager', managerName),
|
||||
getManagers: () => ipcRenderer.invoke('materialType:getManagers'),
|
||||
upsert: (materialName: string, managerName: string) =>
|
||||
ipcRenderer.invoke('materialType:upsert', { materialName, managerName }),
|
||||
delete: (materialName: string, managerName: string) =>
|
||||
ipcRenderer.invoke('materialType:delete', { materialName, managerName }),
|
||||
upsertBatch: (request: MaterialTypeBatchRequest) =>
|
||||
ipcRenderer.invoke('materialType:upsertBatch', request)
|
||||
getAll: (): Promise<IpcResult<MaterialTypeRecord[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIAL_TYPE_GET_ALL),
|
||||
getByManager: (managerName: string): Promise<IpcResult<MaterialTypeRecord[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIAL_TYPE_GET_BY_MANAGER, managerName),
|
||||
getManagers: (): Promise<IpcResult<string[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIAL_TYPE_GET_MANAGERS),
|
||||
upsert: (materialName: string, managerName: string): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIAL_TYPE_UPSERT, { materialName, managerName }),
|
||||
delete: (materialName: string, managerName: string): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIAL_TYPE_DELETE, { materialName, managerName }),
|
||||
upsertBatch: (request: MaterialTypeBatchRequest): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.MATERIAL_TYPE_UPSERT_BATCH, request)
|
||||
},
|
||||
|
||||
userErpConfig: {
|
||||
getCurrent: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.USER_ERP_CONFIG_GET_CURRENT),
|
||||
update: (config: { url: string; username: string; password: string }): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.USER_ERP_CONFIG_UPDATE, config),
|
||||
testConnection: (config: {
|
||||
url: string
|
||||
username: string
|
||||
password: string
|
||||
}): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.USER_ERP_CONFIG_TEST_CONNECTION, config),
|
||||
getAll: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.USER_ERP_CONFIG_GET_ALL)
|
||||
},
|
||||
|
||||
config: {
|
||||
getCleaner: (): Promise<IpcResult<CleanerConfig>> => invokeIpc(IPC_CHANNELS.CONFIG_GET_CLEANER),
|
||||
updateCleaner: (updates: Partial<CleanerConfig>): Promise<IpcResult<CleanerConfig>> =>
|
||||
invokeIpc(IPC_CHANNELS.CONFIG_UPDATE_CLEANER, updates)
|
||||
},
|
||||
|
||||
logger: {
|
||||
log: (level: LogLevel, message: string, context?: Record<string, unknown>): void => {
|
||||
ipcRenderer.send(IPC_CHANNELS.LOGGER_FORWARD, {
|
||||
level,
|
||||
message,
|
||||
context,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
report: {
|
||||
listAll: (): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.REPORT_LIST_ALL),
|
||||
listByUser: (username: string): Promise<IpcResult> =>
|
||||
invokeIpc(IPC_CHANNELS.REPORT_LIST_BY_USER, username),
|
||||
download: (key: string): Promise<IpcResult> => invokeIpc(IPC_CHANNELS.REPORT_DOWNLOAD, key)
|
||||
}
|
||||
} as const
|
||||
|
||||
// Use `contextBridge` APIs to expose Electron APIs to
|
||||
// renderer only if context isolation is enabled, otherwise
|
||||
// just add to the DOM global.
|
||||
if (process.contextIsolated) {
|
||||
try {
|
||||
contextBridge.exposeInMainWorld('electron', { ...electronAPI, ...api })
|
||||
contextBridge.exposeInMainWorld('electron', api)
|
||||
contextBridge.exposeInMainWorld('api', api)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
} else {
|
||||
// @ts-ignore (define in dts)
|
||||
window.electron = { ...electronAPI, ...api }
|
||||
window.electron = api
|
||||
// @ts-ignore (define in dts)
|
||||
window.api = api
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@
|
||||
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { LayoutDashboard, Download, Trash2, Settings, Database, User, LogOut } from 'lucide-react'
|
||||
import { useLogger } from './hooks/useLogger'
|
||||
import LoginDialog from './components/LoginDialog'
|
||||
import UserSelectionDialog, {
|
||||
type UserInfo as SelectedUserInfo
|
||||
} from './components/UserSelectionDialog'
|
||||
import { Toast } from './components/ui/Toast'
|
||||
import ExtractorPage from './pages/ExtractorPage'
|
||||
import CleanerPage from './pages/CleanerPage'
|
||||
import SettingsPage from './pages/SettingsPage'
|
||||
@@ -26,6 +28,9 @@ interface CurrentUser {
|
||||
}
|
||||
|
||||
function App(): React.JSX.Element {
|
||||
// Create logger instance for App component
|
||||
const logger = useLogger('App')
|
||||
|
||||
// Authentication state
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false)
|
||||
const [isAuthenticating, setIsAuthenticating] = useState(true)
|
||||
@@ -41,6 +46,9 @@ function App(): React.JSX.Element {
|
||||
// Track if current session is switched by Admin
|
||||
const [isSwitchedByAdmin, setIsSwitchedByAdmin] = useState(false)
|
||||
|
||||
// Ref for logout button (for focus restoration)
|
||||
const logoutButtonRef = React.useRef<HTMLButtonElement>(null)
|
||||
|
||||
// Navigation state
|
||||
const [currentPage, setCurrentPage] = useState<Page>('extractor') // Default to extractor for the new layout
|
||||
|
||||
@@ -52,26 +60,30 @@ function App(): React.JSX.Element {
|
||||
|
||||
// Initialize authentication on mount
|
||||
useEffect(() => {
|
||||
console.log('=== App: Initializing auth... ===')
|
||||
logger.info('=== Initializing auth... ===')
|
||||
initializeAuth()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
const initializeAuth = async () => {
|
||||
console.log('=== App: Starting initializeAuth ===')
|
||||
logger.info('=== Starting initializeAuth ===')
|
||||
try {
|
||||
// Get computer name
|
||||
console.log('Getting computer name...')
|
||||
const name = await window.electron.auth.getComputerName()
|
||||
console.log('Computer name:', name)
|
||||
logger.debug('Getting computer name...')
|
||||
const computerNameResult = await window.electron.auth.getComputerName()
|
||||
const name =
|
||||
computerNameResult.success && computerNameResult.data ? computerNameResult.data : ''
|
||||
logger.debug('Computer name obtained', { name })
|
||||
setComputerName(name)
|
||||
|
||||
// Try silent login
|
||||
console.log('Trying silent login...')
|
||||
const result = await window.electron.auth.silentLogin()
|
||||
console.log('Silent login result:', result)
|
||||
logger.debug('Trying silent login...')
|
||||
const silentLoginResult = await window.electron.auth.silentLogin()
|
||||
const result = silentLoginResult.data
|
||||
logger.debug('Silent login result', { result })
|
||||
|
||||
if (result.success && result.userInfo) {
|
||||
console.log('Silent login success:', result.userInfo)
|
||||
if (silentLoginResult.success && result?.success && result.userInfo) {
|
||||
logger.info('Silent login success', { username: result.userInfo.username })
|
||||
setCurrentUser({
|
||||
username: result.userInfo.username,
|
||||
userType: result.userInfo.userType
|
||||
@@ -79,47 +91,50 @@ function App(): React.JSX.Element {
|
||||
|
||||
// Check if admin needs user selection
|
||||
if (result.requiresUserSelection) {
|
||||
console.log('Admin user needs to select user')
|
||||
logger.info('Admin user needs to select user')
|
||||
// Load all users for selection
|
||||
const users = await window.electron.auth.getAllUsers()
|
||||
setAllUsers(users)
|
||||
const usersResult = await window.electron.auth.getAllUsers()
|
||||
setAllUsers(usersResult.success && usersResult.data ? usersResult.data : [])
|
||||
setShowUserSelection(true)
|
||||
} else {
|
||||
console.log('Setting authenticated to true')
|
||||
logger.info('Setting authenticated to true')
|
||||
setIsAuthenticated(true)
|
||||
}
|
||||
} else {
|
||||
console.log('Silent login failed, showing login dialog')
|
||||
logger.info('Silent login failed, showing login dialog')
|
||||
// Silent login failed, show login dialog
|
||||
setShowLoginDialog(true)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Auth initialization error:', error)
|
||||
logger.error('Auth initialization error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
setShowLoginDialog(true)
|
||||
} finally {
|
||||
console.log('Setting isAuthenticating to false')
|
||||
logger.debug('Setting isAuthenticating to false')
|
||||
setIsAuthenticating(false)
|
||||
}
|
||||
console.log('=== App: Auth initialization complete ===')
|
||||
logger.info('=== Auth initialization complete ===')
|
||||
}
|
||||
|
||||
// Handle login dialog submit
|
||||
const handleLogin = async (username: string, password: string): Promise<boolean> => {
|
||||
try {
|
||||
const result = await window.electron.auth.login({ username, password })
|
||||
const loginData = result.success ? result.data : undefined
|
||||
|
||||
if (result.success && result.userInfo) {
|
||||
if (result.success && loginData?.userInfo) {
|
||||
setCurrentUser({
|
||||
username: result.userInfo.username,
|
||||
userType: result.userInfo.userType
|
||||
username: loginData.userInfo.username,
|
||||
userType: loginData.userInfo.userType
|
||||
})
|
||||
|
||||
// Check if admin needs user selection
|
||||
if (result.userInfo.userType === 'Admin') {
|
||||
if (loginData.userInfo.userType === 'Admin') {
|
||||
setShowLoginDialog(false)
|
||||
// Load all users for selection
|
||||
const users = await window.electron.auth.getAllUsers()
|
||||
setAllUsers(users)
|
||||
const usersResult = await window.electron.auth.getAllUsers()
|
||||
setAllUsers(usersResult.success && usersResult.data ? usersResult.data : [])
|
||||
setShowUserSelection(true)
|
||||
} else {
|
||||
setIsAuthenticated(true)
|
||||
@@ -129,7 +144,7 @@ function App(): React.JSX.Element {
|
||||
}
|
||||
return false
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
logger.error('Login error', { error: error instanceof Error ? error.message : String(error) })
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -144,10 +159,11 @@ function App(): React.JSX.Element {
|
||||
const handleUserSelect = async (user: SelectedUserInfo) => {
|
||||
try {
|
||||
const result = await window.electron.auth.switchUser(user)
|
||||
if (result.success) {
|
||||
const switchData = result.success ? result.data : undefined
|
||||
if (result.success && switchData) {
|
||||
setCurrentUser({
|
||||
username: result.userInfo?.username || user.username,
|
||||
userType: result.userInfo?.userType || user.userType
|
||||
username: switchData.userInfo?.username || user.username,
|
||||
userType: switchData.userInfo?.userType || user.userType
|
||||
})
|
||||
setIsAuthenticated(true)
|
||||
setShowUserSelection(false)
|
||||
@@ -155,7 +171,9 @@ function App(): React.JSX.Element {
|
||||
setIsSwitchedByAdmin(true)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('User selection error:', error)
|
||||
logger.error('User selection error', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
showError('切换用户失败')
|
||||
}
|
||||
}
|
||||
@@ -219,12 +237,7 @@ function App(): React.JSX.Element {
|
||||
|
||||
// Show login dialog if not authenticated
|
||||
if (!isAuthenticated) {
|
||||
console.log(
|
||||
'Render: not authenticated, showLoginDialog:',
|
||||
showLoginDialog,
|
||||
'computerName:',
|
||||
computerName
|
||||
)
|
||||
logger.debug('Render: not authenticated', { showLoginDialog, computerName })
|
||||
return (
|
||||
<>
|
||||
<LoginDialog
|
||||
@@ -242,6 +255,7 @@ function App(): React.JSX.Element {
|
||||
currentUsername={currentUser?.username || ''}
|
||||
onSelectUser={handleUserSelect}
|
||||
onCancel={handleUserSelectionCancel}
|
||||
triggerRef={logoutButtonRef}
|
||||
/>
|
||||
|
||||
{errorMessage && <div className="error-toast">{errorMessage}</div>}
|
||||
@@ -295,7 +309,7 @@ function App(): React.JSX.Element {
|
||||
}
|
||||
|
||||
// Show main content when authenticated
|
||||
console.log('Render: authenticated, currentUser:', currentUser, 'currentPage:', currentPage)
|
||||
logger.debug('Render: authenticated', { currentUser, currentPage })
|
||||
|
||||
const navItems = [
|
||||
{ id: 'extractor', label: '数据提取 (Extractor)', icon: <Download size={18} /> },
|
||||
@@ -318,12 +332,17 @@ function App(): React.JSX.Element {
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex items-center gap-2 text-white font-bold text-lg cursor-pointer"
|
||||
className="flex flex-col cursor-pointer"
|
||||
onClick={() => setCurrentPage('home')}
|
||||
style={{ WebkitAppRegion: 'no-drag' } as any}
|
||||
>
|
||||
<LayoutDashboard size={22} className="text-blue-500" />
|
||||
<span>ERP Auto</span>
|
||||
<div className="flex items-center gap-2 text-white font-bold text-lg">
|
||||
<LayoutDashboard size={22} className="text-blue-500" />
|
||||
<span>ERP Auto</span>
|
||||
</div>
|
||||
<span className="text-xs text-slate-400 ml-7">
|
||||
{__APP_VERSION__}({__GIT_HASH__})
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -365,6 +384,7 @@ function App(): React.JSX.Element {
|
||||
</span>
|
||||
{shouldShowLogout && (
|
||||
<button
|
||||
ref={logoutButtonRef}
|
||||
onClick={handleLogout}
|
||||
className="ml-2 text-slate-400 hover:text-red-400 transition-colors"
|
||||
title="退出登录"
|
||||
@@ -378,14 +398,16 @@ function App(): React.JSX.Element {
|
||||
|
||||
{/* ================= 主体内容区域 ================= */}
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
<main className="flex-1 overflow-y-auto bg-slate-50 p-6">
|
||||
<main className="flex-1 overflow-hidden bg-slate-50 p-6 h-full">
|
||||
{currentPage === 'home' && (
|
||||
<div className="max-w-4xl mx-auto mt-10 text-center animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<LayoutDashboard size={48} className="mx-auto text-blue-500 mb-4" />
|
||||
<h1 className="text-3xl font-bold text-slate-800 mb-4">欢迎使用 ERP Auto</h1>
|
||||
<p className="text-slate-500 text-lg max-w-2xl mx-auto">
|
||||
自动化处理 ERP 系统中的数据提取和清理任务。请使用上方导航栏选择您需要的功能模块。
|
||||
</p>
|
||||
<div className="h-full overflow-auto">
|
||||
<div className="max-w-4xl mx-auto mt-10 text-center animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<LayoutDashboard size={48} className="mx-auto text-blue-500 mb-4" />
|
||||
<h1 className="text-3xl font-bold text-slate-800 mb-4">欢迎使用 ERP Auto</h1>
|
||||
<p className="text-slate-500 text-lg max-w-2xl mx-auto">
|
||||
自动化处理 ERP 系统中的数据提取和清理任务。请使用上方导航栏选择您需要的功能模块。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{currentPage === 'extractor' && <ExtractorPage />}
|
||||
@@ -393,6 +415,9 @@ function App(): React.JSX.Element {
|
||||
{currentPage === 'settings' && <SettingsPage />}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{/* Toast Notifications */}
|
||||
<Toast />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
401
src/renderer/src/components/ExecutionReportDialog.tsx
Normal file
401
src/renderer/src/components/ExecutionReportDialog.tsx
Normal file
@@ -0,0 +1,401 @@
|
||||
/**
|
||||
* Execution Report Dialog - Shows execution progress and results after cleaner runs
|
||||
*
|
||||
* Displays:
|
||||
* - Progress bar during execution
|
||||
* - Orders processed count, Materials deleted/skipped count after completion
|
||||
* - Error list (if any)
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { CheckCircle, XCircle, SkipForward, Package, Loader2 } from 'lucide-react'
|
||||
import { Modal } from './ui/Modal'
|
||||
|
||||
interface CleanerProgress {
|
||||
message: string
|
||||
progress: number
|
||||
currentOrderIndex: number
|
||||
totalOrders: number
|
||||
currentMaterialIndex: number
|
||||
totalMaterialsInOrder: number
|
||||
currentOrderNumber?: string
|
||||
phase: 'login' | 'processing' | 'complete'
|
||||
}
|
||||
|
||||
interface ExecutionReportDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
ordersProcessed?: number
|
||||
materialsDeleted?: number
|
||||
materialsSkipped?: number
|
||||
errors?: string[]
|
||||
dryRun?: boolean
|
||||
isExecuting?: boolean
|
||||
progress?: CleanerProgress | null
|
||||
startTime?: number | null
|
||||
triggerRef?: React.RefObject<HTMLElement | null>
|
||||
// Retry-related props
|
||||
retriedOrders?: number
|
||||
successfulRetries?: number
|
||||
}
|
||||
|
||||
export const ExecutionReportDialog: React.FC<ExecutionReportDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
ordersProcessed = 0,
|
||||
materialsDeleted = 0,
|
||||
materialsSkipped = 0,
|
||||
errors = [],
|
||||
dryRun = false,
|
||||
isExecuting = false,
|
||||
progress = null,
|
||||
startTime = null,
|
||||
triggerRef,
|
||||
retriedOrders = 0,
|
||||
successfulRetries = 0
|
||||
}) => {
|
||||
const [now, setNow] = React.useState(() => Date.now())
|
||||
|
||||
const hasErrors = errors.length > 0
|
||||
const hasRetries = retriedOrders > 0
|
||||
const showProgress = isExecuting && progress
|
||||
const isProgressing = !!showProgress
|
||||
|
||||
// Update timer during progress
|
||||
React.useEffect(() => {
|
||||
if (!showProgress || !startTime) return
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setNow(Date.now())
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [showProgress, startTime])
|
||||
|
||||
// Update time when execution completes
|
||||
React.useEffect(() => {
|
||||
if (showProgress === false && startTime && isExecuting === false) {
|
||||
setNow(Date.now())
|
||||
}
|
||||
}, [showProgress, isExecuting, startTime])
|
||||
|
||||
const elapsedTime = React.useMemo(() => {
|
||||
if (!startTime) return null
|
||||
|
||||
const elapsedMs = now - startTime
|
||||
const elapsedSeconds = Math.floor(elapsedMs / 1000)
|
||||
const minutes = Math.floor(elapsedSeconds / 60)
|
||||
const seconds = elapsedSeconds % 60
|
||||
|
||||
return {
|
||||
totalSeconds: elapsedSeconds,
|
||||
formatted: minutes > 0 ? `${minutes}分${seconds}秒` : `${seconds}秒`
|
||||
}
|
||||
}, [startTime, now])
|
||||
|
||||
const estimatedTime = React.useMemo(() => {
|
||||
if (!showProgress || !startTime || !progress) return null
|
||||
|
||||
const currentProgress = progress.progress
|
||||
if (currentProgress < 5) return null
|
||||
|
||||
const elapsedMs = now - startTime
|
||||
const elapsedMinutes = elapsedMs / 60000
|
||||
|
||||
const totalEstimatedMinutes = elapsedMinutes / (currentProgress / 100)
|
||||
const remainingMinutes = Math.max(0, totalEstimatedMinutes - elapsedMinutes)
|
||||
const remainingRounded = Math.round(remainingMinutes)
|
||||
|
||||
const endTime = new Date(now + remainingMinutes * 60000)
|
||||
const hours = endTime.getHours()
|
||||
const minutes = endTime.getMinutes()
|
||||
const seconds = endTime.getSeconds()
|
||||
const period = hours >= 12 ? '下午' : '上午'
|
||||
const displayHours = hours % 12 || 12
|
||||
const formattedTime = `${period} ${displayHours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
|
||||
|
||||
return {
|
||||
remainingMinutes: remainingRounded,
|
||||
formattedTime
|
||||
}
|
||||
}, [showProgress, startTime, progress, now])
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title={
|
||||
isProgressing
|
||||
? '正在执行清理...'
|
||||
: dryRun
|
||||
? '预览执行报告'
|
||||
: hasErrors
|
||||
? '执行完成 (有错误)'
|
||||
: '执行完成'
|
||||
}
|
||||
size={isProgressing ? 'lg' : 'md'}
|
||||
showCloseButton={!isExecuting}
|
||||
triggerRef={triggerRef}
|
||||
isAlertDialog={isProgressing}
|
||||
disableEscapeKey={isProgressing}
|
||||
disableBackdropClick={isProgressing}
|
||||
ariaDescribedBy={isProgressing ? 'execution-dialog-progress-desc' : undefined}
|
||||
initialFocusSelector={!isProgressing ? '.btn-report-close' : undefined}
|
||||
>
|
||||
{isProgressing ? (
|
||||
// Progress View
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="relative">
|
||||
<Loader2 className="w-12 h-12 text-blue-500 animate-spin" />
|
||||
</div>
|
||||
</div>
|
||||
<p
|
||||
id="execution-dialog-progress-desc"
|
||||
className="text-sm text-gray-600 mb-4"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{progress?.message || '处理中...'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
// Result View
|
||||
<div className="text-center mb-4">
|
||||
<div className="flex justify-center mb-4">
|
||||
{dryRun ? (
|
||||
<Package className="w-12 h-12 text-amber-500" />
|
||||
) : hasErrors ? (
|
||||
<XCircle className="w-12 h-12 text-red-500" />
|
||||
) : (
|
||||
<CheckCircle className="w-12 h-12 text-green-500" />
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-600">
|
||||
{dryRun
|
||||
? '预览模式 - 未实际删除数据'
|
||||
: hasErrors
|
||||
? '部分操作未能完成,请查看下方错误信息'
|
||||
: '所有操作已成功完成'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isProgressing ? (
|
||||
// Progress View Content
|
||||
<div className="space-y-4">
|
||||
<div className="progress-bar-container w-full h-6 bg-gradient-to-r from-blue-50 to-sky-100 rounded-full overflow-hidden border border-blue-200 relative">
|
||||
<div
|
||||
className="progress-bar-fill h-full bg-gradient-to-r from-blue-500 to-blue-700 transition-all duration-300 relative overflow-hidden"
|
||||
style={{ width: `${progress?.progress || 0}%` }}
|
||||
>
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent animate-shimmer" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-around py-4 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-xs text-gray-600">订单进度</span>
|
||||
<span className="text-lg font-semibold text-blue-600">
|
||||
{Math.min(progress!.currentOrderIndex, progress!.totalOrders)} /{' '}
|
||||
{progress!.totalOrders}
|
||||
</span>
|
||||
</div>
|
||||
{progress!.totalMaterialsInOrder > 0 && (
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-xs text-gray-600">物料进度</span>
|
||||
<span className="text-lg font-semibold text-blue-600">
|
||||
{progress!.currentMaterialIndex} / {progress!.totalMaterialsInOrder}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-xs text-gray-600">总进度</span>
|
||||
<span className="text-lg font-semibold text-blue-600">
|
||||
{Math.round(progress?.progress || 0)}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{progress?.currentOrderNumber && (
|
||||
<div className="flex items-center justify-center gap-2 p-3 bg-blue-50 rounded-lg border border-blue-200">
|
||||
<Package size={14} className="text-blue-600" />
|
||||
<span className="text-sm text-gray-600">当前订单:</span>
|
||||
<span className="text-sm font-medium text-gray-900 font-mono">
|
||||
{progress.currentOrderNumber}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{elapsedTime && (
|
||||
<div className="flex flex-col items-center gap-2 p-3 bg-blue-50 rounded-lg border border-blue-200 mb-2">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-gray-600">已运行</span>
|
||||
<span className="font-semibold text-blue-600">{elapsedTime.formatted}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{estimatedTime && (
|
||||
<div className="flex flex-col items-center gap-2 p-3 bg-green-50 rounded-lg border border-green-200">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-gray-600">预估还要</span>
|
||||
<span className="font-semibold text-green-600">
|
||||
{estimatedTime.remainingMinutes} 分钟
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-gray-600">将会在</span>
|
||||
<span className="font-semibold text-green-600">{estimatedTime.formattedTime}</span>
|
||||
<span className="text-gray-600">执行完毕</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Result View Content
|
||||
<>
|
||||
<div className="grid grid-cols-3 gap-3 mb-4">
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
|
||||
<div className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0">
|
||||
<Package size={20} className="text-blue-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs text-gray-600">处理订单</div>
|
||||
<div className="text-xl font-semibold text-gray-900">{ordersProcessed}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
|
||||
<div className="w-9 h-9 rounded-lg bg-green-50 flex items-center justify-center flex-shrink-0">
|
||||
<CheckCircle size={20} className="text-green-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs text-gray-600">{dryRun ? '拟删除物料' : '删除物料'}</div>
|
||||
<div className="text-xl font-semibold text-gray-900">{materialsDeleted}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
|
||||
<div className="w-9 h-9 rounded-lg bg-amber-50 flex items-center justify-center flex-shrink-0">
|
||||
<SkipForward size={20} className="text-amber-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs text-gray-600">跳过物料</div>
|
||||
<div className="text-xl font-semibold text-gray-900">{materialsSkipped}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasErrors && (
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200 col-span-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-red-50 flex items-center justify-center flex-shrink-0">
|
||||
<XCircle size={20} className="text-red-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs text-gray-600">错误数量</div>
|
||||
<div className="text-xl font-semibold text-red-600">{errors.length}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasRetries && (
|
||||
<>
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
|
||||
<div className="w-9 h-9 rounded-lg bg-purple-50 flex items-center justify-center flex-shrink-0">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="text-purple-600"
|
||||
>
|
||||
<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
|
||||
<path d="M3 3v5h5" />
|
||||
<path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />
|
||||
<path d="M16 21h5v-5" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs text-gray-600">重试订单</div>
|
||||
<div className="text-xl font-semibold text-gray-900">{retriedOrders}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
|
||||
<div className="w-9 h-9 rounded-lg bg-emerald-50 flex items-center justify-center flex-shrink-0">
|
||||
<CheckCircle size={20} className="text-emerald-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs text-gray-600">成功重试</div>
|
||||
<div className="text-xl font-semibold text-gray-900">{successfulRetries}</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{elapsedTime && (
|
||||
<div className="flex items-center justify-center gap-2 p-3 bg-blue-50 rounded-lg border border-blue-200 text-blue-700 text-sm mb-3">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<polyline points="12 6 12 12 16 14" />
|
||||
</svg>
|
||||
<span>
|
||||
总耗时:<span className="font-semibold">{elapsedTime.formatted}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasErrors && (
|
||||
<div className="mt-4 pt-4 border-t border-gray-200">
|
||||
<div className="text-sm font-semibold text-red-600 mb-2">错误详情</div>
|
||||
<div className="flex flex-col gap-2 max-h-40 overflow-y-auto">
|
||||
{errors.map((error, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-start gap-2 p-2 bg-red-50 rounded border border-red-200"
|
||||
>
|
||||
<XCircle size={14} className="text-red-600 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-sm text-gray-900 break-words">{error}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasErrors && !dryRun && (
|
||||
<div className="flex items-center justify-center gap-2 p-3 bg-green-50 rounded-lg border border-green-200 text-green-700 text-sm">
|
||||
<CheckCircle size={16} className="flex-shrink-0" />
|
||||
<span>操作已成功完成,数据已同步到 ERP 系统</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasErrors && dryRun && (
|
||||
<div className="flex items-center justify-center gap-2 p-3 bg-amber-50 rounded-lg border border-amber-200 text-amber-700 text-sm">
|
||||
<Package size={16} className="flex-shrink-0" />
|
||||
<span>预览模式结束,数据未实际修改。确认无误后可正式执行。</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default ExecutionReportDialog
|
||||
@@ -7,7 +7,8 @@
|
||||
* - Enter key to submit
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react'
|
||||
import React, { useState, useRef } from 'react'
|
||||
import { Modal } from './ui/Modal'
|
||||
|
||||
interface LoginDialogProps {
|
||||
isOpen: boolean
|
||||
@@ -27,24 +28,27 @@ export const LoginDialog: React.FC<LoginDialogProps> = ({
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [isLoggingIn, setIsLoggingIn] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState('')
|
||||
const usernameInputRef = useRef<HTMLInputElement>(null)
|
||||
const errorRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Focus on username input when dialog opens
|
||||
useEffect(() => {
|
||||
if (isOpen && usernameInputRef.current) {
|
||||
usernameInputRef.current.focus()
|
||||
}
|
||||
}, [isOpen])
|
||||
// Display error message with aria-live
|
||||
const showError = (message: string): void => {
|
||||
setErrorMessage(message)
|
||||
onError(message)
|
||||
}
|
||||
|
||||
const handleLogin = async (): Promise<void> => {
|
||||
setErrorMessage('')
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!username.trim()) {
|
||||
onError('请输入用户名')
|
||||
showError('请输入用户名')
|
||||
usernameInputRef.current?.focus()
|
||||
return
|
||||
}
|
||||
|
||||
if (!password.trim()) {
|
||||
onError('请输入密码')
|
||||
showError('请输入密码')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -53,36 +57,51 @@ export const LoginDialog: React.FC<LoginDialogProps> = ({
|
||||
setIsLoggingIn(false)
|
||||
|
||||
if (!success) {
|
||||
onError('用户名或密码错误')
|
||||
showError('用户名或密码错误')
|
||||
setPassword('')
|
||||
}
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
const handleKeyDown = (e: React.KeyboardEvent): void => {
|
||||
if (e.key === 'Enter') {
|
||||
handleLogin()
|
||||
} else if (e.key === 'Escape') {
|
||||
onCancel()
|
||||
}
|
||||
}
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="login-overlay" onKeyDown={handleKeyDown}>
|
||||
<div className="login-dialog">
|
||||
<div className="login-header">
|
||||
<h2 className="login-title">请登录</h2>
|
||||
<p className="computer-name">当前计算机:{computerName}</p>
|
||||
</div>
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onCancel}
|
||||
title="请登录"
|
||||
size="md"
|
||||
showCloseButton={true}
|
||||
initialFocusSelector='input[type="text"]'
|
||||
ariaDescribedBy={errorMessage ? 'login-dialog-error' : undefined}
|
||||
>
|
||||
<div onKeyDown={handleKeyDown}>
|
||||
{/* Error message area with aria-live for screen readers */}
|
||||
{errorMessage && (
|
||||
<div
|
||||
ref={errorRef}
|
||||
id="login-dialog-error"
|
||||
className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md text-red-700 text-sm"
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{errorMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="login-body">
|
||||
<div className="form-group">
|
||||
<label className="form-label text-slate-700">用户名:</label>
|
||||
<div className="space-y-4">
|
||||
<div className="text-sm text-gray-600">当前计算机:{computerName}</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-slate-700 mb-1">用户名:</label>
|
||||
<input
|
||||
ref={usernameInputRef}
|
||||
type="text"
|
||||
className="form-input border border-slate-300 rounded-md p-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
className="border border-slate-300 rounded-md p-2 w-full text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="请输入用户名"
|
||||
@@ -90,11 +109,11 @@ export const LoginDialog: React.FC<LoginDialogProps> = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group mt-4">
|
||||
<label className="form-label text-slate-700">密码:</label>
|
||||
<div>
|
||||
<label className="block text-sm text-slate-700 mb-1">密码:</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-input border border-slate-300 rounded-md p-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
className="border border-slate-300 rounded-md p-2 w-full text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="请输入密码"
|
||||
@@ -103,16 +122,16 @@ export const LoginDialog: React.FC<LoginDialogProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="login-footer mt-6 flex justify-end gap-3">
|
||||
<div className="mt-6 flex justify-end gap-3">
|
||||
<button
|
||||
className="btn btn-secondary px-4 py-2 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-700 transition-colors"
|
||||
className="px-4 py-2 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-700 transition-colors"
|
||||
onClick={onCancel}
|
||||
disabled={isLoggingIn}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-primary px-4 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white transition-colors disabled:opacity-50"
|
||||
className="px-4 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white transition-colors disabled:opacity-50"
|
||||
onClick={handleLogin}
|
||||
disabled={isLoggingIn}
|
||||
>
|
||||
@@ -120,145 +139,9 @@ export const LoginDialog: React.FC<LoginDialogProps> = ({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="login-version">v1.0</div>
|
||||
<div className="mt-4 text-xs text-gray-400 text-right">v1.0</div>
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
.login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.login-dialog {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
||||
width: 400px;
|
||||
padding: 24px;
|
||||
animation: slideDown 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slideDown {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.login-header {
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.login-title {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.computer-name {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.login-body {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
margin-bottom: 6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-input {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
transition: border-color 0.3s, box-shadow 0.3s;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.form-input:focus {
|
||||
outline: none;
|
||||
border-color: #1890ff;
|
||||
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
|
||||
}
|
||||
|
||||
.form-input:disabled {
|
||||
background: #f5f5f5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.login-footer {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 10px 24px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #1890ff;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background: #40a9ff;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #f5f5f5;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
background: #e8e8e8;
|
||||
}
|
||||
|
||||
.login-version {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
margin-top: 16px;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { Plus, Trash2, Save, RotateCcw, Users } from 'lucide-react'
|
||||
import { Modal } from './ui/Modal'
|
||||
import { showSuccess, showError, showInfo } from '../stores/useAppStore'
|
||||
import { useConfirmDialog } from './ui/ConfirmDialog'
|
||||
import { ConfirmDialog } from './ui/ConfirmDialog'
|
||||
|
||||
interface MaterialTypeRecord {
|
||||
id?: number
|
||||
@@ -27,13 +30,15 @@ interface MaterialTypeManagementDialogProps {
|
||||
onClose: () => void
|
||||
isAdmin: boolean
|
||||
currentUsername: string
|
||||
triggerRef?: React.RefObject<HTMLButtonElement | null>
|
||||
}
|
||||
|
||||
export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
isAdmin,
|
||||
currentUsername
|
||||
currentUsername,
|
||||
triggerRef
|
||||
}) => {
|
||||
const [rows, setRows] = useState<RowState[]>([])
|
||||
const [managers, setManagers] = useState<string[]>([])
|
||||
@@ -47,6 +52,9 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
const tableRef = useRef<HTMLTableElement>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Confirmation dialog hook
|
||||
const { confirm, dialog: confirmDialog } = useConfirmDialog()
|
||||
|
||||
// Calculate pending changes count
|
||||
const pendingCount = rows.filter(
|
||||
(r) => r.state === 'new' || r.state === 'modified' || r.state === 'deleted'
|
||||
@@ -115,31 +123,8 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
return rows.filter((row) => selectedManagers.has(row.record.managerName) || row.state === 'new')
|
||||
}, [rows, isAdmin, selectedManagers])
|
||||
|
||||
// Handle keyboard events
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent) => {
|
||||
if (editingCell) {
|
||||
if (event.key === 'Enter') {
|
||||
saveEdit()
|
||||
} else if (event.key === 'Escape') {
|
||||
cancelEdit()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key === 'Insert') {
|
||||
event.preventDefault()
|
||||
insertNewRow()
|
||||
} else if (event.key === 'Delete' && selectedRowIndex !== null) {
|
||||
event.preventDefault()
|
||||
deleteRow(selectedRowIndex)
|
||||
}
|
||||
},
|
||||
[editingCell, selectedRowIndex]
|
||||
)
|
||||
|
||||
// Insert new row
|
||||
const insertNewRow = () => {
|
||||
const insertNewRow = useCallback(() => {
|
||||
const newRow: RowState = {
|
||||
record: {
|
||||
materialName: '',
|
||||
@@ -147,17 +132,20 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
},
|
||||
state: 'new'
|
||||
}
|
||||
setRows((prev) => [...prev, newRow])
|
||||
// Start editing the material name cell
|
||||
const newIndex = rows.length
|
||||
setTimeout(() => {
|
||||
setEditingCell({ rowIndex: newIndex, field: 'materialName' })
|
||||
setEditValue('')
|
||||
}, 0)
|
||||
}
|
||||
|
||||
// 在 setRows 回调中计算索引并设置编辑状态
|
||||
setRows((prev) => {
|
||||
const newIndex = prev.length
|
||||
setTimeout(() => {
|
||||
setEditingCell({ rowIndex: newIndex, field: 'materialName' })
|
||||
setEditValue('')
|
||||
}, 0)
|
||||
return [...prev, newRow]
|
||||
})
|
||||
}, [isAdmin, currentUsername])
|
||||
|
||||
// Delete row
|
||||
const deleteRow = (index: number) => {
|
||||
const deleteRow = useCallback((index: number) => {
|
||||
setRows((prev) => {
|
||||
const newRows = [...prev]
|
||||
const row = newRows[index]
|
||||
@@ -171,19 +159,22 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
return newRows
|
||||
})
|
||||
setSelectedRowIndex(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Start editing a cell
|
||||
const startEdit = (rowIndex: number, field: string) => {
|
||||
const row = rows[rowIndex]
|
||||
if (row.state === 'deleted') return
|
||||
const startEdit = useCallback(
|
||||
(rowIndex: number, field: string) => {
|
||||
const row = rows[rowIndex]
|
||||
if (row.state === 'deleted') return
|
||||
|
||||
setEditingCell({ rowIndex, field })
|
||||
setEditValue(row.record[field as keyof MaterialTypeRecord] as string)
|
||||
}
|
||||
setEditingCell({ rowIndex, field })
|
||||
setEditValue(row.record[field as keyof MaterialTypeRecord] as string)
|
||||
},
|
||||
[rows]
|
||||
)
|
||||
|
||||
// Save edit
|
||||
const saveEdit = () => {
|
||||
const saveEdit = useCallback(() => {
|
||||
if (!editingCell) return
|
||||
|
||||
const { rowIndex, field } = editingCell
|
||||
@@ -206,13 +197,36 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
|
||||
setEditingCell(null)
|
||||
setEditValue('')
|
||||
}
|
||||
}, [editingCell, editValue])
|
||||
|
||||
// Cancel edit
|
||||
const cancelEdit = () => {
|
||||
const cancelEdit = useCallback(() => {
|
||||
setEditingCell(null)
|
||||
setEditValue('')
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Handle keyboard events
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent) => {
|
||||
if (editingCell) {
|
||||
if (event.key === 'Enter') {
|
||||
saveEdit()
|
||||
} else if (event.key === 'Escape') {
|
||||
cancelEdit()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key === 'Insert') {
|
||||
event.preventDefault()
|
||||
insertNewRow()
|
||||
} else if (event.key === 'Delete' && selectedRowIndex !== null) {
|
||||
event.preventDefault()
|
||||
deleteRow(selectedRowIndex)
|
||||
}
|
||||
},
|
||||
[editingCell, selectedRowIndex, insertNewRow, deleteRow, saveEdit, cancelEdit]
|
||||
)
|
||||
|
||||
// Save all changes
|
||||
const handleSave = async () => {
|
||||
@@ -231,7 +245,7 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
}
|
||||
|
||||
if (toInsert.length === 0 && toUpdate.length === 0 && toDelete.length === 0) {
|
||||
alert('没有需要保存的更改')
|
||||
showInfo('没有需要保存的更改')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -240,7 +254,12 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
if (toUpdate.length > 0) confirmParts.push(`更新 ${toUpdate.length} 条记录`)
|
||||
if (toDelete.length > 0) confirmParts.push(`删除 ${toDelete.length} 条记录`)
|
||||
|
||||
if (!window.confirm(`确认以下操作?\n\n${confirmParts.join('\n')}`)) return
|
||||
const confirmed = await confirm({
|
||||
title: '确认操作',
|
||||
message: `确认以下操作?\n\n${confirmParts.join('\n')}`,
|
||||
variant: 'warning'
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
@@ -249,33 +268,47 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
toUpdate,
|
||||
toDelete
|
||||
})
|
||||
const payload = result.success
|
||||
? (result.data as { stats?: { success?: number; failed?: number } } | undefined)
|
||||
: undefined
|
||||
|
||||
if (result.success) {
|
||||
alert(
|
||||
`保存完成!\n成功:${result.stats?.success || 0} 条\n失败:${result.stats?.failed || 0} 条`
|
||||
showSuccess(
|
||||
`保存完成!\n成功:${payload?.stats?.success || 0} 条\n失败:${payload?.stats?.failed || 0} 条`
|
||||
)
|
||||
await loadData()
|
||||
} else {
|
||||
alert(`保存失败:${result.error || '未知错误'}`)
|
||||
showError(`保存失败:${result.error || '未知错误'}`)
|
||||
}
|
||||
} catch (error) {
|
||||
alert(`保存失败:${error instanceof Error ? error.message : '未知错误'}`)
|
||||
showError(`保存失败:${error instanceof Error ? error.message : '未知错误'}`)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Reset changes
|
||||
const handleReset = () => {
|
||||
const handleReset = async () => {
|
||||
if (pendingCount === 0) return
|
||||
if (!window.confirm('确定要放弃所有未保存的更改吗?')) return
|
||||
loadData()
|
||||
const confirmed = await confirm({
|
||||
title: '确认重置',
|
||||
message: '确定要放弃所有未保存的更改吗?',
|
||||
variant: 'warning'
|
||||
})
|
||||
if (confirmed) {
|
||||
loadData()
|
||||
}
|
||||
}
|
||||
|
||||
// Handle close with unsaved changes warning
|
||||
const handleClose = () => {
|
||||
const handleClose = async () => {
|
||||
if (pendingCount > 0) {
|
||||
if (!window.confirm('有未保存的更改,确定要关闭吗?')) return
|
||||
const confirmed = await confirm({
|
||||
title: '确认关闭',
|
||||
message: '有未保存的更改,确定要关闭吗?',
|
||||
variant: 'warning'
|
||||
})
|
||||
if (!confirmed) return
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
@@ -295,7 +328,13 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={handleClose} title="物料类型管理" size="2xl">
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={handleClose}
|
||||
title="物料类型管理"
|
||||
size="2xl"
|
||||
triggerRef={triggerRef}
|
||||
>
|
||||
<div onKeyDown={handleKeyDown}>
|
||||
{/* Manager filter (admin only) */}
|
||||
{isAdmin && (
|
||||
@@ -516,6 +555,9 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
|
||||
<span>共 {filteredRows.filter((r) => r.state !== 'deleted').length} 条记录</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Confirmation Dialog */}
|
||||
{confirmDialog && <ConfirmDialog {...confirmDialog} />}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
|
||||
interface OrderNumberInputProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
label?: string
|
||||
enableFormatStats?: boolean // Whether to show format statistics
|
||||
enableFormatStats?: boolean
|
||||
disabled?: boolean
|
||||
showReset?: boolean
|
||||
onReset?: () => void
|
||||
}
|
||||
|
||||
interface FormatStats {
|
||||
@@ -14,24 +18,20 @@ interface FormatStats {
|
||||
unknownCount: number
|
||||
}
|
||||
|
||||
// Regular expression patterns for order number recognition
|
||||
const ORDER_PATTERNS = {
|
||||
// productionID: 2 digits + 1 letter + serial number (1+)
|
||||
PRODUCTION_ID: /^\d{2}[A-Za-z]\d+$/,
|
||||
// 生产订单号:SC + 14 digits
|
||||
ORDER_NUMBER: /^SC\d{14}$/
|
||||
}
|
||||
|
||||
/**
|
||||
* OrderNumberInput - A textarea component for entering line-separated order numbers
|
||||
* Supports automatic recognition of productionID and 生产订单号 formats
|
||||
*/
|
||||
export const OrderNumberInput: React.FC<OrderNumberInputProps> = ({
|
||||
const OrderNumberInput: React.FC<OrderNumberInputProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = '请输入订单号,每行一个\n支持两种格式:\n- productionID: 22A1, 22A123\n- 生产订单号:SC70202602120085',
|
||||
placeholder = '每行输入一个订单号\n支持格式:\n- 总排号: 22A1, 22A123\n- 生产订单号: SC70202602120085',
|
||||
label = '订单号列表',
|
||||
enableFormatStats = true
|
||||
enableFormatStats = true,
|
||||
disabled = false,
|
||||
showReset = false,
|
||||
onReset
|
||||
}) => {
|
||||
const [count, setCount] = useState(0)
|
||||
const [stats, setStats] = useState<FormatStats>({
|
||||
@@ -43,22 +43,15 @@ export const OrderNumberInput: React.FC<OrderNumberInputProps> = ({
|
||||
const recognizeType = (input: string): 'productionId' | 'orderNumber' | 'unknown' => {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) return 'unknown'
|
||||
|
||||
if (ORDER_PATTERNS.ORDER_NUMBER.test(trimmed)) {
|
||||
return 'orderNumber'
|
||||
}
|
||||
if (ORDER_PATTERNS.PRODUCTION_ID.test(trimmed)) {
|
||||
return 'productionId'
|
||||
}
|
||||
if (ORDER_PATTERNS.ORDER_NUMBER.test(trimmed)) return 'orderNumber'
|
||||
if (ORDER_PATTERNS.PRODUCTION_ID.test(trimmed)) return 'productionId'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Count non-empty lines and categorize by format
|
||||
const lines = value.split('\n').filter((line) => line.trim().length > 0)
|
||||
setCount(lines.length)
|
||||
|
||||
// Calculate format statistics
|
||||
const newStats: FormatStats = {
|
||||
productionIdCount: 0,
|
||||
orderNumberCount: 0,
|
||||
@@ -67,13 +60,9 @@ export const OrderNumberInput: React.FC<OrderNumberInputProps> = ({
|
||||
|
||||
for (const line of lines) {
|
||||
const type = recognizeType(line)
|
||||
if (type === 'productionId') {
|
||||
newStats.productionIdCount++
|
||||
} else if (type === 'orderNumber') {
|
||||
newStats.orderNumberCount++
|
||||
} else {
|
||||
newStats.unknownCount++
|
||||
}
|
||||
if (type === 'productionId') newStats.productionIdCount++
|
||||
else if (type === 'orderNumber') newStats.orderNumberCount++
|
||||
else newStats.unknownCount++
|
||||
}
|
||||
|
||||
setStats(newStats)
|
||||
@@ -84,96 +73,55 @@ export const OrderNumberInput: React.FC<OrderNumberInputProps> = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="order-number-input">
|
||||
<div className="input-header">
|
||||
<label>{label}</label>
|
||||
<div className="stats-wrapper">
|
||||
<span className="count-badge">{count} 个</span>
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label className="text-sm font-medium text-slate-700">{label}</label>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="bg-blue-50 text-blue-600 px-2 py-0.5 rounded-full text-xs font-medium">
|
||||
{count} 个
|
||||
</span>
|
||||
{enableFormatStats && stats.productionIdCount > 0 && (
|
||||
<span className="stat-badge production-id">{stats.productionIdCount} 总排号</span>
|
||||
<span className="bg-emerald-50 text-emerald-600 px-2 py-0.5 rounded-full text-xs font-medium">
|
||||
{stats.productionIdCount} 总排号
|
||||
</span>
|
||||
)}
|
||||
{enableFormatStats && stats.orderNumberCount > 0 && (
|
||||
<span className="stat-badge order-number">{stats.orderNumberCount} 订单号</span>
|
||||
<span className="bg-amber-50 text-amber-600 px-2 py-0.5 rounded-full text-xs font-medium">
|
||||
{stats.orderNumberCount} 订单号
|
||||
</span>
|
||||
)}
|
||||
{enableFormatStats && stats.unknownCount > 0 && (
|
||||
<span className="stat-badge unknown">{stats.unknownCount} 未知格式</span>
|
||||
<span className="bg-red-50 text-red-500 px-2 py-0.5 rounded-full text-xs font-medium">
|
||||
{stats.unknownCount} 未知
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
rows={10}
|
||||
className="order-textarea"
|
||||
disabled={disabled}
|
||||
className="flex-1 w-full border border-slate-300 rounded-lg p-3 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{
|
||||
userSelect: disabled ? 'none' : 'text',
|
||||
cursor: disabled ? 'not-allowed' : 'text'
|
||||
}}
|
||||
/>
|
||||
<style>{`
|
||||
.order-number-input {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.input-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.input-header label {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
}
|
||||
.stats-wrapper {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.count-badge {
|
||||
background: #e6f7ff;
|
||||
color: #1890ff;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.stat-badge {
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.stat-badge.production-id {
|
||||
background: #f6ffed;
|
||||
color: #52c41a;
|
||||
}
|
||||
.stat-badge.order-number {
|
||||
background: #fff7e6;
|
||||
color: #fa8c16;
|
||||
}
|
||||
.stat-badge.unknown {
|
||||
background: #fff1f0;
|
||||
color: #ff4d4f;
|
||||
}
|
||||
.order-textarea {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
font-family: 'Consolas', 'Monaco', monospace;
|
||||
resize: vertical;
|
||||
transition: border-color 0.3s;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.order-textarea:focus {
|
||||
outline: none;
|
||||
border-color: #1890ff;
|
||||
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
|
||||
}
|
||||
.order-textarea::placeholder {
|
||||
color: #bfbfbf;
|
||||
}
|
||||
`}</style>
|
||||
|
||||
{showReset && (
|
||||
<div className="flex items-center justify-end mt-2">
|
||||
<button
|
||||
onClick={onReset}
|
||||
disabled={disabled}
|
||||
className="flex items-center gap-1 px-3 py-1.5 text-xs text-slate-500 hover:text-red-600 hover:bg-red-50 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<X size={14} />
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
188
src/renderer/src/components/ReportViewerDialog.tsx
Normal file
188
src/renderer/src/components/ReportViewerDialog.tsx
Normal file
@@ -0,0 +1,188 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { X, FileText, Loader2 } from 'lucide-react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
|
||||
interface ReportMetadata {
|
||||
key: string
|
||||
filename: string
|
||||
username: string
|
||||
lastModified?: Date
|
||||
size?: number
|
||||
}
|
||||
|
||||
interface ReportViewerDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
isAdmin: boolean
|
||||
currentUsername: string
|
||||
}
|
||||
|
||||
export const ReportViewerDialog: React.FC<ReportViewerDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
isAdmin,
|
||||
currentUsername
|
||||
}) => {
|
||||
const [reports, setReports] = useState<ReportMetadata[]>([])
|
||||
const [selectedReportKey, setSelectedReportKey] = useState<string>('')
|
||||
const [reportContent, setReportContent] = useState<string>('')
|
||||
const [isLoadingList, setIsLoadingList] = useState<boolean>(false)
|
||||
const [isLoadingContent, setIsLoadingContent] = useState<boolean>(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadReports()
|
||||
} else {
|
||||
// Reset state when closed
|
||||
setReports([])
|
||||
setSelectedReportKey('')
|
||||
setReportContent('')
|
||||
setError(null)
|
||||
}
|
||||
}, [isOpen, isAdmin, currentUsername])
|
||||
|
||||
const loadReports = async () => {
|
||||
setIsLoadingList(true)
|
||||
setError(null)
|
||||
try {
|
||||
let result
|
||||
if (isAdmin) {
|
||||
result = await window.electron.report.listAll()
|
||||
} else {
|
||||
result = await window.electron.report.listByUser(currentUsername)
|
||||
}
|
||||
|
||||
if (result.success && result.data) {
|
||||
setReports(result.data)
|
||||
} else {
|
||||
setError(result.error || '无法获取报告列表')
|
||||
}
|
||||
} catch (err) {
|
||||
setError('获取报告列表时发生错误')
|
||||
} finally {
|
||||
setIsLoadingList(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReportChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const key = e.target.value
|
||||
setSelectedReportKey(key)
|
||||
|
||||
if (!key) {
|
||||
setReportContent('')
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoadingContent(true)
|
||||
setError(null)
|
||||
try {
|
||||
const result = await window.electron.report.download(key)
|
||||
if (result.success && result.data) {
|
||||
setReportContent(result.data)
|
||||
} else {
|
||||
setError(result.error || '无法获取报告内容')
|
||||
setReportContent('')
|
||||
}
|
||||
} catch (err) {
|
||||
setError('获取报告内容时发生错误')
|
||||
setReportContent('')
|
||||
} finally {
|
||||
setIsLoadingContent(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
// Format date to local string
|
||||
const formatDate = (dateString?: Date | string) => {
|
||||
if (!dateString) return '未知时间'
|
||||
const date = typeof dateString === 'string' ? new Date(dateString) : dateString
|
||||
return date.toLocaleString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/50 backdrop-blur-sm animate-in fade-in duration-200">
|
||||
<div className="bg-white rounded-2xl shadow-2xl w-[900px] max-w-[90vw] h-[80vh] flex flex-col border border-slate-200 overflow-hidden animate-in zoom-in-95 duration-200">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 bg-slate-50 flex-shrink-0">
|
||||
<div className="flex items-center gap-2 text-slate-800">
|
||||
<FileText size={20} className="text-blue-600" />
|
||||
<h2 className="text-lg font-semibold">执行报告浏览器</h2>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-slate-400 hover:text-slate-600 hover:bg-slate-200/50 p-1.5 rounded-lg transition-colors"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="px-6 py-4 border-b border-slate-200 bg-white flex-shrink-0">
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="text-sm font-medium text-slate-700 flex-shrink-0">选择报告:</label>
|
||||
<div className="relative flex-1 max-w-2xl">
|
||||
<select
|
||||
value={selectedReportKey}
|
||||
onChange={handleReportChange}
|
||||
disabled={isLoadingList}
|
||||
className="w-full appearance-none bg-slate-50 border border-slate-300 text-slate-700 py-2 pl-3 pr-10 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 disabled:opacity-50 text-sm"
|
||||
>
|
||||
<option value="">请选择要查看的报告...</option>
|
||||
{reports.map((report) => (
|
||||
<option key={report.key} value={report.key}>
|
||||
{isAdmin ? `[${report.username}] ` : ''}
|
||||
{report.filename} ({formatDate(report.lastModified)})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-slate-500">
|
||||
<svg
|
||||
className="fill-current h-4 w-4"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
{isLoadingList && <Loader2 size={16} className="text-blue-500 animate-spin" />}
|
||||
</div>
|
||||
{error && <div className="mt-3 text-sm text-red-600 flex items-center gap-1.5 bg-red-50 p-2 rounded">{error}</div>}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 bg-slate-50 overflow-hidden relative">
|
||||
{isLoadingContent ? (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center text-slate-500 bg-white/80 z-10">
|
||||
<Loader2 size={32} className="animate-spin text-blue-500 mb-4" />
|
||||
<p>正在加载报告内容...</p>
|
||||
</div>
|
||||
) : reportContent ? (
|
||||
<div className="h-full overflow-y-auto p-8">
|
||||
<div className="prose prose-slate prose-sm max-w-none bg-white p-8 rounded-xl shadow-sm border border-slate-200">
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]}>{reportContent}</ReactMarkdown>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center text-slate-400">
|
||||
<FileText size={48} className="mb-4 text-slate-300 opacity-50" />
|
||||
<p>请在上方选择一个报告进行浏览</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ReportViewerDialog
|
||||
@@ -7,7 +7,8 @@
|
||||
* - Return selected user info
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import React, { useState, useEffect, useRef } from 'react'
|
||||
import { Modal } from './ui/Modal'
|
||||
|
||||
export interface UserInfo {
|
||||
id: number
|
||||
@@ -22,6 +23,7 @@ interface UserSelectionDialogProps {
|
||||
currentUsername: string
|
||||
onSelectUser: (user: UserInfo) => void
|
||||
onCancel: () => void
|
||||
triggerRef?: React.RefObject<HTMLElement | null>
|
||||
}
|
||||
|
||||
export const UserSelectionDialog: React.FC<UserSelectionDialogProps> = ({
|
||||
@@ -29,9 +31,11 @@ export const UserSelectionDialog: React.FC<UserSelectionDialogProps> = ({
|
||||
users,
|
||||
currentUsername,
|
||||
onSelectUser,
|
||||
onCancel
|
||||
onCancel,
|
||||
triggerRef
|
||||
}) => {
|
||||
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
|
||||
const dialogRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Reset selection when dialog opens
|
||||
useEffect(() => {
|
||||
@@ -55,230 +59,85 @@ export const UserSelectionDialog: React.FC<UserSelectionDialogProps> = ({
|
||||
onSelectUser(user)
|
||||
}
|
||||
|
||||
const userTypeStyles: Record<string, string> = {
|
||||
Admin: 'bg-amber-50 text-amber-600',
|
||||
User: 'bg-blue-50 text-blue-600',
|
||||
Guest: 'bg-gray-100 text-gray-600'
|
||||
}
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="user-selection-overlay">
|
||||
<div className="user-selection-dialog">
|
||||
<div className="user-selection-header">
|
||||
<h2 className="user-selection-title">选择用户</h2>
|
||||
<p className="user-selection-hint">当前登录:{currentUsername}</p>
|
||||
</div>
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onCancel}
|
||||
title="选择用户"
|
||||
size="md"
|
||||
triggerRef={triggerRef}
|
||||
initialFocusSelector={users.length > 0 ? '.user-item:first-child' : undefined}
|
||||
ariaDescribedBy="user-selection-description"
|
||||
>
|
||||
<div ref={dialogRef} className="max-h-[60vh] flex flex-col">
|
||||
<div className="text-sm text-gray-600 mb-4">当前登录:{currentUsername}</div>
|
||||
<p id="user-selection-description" className="sr-only">
|
||||
从列表中选择一个用户,双击可直接确认选择
|
||||
</p>
|
||||
|
||||
<div className="user-selection-body">
|
||||
<div className="user-list">
|
||||
<div className="flex-1 overflow-y-auto mb-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
{users.map((user) => (
|
||||
<div
|
||||
key={user.id}
|
||||
className={`user-item ${selectedUserId === user.id ? 'selected' : ''}`}
|
||||
className={`user-item p-3 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-blue-500 hover:bg-green-50 ${
|
||||
selectedUserId === user.id ? 'border-blue-500 bg-blue-50' : ''
|
||||
}`}
|
||||
onClick={() => setSelectedUserId(user.id)}
|
||||
onDoubleClick={() => handleDoubleClick(user)}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
setSelectedUserId(user.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="user-item-content">
|
||||
<div className="user-item-row">
|
||||
<span className="user-name">{user.username}</span>
|
||||
<span className={`user-type user-type-${user.userType.toLowerCase()}`}>
|
||||
{user.userType}
|
||||
</span>
|
||||
</div>
|
||||
{user.createTime && (
|
||||
<div className="user-item-row">
|
||||
<span className="user-create-time">
|
||||
创建于:{new Date(user.createTime).toLocaleString('zh-CN')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-900">{user.username}</span>
|
||||
<span
|
||||
className={`text-xs px-2 py-1 rounded font-medium ${userTypeStyles[user.userType]}`}
|
||||
>
|
||||
{user.userType}
|
||||
</span>
|
||||
</div>
|
||||
{user.createTime && (
|
||||
<div className="mt-1 text-xs text-gray-500">
|
||||
创建于:{new Date(user.createTime).toLocaleString('zh-CN')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="user-selection-footer">
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={handleConfirm}
|
||||
disabled={selectedUserId === null}
|
||||
>
|
||||
确认
|
||||
</button>
|
||||
<button className="btn btn-secondary" onClick={onCancel}>
|
||||
取消
|
||||
</button>
|
||||
<div className="border-t border-gray-200 pt-4">
|
||||
<div className="flex justify-center gap-3">
|
||||
<button
|
||||
className="px-6 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
onClick={handleConfirm}
|
||||
disabled={selectedUserId === null}
|
||||
>
|
||||
确认
|
||||
</button>
|
||||
<button
|
||||
className="px-6 py-2 rounded-md bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium transition-colors"
|
||||
onClick={onCancel}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
<div className="text-center text-xs text-gray-500 mt-3">双击用户可直接选择</div>
|
||||
</div>
|
||||
|
||||
<div className="user-selection-hint-footer">双击用户可直接选择</div>
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
.user-selection-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.user-selection-dialog {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
||||
width: 450px;
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.user-selection-header {
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.user-selection-title {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.user-selection-hint {
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.user-selection-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px 24px;
|
||||
min-height: 200px;
|
||||
max-height: 400px;
|
||||
}
|
||||
|
||||
.user-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.user-item {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid #e8e8e8;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.user-item:hover {
|
||||
border-color: #1890ff;
|
||||
background: #f6ffed;
|
||||
}
|
||||
|
||||
.user-item.selected {
|
||||
border-color: #1890ff;
|
||||
background: #e6f7ff;
|
||||
}
|
||||
|
||||
.user-item-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.user-item-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.user-name {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.user-type {
|
||||
font-size: 12px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.user-type-admin {
|
||||
background: #fff7e6;
|
||||
color: #fa8c16;
|
||||
}
|
||||
|
||||
.user-type-user {
|
||||
background: #e6f7ff;
|
||||
color: #1890ff;
|
||||
}
|
||||
|
||||
.user-type-guest {
|
||||
background: #f5f5f5;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.user-create-time {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.user-selection-footer {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
padding: 16px 24px;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 10px 24px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #1890ff;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background: #40a9ff;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #f5f5f5;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
background: #e8e8e8;
|
||||
}
|
||||
|
||||
.user-selection-hint-footer {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
padding: 8px 16px;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
168
src/renderer/src/components/ui/ConfirmDialog.tsx
Normal file
168
src/renderer/src/components/ui/ConfirmDialog.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* ConfirmDialog Component
|
||||
*
|
||||
* A confirmation dialog component for displaying confirmation prompts.
|
||||
* Extends the Modal component with consistent styling and behavior.
|
||||
*/
|
||||
|
||||
import React, { useState, useCallback, useEffect } from 'react'
|
||||
import { AlertTriangle, Info, AlertCircle } from 'lucide-react'
|
||||
import { Modal } from './Modal'
|
||||
import { Button } from './Button'
|
||||
|
||||
export type ConfirmDialogVariant = 'danger' | 'warning' | 'info'
|
||||
|
||||
export interface ConfirmDialogProps {
|
||||
isOpen: boolean
|
||||
title: string
|
||||
message: string | React.ReactNode
|
||||
confirmText?: string
|
||||
cancelText?: string
|
||||
variant?: ConfirmDialogVariant
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
const variantStyles: Record<
|
||||
ConfirmDialogVariant,
|
||||
{ icon: React.ReactNode; iconColor: string; buttonVariant: 'danger' | 'primary' }
|
||||
> = {
|
||||
danger: {
|
||||
icon: <AlertCircle className="w-6 h-6" />,
|
||||
iconColor: 'text-red-500',
|
||||
buttonVariant: 'danger'
|
||||
},
|
||||
warning: {
|
||||
icon: <AlertTriangle className="w-6 h-6" />,
|
||||
iconColor: 'text-yellow-500',
|
||||
buttonVariant: 'primary'
|
||||
},
|
||||
info: {
|
||||
icon: <Info className="w-6 h-6" />,
|
||||
iconColor: 'text-blue-500',
|
||||
buttonVariant: 'primary'
|
||||
}
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
isOpen,
|
||||
title,
|
||||
message,
|
||||
confirmText = '确认',
|
||||
cancelText = '取消',
|
||||
variant = 'info',
|
||||
onConfirm,
|
||||
onCancel
|
||||
}: ConfirmDialogProps) {
|
||||
// Handle keyboard shortcuts
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
if (!isOpen) return
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
onConfirm()
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
onCancel()
|
||||
}
|
||||
},
|
||||
[isOpen, onConfirm, onCancel]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown)
|
||||
}
|
||||
}, [handleKeyDown])
|
||||
|
||||
const styles = variantStyles[variant]
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onCancel}
|
||||
title={title}
|
||||
size="md"
|
||||
showCloseButton={false}
|
||||
isAlertDialog={true}
|
||||
initialFocusSelector="[data-autofocus]"
|
||||
>
|
||||
<div className="flex items-start gap-4">
|
||||
{/* Icon */}
|
||||
<div className={`flex-shrink-0 ${styles.iconColor}`}>{styles.icon}</div>
|
||||
|
||||
{/* Message */}
|
||||
<div className="flex-1">
|
||||
{typeof message === 'string' ? (
|
||||
<p className="text-gray-700 whitespace-pre-wrap">{message}</p>
|
||||
) : (
|
||||
message
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Buttons */}
|
||||
<div className="flex justify-end gap-3 mt-6">
|
||||
<Button variant="secondary" onClick={onCancel}>
|
||||
{cancelText}
|
||||
</Button>
|
||||
<Button data-autofocus="true" variant={styles.buttonVariant} onClick={onConfirm}>
|
||||
{confirmText}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for using confirmation dialogs
|
||||
* Returns a confirm function that shows a dialog and resolves with user's choice
|
||||
*/
|
||||
export function useConfirmDialog() {
|
||||
const [config, setConfig] = useState<
|
||||
| (Omit<ConfirmDialogProps, 'isOpen' | 'onConfirm' | 'onCancel'> & {
|
||||
resolve: (value: boolean) => void
|
||||
})
|
||||
| null
|
||||
>(null)
|
||||
|
||||
const confirm = useCallback(
|
||||
(options: Omit<ConfirmDialogProps, 'isOpen' | 'onConfirm' | 'onCancel'>): Promise<boolean> => {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
setConfig({
|
||||
...options,
|
||||
resolve
|
||||
})
|
||||
})
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const handleConfirm = useCallback(() => {
|
||||
if (config) {
|
||||
config.resolve(true)
|
||||
setConfig(null)
|
||||
}
|
||||
}, [config])
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
if (config) {
|
||||
config.resolve(false)
|
||||
setConfig(null)
|
||||
}
|
||||
}, [config])
|
||||
|
||||
const dialog = config
|
||||
? {
|
||||
...config,
|
||||
isOpen: true,
|
||||
onConfirm: handleConfirm,
|
||||
onCancel: handleCancel
|
||||
}
|
||||
: null
|
||||
|
||||
return { confirm, dialog }
|
||||
}
|
||||
|
||||
export default ConfirmDialog
|
||||
63
src/renderer/src/components/ui/LogPanel.tsx
Normal file
63
src/renderer/src/components/ui/LogPanel.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import React, { useEffect, useRef } from 'react'
|
||||
import { Terminal } from 'lucide-react'
|
||||
import type { LogEntry, LogLevel } from '../../stores/extractorStore'
|
||||
|
||||
interface LogPanelProps {
|
||||
logs: LogEntry[]
|
||||
onClear: () => void
|
||||
}
|
||||
|
||||
const getLogColor = (level: LogLevel): string => {
|
||||
switch (level) {
|
||||
case 'error':
|
||||
return 'text-red-400'
|
||||
case 'warning':
|
||||
return 'text-amber-400'
|
||||
case 'success':
|
||||
return 'text-emerald-400'
|
||||
case 'system':
|
||||
return 'text-blue-400'
|
||||
default:
|
||||
return 'text-slate-400'
|
||||
}
|
||||
}
|
||||
|
||||
const LogPanel: React.FC<LogPanelProps> = ({ logs, onClear }) => {
|
||||
const logsEndRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
logsEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}, [logs])
|
||||
|
||||
return (
|
||||
<div className="bg-slate-900 rounded-xl shadow-lg border border-slate-700 overflow-hidden flex flex-col min-h-[300px] flex-1">
|
||||
<div className="bg-slate-800 px-4 py-2 flex items-center justify-between border-b border-slate-700 flex-shrink-0">
|
||||
<div className="flex items-center gap-2 text-slate-400 text-sm">
|
||||
<Terminal size={16} />
|
||||
<span>执行日志</span>
|
||||
</div>
|
||||
<button
|
||||
className="text-xs text-slate-400 hover:text-white transition-colors"
|
||||
onClick={onClear}
|
||||
>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 p-4 font-mono text-sm overflow-y-auto leading-relaxed">
|
||||
{logs.length === 0 ? (
|
||||
<div className="text-slate-500 text-center py-8">等待执行...</div>
|
||||
) : (
|
||||
logs.map((log, index) => (
|
||||
<div key={index} className={getLogColor(log.level)}>
|
||||
<span className="text-slate-600">[{log.timestamp}]</span>{' '}
|
||||
<span className="text-slate-500">[{log.level.toUpperCase()}]</span> {log.message}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<div ref={logsEndRef} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LogPanel
|
||||
@@ -4,8 +4,10 @@
|
||||
* A reusable modal dialog component.
|
||||
*/
|
||||
|
||||
import React, { useEffect, useCallback } from 'react'
|
||||
import React, { useRef, useMemo, useState } from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
import FocusLock from 'react-focus-lock'
|
||||
import { useDialogFocus } from '../../hooks/useDialogFocus'
|
||||
|
||||
interface ModalProps {
|
||||
isOpen: boolean
|
||||
@@ -14,6 +16,20 @@ interface ModalProps {
|
||||
children: React.ReactNode
|
||||
size?: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl'
|
||||
showCloseButton?: boolean
|
||||
/** Ref to the element that triggered opening the modal (for focus restoration) */
|
||||
triggerRef?: React.RefObject<HTMLElement | null>
|
||||
/** ID of the title element (for aria-labelledby) */
|
||||
titleId?: string
|
||||
/** Selector for the element to focus initially inside the modal */
|
||||
initialFocusSelector?: string
|
||||
/** ID of the element that describes the modal (for aria-describedby) */
|
||||
ariaDescribedBy?: string
|
||||
/** Whether this is an alert dialog (role="alertdialog" instead of "dialog") */
|
||||
isAlertDialog?: boolean
|
||||
/** Whether to disable escape key handling (e.g., during execution) */
|
||||
disableEscapeKey?: boolean
|
||||
/** Whether to disable closing when clicking on backdrop (e.g., during execution) */
|
||||
disableBackdropClick?: boolean
|
||||
}
|
||||
|
||||
const sizeStyles: Record<string, string> = {
|
||||
@@ -31,63 +47,86 @@ export function Modal({
|
||||
title,
|
||||
children,
|
||||
size = 'md',
|
||||
showCloseButton = true
|
||||
}: ModalProps) {
|
||||
// Handle escape key
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
onClose()
|
||||
}
|
||||
},
|
||||
[onClose]
|
||||
showCloseButton = true,
|
||||
triggerRef,
|
||||
titleId,
|
||||
initialFocusSelector,
|
||||
ariaDescribedBy,
|
||||
isAlertDialog = false,
|
||||
disableEscapeKey = false,
|
||||
disableBackdropClick = false
|
||||
}: ModalProps): React.JSX.Element | null {
|
||||
const dialogRef = useRef<HTMLDivElement>(null)
|
||||
const [generatedId] = useState(
|
||||
() => `modal-title-${Date.now().toString(36)}-${Math.random().toString(36).substr(2, 9)}`
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
document.body.style.overflow = 'hidden'
|
||||
}
|
||||
// Use provided titleId or generated one
|
||||
const generatedTitleId = useMemo((): string => {
|
||||
return titleId || generatedId
|
||||
}, [titleId, generatedId])
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown)
|
||||
document.body.style.overflow = 'unset'
|
||||
}
|
||||
}, [isOpen, handleKeyDown])
|
||||
// Setup focus management (includes Escape key handling)
|
||||
const { focusLockProps } = useDialogFocus({
|
||||
isOpen,
|
||||
dialogRef,
|
||||
onClose,
|
||||
triggerRef,
|
||||
initialFocusSelector,
|
||||
shouldCloseOnEscape: !disableEscapeKey
|
||||
})
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 overflow-y-auto">
|
||||
{/* Backdrop */}
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 transition-opacity" onClick={onClose} />
|
||||
|
||||
{/* Modal container */}
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<FocusLock {...focusLockProps}>
|
||||
<div
|
||||
className="fixed inset-0 z-50 overflow-y-auto"
|
||||
role={isAlertDialog ? 'alertdialog' : 'dialog'}
|
||||
aria-modal="true"
|
||||
aria-labelledby={generatedTitleId}
|
||||
aria-describedby={ariaDescribedBy}
|
||||
>
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className={`relative w-full ${sizeStyles[size]} bg-white rounded-lg shadow-xl transform transition-all`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
{(title || showCloseButton) && (
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
|
||||
{title && <h3 className="text-lg font-semibold text-gray-900">{title}</h3>}
|
||||
{showCloseButton && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 rounded"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
className="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
|
||||
onClick={disableBackdropClick ? undefined : onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
{/* Content */}
|
||||
<div className="px-6 py-4">{children}</div>
|
||||
{/* Modal container */}
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<div
|
||||
ref={dialogRef}
|
||||
className={`relative w-full ${sizeStyles[size]} bg-white rounded-lg shadow-xl transform transition-all`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
{(title || showCloseButton) && (
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
|
||||
{title && (
|
||||
<h3 id={generatedTitleId} className="text-lg font-semibold text-gray-900">
|
||||
{title}
|
||||
</h3>
|
||||
)}
|
||||
{showCloseButton && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 rounded"
|
||||
aria-label="关闭对话框"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Content */}
|
||||
<div className="px-6 py-4">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</FocusLock>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
181
src/renderer/src/components/ui/SegmentedProgressBar.tsx
Normal file
181
src/renderer/src/components/ui/SegmentedProgressBar.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
import React from 'react'
|
||||
import type { ExtractionPhase } from '../../stores/extractorStore'
|
||||
|
||||
interface SegmentedProgressBarProps {
|
||||
progress: number
|
||||
phase?: ExtractionPhase
|
||||
currentBatch?: number
|
||||
totalBatches?: number
|
||||
subProgress?: {
|
||||
step: string
|
||||
current: number
|
||||
total: number
|
||||
}
|
||||
}
|
||||
|
||||
const PHASES: { key: ExtractionPhase; label: string; color: string }[] = [
|
||||
{ key: 'login', label: '登录', color: 'bg-purple-500' },
|
||||
{ key: 'downloading', label: '下载', color: 'bg-blue-500' },
|
||||
{ key: 'merging', label: '合并', color: 'bg-amber-500' },
|
||||
{ key: 'importing', label: '入库', color: 'bg-emerald-500' }
|
||||
]
|
||||
|
||||
export const SegmentedProgressBar: React.FC<SegmentedProgressBarProps> = ({
|
||||
progress,
|
||||
phase,
|
||||
currentBatch,
|
||||
totalBatches,
|
||||
subProgress
|
||||
}) => {
|
||||
// Calculate phase boundaries
|
||||
const getPhaseBoundaries = () => {
|
||||
if (!totalBatches) {
|
||||
return { loginEnd: 10, downloadingEnd: 90, mergingEnd: 95 }
|
||||
}
|
||||
const totalPoints = 1 + totalBatches + 2
|
||||
const progressPerPoint = 100 / totalPoints
|
||||
const loginEnd = progressPerPoint
|
||||
const downloadingEnd = (1 + totalBatches) * progressPerPoint
|
||||
const mergingEnd = (1 + totalBatches + 1) * progressPerPoint
|
||||
return { loginEnd, downloadingEnd, mergingEnd }
|
||||
}
|
||||
|
||||
const { loginEnd, downloadingEnd, mergingEnd } = getPhaseBoundaries()
|
||||
|
||||
const getCurrentPhaseIndex = (): number => {
|
||||
if (phase === 'downloading') return 1
|
||||
if (phase === 'merging') return 2
|
||||
if (phase === 'importing') return 3
|
||||
return 0
|
||||
}
|
||||
|
||||
const currentPhaseIndex = getCurrentPhaseIndex()
|
||||
|
||||
const getPhaseStatus = (index: number) => {
|
||||
if (index < currentPhaseIndex) return 'completed'
|
||||
if (index === currentPhaseIndex) return 'active'
|
||||
return 'pending'
|
||||
}
|
||||
|
||||
const getStatusDot = (status: string) => {
|
||||
if (status === 'completed') return 'bg-emerald-600'
|
||||
if (status === 'active') return 'bg-blue-600 animate-pulse'
|
||||
return 'bg-slate-300'
|
||||
}
|
||||
|
||||
const getStatusText = (status: string) => {
|
||||
if (status === 'completed') return 'text-emerald-600'
|
||||
if (status === 'active') return 'text-blue-600 font-semibold'
|
||||
return 'text-slate-400'
|
||||
}
|
||||
|
||||
const getDetailText = () => {
|
||||
if (phase === 'login' && subProgress) {
|
||||
return `${subProgress.step} (${subProgress.current}/${subProgress.total})`
|
||||
}
|
||||
if (phase === 'downloading' && currentBatch !== undefined && totalBatches !== undefined) {
|
||||
return `批次 ${currentBatch}/${totalBatches}`
|
||||
}
|
||||
if (phase === 'merging') {
|
||||
return '正在合并 Excel 文件...'
|
||||
}
|
||||
if (phase === 'importing') {
|
||||
return '正在写入数据库...'
|
||||
}
|
||||
return '准备中...'
|
||||
}
|
||||
|
||||
// Calculate segment fills based on current phase
|
||||
const getSegments = () => {
|
||||
// Login phase: simple 0-10% range
|
||||
if (phase === 'login') {
|
||||
return [{ end: 10, fill: progress }]
|
||||
}
|
||||
|
||||
// Unknown phase or missing data: simple progress bar
|
||||
if (!phase || !totalBatches) {
|
||||
return [{ end: 100, fill: progress }]
|
||||
}
|
||||
|
||||
// Multi-phase progress
|
||||
return [
|
||||
{
|
||||
end: loginEnd,
|
||||
fill: Math.min(progress, loginEnd)
|
||||
},
|
||||
{
|
||||
end: downloadingEnd,
|
||||
fill: Math.min(Math.max(progress, loginEnd), downloadingEnd)
|
||||
},
|
||||
{
|
||||
end: mergingEnd,
|
||||
fill: Math.min(Math.max(progress, downloadingEnd), mergingEnd)
|
||||
},
|
||||
{
|
||||
end: 100,
|
||||
fill: Math.min(Math.max(progress, mergingEnd), 100)
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const segments = getSegments()
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
|
||||
{/* 阶段标签 */}
|
||||
<div className="flex justify-between mb-3">
|
||||
{PHASES.map((p, index) => {
|
||||
const status = getPhaseStatus(index)
|
||||
return (
|
||||
<div
|
||||
key={p.key}
|
||||
className={`flex items-center gap-2 ${getStatusText(status)} transition-colors`}
|
||||
>
|
||||
<div className={`w-3 h-3 rounded-full ${getStatusDot(status)} transition-colors`} />
|
||||
<span className="text-sm">{p.label}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 分段进度条 */}
|
||||
<div className="relative h-3 bg-slate-100 rounded-full overflow-hidden mb-3">
|
||||
{segments.map((segment, index) => {
|
||||
const prevEnd = index === 0 ? 0 : segments[index - 1].end
|
||||
const segmentWidth = segment.end - prevEnd
|
||||
const filledWidth = Math.max(0, segment.fill - prevEnd)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="absolute h-full"
|
||||
style={{
|
||||
left: `${prevEnd}%`,
|
||||
width: `${segmentWidth}%`
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={`h-full transition-all duration-300 ${PHASES[index].color}`}
|
||||
style={{
|
||||
width: `${segmentWidth > 0 ? (filledWidth / segmentWidth) * 100 : 0}%`
|
||||
}}
|
||||
/>
|
||||
{index < PHASES.length - 1 && (
|
||||
<div className="absolute right-0 top-0 h-full w-px bg-white/50" />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 详细信息 */}
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="text-sm text-slate-600">
|
||||
<span className="text-slate-500">当前进度:</span>
|
||||
<span className="text-slate-800">{getDetailText()}</span>
|
||||
</div>
|
||||
<div className="text-xl font-bold text-slate-800">{Math.round(progress)}%</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -73,7 +73,7 @@ export function Toast() {
|
||||
if (toasts.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2">
|
||||
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 flex flex-col gap-2">
|
||||
{toasts.map((toast) => (
|
||||
<ToastItem
|
||||
key={toast.id}
|
||||
|
||||
3
src/renderer/src/env.d.ts
vendored
3
src/renderer/src/env.d.ts
vendored
@@ -1 +1,4 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare const __APP_VERSION__: string
|
||||
declare const __GIT_HASH__: string
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
/**
|
||||
* IPC Hook for Authentication operations
|
||||
*
|
||||
* Provides a React-friendly interface for auth IPC calls
|
||||
* with loading state, error handling, and user data management.
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
// Types based on the user types
|
||||
interface UserInfo {
|
||||
id: number
|
||||
username: string
|
||||
@@ -38,9 +30,6 @@ interface UseAuthReturn extends UseAuthState {
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for authentication operations
|
||||
*/
|
||||
export function useAuth(): UseAuthReturn {
|
||||
const [state, setState] = useState<UseAuthState>({
|
||||
loading: false,
|
||||
@@ -51,31 +40,20 @@ export function useAuth(): UseAuthReturn {
|
||||
|
||||
const login = useCallback(async (credentials: LoginCredentials): Promise<boolean> => {
|
||||
setState((prev) => ({ ...prev, loading: true, error: null }))
|
||||
const result = await window.electron.auth.login(credentials)
|
||||
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('auth:login', credentials)
|
||||
|
||||
if (result.success && result.userInfo) {
|
||||
setState({
|
||||
loading: false,
|
||||
user: result.userInfo,
|
||||
error: null,
|
||||
isAuthenticated: true
|
||||
})
|
||||
return true
|
||||
} else {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: result.error || 'Login failed'
|
||||
}))
|
||||
return false
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
setState((prev) => ({ ...prev, loading: false, error: message }))
|
||||
if (!result.success || !result.data?.userInfo) {
|
||||
setState((prev) => ({ ...prev, loading: false, error: result.error ?? 'Login failed' }))
|
||||
return false
|
||||
}
|
||||
|
||||
setState({
|
||||
loading: false,
|
||||
user: result.data.userInfo,
|
||||
error: null,
|
||||
isAuthenticated: true
|
||||
})
|
||||
return true
|
||||
}, [])
|
||||
|
||||
const silentLogin = useCallback(async (): Promise<{
|
||||
@@ -83,107 +61,76 @@ export function useAuth(): UseAuthReturn {
|
||||
requiresUserSelection?: boolean
|
||||
}> => {
|
||||
setState((prev) => ({ ...prev, loading: true, error: null }))
|
||||
const result = await window.electron.auth.silentLogin()
|
||||
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('auth:silentLogin')
|
||||
|
||||
if (result.success && result.userInfo) {
|
||||
setState({
|
||||
loading: false,
|
||||
user: result.userInfo,
|
||||
error: null,
|
||||
isAuthenticated: true
|
||||
})
|
||||
return { success: true, requiresUserSelection: result.requiresUserSelection }
|
||||
} else {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: result.error || null
|
||||
}))
|
||||
return { success: false }
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
setState((prev) => ({ ...prev, loading: false, error: message }))
|
||||
if (!result.success || !result.data?.userInfo) {
|
||||
setState((prev) => ({ ...prev, loading: false, error: result.error || null }))
|
||||
return { success: false }
|
||||
}
|
||||
|
||||
setState({
|
||||
loading: false,
|
||||
user: result.data.userInfo,
|
||||
error: null,
|
||||
isAuthenticated: true
|
||||
})
|
||||
return { success: true, requiresUserSelection: result.data.requiresUserSelection }
|
||||
}, [])
|
||||
|
||||
const logout = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
await window.electron.ipcRenderer.invoke('auth:logout')
|
||||
setState({
|
||||
loading: false,
|
||||
user: null,
|
||||
error: null,
|
||||
isAuthenticated: false
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error)
|
||||
}
|
||||
await window.electron.auth.logout()
|
||||
setState({
|
||||
loading: false,
|
||||
user: null,
|
||||
error: null,
|
||||
isAuthenticated: false
|
||||
})
|
||||
}, [])
|
||||
|
||||
const getCurrentUser = useCallback(async (): Promise<UserInfo | null> => {
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('auth:getCurrentUser')
|
||||
if (result.isAuthenticated && result.userInfo) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
user: result.userInfo,
|
||||
isAuthenticated: true
|
||||
}))
|
||||
return result.userInfo
|
||||
}
|
||||
return null
|
||||
} catch {
|
||||
const result = await window.electron.auth.getCurrentUser()
|
||||
if (!result.success || !result.data?.isAuthenticated || !result.data.userInfo) {
|
||||
return null
|
||||
}
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
user: result.data!.userInfo!,
|
||||
isAuthenticated: true
|
||||
}))
|
||||
return result.data.userInfo
|
||||
}, [])
|
||||
|
||||
const getAllUsers = useCallback(async (): Promise<UserInfo[]> => {
|
||||
try {
|
||||
return await window.electron.ipcRenderer.invoke('auth:getAllUsers')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const result = await window.electron.auth.getAllUsers()
|
||||
return result.success && result.data ? result.data : []
|
||||
}, [])
|
||||
|
||||
const switchUser = useCallback(async (userInfo: UserInfo): Promise<boolean> => {
|
||||
setState((prev) => ({ ...prev, loading: true, error: null }))
|
||||
const result = await window.electron.auth.switchUser(userInfo)
|
||||
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('auth:switchUser', userInfo)
|
||||
|
||||
if (result.success && result.userInfo) {
|
||||
setState({
|
||||
loading: false,
|
||||
user: result.userInfo,
|
||||
error: null,
|
||||
isAuthenticated: true
|
||||
})
|
||||
return true
|
||||
} else {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: result.error || 'Switch user failed'
|
||||
}))
|
||||
return false
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
setState((prev) => ({ ...prev, loading: false, error: message }))
|
||||
if (!result.success || !result.data?.userInfo) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: result.error || 'Switch user failed'
|
||||
}))
|
||||
return false
|
||||
}
|
||||
|
||||
setState({
|
||||
loading: false,
|
||||
user: result.data.userInfo,
|
||||
error: null,
|
||||
isAuthenticated: true
|
||||
})
|
||||
return true
|
||||
}, [])
|
||||
|
||||
const isAdmin = useCallback(async (): Promise<boolean> => {
|
||||
try {
|
||||
return await window.electron.ipcRenderer.invoke('auth:isAdmin')
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
const result = await window.electron.auth.isAdmin()
|
||||
return result.success && Boolean(result.data)
|
||||
}, [])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
|
||||
@@ -1,74 +1,570 @@
|
||||
/**
|
||||
* IPC Hook for Cleaner operations
|
||||
*
|
||||
* Provides a React-friendly interface for cleaner IPC calls
|
||||
* with loading state, error handling, and data management.
|
||||
*/
|
||||
import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
|
||||
import { showSuccess, showError, showWarning, formatListMessage } from '../stores/useAppStore'
|
||||
import { ConfirmDialogProps } from '../components/ui/ConfirmDialog'
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
// Types based on the cleaner types
|
||||
interface CleanerInput {
|
||||
orderNumbers: string[]
|
||||
materialCodes: string[]
|
||||
dryRun: boolean
|
||||
export interface ValidationResult {
|
||||
materialName: string
|
||||
materialCode: string
|
||||
specification: string
|
||||
model: string
|
||||
managerName: string
|
||||
isMarkedForDeletion: boolean
|
||||
matchedTypeKeyword?: string
|
||||
}
|
||||
|
||||
interface CleanerResult {
|
||||
processedCount: number
|
||||
errors: string[]
|
||||
export interface CleanerProgress {
|
||||
message: string
|
||||
progress: number
|
||||
currentOrderIndex: number
|
||||
totalOrders: number
|
||||
currentMaterialIndex: number
|
||||
totalMaterialsInOrder: number
|
||||
currentOrderNumber?: string
|
||||
phase: 'login' | 'processing' | 'complete'
|
||||
}
|
||||
|
||||
interface UseCleanerState {
|
||||
loading: boolean
|
||||
data: CleanerResult | null
|
||||
error: string | null
|
||||
}
|
||||
export function useCleaner() {
|
||||
// Authentication & permissions
|
||||
const [isAdmin, setIsAdmin] = useState(false)
|
||||
const [currentUsername, setCurrentUsername] = useState<string>('')
|
||||
|
||||
interface UseCleanerReturn extends UseCleanerState {
|
||||
execute: (input: CleanerInput) => Promise<CleanerResult | null>
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for executing cleaner operations
|
||||
*/
|
||||
export function useCleaner(): UseCleanerReturn {
|
||||
const [state, setState] = useState<UseCleanerState>({
|
||||
loading: false,
|
||||
data: null,
|
||||
error: null
|
||||
// State with sessionStorage persistence
|
||||
const [dryRun, setDryRun] = useState(() => {
|
||||
const saved = sessionStorage.getItem('cleaner_dryRun')
|
||||
return saved ? saved === 'true' : false
|
||||
})
|
||||
|
||||
const execute = useCallback(async (input: CleanerInput): Promise<CleanerResult | null> => {
|
||||
setState({ loading: true, data: null, error: null })
|
||||
const [valMode, setValMode] = useState<'full' | 'filtered'>(() => {
|
||||
const saved = sessionStorage.getItem('cleaner_validationMode')
|
||||
return saved === 'full' ? 'full' : 'filtered'
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('cleaner:run', input)
|
||||
// Validation state
|
||||
const [validationResults, setValidationResults] = useState<ValidationResult[]>([])
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set())
|
||||
const [hiddenItems, setHiddenItems] = useState<Set<string>>(new Set())
|
||||
const [managers, setManagers] = useState<string[]>([])
|
||||
const [selectedManagers, setSelectedManagers] = useState<Set<string>>(new Set())
|
||||
|
||||
if (result.success) {
|
||||
setState({ loading: false, data: result.data, error: null })
|
||||
return result.data
|
||||
} else {
|
||||
setState({ loading: false, data: null, error: result.error || 'Unknown error' })
|
||||
return null
|
||||
// Execution state
|
||||
const [isRunning, setIsRunning] = useState(false)
|
||||
const [isValidationRunning, setIsValidationRunning] = useState(false)
|
||||
const [isExporting, setIsExporting] = useState(false)
|
||||
const [isExecuting, setIsExecuting] = useState(false)
|
||||
|
||||
// Shared Production IDs state
|
||||
const [sharedProductionIdsCount, setSharedProductionIdsCount] = useState(0)
|
||||
|
||||
// Material type management dialog state
|
||||
const [isTypeDialogOpen, setIsTypeDialogOpen] = useState(false)
|
||||
|
||||
// Execution report dialog state
|
||||
const [isReportDialogOpen, setIsReportDialogOpen] = useState(false)
|
||||
const [reportData, setReportData] = useState<{
|
||||
ordersProcessed: number
|
||||
materialsDeleted: number
|
||||
materialsSkipped: number
|
||||
errors: string[]
|
||||
retriedOrders?: number
|
||||
successfulRetries?: number
|
||||
} | null>(null)
|
||||
|
||||
// Progress state
|
||||
const [progress, setProgress] = useState<CleanerProgress | null>(null)
|
||||
const [startTime, setStartTime] = useState<number | null>(null)
|
||||
|
||||
// Execution settings state
|
||||
const [headless, setHeadless] = useState(() => {
|
||||
const saved = sessionStorage.getItem('cleaner_headless')
|
||||
return saved ? saved === 'true' : true
|
||||
})
|
||||
const [queryBatchSize, setQueryBatchSize] = useState(100)
|
||||
const [processConcurrency, setProcessConcurrency] = useState(1)
|
||||
const [showSettingsMenu, setShowSettingsMenu] = useState(false)
|
||||
|
||||
// Inline editing state for manager field (Admin only)
|
||||
const [editingCell, setEditingCell] = useState<{ rowIndex: number; field: string } | null>(null)
|
||||
const [editValue, setEditValue] = useState('')
|
||||
const inputRef = useRef<HTMLInputElement | HTMLSelectElement>(null)
|
||||
|
||||
// Confirmation dialog state
|
||||
const [confirmDialog, setConfirmDialog] = useState<ConfirmDialogProps | null>(null)
|
||||
|
||||
/**
|
||||
* Show a confirmation dialog and return user's choice
|
||||
*/
|
||||
const showConfirmDialog = useCallback(
|
||||
(options: Omit<ConfirmDialogProps, 'isOpen' | 'onConfirm' | 'onCancel'>): Promise<boolean> => {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
setConfirmDialog({
|
||||
...options,
|
||||
isOpen: true,
|
||||
onConfirm: () => {
|
||||
setConfirmDialog(null)
|
||||
resolve(true)
|
||||
},
|
||||
onCancel: () => {
|
||||
setConfirmDialog(null)
|
||||
resolve(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// Check admin status and get shared Production IDs on mount
|
||||
useEffect(() => {
|
||||
const initializePage = async () => {
|
||||
try {
|
||||
const adminResult = await window.electron.auth.isAdmin()
|
||||
const userResult = await window.electron.auth.getCurrentUser()
|
||||
const admin = adminResult.success && Boolean(adminResult.data)
|
||||
const user = userResult.success ? userResult.data : undefined
|
||||
setIsAdmin(admin)
|
||||
if (user && user.userInfo) {
|
||||
setCurrentUsername(user.userInfo.username)
|
||||
if (!admin) {
|
||||
setSelectedManagers(new Set([user.userInfo.username]))
|
||||
}
|
||||
}
|
||||
|
||||
// Load managers
|
||||
if (admin) {
|
||||
const resp = await window.electron.materials.getManagers()
|
||||
const managersPayload = resp.success
|
||||
? (resp.data as { managers: string[] } | undefined)
|
||||
: undefined
|
||||
const managerList = managersPayload?.managers ?? []
|
||||
setManagers(managerList)
|
||||
setSelectedManagers(new Set(managerList))
|
||||
}
|
||||
|
||||
// Get shared Production IDs
|
||||
const result = await window.electron.validation.getSharedProductionIds()
|
||||
const idsPayload = result.success
|
||||
? (result.data as { productionIds?: string[] } | undefined)
|
||||
: undefined
|
||||
setSharedProductionIdsCount(idsPayload?.productionIds?.length ?? 0)
|
||||
} catch (err) {
|
||||
console.error('Initialization failed:', err)
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
setState({ loading: false, data: null, error: message })
|
||||
return null
|
||||
}
|
||||
initializePage()
|
||||
}, [])
|
||||
|
||||
// Subscribe to cleaner progress events
|
||||
useEffect(() => {
|
||||
const unsubscribeProgress = window.electron.cleaner.onProgress((data) => {
|
||||
setProgress(data)
|
||||
})
|
||||
|
||||
return () => {
|
||||
unsubscribeProgress()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setState({ loading: false, data: null, error: null })
|
||||
// Load cleaner config from config.yaml on mount
|
||||
useEffect(() => {
|
||||
const loadCleanerConfig = async () => {
|
||||
try {
|
||||
const result = await window.electron.config.getCleaner()
|
||||
if (result.success && result.data) {
|
||||
setQueryBatchSize(result.data.queryBatchSize)
|
||||
setProcessConcurrency(result.data.processConcurrency)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load cleaner config:', err)
|
||||
}
|
||||
}
|
||||
loadCleanerConfig()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
sessionStorage.setItem('cleaner_dryRun', dryRun.toString())
|
||||
}, [dryRun])
|
||||
|
||||
useEffect(() => {
|
||||
sessionStorage.setItem('cleaner_headless', headless.toString())
|
||||
}, [headless])
|
||||
|
||||
const updateProcessConcurrency = async (value: number) => {
|
||||
const clamped = Math.max(1, Math.min(20, value))
|
||||
setProcessConcurrency(clamped)
|
||||
try {
|
||||
await window.electron.config.updateCleaner({ processConcurrency: clamped })
|
||||
} catch (err) {
|
||||
console.error('Failed to update cleaner config:', err)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
sessionStorage.setItem('cleaner_validationMode', valMode)
|
||||
}, [valMode])
|
||||
|
||||
// Filter validation results by selected managers and hidden items
|
||||
const filteredResults = useMemo(() => {
|
||||
let results = validationResults
|
||||
if (!isAdmin && currentUsername) {
|
||||
results = results.filter((r) => r.managerName === currentUsername || !r.managerName)
|
||||
} else if (managers.length > 0 && selectedManagers.size > 0) {
|
||||
results = results.filter((r) => selectedManagers.has(r.managerName) || !r.managerName)
|
||||
}
|
||||
results = results.filter((r) => !hiddenItems.has(r.materialCode))
|
||||
return results
|
||||
}, [validationResults, isAdmin, currentUsername, managers, selectedManagers, hiddenItems])
|
||||
|
||||
// Handlers
|
||||
const handleValidation = async () => {
|
||||
setIsValidationRunning(true)
|
||||
setValidationResults([])
|
||||
setSelectedItems(new Set())
|
||||
setHiddenItems(new Set())
|
||||
|
||||
try {
|
||||
const response = await window.electron.validation.validate({
|
||||
mode: valMode === 'full' ? 'database_full' : 'database_filtered',
|
||||
useSharedProductionIds: valMode === 'filtered'
|
||||
})
|
||||
const validationData = response.success ? (response.data as any) : null
|
||||
|
||||
if (response.success && validationData?.success && validationData.results) {
|
||||
setValidationResults(validationData.results)
|
||||
const markedCodes = new Set<string>(
|
||||
validationData.results
|
||||
.filter((r: ValidationResult) => r.isMarkedForDeletion)
|
||||
.map((r: ValidationResult) => r.materialCode)
|
||||
)
|
||||
setSelectedItems(markedCodes)
|
||||
|
||||
if (isAdmin) {
|
||||
const uniqueManagers = new Set<string>(
|
||||
validationData.results
|
||||
.map((r: ValidationResult) => r.managerName)
|
||||
.filter((name: string) => Boolean(name))
|
||||
)
|
||||
setManagers(Array.from(uniqueManagers))
|
||||
setSelectedManagers(uniqueManagers)
|
||||
}
|
||||
showSuccess('校验完成')
|
||||
} else {
|
||||
showError(response.error || validationData?.error || '校验失败')
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err instanceof Error ? err.message : '校验过程中发生未知错误')
|
||||
} finally {
|
||||
setIsValidationRunning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCheckboxToggle = (materialCode: string) => {
|
||||
setSelectedItems((prev) => {
|
||||
const newSet = new Set(prev)
|
||||
if (newSet.has(materialCode)) newSet.delete(materialCode)
|
||||
else newSet.add(materialCode)
|
||||
return newSet
|
||||
})
|
||||
}
|
||||
|
||||
const startEdit = (rowIndex: number, field: string) => {
|
||||
const row = filteredResults[rowIndex]
|
||||
if (!row) return
|
||||
setEditingCell({ rowIndex, field })
|
||||
setEditValue(row[field as keyof ValidationResult] as string)
|
||||
setTimeout(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus()
|
||||
if (inputRef.current instanceof HTMLInputElement) {
|
||||
inputRef.current.select()
|
||||
}
|
||||
}
|
||||
}, 0)
|
||||
}
|
||||
|
||||
const saveEdit = () => {
|
||||
if (!editingCell) return
|
||||
const { rowIndex } = editingCell
|
||||
const row = filteredResults[rowIndex]
|
||||
if (!row) return
|
||||
|
||||
const newValue = editValue.trim()
|
||||
if (row.managerName === newValue) {
|
||||
setEditingCell(null)
|
||||
return
|
||||
}
|
||||
|
||||
setValidationResults((prev) =>
|
||||
prev.map((r) => (r.materialCode === row.materialCode ? { ...r, managerName: newValue } : r))
|
||||
)
|
||||
setEditingCell(null)
|
||||
}
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingCell(null)
|
||||
}
|
||||
|
||||
const handleAssignManagerOnSelect = (materialCode: string) => {
|
||||
if (!isAdmin && currentUsername) {
|
||||
const result = validationResults.find((r) => r.materialCode === materialCode)
|
||||
if (result && (!result.managerName || result.managerName !== currentUsername)) {
|
||||
setValidationResults((prev) =>
|
||||
prev.map((r) =>
|
||||
r.materialCode === materialCode ? { ...r, managerName: currentUsername } : r
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleConfirmDeletion = async () => {
|
||||
const resultsToProcess = isAdmin ? validationResults : filteredResults
|
||||
|
||||
if (resultsToProcess.length === 0) {
|
||||
showWarning('没有可处理的数据')
|
||||
return
|
||||
}
|
||||
|
||||
const materialsToUpsert: { materialCode: string; managerName: string }[] = []
|
||||
const materialsToDelete: string[] = []
|
||||
const missingManager: string[] = []
|
||||
|
||||
for (const result of resultsToProcess) {
|
||||
if (!result.materialCode?.trim()) continue
|
||||
|
||||
const code = result.materialCode.trim()
|
||||
if (selectedItems.has(code)) {
|
||||
if (!result.managerName?.trim()) missingManager.push(code)
|
||||
else materialsToUpsert.push({ materialCode: code, managerName: result.managerName.trim() })
|
||||
} else {
|
||||
materialsToDelete.push(code)
|
||||
}
|
||||
}
|
||||
|
||||
if (missingManager.length > 0) {
|
||||
showError(
|
||||
`以下已勾选的记录缺少负责人信息,无法保存:\n\n${formatListMessage(missingManager, 10)}`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (materialsToUpsert.length === 0 && materialsToDelete.length === 0) {
|
||||
showWarning('没有需要处理的记录')
|
||||
return
|
||||
}
|
||||
|
||||
const confirmParts: string[] = []
|
||||
if (materialsToUpsert.length > 0)
|
||||
confirmParts.push(`写入/更新 ${materialsToUpsert.length} 条记录`)
|
||||
if (materialsToDelete.length > 0) confirmParts.push(`删除 ${materialsToDelete.length} 条记录`)
|
||||
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: '确认操作',
|
||||
message: `确认以下操作吗?\n\n${confirmParts.join('\n')}`,
|
||||
variant: 'warning'
|
||||
})
|
||||
if (!confirmed) return
|
||||
|
||||
try {
|
||||
setIsRunning(true)
|
||||
const msgParts: string[] = []
|
||||
|
||||
if (materialsToUpsert.length > 0) {
|
||||
const res = await window.electron.materials.upsertBatch(materialsToUpsert)
|
||||
const payload = res.success
|
||||
? (res.data as { stats?: { success?: number } } | undefined)
|
||||
: undefined
|
||||
if (!res.success) throw new Error(res.error || '写入物料失败')
|
||||
msgParts.push(`写入/更新成功:${payload?.stats?.success || 0} 条`)
|
||||
}
|
||||
|
||||
if (materialsToDelete.length > 0) {
|
||||
const res = await window.electron.materials.delete(materialsToDelete)
|
||||
const payload = res.success ? (res.data as { count?: number } | undefined) : undefined
|
||||
if (!res.success) throw new Error(res.error || '删除物料失败')
|
||||
msgParts.push(`删除成功:${payload?.count || 0} 条`)
|
||||
}
|
||||
|
||||
showSuccess(`操作完成!\n\n${msgParts.join('\n')}`)
|
||||
|
||||
// Reload managers if admin
|
||||
if (isAdmin) {
|
||||
const resp = await window.electron.materials.getManagers()
|
||||
const payload = resp.success
|
||||
? (resp.data as { managers?: string[] } | undefined)
|
||||
: undefined
|
||||
setManagers(payload?.managers ?? [])
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err instanceof Error ? err.message : '操作失败')
|
||||
} finally {
|
||||
setIsRunning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleExecuteDeletion = async () => {
|
||||
if (!dryRun) {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: '警告',
|
||||
message: '正式执行将删除 ERP 系统中的物料数据,是否继续?',
|
||||
variant: 'danger',
|
||||
confirmText: '继续',
|
||||
cancelText: '取消'
|
||||
})
|
||||
if (!confirmed) return
|
||||
}
|
||||
|
||||
setIsRunning(true)
|
||||
// Initialize progress state BEFORE opening dialog to ensure progress view shows first
|
||||
setProgress({
|
||||
message: '正在初始化...',
|
||||
progress: 0,
|
||||
currentOrderIndex: 0,
|
||||
totalOrders: 0,
|
||||
currentMaterialIndex: 0,
|
||||
totalMaterialsInOrder: 0,
|
||||
phase: 'login'
|
||||
})
|
||||
setIsExecuting(true)
|
||||
setStartTime(Date.now())
|
||||
setIsReportDialogOpen(true)
|
||||
|
||||
try {
|
||||
const cleanerDataResult = await window.electron.validation.getCleanerData()
|
||||
const cleanerData = cleanerDataResult.success ? (cleanerDataResult.data as any) : null
|
||||
if (!cleanerDataResult.success || cleanerData?.success === false) {
|
||||
throw new Error(cleanerDataResult.error || '获取清理数据失败')
|
||||
}
|
||||
|
||||
const orderNumberList = cleanerData?.orderNumbers || []
|
||||
const materialCodeList = cleanerData?.materialCodes || []
|
||||
|
||||
if (orderNumberList.length === 0)
|
||||
throw new Error('没有订单号数据。请先到数据提取页面输入 Production ID。')
|
||||
if (materialCodeList.length === 0)
|
||||
throw new Error('没有物料代码数据。请确认已在物料清理界面确认要删除的物料。')
|
||||
|
||||
const response = await window.electron.cleaner.runCleaner({
|
||||
orderNumbers: orderNumberList,
|
||||
materialCodes: materialCodeList,
|
||||
dryRun,
|
||||
headless,
|
||||
queryBatchSize,
|
||||
processConcurrency
|
||||
})
|
||||
const cleanerRunData = response.success ? (response.data as any) : null
|
||||
|
||||
if (response.success && cleanerRunData) {
|
||||
setReportData({
|
||||
ordersProcessed: cleanerRunData.ordersProcessed,
|
||||
materialsDeleted: cleanerRunData.materialsDeleted,
|
||||
materialsSkipped: cleanerRunData.materialsSkipped,
|
||||
errors: cleanerRunData.errors,
|
||||
retriedOrders: cleanerRunData.retriedOrders,
|
||||
successfulRetries: cleanerRunData.successfulRetries
|
||||
})
|
||||
} else {
|
||||
throw new Error(response.error || '清理失败')
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err instanceof Error ? err.message : '发生未知错误')
|
||||
} finally {
|
||||
setIsRunning(false)
|
||||
setIsExecuting(false)
|
||||
setProgress(null)
|
||||
// Note: Don't clear startTime here - it's needed for the execution report dialog
|
||||
// startTime will be reset when the dialog closes and a new execution starts
|
||||
}
|
||||
}
|
||||
|
||||
const resetStartTime = useCallback(() => {
|
||||
setStartTime(null)
|
||||
}, [])
|
||||
|
||||
const handleExportResults = async () => {
|
||||
if (filteredResults.length === 0) {
|
||||
showWarning('没有数据可导出')
|
||||
return
|
||||
}
|
||||
|
||||
setIsExporting(true)
|
||||
try {
|
||||
// Prepare export data from filtered results
|
||||
const exportItems = filteredResults.map((result) => ({
|
||||
materialName: result.materialName,
|
||||
materialCode: result.materialCode,
|
||||
specification: result.specification || '',
|
||||
model: result.model || '',
|
||||
managerName: result.managerName || '',
|
||||
isMarkedForDeletion: result.isMarkedForDeletion,
|
||||
isSelected: selectedItems.has(result.materialCode)
|
||||
}))
|
||||
|
||||
const response = await window.electron.cleaner.exportResults(exportItems)
|
||||
const exportData = response.success ? (response.data as any) : null
|
||||
|
||||
if (response.success && exportData?.success !== false) {
|
||||
showSuccess(`导出成功!\n文件已保存到:${exportData?.filePath ?? ''}`)
|
||||
} else {
|
||||
throw new Error(response.error || exportData?.error || '导出失败')
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err instanceof Error ? err.message : '导出过程中发生错误')
|
||||
} finally {
|
||||
setIsExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
execute,
|
||||
reset
|
||||
isAdmin,
|
||||
currentUsername,
|
||||
dryRun,
|
||||
setDryRun,
|
||||
valMode,
|
||||
setValMode,
|
||||
validationResults,
|
||||
selectedItems,
|
||||
setSelectedItems,
|
||||
hiddenItems,
|
||||
setHiddenItems,
|
||||
managers,
|
||||
selectedManagers,
|
||||
setSelectedManagers,
|
||||
isRunning,
|
||||
isExecuting,
|
||||
isValidationRunning,
|
||||
isExporting,
|
||||
sharedProductionIdsCount,
|
||||
isTypeDialogOpen,
|
||||
setIsTypeDialogOpen,
|
||||
headless,
|
||||
setHeadless,
|
||||
queryBatchSize,
|
||||
setQueryBatchSize,
|
||||
processConcurrency,
|
||||
setProcessConcurrency,
|
||||
updateProcessConcurrency,
|
||||
showSettingsMenu,
|
||||
setShowSettingsMenu,
|
||||
filteredResults,
|
||||
isReportDialogOpen,
|
||||
setIsReportDialogOpen,
|
||||
reportData,
|
||||
editingCell,
|
||||
editValue,
|
||||
setEditValue,
|
||||
inputRef,
|
||||
startEdit,
|
||||
saveEdit,
|
||||
cancelEdit,
|
||||
handleAssignManagerOnSelect,
|
||||
progress,
|
||||
startTime,
|
||||
resetStartTime,
|
||||
handleValidation,
|
||||
handleCheckboxToggle,
|
||||
handleConfirmDeletion,
|
||||
handleExecuteDeletion,
|
||||
handleExportResults,
|
||||
confirmDialog
|
||||
}
|
||||
}
|
||||
|
||||
export default useCleaner
|
||||
|
||||
322
src/renderer/src/hooks/useDialogFocus.ts
Normal file
322
src/renderer/src/hooks/useDialogFocus.ts
Normal file
@@ -0,0 +1,322 @@
|
||||
import { useEffect, RefObject } from 'react'
|
||||
|
||||
/**
|
||||
* Options for configuring dialog focus management
|
||||
*/
|
||||
export interface UseDialogFocusOptions {
|
||||
/** Whether the dialog is currently open */
|
||||
isOpen: boolean
|
||||
/** Ref to the dialog container element */
|
||||
dialogRef: RefObject<HTMLElement | null>
|
||||
/** Callback to close the dialog */
|
||||
onClose: () => void
|
||||
/** Optional ref to the element that triggered opening the dialog */
|
||||
triggerRef?: RefObject<HTMLElement | null>
|
||||
/** Optional selector for the element to focus initially inside the dialog */
|
||||
initialFocusSelector?: string
|
||||
/** Whether to lock body scroll when dialog is open (default: true) */
|
||||
lockBodyScroll?: boolean
|
||||
/**
|
||||
* Whether Escape key should close the dialog (default: true)
|
||||
* Can be a boolean or a function that receives the keyboard event and returns a boolean
|
||||
*/
|
||||
shouldCloseOnEscape?: boolean | ((event: KeyboardEvent) => boolean)
|
||||
}
|
||||
|
||||
/**
|
||||
* Return type for useDialogFocus hook
|
||||
*/
|
||||
export interface UseDialogFocusReturn {
|
||||
/** Whether focus lock should be enabled */
|
||||
focusLockEnabled: boolean
|
||||
/** Props to spread on FocusLock component */
|
||||
focusLockProps: {
|
||||
disabled: boolean
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* React Hook for managing focus in modal dialogs
|
||||
*
|
||||
* Integrates with react-focus-lock to provide:
|
||||
* - Focus trapping within dialog
|
||||
* - Initial focus management (first interactive element or custom selector)
|
||||
* - Focus restoration to trigger element on close
|
||||
* - Escape key handling
|
||||
* - Body scroll locking
|
||||
*
|
||||
* @param options - Configuration options for focus management
|
||||
* @returns Focus lock props and state
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* function MyDialog({ isOpen, onClose, isExecuting }) {
|
||||
* const dialogRef = useRef<HTMLDivElement>(null)
|
||||
* const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
* const { focusLockEnabled, focusLockProps } = useDialogFocus({
|
||||
* isOpen,
|
||||
* dialogRef,
|
||||
* onClose,
|
||||
* triggerRef,
|
||||
* shouldCloseOnEscape: () => !isExecuting // Only close when not executing
|
||||
* })
|
||||
*
|
||||
* return (
|
||||
* <FocusLock {...focusLockProps}>
|
||||
* <div ref={dialogRef} role="dialog" aria-modal="true">
|
||||
* <h2>Dialog Title</h2>
|
||||
* <button onClick={onClose}>Close</button>
|
||||
* </div>
|
||||
* </FocusLock>
|
||||
* )
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function useDialogFocus(options: UseDialogFocusOptions): UseDialogFocusReturn {
|
||||
const {
|
||||
isOpen,
|
||||
dialogRef,
|
||||
onClose,
|
||||
triggerRef,
|
||||
initialFocusSelector,
|
||||
lockBodyScroll = true,
|
||||
shouldCloseOnEscape = true
|
||||
} = options
|
||||
|
||||
// Handle Escape key press
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent): void => {
|
||||
if (event.key === 'Escape' || event.keyCode === 27) {
|
||||
// Check if we should close on escape
|
||||
let shouldClose = true
|
||||
if (shouldCloseOnEscape !== undefined) {
|
||||
if (typeof shouldCloseOnEscape === 'function') {
|
||||
shouldClose = shouldCloseOnEscape(event)
|
||||
} else {
|
||||
shouldClose = shouldCloseOnEscape
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldClose) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return (): void => {
|
||||
window.removeEventListener('keydown', handleKeyDown)
|
||||
}
|
||||
}, [isOpen, onClose, shouldCloseOnEscape])
|
||||
|
||||
// Manage body scroll locking
|
||||
useEffect(() => {
|
||||
if (!lockBodyScroll) return
|
||||
|
||||
if (isOpen) {
|
||||
// Store current scroll position
|
||||
const scrollY = window.scrollY
|
||||
document.body.style.position = 'fixed'
|
||||
document.body.style.top = `-${scrollY}px`
|
||||
document.body.style.left = '0'
|
||||
document.body.style.right = '0'
|
||||
document.body.style.overflow = 'hidden'
|
||||
} else {
|
||||
// Restore scroll position
|
||||
const scrollY = document.body.style.top
|
||||
document.body.style.position = ''
|
||||
document.body.style.top = ''
|
||||
document.body.style.left = ''
|
||||
document.body.style.right = ''
|
||||
document.body.style.overflow = ''
|
||||
if (scrollY) {
|
||||
window.scrollTo(0, parseInt(scrollY, 10) * -1)
|
||||
}
|
||||
}
|
||||
|
||||
return (): void => {
|
||||
// Cleanup on unmount or when isOpen changes
|
||||
if (isOpen) {
|
||||
const scrollY = document.body.style.top
|
||||
document.body.style.position = ''
|
||||
document.body.style.top = ''
|
||||
document.body.style.left = ''
|
||||
document.body.style.right = ''
|
||||
document.body.style.overflow = ''
|
||||
if (scrollY) {
|
||||
window.scrollTo(0, parseInt(scrollY, 10) * -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [isOpen, lockBodyScroll])
|
||||
|
||||
// Manage initial focus when dialog opens
|
||||
useEffect(() => {
|
||||
if (!isOpen || !dialogRef.current) return
|
||||
|
||||
const setupFocus = (): void => {
|
||||
const dialogElement = dialogRef.current
|
||||
if (!dialogElement) return
|
||||
|
||||
// If initialFocusSelector is provided, try to focus that element
|
||||
if (initialFocusSelector) {
|
||||
const focusElement = dialogElement.querySelector(initialFocusSelector) as HTMLElement
|
||||
if (focusElement && typeof focusElement.focus === 'function') {
|
||||
// Check if element is visible and focusable
|
||||
const style = window.getComputedStyle(focusElement)
|
||||
if (style.display !== 'none' && style.visibility !== 'hidden') {
|
||||
requestAnimationFrame(() => {
|
||||
focusElement.focus({ preventScroll: true })
|
||||
})
|
||||
return
|
||||
}
|
||||
// Fallback: element found but not visible, log warning and try default
|
||||
console.warn(`Focus element found but not visible: ${initialFocusSelector}`)
|
||||
} else {
|
||||
// Fallback: element not found, log warning and try default
|
||||
console.warn(`Focus element not found for selector: ${initialFocusSelector}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, focus the first interactive element
|
||||
const focusableSelectors = [
|
||||
'button:not([disabled]):not([tabindex="-1"])',
|
||||
'a[href]',
|
||||
'input:not([disabled]):not([tabindex="-1"])',
|
||||
'select:not([disabled]):not([tabindex="-1"])',
|
||||
'textarea:not([disabled]):not([tabindex="-1"])',
|
||||
'[tabindex]:not([tabindex="-1"])'
|
||||
]
|
||||
const firstFocusable = dialogElement.querySelector(
|
||||
focusableSelectors.join(', ')
|
||||
) as HTMLElement
|
||||
if (firstFocusable && typeof firstFocusable.focus === 'function') {
|
||||
requestAnimationFrame(() => {
|
||||
firstFocusable.focus({ preventScroll: true })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Delay to ensure portal content is rendered
|
||||
requestAnimationFrame(setupFocus)
|
||||
}, [isOpen, dialogRef, initialFocusSelector])
|
||||
|
||||
// Restore focus to trigger element when dialog closes
|
||||
useEffect(() => {
|
||||
if (isOpen || !triggerRef?.current) return
|
||||
|
||||
const restoreFocus = (): void => {
|
||||
const triggerElement = triggerRef.current
|
||||
|
||||
// Check if element still exists in DOM
|
||||
if (!triggerElement || !document.contains(triggerElement)) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn('[useDialogFocus] Trigger element not found in DOM, cannot restore focus')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Check if element has a focus method
|
||||
if (typeof triggerElement.focus !== 'function') {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn('[useDialogFocus] Trigger element does not have a focus method')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Check if element is visible (not display: none)
|
||||
const style = window.getComputedStyle(triggerElement)
|
||||
if (style.display === 'none') {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn('[useDialogFocus] Trigger element is display: none, cannot restore focus')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (style.visibility === 'hidden') {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(
|
||||
'[useDialogFocus] Trigger element is visibility: hidden, cannot restore focus'
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Check if element is disabled
|
||||
if (triggerElement instanceof HTMLButtonElement && triggerElement.disabled) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn('[useDialogFocus] Trigger element is disabled, cannot restore focus')
|
||||
}
|
||||
// Try to find nearest enabled ancestor or fallback to body
|
||||
const focusableParent = findNearestFocusableElement(triggerElement)
|
||||
if (focusableParent) {
|
||||
focusableParent.focus({ preventScroll: true })
|
||||
if (import.meta.env.DEV) {
|
||||
console.info('[useDialogFocus] Restored focus to nearest focusable ancestor')
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// All checks passed, restore focus
|
||||
try {
|
||||
triggerElement.focus({ preventScroll: true })
|
||||
if (import.meta.env.DEV) {
|
||||
console.info('[useDialogFocus] Successfully restored focus to trigger element')
|
||||
}
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.error('[useDialogFocus] Error restoring focus:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to find nearest focusable ancestor
|
||||
const findNearestFocusableElement = (element: HTMLElement): HTMLElement | null => {
|
||||
let parent = element.parentElement
|
||||
const focusableSelectors = [
|
||||
'button:not([disabled]):not([tabindex="-1"])',
|
||||
'a[href]',
|
||||
'input:not([disabled]):not([tabindex="-1"])',
|
||||
'select:not([disabled]):not([tabindex="-1"])',
|
||||
'textarea:not([disabled]):not([tabindex="-1"])',
|
||||
'[tabindex]:not([tabindex="-1"])'
|
||||
]
|
||||
|
||||
while (parent && parent !== document.body) {
|
||||
// Check if parent itself is focusable
|
||||
if (
|
||||
focusableSelectors.some((selector) => parent?.matches(selector)) &&
|
||||
window.getComputedStyle(parent).display !== 'none' &&
|
||||
window.getComputedStyle(parent).visibility !== 'hidden'
|
||||
) {
|
||||
return parent
|
||||
}
|
||||
// Check if parent contains focusable element
|
||||
const focusableChild = parent.querySelector(focusableSelectors.join(', ')) as HTMLElement
|
||||
if (focusableChild) {
|
||||
return focusableChild
|
||||
}
|
||||
parent = parent.parentElement
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Use microtask queue to ensure this runs after DOM cleanup
|
||||
queueMicrotask(restoreFocus)
|
||||
}, [isOpen, triggerRef])
|
||||
|
||||
// Return focus lock configuration
|
||||
return {
|
||||
focusLockEnabled: isOpen,
|
||||
focusLockProps: {
|
||||
disabled: !isOpen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default useDialogFocus
|
||||
@@ -1,73 +1,105 @@
|
||||
/**
|
||||
* IPC Hook for Extractor operations
|
||||
*
|
||||
* Provides a React-friendly interface for extractor IPC calls
|
||||
* with loading state, error handling, and data management.
|
||||
*/
|
||||
import { useEffect } from 'react'
|
||||
import { useExtractorStore } from '../stores/extractorStore'
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
export function useExtractor() {
|
||||
const {
|
||||
isRunning,
|
||||
isComplete,
|
||||
progress,
|
||||
error,
|
||||
logs,
|
||||
setRunning,
|
||||
setProgress,
|
||||
setError,
|
||||
setComplete,
|
||||
addLog,
|
||||
clearLogs,
|
||||
resetState
|
||||
} = useExtractorStore()
|
||||
|
||||
// Types based on the extractor types
|
||||
interface ExtractorInput {
|
||||
orderNumbers: string[]
|
||||
batchSize?: number
|
||||
}
|
||||
useEffect(() => {
|
||||
const unsubscribeProgress = window.electron.extractor.onProgress((data) => {
|
||||
setProgress({
|
||||
message: data.message,
|
||||
progress: data.progress,
|
||||
phase: data.phase,
|
||||
currentBatch: data.currentBatch,
|
||||
totalBatches: data.totalBatches,
|
||||
subProgress: data.subProgress
|
||||
})
|
||||
})
|
||||
|
||||
interface ExtractorResult {
|
||||
data: Record<string, unknown>[]
|
||||
errors: string[]
|
||||
}
|
||||
const unsubscribeLog = window.electron.extractor.onLog((data) => {
|
||||
addLog(data.level as any, data.message)
|
||||
})
|
||||
|
||||
interface UseExtractorState {
|
||||
loading: boolean
|
||||
data: ExtractorResult | null
|
||||
error: string | null
|
||||
}
|
||||
return () => {
|
||||
unsubscribeProgress()
|
||||
unsubscribeLog()
|
||||
}
|
||||
}, [setProgress, addLog])
|
||||
|
||||
interface UseExtractorReturn extends UseExtractorState {
|
||||
execute: (input: ExtractorInput) => Promise<ExtractorResult | null>
|
||||
reset: () => void
|
||||
}
|
||||
const startExtraction = async (orderNumbers: string) => {
|
||||
if (!orderNumbers.trim()) {
|
||||
setError('请输入至少一个订单号')
|
||||
return
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for executing extractor operations
|
||||
*/
|
||||
export function useExtractor(): UseExtractorReturn {
|
||||
const [state, setState] = useState<UseExtractorState>({
|
||||
loading: false,
|
||||
data: null,
|
||||
error: null
|
||||
})
|
||||
|
||||
const execute = useCallback(async (input: ExtractorInput): Promise<ExtractorResult | null> => {
|
||||
setState({ loading: true, data: null, error: null })
|
||||
resetState()
|
||||
setRunning(true)
|
||||
addLog('system', '提取引擎启动,准备执行...')
|
||||
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('extractor:run', input)
|
||||
const orderNumberList = orderNumbers
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
|
||||
if (result.success) {
|
||||
setState({ loading: false, data: result.data, error: null })
|
||||
return result.data
|
||||
await window.electron.validation.setSharedProductionIds(orderNumberList)
|
||||
addLog('info', `已存储 ${orderNumberList.length} 个订单号用于跨模块共享`)
|
||||
|
||||
const response = await window.electron.extractor.runExtractor({
|
||||
orderNumbers: orderNumberList
|
||||
})
|
||||
|
||||
if (response.success && response.data) {
|
||||
const { data } = response
|
||||
addLog(
|
||||
'success',
|
||||
`提取完成:下载 ${data.downloadedFiles.length} 个文件,共 ${data.recordCount} 条记录`
|
||||
)
|
||||
if (data.errors.length > 0) {
|
||||
addLog('warning', `存在 ${data.errors.length} 个错误`)
|
||||
// Log each error detail for debugging
|
||||
data.errors.forEach((err, index) => {
|
||||
addLog('error', `错误 ${index + 1}/${data.errors.length}: ${err}`)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
setState({ loading: false, data: null, error: result.error || 'Unknown error' })
|
||||
return null
|
||||
setError(response.error || '提取失败')
|
||||
addLog('error', response.error || '提取失败')
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
setState({ loading: false, data: null, error: message })
|
||||
return null
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : '发生未知错误'
|
||||
setError(errMsg)
|
||||
addLog('error', errMsg)
|
||||
} finally {
|
||||
setRunning(false)
|
||||
setProgress(null)
|
||||
setComplete(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setState({ loading: false, data: null, error: null })
|
||||
}, [])
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
execute,
|
||||
reset
|
||||
isRunning,
|
||||
progress,
|
||||
error,
|
||||
logs,
|
||||
isComplete,
|
||||
startExtraction,
|
||||
clearLogs,
|
||||
setError,
|
||||
setComplete,
|
||||
resetState
|
||||
}
|
||||
}
|
||||
|
||||
export default useExtractor
|
||||
|
||||
156
src/renderer/src/hooks/useLogger.ts
Normal file
156
src/renderer/src/hooks/useLogger.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { useRef, useCallback } from 'react'
|
||||
import type { LogLevel } from '../../../shared/ipc-channels'
|
||||
|
||||
/**
|
||||
* Logger interface for renderer process
|
||||
* Provides type-safe logging with component context
|
||||
*/
|
||||
export interface RendererLogger {
|
||||
/**
|
||||
* Log a message at specified level
|
||||
*/
|
||||
log: (level: LogLevel, message: string, meta?: Record<string, unknown>) => void
|
||||
/**
|
||||
* Log an info level message (business operations)
|
||||
*/
|
||||
info: (message: string, meta?: Record<string, unknown>) => void
|
||||
/**
|
||||
* Log a warning level message (recoverable issues)
|
||||
*/
|
||||
warn: (message: string, meta?: Record<string, unknown>) => void
|
||||
/**
|
||||
* Log an error level message (failures)
|
||||
*/
|
||||
error: (message: string, meta?: Record<string, unknown>) => void
|
||||
/**
|
||||
* Log a debug level message (technical details)
|
||||
*/
|
||||
debug: (message: string, meta?: Record<string, unknown>) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* React Hook for logging from renderer process to main process Winston logger
|
||||
*
|
||||
* @param context - Component or feature context for log messages
|
||||
* @returns Logger instance with component context
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* function MyComponent() {
|
||||
* const logger = useLogger('MyComponent')
|
||||
*
|
||||
* const handleClick = () => {
|
||||
* logger.info('User clicked button', { buttonId: 'submit' })
|
||||
* }
|
||||
*
|
||||
* const handleError = (err: Error) => {
|
||||
* logger.error('Operation failed', { error: err.message })
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function useLogger(context: string): RendererLogger {
|
||||
// Use ref to store context to avoid recreating logger on re-renders
|
||||
const contextRef = useRef(context)
|
||||
contextRef.current = context
|
||||
|
||||
// Create stable logger instance using useCallback
|
||||
const logger = useCallback((level: LogLevel, message: string, meta?: Record<string, unknown>) => {
|
||||
// Check if window.electron is available (safety check)
|
||||
if (typeof window !== 'undefined' && window.electron?.logger?.log) {
|
||||
window.electron.logger.log(level, message, {
|
||||
...meta,
|
||||
context: contextRef.current
|
||||
})
|
||||
} else {
|
||||
// Fallback to console in development if IPC not available
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
const consoleMethod = console[level] || console.log
|
||||
consoleMethod(`[${contextRef.current}] ${message}`, meta || '')
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Return memoized logger methods
|
||||
return {
|
||||
log: logger,
|
||||
info: useCallback(
|
||||
(message: string, meta?: Record<string, unknown>) => {
|
||||
logger('info', message, meta)
|
||||
},
|
||||
[logger]
|
||||
),
|
||||
warn: useCallback(
|
||||
(message: string, meta?: Record<string, unknown>) => {
|
||||
logger('warn', message, meta)
|
||||
},
|
||||
[logger]
|
||||
),
|
||||
error: useCallback(
|
||||
(message: string, meta?: Record<string, unknown>) => {
|
||||
logger('error', message, meta)
|
||||
},
|
||||
[logger]
|
||||
),
|
||||
debug: useCallback(
|
||||
(message: string, meta?: Record<string, unknown>) => {
|
||||
logger('debug', message, meta)
|
||||
},
|
||||
[logger]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* FPS monitoring utility for detecting UI lag from excessive logging
|
||||
*
|
||||
* @param threshold - FPS threshold below which to warn (default: 30)
|
||||
* @param logger - Logger instance to use for warnings
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* useEffect(() => {
|
||||
* const stopMonitoring = monitorFps(30, logger)
|
||||
* return () => stopMonitoring()
|
||||
* }, [logger])
|
||||
* ```
|
||||
*/
|
||||
export function monitorFps(threshold: number = 30, logger: RendererLogger): () => void {
|
||||
let frames = 0
|
||||
let lastFpsCheck = 0
|
||||
let warningCooldown = 0
|
||||
let animationFrameId: number
|
||||
|
||||
const measureFps = (currentTime: number) => {
|
||||
frames++
|
||||
|
||||
// Check FPS every second
|
||||
const elapsed = currentTime - lastFpsCheck
|
||||
if (elapsed >= 1000) {
|
||||
const fps = Math.round((frames * 1000) / elapsed)
|
||||
|
||||
if (fps < threshold && warningCooldown <= 0) {
|
||||
logger.warn('Low FPS detected - logging may be causing UI lag', {
|
||||
fps,
|
||||
threshold,
|
||||
context: 'FPSMonitor'
|
||||
})
|
||||
warningCooldown = 5 // Don't warn again for 5 seconds
|
||||
}
|
||||
|
||||
warningCooldown = Math.max(0, warningCooldown - 1)
|
||||
frames = 0
|
||||
lastFpsCheck = currentTime
|
||||
}
|
||||
|
||||
animationFrameId = requestAnimationFrame(measureFps)
|
||||
}
|
||||
|
||||
// Start monitoring
|
||||
animationFrameId = requestAnimationFrame(measureFps)
|
||||
|
||||
// Return cleanup function
|
||||
return () => {
|
||||
cancelAnimationFrame(animationFrameId)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,5 @@
|
||||
/**
|
||||
* IPC Hook for Validation operations
|
||||
*
|
||||
* Provides a React-friendly interface for validation IPC calls
|
||||
* with loading state, error handling, and data management.
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
// Types based on validation types
|
||||
interface ValidationRequest {
|
||||
mode: 'database_full' | 'database_filtered'
|
||||
productionIdFile?: string
|
||||
@@ -52,9 +44,6 @@ interface UseValidationReturn extends UseValidationState {
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for validation operations
|
||||
*/
|
||||
export function useValidation(): UseValidationReturn {
|
||||
const [state, setState] = useState<UseValidationState>({
|
||||
loading: false,
|
||||
@@ -66,68 +55,73 @@ export function useValidation(): UseValidationReturn {
|
||||
const validate = useCallback(
|
||||
async (request: ValidationRequest): Promise<ValidationResponse | null> => {
|
||||
setState((prev) => ({ ...prev, loading: true, error: null }))
|
||||
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('validation:validate', request)
|
||||
|
||||
if (result.success) {
|
||||
setState({
|
||||
loading: false,
|
||||
data: result.results || null,
|
||||
stats: result.stats || null,
|
||||
error: null
|
||||
})
|
||||
return result
|
||||
} else {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: result.error || 'Validation failed'
|
||||
}))
|
||||
return result
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
setState((prev) => ({ ...prev, loading: false, error: message }))
|
||||
return null
|
||||
const response = await window.electron.validation.validate(request)
|
||||
if (!response.success || !response.data) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: response.error || 'Validation failed'
|
||||
}))
|
||||
return response.success ? null : { success: false, error: response.error }
|
||||
}
|
||||
|
||||
const result = response.data as ValidationResponse
|
||||
if (!result.success) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: result.error || 'Validation failed'
|
||||
}))
|
||||
return result
|
||||
}
|
||||
|
||||
setState({
|
||||
loading: false,
|
||||
data: result.results || null,
|
||||
stats: result.stats || null,
|
||||
error: null
|
||||
})
|
||||
return result
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const setSharedProductionIds = useCallback(async (ids: string[]): Promise<void> => {
|
||||
try {
|
||||
await window.electron.ipcRenderer.invoke('validation:setSharedProductionIds', ids)
|
||||
} catch (error) {
|
||||
console.error('Failed to set shared production IDs:', error)
|
||||
}
|
||||
await window.electron.validation.setSharedProductionIds(ids)
|
||||
}, [])
|
||||
|
||||
const getSharedProductionIds = useCallback(async (): Promise<string[]> => {
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('validation:getSharedProductionIds')
|
||||
return result?.productionIds || []
|
||||
} catch {
|
||||
const result = await window.electron.validation.getSharedProductionIds()
|
||||
if (!result.success || !result.data) {
|
||||
return []
|
||||
}
|
||||
const payload = result.data as { productionIds?: string[] }
|
||||
return payload.productionIds || []
|
||||
}, [])
|
||||
|
||||
const getCleanerData = useCallback(async (): Promise<{
|
||||
orderNumbers: string[]
|
||||
materialCodes: string[]
|
||||
} | null> => {
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke('validation:getCleanerData')
|
||||
if (result.success) {
|
||||
return {
|
||||
orderNumbers: result.orderNumbers || [],
|
||||
materialCodes: result.materialCodes || []
|
||||
}
|
||||
}
|
||||
const result = await window.electron.validation.getCleanerData()
|
||||
if (!result.success || !result.data) {
|
||||
return null
|
||||
} catch {
|
||||
}
|
||||
|
||||
const payload = result.data as {
|
||||
success?: boolean
|
||||
orderNumbers?: string[]
|
||||
materialCodes?: string[]
|
||||
}
|
||||
|
||||
if (payload.success === false) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
orderNumbers: payload.orderNumbers || [],
|
||||
materialCodes: payload.materialCodes || []
|
||||
}
|
||||
}, [])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import React from 'react'
|
||||
import {
|
||||
Play,
|
||||
ToggleLeft,
|
||||
@@ -13,304 +13,76 @@ import {
|
||||
Eye,
|
||||
HardDrive,
|
||||
Settings2,
|
||||
FileSpreadsheet
|
||||
FileSpreadsheet,
|
||||
FileText
|
||||
} from 'lucide-react'
|
||||
import MaterialTypeManagementDialog from '../components/MaterialTypeManagementDialog'
|
||||
|
||||
/**
|
||||
* Material validation result interface
|
||||
*/
|
||||
interface ValidationResult {
|
||||
materialName: string
|
||||
materialCode: string
|
||||
specification: string
|
||||
model: string
|
||||
managerName: string
|
||||
isMarkedForDeletion: boolean
|
||||
matchedTypeKeyword?: string
|
||||
}
|
||||
import ExecutionReportDialog from '../components/ExecutionReportDialog'
|
||||
import ReportViewerDialog from '../components/ReportViewerDialog'
|
||||
import { ConfirmDialog } from '../components/ui/ConfirmDialog'
|
||||
import { useCleaner } from '../hooks/useCleaner'
|
||||
|
||||
const CleanerPage: React.FC = () => {
|
||||
// Authentication & permissions
|
||||
const [isAdmin, setIsAdmin] = useState(false)
|
||||
const [currentUsername, setCurrentUsername] = useState<string>('')
|
||||
const typeManagementButtonRef = React.useRef<HTMLButtonElement>(null)
|
||||
const executeButtonRef = React.useRef<HTMLButtonElement>(null)
|
||||
|
||||
// State with sessionStorage persistence
|
||||
const [dryRun, setDryRun] = useState(() => {
|
||||
const saved = sessionStorage.getItem('cleaner_dryRun')
|
||||
return saved ? saved === 'true' : true
|
||||
})
|
||||
const {
|
||||
isAdmin,
|
||||
currentUsername,
|
||||
dryRun,
|
||||
setDryRun,
|
||||
valMode,
|
||||
setValMode,
|
||||
validationResults,
|
||||
selectedItems,
|
||||
setSelectedItems,
|
||||
setHiddenItems,
|
||||
managers,
|
||||
selectedManagers,
|
||||
setSelectedManagers,
|
||||
isRunning,
|
||||
isExecuting,
|
||||
isValidationRunning,
|
||||
isExporting,
|
||||
isTypeDialogOpen,
|
||||
setIsTypeDialogOpen,
|
||||
headless,
|
||||
setHeadless,
|
||||
processConcurrency,
|
||||
updateProcessConcurrency,
|
||||
showSettingsMenu,
|
||||
setShowSettingsMenu,
|
||||
filteredResults,
|
||||
isReportDialogOpen,
|
||||
setIsReportDialogOpen,
|
||||
reportData,
|
||||
editingCell,
|
||||
editValue,
|
||||
setEditValue,
|
||||
inputRef,
|
||||
startEdit,
|
||||
saveEdit,
|
||||
cancelEdit,
|
||||
handleAssignManagerOnSelect,
|
||||
progress,
|
||||
startTime,
|
||||
resetStartTime,
|
||||
handleValidation,
|
||||
handleCheckboxToggle,
|
||||
handleConfirmDeletion,
|
||||
handleExecuteDeletion,
|
||||
handleExportResults,
|
||||
confirmDialog
|
||||
} = useCleaner()
|
||||
|
||||
const [valMode, setValMode] = useState<'full' | 'filtered'>(() => {
|
||||
const saved = sessionStorage.getItem('cleaner_validationMode')
|
||||
return saved === 'full' ? 'full' : 'filtered'
|
||||
})
|
||||
|
||||
// Validation state
|
||||
const [validationResults, setValidationResults] = useState<ValidationResult[]>([])
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set())
|
||||
const [hiddenItems, setHiddenItems] = useState<Set<string>>(new Set())
|
||||
const [managers, setManagers] = useState<string[]>([])
|
||||
const [selectedManagers, setSelectedManagers] = useState<Set<string>>(new Set())
|
||||
|
||||
// Execution state
|
||||
const [isRunning, setIsRunning] = useState(false)
|
||||
const [isValidationRunning, setIsValidationRunning] = useState(false)
|
||||
const [isExporting, setIsExporting] = useState(false)
|
||||
|
||||
// Shared Production IDs state
|
||||
const [sharedProductionIdsCount, setSharedProductionIdsCount] = useState(0)
|
||||
console.log(sharedProductionIdsCount)
|
||||
|
||||
// Material type management dialog state
|
||||
const [isTypeDialogOpen, setIsTypeDialogOpen] = useState(false)
|
||||
|
||||
// Check admin status and get shared Production IDs on mount
|
||||
React.useEffect(() => {
|
||||
const initializePage = async () => {
|
||||
try {
|
||||
const admin = await window.electron.auth.isAdmin()
|
||||
const user = await window.electron.auth.getCurrentUser()
|
||||
setIsAdmin(admin)
|
||||
if (user && user.userInfo) {
|
||||
setCurrentUsername(user.userInfo.username)
|
||||
if (!admin) {
|
||||
setSelectedManagers(new Set([user.userInfo.username]))
|
||||
}
|
||||
}
|
||||
|
||||
// Load managers
|
||||
if (admin) {
|
||||
const resp = await window.electron.materials.getManagers()
|
||||
setManagers(resp.managers)
|
||||
setSelectedManagers(new Set(resp.managers))
|
||||
}
|
||||
|
||||
// Get shared Production IDs
|
||||
const result = await window.electron.validation.getSharedProductionIds()
|
||||
setSharedProductionIdsCount(result.productionIds.length)
|
||||
} catch (err) {
|
||||
console.error('Initialization failed:', err)
|
||||
}
|
||||
}
|
||||
initializePage()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
sessionStorage.setItem('cleaner_dryRun', dryRun.toString())
|
||||
}, [dryRun])
|
||||
|
||||
useEffect(() => {
|
||||
sessionStorage.setItem('cleaner_validationMode', valMode)
|
||||
}, [valMode])
|
||||
|
||||
// Filter validation results by selected managers and hidden items
|
||||
const filteredResults = React.useMemo(() => {
|
||||
let results = validationResults
|
||||
if (!isAdmin && currentUsername) {
|
||||
results = results.filter((r) => r.managerName === currentUsername || !r.managerName)
|
||||
} else if (managers.length > 0 && selectedManagers.size > 0) {
|
||||
results = results.filter((r) => selectedManagers.has(r.managerName) || !r.managerName)
|
||||
}
|
||||
results = results.filter((r) => !hiddenItems.has(r.materialCode))
|
||||
return results
|
||||
}, [validationResults, isAdmin, currentUsername, managers, selectedManagers, hiddenItems])
|
||||
|
||||
// Handlers
|
||||
const handleValidation = async () => {
|
||||
setIsValidationRunning(true)
|
||||
setValidationResults([])
|
||||
setSelectedItems(new Set())
|
||||
setHiddenItems(new Set())
|
||||
|
||||
try {
|
||||
const response = await window.electron.validation.validate({
|
||||
mode: valMode === 'full' ? 'database_full' : 'database_filtered',
|
||||
useSharedProductionIds: valMode === 'filtered'
|
||||
})
|
||||
|
||||
if (response.success && response.results) {
|
||||
setValidationResults(response.results)
|
||||
const markedCodes = new Set(
|
||||
response.results.filter((r) => r.isMarkedForDeletion).map((r) => r.materialCode)
|
||||
)
|
||||
setSelectedItems(markedCodes)
|
||||
|
||||
if (isAdmin) {
|
||||
const uniqueManagers = new Set(response.results.map((r) => r.managerName).filter(Boolean))
|
||||
setManagers([...uniqueManagers])
|
||||
setSelectedManagers(uniqueManagers)
|
||||
}
|
||||
} else {
|
||||
alert(response.error || '校验失败')
|
||||
}
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : '校验过程中发生未知错误')
|
||||
} finally {
|
||||
setIsValidationRunning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCheckboxToggle = (materialCode: string) => {
|
||||
setSelectedItems((prev) => {
|
||||
const newSet = new Set(prev)
|
||||
if (newSet.has(materialCode)) newSet.delete(materialCode)
|
||||
else newSet.add(materialCode)
|
||||
return newSet
|
||||
})
|
||||
}
|
||||
|
||||
const handleConfirmDeletion = async () => {
|
||||
// For non-admin users, only process visible filtered results
|
||||
// For admin users, process all validation results
|
||||
const resultsToProcess = isAdmin ? validationResults : filteredResults
|
||||
|
||||
if (resultsToProcess.length === 0) return alert('没有可处理的数据')
|
||||
|
||||
const materialsToUpsert: { materialCode: string; managerName: string }[] = []
|
||||
const materialsToDelete: string[] = []
|
||||
const missingManager: string[] = []
|
||||
|
||||
for (const result of resultsToProcess) {
|
||||
if (!result.materialCode?.trim()) continue
|
||||
|
||||
const code = result.materialCode.trim()
|
||||
if (selectedItems.has(code)) {
|
||||
if (!result.managerName?.trim()) missingManager.push(code)
|
||||
else materialsToUpsert.push({ materialCode: code, managerName: result.managerName.trim() })
|
||||
} else {
|
||||
materialsToDelete.push(code)
|
||||
}
|
||||
}
|
||||
|
||||
if (missingManager.length > 0) {
|
||||
alert(
|
||||
`以下已勾选的记录缺少负责人信息,无法保存:\n\n${missingManager.slice(0, 10).join('\n')}`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (materialsToUpsert.length === 0 && materialsToDelete.length === 0)
|
||||
return alert('没有需要处理的记录')
|
||||
|
||||
const confirmParts: string[] = []
|
||||
if (materialsToUpsert.length > 0)
|
||||
confirmParts.push(`写入/更新 ${materialsToUpsert.length} 条记录`)
|
||||
if (materialsToDelete.length > 0) confirmParts.push(`删除 ${materialsToDelete.length} 条记录`)
|
||||
|
||||
if (!window.confirm(`确认以下操作吗?\n\n${confirmParts.join('\n')}`)) return
|
||||
|
||||
try {
|
||||
setIsRunning(true)
|
||||
let msgParts: string[] = []
|
||||
|
||||
if (materialsToUpsert.length > 0) {
|
||||
const res = await window.electron.materials.upsertBatch(materialsToUpsert)
|
||||
if (!res.success) throw new Error(res.error || '写入物料失败')
|
||||
msgParts.push(`写入/更新成功:${res.stats?.success || 0} 条`)
|
||||
}
|
||||
|
||||
if (materialsToDelete.length > 0) {
|
||||
const res = await window.electron.materials.delete(materialsToDelete)
|
||||
if (!res.success) throw new Error(res.error || '删除物料失败')
|
||||
msgParts.push(`删除成功:${res.count || 0} 条`)
|
||||
}
|
||||
|
||||
alert(`操作完成!\n\n${msgParts.join('\n')}`)
|
||||
|
||||
// Reload managers if admin
|
||||
if (isAdmin) {
|
||||
const resp = await window.electron.materials.getManagers()
|
||||
setManagers(resp.managers)
|
||||
}
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : '操作失败')
|
||||
} finally {
|
||||
setIsRunning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleExecuteDeletion = async () => {
|
||||
if (!dryRun) {
|
||||
if (!window.confirm('警告:正式执行将删除 ERP 系统中的物料数据,是否继续?')) return
|
||||
}
|
||||
|
||||
setIsRunning(true)
|
||||
try {
|
||||
const cleanerDataResult = await window.electron.validation.getCleanerData()
|
||||
if (!cleanerDataResult.success) {
|
||||
throw new Error(cleanerDataResult.error || '获取清理数据失败')
|
||||
}
|
||||
|
||||
const orderNumberList = cleanerDataResult.orderNumbers || []
|
||||
const materialCodeList = cleanerDataResult.materialCodes || []
|
||||
|
||||
if (orderNumberList.length === 0)
|
||||
throw new Error('没有订单号数据。请先到数据提取页面输入 Production ID。')
|
||||
if (materialCodeList.length === 0)
|
||||
throw new Error('没有物料代码数据。请确认已在物料清理界面确认要删除的物料。')
|
||||
|
||||
const response = await window.electron.cleaner.runCleaner({
|
||||
orderNumbers: orderNumberList,
|
||||
materialCodes: materialCodeList,
|
||||
dryRun
|
||||
})
|
||||
|
||||
if (response.success && response.data) {
|
||||
let msg = `清理执行完毕:\n处理订单: ${response.data.ordersProcessed}\n删除物料: ${response.data.materialsDeleted}\n跳过物料: ${response.data.materialsSkipped}`
|
||||
if (response.data.errors.length) {
|
||||
msg += `\n错误: ${response.data.errors.join(', ')}`
|
||||
}
|
||||
alert(msg)
|
||||
} else {
|
||||
throw new Error(response.error || '清理失败')
|
||||
}
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : '发生未知错误')
|
||||
} finally {
|
||||
setIsRunning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleExportResults = async () => {
|
||||
if (filteredResults.length === 0) {
|
||||
alert('没有数据可导出')
|
||||
return
|
||||
}
|
||||
|
||||
setIsExporting(true)
|
||||
try {
|
||||
// Prepare export data from filtered results
|
||||
const exportItems = filteredResults.map((result) => ({
|
||||
materialName: result.materialName,
|
||||
materialCode: result.materialCode,
|
||||
specification: result.specification || '',
|
||||
model: result.model || '',
|
||||
managerName: result.managerName || '',
|
||||
isMarkedForDeletion: result.isMarkedForDeletion,
|
||||
isSelected: selectedItems.has(result.materialCode)
|
||||
}))
|
||||
|
||||
const response = await window.electron.cleaner.exportResults(exportItems)
|
||||
|
||||
if (response.success) {
|
||||
alert(`导出成功!\n文件已保存到:${response.filePath}`)
|
||||
} else {
|
||||
throw new Error(response.error || '导出失败')
|
||||
}
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : '导出过程中发生错误')
|
||||
} finally {
|
||||
setIsExporting(false)
|
||||
}
|
||||
}
|
||||
const [isReportViewerOpen, setIsReportViewerOpen] = React.useState(false)
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col xl:flex-row gap-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
{/* 左栏:数据源与执行控制区 */}
|
||||
<div className="xl:w-[380px] flex-shrink-0 flex flex-col gap-5">
|
||||
{/* 1. 数据来源选择 (仅 Admin 可见) */}
|
||||
{isAdmin && (
|
||||
{/* 左栏:数据源与执行控制区 (仅 Admin 可见) */}
|
||||
{isAdmin && (
|
||||
<div className="w-full xl:w-[380px] flex-shrink-0 flex flex-col gap-5 xl:self-start overflow-auto">
|
||||
{/* 1. 数据来源选择 */}
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
|
||||
<h3 className="text-base font-semibold mb-4 flex items-center gap-2 text-slate-800">
|
||||
<DatabaseZap size={18} className="text-blue-500" />
|
||||
@@ -361,10 +133,8 @@ const CleanerPage: React.FC = () => {
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 2. 负责人筛选 (仅 Admin 可见) */}
|
||||
{isAdmin && (
|
||||
{/* 2. 负责人筛选 */}
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-base font-semibold flex items-center gap-2 text-slate-800">
|
||||
@@ -414,43 +184,24 @@ const CleanerPage: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 3. 基础执行控制区 */}
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-200 p-5 mt-auto">
|
||||
{isAdmin && (
|
||||
<div className="flex items-center justify-between bg-amber-50/50 p-3 rounded-lg border border-amber-200 mb-4">
|
||||
<div>
|
||||
<div className="font-semibold text-sm text-amber-900">预览模式 (Dry-Run)</div>
|
||||
<div className="text-xs text-amber-700/80 mt-0.5">
|
||||
仅执行页面操作定位,不保存更改
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setDryRun(!dryRun)}
|
||||
className={`transition-colors flex-shrink-0 ml-4 ${dryRun ? 'text-amber-500' : 'text-slate-300'}`}
|
||||
>
|
||||
{dryRun ? <ToggleRight size={40} /> : <ToggleLeft size={40} />}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2.5">
|
||||
<button
|
||||
onClick={handleValidation}
|
||||
disabled={isValidationRunning}
|
||||
className="w-full bg-slate-100 hover:bg-slate-200 text-slate-800 py-3 rounded-lg font-medium transition-colors shadow-sm flex justify-center items-center gap-2 border border-slate-200 disabled:opacity-50"
|
||||
>
|
||||
<Search size={18} /> {isValidationRunning ? '正在获取...' : '获取并校验物料状态'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 右栏:结果表格与工具栏 */}
|
||||
<div className="flex-1 bg-white rounded-xl shadow-sm border border-slate-200 flex flex-col overflow-hidden min-h-[500px]">
|
||||
<div className="flex-1 bg-white rounded-xl shadow-sm border border-slate-200 flex flex-col overflow-hidden">
|
||||
{/* 获取物料状态按钮 */}
|
||||
<div className="p-4 border-b border-slate-200 flex-shrink-0">
|
||||
<button
|
||||
onClick={handleValidation}
|
||||
disabled={isValidationRunning}
|
||||
className="w-full bg-slate-100 hover:bg-slate-200 text-slate-800 py-3 rounded-lg font-medium transition-colors shadow-sm flex justify-center items-center gap-2 border border-slate-200 disabled:opacity-50"
|
||||
>
|
||||
<Search size={18} /> {isValidationRunning ? '正在获取...' : '获取并校验物料状态'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 顶部操作条 */}
|
||||
<div className="bg-slate-50 border-b border-slate-200 px-4 py-3 flex justify-between items-center">
|
||||
<div className="bg-slate-50 border-b border-slate-200 px-4 py-3 flex justify-between items-center flex-shrink-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={() => setSelectedItems(new Set(filteredResults.map((r) => r.materialCode)))}
|
||||
@@ -510,6 +261,7 @@ const CleanerPage: React.FC = () => {
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setIsTypeDialogOpen(true)}
|
||||
ref={typeManagementButtonRef}
|
||||
className="text-xs bg-white border border-slate-300 text-slate-700 px-3 py-1.5 rounded shadow-sm hover:bg-slate-50 flex items-center gap-1.5"
|
||||
>
|
||||
<Settings2 size={14} /> 类型管理
|
||||
@@ -521,11 +273,17 @@ const CleanerPage: React.FC = () => {
|
||||
>
|
||||
<FileSpreadsheet size={14} /> {isExporting ? '导出中...' : '导出结果'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsReportViewerOpen(true)}
|
||||
className="text-xs bg-emerald-50 border border-emerald-200 text-emerald-700 px-3 py-1.5 rounded shadow-sm hover:bg-emerald-100 flex items-center gap-1.5 font-medium transition-colors"
|
||||
>
|
||||
<FileText size={14} /> 查看报告
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 表格区域 */}
|
||||
<div className="flex-1 overflow-auto">
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<table className="w-full text-left text-sm whitespace-nowrap table-fixed">
|
||||
<thead className="bg-slate-100 text-slate-600 sticky top-0 shadow-sm z-10 text-xs font-semibold">
|
||||
<tr>
|
||||
@@ -549,13 +307,15 @@ const CleanerPage: React.FC = () => {
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredResults.map((result) => {
|
||||
filteredResults.map((result, rowIndex) => {
|
||||
const isChecked = selectedItems.has(result.materialCode)
|
||||
const trClass = isChecked ? 'bg-blue-50/30' : 'hover:bg-slate-50'
|
||||
const noManager = !result.managerName?.trim()
|
||||
const managerCellClass = noManager
|
||||
? 'text-amber-500 text-xs italic'
|
||||
: 'text-slate-700'
|
||||
const isEditingManager =
|
||||
editingCell?.rowIndex === rowIndex && editingCell?.field === 'managerName'
|
||||
|
||||
return (
|
||||
<tr
|
||||
@@ -565,13 +325,23 @@ const CleanerPage: React.FC = () => {
|
||||
<td className="px-4 py-3 text-center truncate">
|
||||
{isChecked ? (
|
||||
<CheckSquare
|
||||
onClick={() => handleCheckboxToggle(result.materialCode)}
|
||||
onClick={() => {
|
||||
handleCheckboxToggle(result.materialCode)
|
||||
if (!isAdmin) {
|
||||
handleAssignManagerOnSelect(result.materialCode)
|
||||
}
|
||||
}}
|
||||
size={16}
|
||||
className="text-blue-600 inline cursor-pointer"
|
||||
/>
|
||||
) : (
|
||||
<Square
|
||||
onClick={() => handleCheckboxToggle(result.materialCode)}
|
||||
onClick={() => {
|
||||
handleCheckboxToggle(result.materialCode)
|
||||
if (!isAdmin) {
|
||||
handleAssignManagerOnSelect(result.materialCode)
|
||||
}
|
||||
}}
|
||||
size={16}
|
||||
className="text-slate-300 inline cursor-pointer"
|
||||
/>
|
||||
@@ -603,9 +373,43 @@ const CleanerPage: React.FC = () => {
|
||||
</td>
|
||||
<td
|
||||
className={`px-4 py-3 truncate ${managerCellClass}`}
|
||||
title={result.managerName || '空(待分配)'}
|
||||
title={result.managerName || '空 (待分配)'}
|
||||
>
|
||||
{result.managerName || '空(待分配)'}
|
||||
{isAdmin && isEditingManager ? (
|
||||
<select
|
||||
ref={inputRef as React.Ref<HTMLSelectElement>}
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
onBlur={saveEdit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') saveEdit()
|
||||
if (e.key === 'Escape') cancelEdit()
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="w-full px-2 py-1 border border-blue-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 text-xs"
|
||||
>
|
||||
<option value="">选择负责人</option>
|
||||
{managers.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : isAdmin ? (
|
||||
<div
|
||||
className="min-h-[24px] cursor-text"
|
||||
onDoubleClick={(e) => {
|
||||
e.stopPropagation()
|
||||
startEdit(rowIndex, 'managerName')
|
||||
}}
|
||||
>
|
||||
{result.managerName || (
|
||||
<span className="text-slate-400 italic">双击编辑</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
result.managerName || '空 (待分配)'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
@@ -616,37 +420,89 @@ const CleanerPage: React.FC = () => {
|
||||
</div>
|
||||
|
||||
{/* 底部状态与执行区 */}
|
||||
<div className="bg-white border-t border-slate-200 p-4 flex justify-between items-center shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)] z-10">
|
||||
<div className="bg-white border-t border-slate-200 p-4 flex justify-between items-center shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)] z-10 flex-shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="text-sm text-slate-600 font-medium">
|
||||
共计 {filteredResults.length} 条记录 | 已选中{' '}
|
||||
<span className="text-blue-600">{selectedItems.size}</span> 条
|
||||
</div>
|
||||
{isAdmin && dryRun && (
|
||||
<span className="text-xs bg-amber-100 text-amber-700 px-2 py-1 rounded border border-amber-200">
|
||||
当前为预览模式
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => {
|
||||
setValidationResults([])
|
||||
setSelectedItems(new Set())
|
||||
setHiddenItems(new Set())
|
||||
}}
|
||||
className="text-sm text-slate-600 bg-slate-100 hover:bg-slate-200 px-5 py-2.5 rounded-lg font-medium transition-colors"
|
||||
>
|
||||
重置列表
|
||||
</button>
|
||||
<div className="relative" data-settings-menu>
|
||||
<button
|
||||
onClick={() => setShowSettingsMenu(!showSettingsMenu)}
|
||||
className="text-sm text-slate-600 bg-slate-100 hover:bg-slate-200 px-5 py-2.5 rounded-lg font-medium transition-colors flex items-center gap-2"
|
||||
>
|
||||
<Settings2 size={16} /> 执行设置
|
||||
</button>
|
||||
{showSettingsMenu && (
|
||||
<div className="absolute bottom-full right-0 mb-2 bg-white rounded-lg shadow-lg border border-slate-200 py-3 px-4 min-w-[280px] z-50">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-slate-800">预览模式 (Dry-Run)</div>
|
||||
<div className="text-xs text-slate-500 mt-0.5">
|
||||
仅执行页面操作定位,不保存更改
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setDryRun(!dryRun)}
|
||||
className={`transition-colors flex-shrink-0 ml-4 ${dryRun ? 'text-amber-500' : 'text-slate-300'}`}
|
||||
>
|
||||
{dryRun ? <ToggleRight size={32} /> : <ToggleLeft size={32} />}
|
||||
</button>
|
||||
</div>
|
||||
<div className="border-t border-slate-100 pt-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-slate-800">
|
||||
后台模式 (Headless)
|
||||
</div>
|
||||
<div className="text-xs text-slate-500 mt-0.5">
|
||||
浏览器在后台运行,不显示界面
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setHeadless(!headless)}
|
||||
className={`transition-colors flex-shrink-0 ml-4 ${headless ? 'text-blue-500' : 'text-slate-300'}`}
|
||||
>
|
||||
{headless ? <ToggleRight size={32} /> : <ToggleLeft size={32} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t border-slate-100 pt-3 space-y-3">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-slate-800">并行处理数量</div>
|
||||
<div className="text-xs text-slate-500 mt-0.5">
|
||||
同时处理详情页数量,范围 1-20
|
||||
</div>
|
||||
<div className="mt-2 flex items-center gap-3">
|
||||
<input
|
||||
type="range"
|
||||
min={1}
|
||||
max={20}
|
||||
value={processConcurrency}
|
||||
onChange={(e) => updateProcessConcurrency(Number(e.target.value))}
|
||||
className="flex-1 h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-blue-600"
|
||||
/>
|
||||
<span className="text-sm font-medium text-slate-700 w-8 text-center">
|
||||
{processConcurrency}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleExecuteDeletion}
|
||||
disabled={isRunning || validationResults.length === 0}
|
||||
className={`${isAdmin && dryRun ? 'bg-amber-500 hover:bg-amber-600' : 'bg-red-600 hover:bg-red-700 shadow-red-500/30'} text-white px-8 py-2.5 rounded-lg font-medium shadow-md transition-all flex items-center gap-2 disabled:opacity-50`}
|
||||
ref={executeButtonRef}
|
||||
disabled={isRunning}
|
||||
className={`${dryRun ? 'bg-amber-500 hover:bg-amber-600' : 'bg-red-600 hover:bg-red-700 shadow-red-500/30'} text-white px-8 py-2.5 rounded-lg font-medium shadow-md transition-all flex items-center gap-2 disabled:opacity-50 w-[300px] justify-center`}
|
||||
>
|
||||
<Play size={18} fill="currentColor" />{' '}
|
||||
{isAdmin && dryRun ? '开始预览执行' : '正式执行 ERP 清理'}
|
||||
<Play size={18} fill="currentColor" /> {dryRun ? '开始预览执行' : '正式执行 ERP 清理'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -658,7 +514,39 @@ const CleanerPage: React.FC = () => {
|
||||
onClose={() => setIsTypeDialogOpen(false)}
|
||||
isAdmin={isAdmin}
|
||||
currentUsername={currentUsername}
|
||||
triggerRef={typeManagementButtonRef}
|
||||
/>
|
||||
|
||||
{/* Execution Report Dialog */}
|
||||
<ExecutionReportDialog
|
||||
isOpen={isReportDialogOpen}
|
||||
onClose={() => {
|
||||
setIsReportDialogOpen(false)
|
||||
resetStartTime()
|
||||
}}
|
||||
ordersProcessed={reportData?.ordersProcessed}
|
||||
materialsDeleted={reportData?.materialsDeleted}
|
||||
materialsSkipped={reportData?.materialsSkipped}
|
||||
errors={reportData?.errors}
|
||||
dryRun={dryRun}
|
||||
isExecuting={isExecuting}
|
||||
progress={progress}
|
||||
startTime={startTime}
|
||||
triggerRef={executeButtonRef}
|
||||
retriedOrders={reportData?.retriedOrders}
|
||||
successfulRetries={reportData?.successfulRetries}
|
||||
/>
|
||||
|
||||
{/* Report Viewer Dialog */}
|
||||
<ReportViewerDialog
|
||||
isOpen={isReportViewerOpen}
|
||||
onClose={() => setIsReportViewerOpen(false)}
|
||||
isAdmin={isAdmin}
|
||||
currentUsername={currentUsername}
|
||||
/>
|
||||
|
||||
{/* Confirmation Dialog */}
|
||||
{confirmDialog && <ConfirmDialog {...confirmDialog} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user