Commit 8c75caa2 by JOE S

Merge remote-tracking branch 'origin/dev' into chore/eslint

# Conflicts:
#	.prettierignore
#	internal/lint-configs/eslint-config/src/configs/typescript.ts
2 parents df641511 bf078635
Showing 202 changed files with 977 additions and 1112 deletions
name: 📚 Documentation name: 📚 Documentation
description: Report an issue with Vben Admin Website to help us make it better. description: Report an issue with Vben Admin Website to help us make it better.
title: 'Docs: ' title: "Docs: "
labels: [documentation] labels: [documentation]
body: body:
- type: markdown - type: markdown
......
name: ✨ New Feature Proposal name: ✨ New Feature Proposal
description: Propose a new feature to be added to Vben Admin description: Propose a new feature to be added to Vben Admin
title: 'FEATURE: ' title: "FEATURE: "
labels: ['enhancement: pending triage'] labels: ["enhancement: pending triage"]
body: body:
- type: markdown - type: markdown
attributes: attributes:
......
...@@ -67,10 +67,12 @@ jobs: ...@@ -67,10 +67,12 @@ jobs:
**作用**:安装 pnpm 包管理器 **作用**:安装 pnpm 包管理器
**版本来源**: **版本来源**:
- 优先使用 `package.json` 中 `packageManager` 字段指定的版本 - 优先使用 `package.json` 中 `packageManager` 字段指定的版本
- 示例:`"packageManager": "pnpm@9.0.0"` - 示例:`"packageManager": "pnpm@9.0.0"`
**优点**: **优点**:
- 确保使用正确的 pnpm 版本 - 确保使用正确的 pnpm 版本
- 避免版本不一致导致的问题 - 避免版本不一致导致的问题
...@@ -89,17 +91,20 @@ jobs: ...@@ -89,17 +91,20 @@ jobs:
**配置说明**: **配置说明**:
| 配置项 | 值 | 说明 | | 配置项 | 值 | 说明 |
|-------|---|------| | ------------------- | --------------- | ----------------------- |
| `node-version-file` | `.node-version` | 从文件读取 Node.js 版本 | | `node-version-file` | `.node-version` | 从文件读取 Node.js 版本 |
| `cache` | `pnpm` | 启用 pnpm 包缓存 | | `cache` | `pnpm` | 启用 pnpm 包缓存 |
**`.node-version` 文件**: **`.node-version` 文件**:
``` ```
20.11.0 20.11.0
``` ```
只需在文件中写入版本号,无需 `v` 前缀。 只需在文件中写入版本号,无需 `v` 前缀。
**缓存作用**: **缓存作用**:
- 第一次运行:下载并缓存 pnpm 包 - 第一次运行:下载并缓存 pnpm 包
- 后续运行:从缓存读取,大幅加速 - 后续运行:从缓存读取,大幅加速
...@@ -115,11 +120,13 @@ jobs: ...@@ -115,11 +120,13 @@ jobs:
``` ```
**作用**: **作用**:
- 获取 pnpm 包缓存存储目录 - 获取 pnpm 包缓存存储目录
- 存储到 `STORE_PATH` 环境变量 - 存储到 `STORE_PATH` 环境变量
- 供后续的缓存步骤使用 - 供后续的缓存步骤使用
**输出示例**: **输出示例**:
``` ```
STORE_PATH=/home/runner/.pnpm-store STORE_PATH=/home/runner/.pnpm-store
``` ```
...@@ -144,6 +151,7 @@ STORE_PATH=/home/runner/.pnpm-store ...@@ -144,6 +151,7 @@ STORE_PATH=/home/runner/.pnpm-store
**触发条件**:`github.ref_name == 'main'` **触发条件**:`github.ref_name == 'main'`
**缓存策略**: **缓存策略**:
- **缓存路径**:pnpm 包存储目录 - **缓存路径**:pnpm 包存储目录
- **缓存键**:`ubuntu-latest-pnpm-store-abc123def456` - **缓存键**:`ubuntu-latest-pnpm-store-abc123def456`
- 包含:操作系统 + 锁定文件的哈希值 - 包含:操作系统 + 锁定文件的哈希值
...@@ -152,6 +160,7 @@ STORE_PATH=/home/runner/.pnpm-store ...@@ -152,6 +160,7 @@ STORE_PATH=/home/runner/.pnpm-store
- 如果精确匹配失败,使用此模糊匹配 - 如果精确匹配失败,使用此模糊匹配
**优点**: **优点**:
- 保存缓存供后续使用 - 保存缓存供后续使用
- 新的依赖版本会触发缓存更新 - 新的依赖版本会触发缓存更新
- 避免使用过时的包 - 避免使用过时的包
...@@ -170,6 +179,7 @@ STORE_PATH=/home/runner/.pnpm-store ...@@ -170,6 +179,7 @@ STORE_PATH=/home/runner/.pnpm-store
**触发条件**:`github.ref_name != 'main'` **触发条件**:`github.ref_name != 'main'`
**行为**: **行为**:
- 只读取缓存,不写入 - 只读取缓存,不写入
- 使用模糊匹配查找最近的缓存 - 使用模糊匹配查找最近的缓存
- 加快特性分支的 CI 速度 - 加快特性分支的 CI 速度
...@@ -177,6 +187,7 @@ STORE_PATH=/home/runner/.pnpm-store ...@@ -177,6 +187,7 @@ STORE_PATH=/home/runner/.pnpm-store
**为什么这样设计**? **为什么这样设计**?
避免 main 分支上的多个 PR 并发运行时发生**缓存竞争**: 避免 main 分支上的多个 PR 并发运行时发生**缓存竞争**:
- 如果都写入缓存,可能导致缓存损坏 - 如果都写入缓存,可能导致缓存损坏
- 只有 main 分支写入,其他分支读取,保证缓存一致性 - 只有 main 分支写入,其他分支读取,保证缓存一致性
...@@ -193,10 +204,11 @@ STORE_PATH=/home/runner/.pnpm-store ...@@ -193,10 +204,11 @@ STORE_PATH=/home/runner/.pnpm-store
**参数说明**: **参数说明**:
| 参数 | 说明 | | 参数 | 说明 |
|-----|------| | ------------------- | ------------------------------------- |
| `--frozen-lockfile` | 不修改 `pnpm-lock.yaml`,确保版本一致 | | `--frozen-lockfile` | 不修改 `pnpm-lock.yaml`,确保版本一致 |
**作用**: **作用**:
- 根据 `pnpm-lock.yaml` 安装精确版本的依赖 - 根据 `pnpm-lock.yaml` 安装精确版本的依赖
- 适合 CI 环境,确保可重现的构建 - 适合 CI 环境,确保可重现的构建
- 如果缓存命中,此步骤极快 - 如果缓存命中,此步骤极快
...@@ -224,7 +236,7 @@ STORE_PATH=/home/runner/.pnpm-store ...@@ -224,7 +236,7 @@ STORE_PATH=/home/runner/.pnpm-store
### 缓存键示例 ### 缓存键示例
| pnpm-lock.yaml 变化 | 缓存键 | 缓存是否命中 | | pnpm-lock.yaml 变化 | 缓存键 | 缓存是否命中 |
|------------------|-------|-----------| | ------------------- | --------------------------------- | ------------------- |
| `dependencies` 改变 | `ubuntu-latest-pnpm-store-new123` | ❌ 新键,不命中 | | `dependencies` 改变 | `ubuntu-latest-pnpm-store-new123` | ❌ 新键,不命中 |
| 未改变 | `ubuntu-latest-pnpm-store-abc123` | ✅ 命中 | | 未改变 | `ubuntu-latest-pnpm-store-abc123` | ✅ 命中 |
| PR 中修改 | 使用模糊键 | ✅ 使用 main 的缓存 | | PR 中修改 | 使用模糊键 | ✅ 使用 main 的缓存 |
...@@ -329,7 +341,7 @@ jobs: ...@@ -329,7 +341,7 @@ jobs:
该 Action 被以下工作流使用: 该 Action 被以下工作流使用:
| 工作流文件 | 用途 | 位置 | | 工作流文件 | 用途 | 位置 |
|-----------|------|------| | ----------------------- | -------------- | ----------------------------------------- |
| `ci.yml` | 运行测试和构建 | `.github/workflows/ci.yml` | | `ci.yml` | 运行测试和构建 | `.github/workflows/ci.yml` |
| `build.yml` | 验证构建可行性 | `.github/workflows/build.yml` | | `build.yml` | 验证构建可行性 | `.github/workflows/build.yml` |
| `deploy.yml` | 部署前环境配置 | `.github/workflows/deploy.yml` | | `deploy.yml` | 部署前环境配置 | `.github/workflows/deploy.yml` |
...@@ -359,6 +371,7 @@ jobs: ...@@ -359,6 +371,7 @@ jobs:
### 修改 Node.js 版本 ### 修改 Node.js 版本
1. 编辑 `.node-version` 文件: 1. 编辑 `.node-version` 文件:
```bash ```bash
# 当前版本 # 当前版本
cat .node-version cat .node-version
...@@ -378,6 +391,7 @@ jobs: ...@@ -378,6 +391,7 @@ jobs:
### 修改 pnpm 版本 ### 修改 pnpm 版本
1. 更新 `package.json` 中的 `packageManager` 字段: 1. 更新 `package.json` 中的 `packageManager` 字段:
```json ```json
{ {
"packageManager": "pnpm@9.1.0" "packageManager": "pnpm@9.1.0"
...@@ -385,6 +399,7 @@ jobs: ...@@ -385,6 +399,7 @@ jobs:
``` ```
2. 更新到新版本: 2. 更新到新版本:
```bash ```bash
pnpm install -g pnpm@9.1.0 pnpm install -g pnpm@9.1.0
pnpm install --frozen-lockfile pnpm install --frozen-lockfile
...@@ -417,11 +432,13 @@ jobs: ...@@ -417,11 +432,13 @@ jobs:
**症状**:安装依赖速度很慢,每次都重新下载 **症状**:安装依赖速度很慢,每次都重新下载
**原因**: **原因**:
- `pnpm-lock.yaml` 频繁变化 - `pnpm-lock.yaml` 频繁变化
- 缓存过期(GitHub 默认 7 天) - 缓存过期(GitHub 默认 7 天)
- 操作系统不同(Linux、Windows 缓存分离) - 操作系统不同(Linux、Windows 缓存分离)
**解决方案**: **解决方案**:
```bash ```bash
# 检查 pnpm-lock.yaml 是否正确提交 # 检查 pnpm-lock.yaml 是否正确提交
git status pnpm-lock.yaml git status pnpm-lock.yaml
...@@ -438,10 +455,12 @@ git commit -m "fix: regenerate pnpm-lock" ...@@ -438,10 +455,12 @@ git commit -m "fix: regenerate pnpm-lock"
**症状**:工作流中 `node --version` 输出意外的版本 **症状**:工作流中 `node --version` 输出意外的版本
**原因**: **原因**:
- `.node-version` 文件不存在或格式错误 - `.node-version` 文件不存在或格式错误
- 缓存中有旧版本 - 缓存中有旧版本
**解决方案**: **解决方案**:
```bash ```bash
# 检查 .node-version 文件 # 检查 .node-version 文件
cat .node-version cat .node-version
...@@ -455,10 +474,12 @@ cat .node-version ...@@ -455,10 +474,12 @@ cat .node-version
**症状**:`Run pnpm install` 失败,提示权限不足 **症状**:`Run pnpm install` 失败,提示权限不足
**原因**: **原因**:
- 缓存目录权限问题 - 缓存目录权限问题
- 跨操作系统的缓存冲突 - 跨操作系统的缓存冲突
**解决方案**: **解决方案**:
```yaml ```yaml
# 在 action.yml 中添加权限修复 # 在 action.yml 中添加权限修复
- name: Fix cache permissions - name: Fix cache permissions
...@@ -473,7 +494,7 @@ cat .node-version ...@@ -473,7 +494,7 @@ cat .node-version
该 Action 的性能优化措施: 该 Action 的性能优化措施:
| 优化 | 效果 | 说明 | | 优化 | 效果 | 说明 |
|-----|------|------| | --------------- | ------------------------ | -------------------- |
| 缓存 pnpm store | 节省 50-80% 时间 | 依赖下载只发生一次 | | 缓存 pnpm store | 节省 50-80% 时间 | 依赖下载只发生一次 |
| 冻结锁定文件 | 100% 可重现构建 | 避免版本不一致 | | 冻结锁定文件 | 100% 可重现构建 | 避免版本不一致 |
| 主分支缓存写入 | 避免缓存竞争 | 多 PR 并发安全 | | 主分支缓存写入 | 避免缓存竞争 | 多 PR 并发安全 |
...@@ -482,7 +503,7 @@ cat .node-version ...@@ -482,7 +503,7 @@ cat .node-version
**典型执行时间**: **典型执行时间**:
| 场景 | 时间 | 说明 | | 场景 | 时间 | 说明 |
|-----|------|------| | -------- | -------- | ---------------- |
| 首次运行 | 2-3 分钟 | 下载并缓存所有包 | | 首次运行 | 2-3 分钟 | 下载并缓存所有包 |
| 依赖未变 | 20-30 秒 | 从缓存恢复 | | 依赖未变 | 20-30 秒 | 从缓存恢复 |
| 新增小包 | 40-50 秒 | 只下载新增包 | | 新增小包 | 40-50 秒 | 只下载新增包 |
...@@ -506,7 +527,7 @@ cat .node-version ...@@ -506,7 +527,7 @@ cat .node-version
本 Action 依赖的官方 Action: 本 Action 依赖的官方 Action:
| Action | 当前版本 | 检查更新 | | Action | 当前版本 | 检查更新 |
|--------|---------|---------| | -------------------- | -------- | ---------------------------------------------------------- |
| `pnpm/action-setup` | v4 | [releases](https://github.com/pnpm/action-setup/releases) | | `pnpm/action-setup` | v4 | [releases](https://github.com/pnpm/action-setup/releases) |
| `actions/setup-node` | v4 | [releases](https://github.com/actions/setup-node/releases) | | `actions/setup-node` | v4 | [releases](https://github.com/actions/setup-node/releases) |
| `actions/cache` | v4 | [releases](https://github.com/actions/cache/releases) | | `actions/cache` | v4 | [releases](https://github.com/actions/cache/releases) |
...@@ -514,17 +535,20 @@ cat .node-version ...@@ -514,17 +535,20 @@ cat .node-version
### 更新步骤 ### 更新步骤
1. **检查新版本**: 1. **检查新版本**:
```bash ```bash
# 访问上述链接检查是否有更新 # 访问上述链接检查是否有更新
``` ```
2. **测试新版本**: 2. **测试新版本**:
```yaml ```yaml
# 在测试分支中更新版本 # 在测试分支中更新版本
uses: pnpm/action-setup@v5 # 新版本 uses: pnpm/action-setup@v5 # 新版本
``` ```
3. **验证功能**: 3. **验证功能**:
```bash ```bash
# 确保工作流仍然正常运行 # 确保工作流仍然正常运行
``` ```
...@@ -541,12 +565,14 @@ cat .node-version ...@@ -541,12 +565,14 @@ cat .node-version
### ✅ 推荐做法 ### ✅ 推荐做法
1. **始终使用此 Action** 1. **始终使用此 Action**
```yaml ```yaml
# ✅ 好的做法 # ✅ 好的做法
- uses: ./.github/actions/setup-node - uses: ./.github/actions/setup-node
``` ```
2. **在所有需要 Node.js 的工作流中使用** 2. **在所有需要 Node.js 的工作流中使用**
```yaml ```yaml
# 测试工作流 # 测试工作流
- uses: ./.github/actions/setup-node - uses: ./.github/actions/setup-node
...@@ -567,6 +593,7 @@ cat .node-version ...@@ -567,6 +593,7 @@ cat .node-version
### ❌ 避免做法 ### ❌ 避免做法
1. **不要手动安装 Node.js** 1. **不要手动安装 Node.js**
```yaml ```yaml
# ❌ 避免 # ❌ 避免
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
...@@ -575,6 +602,7 @@ cat .node-version ...@@ -575,6 +602,7 @@ cat .node-version
``` ```
2. **不要跳过缓存** 2. **不要跳过缓存**
```yaml ```yaml
# ❌ 避免 # ❌ 避免
- run: pnpm install # 没有缓存优化 - run: pnpm install # 没有缓存优化
......
version: 2 version: 2
updates: updates:
- package-ecosystem: npm - package-ecosystem: npm
directory: '/' directory: "/"
schedule: schedule:
interval: daily interval: daily
groups: groups:
...@@ -9,7 +9,7 @@ updates: ...@@ -9,7 +9,7 @@ updates:
update-types: [minor, patch] update-types: [minor, patch]
- package-ecosystem: github-actions - package-ecosystem: github-actions
directory: '/' directory: "/"
schedule: schedule:
interval: weekly interval: weekly
groups: groups:
......
name-template: 'v$RESOLVED_VERSION' name-template: "v$RESOLVED_VERSION"
tag-template: 'v$RESOLVED_VERSION' tag-template: "v$RESOLVED_VERSION"
version-template: $MAJOR.$MINOR.$PATCH version-template: $MAJOR.$MINOR.$PATCH
change-template: '* $TITLE (#$NUMBER) @$AUTHOR' change-template: "* $TITLE (#$NUMBER) @$AUTHOR"
template: | template: |
# What's Changed # What's Changed
...@@ -10,52 +10,52 @@ template: | ...@@ -10,52 +10,52 @@ template: |
**Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION **Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION
categories: categories:
- title: '🚀 Features' - title: "🚀 Features"
labels: labels:
- 'feature' - "feature"
- title: '🐞 Bug Fixes' - title: "🐞 Bug Fixes"
labels: labels:
- 'bug' - "bug"
- title: '📈 Performance & Enhancement' - title: "📈 Performance & Enhancement"
labels: labels:
- 'perf' - "perf"
- 'enhancement' - "enhancement"
- title: 📝 Documentation - title: 📝 Documentation
labels: labels:
- 'documentation' - "documentation"
- title: 👻 Maintenance - title: 👻 Maintenance
labels: labels:
- 'chore' - "chore"
- 'dependencies' - "dependencies"
# collapse-after: 12 # collapse-after: 12
- title: 🚦 Tests - title: 🚦 Tests
labels: labels:
- 'tests' - "tests"
- title: 'Breaking' - title: "Breaking"
label: 'breaking' label: "breaking"
version-resolver: version-resolver:
major: major:
labels: labels:
- 'major' - "major"
- 'breaking' - "breaking"
minor: minor:
labels: labels:
- 'minor' - "minor"
patch: patch:
labels: labels:
- 'feature' - "feature"
- 'patch' - "patch"
- 'bug' - "bug"
- 'maintenance' - "maintenance"
- 'docs' - "docs"
- 'dependencies' - "dependencies"
- 'security' - "security"
exclude-labels: exclude-labels:
- 'skip-changelog' - "skip-changelog"
- 'no-changelog' - "no-changelog"
- 'changelog' - "changelog"
- 'bump versions' - "bump versions"
- 'reverted' - "reverted"
- 'invalid' - "invalid"
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
``` ```
**工作流分类:** **工作流分类:**
- 🔨 **构建和测试**:验证代码质量 - 🔨 **构建和测试**:验证代码质量
- 📦 **版本和发布**:管理版本发布流程 - 📦 **版本和发布**:管理版本发布流程
- 🚀 **部署**:自动部署网站 - 🚀 **部署**:自动部署网站
...@@ -41,11 +42,13 @@ ...@@ -41,11 +42,13 @@
**描述**:持续集成工作流,在每次 PR 和推送到 main 分支时运行测试和构建。 **描述**:持续集成工作流,在每次 PR 和推送到 main 分支时运行测试和构建。
**触发条件**: **触发条件**:
- Pull Request 事件 - Pull Request 事件
- 推送到 `main` 分支 - 推送到 `main` 分支
- 推送到 `releases/*` 分支 - 推送到 `releases/*` 分支
**执行环境**: **执行环境**:
- Ubuntu Latest - Ubuntu Latest
- Windows Latest - Windows Latest
- ~~macOS Latest~~ (已注释) - ~~macOS Latest~~ (已注释)
...@@ -53,6 +56,7 @@ ...@@ -53,6 +56,7 @@
**超时**:20 分钟 **超时**:20 分钟
**主要步骤**: **主要步骤**:
```yaml ```yaml
1. 检查代码 (checkout@v4) 1. 检查代码 (checkout@v4)
2. 安装 pnpm 2. 安装 pnpm
...@@ -63,6 +67,7 @@ ...@@ -63,6 +67,7 @@
``` ```
**环境变量**: **环境变量**:
- `CI=true` - 标记为 CI 环境 - `CI=true` - 标记为 CI 环境
- `TZ=Asia/Shanghai` - 时区设置 - `TZ=Asia/Shanghai` - 时区设置
...@@ -75,14 +80,17 @@ ...@@ -75,14 +80,17 @@
**描述**:在多个操作系统上验证 PR 的构建可行性,确保代码在不同平台上都能正确构建。 **描述**:在多个操作系统上验证 PR 的构建可行性,确保代码在不同平台上都能正确构建。
**触发条件**: **触发条件**:
- PR 打开、同步或重新打开时 - PR 打开、同步或重新打开时
- 仅针对 `main` 分支 - 仅针对 `main` 分支
**执行环境**: **执行环境**:
- Ubuntu Latest - Ubuntu Latest
- Windows Latest - Windows Latest
**主要步骤**: **主要步骤**:
```yaml ```yaml
1. 检查代码 1. 检查代码
2. 检查出 PR 分支 2. 检查出 PR 分支
...@@ -91,10 +99,12 @@ ...@@ -91,10 +99,12 @@
``` ```
**特殊配置**: **特殊配置**:
- **并发控制**:同一 PR 的多个运行会互相取消,节省资源 - **并发控制**:同一 PR 的多个运行会互相取消,节省资源
- **权限**:读取内容、写入 PR - **权限**:读取内容、写入 PR
**用途**: **用途**:
- 验证 PR 能否成功构建 - 验证 PR 能否成功构建
- 在合并前捕获构建错误 - 在合并前捕获构建错误
- 检测跨平台兼容性问题 - 检测跨平台兼容性问题
...@@ -106,23 +116,28 @@ ...@@ -106,23 +116,28 @@
**描述**:使用 GitHub CodeQL 对代码进行静态安全分析,检测潜在的代码漏洞和安全问题。 **描述**:使用 GitHub CodeQL 对代码进行静态安全分析,检测潜在的代码漏洞和安全问题。
**触发条件**: **触发条件**:
- 推送到 `main` 分支 - 推送到 `main` 分支
- PR 到 `main` 分支 - PR 到 `main` 分支
- 每周日午夜定时运行(`0 35 * * 0`) - 每周日午夜定时运行(`0 35 * * 0`)
**执行环境**: **执行环境**:
- Swift: macOS Latest - Swift: macOS Latest
- 其他语言: Ubuntu Latest - 其他语言: Ubuntu Latest
**超时**: **超时**:
- Swift: 120 分钟 - Swift: 120 分钟
- 其他: 360 分钟 - 其他: 360 分钟
**权限**: **权限**:
- `security-events: write` - 创建安全事件 - `security-events: write` - 创建安全事件
- `packages: read` - 读取包 - `packages: read` - 读取包
**用途**: **用途**:
- 发现代码漏洞 - 发现代码漏洞
- 检测安全问题 - 检测安全问题
- 生成安全报告 - 生成安全报告
...@@ -136,12 +151,14 @@ ...@@ -136,12 +151,14 @@
**描述**:自动管理 monorepo 的版本更新,使用 changesets 工具管理语义化版本。 **描述**:自动管理 monorepo 的版本更新,使用 changesets 工具管理语义化版本。
**触发条件**: **触发条件**:
- PR 合并到 `main` 分支时 - PR 合并到 `main` 分支时
- 手动触发 (`workflow_dispatch`) - 手动触发 (`workflow_dispatch`)
**超时**:15 分钟 **超时**:15 分钟
**主要步骤**: **主要步骤**:
```yaml ```yaml
1. 检查代码 1. 检查代码
2. 设置 Node 环境 2. 设置 Node 环境
...@@ -151,6 +168,7 @@ ...@@ -151,6 +168,7 @@
``` ```
**条件**: **条件**:
- PR 必须已合并 - PR 必须已合并
- 非 dependabot 用户 - 非 dependabot 用户
- 不包含 `[skip ci]` 标记 - 不包含 `[skip ci]` 标记
...@@ -158,6 +176,7 @@ ...@@ -158,6 +176,7 @@
**工具**:[changesets/action](https://github.com/changesets/action) **工具**:[changesets/action](https://github.com/changesets/action)
**用途**: **用途**:
- 自动化版本号更新 - 自动化版本号更新
- 生成 CHANGELOG - 生成 CHANGELOG
- 为发布做准备 - 为发布做准备
...@@ -169,12 +188,14 @@ ...@@ -169,12 +188,14 @@
**描述**:检测版本标签推送事件,触发发布流程。 **描述**:检测版本标签推送事件,触发发布流程。
**触发条件**: **触发条件**:
- 推送版本标签,格式:`v*.*.*` - 推送版本标签,格式:`v*.*.*`
- 示例:`v1.0.0`、`v20.15.10` - 示例:`v1.0.0`、`v20.15.10`
**执行环境**:Ubuntu Latest (Node 20) **执行环境**:Ubuntu Latest (Node 20)
**主要步骤**: **主要步骤**:
```yaml ```yaml
1. 检查代码 1. 检查代码
2. 执行构建 2. 执行构建
...@@ -191,15 +212,18 @@ ...@@ -191,15 +212,18 @@
**描述**:自动生成发布说明(Release Notes),基于 PR 标签和信息。 **描述**:自动生成发布说明(Release Notes),基于 PR 标签和信息。
**触发条件**: **触发条件**:
- 推送到 `main` 分支时 - 推送到 `main` 分支时
**工具**:[release-drafter/release-drafter](https://github.com/release-drafter/release-drafter) **工具**:[release-drafter/release-drafter](https://github.com/release-drafter/release-drafter)
**权限**: **权限**:
- `contents: write` - 创建发布 - `contents: write` - 创建发布
- `pull-requests: write` - 处理 PR 信息 - `pull-requests: write` - 处理 PR 信息
**用途**: **用途**:
- 自动化生成发布说明 - 自动化生成发布说明
- 基于 PR 自动分类更改 - 基于 PR 自动分类更改
- 简化发布流程 - 简化发布流程
...@@ -213,12 +237,14 @@ ...@@ -213,12 +237,14 @@
**描述**:自动部署演示站点、文档和 Web 应用到服务器。 **描述**:自动部署演示站点、文档和 Web 应用到服务器。
**触发条件**: **触发条件**:
- 推送到 `main` 分支时 - 推送到 `main` 分支时
- 排除:Dependabot 推送和包含 `[skip ci]` 的提交 - 排除:Dependabot 推送和包含 `[skip ci]` 的提交
**部署目标**: **部署目标**:
**1) Playground FTP 部署** **1) Playground FTP 部署**
- **目标**:演示站点(Playground) - **目标**:演示站点(Playground)
- **步骤**: - **步骤**:
```yaml ```yaml
...@@ -234,10 +260,12 @@ ...@@ -234,10 +260,12 @@
- `WEB_PLAYGROUND_FTP_PWSSWORD` - FTP 密码 - `WEB_PLAYGROUND_FTP_PWSSWORD` - FTP 密码
**2) Docs FTP 部署** **2) Docs FTP 部署**
- **目标**:项目文档 - **目标**:项目文档
- **步骤**:类似 Playground,构建并上传文档 - **步骤**:类似 Playground,构建并上传文档
**3) Web FTP 部署** **3) Web FTP 部署**
- **目标**:主网站 - **目标**:主网站
- **步骤**:构建 Web 应用并上传 - **步骤**:构建 Web 应用并上传
...@@ -254,9 +282,11 @@ ...@@ -254,9 +282,11 @@
**描述**:验证 PR 标题是否符合语义化提交规范,确保提交信息的一致性。 **描述**:验证 PR 标题是否符合语义化提交规范,确保提交信息的一致性。
**触发条件**: **触发条件**:
- PR 打开、编辑或同步时 - PR 打开、编辑或同步时
**验证规则**: **验证规则**:
- **首字母**:主体首字母不能大写 - **首字母**:主体首字母不能大写
- **允许的类型**: - **允许的类型**:
``` ```
...@@ -265,6 +295,7 @@ ...@@ -265,6 +295,7 @@
``` ```
**示例**: **示例**:
- ✅ 正确:`fix: button click issue` - ✅ 正确:`fix: button click issue`
- ❌ 错误:`Fix: button click issue` - ❌ 错误:`Fix: button click issue`
- ✅ 正确:`feat: add new feature` - ✅ 正确:`feat: add new feature`
...@@ -273,6 +304,7 @@ ...@@ -273,6 +304,7 @@
**工具**:[amannn/action-semantic-pull-request](https://github.com/amannn/action-semantic-pull-request) **工具**:[amannn/action-semantic-pull-request](https://github.com/amannn/action-semantic-pull-request)
**用途**: **用途**:
- 保证提交信息格式一致 - 保证提交信息格式一致
- 便于自动生成 CHANGELOG - 便于自动生成 CHANGELOG
- 提高代码库可读性 - 提高代码库可读性
...@@ -284,20 +316,24 @@ ...@@ -284,20 +316,24 @@
**描述**:自动关闭标记为 "needs reproduction" 的长期未活动 Issue,保持 Issue 列表整洁。 **描述**:自动关闭标记为 "needs reproduction" 的长期未活动 Issue,保持 Issue 列表整洁。
**触发条件**: **触发条件**:
- 每天零点运行 - 每天零点运行
- 手动触发 (`workflow_dispatch`) - 手动触发 (`workflow_dispatch`)
**关闭规则**: **关闭规则**:
- 标签:`needs-reproduction` - 标签:`needs-reproduction`
- 无活动天数:3 天 - 无活动天数:3 天
- 关闭标签:`closed-by-action` - 关闭标签:`closed-by-action`
**关闭消息**: **关闭消息**:
``` ```
This issue was closed because it was open for 3 days without a valid reproduction. This issue was closed because it was open for 3 days without a valid reproduction.
``` ```
**用途**: **用途**:
- 要求用户提供复现步骤 - 要求用户提供复现步骤
- 自动清理无效 Issue - 自动清理无效 Issue
- 减少维护负担 - 减少维护负担
...@@ -309,17 +345,19 @@ This issue was closed because it was open for 3 days without a valid reproductio ...@@ -309,17 +345,19 @@ This issue was closed because it was open for 3 days without a valid reproductio
**描述**:根据添加的 Issue 标签自动做出响应,如发送评论或移除其他标签。 **描述**:根据添加的 Issue 标签自动做出响应,如发送评论或移除其他标签。
**触发条件**: **触发条件**:
- Issue 被添加标签时 - Issue 被添加标签时
**响应规则**: **响应规则**:
| 添加的标签 | 响应动作 | 说明 | | 添加的标签 | 响应动作 | 说明 |
|-----------|--------|------| | -------------------- | ------------------------------------- | -------------------- |
| `enhancement` | 移除 `enhancement: pending triage` | 确认为新功能需求 | | `enhancement` | 移除 `enhancement: pending triage` | 确认为新功能需求 |
| `bug` | 移除 `bug: pending triage` | 确认为 Bug | | `bug` | 移除 `bug: pending triage` | 确认为 Bug |
| `needs reproduction` | 发送评论 + 移除 `bug: pending triage` | 要求用户提供复现步骤 | | `needs reproduction` | 发送评论 + 移除 `bug: pending triage` | 要求用户提供复现步骤 |
**needs reproduction 评论内容**: **needs reproduction 评论内容**:
``` ```
Hello @${{ github.event.issue.user.login }}. Hello @${{ github.event.issue.user.login }}.
Please provide the complete reproduction steps and code. Please provide the complete reproduction steps and code.
...@@ -337,16 +375,18 @@ Issues labeled by `needs reproduction` will be closed if no activities in 3 days ...@@ -337,16 +375,18 @@ Issues labeled by `needs reproduction` will be closed if no activities in 3 days
**描述**:自动关闭长时间无活动的 Issue 和 PR,保持项目的活跃度。 **描述**:自动关闭长时间无活动的 Issue 和 PR,保持项目的活跃度。
**触发条件**: **触发条件**:
- 每天凌晨 1 点运行 - 每天凌晨 1 点运行
**关闭规则**: **关闭规则**:
| 内容类型 | 无活动天数 | 标记为 Stale | 再等天数 | 关闭 | 豁免标签 | | 内容类型 | 无活动天数 | 标记为 Stale | 再等天数 | 关闭 | 豁免标签 |
|--------|---------|------------|--------|------|---------| | -------- | ---------- | ------------ | -------- | ---- | ---------------- |
| Issue | 60 天 | 是 | 7 天 | 是 | bug, enhancement | | Issue | 60 天 | 是 | 7 天 | 是 | bug, enhancement |
| PR | 60 天 | 是 | 7 天 | 是 | 无 | | PR | 60 天 | 是 | 7 天 | 是 | 无 |
**提醒消息**: **提醒消息**:
``` ```
This issue/PR is stale because it has been open 60 days with no activity. This issue/PR is stale because it has been open 60 days with no activity.
Remove stale label or comment or this will be closed in 7 days. Remove stale label or comment or this will be closed in 7 days.
...@@ -357,6 +397,7 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -357,6 +397,7 @@ Remove stale label or comment or this will be closed in 7 days.
**工具**:[actions/stale](https://github.com/actions/stale) **工具**:[actions/stale](https://github.com/actions/stale)
**用途**: **用途**:
- 自动清理废弃的 Issue/PR - 自动清理废弃的 Issue/PR
- 鼓励用户跟进问题 - 鼓励用户跟进问题
- 保持项目整洁 - 保持项目整洁
...@@ -368,13 +409,14 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -368,13 +409,14 @@ Remove stale label or comment or this will be closed in 7 days.
**描述**:自动锁定长时间无活动的讨论,防止垃圾评论。 **描述**:自动锁定长时间无活动的讨论,防止垃圾评论。
**触发条件**: **触发条件**:
- 每天零点运行 - 每天零点运行
- 手动触发 - 手动触发
**锁定规则**: **锁定规则**:
| 内容类型 | 无活动天数 | 是否锁定 | 锁定原因 | | 内容类型 | 无活动天数 | 是否锁定 | 锁定原因 |
|--------|---------|--------|--------| | -------- | ---------- | -------- | -------------------------- |
| Issue | 14 天 | 是 | 空(默认:已解决或已弃用) | | Issue | 14 天 | 是 | 空(默认:已解决或已弃用) |
| PR | 30 天 | 是 | 空(默认:已合并或已弃用) | | PR | 30 天 | 是 | 空(默认:已合并或已弃用) |
...@@ -383,6 +425,7 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -383,6 +425,7 @@ Remove stale label or comment or this will be closed in 7 days.
**工具**:[dessant/lock-threads](https://github.com/dessant/lock-threads) **工具**:[dessant/lock-threads](https://github.com/dessant/lock-threads)
**用途**: **用途**:
- 防止已解决问题的垃圾评论 - 防止已解决问题的垃圾评论
- 保护历史讨论 - 保护历史讨论
- 减少通知干扰 - 减少通知干扰
...@@ -396,18 +439,22 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -396,18 +439,22 @@ Remove stale label or comment or this will be closed in 7 days.
**描述**:手动重新运行失败的 GitHub Actions 工作流,无需提交新的代码。 **描述**:手动重新运行失败的 GitHub Actions 工作流,无需提交新的代码。
**触发条件**: **触发条件**:
- 手动触发 (`workflow_dispatch`) - 手动触发 (`workflow_dispatch`)
**输入参数**: **输入参数**:
- `run_id` - 需要重新运行的工作流 ID(必需) - `run_id` - 需要重新运行的工作流 ID(必需)
**执行步骤**: **执行步骤**:
```yaml ```yaml
1. 等待原始工作流完成 1. 等待原始工作流完成
2. 重新运行失败的任务 2. 重新运行失败的任务
``` ```
**用途**: **用途**:
- 处理临时网络错误 - 处理临时网络错误
- 重新运行因外部因素失败的工作流 - 重新运行因外部因素失败的工作流
- 无需推送新代码 - 无需推送新代码
...@@ -419,7 +466,7 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -419,7 +466,7 @@ Remove stale label or comment or this will be closed in 7 days.
### 工作流触发时间表 ### 工作流触发时间表
| 时间 | 工作流 | 说明 | | 时间 | 工作流 | 说明 |
|-----|------|------| | ------------------ | ------------------------------------ | ------------------------ |
| **PR 打开/编辑时** | build.yml, semantic-pull-request.yml | 验证代码构建和 PR 规范 | | **PR 打开/编辑时** | build.yml, semantic-pull-request.yml | 验证代码构建和 PR 规范 |
| **PR 合并到 main** | changeset-version.yml | 更新版本号 | | **PR 合并到 main** | changeset-version.yml | 更新版本号 |
| **推送到 main** | ci.yml, deploy.yml, draft.yml | 测试、部署、生成发布说明 | | **推送到 main** | ci.yml, deploy.yml, draft.yml | 测试、部署、生成发布说明 |
...@@ -433,7 +480,7 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -433,7 +480,7 @@ Remove stale label or comment or this will be closed in 7 days.
### 权限总览 ### 权限总览
| 权限 | 用途 | 工作流 | | 权限 | 用途 | 工作流 |
|-----|------|-------| | ------------------------ | ------------ | ----------------------------- |
| `contents: read` | 读取仓库内容 | ci.yml, build.yml 等 | | `contents: read` | 读取仓库内容 | ci.yml, build.yml 等 |
| `contents: write` | 写入仓库内容 | release-tag.yml, draft.yml 等 | | `contents: write` | 写入仓库内容 | release-tag.yml, draft.yml 等 |
| `pull-requests: write` | 写入 PR | build.yml, draft.yml 等 | | `pull-requests: write` | 写入 PR | build.yml, draft.yml 等 |
...@@ -443,7 +490,7 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -443,7 +490,7 @@ Remove stale label or comment or this will be closed in 7 days.
### 环境变量 ### 环境变量
| 变量 | 值 | 用途 | 工作流 | | 变量 | 值 | 用途 | 工作流 |
|-----|---|------|-------| | ------- | --------------- | ------------- | -------------------------------- |
| `HUSKY` | `0` | 禁用 Git Hook | build.yml, changeset-version.yml | | `HUSKY` | `0` | 禁用 Git Hook | build.yml, changeset-version.yml |
| `CI` | `true` | 标记 CI 环境 | ci.yml, changeset-version.yml | | `CI` | `true` | 标记 CI 环境 | ci.yml, changeset-version.yml |
| `TZ` | `Asia/Shanghai` | 时区设置 | ci.yml | | `TZ` | `Asia/Shanghai` | 时区设置 | ci.yml |
...@@ -455,13 +502,14 @@ Remove stale label or comment or this will be closed in 7 days. ...@@ -455,13 +502,14 @@ Remove stale label or comment or this will be closed in 7 days.
### 部署所需的 GitHub Secrets ### 部署所需的 GitHub Secrets
| 秘密名称 | 用途 | 工作流 | | 秘密名称 | 用途 | 工作流 |
|--------|------|-------| | ----------------------------- | --------------- | ---------- |
| `GITHUB_TOKEN` | GitHub API 认证 | 所有工作流 | | `GITHUB_TOKEN` | GitHub API 认证 | 所有工作流 |
| `PRO_FTP_HOST` | FTP 主机地址 | deploy.yml | | `PRO_FTP_HOST` | FTP 主机地址 | deploy.yml |
| `WEB_PLAYGROUND_FTP_ACCOUNT` | FTP 账号 | deploy.yml | | `WEB_PLAYGROUND_FTP_ACCOUNT` | FTP 账号 | deploy.yml |
| `WEB_PLAYGROUND_FTP_PWSSWORD` | FTP 密码 | deploy.yml | | `WEB_PLAYGROUND_FTP_PWSSWORD` | FTP 密码 | deploy.yml |
**配置方式**: **配置方式**:
1. 进入 GitHub 仓库 Settings 1. 进入 GitHub 仓库 Settings
2. 找到 Secrets and variables → Actions 2. 找到 Secrets and variables → Actions
3. 点击 New repository secret 3. 点击 New repository secret
...@@ -485,11 +533,13 @@ git push ...@@ -485,11 +533,13 @@ git push
编辑 PR 标题使其符合规范: 编辑 PR 标题使其符合规范:
**错误格式**: **错误格式**:
``` ```
Fix: button click issue Fix: button click issue
``` ```
**正确格式**: **正确格式**:
``` ```
fix: button click issue fix: button click issue
``` ```
...@@ -538,6 +588,7 @@ fix: button click issue ...@@ -538,6 +588,7 @@ fix: button click issue
修改工作流时,请遵循以下步骤: 修改工作流时,请遵循以下步骤:
1. **创建分支**: 1. **创建分支**:
```bash ```bash
git checkout -b feature/workflow-update git checkout -b feature/workflow-update
``` ```
...@@ -551,6 +602,7 @@ fix: button click issue ...@@ -551,6 +602,7 @@ fix: button click issue
- 测试工作流逻辑 - 测试工作流逻辑
4. **提交 PR**: 4. **提交 PR**:
```bash ```bash
git add .github/workflows/ git add .github/workflows/
git commit -m "chore: update workflow configuration" git commit -m "chore: update workflow configuration"
......
dist dist
dev-dist dev-dist
.local .local
...@@ -7,7 +8,6 @@ coverage ...@@ -7,7 +8,6 @@ coverage
CODEOWNERS CODEOWNERS
.nitro .nitro
.output .output
**/*.uvue **/*.uvue
**/*.uts **/*.uts
**/*.vue **/*.vue
...@@ -32,3 +32,5 @@ unpackage ...@@ -32,3 +32,5 @@ unpackage
# 只格式化 wxml # 只格式化 wxml
!*.wxml !*.wxml
!*.json !*.json
...@@ -3,9 +3,7 @@ ...@@ -3,9 +3,7 @@
"ESLint": { "ESLint": {
"type": "stdio", "type": "stdio",
"command": "npx", "command": "npx",
"args": [ "args": ["@eslint/mcp@latest"]
"@eslint/mcp@latest"
]
} }
}, },
"inputs": [] "inputs": []
......
...@@ -266,5 +266,5 @@ ...@@ -266,5 +266,5 @@
"vue.server.hybridMode": true, "vue.server.hybridMode": true,
"typescript.tsdk": "node_modules/typescript/lib", "typescript.tsdk": "node_modules/typescript/lib",
"oxc.enable": false, "oxc.enable": false,
"cSpell.words": ["archiver", "axios", "dotenv", "isequal", "jspm", "napi", "nolebase", "rollup", "vitest"], "cSpell.words": ["archiver", "axios", "dotenv", "isequal", "jspm", "napi", "nolebase", "rollup", "vitest"]
} }
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
## 开发相关 ## 开发相关
### `dev` ### `dev`
启动开发服务器,运行所有包/应用的开发模式。 启动开发服务器,运行所有包/应用的开发模式。
```bash ```bash
...@@ -12,6 +13,7 @@ pnpm dev ...@@ -12,6 +13,7 @@ pnpm dev
``` ```
### `dev:docs` ### `dev:docs`
启动文档开发服务器。 启动文档开发服务器。
```bash ```bash
...@@ -19,6 +21,7 @@ pnpm dev:docs ...@@ -19,6 +21,7 @@ pnpm dev:docs
``` ```
### `preview` ### `preview`
预览构建后的应用。 预览构建后的应用。
```bash ```bash
...@@ -28,6 +31,7 @@ pnpm preview ...@@ -28,6 +31,7 @@ pnpm preview
## 构建相关 ## 构建相关
### `build` ### `build`
构建项目(使用 turbo-run,设置内存限制为 8GB)。 构建项目(使用 turbo-run,设置内存限制为 8GB)。
```bash ```bash
...@@ -35,6 +39,7 @@ pnpm build ...@@ -35,6 +39,7 @@ pnpm build
``` ```
### `build:all` ### `build:all`
构建所有项目(使用 turbo,设置内存限制为 8GB)。 构建所有项目(使用 turbo,设置内存限制为 8GB)。
```bash ```bash
...@@ -42,6 +47,7 @@ pnpm build:all ...@@ -42,6 +47,7 @@ pnpm build:all
``` ```
### `build:filter` ### `build:filter`
按过滤条件构建并复制到根目录。 按过滤条件构建并复制到根目录。
```bash ```bash
...@@ -49,6 +55,7 @@ pnpm build:filter ...@@ -49,6 +55,7 @@ pnpm build:filter
``` ```
### `build:docs` ### `build:docs`
构建文档项目。 构建文档项目。
```bash ```bash
...@@ -58,6 +65,7 @@ pnpm build:docs ...@@ -58,6 +65,7 @@ pnpm build:docs
## 代码质量检查 ## 代码质量检查
### `check` ### `check`
运行所有检查:循环依赖、依赖、类型检查、拼写检查。 运行所有检查:循环依赖、依赖、类型检查、拼写检查。
```bash ```bash
...@@ -65,6 +73,7 @@ pnpm check ...@@ -65,6 +73,7 @@ pnpm check
``` ```
### `check:circular` ### `check:circular`
检查代码中的循环依赖。 检查代码中的循环依赖。
```bash ```bash
...@@ -72,6 +81,7 @@ pnpm check:circular ...@@ -72,6 +81,7 @@ pnpm check:circular
``` ```
### `check:dep` ### `check:dep`
检查依赖关系。 检查依赖关系。
```bash ```bash
...@@ -79,6 +89,7 @@ pnpm check:dep ...@@ -79,6 +89,7 @@ pnpm check:dep
``` ```
### `check:type` ### `check:type`
运行 TypeScript 类型检查。 运行 TypeScript 类型检查。
```bash ```bash
...@@ -86,6 +97,7 @@ pnpm check:type ...@@ -86,6 +97,7 @@ pnpm check:type
``` ```
### `check:cspell` ### `check:cspell`
对代码和文档进行拼写检查。 对代码和文档进行拼写检查。
```bash ```bash
...@@ -93,6 +105,7 @@ pnpm check:cspell ...@@ -93,6 +105,7 @@ pnpm check:cspell
``` ```
### `lint` ### `lint`
运行 ESLint 代码检查。 运行 ESLint 代码检查。
```bash ```bash
...@@ -100,6 +113,7 @@ pnpm lint ...@@ -100,6 +113,7 @@ pnpm lint
``` ```
### `format` ### `format`
格式化代码(自动修复格式问题)。 格式化代码(自动修复格式问题)。
```bash ```bash
...@@ -107,6 +121,7 @@ pnpm format ...@@ -107,6 +121,7 @@ pnpm format
``` ```
### `publint` ### `publint`
发布前对包进行 lint 检查。 发布前对包进行 lint 检查。
```bash ```bash
...@@ -116,6 +131,7 @@ pnpm publint ...@@ -116,6 +131,7 @@ pnpm publint
## 测试相关 ## 测试相关
### `test:unit` ### `test:unit`
运行单元测试(使用 Vitest,DOM 环境)。 运行单元测试(使用 Vitest,DOM 环境)。
```bash ```bash
...@@ -123,6 +139,7 @@ pnpm test:unit ...@@ -123,6 +139,7 @@ pnpm test:unit
``` ```
### `test:e2e` ### `test:e2e`
运行端到端测试(使用 Playwright)。 运行端到端测试(使用 Playwright)。
```bash ```bash
...@@ -130,6 +147,7 @@ pnpm test:e2e ...@@ -130,6 +147,7 @@ pnpm test:e2e
``` ```
### `command:test` ### `command:test`
测试构建命令。 测试构建命令。
```bash ```bash
...@@ -139,6 +157,7 @@ pnpm command:test ...@@ -139,6 +157,7 @@ pnpm command:test
## 依赖管理 ## 依赖管理
### `update:deps` ### `update:deps`
交互式更新所有依赖到最新版本。 交互式更新所有依赖到最新版本。
```bash ```bash
...@@ -146,6 +165,7 @@ pnpm update:deps ...@@ -146,6 +165,7 @@ pnpm update:deps
``` ```
### `reinstall` ### `reinstall`
清理并重新安装依赖(删除锁文件后重新安装)。 清理并重新安装依赖(删除锁文件后重新安装)。
```bash ```bash
...@@ -153,6 +173,7 @@ pnpm reinstall ...@@ -153,6 +173,7 @@ pnpm reinstall
``` ```
### `clean` ### `clean`
清理构建产物和临时文件。 清理构建产物和临时文件。
```bash ```bash
...@@ -162,6 +183,7 @@ pnpm clean ...@@ -162,6 +183,7 @@ pnpm clean
## 版本管理 ## 版本管理
### `changeset` ### `changeset`
创建变更集(用于版本管理和生成 CHANGELOG)。 创建变更集(用于版本管理和生成 CHANGELOG)。
```bash ```bash
...@@ -169,6 +191,7 @@ pnpm changeset ...@@ -169,6 +191,7 @@ pnpm changeset
``` ```
### `version` ### `version`
更新版本号并更新锁文件(通常在发布前使用)。 更新版本号并更新锁文件(通常在发布前使用)。
```bash ```bash
...@@ -176,6 +199,7 @@ pnpm version ...@@ -176,6 +199,7 @@ pnpm version
``` ```
### `catalog` ### `catalog`
运行 pnpm catalog codemod(管理依赖目录)。 运行 pnpm catalog codemod(管理依赖目录)。
```bash ```bash
...@@ -185,6 +209,7 @@ pnpm catalog ...@@ -185,6 +209,7 @@ pnpm catalog
## Venus CLI 相关 ## Venus CLI 相关
### `venus` ### `venus`
运行 Venus CLI 工具。 运行 Venus CLI 工具。
```bash ```bash
...@@ -192,6 +217,7 @@ pnpm venus ...@@ -192,6 +217,7 @@ pnpm venus
``` ```
### `venus:build` ### `venus:build`
构建 Venus CLI 工具。 构建 Venus CLI 工具。
```bash ```bash
...@@ -199,6 +225,7 @@ pnpm venus:build ...@@ -199,6 +225,7 @@ pnpm venus:build
``` ```
### `venus:create` ### `venus:create`
创建新的 Venus 项目。 创建新的 Venus 项目。
```bash ```bash
...@@ -206,6 +233,7 @@ pnpm venus:create ...@@ -206,6 +233,7 @@ pnpm venus:create
``` ```
### `venus:create:interactive` ### `venus:create:interactive`
交互式创建新的 Venus 项目。 交互式创建新的 Venus 项目。
```bash ```bash
...@@ -213,6 +241,7 @@ pnpm venus:create:interactive ...@@ -213,6 +241,7 @@ pnpm venus:create:interactive
``` ```
### `venus:ls` ### `venus:ls`
列出可用的 Venus 模板。 列出可用的 Venus 模板。
```bash ```bash
...@@ -222,6 +251,7 @@ pnpm venus:ls ...@@ -222,6 +251,7 @@ pnpm venus:ls
## Git 相关 ## Git 相关
### `commit` ### `commit`
使用 PowerShell 脚本进行 Git 提交(配置了 commitlint)。 使用 PowerShell 脚本进行 Git 提交(配置了 commitlint)。
```bash ```bash
...@@ -231,11 +261,13 @@ pnpm commit ...@@ -231,11 +261,13 @@ pnpm commit
## 生命周期钩子 ## 生命周期钩子
### `preinstall` ### `preinstall`
安装前钩子:强制使用 pnpm 作为包管理器。 安装前钩子:强制使用 pnpm 作为包管理器。
### `postinstall` ### `postinstall`
安装后钩子:在所有包中运行 stub 脚本(如果存在)。 安装后钩子:在所有包中运行 stub 脚本(如果存在)。
### `prepare` ### `prepare`
初始化 Husky Git hooks。
初始化 Husky Git hooks。
...@@ -89,11 +89,13 @@ micro-app-template/ ...@@ -89,11 +89,13 @@ micro-app-template/
在启动前,请确保配置正确(已在本次更新中修复): 在启动前,请确保配置正确(已在本次更新中修复):
**子应用配置检查:** **子应用配置检查:**
- ✅ `vite.config.ts` - base 配置为 `http://localhost:8081/` - ✅ `vite.config.ts` - base 配置为 `http://localhost:8081/`
- ✅ `src/router/index.ts` - 导出 `createRouter` 函数 - ✅ `src/router/index.ts` - 导出 `createRouter` 函数
- ✅ `src/main.ts` - 动态创建路由实例 - ✅ `src/main.ts` - 动态创建路由实例
**基座配置检查:** **基座配置检查:**
- ✅ `src/qiankun/apps.ts` - entry 配置为 `http://localhost:8081` - ✅ `src/qiankun/apps.ts` - entry 配置为 `http://localhost:8081`
- ✅ `src/views/MicroApp.vue` - 包含 `<div id="subapp-container"></div>` - ✅ `src/views/MicroApp.vue` - 包含 `<div id="subapp-container"></div>`
...@@ -107,6 +109,7 @@ pnpm dev ...@@ -107,6 +109,7 @@ pnpm dev
子应用会在 `http://localhost:8081` 启动 子应用会在 `http://localhost:8081` 启动
**验证:** **验证:**
- 访问 `http://localhost:8081` 应显示子应用 - 访问 `http://localhost:8081` 应显示子应用
- 控制台显示 "独立运行模式" - 控制台显示 "独立运行模式"
...@@ -120,6 +123,7 @@ pnpm dev ...@@ -120,6 +123,7 @@ pnpm dev
基座会在 `http://localhost:8080` 启动 基座会在 `http://localhost:8080` 启动
**验证:** **验证:**
- 控制台显示 "[qiankun] 微前端框架已启动" - 控制台显示 "[qiankun] 微前端框架已启动"
### 3. 在基座中访问子应用 ### 3. 在基座中访问子应用
...@@ -127,6 +131,7 @@ pnpm dev ...@@ -127,6 +131,7 @@ pnpm dev
访问 `http://localhost:8080/subapp-vue`,基座会自动加载并挂载子应用 访问 `http://localhost:8080/subapp-vue`,基座会自动加载并挂载子应用
**预期结果:** **预期结果:**
- 看到子应用内容(紫色渐变背景) - 看到子应用内容(紫色渐变背景)
- 控制台显示生命周期日志 - 控制台显示生命周期日志
- 运行模式显示 "🔗 基座模式" - 运行模式显示 "🔗 基座模式"
...@@ -148,7 +153,7 @@ const PORT = 8081; // 修改为你想要的端口 ...@@ -148,7 +153,7 @@ const PORT = 8081; // 修改为你想要的端口
1. 在 `vite.config.ts` 中修改 `APP_NAME`: 1. 在 `vite.config.ts` 中修改 `APP_NAME`:
```typescript ```typescript
const APP_NAME = 'your-app-name'; const APP_NAME = "your-app-name";
``` ```
2. 在基座的 `src/micro-apps.ts` 中添加或修改对应配置: 2. 在基座的 `src/micro-apps.ts` 中添加或修改对应配置:
...@@ -203,12 +208,12 @@ pnpm dev ...@@ -203,12 +208,12 @@ pnpm dev
使用以下方式判断应用是否在 qiankun 环境中运行: 使用以下方式判断应用是否在 qiankun 环境中运行:
```typescript ```typescript
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'; import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
if (qiankunWindow.__POWERED_BY_QIANKUN__) { if (qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log('在基座中运行'); console.log("在基座中运行");
} else { } else {
console.log('独立运行'); console.log("独立运行");
} }
``` ```
...@@ -217,11 +222,13 @@ if (qiankunWindow.__POWERED_BY_QIANKUN__) { ...@@ -217,11 +222,13 @@ if (qiankunWindow.__POWERED_BY_QIANKUN__) {
### 1. 子应用无法加载(白屏) ### 1. 子应用无法加载(白屏)
**原因:** **原因:**
- 子应用未启动 - 子应用未启动
- entry 地址配置错误 - entry 地址配置错误
- 容器 ID 不存在 - 容器 ID 不存在
**解决:** **解决:**
```bash ```bash
# 确认子应用运行 # 确认子应用运行
curl http://localhost:8081 curl http://localhost:8081
...@@ -238,11 +245,13 @@ entry: 'http://localhost:8081' // ✅ 使用完整 URL ...@@ -238,11 +245,13 @@ entry: 'http://localhost:8081' // ✅ 使用完整 URL
### 2. CORS 错误 ### 2. CORS 错误
**控制台显示:** **控制台显示:**
``` ```
Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
``` ```
**解决:** **解决:**
- 确认子应用 `vite.config.ts` 中 `cors: true` - 确认子应用 `vite.config.ts` 中 `cors: true`
- 确认 headers 配置正确 - 确认 headers 配置正确
- 重启子应用服务 - 重启子应用服务
...@@ -250,15 +259,15 @@ Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy ...@@ -250,15 +259,15 @@ Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
### 3. 路由跳转异常 ### 3. 路由跳转异常
**原因:** **原因:**
- 路由 base 配置错误 - 路由 base 配置错误
- `routerBase` 未正确传递 - `routerBase` 未正确传递
**解决:** **解决:**
```typescript ```typescript
// ✅ 已修复:子应用动态创建路由 // ✅ 已修复:子应用动态创建路由
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ ? props.routerBase || "/subapp-vue" : "/";
? (props.routerBase || '/subapp-vue')
: '/';
const router = createRouter(routerBase); const router = createRouter(routerBase);
``` ```
...@@ -271,18 +280,20 @@ const router = createRouter(routerBase); ...@@ -271,18 +280,20 @@ const router = createRouter(routerBase);
### 5. 生命周期未触发 ### 5. 生命周期未触发
**原因:** **原因:**
- 应用名称不一致 - 应用名称不一致
- 生命周期钩子未正确导出 - 生命周期钩子未正确导出
**解决:** **解决:**
```typescript ```typescript
// vite.config.ts // vite.config.ts
qiankun('subapp-vue') // 必须与基座配置一致 qiankun("subapp-vue"); // 必须与基座配置一致
// main.ts // main.ts
export async function bootstrap() { } export async function bootstrap() {}
export async function mount(props) { } export async function mount(props) {}
export async function unmount(props) { } export async function unmount(props) {}
``` ```
**详细排查指南:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md) **详细排查指南:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md)
...@@ -294,4 +305,3 @@ MIT ...@@ -294,4 +305,3 @@ MIT
## 🤝 贡献 ## 🤝 贡献
欢迎提交 Issue 和 Pull Request! 欢迎提交 Issue 和 Pull Request!
// / <reference types="vite/client" /> declare module "*.vue" {
import type { DefineComponent } from "vue";
declare module '*.vue' { const component: DefineComponent<Record<string, never>, Record<string, never>, any>;
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component; export default component;
} }
......
<!doctype html> <!doctype html>
<html lang="zh-CN" sstyle="--el-color-primary: #185EFE; --el-color-primary-dark-2: #185EFE; --el-color-primary-light-1: #185EFE;"> <html
lang="zh-CN"
sstyle="--el-color-primary: #185EFE; --el-color-primary-dark-2: #185EFE; --el-color-primary-light-1: #185EFE;">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
...@@ -12,4 +14,3 @@ ...@@ -12,4 +14,3 @@
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
</html> </html>
...@@ -27,12 +27,12 @@ ...@@ -27,12 +27,12 @@
"axios": "catalog:", "axios": "catalog:",
"element-plus": "catalog:", "element-plus": "catalog:",
"glsk-oss-jssdk": "catalog:", "glsk-oss-jssdk": "catalog:",
"glsk-toolkit": "catalog:",
"pinia": "catalog:", "pinia": "catalog:",
"sass": "catalog:", "sass": "catalog:",
"tailwindcss": "catalog:", "tailwindcss": "catalog:",
"vue": "catalog:", "vue": "catalog:",
"vue-router": "catalog:" "vue-router": "catalog:"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "catalog:", "@types/node": "catalog:",
......
export { default } from '@venus/tailwind-config/postcss'; export { default } from "@venus/tailwind-config/postcss";
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 质检规则列表查询 * 质检规则列表查询
*/ */
export async function inspectionRuleList(data: any) { export async function inspectionRuleList(data: any) {
try { return await gscPost("/inspectionRule/findPageInspectionRule", data);
const response = await gscPost('/inspectionRule/findPageInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检规则新增 * 质检规则新增
*/ */
export async function addInspectionRule(data: any) { export async function addInspectionRule(data: any) {
try { return await gscPost("/inspectionRule/addInspectionRule", data);
const response = await gscPost('/inspectionRule/addInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检规则列表修改 * 质检规则列表修改
*/ */
export async function updateInspectionRule(data: any) { export async function updateInspectionRule(data: any) {
try { return await gscPost("/inspectionRule/updateInspectionRule", data);
const response = await gscPost('/inspectionRule/updateInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检规则列表删除 * 质检规则列表删除
*/ */
export async function deleteInspectionRule(data: any) { export async function deleteInspectionRule(data: any) {
try { return await gscPost("/inspectionRule/deleteInspectionRule", data);
const response = await gscPost('/inspectionRule/deleteInspectionRule', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版列表查询 * 质检模版列表查询
*/ */
export async function inspectionTemplateList(data: any) { export async function inspectionTemplateList(data: any) {
try { return await gscPost("/inspectionTemplate/findPageInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/findPageInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版新增 * 质检模版新增
*/ */
export async function addInspectionTemplate(data: any) { export async function addInspectionTemplate(data: any) {
try { return await gscPost("/inspectionTemplate/saveInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/saveInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版修改 * 质检模版修改
*/ */
export async function updateInspectionTemplate(data: any) { export async function updateInspectionTemplate(data: any) {
try { return await gscPost("/inspectionTemplate/updateInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/updateInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 质检模版删除 * 质检模版删除
*/ */
export async function deleteInspectionTemplate(data: any) { export async function deleteInspectionTemplate(data: any) {
try { return await gscPost("/inspectionTemplate/deleteInspectionTemplate", data);
const response = await gscPost('/inspectionTemplate/deleteInspectionTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体列表查询 * 培训智能体列表查询
*/ */
export async function trainingPlanList(data: any) { export async function trainingPlanList(data: any) {
try { return await gscPost("/trainingPlan/findPageTrainingPlan", data);
const response = await gscPost('/trainingPlan/findPageTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体新增 * 培训智能体新增
*/ */
export async function addTrainingPlan(data: any) { export async function addTrainingPlan(data: any) {
try { return await gscPost("/trainingPlan/addTrainingPlan", data);
const response = await gscPost('/trainingPlan/addTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体修改 * 培训智能体修改
*/ */
export async function updateTrainingPlan(data: any) { export async function updateTrainingPlan(data: any) {
try { return await gscPost("/trainingPlan/updateTrainingPlan", data);
const response = await gscPost('/trainingPlan/updateTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体删除 * 培训智能体删除
*/ */
export async function deleteTrainingPlan(data: any) { export async function deleteTrainingPlan(data: any) {
try { return await gscPost("/trainingPlan/deleteTrainingPlan", data);
const response = await gscPost('/trainingPlan/deleteTrainingPlan', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 培训智能体详情 * 培训智能体详情
*/ */
export async function ftrainingPlanDetail(data: any) { export async function ftrainingPlanDetail(data: any) {
try { return await gscPost(`/trainingPlan/findTrainingPlanDetail/${data.planId}`, data);
const response = await gscPost(`/trainingPlan/findTrainingPlanDetail/${data.planId}`, data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 通用知识分类列表 * 通用知识分类列表
*/ */
export async function generalKnowledgeList(data: any) { export async function generalKnowledgeList(data: any) {
try { return await gscPost("/generalKnowledgeCategory/findCategoryWithGeneralKnowledgeList", data);
const response = await gscPost('/generalKnowledgeCategory/findCategoryWithGeneralKnowledgeList', data);
return response;
} catch (error) {
throw error;
}
} }
/* /*
* 复盘智能体提示词模板查询 * 复盘智能体提示词模板查询
*/ */
export async function getPromptTemplate(data: any) { export async function getPromptTemplate(data: any) {
try { return await gscPost("/reviewAgentPromptTemplate/findPromptTemplate", data);
const response = await gscPost('/reviewAgentPromptTemplate/findPromptTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
/* /*
* 复盘智能体提示词模板更新 * 复盘智能体提示词模板更新
*/ */
export async function updatePromptTemplate(data: any) { export async function updatePromptTemplate(data: any) {
try { return await gscPost("/reviewAgentPromptTemplate/updatePromptTemplate", data);
const response = await gscPost('/reviewAgentPromptTemplate/updatePromptTemplate', data);
return response;
} catch (error) {
throw error;
}
} }
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 岗位助理列表 * 岗位助理列表
*/ */
export async function assistantList(data: any) { export async function assistantList(data: any) {
try { return await gscPost("/jobAgentInfo/findPageAgentInfo", data);
const response = await gscPost('/jobAgentInfo/findPageAgentInfo', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理详情 * 岗位助理详情
*/ */
export async function assistantDetail(data: any) { export async function assistantDetail(data: any) {
try { return await gscPost("/jobAgentDetail/detailById", data);
const response = await gscPost('/jobAgentDetail/detailById', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理创建 * 岗位助理创建
*/ */
export async function assistantCreate(data: any) { export async function assistantCreate(data: any) {
try { return await gscPost("/jobAgentInfo/create", data);
const response = await gscPost('/jobAgentInfo/create', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理更新 * 岗位助理更新
*/ */
export async function assistantUpdate(data: any) { export async function assistantUpdate(data: any) {
try { return await gscPost("/jobAgentInfo/update", data);
const response = await gscPost('/jobAgentInfo/update', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 岗位助理状态修改 * 岗位助理状态修改
*/ */
export async function assistantStatus(data: any) { export async function assistantStatus(data: any) {
try { return await gscPost("/jobAgentInfo/forbiddenOrEnable", data);
const response = await gscPost('/jobAgentInfo/forbiddenOrEnable', data);
return response;
} catch (error) {
throw error;
}
} }
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 企微部门模块树 * 企微部门模块树
*/ */
export async function findDeptTree(data: any) { export async function findDeptTree(data: any) {
try { return await gscPost("/entmicroDepartment/findDeptTree", data);
const response = await gscPost('/entmicroDepartment/findDeptTree', data);
return response;
} catch (error) {
throw error;
}
} }
import { gscPost} from '@/utils/gscRequest'; import { gscPost } from "@/utils/gscRequest";
/** /**
* 素材分组列表 * 素材分组列表
*/ */
export async function findCategoryList(data: any) { export async function findCategoryList(data: any) {
try { return await gscPost("/knowledgeCategory/findCategoryList", data);
const response = await gscPost('/knowledgeCategory/findCategoryList', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材分组新增 * 素材分组新增
*/ */
export async function addCategory(data: any) { export async function addCategory(data: any) {
try { return await gscPost("/knowledgeCategory/addCategory", data, { returnAll:true });
const response = await gscPost('/knowledgeCategory/addCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材分组修改 * 素材分组修改
*/ */
export async function updateCategory(data: any) { export async function updateCategory(data: any) {
try { return await gscPost("/knowledgeCategory/updateCategory", data, { returnAll:true });
const response = await gscPost('/knowledgeCategory/updateCategory', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 分组列表包含的素材列表 * 分组列表包含的素材列表
*/ */
export async function findCategoryWithMaterialList(data: any) { export async function findCategoryWithMaterialList(data: any) {
try { return await gscPost("/knowledgeCategory/findCategoryWithMaterialList", data);
const response = await gscPost('/knowledgeCategory/findCategoryWithMaterialList', data);
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材列表 * 素材列表
*/ */
export async function findPageKnowledgeMaterial(data: any) { export async function findPageKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/findPageKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/findPageKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
...@@ -65,34 +40,19 @@ export async function findPageKnowledgeMaterial(data: any) { ...@@ -65,34 +40,19 @@ export async function findPageKnowledgeMaterial(data: any) {
* 素材编辑 * 素材编辑
*/ */
export async function updateKnowledgeMaterial(data: any) { export async function updateKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/updateKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/updateKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材上传 * 素材上传
*/ */
export async function saveKnowledgeMaterial(data: any) { export async function saveKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/saveKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/saveKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
/** /**
* 素材删除 * 素材删除
*/ */
export async function deleteKnowledgeMaterial(data: any) { export async function deleteKnowledgeMaterial(data: any) {
try { return await gscPost("/knowledgeMaterial/deleteKnowledgeMaterial", data, { returnAll:true });
const response = await gscPost('/knowledgeMaterial/deleteKnowledgeMaterial', data, { returnAll:true });
return response;
} catch (error) {
throw error;
}
} }
<template> <template>
<div class="card-list w-full flex flex-nowrap gap-6"> <div class="card-list w-full flex flex-nowrap gap-6">
<div <div v-for="(item, index) in data"
class="card-item flex-1 min-w-[202.5px] rounded-[10px] box-border shadow-[0_4px_12px_0_#525b6629]"
:style="{ minHeight: cardHeight }"
v-for="(item, index) in data"
:key="index" :key="index"
> class="card-item flex-1 min-w-[202.5px] rounded-[10px] box-border shadow-[0_4px_12px_0_#525b6629]"
<img class="rounded-t-[10px]" :src="`https://img02.glsx.com.cn/weapp/resource/venus-agentic/${item.iconUrl}`" alt="background"> :style="{ minHeight: cardHeight }">
<img alt="background"
class="rounded-t-[10px]"
:src="`https://img02.glsx.com.cn/weapp/resource/venus-agentic/${item.iconUrl}`">
<div class="card-item-bottom h-[102.5px] w-full pl-[16px] pr-[16px]"> <div class="card-item-bottom h-[102.5px] w-full pl-[16px] pr-[16px]">
<p class="text-[#2f3133] text-[14px] font-medium mb-1 leading-[22px] bg-red-500">{{ item.name }}</p> <p class="text-[#2f3133] text-[14px] font-medium mb-1 leading-[22px] bg-red-500">
<div class="flex justify-between" v-for="value in item.desc"> {{ item.name }}
</p>
<div v-for="value in item.desc"
:key="value"
class="flex justify-between">
<p class="h-[6px] w-[6px] bg-[#1956FE] rounded-[3px] mt-[12px] mr-1"></p> <p class="h-[6px] w-[6px] bg-[#1956FE] rounded-[3px] mt-[12px] mr-1"></p>
<p class="w-full text-[#565C66] text-[12px] leading-[18px] mt-[6px]">{{value}}</p> <p class="w-full text-[#565C66] text-[12px] leading-[18px] mt-[6px]">
{{ value }}
</p>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, PropType } from 'vue'; import { computed, PropType } from "vue";
interface DataItem { interface DataItem {
iconUrl: string; iconUrl: string;
...@@ -31,16 +37,16 @@ const props = defineProps({ ...@@ -31,16 +37,16 @@ const props = defineProps({
required: true, required: true,
}, },
source: { source: {
type: String as PropType<'train' | 'raplay' | 'other'>, type: String as PropType<"other" | "raplay" | "train">,
required: false, required: false,
default: 'other', default: "other",
}, },
}); });
const cardHeight = computed(() => { const cardHeight = computed(() => {
if (props.source === 'train') return '246px'; if (props.source === "train") return "246px";
if (props.source === 'raplay') return '204px'; if (props.source === "raplay") return "204px";
return '182px'; return "182px";
}); });
console.log('[CustomCardList] data', props.data); console.log("[CustomCardList] data", props.data);
</script> </script>
<template> <template>
<div class="flex align-center items-center h-[42px] mb-4"> <div class="flex align-center items-center h-[42px] mb-4">
<img src="/images/icon-title.png" alt="title" class="w-[4px] h-[18px] rounded-sm"> <img alt="title"
<p class="text-[14px] font-medium text-[#2F3133] ml-[12px]">{{ title }}</p> class="w-[4px] h-[18px] rounded-sm"
src="/images/icon-title.png">
<p class="text-[14px] font-medium text-[#2F3133] ml-[12px]">
{{ title }}
</p>
</div> </div>
</template> </template>
...@@ -14,6 +18,8 @@ const props = defineProps({ ...@@ -14,6 +18,8 @@ const props = defineProps({
icon: { icon: {
type: String, type: String,
required: false, required: false,
default: "",
}, },
}); });
console.log(props.icon);
</script> </script>
<template> <template>
<div class="pl-2"> <div class="pl-2">
<div <div v-for="(item, index) in workflowSteps"
v-for="(item, index) in workflowSteps"
:key="index" :key="index"
class="relative pb-8 last:pb-0" class="relative pb-8 last:pb-0">
>
<!-- 连接线 --> <!-- 连接线 -->
<div <div v-if="index !== workflowSteps.length - 1"
v-if="index !== workflowSteps.length - 1"
class="absolute left-3.5 top-8 -ml-px h-full w-[2px] bg-gray-200"
aria-hidden="true" aria-hidden="true"
></div> class="absolute left-3.5 top-8 -ml-px h-full w-[2px] bg-gray-200">
</div>
<div class="group relative flex items-start"> <div class="group relative flex items-start">
<!-- 步骤数字 --> <!-- 步骤数字 -->
<span <span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-50 ring-4 ring-white">
class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-50 ring-4 ring-white"
>
<span class="text-sm font-bold text-blue-600">{{ index + 1 }}</span> <span class="text-sm font-bold text-blue-600">{{ index + 1 }}</span>
</span> </span>
<!-- 步骤内容 --> <!-- 步骤内容 -->
...@@ -25,13 +20,11 @@ ...@@ -25,13 +20,11 @@
{{ item.title }} {{ item.title }}
</h4> </h4>
<div v-if="Array.isArray(item.desc)"> <div v-if="Array.isArray(item.desc)">
<p <p v-for="value in item.desc"
class="mt-[4px] text-[12px] font-normal text-[#969AA3]" :key="value"
v-for="value in item.desc" class="mt-[4px] text-[12px] font-normal text-[#969AA3]">
> <span class="mb-[2px] mr-[4px] inline-block h-[5px] w-[5px] rounded-[3px] bg-[#1956FE]">
<span </span>
class="mb-[2px] mr-[4px] inline-block h-[5px] w-[5px] rounded-[3px] bg-[#1956FE]"
></span>
{{ value }} {{ value }}
</p> </p>
</div> </div>
...@@ -47,7 +40,8 @@ ...@@ -47,7 +40,8 @@
</template> </template>
<script setup> <script setup>
import { defineProps } from 'vue'; import { defineProps } from "vue";
const props = defineProps({ const props = defineProps({
workflowSteps: { workflowSteps: {
type: Array, type: Array,
......
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper'; import type { QiankunProps } from "vite-plugin-qiankun/dist/helper";
import type { App as VueApp } from "vue";
import { createApp } from "vue";
import CommonUI from "@venus/common-ui-vue";
import ElementPlus from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn"; import zhCn from "element-plus/es/locale/lang/zh-cn";
import type { App as VueApp } from 'vue';
import { createApp } from 'vue';
import ElementPlus from 'element-plus';
// import './styles/element/index.scss'; // import './styles/element/index.scss';
import { createPinia } from 'pinia'; import { createPinia } from "pinia";
import { import {
qiankunWindow, qiankunWindow,
renderWithQiankun, renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper'; } from "vite-plugin-qiankun/dist/helper";
import CommonUI from '@venus/common-ui-vue';
import App from './App.vue'; import App from "./App.vue";
import { createRouter } from './router'; import { createRouter } from "./router";
import 'element-plus/dist/index.css'; import "element-plus/dist/index.css";
import './assets/style.css'; import "./assets/style.css";
let app: null | VueApp<Element> = null; let app: null | VueApp<Element> = null;
let router: any = null; let router: any = null;
...@@ -37,21 +41,21 @@ async function render(props: QiankunProps = {}) { ...@@ -37,21 +41,21 @@ async function render(props: QiankunProps = {}) {
// 配置 Element-Plus // 配置 Element-Plus
app.use(ElementPlus, { app.use(ElementPlus, {
//改中文 // 改中文
locale: zhCn locale: zhCn
}); });
// 配置路由 - 根据是否在 qiankun 环境中使用不同的 base // 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? props.routerBase || '/assisant/' ? props.routerBase || "/assisant/"
: '/'; : "/";
router = createRouter(routerBase); router = createRouter(routerBase);
app.use(router); app.use(router);
// 初始化通信管理器(仅在 qiankun 环境中) // 初始化通信管理器(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) { if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
const { subAppCommunication } = await import('./utils/communication'); const { subAppCommunication } = await import("./utils/communication");
subAppCommunication.init(props); subAppCommunication.init(props);
// 将通信管理器挂载到全局属性,方便组件使用 // 将通信管理器挂载到全局属性,方便组件使用
...@@ -61,26 +65,26 @@ async function render(props: QiankunProps = {}) { ...@@ -61,26 +65,26 @@ async function render(props: QiankunProps = {}) {
// 初始化 GSC Request(仅在 qiankun 环境中) // 初始化 GSC Request(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.getGscRequest) { if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.getGscRequest) {
try { try {
const { gscRequestManager } = await import('./utils/gscRequest'); const { gscRequestManager } = await import("./utils/gscRequest");
await gscRequestManager.init(props); await gscRequestManager.init(props);
// 将 GSC Request 管理器挂载到全局属性,方便组件使用 // 将 GSC Request 管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$gscRequest = gscRequestManager; app.config.globalProperties.$gscRequest = gscRequestManager;
// console.log('[子应用] GSC Request 管理器已初始化并挂载'); // console.log('[子应用] GSC Request 管理器已初始化并挂载');
} catch (error) { } catch (error) {
console.error('[子应用] GSC Request 管理器初始化失败:', error); console.error("[子应用] GSC Request 管理器初始化失败:", error);
} }
} }
// 挂载应用 // 挂载应用
const containerEl = container const containerEl = container
? container.querySelector('#app') ? container.querySelector("#app")
: document.querySelector('#app'); : document.querySelector("#app");
if (containerEl) { if (containerEl) {
app.mount(containerEl as Element); app.mount(containerEl as Element);
} else { } else {
console.error('[Vue3 微应用] 挂载容器未找到'); console.error("[Vue3 微应用] 挂载容器未找到");
} }
} }
...@@ -114,14 +118,14 @@ export async function mount(props: QiankunProps) { ...@@ -114,14 +118,14 @@ export async function mount(props: QiankunProps) {
* 应用每次切出/卸载都会调用 unmount 方法 * 应用每次切出/卸载都会调用 unmount 方法
*/ */
export async function unmount(props: QiankunProps) { export async function unmount(props: QiankunProps) {
console.log('[子应用] unmount', props); console.log("[子应用] unmount", props);
// 销毁通信管理器 // 销毁通信管理器
if (qiankunWindow.__POWERED_BY_QIANKUN__) { if (qiankunWindow.__POWERED_BY_QIANKUN__) {
const { subAppCommunication } = await import('./utils/communication'); const { subAppCommunication } = await import("./utils/communication");
subAppCommunication.destroy(); subAppCommunication.destroy();
// 销毁 GSC Request 管理器 // 销毁 GSC Request 管理器
const { gscRequestManager } = await import('./utils/gscRequest'); const { gscRequestManager } = await import("./utils/gscRequest");
gscRequestManager.destroy(); gscRequestManager.destroy();
} }
...@@ -139,7 +143,7 @@ export async function unmount(props: QiankunProps) { ...@@ -139,7 +143,7 @@ export async function unmount(props: QiankunProps) {
* 主应用向子应用下发新的props时触发 * 主应用向子应用下发新的props时触发
*/ */
export async function update(props: QiankunProps) { export async function update(props: QiankunProps) {
console.log('[Vue3 微应用] update', props); console.log("[Vue3 微应用] update", props);
} }
// 使用 vite-plugin-qiankun 提供的渲染函数 // 使用 vite-plugin-qiankun 提供的渲染函数
......
// 此文件由 auto-routes 插件自动生成,请勿手动编辑
// 如需自定义路由,请在 vite.config.ts 中配置 customRules
// 生成时间: 2026/1/23 10:58:16
import type { RouteRecordRaw } from 'vue-router';
export const autoRoutes: RouteRecordRaw[] = [
{
path: "/assistant/index",
id: "assistant",
title: "Assistant",
icon: "",
level: 1,
hidden: false,
meta: {
"authority": "assistant",
"keepAlive": false,
"requiresAuth": false,
"title": "Assistant"
},
children: [
{
path: "add-update",
id: "assistant-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "assistant:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/manage-agentic/index",
id: "manage-agentic",
title: "ManageAgentic",
icon: "",
level: 1,
hidden: false,
meta: {
"authority": "manage-agentic",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageAgentic"
},
},
{
path: "/manage-konw/index",
id: "manage-konw",
title: "ManageKonw",
icon: "",
level: 1,
hidden: false,
meta: {
"authority": "manage-konw",
"keepAlive": false,
"requiresAuth": false,
"title": "ManageKonw"
},
children: [
{
path: "add-update",
id: "manage-konw-add-update",
title: "AddUpdate",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "manage-konw:add-update",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "AddUpdate"
},
}
],
},
{
path: "/communication",
id: ".-communication",
title: "Communication",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "communication",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Communication"
},
},
{
path: "/home",
id: ".-home",
title: "Home",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "home",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Home"
},
},
{
path: "/settings",
id: ".-settings",
title: "Settings",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "settings",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "Settings"
},
},
{
path: "/user",
id: ".-user",
title: "User",
icon: "",
level: 2,
hidden: false,
meta: {
"authority": "user",
"keepAlive": false,
"order": 1,
"requiresAuth": false,
"title": "User"
},
},
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/NotFound.vue"),
meta: {
"title": "404",
"hidden": true
},
}
];
import type { Router, RouteRecordRaw, RouterOptions } from 'vue-router'; import type { Router, RouteRecordRaw, RouterOptions } from "vue-router";
import { createRouter as _createRouter, createWebHistory } from 'vue-router'; import { createRouter as _createRouter, createWebHistory } from "vue-router";
// 手动配置的路由 // 手动配置的路由
// 注意:auto-routes.ts 文件仅作为示例,不在项目中使用 // 注意:auto-routes.ts 文件仅作为示例,不在项目中使用
const routes: RouteRecordRaw[] = [ const routes: RouteRecordRaw[] = [
{ {
path: '/', path: "/",
name: 'Home', name: "Home",
component: () => import('@/views/Home.vue'), component: () => import("@/views/Home.vue"),
meta: { meta: {
title: '首页', title: "首页",
}, },
}, },
{ {
path: '/managekonw', path: "/managekonw",
name: 'ManageKonw', name: "ManageKonw",
component: () => import('@/views/ManageKonw/index.vue'), component: () => import("@/views/ManageKonw/index.vue"),
meta: { meta: {
title: '知识管理', title: "知识管理",
}, },
}, },
{ {
path: '/assistant', path: "/assistant",
name: 'Assistant', name: "Assistant",
component: () => import('@/views/Assistant/index.vue'), component: () => import("@/views/Assistant/index.vue"),
meta: { meta: {
title: '岗位助理配置', title: "岗位助理配置",
}, },
}, },
{ {
path: '/manageagentic', path: "/manageagentic",
name: 'ManageAgentic', name: "ManageAgentic",
component: () => import('@/views/ManageAgentic/index.vue'), component: () => import("@/views/ManageAgentic/index.vue"),
meta: { meta: {
title: '智能体管理', title: "智能体管理",
}, },
}, },
{ {
path: '/assistant/add', path: "/assistant/add",
name: 'AssistantAdd', name: "AssistantAdd",
component: () => import('@/views/Assistant/addUpdate.vue'), component: () => import("@/views/Assistant/addUpdate.vue"),
meta: { meta: {
title: '新增智能体', title: "新增智能体",
}, },
}, },
{ {
path: '/assistant/edit/:id', path: "/assistant/edit/:id",
name: 'AssistantEdit', name: "AssistantEdit",
component: () => import('@/views/Assistant/addUpdate.vue'), component: () => import("@/views/Assistant/addUpdate.vue"),
meta: { meta: {
title: '编辑', title: "编辑",
}, },
}, },
{ {
path: '/user', path: "/user",
name: 'User', name: "User",
component: () => import('@/views/User.vue'), component: () => import("@/views/User.vue"),
meta: { meta: {
title: '用户管理', title: "用户管理",
}, },
}, },
{ {
path: '/settings', path: "/settings",
name: 'Settings', name: "Settings",
component: () => import('@/views/Settings.vue'), component: () => import("@/views/Settings.vue"),
meta: { meta: {
title: '系统设置', title: "系统设置",
}, },
}, },
{ {
path: '/communication', path: "/communication",
name: 'Communication', name: "Communication",
component: () => import('@/views/Communication.vue'), component: () => import("@/views/Communication.vue"),
meta: { meta: {
title: '通信示例', title: "通信示例",
}, },
}, },
{ {
path: '/:pathMatch(.*)*', path: "/:pathMatch(.*)*",
name: 'NotFound', name: "NotFound",
component: () => import('@/views/NotFound.vue'), component: () => import("@/views/NotFound.vue"),
}, },
]; ];
// 转换为 RouterOptions 需要的类型 // 转换为 RouterOptions 需要的类型
const routerRoutes = routes as unknown as RouterOptions['routes']; const routerRoutes = routes as unknown as RouterOptions["routes"];
/** /**
* 创建路由实例 * 创建路由实例
* @param base 路由 base 路径 * @param base 路由 base 路径
*/ */
export function createRouter(base: string = '/'): Router { export function createRouter(base: string = "/"): Router {
const router = _createRouter({ const router = _createRouter({
history: createWebHistory(base), history: createWebHistory(base),
routes: routerRoutes, routes: routerRoutes,
...@@ -107,7 +107,7 @@ export function createRouter(base: string = '/'): Router { ...@@ -107,7 +107,7 @@ export function createRouter(base: string = '/'): Router {
}); });
router.afterEach((to, from) => { router.afterEach((to, from) => {
console.log('[Vue3 微应用] 路由切换:', from.path, '->', to.path); console.log("[Vue3 微应用] 路由切换:", from.path, "->", to.path);
}); });
return router; return router;
......
@forward 'element-plus/theme-chalk/src/common/var.scss' with ( @forward "element-plus/theme-chalk/src/common/var.scss" with (
// $button: (
// "color": #666666,
// "border-color": #E1E3E6,
// "hover-bg-color": #3d6eff,
// "hover-text-color": #ffffff,
// "hover-border-color": #3d6eff,
// )
$colors: ( $colors: (
'primary': ( "primary": (
'base': #3d6eff, "base": #3d6eff,
) ),
) )
); );
@use 'element-plus/theme-chalk/src/index.scss' as *; @use "element-plus/theme-chalk/src/index.scss" as *;
/** /**
* glsk-oss-jssdk 类型声明 * glsk-oss-jssdk 类型声明
*/ */
declare module 'glsk-oss-jssdk' { declare module "glsk-oss-jssdk" {
/** /**
* 上传结果接口 * 上传结果接口
*/ */
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
* 扩展 Vue Router 的 RouteRecordRaw 接口,支持自定义字段 * 扩展 Vue Router 的 RouteRecordRaw 接口,支持自定义字段
*/ */
import 'vue-router'; import "vue-router";
declare module 'vue-router' { declare module "vue-router" {
interface RouteRecordRaw { interface RouteRecordRaw {
/** 路由唯一标识 */ /** 路由唯一标识 */
id?: string; id?: string;
......
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'; import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
/** /**
* 获取子应用的基础 URL * 获取子应用的基础 URL
...@@ -22,7 +22,7 @@ export function getSubAppBaseUrl(): string { ...@@ -22,7 +22,7 @@ export function getSubAppBaseUrl(): string {
// 尝试将 publicPath 解析为完整 URL // 尝试将 publicPath 解析为完整 URL
const url = new URL(publicPath); const url = new URL(publicPath);
// 如果 publicPath 是完整 URL(包含协议),返回其 origin // 如果 publicPath 是完整 URL(包含协议),返回其 origin
if (url.protocol.startsWith('http')) { if (url.protocol.startsWith("http")) {
return url.origin; return url.origin;
} }
} catch { } catch {
...@@ -30,11 +30,11 @@ export function getSubAppBaseUrl(): string { ...@@ -30,11 +30,11 @@ export function getSubAppBaseUrl(): string {
} }
// 在开发环境中,子应用通常运行在独立端口(如 8081) // 在开发环境中,子应用通常运行在独立端口(如 8081)
const isDev = (import.meta as any).env?.MODE === 'development'; const isDev = (import.meta as any).env?.MODE === "development";
if (isDev) { if (isDev) {
// 开发环境:子应用运行在独立端口 8081(与 vite.config.ts 中的 PORT 一致) // 开发环境:子应用运行在独立端口 8081(与 vite.config.ts 中的 PORT 一致)
const devPort = '8081'; const devPort = "8081";
const host = window.location.hostname; const host = window.location.hostname;
return `http://${host}:${devPort}`; return `http://${host}:${devPort}`;
} }
...@@ -45,7 +45,7 @@ export function getSubAppBaseUrl(): string { ...@@ -45,7 +45,7 @@ export function getSubAppBaseUrl(): string {
} }
// 如果无法从 publicPath 获取,根据环境判断 // 如果无法从 publicPath 获取,根据环境判断
const isDev = (import.meta as any).env?.MODE === 'development'; const isDev = (import.meta as any).env?.MODE === "development";
if (isDev) { if (isDev) {
// 开发环境:使用默认端口 // 开发环境:使用默认端口
const host = window.location.hostname; const host = window.location.hostname;
...@@ -67,7 +67,7 @@ export function getSubAppBaseUrl(): string { ...@@ -67,7 +67,7 @@ export function getSubAppBaseUrl(): string {
*/ */
export function getImageUrl(imagePath: string): string { export function getImageUrl(imagePath: string): string {
if (!imagePath) { if (!imagePath) {
return ''; return "";
} }
// 如果已经是完整的 URL(包含 http:// 或 https://),直接返回 // 如果已经是完整的 URL(包含 http:// 或 https://),直接返回
...@@ -91,7 +91,7 @@ export function getImageUrl(imagePath: string): string { ...@@ -91,7 +91,7 @@ export function getImageUrl(imagePath: string): string {
} }
// 如果是相对路径(以 / 开头),拼接子应用的基础 URL // 如果是相对路径(以 / 开头),拼接子应用的基础 URL
if (imagePath.startsWith('/')) { if (imagePath.startsWith("/")) {
const baseUrl = getSubAppBaseUrl(); const baseUrl = getSubAppBaseUrl();
return `${baseUrl}${imagePath}`; return `${baseUrl}${imagePath}`;
} }
......
import { onUnmounted } from 'vue'; import { onUnmounted } from "vue";
/** /**
* 全局状态接口定义(与基座保持一致) * 全局状态接口定义(与基座保持一致)
...@@ -12,7 +12,7 @@ export interface GlobalState { ...@@ -12,7 +12,7 @@ export interface GlobalState {
notifications: Notification[]; notifications: Notification[];
theme: { theme: {
mode: 'dark' | 'light'; mode: "dark" | "light";
primaryColor: string; primaryColor: string;
}; };
...@@ -34,7 +34,7 @@ export interface Notification { ...@@ -34,7 +34,7 @@ export interface Notification {
message: string; message: string;
timestamp: number; timestamp: number;
title: string; title: string;
type: 'error' | 'info' | 'success' | 'warning'; type: "error" | "info" | "success" | "warning";
} }
/** /**
...@@ -102,7 +102,7 @@ class SubAppCommunicationManager { ...@@ -102,7 +102,7 @@ class SubAppCommunicationManager {
true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据 true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
); );
// 只在返回值是函数时才赋值 // 只在返回值是函数时才赋值
if (typeof unsubscribeFn === 'function') { if (typeof unsubscribeFn === "function") {
this.unsubscribe = unsubscribeFn; this.unsubscribe = unsubscribeFn;
} }
} }
...@@ -135,7 +135,7 @@ class SubAppCommunicationManager { ...@@ -135,7 +135,7 @@ class SubAppCommunicationManager {
* 向基座发送通知 * 向基座发送通知
* @param notification 通知消息 * @param notification 通知消息
*/ */
sendNotification(notification: Omit<Notification, 'id' | 'timestamp'>) { sendNotification(notification: Omit<Notification, "id" | "timestamp">) {
if (!this.props?.setGlobalState) { if (!this.props?.setGlobalState) {
return; return;
} }
...@@ -146,14 +146,14 @@ class SubAppCommunicationManager { ...@@ -146,14 +146,14 @@ class SubAppCommunicationManager {
...notification, ...notification,
id: Date.now().toString(), id: Date.now().toString(),
timestamp: Date.now(), timestamp: Date.now(),
from: notification.from || 'Vue子应用', from: notification.from || "Vue子应用",
}; };
// 通过修改全局状态来添加通知 // 通过修改全局状态来添加通知
// 注意:这里需要基座的 communication manager 来处理通知添加逻辑 // 注意:这里需要基座的 communication manager 来处理通知添加逻辑
// 所以我们实际上是触发一个状态变化,让基座来处理 // 所以我们实际上是触发一个状态变化,让基座来处理
this.setGlobalState({ this.setGlobalState({
notifications: [newNotification] as any, // 基座会合并到现有通知列表 notifications: [ newNotification ] as any, // 基座会合并到现有通知列表
}); });
} }
...@@ -192,7 +192,7 @@ export function useGlobalState( ...@@ -192,7 +192,7 @@ export function useGlobalState(
* 便捷方法:发送通知到基座 * 便捷方法:发送通知到基座
*/ */
export function notify( export function notify(
type: Notification['type'], type: Notification["type"],
title: string, title: string,
message: string, message: string,
) { ) {
......
import type { Request } from 'glsk-toolkit'; import type { Request } from "glsk-toolkit";
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper'; import type { QiankunProps } from "vite-plugin-qiankun/dist/helper";
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
/** /**
* GSC Request 管理器 * GSC Request 管理器
* 用于管理从基座获取的 Request 实例 * 用于管理从基座获取的 Request 实例
*/ */
class GscRequestManager { class GscRequestManager {
private requestInstance: Request | null = null;
private getGscRequestFn: (() => Promise<Request>) | null = null; private getGscRequestFn: (() => Promise<Request>) | null = null;
private initPromise: Promise<Request> | null = null; private initPromise: null | Promise<Request> = null;
private requestInstance: null | Request = null;
/** /**
* 初始化 GSC Request(在子应用 render 函数中调用) * 销毁管理器
* @param props qiankun 传递的 props
*/ */
async init(props: QiankunProps) { destroy() {
if (!qiankunWindow.__POWERED_BY_QIANKUN__) { this.requestInstance = null;
console.warn('[GSC Request] 非 qiankun 环境,无法获取 Request 实例'); this.getGscRequestFn = null;
return; this.initPromise = null;
}
if (!props.getGscRequest) {
console.warn('[GSC Request] props 中未找到 getGscRequest 函数');
return;
}
this.getGscRequestFn = props.getGscRequest;
try {
if (this.getGscRequestFn) {
this.requestInstance = await this.getGscRequestFn();
}
} catch (error) {
console.error('[GSC Request] 实例初始化失败:', error);
throw error;
}
} }
/** /**
...@@ -66,24 +49,42 @@ class GscRequestManager { ...@@ -66,24 +49,42 @@ class GscRequestManager {
} }
throw new Error( throw new Error(
'[GSC Request] Request 未初始化,请确保在 qiankun 环境中运行并已调用 init 方法', "[GSC Request] Request 未初始化,请确保在 qiankun 环境中运行并已调用 init 方法",
); );
} }
/** /**
* 检查 Request 是否已初始化 * 初始化 GSC Request(在子应用 render 函数中调用)
* @param props qiankun 传递的 props
*/ */
isInitialized(): boolean { async init(props: QiankunProps) {
return this.requestInstance !== null; if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
console.warn("[GSC Request] 非 qiankun 环境,无法获取 Request 实例");
return;
}
if (!props.getGscRequest) {
console.warn("[GSC Request] props 中未找到 getGscRequest 函数");
return;
}
this.getGscRequestFn = props.getGscRequest;
try {
if (this.getGscRequestFn) {
this.requestInstance = await this.getGscRequestFn();
}
} catch (error) {
console.error("[GSC Request] 实例初始化失败:", error);
throw error;
}
} }
/** /**
* 销毁管理器 * 检查 Request 是否已初始化
*/ */
destroy() { isInitialized(): boolean {
this.requestInstance = null; return this.requestInstance !== null;
this.getGscRequestFn = null;
this.initPromise = null;
} }
} }
......
import GlOssApi from 'glsk-oss-jssdk'; import GlOssApi from "glsk-oss-jssdk";
/** /**
* 上传结果接口 * 上传结果接口
...@@ -32,16 +32,6 @@ class OssUploadManager { ...@@ -32,16 +32,6 @@ class OssUploadManager {
private ossApi: GlOssApi | null = null; private ossApi: GlOssApi | null = null;
/** /**
* 初始化 OSS API 实例
*/
private getOssApi(): GlOssApi {
if (!this.ossApi) {
this.ossApi = new GlOssApi();
}
return this.ossApi;
}
/**
* 上传文件 * 上传文件
* @param file 要上传的文件 * @param file 要上传的文件
* @param options 上传配置选项 * @param options 上传配置选项
...@@ -52,7 +42,7 @@ class OssUploadManager { ...@@ -52,7 +42,7 @@ class OssUploadManager {
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult> { ): Promise<UploadResult> {
if (!file) { if (!file) {
throw new Error('文件不能为空'); throw new Error("文件不能为空");
} }
const ossApi = this.getOssApi(); const ossApi = this.getOssApi();
...@@ -85,7 +75,7 @@ class OssUploadManager { ...@@ -85,7 +75,7 @@ class OssUploadManager {
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult[]> { ): Promise<UploadResult[]> {
if (!files || files.length === 0) { if (!files || files.length === 0) {
throw new Error('文件列表不能为空'); throw new Error("文件列表不能为空");
} }
const uploadPromises = files.map((file) => const uploadPromises = files.map((file) =>
...@@ -94,6 +84,16 @@ class OssUploadManager { ...@@ -94,6 +84,16 @@ class OssUploadManager {
return Promise.all(uploadPromises); return Promise.all(uploadPromises);
} }
/**
* 初始化 OSS API 实例
*/
private getOssApi(): GlOssApi {
if (!this.ossApi) {
this.ossApi = new GlOssApi();
}
return this.ossApi;
}
} }
// 导出单例实例 // 导出单例实例
...@@ -170,14 +170,14 @@ export async function uploadFiles( ...@@ -170,14 +170,14 @@ export async function uploadFiles(
* ``` * ```
*/ */
export async function uploadFromInput( export async function uploadFromInput(
fileInput: HTMLInputElement | FileList | File[], fileInput: File[] | FileList | HTMLInputElement,
options: UploadOptions = {}, options: UploadOptions = {},
): Promise<UploadResult | UploadResult[]> { ): Promise<UploadResult | UploadResult[]> {
let files: File[] = []; let files: File[] = [];
if (fileInput instanceof HTMLInputElement) { if (fileInput instanceof HTMLInputElement) {
if (!fileInput.files || fileInput.files.length === 0) { if (!fileInput.files || fileInput.files.length === 0) {
throw new Error('请选择文件'); throw new Error("请选择文件");
} }
files = Array.from(fileInput.files); files = Array.from(fileInput.files);
} else if (fileInput instanceof FileList) { } else if (fileInput instanceof FileList) {
...@@ -185,7 +185,7 @@ export async function uploadFromInput( ...@@ -185,7 +185,7 @@ export async function uploadFromInput(
} else if (Array.isArray(fileInput)) { } else if (Array.isArray(fileInput)) {
files = fileInput; files = fileInput;
} else { } else {
throw new Error('不支持的文件输入类型'); throw new TypeError("不支持的文件输入类型");
} }
if (files.length === 1) { if (files.length === 1) {
......
...@@ -60,7 +60,7 @@ const formatTime = (timestamp: number) => { ...@@ -60,7 +60,7 @@ const formatTime = (timestamp: number) => {
// 发送通知 // 发送通知
const sendNotification = async () => { const sendNotification = async () => {
if (!notificationForm.title || !notificationForm.message) { if (!notificationForm.title || !notificationForm.message) {
alert("请填写标题和内容"); console.warn("请填写标题和内容");
return; return;
} }
......
...@@ -5,15 +5,19 @@ ...@@ -5,15 +5,19 @@
<!-- ================= 1. 智能体概况 ================= --> <!-- ================= 1. 智能体概况 ================= -->
<section> <section>
<!-- 标题头 --> <!-- 标题头 -->
<CustomHeaderTitle title="智能体概况"/> <CustomHeaderTitle title="智能体概况" />
<!-- 卡片内容 --> <!-- 卡片内容 -->
<div class="rounded-[8px] p-6 shadow-[0_4px_12px_0_#525b6629] transition-shadow"> <div class="rounded-[8px] p-6 shadow-[0_4px_12px_0_#525b6629] transition-shadow">
<div class="flex items-center"> <div class="flex items-center">
<img src="/images/icon-agentic-practice.png" class="h-[32px] w-[32px] mr-[12px] rounded-full bg-red-200" /> <img class="h-[32px] w-[32px] mr-[12px] rounded-full bg-red-200" src="/images/icon-agentic-practice.png" />
<div> <div>
<p class="text-[14px] font-medium text-[#2F3133]">对练智能体</p> <p class="text-[14px] font-medium text-[#2F3133]">
<p class="text-[12px] text-[#969AA3] font-normal mt-[4px]">销售和客服对话训练</p> 对练智能体
</p>
<p class="text-[12px] text-[#969AA3] font-normal mt-[4px]">
销售和客服对话训练
</p>
</div> </div>
</div> </div>
<!-- 文本内容 --> <!-- 文本内容 -->
...@@ -25,24 +29,32 @@ ...@@ -25,24 +29,32 @@
<!-- ================= 2. 工作流程 ================= --> <!-- ================= 2. 工作流程 ================= -->
<section> <section>
<CustomHeaderTitle title="工作流程"/> <CustomHeaderTitle title="工作流程" />
<CustomWorkFlow :workflowSteps="workflowSteps" /> <CustomWorkFlow :workflow-steps="workflowSteps" />
</section> </section>
<!-- ================= 3. 质检规则管理 ================= --> <!-- ================= 3. 质检规则管理 ================= -->
<section> <section>
<CustomHeaderTitle title="客户角色类型"/> <CustomHeaderTitle title="客户角色类型" />
<!-- 卡片 --> <!-- 卡片 -->
<div class="grid grid-cols-3 gap-x-8 gap-y-4"> <div class="grid grid-cols-3 gap-x-8 gap-y-4">
<div class="min-w-[278px] h-[94px] rounded-[10px] bg-white shadow-[0_4px_12px_0_#525b6629] flex items-start p-[16px]" v-for="(item, index) in roleTypes" :key="index"> <div v-for="(item, index) in roleTypes"
:key="index"
class="min-w-[278px] h-[94px] rounded-[10px] bg-white shadow-[0_4px_12px_0_#525b6629] flex items-start p-[16px]">
<div class="shrink-0 w-[38px] h-[38px] rounded-lg overflow-hidden mr-[12px] bg-gray-50 flex items-center justify-center"> <div class="shrink-0 w-[38px] h-[38px] rounded-lg overflow-hidden mr-[12px] bg-gray-50 flex items-center justify-center">
<img :src="`https://img02.glsx.com.cn/weapp/resource/venus-agentic/${item.iconUrl}`" alt="头像" class="w-full h-full object-cover" /> <img alt="头像"
class="w-full h-full object-cover"
:src="`https://img02.glsx.com.cn/weapp/resource/venus-agentic/${item.iconUrl}`" />
</div> </div>
<div class="flex-1 flex flex-col justify-start min-w-0"> <div class="flex-1 flex flex-col justify-start min-w-0">
<p class="text-[#2f3133] text-[14px] font-medium mb-1 leading-[22px] ">{{item.name}}</p> <p class="text-[#2f3133] text-[14px] font-medium mb-1 leading-[22px] ">
<p class="text-[#969aa3] text-[12px] font-normal m-0 leading-[18px] overflow-hidden text-ellipsis line-clamp-2">{{item.desc}}</p> {{ item.name }}
</p>
<p class="text-[#969aa3] text-[12px] font-normal m-0 leading-[18px] overflow-hidden text-ellipsis line-clamp-2">
{{ item.desc }}
</p>
</div> </div>
</div> </div>
</div> </div>
...@@ -50,7 +62,7 @@ ...@@ -50,7 +62,7 @@
<!-- ================= 4. 核心功能 ================= --> <!-- ================= 4. 核心功能 ================= -->
<section class="mt-[48px]"> <section class="mt-[48px]">
<CustomHeaderTitle title="核心功能"/> <CustomHeaderTitle title="核心功能" />
<CustomCardList :data="coreFunctions" /> <CustomCardList :data="coreFunctions" />
</section> </section>
...@@ -62,78 +74,78 @@ ...@@ -62,78 +74,78 @@
// 1. 工作流程数据 // 1. 工作流程数据
const workflowSteps = [ const workflowSteps = [
{ {
title: '外部指令输入', title: "外部指令输入",
desc: '支持输入对练主题、产品信息、客户画像等指令,智能体根据指令生成相应的对话场景' desc: "支持输入对练主题、产品信息、客户画像等指令,智能体根据指令生成相应的对话场景"
}, },
{ {
title: '对练目标设定', title: "对练目标设定",
desc: '可设置具体的训练目标,如产品介绍、异议处理、促成交易等,智能体据此调整对话策略' desc: "可设置具体的训练目标,如产品介绍、异议处理、促成交易等,智能体据此调整对话策略"
}, },
{ {
title: '通过标准设定', title: "通过标准设定",
desc: '系统内置练习通过标准,包括对话流畅度、产品知识准确性、应对技巧等多维度评估' desc: "系统内置练习通过标准,包括对话流畅度、产品知识准确性、应对技巧等多维度评估"
}, },
{ {
title: '会话场景生成', title: "会话场景生成",
desc: '智能体自动生成符合设定目标的对话场景,包括初始问题、常见异议和特殊情况' desc: "智能体自动生成符合设定目标的对话场景,包括初始问题、常见异议和特殊情况"
}, },
{ {
title: '移动端H5练习', title: "移动端H5练习",
desc: '员工可在移动端H5页面进行对话练习,获得即时反馈和改进建议' desc: "员工可在移动端H5页面进行对话练习,获得即时反馈和改进建议"
} }
]; ];
const roleTypes = [ const roleTypes = [
{ {
name: '独裁型客户', name: "独裁型客户",
iconUrl: '/icon-agentic-role01.png', iconUrl: "/icon-agentic-role01.png",
desc: '具有强烈的控制欲,决策迅速,注重效率,对产品细节要求高' desc: "具有强烈的控制欲,决策迅速,注重效率,对产品细节要求高"
}, },
{ {
name: '人际型客户', name: "人际型客户",
iconUrl: '/icon-agentic-role02.png', iconUrl: "/icon-agentic-role02.png",
desc: '注重人际关系,友好健谈,容易建立信任,但决策可能受情感影响' desc: "注重人际关系,友好健谈,容易建立信任,但决策可能受情感影响"
}, },
{ {
name: '犹豫型客户', name: "犹豫型客户",
iconUrl: '/icon-agentic-role03.png', iconUrl: "/icon-agentic-role03.png",
desc: '顾虑较多,决策缓慢,需要更多的产品信息和客户见证' desc: "顾虑较多,决策缓慢,需要更多的产品信息和客户见证"
}, },
{ {
name: '沉默型客户', name: "沉默型客户",
iconUrl: '/icon-agentic-role04.png', iconUrl: "/icon-agentic-role04.png",
desc: '不善言辞,需要引导,决策谨慎,注重产品可靠性和口碑' desc: "不善言辞,需要引导,决策谨慎,注重产品可靠性和口碑"
}, },
{ {
name: '分析型客户', name: "分析型客户",
iconUrl: '/icon-agentic-role05.png', iconUrl: "/icon-agentic-role05.png",
desc: '理性思考,注重数据和事实,决策过程长,需要充分的信息支持' desc: "理性思考,注重数据和事实,决策过程长,需要充分的信息支持"
}, },
{ {
name: '价格型客户', name: "价格型客户",
iconUrl: '/icon-agentic-role06.png', iconUrl: "/icon-agentic-role06.png",
desc: '对价格敏感,追求性价比,注重产品优惠和折扣' desc: "对价格敏感,追求性价比,注重产品优惠和折扣"
} }
]; ];
const coreFunctions = [ const coreFunctions = [
{ {
name: '岗位助理配置', name: "岗位助理配置",
iconUrl: '/icon-agentic-core01.png', iconUrl: "/icon-agentic-core01.png",
desc: ['无需复杂配置,可直接与岗位助理系统对接,自动获取相关岗位信息'] desc: [ "无需复杂配置,可直接与岗位助理系统对接,自动获取相关岗位信息" ]
}, },
{ {
name: '智能体编排', name: "智能体编排",
iconUrl: '/icon-agentic-core02.png', iconUrl: "/icon-agentic-core02.png",
desc: ['支持与其他智能体协同工作,如培训智能体、质检智能体等,形成完整的训练体系'] desc: [ "支持与其他智能体协同工作,如培训智能体、质检智能体等,形成完整的训练体系" ]
}, },
{ {
name: '实时反馈', name: "实时反馈",
iconUrl: '/icon-agentic-core03.png', iconUrl: "/icon-agentic-core03.png",
desc: ['提供即时的对话分析和改进建议,帮助员工快速提升技能'] desc: [ "提供即时的对话分析和改进建议,帮助员工快速提升技能" ]
}, },
{ {
name: '学习记录追踪', name: "学习记录追踪",
iconUrl: '/icon-agentic-core04.png', iconUrl: "/icon-agentic-core04.png",
desc: ['记录员工的训练历史和进步情况,生成学习报告和能力评估'] desc: [ "记录员工的训练历史和进步情况,生成学习报告和能力评估" ]
} }
]; ];
......
<script setup> <script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'; import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { import {
ChatDotRound, ChatDotRound,
Cpu,
DataAnalysis,
Monitor, Monitor,
Notebook,
Reading, Reading,
TrendCharts, TrendCharts,
UserFilled, } from "@element-plus/icons-vue";
} from '@element-plus/icons-vue';
import AgenticQuality from './components/AgenticQuality.vue'; import AgenticPractice from "./components/AgenticPractice.vue";
import AgenticPractice from './components/AgenticPractice.vue'; import AgenticQuality from "./components/AgenticQuality.vue";
import AgenticReplay from './components/AgenticReplay.vue'; import AgenticReplay from "./components/AgenticReplay.vue";
import AgenticTrain from './components/AgenticTrain.vue'; import AgenticTrain from "./components/AgenticTrain.vue";
// 状态 // 状态
const activeMenu = ref(0); const activeMenu = ref(0);
...@@ -48,7 +44,7 @@ const handleScroll = (event) => { ...@@ -48,7 +44,7 @@ const handleScroll = (event) => {
}; };
// 调试信息,可以在控制台查看滚动数据 // 调试信息,可以在控制台查看滚动数据
console.log('滚动事件触发:', { console.log("滚动事件触发:", {
scrollTop: scrollData.value.scrollTop, scrollTop: scrollData.value.scrollTop,
scrollHeight: scrollData.value.scrollHeight, scrollHeight: scrollData.value.scrollHeight,
clientHeight: scrollData.value.clientHeight, clientHeight: scrollData.value.clientHeight,
...@@ -60,12 +56,12 @@ const initScrollListener = async () => { ...@@ -60,12 +56,12 @@ const initScrollListener = async () => {
await nextTick(); await nextTick();
if (scrollContainerRef.value) { if (scrollContainerRef.value) {
// 先移除旧的监听器(如果存在) // 先移除旧的监听器(如果存在)
scrollContainerRef.value.removeEventListener('scroll', handleScroll); scrollContainerRef.value.removeEventListener("scroll", handleScroll);
// 添加新的监听器 // 添加新的监听器
scrollContainerRef.value.addEventListener('scroll', handleScroll, { passive: true }); scrollContainerRef.value.addEventListener("scroll", handleScroll, { passive: true });
console.log('滚动监听器已绑定'); console.log("滚动监听器已绑定");
} else { } else {
console.warn('滚动容器引用未找到'); console.warn("滚动容器引用未找到");
} }
}; };
...@@ -88,7 +84,7 @@ const handleMenuClick = async (index) => { ...@@ -88,7 +84,7 @@ const handleMenuClick = async (index) => {
requestAnimationFrame(() => { requestAnimationFrame(() => {
const el = scrollContainerRef.value; const el = scrollContainerRef.value;
if (!el) return; if (!el) return;
el.scrollTo({ top: 0, left: 0, behavior: 'auto' }); el.scrollTo({ top: 0, left: 0, behavior: "auto" });
// 更新一次滚动数据,保持同步 // 更新一次滚动数据,保持同步
handleScroll({ target: el }); handleScroll({ target: el });
}); });
...@@ -97,7 +93,7 @@ const handleMenuClick = async (index) => { ...@@ -97,7 +93,7 @@ const handleMenuClick = async (index) => {
// 组件卸载前移除事件监听 // 组件卸载前移除事件监听
onUnmounted(() => { onUnmounted(() => {
if (scrollContainerRef.value) { if (scrollContainerRef.value) {
scrollContainerRef.value.removeEventListener('scroll', handleScroll); scrollContainerRef.value.removeEventListener("scroll", handleScroll);
} }
}); });
...@@ -105,31 +101,31 @@ onUnmounted(() => { ...@@ -105,31 +101,31 @@ onUnmounted(() => {
const sidebarItems = [ const sidebarItems = [
{ {
icon: Monitor, icon: Monitor,
title: '质检智能体', title: "质检智能体",
desc: '对话质量检测和评估', desc: "对话质量检测和评估",
color: 'bg-blue-500', color: "bg-blue-500",
activeColor: 'bg-blue-500', activeColor: "bg-blue-500",
}, },
{ {
icon: ChatDotRound, icon: ChatDotRound,
title: '对练智能体', title: "对练智能体",
desc: '销售和客服对话训练', desc: "销售和客服对话训练",
color: 'bg-[#2ccdce]', color: "bg-[#2ccdce]",
activeColor: 'bg-[#2ccdce]', activeColor: "bg-[#2ccdce]",
}, },
{ {
icon: TrendCharts, icon: TrendCharts,
title: '复盘智能体', title: "复盘智能体",
desc: '对话过程分析和总结', desc: "对话过程分析和总结",
color: 'bg-orange-400', color: "bg-orange-400",
activeColor: 'bg-orange-400', activeColor: "bg-orange-400",
}, },
{ {
icon: Reading, icon: Reading,
title: '培训智能体', title: "培训智能体",
desc: '员工产品知识培训', desc: "员工产品知识培训",
color: 'bg-indigo-500', color: "bg-indigo-500",
activeColor: 'bg-indigo-500', activeColor: "bg-indigo-500",
}, },
]; ];
...@@ -146,50 +142,52 @@ const sidebarItems = [ ...@@ -146,50 +142,52 @@ const sidebarItems = [
</header> </header>
<!-- 主要内容 --> <!-- 主要内容 -->
<main class="flex"> <main class="flex">
<aside <aside class="sticky top-[60px] self-start flex h-[760px] w-[278px] flex-shrink-0 flex-col bg-white ml-[24px] rounded-[12px] border border-[#E1E3E6]">
class="sticky top-[60px] self-start flex h-[760px] w-[278px] flex-shrink-0 flex-col bg-white ml-[24px] rounded-[12px] border border-[#E1E3E6]"
>
<div class="w-[278px] h-47 flex-1 space-y-2 overflow-y-auto px-4 "> <div class="w-[278px] h-47 flex-1 space-y-2 overflow-y-auto px-4 ">
<div class="mr-[16px] mt-[16px] mb-[16px] text-[14px] text-[#2F3133] font-normal">智能体列表</div> <div class="mr-[16px] mt-[16px] mb-[16px] text-[14px] text-[#2F3133] font-normal">
<div 智能体列表
v-for="(item, index) in sidebarItems" </div>
<div v-for="(item, index) in sidebarItems"
:key="index" :key="index"
@click="handleMenuClick(index)"
class="group flex cursor-pointer items-center rounded-[8px] p-4 transition-all duration-200" class="group flex cursor-pointer items-center rounded-[8px] p-4 transition-all duration-200"
:class="activeMenu === index ? 'bg-[#eef6ff]' : 'hover:bg-gray-50'" :class="activeMenu === index ? 'bg-[#eef6ff]' : 'hover:bg-gray-50'"
> @click="handleMenuClick(index)">
<!-- 图标容器 --> <!-- 图标容器 -->
<div <div class="mr-4">
class="mr-4" <img v-if="index === 0"
> class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors"
<img v-if="index === 0" src="/images/icon-agentic-quality.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" /> src="/images/icon-agentic-quality.png" />
<img v-if="index === 1" src="/images/icon-agentic-practice.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" /> <img v-if="index === 1"
<img v-if="index === 2" src="/images/icon-agentic-replay.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" /> class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors"
<img v-if="index === 3" src="/images/icon-agentic-train.png" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors" /> src="/images/icon-agentic-practice.png" />
<img v-if="index === 2"
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors"
src="/images/icon-agentic-replay.png" />
<img v-if="index === 3"
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-colors"
src="/images/icon-agentic-train.png" />
</div> </div>
<!-- 文本 --> <!-- 文本 -->
<div class="flex flex-col"> <div class="flex flex-col">
<span <span class="mb-0.5 text-base font-medium text-[#2F3133]">
class="mb-0.5 text-base font-medium text-[#2F3133]"
>
{{ item.title }} {{ item.title }}
</span> </span>
<span class="text-[12px] text-[#969AA3]">{{ <span class="text-[12px] text-[#969AA3]">
{{
item.desc item.desc
}}</span> }}
</span>
</div> </div>
</div> </div>
</div> </div>
</aside> </aside>
<!-- 右侧主要内容区 --> <!-- 右侧主要内容区 -->
<section <section ref="scrollContainerRef"
ref="scrollContainerRef"
class="flex-1 overflow-y-auto scroll-smooth bg-white pr-[24px] pb-[94px]" class="flex-1 overflow-y-auto scroll-smooth bg-white pr-[24px] pb-[94px]"
:style="{ height: 'calc(100vh - 60px)' }" :style="{ height: 'calc(100vh - 60px)' }"
@scroll="handleScroll" @scroll="handleScroll">
>
<AgenticQuality v-if="activeMenu === 0" /> <AgenticQuality v-if="activeMenu === 0" />
<AgenticPractice v-if="activeMenu === 1" /> <AgenticPractice v-if="activeMenu === 1" />
<AgenticReplay v-if="activeMenu === 2" /> <AgenticReplay v-if="activeMenu === 2" />
......
<script setup lang="ts"> <script setup lang="ts">
import { useRouter } from 'vue-router'; import { useRouter } from "vue-router";
const router = useRouter(); const router = useRouter();
/**
* 返回首页
* 若缓存中无用户token信息,则跳转到登录页面
*/
const goHome = () => { const goHome = () => {
router.push('/'); console.log("goHome");
// 检查 localStorage 中是否存在 token
const TOKEN_KEY = "scrm_access_token";
const token = localStorage.getItem(TOKEN_KEY);
if (!token) {
// 如果没有 token,跳转到登录页面
// 登录页是基座应用的页面,直接使用绝对路径
window.location.href = "/login";
} else {
// 有 token,跳转到首页
router.push("/");
}
}; };
</script> </script>
<template> <template>
<div class="notfound-view"> <div class="notfound-view">
<div class="content-card"> <div class="content-card">
<div class="error-code">404</div> <div class="error-code">
404
</div>
<h1>页面未找到</h1> <h1>页面未找到</h1>
<p>抱歉,您访问的页面不存在或已被删除</p> <p>抱歉,您访问的页面不存在或已被删除</p>
<button @click="goHome" class="btn-home">🏠 返回首页</button> <button class="btn-home" @click="goHome">
🏠 返回首页
</button>
</div> </div>
</div> </div>
</template> </template>
......
<script setup lang="ts"> <script setup lang="ts">
import { reactive } from 'vue'; import { reactive } from "vue";
interface Settings { interface Settings {
darkMode: boolean; darkMode: boolean;
...@@ -18,15 +18,15 @@ interface Settings { ...@@ -18,15 +18,15 @@ interface Settings {
} }
const defaultSettings: Settings = { const defaultSettings: Settings = {
theme: 'purple', theme: "purple",
darkMode: false, darkMode: false,
notifications: { notifications: {
desktop: true, desktop: true,
email: true, email: true,
sms: false, sms: false,
}, },
language: 'zh-CN', language: "zh-CN",
timezone: 'Asia/Shanghai', timezone: "Asia/Shanghai",
security: { security: {
twoFactor: false, twoFactor: false,
sessionTimeout: 30, sessionTimeout: 30,
...@@ -36,14 +36,11 @@ const defaultSettings: Settings = { ...@@ -36,14 +36,11 @@ const defaultSettings: Settings = {
const settings = reactive<Settings>({ ...defaultSettings }); const settings = reactive<Settings>({ ...defaultSettings });
const saveSettings = () => { const saveSettings = () => {
alert('设置已保存!'); console.log("保存设置:", settings);
}; };
const resetSettings = () => { const resetSettings = () => {
if (confirm('确定要重置为默认设置吗?')) { console.log("重置设置:", settings);
Object.assign(settings, defaultSettings);
alert('已重置为默认设置!');
}
}; };
</script> </script>
...@@ -58,19 +55,25 @@ const resetSettings = () => { ...@@ -58,19 +55,25 @@ const resetSettings = () => {
<div class="setting-item"> <div class="setting-item">
<label>主题色:</label> <label>主题色:</label>
<select v-model="settings.theme" class="select-input"> <select v-model="settings.theme" class="select-input">
<option value="purple">紫色</option> <option value="purple">
<option value="blue">蓝色</option> 紫色
<option value="green">绿色</option> </option>
<option value="orange">橙色</option> <option value="blue">
蓝色
</option>
<option value="green">
绿色
</option>
<option value="orange">
橙色
</option>
</select> </select>
</div> </div>
<div class="setting-item"> <div class="setting-item">
<label>暗黑模式:</label> <label>暗黑模式:</label>
<input <input v-model="settings.darkMode"
type="checkbox"
v-model="settings.darkMode"
class="checkbox-input" class="checkbox-input"
/> type="checkbox" />
</div> </div>
</div> </div>
...@@ -78,27 +81,21 @@ const resetSettings = () => { ...@@ -78,27 +81,21 @@ const resetSettings = () => {
<h2>🔔 通知设置</h2> <h2>🔔 通知设置</h2>
<div class="setting-item"> <div class="setting-item">
<label>桌面通知:</label> <label>桌面通知:</label>
<input <input v-model="settings.notifications.desktop"
type="checkbox"
v-model="settings.notifications.desktop"
class="checkbox-input" class="checkbox-input"
/> type="checkbox" />
</div> </div>
<div class="setting-item"> <div class="setting-item">
<label>邮件通知:</label> <label>邮件通知:</label>
<input <input v-model="settings.notifications.email"
type="checkbox"
v-model="settings.notifications.email"
class="checkbox-input" class="checkbox-input"
/> type="checkbox" />
</div> </div>
<div class="setting-item"> <div class="setting-item">
<label>短信通知:</label> <label>短信通知:</label>
<input <input v-model="settings.notifications.sms"
type="checkbox"
v-model="settings.notifications.sms"
class="checkbox-input" class="checkbox-input"
/> type="checkbox" />
</div> </div>
</div> </div>
...@@ -107,17 +104,29 @@ const resetSettings = () => { ...@@ -107,17 +104,29 @@ const resetSettings = () => {
<div class="setting-item"> <div class="setting-item">
<label>界面语言:</label> <label>界面语言:</label>
<select v-model="settings.language" class="select-input"> <select v-model="settings.language" class="select-input">
<option value="zh-CN">简体中文</option> <option value="zh-CN">
<option value="en-US">English</option> 简体中文
<option value="ja-JP">日本語</option> </option>
<option value="en-US">
English
</option>
<option value="ja-JP">
日本語
</option>
</select> </select>
</div> </div>
<div class="setting-item"> <div class="setting-item">
<label>时区:</label> <label>时区:</label>
<select v-model="settings.timezone" class="select-input"> <select v-model="settings.timezone" class="select-input">
<option value="Asia/Shanghai">北京时间 (UTC+8)</option> <option value="Asia/Shanghai">
<option value="America/New_York">纽约时间 (UTC-5)</option> 北京时间 (UTC+8)
<option value="Europe/London">伦敦时间 (UTC+0)</option> </option>
<option value="America/New_York">
纽约时间 (UTC-5)
</option>
<option value="Europe/London">
伦敦时间 (UTC+0)
</option>
</select> </select>
</div> </div>
</div> </div>
...@@ -126,28 +135,28 @@ const resetSettings = () => { ...@@ -126,28 +135,28 @@ const resetSettings = () => {
<h2>🔒 安全设置</h2> <h2>🔒 安全设置</h2>
<div class="setting-item"> <div class="setting-item">
<label>双因素认证:</label> <label>双因素认证:</label>
<input <input v-model="settings.security.twoFactor"
type="checkbox"
v-model="settings.security.twoFactor"
class="checkbox-input" class="checkbox-input"
/> type="checkbox" />
</div> </div>
<div class="setting-item"> <div class="setting-item">
<label>会话超时 (分钟):</label> <label>会话超时 (分钟):</label>
<input <input v-model="settings.security.sessionTimeout"
type="number"
v-model="settings.security.sessionTimeout"
class="number-input" class="number-input"
min="5"
max="120" max="120"
/> min="5"
type="number" />
</div> </div>
</div> </div>
</div> </div>
<div class="actions"> <div class="actions">
<button @click="saveSettings" class="btn-save">💾 保存设置</button> <button class="btn-save" @click="saveSettings">
<button @click="resetSettings" class="btn-reset">🔄 重置默认</button> 💾 保存设置
</button>
<button class="btn-reset" @click="resetSettings">
🔄 重置默认
</button>
</div> </div>
<div class="current-settings"> <div class="current-settings">
......
export { default } from '@venus/tailwind-config'; export { default } from "@venus/tailwind-config";
...@@ -28,11 +28,5 @@ ...@@ -28,11 +28,5 @@
"skipLibCheck": true "skipLibCheck": true
}, },
"references": [{ "path": "./tsconfig.node.json" }], "references": [{ "path": "./tsconfig.node.json" }],
"include": [ "include": ["env.d.ts", "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/**/*.js"]
"env.d.ts",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/**/*.js"
]
} }
...@@ -9,5 +9,6 @@ ...@@ -9,5 +9,6 @@
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"skipLibCheck": true "skipLibCheck": true
}, },
"include": ["vite.config.ts", "vite-plugins/**/*.ts"] "include": ["vite.config.ts", "vite-plugins/**/*.ts"],
"exclude": ["env.d.ts"]
} }
...@@ -74,12 +74,12 @@ pnpm preview ...@@ -74,12 +74,12 @@ pnpm preview
```typescript ```typescript
export const microApps: MicroAppConfig[] = [ export const microApps: MicroAppConfig[] = [
{ {
name: 'subapp-vue', // 微应用名称 name: "subapp-vue", // 微应用名称
entry: '//localhost:8081', // 微应用入口 entry: "//localhost:8081", // 微应用入口
container: '#subapp-container', // 微应用挂载点 container: "#subapp-container", // 微应用挂载点
activeRule: '/subapp-vue', // 激活路由 activeRule: "/subapp-vue", // 激活路由
props: { props: {
routerBase: '/subapp-vue', // 路由基础路径 routerBase: "/subapp-vue", // 路由基础路径
}, },
}, },
// 添加更多微应用... // 添加更多微应用...
...@@ -115,15 +115,15 @@ export const microApps: MicroAppConfig[] = [ ...@@ -115,15 +115,15 @@ export const microApps: MicroAppConfig[] = [
主应用在 `main.ts` 中初始化 qiankun: 主应用在 `main.ts` 中初始化 qiankun:
```typescript ```typescript
import { registerMicroApps, start } from 'qiankun'; import { registerMicroApps, start } from "qiankun";
// 注册微应用 // 注册微应用
registerMicroApps(microApps, { registerMicroApps(microApps, {
beforeLoad: (app) => console.log('before load', app.name), beforeLoad: (app) => console.log("before load", app.name),
beforeMount: (app) => console.log('before mount', app.name), beforeMount: (app) => console.log("before mount", app.name),
afterMount: (app) => console.log('after mount', app.name), afterMount: (app) => console.log("after mount", app.name),
beforeUnmount: (app) => console.log('before unmount', app.name), beforeUnmount: (app) => console.log("before unmount", app.name),
afterUnmount: (app) => console.log('after unmount', app.name), afterUnmount: (app) => console.log("after unmount", app.name),
}); });
// 启动 qiankun // 启动 qiankun
...@@ -151,12 +151,12 @@ start({ ...@@ -151,12 +151,12 @@ start({
let instance: any = null; let instance: any = null;
export async function bootstrap() { export async function bootstrap() {
console.log('vue app bootstraped'); console.log("vue app bootstraped");
} }
export async function mount(props: any) { export async function mount(props: any) {
instance = createApp(App); instance = createApp(App);
instance.mount(props.container ? props.container.querySelector('#app') : '#app'); instance.mount(props.container ? props.container.querySelector("#app") : "#app");
} }
export async function unmount() { export async function unmount() {
...@@ -169,20 +169,20 @@ export async function unmount() { ...@@ -169,20 +169,20 @@ export async function unmount() {
```typescript ```typescript
// vite.config.ts // vite.config.ts
import qiankun from 'vite-plugin-qiankun'; import qiankun from "vite-plugin-qiankun";
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [
vue(), vue(),
qiankun('subapp-vue', { qiankun("subapp-vue", {
useDevMode: true useDevMode: true,
}) }),
], ],
server: { server: {
port: 8081, port: 8081,
cors: true, cors: true,
origin: 'http://localhost:8081' origin: "http://localhost:8081",
} },
}); });
``` ```
...@@ -223,4 +223,3 @@ export default defineConfig({ ...@@ -223,4 +223,3 @@ export default defineConfig({
## License ## License
MIT MIT
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
## 🚀 功能特性 ## 🚀 功能特性
### 1. 登录页面 ### 1. 登录页面
- ✅ 现代化 UI 设计,支持响应式布局 - ✅ 现代化 UI 设计,支持响应式布局
- ✅ 用户名密码登录 - ✅ 用户名密码登录
- ✅ 验证码功能(可选) - ✅ 验证码功能(可选)
...@@ -16,11 +17,13 @@ ...@@ -16,11 +17,13 @@
- ✅ 加载状态显示 - ✅ 加载状态显示
### 2. 状态管理(Pinia) ### 2. 状态管理(Pinia)
- ✅ 用户状态管理(`useUserStore`) - ✅ 用户状态管理(`useUserStore`)
- ✅ 权限管理(`usePermissionStore`) - ✅ 权限管理(`usePermissionStore`)
- ✅ 应用全局状态管理(`useAppStore`) - ✅ 应用全局状态管理(`useAppStore`)
### 3. 认证与授权 ### 3. 认证与授权
- ✅ Token 存储和管理 - ✅ Token 存储和管理
- ✅ 自动刷新用户信息 - ✅ 自动刷新用户信息
- ✅ 路由守卫 - ✅ 路由守卫
...@@ -28,6 +31,7 @@ ...@@ -28,6 +31,7 @@
- ✅ 角色检查 - ✅ 角色检查
### 4. API 封装 ### 4. API 封装
- ✅ Axios 请求拦截器 - ✅ Axios 请求拦截器
- ✅ 响应拦截器 - ✅ 响应拦截器
- ✅ 自动添加 Token - ✅ 自动添加 Token
...@@ -106,18 +110,18 @@ graph TD ...@@ -106,18 +110,18 @@ graph TD
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const userStore = useUserStore(); const userStore = useUserStore();
const handleLogin = async () => { const handleLogin = async () => {
const result = await userStore.login({ const result = await userStore.login({
username: 'admin', username: "admin",
password: '123456', password: "123456",
}); });
if (result.success) { if (result.success) {
console.log('登录成功'); console.log("登录成功");
} }
}; };
</script> </script>
...@@ -127,7 +131,7 @@ const handleLogin = async () => { ...@@ -127,7 +131,7 @@ const handleLogin = async () => {
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const userStore = useUserStore(); const userStore = useUserStore();
</script> </script>
``` ```
...@@ -136,18 +140,18 @@ const userStore = useUserStore(); ...@@ -136,18 +140,18 @@ const userStore = useUserStore();
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const userStore = useUserStore(); const userStore = useUserStore();
// 检查权限 // 检查权限
if (userStore.hasPermission('user:create')) { if (userStore.hasPermission("user:create")) {
console.log('有创建用户权限'); console.log("有创建用户权限");
} }
// 检查角色 // 检查角色
if (userStore.hasRole('admin')) { if (userStore.hasRole("admin")) {
console.log('是管理员'); console.log("是管理员");
} }
</script> </script>
``` ```
...@@ -156,15 +160,15 @@ if (userStore.hasRole('admin')) { ...@@ -156,15 +160,15 @@ if (userStore.hasRole('admin')) {
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useRouter } from 'vue-router'; import { useRouter } from "vue-router";
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const router = useRouter(); const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
const handleLogout = async () => { const handleLogout = async () => {
await userStore.logout(); await userStore.logout();
router.push('/login'); router.push("/login");
}; };
</script> </script>
``` ```
...@@ -202,7 +206,7 @@ VITE_API_BASE_URL=http://localhost:3000/api ...@@ -202,7 +206,7 @@ VITE_API_BASE_URL=http://localhost:3000/api
在 `router/index.ts` 中配置不需要登录的路由: 在 `router/index.ts` 中配置不需要登录的路由:
```typescript ```typescript
const whiteList = ['/login', '/register', '/forgot-password']; const whiteList = ["/login", "/register", "/forgot-password"];
``` ```
### 3. Token 存储 Key ### 3. Token 存储 Key
...@@ -210,8 +214,8 @@ const whiteList = ['/login', '/register', '/forgot-password']; ...@@ -210,8 +214,8 @@ const whiteList = ['/login', '/register', '/forgot-password'];
在 `utils/auth.ts` 中配置: 在 `utils/auth.ts` 中配置:
```typescript ```typescript
const TOKEN_KEY = 'scrm_access_token'; const TOKEN_KEY = "scrm_access_token";
const REFRESH_TOKEN_KEY = 'scrm_refresh_token'; const REFRESH_TOKEN_KEY = "scrm_refresh_token";
``` ```
## 🌐 API 接口规范 ## 🌐 API 接口规范
...@@ -219,6 +223,7 @@ const REFRESH_TOKEN_KEY = 'scrm_refresh_token'; ...@@ -219,6 +223,7 @@ const REFRESH_TOKEN_KEY = 'scrm_refresh_token';
### 1. 登录接口 ### 1. 登录接口
**请求:** **请求:**
```http ```http
POST /auth/login POST /auth/login
Content-Type: application/json Content-Type: application/json
...@@ -231,6 +236,7 @@ Content-Type: application/json ...@@ -231,6 +236,7 @@ Content-Type: application/json
``` ```
**响应:** **响应:**
```json ```json
{ {
"code": 200, "code": 200,
...@@ -253,12 +259,14 @@ Content-Type: application/json ...@@ -253,12 +259,14 @@ Content-Type: application/json
### 2. 获取用户信息接口 ### 2. 获取用户信息接口
**请求:** **请求:**
```http ```http
GET /user/info GET /user/info
Authorization: Bearer {token} Authorization: Bearer {token}
``` ```
**响应:** **响应:**
```json ```json
{ {
"code": 200, "code": 200,
...@@ -277,12 +285,14 @@ Authorization: Bearer {token} ...@@ -277,12 +285,14 @@ Authorization: Bearer {token}
### 3. 登出接口 ### 3. 登出接口
**请求:** **请求:**
```http ```http
POST /auth/logout POST /auth/logout
Authorization: Bearer {token} Authorization: Bearer {token}
``` ```
**响应:** **响应:**
```json ```json
{ {
"code": 200, "code": 200,
...@@ -335,16 +345,16 @@ export const login = (data: LoginParams) => { ...@@ -335,16 +345,16 @@ export const login = (data: LoginParams) => {
// 模拟登录 // 模拟登录
return Promise.resolve({ return Promise.resolve({
code: 200, code: 200,
message: '登录成功', message: "登录成功",
data: { data: {
token: 'mock_token_' + Date.now(), token: "mock_token_" + Date.now(),
userInfo: { userInfo: {
id: '1', id: "1",
username: data.username, username: data.username,
name: '测试用户', name: "测试用户",
avatar: '👤', avatar: "👤",
roles: ['admin'], roles: ["admin"],
permissions: ['*:*:*'], permissions: ["*:*:*"],
}, },
}, },
}); });
...@@ -370,7 +380,7 @@ if (token) { ...@@ -370,7 +380,7 @@ if (token) {
检查路由守卫中是否正确处理了白名单和登录页: 检查路由守卫中是否正确处理了白名单和登录页:
```typescript ```typescript
if (to.path === '/login') { if (to.path === "/login") {
next(); // 必须放行登录页 next(); // 必须放行登录页
} }
``` ```
...@@ -380,7 +390,7 @@ if (to.path === '/login') { ...@@ -380,7 +390,7 @@ if (to.path === '/login') {
检查请求拦截器是否正确添加 Token: 检查请求拦截器是否正确添加 Token:
```typescript ```typescript
config.headers['Authorization'] = `Bearer ${token}`; config.headers["Authorization"] = `Bearer ${token}`;
``` ```
## 📚 相关文档 ## 📚 相关文档
...@@ -392,4 +402,3 @@ config.headers['Authorization'] = `Bearer ${token}`; ...@@ -392,4 +402,3 @@ config.headers['Authorization'] = `Bearer ${token}`;
## 🙋 支持 ## 🙋 支持
如有问题,请联系开发团队或提交 Issue。 如有问题,请联系开发团队或提交 Issue。
/// <reference types="vite/client" />
declare module '*.vue' { declare module "*.vue" {
import type { DefineComponent } from 'vue'; import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<object, object, any>;
export default component; export default component;
} }
...@@ -16,7 +15,7 @@ interface ImportMeta { ...@@ -16,7 +15,7 @@ interface ImportMeta {
readonly env: ImportMetaEnv; readonly env: ImportMetaEnv;
} }
// declare module 手动提供模块类型定义,避免异常 // declare module 手动提供模块类型定义,避免异常
declare module 'glsk-common' { declare module "glsk-common" {
export interface HttpConfig { export interface HttpConfig {
response?: any; response?: any;
request?: any; request?: any;
...@@ -24,14 +23,14 @@ declare module 'glsk-common' { ...@@ -24,14 +23,14 @@ declare module 'glsk-common' {
secret?: any; secret?: any;
alert?: (message: string) => void; alert?: (message: string) => void;
} }
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class Http { export class Http {
[key: string]: any; [key: string]: any;
constructor(config: HttpConfig); constructor(config: HttpConfig);
} }
} }
declare module 'glsk-toolkit' { declare module "glsk-toolkit" {
export class Request { export class Request {
[key: string]: any; [key: string]: any;
constructor(config: any); constructor(config: any);
......
<!DOCTYPE html> <!doctype html>
<html lang="zh-CN" style="--el-color-primary: #185EFE; "> <html lang="zh-CN" style="
--el-color-primary: #185efe">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
...@@ -11,4 +13,3 @@ ...@@ -11,4 +13,3 @@
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
</html> </html>
export * from './route'; export * from "./route";
/** /**
* API 统一导出 * API 统一导出
*/ */
export * from './user'; export * from "./user";
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
* 模拟 API(用于开发测试,后端接口完成后可删除此文件) * 模拟 API(用于开发测试,后端接口完成后可删除此文件)
*/ */
import type { ApiResponse } from '@/types/api'; import type { ApiResponse } from "@/types/api";
import type { LoginParams, LoginResponse, UserInfo } from '@/types/user'; import type { LoginParams, LoginResponse, UserInfo } from "@/types/user";
/** /**
* 模拟延迟 * 模拟延迟
...@@ -17,53 +17,53 @@ const mockDelay = (ms: number = 500) => { ...@@ -17,53 +17,53 @@ const mockDelay = (ms: number = 500) => {
*/ */
const mockUsers = [ const mockUsers = [
{ {
username: 'admin', username: "admin",
password: '123456', password: "123456",
userInfo: { userInfo: {
id: '1', id: "1",
username: 'admin', username: "admin",
name: '管理员', name: "管理员",
avatar: '👤', avatar: "👤",
email: 'admin@scrm.com', email: "admin@scrm.com",
phone: '13800138000', phone: "13800138000",
roles: ['admin', 'user'], roles: [ "admin", "user" ],
permissions: ['*:*:*'], permissions: [ "*:*:*" ],
department: '技术部', department: "技术部",
position: '系统管理员', position: "系统管理员",
status: 1, status: 1,
}, },
}, },
{ {
username: 'user', username: "user",
password: '123456', password: "123456",
userInfo: { userInfo: {
id: '2', id: "2",
username: 'user', username: "user",
name: '普通用户', name: "普通用户",
avatar: '👨', avatar: "👨",
email: 'user@scrm.com', email: "user@scrm.com",
phone: '13800138001', phone: "13800138001",
roles: ['user'], roles: [ "user" ],
permissions: ['user:read', 'user:write'], permissions: [ "user:read", "user:write" ],
department: '销售部', department: "销售部",
position: '销售专员', position: "销售专员",
status: 1, status: 1,
}, },
}, },
{ {
username: 'guest', username: "guest",
password: '123456', password: "123456",
userInfo: { userInfo: {
id: '3', id: "3",
username: 'guest', username: "guest",
name: '访客', name: "访客",
avatar: '🧑', avatar: "🧑",
email: 'guest@scrm.com', email: "guest@scrm.com",
phone: '13800138002', phone: "13800138002",
roles: ['guest'], roles: [ "guest" ],
permissions: ['user:read'], permissions: [ "user:read" ],
department: '访客', department: "访客",
position: '访客', position: "访客",
status: 1, status: 1,
}, },
}, },
...@@ -82,7 +82,7 @@ export const mockLogin = async ( ...@@ -82,7 +82,7 @@ export const mockLogin = async (
if (!user) { if (!user) {
return { return {
code: 400, code: 400,
message: '用户不存在', message: "用户不存在",
data: null as any, data: null as any,
}; };
} }
...@@ -90,7 +90,7 @@ export const mockLogin = async ( ...@@ -90,7 +90,7 @@ export const mockLogin = async (
if (user.password !== data.password) { if (user.password !== data.password) {
return { return {
code: 400, code: 400,
message: '密码错误', message: "密码错误",
data: null as any, data: null as any,
}; };
} }
...@@ -101,7 +101,7 @@ export const mockLogin = async ( ...@@ -101,7 +101,7 @@ export const mockLogin = async (
return { return {
code: 200, code: 200,
message: '登录成功', message: "登录成功",
data: { data: {
token, token,
refreshToken, refreshToken,
...@@ -118,7 +118,7 @@ export const mockLogout = async (): Promise<ApiResponse<void>> => { ...@@ -118,7 +118,7 @@ export const mockLogout = async (): Promise<ApiResponse<void>> => {
return { return {
code: 200, code: 200,
message: '登出成功', message: "登出成功",
data: undefined as any, data: undefined as any,
}; };
}; };
...@@ -132,20 +132,20 @@ export const mockGetUserInfo = async ( ...@@ -132,20 +132,20 @@ export const mockGetUserInfo = async (
await mockDelay(500); await mockDelay(500);
// 从 token 中解析用户名 // 从 token 中解析用户名
const username = token.split('_')[2]; const username = token.split("_")[2];
const user = mockUsers.find((u) => u.username === username); const user = mockUsers.find((u) => u.username === username);
if (!user) { if (!user) {
return { return {
code: 401, code: 401,
message: 'Token 无效', message: "Token 无效",
data: null as any, data: null as any,
}; };
} }
return { return {
code: 200, code: 200,
message: 'success', message: "success",
data: user.userInfo, data: user.userInfo,
}; };
}; };
......
/** /**
* 路由和菜单相关 API * 路由和菜单相关 API
*/ */
import type { MenuItem, TopMenuItem } from '@/types/menu'; import type { MenuItem, TopMenuItem } from "@/types/menu";
import type { RouteRecordRaw } from 'vue-router';
import type { RouteRecordRaw } from "vue-router";
/** /**
* 路由配置接口(从 API 返回的数据结构) * 路由配置接口(从 API 返回的数据结构)
*/ */
...@@ -37,15 +38,15 @@ export interface MenuConfig { ...@@ -37,15 +38,15 @@ export interface MenuConfig {
id: string; id: string;
path: string; path: string;
sidebarMenus: Array<{ sidebarMenus: Array<{
children?: MenuConfig['topMenus'][0]['sidebarMenus']; children?: MenuConfig["topMenus"][0]["sidebarMenus"];
hidden?: boolean;
icon?: string; icon?: string;
id: string; id: string;
level?: number; level?: number;
meta?: MenuItem['meta']; meta?: MenuItem["meta"];
parentId?: string; parentId?: string;
path: string; path: string;
title: string; title: string;
hidden?: boolean;
}>; }>;
title: string; title: string;
}>; }>;
...@@ -59,12 +60,12 @@ export interface MenuConfig { ...@@ -59,12 +60,12 @@ export interface MenuConfig {
export function transformRouteConfig(config: RouteConfig): RouteRecordRaw { export function transformRouteConfig(config: RouteConfig): RouteRecordRaw {
// 微应用路由使用 MicroApp 组件 // 微应用路由使用 MicroApp 组件
const component = config.isMicroApp const component = config.isMicroApp
? () => import('@/views/MicroApp.vue') ? () => import("@/views/MicroApp.vue")
: // 非微应用路由需要根据实际情况设置组件 : // 非微应用路由需要根据实际情况设置组件
// 如果 API 返回了组件路径,可以在这里动态导入 // 如果 API 返回了组件路径,可以在这里动态导入
// 示例:() => import(`@/views/${config.component}.vue`); // 示例:() => import(`@/views/${config.component}.vue`);
// 目前暂时使用 MicroApp 作为默认组件,实际使用时需要根据 API 返回的数据设置 // 目前暂时使用 MicroApp 作为默认组件,实际使用时需要根据 API 返回的数据设置
() => import('@/views/MicroApp.vue'); () => import("@/views/MicroApp.vue");
return { return {
path: config.path, path: config.path,
...@@ -97,6 +98,7 @@ export function transformMenuConfig(config: MenuConfig): { ...@@ -97,6 +98,7 @@ export function transformMenuConfig(config: MenuConfig): {
sidebarMenus: transformSidebarMenus(topMenu.sidebarMenus), sidebarMenus: transformSidebarMenus(topMenu.sidebarMenus),
})); }));
// eslint-disable-next-line unicorn/no-array-callback-reference
const routes: RouteRecordRaw[] = config.routes.map(transformRouteConfig); const routes: RouteRecordRaw[] = config.routes.map(transformRouteConfig);
return { topMenus, routes }; return { topMenus, routes };
...@@ -106,7 +108,7 @@ export function transformMenuConfig(config: MenuConfig): { ...@@ -106,7 +108,7 @@ export function transformMenuConfig(config: MenuConfig): {
* 递归转换侧边栏菜单 * 递归转换侧边栏菜单
*/ */
function transformSidebarMenus( function transformSidebarMenus(
menus: MenuConfig['topMenus'][0]['sidebarMenus'], menus: MenuConfig["topMenus"][0]["sidebarMenus"],
): MenuItem[] { ): MenuItem[] {
return menus.map((menu) => ({ return menus.map((menu) => ({
id: menu.id, id: menu.id,
......
...@@ -2,22 +2,23 @@ ...@@ -2,22 +2,23 @@
* 用户相关 API * 用户相关 API
*/ */
import type { ApiResponse } from '@/types/api'; import type { ApiResponse } from "@/types/api";
import type { import type {
ChangePasswordParams, ChangePasswordParams,
LoginParams, LoginParams,
UpdateUserInfoParams, UpdateUserInfoParams,
UserInfo, UserInfo,
} from '@/types/user'; } from "@/types/user";
import { post } from '@/utils/request'; import gscPost from "@/config/gscrequest";
import gscPost from '@/config/gscrequest'; import { post } from "@/utils/request";
import { mockLogout } from "./mock";
// 数据看板指标统计 // 数据看板指标统计
export function getdataBoard(data: any) { export function getdataBoard(data: any) {
return gscPost('/dataBoard/indexs', data); return gscPost("/dataBoard/indexs", data);
} }
import { mockLogout } from './mock';
const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 false const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 false
...@@ -25,19 +26,19 @@ const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 fa ...@@ -25,19 +26,19 @@ const USE_MOCK_API = true; // 开发时设置为 true,生产环境设置为 fa
* 用户登录 * 用户登录
*/ */
export const login = (data: LoginParams) => { export const login = (data: LoginParams) => {
return gscPost('/login',data,{ returnAll:true }); return gscPost("/login", data, { returnAll:true });
}; };
/** /**
* 公钥 * 公钥
*/ */
export const getPublicKey = (data: any) => { export const getPublicKey = (data: any) => {
return gscPost('/login/publicKey',data,{ returnAll:true }); return gscPost("/login/publicKey", data, { returnAll:true });
}; };
/** /**
* 获取当前用户信息 * 获取当前用户信息
*/ */
export const getUserInfo = () => { export const getUserInfo = () => {
return gscPost('/login/currLoginUser', {}, { returnAll: true }); return gscPost("/login/currLoginUser", {}, { returnAll: true });
}; };
/** /**
* 用户登出 * 用户登出
...@@ -46,7 +47,7 @@ export const logout = () => { ...@@ -46,7 +47,7 @@ export const logout = () => {
if (USE_MOCK_API) { if (USE_MOCK_API) {
return mockLogout(); return mockLogout();
} }
return post<ApiResponse<void>>('/auth/logout'); return post<ApiResponse<void>>("/auth/logout");
}; };
...@@ -55,7 +56,7 @@ export const logout = () => { ...@@ -55,7 +56,7 @@ export const logout = () => {
*/ */
export const refreshToken = (refreshToken: string) => { export const refreshToken = (refreshToken: string) => {
return post<ApiResponse<{ refreshToken: string; token: string }>>( return post<ApiResponse<{ refreshToken: string; token: string }>>(
'/auth/refresh', "/auth/refresh",
{ {
refreshToken, refreshToken,
}, },
...@@ -66,19 +67,19 @@ export const refreshToken = (refreshToken: string) => { ...@@ -66,19 +67,19 @@ export const refreshToken = (refreshToken: string) => {
* 修改密码 * 修改密码
*/ */
export const changePassword = (data: ChangePasswordParams) => { export const changePassword = (data: ChangePasswordParams) => {
return post<ApiResponse<void>>('/user/change-password', data); return post<ApiResponse<void>>("/user/change-password", data);
}; };
/** /**
* 更新用户信息 * 更新用户信息
*/ */
export const updateUserInfo = (data: UpdateUserInfoParams) => { export const updateUserInfo = (data: UpdateUserInfoParams) => {
return post<ApiResponse<UserInfo>>('/user/update', data); return post<ApiResponse<UserInfo>>("/user/update", data);
}; };
/** /**
* 获取验证码 * 获取验证码
*/ */
export const getCaptcha = (data: any) => { export const getCaptcha = (data: any) => {
return gscPost('/login/captcha',data); return gscPost("/login/captcha", data);
}; };
import { clearAuth, getToken } from "@/utils/auth";
import { localCache } from "@/utils/storage";
import { ElMessage } from "element-plus";
/** /**
* 配置中心管理 * 配置中心管理
* 使用 fetch 解决 axios 提前实例化导致 sign 里面的 secret 不能通过配置中心动态获取 * 使用 fetch 解决 axios 提前实例化导致 sign 里面的 secret 不能通过配置中心动态获取
*/ */
import { Request, Defaults } from 'glsk-toolkit'; import { Defaults, Request } from "glsk-toolkit";
import { getToken, clearAuth } from '@/utils/auth';
import { ElMessage } from 'element-plus';
import { localCache } from '@/utils/storage';
import { import {
CONFIG_CENTER_URL as CONFIG_URL,
ROUTER_CONFIG_URL as ROUTER_URL,
CONFIG_CACHE_KEY, CONFIG_CACHE_KEY,
CONFIG_CENTER_URL as CONFIG_URL,
ROUTER_CONFIG_CACHE_KEY, ROUTER_CONFIG_CACHE_KEY,
} from './constants'; // 导入常量配置 ROUTER_CONFIG_URL as ROUTER_URL,
} from "./constants"; // 导入常量配置
// 配置数据 // 配置数据
// eslint-disable-next-line import/no-mutable-exports
let baseConfig: any = {}; let baseConfig: any = {};
// GSC API 请求实例(模块级单例,不挂载到 window) // GSC API 请求实例(模块级单例,不挂载到 window)
let gscApiInstance: null | Request = null; let gscApiInstance: null | Request = null;
...@@ -41,7 +43,7 @@ function initConfigReadyPromise() { ...@@ -41,7 +43,7 @@ function initConfigReadyPromise() {
* @returns 路由数据 * @returns 路由数据
*/ */
export async function fetchMicroAppRouteConfig(): Promise<any> { export async function fetchMicroAppRouteConfig(): Promise<any> {
if(baseConfig.features.defaultRoute.enabled){ if (baseConfig.features.defaultRoute.enabled){
return { return {
"code": 200, "code": 200,
"message": "success", "message": "success",
...@@ -160,7 +162,7 @@ export async function fetchConfig(): Promise<any> { ...@@ -160,7 +162,7 @@ export async function fetchConfig(): Promise<any> {
// 保存到本地缓存 // 保存到本地缓存
if (configData) { if (configData) {
localCache.set(CONFIG_CACHE_KEY, configData); localCache.set(CONFIG_CACHE_KEY, configData);
console.log('[配置中心] 基本配置已缓存到本地'); console.log("[配置中心] 基本配置已缓存到本地");
} }
} }
...@@ -168,28 +170,28 @@ export async function fetchConfig(): Promise<any> { ...@@ -168,28 +170,28 @@ export async function fetchConfig(): Promise<any> {
window.$fetchConfig = configData; window.$fetchConfig = configData;
// 统一初始化 GSC API(无论 code 是什么,只要有配置就初始化) // 统一初始化 GSC API(无论 code 是什么,只要有配置就初始化)
const gscConfig = configData?.gsc || configData; const gscConfig = configData?.gsc || configData;
if(gscConfig){ if (gscConfig){
// 创建全局默认配置 // 创建全局默认配置
const globalDefaults = new Defaults({ const globalDefaults = new Defaults({
...gscConfig, ...gscConfig,
events: { events: {
error: (error: any, requestConfig: any) => { error: (error: any, requestConfig: any) => {
console.error('[配置中心] GSC API 错误:', error, requestConfig); console.error("[配置中心] GSC API 错误:", error, requestConfig);
// 检查错误信息中是否包含 401 状态码,待优化项:插件默认所有>=400状态码全部阻塞,后续业务状态码不会捕获处理 // 检查错误信息中是否包含 401 状态码,待优化项:插件默认所有>=400状态码全部阻塞,后续业务状态码不会捕获处理
const errorMessage = error?.msg || error?.message || error?.toString() || String(error); const errorMessage = error?.msg || error?.message || error?.toString() || String(error);
if (errorMessage.includes('401')) { if (errorMessage.includes("401")) {
ElMessage.error('登录已过期,请重新登录'); ElMessage.error("登录已过期,请重新登录");
clearAuth(); clearAuth();
// 跳转到登录页 // 跳转到登录页
if (window.location.pathname !== '/login') { if (window.location.pathname !== "/login") {
window.location.href = '/login'; window.location.href = "/login";
} }
}else{ } else {
ElMessage.error(errorMessage); ElMessage.error(errorMessage);
} }
}, },
logout: (response: any, requestConfig: any) => { logout: (response: any, requestConfig: any) => {
console.log('[配置中心] GSC API 登出:', response, requestConfig); console.log("[配置中心] GSC API 登出:", response, requestConfig);
}, },
}, },
}); });
...@@ -203,13 +205,13 @@ export async function fetchConfig(): Promise<any> { ...@@ -203,13 +205,13 @@ export async function fetchConfig(): Promise<any> {
if (token) { if (token) {
config.headers = { config.headers = {
...config.headers, ...config.headers,
'Authorization': token "Authorization": token
}; };
} }
return config; return config;
}, },
(error: any) => { (error: any) => {
console.error('[配置中心] 请求拦截器错误:', error); console.error("[配置中心] 请求拦截器错误:", error);
return Promise.reject(error); return Promise.reject(error);
} }
); );
...@@ -220,7 +222,7 @@ export async function fetchConfig(): Promise<any> { ...@@ -220,7 +222,7 @@ export async function fetchConfig(): Promise<any> {
} }
} else { } else {
console.warn('[配置中心] 未找到 GSC 配置,无法初始化 API 实例'); console.warn("[配置中心] 未找到 GSC 配置,无法初始化 API 实例");
// 即使没有 GSC 配置,也要 resolve Promise,避免 waitForConfigReady 一直等待 // 即使没有 GSC 配置,也要 resolve Promise,避免 waitForConfigReady 一直等待
if (configReadyResolve) { if (configReadyResolve) {
configReadyResolve(); configReadyResolve();
...@@ -229,7 +231,7 @@ export async function fetchConfig(): Promise<any> { ...@@ -229,7 +231,7 @@ export async function fetchConfig(): Promise<any> {
} }
return configData; return configData;
} catch (error) { } catch (error) {
console.error('[配置中心] 获取配置失败:', error); console.error("[配置中心] 获取配置失败:", error);
// 配置加载失败时,也要 resolve Promise,避免 waitForConfigReady 一直等待 // 配置加载失败时,也要 resolve Promise,避免 waitForConfigReady 一直等待
if (configReadyResolve) { if (configReadyResolve) {
configReadyResolve(); configReadyResolve();
...@@ -255,7 +257,7 @@ export function getConfig(): any { ...@@ -255,7 +257,7 @@ export function getConfig(): any {
export function clearConfigCache(): void { export function clearConfigCache(): void {
localCache.remove(CONFIG_CACHE_KEY); localCache.remove(CONFIG_CACHE_KEY);
localCache.remove(ROUTER_CONFIG_CACHE_KEY); localCache.remove(ROUTER_CONFIG_CACHE_KEY);
console.log('[配置中心] 配置缓存已清空'); console.log("[配置中心] 配置缓存已清空");
} }
// 导出配置数据(只读) // 导出配置数据(只读)
......
...@@ -5,14 +5,14 @@ ...@@ -5,14 +5,14 @@
// ==================== 配置中心相关 ==================== // ==================== 配置中心相关 ====================
/** 公共基础配置请求 URL */ /** 公共基础配置请求 URL */
export const CONFIG_CENTER_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-base-system-config'; export const CONFIG_CENTER_URL = "https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-base-system-config";
/** 路由菜单配置请求 URL */ /** 路由菜单配置请求 URL */
export const ROUTER_CONFIG_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-agentic-router'; export const ROUTER_CONFIG_URL = "https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-agentic-router";
// ==================== 缓存 Key 配置 ==================== // ==================== 缓存 Key 配置 ====================
/** 基础配置缓存 key */ /** 基础配置缓存 key */
export const CONFIG_CACHE_KEY = 'venus_base_config'; export const CONFIG_CACHE_KEY = "venus_base_config";
/** 路由配置缓存 key */ /** 路由配置缓存 key */
export const ROUTER_CONFIG_CACHE_KEY = 'venus_router_config'; export const ROUTER_CONFIG_CACHE_KEY = "venus_router_config";
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* GSC 请求封装 * GSC 请求封装
* Authorization 通过请求拦截器统一处理,无需手动添加 * Authorization 通过请求拦截器统一处理,无需手动添加
*/ */
import { getGscApi, waitForConfigReady } from './center'; import { getGscApi, waitForConfigReady } from "./center";
/** /**
* GSC POST 请求 * GSC POST 请求
...@@ -21,18 +21,16 @@ export const gscPost = async (url: string, data: any, config: any = {}) => { ...@@ -21,18 +21,16 @@ export const gscPost = async (url: string, data: any, config: any = {}) => {
const retryGscApi = getGscApi(); const retryGscApi = getGscApi();
if (!retryGscApi) { if (!retryGscApi) {
const error = new Error( const error = new Error(
'[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成且包含 GSC 配置', "[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成且包含 GSC 配置",
); );
console.error(error); console.error(error);
return Promise.reject(error); throw error;
} }
return retryGscApi.post(url, data, config); return retryGscApi.post(url, data, config);
} catch (error) { } catch (error) {
console.error('[GSC请求] 等待配置加载失败:', error); console.error("[GSC请求] 等待配置加载失败:", error);
return Promise.reject( throw new Error(
new Error( "[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成",
'[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成',
),
); );
} }
} }
...@@ -56,18 +54,16 @@ export const gscGet = async (url: string, config: any = {}) => { ...@@ -56,18 +54,16 @@ export const gscGet = async (url: string, config: any = {}) => {
const retryGscApi = getGscApi(); const retryGscApi = getGscApi();
if (!retryGscApi) { if (!retryGscApi) {
const error = new Error( const error = new Error(
'[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成且包含 GSC 配置', "[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成且包含 GSC 配置",
); );
console.error(error); console.error(error);
return Promise.reject(error); throw error;
} }
return retryGscApi.get(url, config); return retryGscApi.get(url, config);
} catch (error) { } catch (error) {
console.error('[GSC请求] 等待配置加载失败:', error); console.error("[GSC请求] 等待配置加载失败:", error);
return Promise.reject( throw new Error(
new Error( "[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成",
'[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成',
),
); );
} }
} }
......
import type { MenuItem, TopMenuItem } from '@/types/menu'; import type { MenuItem, TopMenuItem } from "@/types/menu";
/** /**
* 侧边栏菜单配置示例 * 侧边栏菜单配置示例
...@@ -59,8 +59,8 @@ export function isPathMatch(menuPath: string, targetPath: string): boolean { ...@@ -59,8 +59,8 @@ export function isPathMatch(menuPath: string, targetPath: string): boolean {
} }
// 去掉末尾多余的 /,方便匹配像 /edit/ 与 /edit/2 这类场景 // 去掉末尾多余的 /,方便匹配像 /edit/ 与 /edit/2 这类场景
const normalizedMenuPath = menuPath.replace(/\/+$/, ''); const normalizedMenuPath = menuPath.replace(/\/+$/, "");
const normalizedTargetPath = targetPath.replace(/\/+$/, ''); const normalizedTargetPath = targetPath.replace(/\/+$/, "");
// 精确匹配 // 精确匹配
if (normalizedMenuPath === normalizedTargetPath) { if (normalizedMenuPath === normalizedTargetPath) {
...@@ -68,12 +68,12 @@ export function isPathMatch(menuPath: string, targetPath: string): boolean { ...@@ -68,12 +68,12 @@ export function isPathMatch(menuPath: string, targetPath: string): boolean {
} }
// 如果菜单路径包含参数占位符(如 :id),转换为正则表达式匹配 // 如果菜单路径包含参数占位符(如 :id),转换为正则表达式匹配
if (normalizedMenuPath.includes(':')) { if (normalizedMenuPath.includes(":")) {
// 将路径中的 :id, :param 等替换为正则表达式的非斜杠字符匹配 // 将路径中的 :id, :param 等替换为正则表达式的非斜杠字符匹配
// 例如: /assisant/assistant/edit/:id -> /assisant/assistant/edit/[^/]+ // 例如: /assisant/assistant/edit/:id -> /assisant/assistant/edit/[^/]+
const pattern = normalizedMenuPath const pattern = normalizedMenuPath
.replace(/:[^/]+/g, '[^/]+') .replaceAll(/:[^/]+/g, "[^/]+")
.replace(/\//g, '\\/'); .replaceAll("/", String.raw`\/`);
// 匹配完整路径,例如: /assisant/assistant/edit/123 应该匹配 /assisant/assistant/edit/:id // 匹配完整路径,例如: /assisant/assistant/edit/123 应该匹配 /assisant/assistant/edit/:id
const regex = new RegExp(`^${pattern}$`); const regex = new RegExp(`^${pattern}$`);
return regex.test(normalizedTargetPath); return regex.test(normalizedTargetPath);
...@@ -85,7 +85,7 @@ export function isPathMatch(menuPath: string, targetPath: string): boolean { ...@@ -85,7 +85,7 @@ export function isPathMatch(menuPath: string, targetPath: string): boolean {
if (normalizedTargetPath.startsWith(normalizedMenuPath)) { if (normalizedTargetPath.startsWith(normalizedMenuPath)) {
const nextChar = normalizedTargetPath[normalizedMenuPath.length]; const nextChar = normalizedTargetPath[normalizedMenuPath.length];
// 如果下一个字符是 / 或者是 undefined(路径结束),则匹配 // 如果下一个字符是 / 或者是 undefined(路径结束),则匹配
if (nextChar === '/' || nextChar === undefined) { if (nextChar === "/" || nextChar === undefined) {
return true; return true;
} }
} }
...@@ -107,7 +107,7 @@ export function getMenuParentPaths( ...@@ -107,7 +107,7 @@ export function getMenuParentPaths(
targetPath: string, targetPath: string,
): string[] { ): string[] {
const paths: string[] = []; const paths: string[] = [];
const normalizedTargetPath = targetPath.replace(/\/+$/, ''); const normalizedTargetPath = targetPath.replace(/\/+$/, "");
/** /**
* 递归查找路径链 * 递归查找路径链
...@@ -123,7 +123,7 @@ export function getMenuParentPaths( ...@@ -123,7 +123,7 @@ export function getMenuParentPaths(
): boolean { ): boolean {
for (const item of items) { for (const item of items) {
// 构建新的路径链(包含当前项) // 构建新的路径链(包含当前项)
const newPathChain = [...currentPathChain, item.path]; const newPathChain = [ ...currentPathChain, item.path ];
// 使用路径匹配检查当前项是否匹配目标路径 // 使用路径匹配检查当前项是否匹配目标路径
if (isPathMatch(item.path, target)) { if (isPathMatch(item.path, target)) {
...@@ -133,13 +133,11 @@ export function getMenuParentPaths( ...@@ -133,13 +133,11 @@ export function getMenuParentPaths(
} }
// 递归查找子菜单 // 递归查找子菜单
if (item.children && item.children.length > 0) { if (item.children && item.children.length > 0 && findPathChain(item.children, target, newPathChain)) {
if (findPathChain(item.children, target, newPathChain)) {
// 在子菜单中找到匹配项,路径链已经添加到 paths 中 // 在子菜单中找到匹配项,路径链已经添加到 paths 中
return true; return true;
} }
} }
}
return false; return false;
} }
...@@ -163,7 +161,7 @@ export function getMenuChain( ...@@ -163,7 +161,7 @@ export function getMenuChain(
targetPath: string, targetPath: string,
): MenuItem[] { ): MenuItem[] {
const menuChain: MenuItem[] = []; const menuChain: MenuItem[] = [];
const normalizedTargetPath = targetPath.replace(/\/+$/, ''); const normalizedTargetPath = targetPath.replace(/\/+$/, "");
/** /**
* 递归查找菜单链 * 递归查找菜单链
...@@ -175,7 +173,7 @@ export function getMenuChain( ...@@ -175,7 +173,7 @@ export function getMenuChain(
): boolean { ): boolean {
for (const item of items) { for (const item of items) {
// 构建新的菜单链(包含当前项) // 构建新的菜单链(包含当前项)
const newChain = [...currentChain, item]; const newChain = [ ...currentChain, item ];
// 使用路径匹配检查当前项是否匹配目标路径 // 使用路径匹配检查当前项是否匹配目标路径
if (isPathMatch(item.path, target)) { if (isPathMatch(item.path, target)) {
...@@ -185,13 +183,11 @@ export function getMenuChain( ...@@ -185,13 +183,11 @@ export function getMenuChain(
} }
// 递归查找子菜单 // 递归查找子菜单
if (item.children && item.children.length > 0) { if (item.children && item.children.length > 0 && findMenuChain(item.children, target, newChain)) {
if (findMenuChain(item.children, target, newChain)) {
// 在子菜单中找到匹配项,菜单链已经添加到 menuChain 中 // 在子菜单中找到匹配项,菜单链已经添加到 menuChain 中
return true; return true;
} }
} }
}
return false; return false;
} }
......
...@@ -9,11 +9,11 @@ ...@@ -9,11 +9,11 @@
export const PERMISSION_WHITELIST = { export const PERMISSION_WHITELIST = {
// 路由白名单:不需要登录即可访问的路由(用于登录检查) // 路由白名单:不需要登录即可访问的路由(用于登录检查)
routes: [ routes: [
'/login', "/login",
'/register', "/register",
'/forgot-password', "/forgot-password",
'/404', "/404",
'/403', "/403",
] as string[], ] as string[],
// 用户ID白名单:白名单内的用户默认可以访问全部权限 // 用户ID白名单:白名单内的用户默认可以访问全部权限
...@@ -34,7 +34,7 @@ export const PERMISSION_WHITELIST = { ...@@ -34,7 +34,7 @@ export const PERMISSION_WHITELIST = {
// 超级管理员角色(保留,作为备用方案) // 超级管理员角色(保留,作为备用方案)
// 如果用户角色包含 super-admin,也会拥有所有权限 // 如果用户角色包含 super-admin,也会拥有所有权限
roles: [ roles: [
'super-admin', // 超级管理员 "super-admin", // 超级管理员
] as string[], ] as string[],
}; };
......
...@@ -3,8 +3,9 @@ ...@@ -3,8 +3,9 @@
* 使用方式:v-auth="'system:user:add'" 或 v-auth="['system:user:add', 'system:user:edit']" * 使用方式:v-auth="'system:user:add'" 或 v-auth="['system:user:add', 'system:user:edit']"
*/ */
import type { Directive } from 'vue'; import type { Directive } from "vue";
import { useUserStore } from '@/stores';
import { useUserStore } from "@/stores";
export const auth: Directive = { export const auth: Directive = {
mounted(el, binding) { mounted(el, binding) {
...@@ -13,11 +14,11 @@ export const auth: Directive = { ...@@ -13,11 +14,11 @@ export const auth: Directive = {
if (!value) return; if (!value) return;
const authorities = Array.isArray(value) ? value : [value]; const authorities = Array.isArray(value) ? value : [ value ];
const hasPermission = userStore.hasAuthority(authorities); const hasPermission = userStore.hasAuthority(authorities);
if (!hasPermission) { if (!hasPermission) {
el.parentNode?.removeChild(el); el.remove();
} }
}, },
updated(el, binding) { updated(el, binding) {
...@@ -26,13 +27,13 @@ export const auth: Directive = { ...@@ -26,13 +27,13 @@ export const auth: Directive = {
if (!value) return; if (!value) return;
const authorities = Array.isArray(value) ? value : [value]; const authorities = Array.isArray(value) ? value : [ value ];
const hasPermission = userStore.hasAuthority(authorities); const hasPermission = userStore.hasAuthority(authorities);
if (!hasPermission) { if (!hasPermission) {
// 如果元素已存在但无权限,移除它 // 如果元素已存在但无权限,移除它
if (el.parentNode) { if (el.parentNode) {
el.parentNode.removeChild(el); el.remove();
} }
} else { } else {
// 如果有权限但元素不存在,需要重新添加(这种情况较少见) // 如果有权限但元素不存在,需要重新添加(这种情况较少见)
......
<script setup lang="ts"> <script setup lang="ts">
import type { BreadcrumbItem } from '@/types/menu'; import type { BreadcrumbItem } from "@/types/menu";
import { useRouter } from 'vue-router'; import { useRouter } from "vue-router";
defineProps<{ defineProps<{
breadcrumbs: BreadcrumbItem[]; breadcrumbs: BreadcrumbItem[];
...@@ -26,18 +26,17 @@ const handleBreadcrumbClick = ( ...@@ -26,18 +26,17 @@ const handleBreadcrumbClick = (
<template> <template>
<div v-if="breadcrumbs.length > 0" class="breadcrumb"> <div v-if="breadcrumbs.length > 0" class="breadcrumb">
<template v-for="(crumb, index) in breadcrumbs" :key="index"> <template v-for="(crumb, index) in breadcrumbs" :key="index">
<span <span class="breadcrumb-item"
class="breadcrumb-item"
:class="{ :class="{
clickable: crumb.path && index < breadcrumbs.length - 1, clickable: crumb.path && index < breadcrumbs.length - 1,
}" }"
@click="handleBreadcrumbClick(crumb, index, breadcrumbs)" @click="handleBreadcrumbClick(crumb, index, breadcrumbs)">
>
{{ crumb.title }} {{ crumb.title }}
</span> </span>
<span v-if="index < breadcrumbs.length - 1" class="breadcrumb-separator" <span v-if="index < breadcrumbs.length - 1"
>/</span class="breadcrumb-separator">
> /
</span>
</template> </template>
</div> </div>
</template> </template>
......
<script setup lang="ts"> <script setup lang="ts">
import type { GlobalState } from '@/qiankun/communication'; import type { GlobalState } from "@/qiankun/communication";
import { computed, onMounted, onUnmounted, ref } from 'vue'; import { computed, onMounted, onUnmounted, ref } from "vue";
import { communicationManager } from '@/qiankun/communication'; import { communicationManager } from "@/qiankun/communication";
import { Bell } from '@element-plus/icons-vue'; import { Bell } from "@element-plus/icons-vue";
// 显示面板 // 显示面板
const showPanel = ref(false); const showPanel = ref(false);
// 通知列表 // 通知列表
const notifications = ref<GlobalState['notifications']>([]); const notifications = ref<GlobalState["notifications"]>([]);
// 未读数量 // 未读数量
const unreadCount = computed(() => notifications.value.length); const unreadCount = computed(() => notifications.value.length);
...@@ -22,12 +22,12 @@ const togglePanel = () => { ...@@ -22,12 +22,12 @@ const togglePanel = () => {
// 获取图标 // 获取图标
const getIcon = (type: string) => { const getIcon = (type: string) => {
const icons: Record<string, string> = { const icons: Record<string, string> = {
success: '✅', success: "✅",
warning: '⚠️', warning: "⚠️",
error: '❌', error: "❌",
info: 'ℹ️', info: "ℹ️",
}; };
return icons[type] || 'ℹ️'; return icons[type] || "ℹ️";
}; };
// 格式化时间 // 格式化时间
...@@ -35,14 +35,14 @@ const formatTime = (timestamp: number) => { ...@@ -35,14 +35,14 @@ const formatTime = (timestamp: number) => {
const now = Date.now(); const now = Date.now();
const diff = now - timestamp; const diff = now - timestamp;
if (diff < 60_000) return '刚刚'; if (diff < 60_000) return "刚刚";
if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}分钟前`; if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}分钟前`;
if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}小时前`; if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}小时前`;
return new Date(timestamp).toLocaleString('zh-CN', { return new Date(timestamp).toLocaleString("zh-CN", {
month: '2-digit', month: "2-digit",
day: '2-digit', day: "2-digit",
hour: '2-digit', hour: "2-digit",
minute: '2-digit', minute: "2-digit",
}); });
}; };
...@@ -84,7 +84,9 @@ onUnmounted(() => { ...@@ -84,7 +84,9 @@ onUnmounted(() => {
<div class="notification-badge" @click="togglePanel"> <div class="notification-badge" @click="togglePanel">
<!-- <span class="icon">🔔</span> --> <!-- <span class="icon">🔔</span> -->
<span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span> <span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
<el-icon size="16" style="margin-right: 6px"><Bell /></el-icon> <el-icon size="16" style="margin-right: 6px">
<Bell />
</el-icon>
<span>消息通知</span> <span>消息通知</span>
</div> </div>
...@@ -93,46 +95,50 @@ onUnmounted(() => { ...@@ -93,46 +95,50 @@ onUnmounted(() => {
<div v-if="showPanel" class="notification-panel"> <div v-if="showPanel" class="notification-panel">
<div class="panel-header"> <div class="panel-header">
<h3>通知中心</h3> <h3>通知中心</h3>
<button <button v-if="notifications.length > 0"
v-if="notifications.length > 0"
@click="clearAll"
class="clear-btn" class="clear-btn"
> @click="clearAll">
清空 清空
</button> </button>
</div> </div>
<div class="notification-list"> <div class="notification-list">
<div <div v-for="notification in notifications"
v-for="notification in notifications"
:key="notification.id" :key="notification.id"
class="notification-item" class="notification-item"
:class="[`type-${notification.type}`]" :class="[`type-${notification.type}`]">
>
<div class="notification-icon"> <div class="notification-icon">
{{ getIcon(notification.type) }} {{ getIcon(notification.type) }}
</div> </div>
<div class="notification-content"> <div class="notification-content">
<div class="notification-title">{{ notification.title }}</div> <div class="notification-title">
<div class="notification-message">{{ notification.message }}</div> {{ notification.title }}
</div>
<div class="notification-message">
{{ notification.message }}
</div>
<div class="notification-meta"> <div class="notification-meta">
<span v-if="notification.from" class="from">来自: {{ notification.from }}</span> <span v-if="notification.from" class="from">来自: {{ notification.from }}</span>
<span class="time">{{ <span class="time">
{{
formatTime(notification.timestamp) formatTime(notification.timestamp)
}}</span> }}
</span>
</div> </div>
</div> </div>
<button <button class="close-btn"
@click="removeNotification(notification.id)" @click="removeNotification(notification.id)">
class="close-btn"
>
✕ ✕
</button> </button>
</div> </div>
<div v-if="notifications.length === 0" class="empty-state"> <div v-if="notifications.length === 0" class="empty-state">
<div class="empty-icon">📭</div> <div class="empty-icon">
<div class="empty-text">暂无通知</div> 📭
</div>
<div class="empty-text">
暂无通知
</div>
</div> </div>
</div> </div>
</div> </div>
......
<script setup lang="ts"> <script setup lang="ts">
import type { MenuItem } from '@/types/menu'; import type { MenuItem } from "@/types/menu";
import { computed, ref, nextTick } from 'vue'; import { computed, nextTick, ref } from "vue";
import { ArrowDown, ArrowRight } from '@element-plus/icons-vue'; import { ArrowDown, ArrowRight } from "@element-plus/icons-vue";
import SidebarMenuItem from './SidebarMenuItem.vue';
interface Props { interface Props {
menu: MenuItem; menu: MenuItem;
...@@ -69,13 +68,13 @@ const handleClick = () => { ...@@ -69,13 +68,13 @@ const handleClick = () => {
if (hasChildren.value) { if (hasChildren.value) {
handleToggle(); handleToggle();
} else { } else {
emit('click', props.menu); emit("click", props.menu);
} }
}; };
// 展开/收起子菜单 // 展开/收起子菜单
const handleToggle = () => { const handleToggle = () => {
emit('toggle', props.menu.id); emit("toggle", props.menu.id);
}; };
// 鼠标进入 // 鼠标进入
...@@ -131,41 +130,35 @@ const hasVisibleChildren = (menu: MenuItem): boolean => { ...@@ -131,41 +130,35 @@ const hasVisibleChildren = (menu: MenuItem): boolean => {
// 点击子菜单项 // 点击子菜单项
const handleChildClick = (child: MenuItem) => { const handleChildClick = (child: MenuItem) => {
emit('click', child); emit("click", child);
showPopover.value = false; showPopover.value = false;
}; };
</script> </script>
<template> <template>
<div <div v-if="!menu.hidden"
v-if="!menu.hidden"
ref="menuItemRef" ref="menuItemRef"
class="sidebar-menu-item" class="sidebar-menu-item"
:class="{ collapsed: collapsed }" :class="{ collapsed }"
@mouseenter="handleMouseEnter" @mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave" @mouseleave="handleMouseLeave">
>
<!-- 菜单项本身 --> <!-- 菜单项本身 -->
<div <div class="menu-item-content"
class="menu-item-content"
:class="{ :class="{
active: isActive, active: isActive,
'has-children': hasChildren, 'has-children': hasChildren,
[`level-${menu.level || 1}`]: true, [`level-${menu.level || 1}`]: true,
collapsed: collapsed, collapsed,
}" }"
@click="handleClick" @click="handleClick">
>
<!-- 折叠模式:上下布局 --> <!-- 折叠模式:上下布局 -->
<template v-if="collapsed && menu.level === 1"> <template v-if="collapsed && menu.level === 1">
<div class="menu-icon-wrapper"> <div class="menu-icon-wrapper">
<img <img v-if="menu?.level === 1"
v-if="menu?.level == 1" alt=""
class="menu-icon" class="menu-icon"
src="/images/icon-menu-agentic.png" src="/images/icon-menu-agentic.png"
alt="" srcset="" />
srcset=""
/>
</div> </div>
<div class="menu-title-wrapper"> <div class="menu-title-wrapper">
<span class="menu-title">{{ menu.title }}</span> <span class="menu-title">{{ menu.title }}</span>
...@@ -175,25 +168,29 @@ const handleChildClick = (child: MenuItem) => { ...@@ -175,25 +168,29 @@ const handleChildClick = (child: MenuItem) => {
<!-- 正常模式:左右布局 --> <!-- 正常模式:左右布局 -->
<template v-else> <template v-else>
<!-- 菜单图标 --> <!-- 菜单图标 -->
<img <img v-if="menu?.level === 1"
v-if="menu?.level == 1" alt=""
class="menu-icon" class="menu-icon"
src="/images/icon-menu-agentic.png" src="/images/icon-menu-agentic.png"
alt="" srcset="" />
srcset=""
/>
<!-- 菜单标题 --> <!-- 菜单标题 -->
<span class="menu-title">{{ menu.title }}</span> <span class="menu-title">{{ menu.title }}</span>
<!-- 展开/收起图标 --> <!-- 展开/收起图标 -->
<span <span v-if="hasChildren && !collapsed"
v-if="hasChildren && !collapsed"
class="expand-icon" class="expand-icon"
@click.stop="handleToggle" @click.stop="handleToggle">
> <el-icon v-if="isExpanded"
<el-icon color="#1956FE" size="1.5em" v-if="isExpanded"><ArrowDown /></el-icon> color="#1956FE"
<el-icon color="#1956FE" size="1.5em" v-else><ArrowRight /></el-icon> size="1.5em">
<ArrowDown />
</el-icon>
<el-icon v-else
color="#1956FE"
size="1.5em">
<ArrowRight />
</el-icon>
</span> </span>
<!-- 徽章 --> <!-- 徽章 -->
...@@ -205,40 +202,32 @@ const handleChildClick = (child: MenuItem) => { ...@@ -205,40 +202,32 @@ const handleChildClick = (child: MenuItem) => {
<!-- 正常模式的子菜单 --> <!-- 正常模式的子菜单 -->
<transition name="submenu-expand"> <transition name="submenu-expand">
<div <div v-if="hasChildren && isExpanded && !collapsed"
v-if="hasChildren && isExpanded && !collapsed" class="submenu">
class="submenu" <SidebarMenuItem v-for="child in menu.children?.filter(c => !c.hidden)"
>
<SidebarMenuItem
v-for="child in menu.children?.filter(c => !c.hidden)"
:key="child.id" :key="child.id"
:menu="child"
:active-path="activePath" :active-path="activePath"
:expanded-keys="expandedKeys"
:collapsed="collapsed" :collapsed="collapsed"
:expanded-keys="expandedKeys"
:menu="child"
@click="$emit('click', $event)" @click="$emit('click', $event)"
@toggle="$emit('toggle', $event)" @toggle="$emit('toggle', $event)" />
/>
</div> </div>
</transition> </transition>
<!-- 折叠模式的悬浮子菜单卡片 --> <!-- 折叠模式的悬浮子菜单卡片 -->
<transition name="popover-fade"> <transition name="popover-fade">
<div <div v-if="collapsed && hasChildren && showPopover && menu.level === 1"
v-if="collapsed && hasChildren && showPopover && menu.level === 1"
class="submenu-popover" class="submenu-popover"
:style="{ top: `${popoverTop}px` }" :style="{ top: `${popoverTop}px` }">
>
<div class="popover-arrow"></div> <div class="popover-arrow"></div>
<div class="popover-content"> <div class="popover-content">
<div class="popover-menu-list"> <div class="popover-menu-list">
<div <div v-for="child in menu.children?.filter(c => !c.hidden)"
v-for="child in menu.children?.filter(c => !c.hidden)"
:key="child.id" :key="child.id"
class="popover-menu-item" class="popover-menu-item"
:class="{ active: checkChildActive(child) }" :class="{ active: checkChildActive(child) }"
@click="handleChildClick(child)" @click="handleChildClick(child)">
>
<span class="popover-menu-title">{{ child.title }}</span> <span class="popover-menu-title">{{ child.title }}</span>
<el-icon v-if="hasVisibleChildren(child)"> <el-icon v-if="hasVisibleChildren(child)">
<ArrowRight /> <ArrowRight />
...@@ -301,6 +290,10 @@ const handleChildClick = (child: MenuItem) => { ...@@ -301,6 +290,10 @@ const handleChildClick = (child: MenuItem) => {
background-color: #fff !important; background-color: #fff !important;
} }
.menu-item-content.collapsed.level-1.active:hover {
background-color: #fff !important;
}
.menu-icon-wrapper { .menu-icon-wrapper {
display: flex; display: flex;
align-items: center; align-items: center;
...@@ -371,15 +364,6 @@ const handleChildClick = (child: MenuItem) => { ...@@ -371,15 +364,6 @@ const handleChildClick = (child: MenuItem) => {
background-color: transparent !important; background-color: transparent !important;
} }
/* 折叠状态下的一级菜单选中样式:使用白色背景 */
.menu-item-content.collapsed.level-1.active {
background-color: #fff !important;
}
.menu-item-content.collapsed.level-1.active:hover {
background-color: #fff !important;
}
.menu-item-content.level-1.active::before { .menu-item-content.level-1.active::before {
display: none; display: none;
} }
......
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'; import { computed, onMounted, onUnmounted, ref } from "vue";
import { useRouter } from 'vue-router'; import { useRouter } from "vue-router";
import { useUserStore } from '@/stores'; import { useUserStore } from "@/stores";
const router = useRouter(); const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
...@@ -12,14 +12,14 @@ const showDropdown = ref(false); ...@@ -12,14 +12,14 @@ const showDropdown = ref(false);
// 获取用户名首字母(英文字母转为大写) // 获取用户名首字母(英文字母转为大写)
const userInitial = computed(() => { const userInitial = computed(() => {
const userName = userStore.userName || ''; const userName = userStore.userName || "";
if (!userName) return ''; if (!userName) return "";
// 获取第一个字符 // 获取第一个字符
const firstChar = userName.charAt(0); const firstChar = userName.charAt(0);
// 如果是英文字母,转换为大写;否则直接返回 // 如果是英文字母,转换为大写;否则直接返回
if (/[a-zA-Z]/.test(firstChar)) { if (/[a-z]/i.test(firstChar)) {
return firstChar.toUpperCase(); return firstChar.toUpperCase();
} }
...@@ -32,12 +32,12 @@ const showConfirmDialog = ref(false); ...@@ -32,12 +32,12 @@ const showConfirmDialog = ref(false);
// 判断是否为本地环境 // 判断是否为本地环境
const isLocalEnv = () => { const isLocalEnv = () => {
const hostname = window.location.hostname; const hostname = window.location.hostname;
return hostname === 'localhost' || hostname === '192.168.1.93'; return hostname === "localhost" || hostname === "192.168.1.93";
}; };
// 切换下拉菜单 // 切换下拉菜单
const toggleDropdown = () => { const toggleDropdown = () => {
console.log('toggleDropdown',isLocalEnv()); console.log("toggleDropdown", isLocalEnv());
if (isLocalEnv()) { if (isLocalEnv()) {
showDropdown.value = !showDropdown.value; showDropdown.value = !showDropdown.value;
} }
...@@ -46,7 +46,7 @@ const toggleDropdown = () => { ...@@ -46,7 +46,7 @@ const toggleDropdown = () => {
// 点击外部关闭下拉菜单 // 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => { const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement; const target = event.target as HTMLElement;
if (!target.closest('.user-info')) { if (!target.closest(".user-info")) {
showDropdown.value = false; showDropdown.value = false;
} }
}; };
...@@ -81,40 +81,52 @@ const confirmLogout = async () => { ...@@ -81,40 +81,52 @@ const confirmLogout = async () => {
await userStore.logout(); await userStore.logout();
// 跳转到登录页 // 跳转到登录页
router.push('/login'); router.push("/login");
} catch { } catch {
// 即使失败也跳转到登录页 // 即使失败也跳转到登录页
router.push('/login'); router.push("/login");
} }
}; };
// 组件挂载 // 组件挂载
onMounted(() => { onMounted(() => {
// 监听点击外部事件 // 监听点击外部事件
document.addEventListener('click', handleClickOutside); document.addEventListener("click", handleClickOutside);
}); });
// 组件卸载 // 组件卸载
onUnmounted(() => { onUnmounted(() => {
// 移除监听 // 移除监听
document.removeEventListener('click', handleClickOutside); document.removeEventListener("click", handleClickOutside);
}); });
</script> </script>
<template> <template>
<div class="user-info" v-if="userStore.isLoggedIn"> <div v-if="userStore.isLoggedIn" class="user-info">
<div class="user-info-card" @click.stop="toggleDropdown"> <div class="user-info-card" @click.stop="toggleDropdown">
<div class="avatar">{{ userInitial }}</div> <div class="avatar">
<p class="name">{{ userStore.userName }}</p> {{ userInitial }}
</div>
<p class="name">
{{ userStore.userName }}
</p>
</div> </div>
<!-- 下拉菜单 --> <!-- 下拉菜单 -->
<div v-if="showDropdown" class="user-dropdown" @click.stop> <div v-if="showDropdown"
class="user-dropdown"
@click.stop>
<div class="dropdown-header"> <div class="dropdown-header">
<div class="dropdown-avatar">{{ userStore.userAvatar || '👤' }}</div> <div class="dropdown-avatar">
{{ userStore.userAvatar || '👤' }}
</div>
<div class="dropdown-info"> <div class="dropdown-info">
<div class="dropdown-name">{{ userStore.userName }}</div> <div class="dropdown-name">
<div class="dropdown-id">ID: {{ userStore.userId }}</div> {{ userStore.userName }}
</div>
<div class="dropdown-id">
ID: {{ userStore.userId }}
</div>
</div> </div>
</div> </div>
...@@ -143,28 +155,28 @@ onUnmounted(() => { ...@@ -143,28 +155,28 @@ onUnmounted(() => {
<!-- 未登录状态 --> <!-- 未登录状态 -->
<div v-if="false" class="user-empty"> <div v-if="false" class="user-empty">
<router-link to="/login" class="login-link">登录</router-link> <router-link class="login-link" to="/login">
登录
</router-link>
</div> </div>
<!-- 确认对话框 --> <!-- 确认对话框 -->
<div <div v-if="showConfirmDialog"
v-if="showConfirmDialog"
class="confirm-dialog-overlay" class="confirm-dialog-overlay"
@click="showConfirmDialog = false" @click="showConfirmDialog = false">
>
<div class="confirm-dialog" @click.stop> <div class="confirm-dialog" @click.stop>
<div class="dialog-header"> <div class="dialog-header">
<span class="dialog-icon">❓</span> <span class="dialog-icon">❓</span>
<h3 class="dialog-title">确认退出</h3> <h3 class="dialog-title">
确认退出
</h3>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
<p>确定要退出登录吗?</p> <p>确定要退出登录吗?</p>
</div> </div>
<div class="dialog-footer"> <div class="dialog-footer">
<button <button class="dialog-btn cancel-btn"
class="dialog-btn cancel-btn" @click="showConfirmDialog = false">
@click="showConfirmDialog = false"
>
取消 取消
</button> </button>
<button class="dialog-btn confirm-btn" @click="confirmLogout"> <button class="dialog-btn confirm-btn" @click="confirmLogout">
......
import type { MicroAppConfig } from './types'; // 微应用配置类型 import type { MicroAppConfig } from "./types"; // 微应用配置类型
import { fetchMicroAppRouteConfig } from '../config/center'; import { fetchMicroAppRouteConfig } from "../config/center";
import { transformToQiankun } from './configTransformer'; import { transformToQiankun } from "./configTransformer";
// 微应用配置列表(初始为空,后续动态加载) // 微应用配置列表(初始为空,后续动态加载)
// eslint-disable-next-line import/no-mutable-exports
export let microApps: MicroAppConfig[] = []; export let microApps: MicroAppConfig[] = [];
// 配置加载状态 // 配置加载状态
let isConfigLoaded = false; let isConfigLoaded = false;
let configLoadPromise: Promise<void> | null = null; let configLoadPromise: null | Promise<void> = null;
// 默认配置(作为降级方案) // 默认配置(作为降级方案)
const defaultMicroApps: MicroAppConfig[] = [ const defaultMicroApps: MicroAppConfig[] = [
{ {
name: 'Home', name: "Home",
entry: '', // 主应用页面,无需 entry entry: "", // 主应用页面,无需 entry
container: '#subapp-viewport', // 微应用容器 container: "#subapp-viewport", // 微应用容器
activeRule: '/home', // 对应路由路径 activeRule: "/home", // 对应路由路径
}, },
]; ];
...@@ -39,7 +40,6 @@ export async function loadMicroAppConfig(): Promise<void> { ...@@ -39,7 +40,6 @@ export async function loadMicroAppConfig(): Promise<void> {
configLoadPromise = (async () => { configLoadPromise = (async () => {
try { try {
const remoteConfig = await fetchMicroAppRouteConfig(); const remoteConfig = await fetchMicroAppRouteConfig();
console.log('remoteConfigAAAAAA',JSON.stringify(remoteConfig));
// 获取子应用路由配置,并转换远程配置为 qiankun 配置( // 获取子应用路由配置,并转换远程配置为 qiankun 配置(
// props注入:communicationManager消息管理,getGscRequest请求实例,mountParcel,name子应用名称,singleSpa // props注入:communicationManager消息管理,getGscRequest请求实例,mountParcel,name子应用名称,singleSpa
microApps = transformToQiankun(remoteConfig.data?.microApps); microApps = transformToQiankun(remoteConfig.data?.microApps);
...@@ -48,8 +48,8 @@ export async function loadMicroAppConfig(): Promise<void> { ...@@ -48,8 +48,8 @@ export async function loadMicroAppConfig(): Promise<void> {
// microApps = defaultMicroApps; // microApps = defaultMicroApps;
// } // }
isConfigLoaded = true; isConfigLoaded = true;
console.log('[微前端配置] 配置加载完成,共加载', microApps, '个微应用'); console.log("[微前端配置] 配置加载完成,共加载", microApps, "个微应用");
} catch (error) { } catch {
microApps = defaultMicroApps; microApps = defaultMicroApps;
isConfigLoaded = true; isConfigLoaded = true;
} finally { } finally {
...@@ -102,7 +102,7 @@ export async function getMicroAppByPath( ...@@ -102,7 +102,7 @@ export async function getMicroAppByPath(
} }
return microApps.find((app) => { return microApps.find((app) => {
if (typeof app.activeRule === 'string') { if (typeof app.activeRule === "string") {
return path.startsWith(app.activeRule); return path.startsWith(app.activeRule);
} }
return false; return false;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!