Commit dd6d98b2 by 林磊

Merge branch 'faet_lint_error' into 'dev'

Faet lint error into Dev

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