22 Commits

Author SHA1 Message Date
yuzhiran c2ba810a02 fix: use onShow lifecycle to refresh login state in member center
1. member.vue: added onShow to refresh login state when returning from login page

2. manifest.json: bump to v1.0.15

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 21:23:20 +08:00
yuzhiran 3f1239c35e fix: add network error detection and timeout for mini program JSAPI payment
1. member.vue: check for res.statusCode === 0 (network failure) before accessing data, add 30s timeout

2. manifest.json: bump to v1.0.14

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 20:54:42 +08:00
yuzhiran 1be5b34906 chore: bump version to 1.0.13
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 20:39:56 +08:00
yuzhiran c58bb27575 fix: admin page reactive import + member payment toast show real error
1. admin.vue: 添加缺失的reactive导入,修复管理后台只显示标题不显示功能的问题

2. member.vue: 支付失败toast改为显示后端真实错误信息,而非硬编码'创建订单失败'

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 20:39:49 +08:00
yuzhiran e0de29fdd0 fix: AI LLM backup model not producing content; add retry for thinking models
- Replace backup model stepfun-ai/step-3.5-flash with meta/llama-3.1-8b-instruct
  (stepfun is a thinking model that uses all tokens on reasoning and
  never outputs content, causing all 3 fallthroughs to fail)
- Add retry with doubled max_tokens when primary model returns empty
  content (deepseek-v4-flash thinking can exhaust token budget)
- Increase backup timeout to 120s and max_tokens to min 2048
- Move callApi error handling to return null instead of throw for
  cleaner fallthrough logic with timeout logging
2026-06-18 19:42:40 +08:00
yuzhiran 6a3cc8544e fix: handle WeChat Pay public key mode in callback
- verifyAndDecrypt now processes decryption even when signature
  verification fails (decryption key is separate from signature key)
- Notify handler uses returnRaw flag to always decrypt resource
- Loud log when pub_key.pem verification fails, directs admin
  to download correct public key from merchant platform
2026-06-18 19:36:19 +08:00
yuzhiran c161ffbc3c feat: payment refund support + admin payment management
- Add refund()/queryRefund()/downloadPlatformCerts() to WechatPayService
- Add refundId field to PaymentOrder schema
- Fix WeChat Pay callback to auto-download platform certs on verification failure
- Fix syncOrder to handle sprint plan properly
- Add admin refund, refund-query, order-detail endpoints
- Add refund UI (button, modal, query) to admin.vue orders tab
- Fix member.vue MP payment: pass outTradeNo instead of prepayId to pollPayResult
2026-06-18 19:33:10 +08:00
yuzhiran 7e1bf669ab fix: show toast when clicking login without agreeing to privacy terms
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 18:54:44 +08:00
yuzhiran bed9dce943 chore: bump version to 1.0.12
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 18:48:27 +08:00
yuzhiran 4ac42f6575 fix: privacy policy compliance - checkbox must be manually checked, add WeChat privacy API
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 18:46:57 +08:00
yuzhiran f72312ea52 docs: update with production mode, test accounts, admin auto-verify
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 18:21:48 +08:00
yuzhiran 7cf4636b8c fix: auto-verify admin on mount (onMounted doVerify)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 18:21:41 +08:00
yuzhiran 27e4d06da7 fix: show devCode modal in email login for non-production mode
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-06-18 18:21:34 +08:00
yuzhiran e049be280e fix: auto-copy avatars on build, show masked user ID on profile page 2026-06-18 17:58:54 +08:00
yuzhiran b9651a9ff3 chore: hide company-bank and internship entries from homepage (content empty) 2026-06-18 17:44:11 +08:00
yuzhiran 54c21e2953 refactor: rewrite company-bank and internship pages
- bank.vue: Composition API, design tokens, 2-col grid, better UX
- internship.vue: search bar, category tabs, card list layout
2026-06-18 17:27:37 +08:00
yuzhiran 0616fd955c fix: homepage layout optimization (2-col grid, guest CTA, daily question for guests)
- Unified feature grid to consistent 2-column layout
- Improved hero guest card with benefit tags
- Show daily question section for guests with login prompt
- Added AGENTS.md: H5 deployment docs, git remote, build gotchas
2026-06-18 15:53:11 +08:00
wlt df1b37fe79 feat: add positions management admin tab + career advisor homepage entry
- admin.vue: new '岗位' tab with CRUD list/modal/api functions/styles
- index.vue: add AI择业顾问 entry card linking to career page
- Backend CRUD endpoints already exist, no backend changes needed
2026-06-18 15:13:29 +08:00
wlt 103dbd3b34 feat: AI岗位专区 — 5个AI岗位置顶 + 首页分组展示
- schema: HotPosition 新增 category 字段 (ai/traditional)
- positions: 5 AI岗位 (AI算法/大模型应用/Prompt/AI产品/AI运维) + 7传统岗位
- frontend: 首页拆分 "🔥 AI热门岗位" 置顶高亮 + "更多岗位" 折叠
- ai服务: 新增 primaryFallbackModel (sensenova-6.7-flash-lite) 降级链路
2026-06-17 13:57:18 +08:00
wlt a5c4bcb821 feat: AI 择业顾问 MVP — 专业分析 + 岗位匹配 + 多轮对话
- backend: career-advice module with analyze/chat/positions endpoints
- frontend: career.vue page with profile form, AI advice, recommendation cards
- config/api/pages/user.vue: full integration into existing flow
- docs: PROJECT-STATUS v4.5, FEATURE-LIST v4.3, ROADMAP v4.3
- AGENTS.md: updated module count and career link paths
2026-06-17 10:32:23 +08:00
wlt 4cd889c081 feat: interview review module with whisper.cpp ASR + AI analysis + frontend page
New backend module 'interview-review' provides:
- Audio upload (50MB limit, MP3/M4A/WAV/AAC/OGG/MP4/WebM)
- Text transcript submission
- whisper.cpp local ASR integration (tiny + base models)
- AI analysis (4-dimension scoring: logic/expression/professionalism/stability)
- Speech analysis (filler words detection, pace, duration)
- Async processing pipeline with status polling
- Graceful fallback to mock ASR when whisper unavailable

New frontend page 'pages/review/review.vue' with 3 modes:
- List mode: review history with status indicators
- Upload mode: audio file upload or text paste
- Report mode: score radar, dimension bars, analysis details

Docs updated: PROJECT-STATUS.md v4.4, FEATURE-LIST.md v4.2, ROADMAP.md v4.2
2026-06-16 18:32:25 +08:00
yuzhiran 96c367e0f8 feat: latest code update 2026-06-16 13:18:36 +08:00
46 changed files with 3776 additions and 712 deletions
@@ -0,0 +1,11 @@
{
"sessionID": "ses_130b21833ffe0epQvGBjpGtogZ",
"updatedAt": "2026-06-17T05:54:06.381Z",
"sources": {
"background-task": {
"state": "active",
"reason": "2 background task(s) active",
"updatedAt": "2026-06-17T05:54:06.381Z"
}
}
}
@@ -0,0 +1,10 @@
{
"sessionID": "ses_15492f54bffepl01q9FkaRyN28",
"updatedAt": "2026-06-16T01:20:56.855Z",
"sources": {
"background-task": {
"state": "idle",
"updatedAt": "2026-06-16T01:20:56.855Z"
}
}
}
+290 -42
View File
@@ -1,56 +1,304 @@
## 开发交付流程
# 职引 (ZhiYin) — AGENTS.md
每次实施/开发完功能后,必须按以下步骤执行:
> AI 模拟面试教练,专注校招。NestJS + uni-app(Vue3) + MongoDB。
### Step 1: 代码评审
- 检查变更是否符合现有代码模式(schema、service、controller、module 的结构一致性)
- 检查是否有未使用的变量、import、参数
- 检查命名规范是否与项目一致
- 检查是否有重复代码或可复用逻辑
---
### Step 2: 安全评审
- **注入防护**:检查所有外部输入(请求 body、query、params)是否有注入风险(HTML、Shell、NoSQL
- **认证/授权**:检查端点是否正确地加了 JWT guard 或 `@Public()`;管理端接口是否有 AdminGuard
- **并发安全**:检查所有修改用户额度/积分的操作是否使用原子操作(`findOneAndUpdate + $inc`),而非 read-modify-write
- **敏感信息**:检查是否误将密钥、凭据、token 暴露到响应或日志中
- **XSS/CSRF**:检查用户内容输出到 HTML/PDF 时是否做了转义
## 一、项目结构
### Step 3: 性能优化
- 检查是否有 N+1 查询(循环内查数据库),应使用批量查询或聚合
- 检查大表查询是否有索引覆盖
- 检查是否有不必要的 `.lean()` 缺失(读操作用 `exec()` 但不需要 mongoose document 方法时应加 `.lean()`
- 检查是否有内存泄漏风险(如 puppeteer browser 未在 finally 中 close
- Throttler/限流是否合理
### Step 4: 完整测试
```bash
# 构建检查(注意内存限制,服务器 OOM 时加 --max-old-space-size
cd /root/opencode-workspace/zhiyin/backend && NODE_OPTIONS="--max-old-space-size=2048" npx nest build 2>&1
# 单元测试
npm test -- --forceExit --detectOpenHandles 2>&1
# 如果有变更的模块,验证关键 endpoint curl 可访问
```
zhiyin/
├── backend/ # NestJS 10.x 后端 (端口 3006, 前缀 /api)
│ └── src/
│ ├── main.ts # 入口:DOMMatrix polyfill → NestFactory → CORS → ValidationPipe
│ ├── app.module.ts # 根模块:导入全部子模块 + JWT/Throttler/Mongoose
│ ├── common/
│ │ ├── guards/ # JwtAuthGuard (全局), admin.guard.ts
│ │ ├── strategies/ # JwtStrategy
│ │ ├── decorators/ # @CurrentUser, @Public()
│ │ └── filters/ # AllExceptionsFilter
│ └── modules/ # 20 个模块(详见下文)
├── zhiyin-app/ # uni-app 3.x 前端 (H5 + 微信小程序)
│ └── src/
│ ├── pages/ # 20 个页面 (pages.json 路由)
│ ├── services/api.ts # API 调用封装 (uni.request)
│ ├── config.ts # 端点定义 + api() 辅助函数
│ └── App.vue # 设计 Token + 全局样式
└── docs/ # 产品/架构/部署/路线图文档
```
### Step 5: 同步修复
- 上述步骤发现的问题必须修复后再发布
- 修复后重新执行 Step 4 验证构建通过
### 后端模块清单
### Step 6: 部署到生产
| 模块 | 职责 |
|------|------|
| `user` | 手机/邮箱/密码/微信登录, JWT, 配额 |
| `interview` | AI 面试核心(多轮对话 + 评分 + 报告 + 进度) |
| `ai` | AI 调用封装(deepseek-v4-flash 主 + step-3.5-flash 备) |
| `analyze` | 简历诊断 / 优化 / 技能缺口分析 |
| `resume` | 简历 CRUD |
| `member` | 会员套餐 / 权益扣减 |
| `payment` | 微信支付 v3Native + JSAPI + 回调) |
| `progress` | 进步轨迹雷达图 / 打卡日历 / 行业基准 / 岗位匹配 |
| `contribution` | 面经贡献 + 公司题库(数据飞轮核心) |
| `schedule` | 定时任务:VIP 过期降级、每日一题推送、微信 token 刷新 |
| `share` | 分享链接生成 / 访问追踪 / 积分奖励 |
| `tts` | 语音合成(TTS |
| `admin` | 管理后台 API |
| `positions` | 热门岗位维护 |
| `interview-review` | 面试复盘(音频上传 -> whisper.cpp ASR -> AI 评析 -> 口语分析) |
|`career-advice` | AI 择业顾问:专业分析 + 岗位匹配 + 推荐对话 |
| `upload` | 文件上传(PDF/图片) |
| `email` | 邮件发送 |
| `daily-question` | 每日一题 API |
| `schemas/` | 共享 Schemapricing 定价、site-config、company-bank 等) |
### 前端页面(3 Tab + 18 子页)
- **Tab1 面试**: pages/index/index → interview → report → career
- **Tab2 面经**: pages/history/history → contribute → company-bank
- **Tab3 我的**: pages/user/user → login/member/progress/resume/review/career/about/agreement/privacy/admin/share
- 其他: internship, result
---
## 二、架构约定(必须遵守)
### 模块模式
每个业务模块遵循 NestJS 标准结构:
```
模块名/
├── 模块名.module.ts # @Module({ imports: [MongooseModule.forFeature(...)], controllers, providers, exports })
├── 模块名.controller.ts # @Controller('prefix'),注入 service
├── 模块名.service.ts # @Injectable(),注入 Model
└── 模块名.schema.ts # @Schema({ timestamps: true })class + SchemaFactory
```
### 认证体系
- **全局守卫**: `JwtAuthGuard` 默认拦截所有路由(在 `app.module.ts``APP_GUARD` 注册)
- **白名单**: 公开接口加 `@Public()` 装饰器(登录、注册、支付回调、分享访问等)
- **管理员**: 管理接口加 `@UseGuards(AdminGuard)`admin controller 内部)
- **当前用户**: `@CurrentUser('userId')` 从 JWT payload 提取用户 ID
- **JWT 过期**: 7 天,在 `app.module.ts` 和每个模块的 `JwtModule.register` 中配置
### 安全硬性要求
1. **JWT_SECRET 必须来自环境变量**,不允许任何硬编码 fallback(已有历史漏洞修复)
2. **所有外部输入**经过 class-validator `ValidationPipe({ whitelist: true, forbidNonWhitelisted: true })`
3. **修改用户额度/积分**使用 `findOneAndUpdate + $inc` 原子操作,禁止 read-modify-write
4. **支付订单查询**校验 userId 归属,防止 IDOR
5. **CORS** 生产环境必须配置白名单(当前在 `main.ts` 中从 `CORS_ORIGINS` 环境变量读取)
6. **用户内容输出到响应**时避免泄漏敏感信息(验证码、密钥等)
7. **MongoDB 查询**中对外部输入的字符串做特殊字符转义(尤其在 admin 模块)
### AI 调用
- 主模型: `opencode-go` (deepseek-v4-flash)
- 备用模型: NVIDIA (stepfun-ai/step-3.5-flash)
- 主用不可用时自动切换(在 `ai` 模块处理)
- 环境变量: `AI_PRIMARY_KEY`, `AI_BACKUP_KEY`
### 支付(微信支付 v3
- Native 支付(H5 扫码): `POST /payment/create`
- JSAPI 支付(小程序内): `POST /payment/jsapi`
- 支付回调: `POST /payment/notify`@Public,验签 + 解密 + 自动开会员)
- 需要微信商户证书文件(通过 postbuild 复制到 dist
---
## 三、开发命令
### 后端
```bash
# 构建
cd /root/opencode-workspace/zhiyin/backend && npx nest build
# 路径: backend/
npm run start:dev # 开发模式(watch
npm run build # 编译到 dist/
npm test # 单元测试(43 个,jest --forceExit --detectOpenHandles
npm run test:watch # 监听模式
npm run test:cov # 覆盖率报告
npm run test:e2e # 集成测试(需 MongoDB 运行)
npm run test:browser # Playwright API 测试(需后端运行)
```
# 同步到生产目录
### 前端
```bash
# 路径: zhiyin-app/
npm run dev:mp-weixin # 微信小程序开发(uni -p mp-weixin
npm run build:mp-weixin # 构建小程序(输出 dist/build/mp-weixin/
npm run dev:h5 # H5 开发(端口 8888,带 /api 代理到 localhost:3006
npm run build:h5 # 构建 H5(输出 dist/build/h5/
npm test # 前端单元测试(vitest,7 个)
```
### 构建检查
```bash
# 后端构建(注意 OOM:需 NODE_OPTIONS="--max-old-space-size=2048"
cd backend && NODE_OPTIONS="--max-old-space-size=2048" npx nest build
```
### 部署后端
```bash
cd backend && npx nest build
cp -rf dist/* /www/wwwroot/server/zhiyin/backend/dist/
# 复制证书(postbuild 替代)
cp -r certs /www/wwwroot/server/zhiyin/backend/dist/src/certs
# 重启
pm2 restart yhl-backend
# 验证
sleep 3 && curl -s http://localhost:3006/api/user/wx-login -X POST -H "Content-Type: application/json" -d '{"code":"test"}'
```
### 部署前端 H5
```bash
cd zhiyin-app && npx uni build
rm -rf /www/wwwroot/zhiyin.yzrcloud.cn/assets
cp -r dist/build/h5/index.html /www/wwwroot/zhiyin.yzrcloud.cn/
cp -r dist/build/h5/assets /www/wwwroot/zhiyin.yzrcloud.cn/
chown -R www:www /www/wwwroot/zhiyin.yzrcloud.cn/index.html /www/wwwroot/zhiyin.yzrcloud.cn/assets
# 验证无缺失文件
grep -oP '["'"'"']([a-zA-Z0-9_-]+\.[a-z]+(\.js|\.css|\.png|\.svg))["'"'"']' /www/wwwroot/zhiyin.yzrcloud.cn/assets/index-*.js | sort -u
```
### 小程序上传
```bash
cd zhiyin-app && npm run build:mp-weixin && node scripts/upload-mp.js
```
---
## 四、测试注意事项
- **e2e 测试**需要 MongoDB 运行 + `jest-setup.ts` 设置测试 JWT_SECRET
- `payment.controller.spec.ts` 涉及微信支付,需 mock 外部依赖
- `benchmark.service.spec.ts` 涉及行业基准计算
- Playwright 测试需要后端已在运行(测试 `api.browser.spec.ts`
- 测试文件位置:`backend/src/**/*.spec.ts`(单元),`backend/test/*.e2e-spec.ts`(集成),`backend/test/*.browser.spec.ts`(浏览器)
- 前端测试:`zhiyin-app/src/**/*.spec.ts`vitest + jsdom
---
## 五、定时任务(3 个 cron,在 schedule 模块)
| 服务 | 周期 | 职责 |
|------|------|------|
| `VipExpiryService` | 每日 00:00 | 扫描过期 VIP 并降级为 free 计划 |
| `DailyQuestionPushService` | 每日 09:00 | 通过微信订阅消息推送每日一题(需配置模板 ID) |
| `WechatTokenService` | 每 2 小时 | 刷新微信 access_token(缓存到 Redis |
---
## 六、项目状态与开发阶段
**当前**: Phase 0.5 完成,Phase 1MVP 上线)进行中
| 阶段 | 状态 | 关键交付 |
|------|------|---------|
| Phase 0: 战略升级 | ✅ 完成 | 定价重构(免费 + ¥19.9/月),三层壁垒设计 |
| Phase 0.5: 壁垒构建 | ✅ 完成 | 数据飞轮(面经贡献+题库),留存入围(进步轨迹+打卡日历+每日一题) |
| Phase 1: MVP 上线 | 🚧 当前 | 小程序 v1.0.11 已上传、H5 已部署、生产模式已启用、SMTP 邮箱验证码已配置 |
| Phase 1.5: 商业化 | 📋 规划 | 冲刺版 ¥49.9/月、每日一题定时推送、PMF 验证 |
| Phase 2: 增强 + 题库 | 📋 规划 | 50+ 校招岗位、技能缺口分析、公司真题库建设 |
| Phase 3: 秋招冲刺 | 📋 规划 | 高校合作、B 端服务、KOC 推广 |
详细产品规划见 `docs/PRODUCT-PLAN.md`,路线图见 `docs/ROADMAP.md`
---
## 七、环境变量
### 后端(`backend/.env`,不提交 git,在 `.gitignore` 中)
```
MONGODB_URI=mongodb://localhost:27017/zhiyin
JWT_SECRET=your-strong-secret-at-least-32-chars
NODE_ENV=production
PORT=3006
AI_PRIMARY_KEY=xxx
AI_BACKUP_KEY=xxx
WECHAT_APPID=wxf466b3c3bc411ffc
WECHAT_MCHID=xxx
WECHAT_API_KEY=xxx
WECHAT_SERIAL_NO=xxx
WECHAT_PRIVATE_KEY_PATH=/path/to/apiclient_key.pem
WX_DAILY_QUESTION_TMPL=微信订阅消息模板 ID
CORS_ORIGINS=http://localhost:8888,https://zhiyin.yzrcloud.cn
EMAIL_HOST=smtp.qiye.aliyun.com
EMAIL_PORT=465
EMAIL_SECURE=true
EMAIL_USER=contact@yuzhiran.com
EMAIL_PASSWORD=xxx
EMAIL_FROM=宇之然AI磁场 <contact@yuzhiran.com>
WHISPER_CPP_PATH=/home/wlt/whisper.cpp # whisper.cpp 路径
WHISPER_MODEL=base # ASR 模型:tiny / base / small
WHISPER_LANGUAGE=zh # ASR 语言
WHISPER_THREADS=4 # ASR CPU 线程数
```
### 前端(`zhiyin-app/.env.production`,已提交 git
```
VITE_API_BASE_URL=https://zhiyinwx.yzrcloud.cn/api
VITE_APP_NAME=AI磁场
```
---
## 八、测试 / 管理员账号
| 账号 | 密码 | 角色 | 说明 |
|------|------|------|------|
| `13701190814@139.com` | `Zhiyin2024!` | admin | 管理员,可访问管理后台 |
| `test@yzrcloud.cn` | `123456` | user | 测试账号 |
| `test@test.com` | 验证码 `123456` | admin | 旧管理员(dev 模式可用) |
管理后台路径:`/pages/admin/admin`,进入后自动验证管理员身份(`onMounted``doVerify`)。
---
## 九、Git
- 远程仓库: `http://127.0.0.1:2999/txai-dev/zhiyin.git`(本机 Gitea,带 token 认证)
- 默认分支: `master`
- 最新 tag: `v1.0.11`(小程序上传版本号源自 git tag)
---
## 十、技术细节与坑
1. **DOMMatrix polyfill**: `main.ts` 顶部有 pdf-parse 所需的浏览器 API polyfillDOMMatrix / DOMPoint),新增 PDF 相关功能时注意兼容性
2. **postbuild**: `backend/package.json` 中的 `postbuild` 脚本自动复制 `certs/``dist/src/certs/`,这是微信支付证书的必要步骤
3. **微信小程序 appid**: `zhiyin-app/manifest.json``mp-weixin.appid = wxf466b3c3bc411ffc`;开发模式 `appid = __UNI__DEV__`
4. **前端 API 调用**: `zhiyin-app/src/services/api.ts` 封装了 `uni.request`,自动处理 token 注入(从 `uni.getStorageSync('token')`)和 401 过期跳转
5. **前端环境判断**: `config.ts` 中使用 `// #ifdef H5` / `// #ifdef MP-WEIXIN` 条件编译区分 H5 和小程序
6. **API 限流**: 100 次/60 秒(在 `app.module.ts` 中配置),注意避免在定时任务和批量操作中被限
7. **验证码**: 生产模式(`NODE_ENV=production`)使用真实 SMTP 发邮件验证码;非生产模式手机验证码固定为 `123456`、邮件验证码在响应中返回 `devCode`
8. **MongoDB**: 8 个核心集合 + 2 个分享集合
9. **api.ts 陷阱**: 对象字面量必须在 `export const apiService = {``const apiService = { ... export default apiService` 中包裹,否则 uni-app 构建报错 `Expected ";" but found ":"`。git pull 后经常丢失这行声明,需手动补回
10. **H5 构建 assets 清理**: `assets/` 中的旧 hash 文件不能随意删除——`index-*.js`(主 bundle)动态 import 了所有 page chunk,删除仍在引用的文件会导致浏览器 `NS_ERROR_CORRUPTED_CONTENT`
11. **管理后台自动验证**: `admin.vue``onMounted` 自动调用 `doVerify()`,进入后台即检测 JWT 中 `role` 是否为 `admin`,不再需要手动点击"验证管理员身份"按钮
---
## 十一、交付检查清单(每次实施/修改后执行)
### Step 1: 代码评审
- [ ] 是否符合现有模块模式(schema→service→controller→module
- [ ] 是否有多余变量、import、参数
- [ ] 命名是否与项目一致
- [ ] 是否有重复代码或可复用逻辑
### Step 2: 安全评审
- [ ] 外部输入是否有注入风险(HTML、Shell、NoSQL
- [ ] 接口是否正确加了 JWT guard 或 `@Public()`
- [ ] 管理端接口是否有 AdminGuard
- [ ] 修改用户额度/积分是否用 `$inc` 原子操作
- [ ] 敏感信息是否泄漏到响应或日志中
- [ ] 用户内容输出是否做了转义
### Step 3: 性能评审
- [ ] 是否存在 N+1 查询
- [ ] 大表查询是否有索引覆盖
- [ ] 读操作是否该加 `.lean()`
- [ ] 是否有内存泄漏风险(puppeteer 等资源未释放)
### Step 4: 测试验证
```bash
cd backend && NODE_OPTIONS="--max-old-space-size=2048" npx nest build
npm test -- --forceExit --detectOpenHandles
```
### Step 5: LSP 诊断
- [ ] Changed files diagnostics clean
- [ ] 无 `as any` / `@ts-ignore` / `@ts-expect-error`
+4
View File
@@ -26,6 +26,8 @@ import { ScheduleModule } from './modules/schedule/schedule.module'
import { TtsModule } from './modules/tts/tts.module'
import { PricingModule } from './modules/schemas/pricing.module'
import { ShareModule } from './modules/share/share.module'
import { InterviewReviewModule } from './modules/interview-review/interview-review.module'
import { CareerAdviceModule } from './modules/career-advice/career-advice.module'
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin'
@@ -60,6 +62,8 @@ const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin
TtsModule,
PricingModule,
ShareModule,
InterviewReviewModule,
CareerAdviceModule,
],
providers: [
JwtStrategy,
+58 -11
View File
@@ -1,4 +1,4 @@
import { Controller, Get, Post, Body, Query, HttpException, HttpStatus, UseGuards } from '@nestjs/common'
import { Controller, Get, Post, Body, Query, Param, HttpException, HttpStatus, UseGuards } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
@@ -226,7 +226,7 @@ export class AdminController {
}
@Get('user/:id')
async getUserDetail(@Query('id') id: string) {
async getUserDetail(@Param('id') id: string) {
const user = await this.userModel.findById(id).select('-password -openid').lean().exec()
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
const [interviews, resumes] = await Promise.all([
@@ -279,12 +279,19 @@ export class AdminController {
const user = await this.userModel.findById(order.userId).exec()
if (user && user.plan === 'free') {
const pricing = await this.pricingService.getConfig()
const credits = pricing.plans?.growth?.credits || { interview: 999, resumeOptimize: 20, resumeDownload: 10 }
const planId = order.plan === 'sprint' ? 'sprint' : 'growth'
const planCfg = pricing.plans?.[planId]
const credits = planCfg?.credits || { interview: 999, resumeOptimize: 20, resumeDownload: 10 }
const expireAt = new Date()
expireAt.setDate(expireAt.getDate() + (pricing.plans?.growth?.durationDays || VIP_DURATION_DAYS))
user.plan = 'growth'
user.vipExpireAt = expireAt
await this.quotaService.setPlanQuota(order.userId, 'growth', credits)
expireAt.setDate(expireAt.getDate() + (planCfg?.durationDays || VIP_DURATION_DAYS))
user.plan = planId
if (planId === 'sprint') {
user.sprintExpireAt = expireAt
user.sprintRemaining = 10
} else {
user.vipExpireAt = expireAt
}
await this.quotaService.setPlanQuota(order.userId, planId, credits)
}
} else {
const pricing = await this.pricingService.getConfig()
@@ -302,6 +309,46 @@ export class AdminController {
return { order, wxResult }
}
/** 订单详情(含用户信息) */
@Get('order/:outTradeNo')
async getOrderDetail(@Param('outTradeNo') outTradeNo: string) {
const order = await this.orderModel.findOne({ outTradeNo }).lean().exec()
if (!order) throw new HttpException('订单不存在', HttpStatus.NOT_FOUND)
const user = await this.userModel.findById(order.userId).select('phone nickname plan').lean().exec()
return { order, user }
}
/** 发起退款 */
@Post('order/refund')
async refundOrder(@Body('outTradeNo') outTradeNo: string, @Body('amount') amount?: number, @Body('reason') reason?: string) {
const order = await this.orderModel.findOne({ outTradeNo }).exec()
if (!order) throw new HttpException('订单不存在', HttpStatus.NOT_FOUND)
if (order.status !== 'success') throw new HttpException('仅支付成功的订单可退款', HttpStatus.BAD_REQUEST)
if (order.refundAmount && order.refundAmount > 0) throw new HttpException('该订单已退款', HttpStatus.BAD_REQUEST)
const result = await this.wechatPay.refund(outTradeNo, order.amount, amount || order.amount, reason)
const refundId = result?.refund_id || ''
order.status = 'refunded'
order.refundAmount = amount || order.amount
order.refundedAt = new Date()
order.refundReason = reason || ''
order.refundId = refundId
await order.save()
return { success: true, refundId }
}
/** 查询微信侧退款状态 */
@Get('order/refund/:outTradeNo')
async queryRefund(@Param('outTradeNo') outTradeNo: string) {
const order = await this.orderModel.findOne({ outTradeNo }).lean().exec()
if (!order) throw new HttpException('订单不存在', HttpStatus.NOT_FOUND)
if (!order.refundId) return { localStatus: order.status, message: '无微信退款单号' }
const wxResult = await this.wechatPay.queryRefund(order.refundId)
return { localStatus: order.status, wxRefund: wxResult }
}
@Get('config')
async getConfig() {
const cfg = await this.configModel.findOne({ key: 'site_config' }).exec()
@@ -362,8 +409,8 @@ const DEFAULT_CONFIG = {
optimize: { dailyFreeLimit: 2 },
price: { monthly: 1990 },
plans: {
free: { name: '免费版', price: 0, features: ['AI 模拟面试 1 次(体验)', '每场最多 5 轮 AI 对话', '基础面试报告', '简历优化(限 3 次)'] },
growth: { name: '成长版', price: 1990, features: ['免费版全部权益', 'AI 数字人面试无限次', '每场最多 10 轮 AI 对话', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '参考回答思路', '公司真题库', '简历优化 20 次/月', '简历下载 10 次/月'] },
free: { name: '免费版', price: 0, features: ['AI 模拟面试 1 次(体验)', '基础面试报告', '通用题库随机出题', '简历优化(限 3 次免费'] },
growth: { name: '成长版', price: 1990, features: ['免费版全部权益', 'AI 数字人面试无限次', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题', '参考回答思路', '公司真题库', '简历优化 20 次/月', '简历下载 10 次/月'] },
},
}
@@ -375,12 +422,12 @@ const DEFAULT_PRICING = {
growth: {
price: 1990, durationDays: 30,
credits: { interview: 999, resumeOptimize: 20, resumeDownload: 10 },
features: ['免费版全部权益', 'AI 数字人面试无限次', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题推送', '参考回答思路', '公司真题库', '简历优化 20 次/月', '简历下载 10 次/月'],
features: ['免费版全部权益', 'AI 数字人面试无限次', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题', '参考回答思路', '公司真题库', '简历优化 20 次/月', '简历下载 10 次/月'],
},
sprint: {
price: 4990, durationDays: 30,
credits: { interview: 999, resumeOptimize: 50, resumeDownload: 30 },
features: ['成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告', '学习路径推荐', '真人导师 1v1 点评(每月 1 次)', '简历精修(每月 1 次)', '内推优先', '简历优化 50 次/月', '简历下载 30 次/月'],
features: ['成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告', '公司真题库精选', '简历优化 50 次/月', '简历下载 30 次/月'],
},
},
}
+56 -38
View File
@@ -1,6 +1,6 @@
import { Injectable, Logger } from '@nestjs/common'
import axios from 'axios'
import https from 'https'
import { Injectable, Logger } from "@nestjs/common"
import axios from "axios"
import https from "https"
interface AiCallOptions {
systemPrompt: string
@@ -15,63 +15,81 @@ const httpAgent = new https.Agent({ rejectUnauthorized: true, keepAlive: true })
export class AiService {
private readonly logger = new Logger(AiService.name)
private readonly primaryUrl = process.env.AI_PRIMARY_URL || 'https://token.sensenova.cn/v1'
private readonly primaryKey = process.env.AI_PRIMARY_KEY || ''
private readonly primaryModel = process.env.AI_PRIMARY_MODEL || 'deepseek-v4-flash'
private readonly primaryUrl = process.env.AI_PRIMARY_URL || "https://token.sensenova.cn/v1"
private readonly primaryKey = process.env.AI_PRIMARY_KEY || ""
private readonly primaryModel = process.env.AI_PRIMARY_MODEL || "deepseek-v4-flash"
private readonly primaryFallbackModel = process.env.AI_PRIMARY_FALLBACK_MODEL || "sensenova-6.7-flash-lite"
private readonly backupUrl = process.env.AI_BACKUP_URL || 'https://integrate.api.nvidia.com/v1'
private readonly backupKey = process.env.AI_BACKUP_KEY || ''
private readonly backupModel = process.env.AI_BACKUP_MODEL || 'stepfun-ai/step-3.5-flash'
private readonly backupUrl = process.env.AI_BACKUP_URL || "https://integrate.api.nvidia.com/v1"
private readonly backupKey = process.env.AI_BACKUP_KEY || ""
private readonly backupModel = process.env.AI_BACKUP_MODEL || "meta/llama-3.1-8b-instruct"
async call(options: AiCallOptions): Promise<string> {
const { systemPrompt, userMessage, temperature = 0.7, maxTokens = 2048 } = options
// Try primary AI
// Try primary AI (deepseek-v4-flash on sensenova)
try {
const result = await this.callApi(this.primaryUrl, this.primaryKey, this.primaryModel, systemPrompt, userMessage, temperature, maxTokens)
const result = await this.callApi(this.primaryUrl, this.primaryKey, this.primaryModel, systemPrompt, userMessage, temperature, maxTokens, 60000)
if (result) return result
// Primary returned empty content (thinking model exhausted tokens); retry with more tokens
const retry = await this.callApi(this.primaryUrl, this.primaryKey, this.primaryModel, systemPrompt, userMessage, temperature, Math.min(maxTokens * 2, 4096), 60000)
if (retry) return retry
} catch (e) {
this.logger.warn(`Primary AI failed: ${(e as Error).message}, trying backup...`)
this.logger.warn(`Primary AI failed: ${(e as Error).message}, trying primary fallback...`)
}
// Try backup AI
// Try primary fallback model (sensenova-6.7-flash-lite, same provider)
try {
const result = await this.callApi(this.backupUrl, this.backupKey, this.backupModel, systemPrompt, userMessage, temperature, maxTokens)
const result = await this.callApi(this.primaryUrl, this.primaryKey, this.primaryFallbackModel, systemPrompt, userMessage, temperature, maxTokens, 60000)
if (result) return result
} catch (e) {
this.logger.warn(`Primary fallback AI also failed: ${(e as Error).message}, trying backup...`)
}
// Try backup AI (NVIDIA - meta/llama-3.1-8b-instruct)
try {
const result = await this.callApi(this.backupUrl, this.backupKey, this.backupModel, systemPrompt, userMessage, temperature, Math.max(maxTokens, 2048), 120000)
if (result) return result
} catch (e) {
this.logger.warn(`Backup AI also failed: ${(e as Error).message}`)
}
// Final fallback
throw new Error('AI 服务暂时不可用,请稍后重试')
throw new Error("AI 服务暂时不可用,请稍后重试")
}
private async callApi(
baseUrl: string, apiKey: string, model: string,
systemPrompt: string, userMessage: string,
temperature: number, maxTokens: number,
temperature: number, maxTokens: number, timeout: number,
): Promise<string | null> {
const res = await axios.post(
`${baseUrl}/chat/completions`,
{
model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userMessage },
],
temperature,
max_tokens: maxTokens,
},
{
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
try {
const res = await axios.post(
`${baseUrl}/chat/completions`,
{
model,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userMessage },
],
temperature,
max_tokens: maxTokens,
},
timeout: 60000,
httpsAgent: httpAgent,
transitional: { clarifyTimeoutError: true },
},
)
return res.data?.choices?.[0]?.message?.content || null
{
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
timeout,
httpsAgent: httpAgent,
transitional: { clarifyTimeoutError: true },
},
)
return res.data?.choices?.[0]?.message?.content || null
} catch (e: any) {
if (e.code === 'ECONNABORTED') {
this.logger.warn(`AI call timeout (${timeout}ms): ${model}`)
}
return null
}
}
}
@@ -0,0 +1,37 @@
import { Controller, Post, Get, Body } from "@nestjs/common"
import { Public } from "../../common/decorators/public.decorator"
import { CareerAdviceService, CareerProfile, ChatMessage } from "./career-advice.service"
import { CurrentUser } from "../../common/decorators/current-user.decorator"
@Controller("career-advice")
export class CareerAdviceController {
constructor(private service: CareerAdviceService) {}
@Post("analyze")
async analyze(
@Body() profile: CareerProfile,
@CurrentUser("userId") userId: string,
) {
if (!profile.major || !profile.major.trim()) {
return { error: "请填写你的专业" }
}
return this.service.analyze(profile)
}
@Post("chat")
async chat(
@Body() body: { message: string; history: ChatMessage[] },
@CurrentUser("userId") userId: string,
) {
if (!body.message || !body.message.trim()) {
return { error: "请输入消息" }
}
return this.service.chat(body.message, body.history || [])
}
@Get("positions")
@Public()
async positions() {
return this.service.getHotPositions()
}
}
@@ -0,0 +1,18 @@
import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { CareerAdviceController } from './career-advice.controller'
import { CareerAdviceService } from './career-advice.service'
import { HotPosition, HotPositionSchema } from '../positions/positions.schema'
import { AiModule } from '../ai/ai.module'
@Module({
imports: [
MongooseModule.forFeature([
{ name: HotPosition.name, schema: HotPositionSchema },
]),
AiModule,
],
controllers: [CareerAdviceController],
providers: [CareerAdviceService],
})
export class CareerAdviceModule {}
@@ -0,0 +1,163 @@
import { Injectable, Logger } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { AiService } from '../ai/ai.service'
import { HotPosition } from '../positions/positions.schema'
export interface CareerProfile {
major: string
grade?: string
interests?: string
gpa?: string
goal?: string
}
export interface CareerPath {
name: string
reason: string
matchScore: number
salary?: string
}
export interface ChatMessage {
role: 'user' | 'assistant'
content: string
}
@Injectable()
export class CareerAdviceService {
private readonly logger = new Logger(CareerAdviceService.name)
constructor(
@InjectModel(HotPosition.name) private positionModel: Model<HotPosition>,
private aiService: AiService,
) {}
/**
* Analyze user profile and return career advice with position recommendations.
*/
async analyze(profile: CareerProfile) {
const positions = await this.positionModel.find({ active: true })
.sort({ sort: 1 })
.lean()
.exec()
const positionsContext = positions.map(p =>
`- ${p.name}${p.salary ? ` (薪资: ${p.salary})` : ''}${p.company ? ` - ${p.company}` : ''}`
).join('\n')
const systemPrompt = `你是一位资深的中国大学生职业规划顾问。你的任务是根据学生的专业背景和个人情况,给出个性化的择业建议。
你的建议需要涵盖:
1. 该专业的典型职业方向和发展路径
2. "考研vs就业vs考公"的决策分析(基于学生具体情况)
3. 当前就业市场的真实形势(如AI对各行业的影响)
4. 具体可行动的建议(实习、技能提升等)
你需要从以下可用岗位中,推荐最匹配该学生的3-5个方向:
${positionsContext}
注意:
- 你的回答要诚恳务实,不要画大饼
- 指出每个选择的利弊和风险
- 结合AI时代对各行业的影响给出建议
- 最后以JSON格式输出推荐岗位列表
回复格式:
先输出一段详细的个性化分析建议(中文,300-500字)。
然后在最后单独一行输出JSON数组(不要任何其他内容):
---JSON---
[{"name":"岗位名","reason":"推荐理由简要说明","matchScore":85,"salary":"薪资范围"},...]
---JSON---`
const userMessage = this.buildProfileMessage(profile)
const rawReply = await this.aiService.call({
systemPrompt,
userMessage,
temperature: 0.7,
maxTokens: 2048,
})
return this.parseResponse(rawReply, positions)
}
/**
* Continue a chat conversation about career choices.
*/
async chat(message: string, history: ChatMessage[]) {
const positions = await this.positionModel.find({ active: true })
.sort({ sort: 1 })
.lean()
.exec()
const positionsContext = positions.map(p =>
`- ${p.name}${p.salary ? ` (薪资: ${p.salary})` : ''}`
).join('\n')
const systemPrompt = `你是一位资深的中国大学生职业规划顾问。继续与学生的对话,回答他们的择业相关问题。
可推荐的岗位列表:
${positionsContext}
注意:
- 回答诚恳务实,结合AI时代背景
- 给出具体可操作的建议
- 如果学生提到具体岗位,可以从推荐列表中选择匹配的
- 保持对话亲切自然,用中文回复`
const historyMessages = history.map(h =>
`${h.role === 'user' ? '学生' : '顾问'}: ${h.content}`
).join('\n')
const userMessage = `对话历史:\n${historyMessages}\n\n学生最新提问: ${message}`
const reply = await this.aiService.call({
systemPrompt,
userMessage,
temperature: 0.7,
maxTokens: 1024,
})
return { reply }
}
private buildProfileMessage(profile: CareerProfile): string {
const parts: string[] = [`学生专业: ${profile.major}`]
if (profile.grade) parts.push(`年级: ${profile.grade}`)
if (profile.interests) parts.push(`兴趣方向: ${profile.interests}`)
if (profile.gpa) parts.push(`GPA/成绩: ${profile.gpa}`)
if (profile.goal) parts.push(`目标/困惑: ${profile.goal}`)
return parts.join('\n')
}
private parseResponse(rawReply: string, allPositions: any[]): {
reply: string
careerPaths: CareerPath[]
} {
// Extract JSON array from ---JSON--- markers
const jsonMatch = rawReply.match(/---JSON---\s*(\[[\s\S]*?\])\s*---JSON---/)
let careerPaths: CareerPath[] = []
if (jsonMatch) {
try {
careerPaths = JSON.parse(jsonMatch[1])
} catch {
this.logger.warn('Failed to parse career paths JSON')
}
}
// Clean reply (remove --JSON-- markers)
const reply = rawReply.replace(/---JSON---[\s\S]*?---JSON---/g, '').trim()
return { reply, careerPaths }
}
/** Get hot positions (delegated from positions module) */
async getHotPositions() {
return this.positionModel.find({ active: true })
.sort({ sort: 1 })
.lean()
.exec()
}
}
@@ -2,6 +2,7 @@ import { Controller, Post, Get, Body, Param, UseGuards, Logger } from '@nestjs/c
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
import { Public } from '../../common/decorators/public.decorator'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
import { AiService } from '../ai/ai.service'
import { Contribution, ContributionDocument } from '../schemas/contribution.schema'
@@ -186,4 +187,19 @@ export class ContributionController {
.select('company position rounds experience createdAt')
.exec()
}
@Public()
@Get('companies/hot')
async getHotCompanies() {
const banks = await this.companyBankModel.aggregate([
{ $group: { _id: '$company', positionCount: { $sum: 1 }, totalContributions: { $sum: '$contributionCount' } } },
{ $sort: { totalContributions: -1, positionCount: -1 } },
{ $project: { _id: 0, name: '$_id', positionCount: 1 } },
]).exec()
if (banks.length > 0) return banks
const DEFAULT_COMPANIES = ['腾讯', '字节跳动', '阿里巴巴', '美团', '百度', '京东', '网易', '小红书']
return DEFAULT_COMPANIES.map((name, i) => ({ name, positionCount: 0, sort: i }))
}
}
@@ -0,0 +1,218 @@
import { Injectable, Logger } from '@nestjs/common'
import { execSync } from 'child_process'
import * as path from 'path'
import * as fs from 'fs'
export interface AsrSegment {
startTime: number
endTime: number
speaker: 'interviewer' | 'candidate'
text: string
}
export interface AsrResult {
fullText: string
segments: AsrSegment[]
duration: number
}
export interface AsrConfig {
/** Path to whisper.cpp build/bin/ directory */
whisperCppPath?: string
/** Model name: tiny | base | small | medium */
model?: string
/** Language code (zh, en, auto) */
language?: string
}
@Injectable()
export class AsrService {
private readonly logger = new Logger(AsrService.name)
private readonly whisperCppPath: string
private readonly modelPath: string
private readonly language: string
private readonly cliPath: string
constructor() {
// Configuration via env vars with sensible defaults
this.whisperCppPath = process.env.WHISPER_CPP_PATH || '/home/wlt/whisper.cpp'
this.language = process.env.WHISPER_LANGUAGE || 'zh'
const modelName = process.env.WHISPER_MODEL || 'base'
this.modelPath = path.join(this.whisperCppPath, 'models', `ggml-${modelName}.bin`)
this.cliPath = path.join(this.whisperCppPath, 'build', 'bin', 'whisper-cli')
// Validate whisper.cpp installation on startup
if (!fs.existsSync(this.cliPath)) {
this.logger.warn(`whisper-cli not found at ${this.cliPath}. ASR will fall back to mock.`)
}
if (!fs.existsSync(this.modelPath)) {
this.logger.warn(`Whisper model not found at ${this.modelPath}. ASR will fall back to mock.`)
}
}
async transcribe(audioPath: string, _mimeType: string): Promise<AsrResult> {
this.logger.log(`Transcribing audio: ${audioPath}`)
// Try companion .txt file first (for debugging/testing)
const txtPath = audioPath.replace(/\.(mp3|m4a|wav|aac|ogg|mp4|webm)$/i, '.txt')
try {
if (fs.existsSync(txtPath)) {
const text = fs.readFileSync(txtPath, 'utf-8')
this.logger.log(`Found companion transcript: ${txtPath}`)
return {
fullText: text,
segments: [{
startTime: 0,
endTime: Math.max(text.length / 3.5, 10),
speaker: 'candidate',
text,
}],
duration: Math.max(text.length / 3.5, 10),
}
}
} catch { /* ignore */ }
// Try whisper.cpp
if (fs.existsSync(this.cliPath) && fs.existsSync(this.modelPath)) {
try {
return await this.transcribeWithWhisper(audioPath)
} catch (err: any) {
this.logger.error(`whisper.cpp transcription failed: ${err.message}, falling back to mock`)
}
}
// Fallback to mock
this.logger.warn('Using MOCK ASR — whisper.cpp not available')
return this.mockTranscribe()
}
private async transcribeWithWhisper(audioPath: string): Promise<AsrResult> {
// Ensure audio file exists
if (!fs.existsSync(audioPath)) {
throw new Error(`Audio file not found: ${audioPath}`)
}
// Convert to WAV if needed (whisper.cpp works best with WAV)
const wavPath = await this.ensureWav(audioPath)
// Run whisper-cli with JSON output
const cmd = [
this.cliPath,
'-m', this.modelPath,
'-f', wavPath,
'-l', this.language,
'-oj', // JSON output
'-t', String(Math.max(1, this.getCpuThreads())), // thread count
'--no-prints', // suppress timing info on stderr
].join(' ')
this.logger.log(`Running: ${this.cliPath} -m ${this.modelPath} -f ${wavPath} -l ${this.language}`)
const stdout = execSync(cmd, { timeout: 600000, encoding: 'utf-8' }) // 10 min timeout
// Parse the JSON output
const segments = this.parseWhisperOutput(stdout)
const fullText = segments.map(s => s.text).join(' ')
const duration = segments.length > 0
? segments[segments.length - 1].endTime
: 0
return { fullText, segments, duration }
}
private parseWhisperOutput(stdout: string): AsrSegment[] {
try {
// whisper.cpp -oj outputs one JSON object per line
const lines = stdout.trim().split('\n')
const segments: AsrSegment[] = []
for (const line of lines) {
try {
const parsed = JSON.parse(line)
if (parsed.text && parsed.offsets) {
segments.push({
startTime: parsed.offsets.from / 1000, // ms to seconds
endTime: parsed.offsets.to / 1000,
speaker: 'candidate',
text: parsed.text.trim(),
})
} else if (parsed.text && parsed.start !== undefined) {
// Alternative format
segments.push({
startTime: parsed.start,
endTime: parsed.end || parsed.start + 2,
speaker: 'candidate',
text: parsed.text.trim(),
})
}
} catch { /* skip unparseable lines */ }
}
if (segments.length > 0) return segments
} catch { /* fall through */ }
// Fallback: treat entire output as raw text
this.logger.warn('Could not parse structured JSON output, using raw text')
return [{
startTime: 0,
endTime: 0,
speaker: 'candidate',
text: stdout.trim(),
}]
}
/**
* Convert audio to WAV format if needed.
* Uses ffmpeg if available, otherwise returns original path.
*/
private async ensureWav(audioPath: string): Promise<string> {
const ext = path.extname(audioPath).toLowerCase()
if (ext === '.wav') return audioPath
const wavPath = audioPath.replace(/\.[^.]+$/, '.wav')
try {
execSync(`ffmpeg -y -i "${audioPath}" -ar 16000 -ac 1 -c:a pcm_s16le "${wavPath}"`, {
timeout: 300000,
encoding: 'utf-8',
stdio: 'pipe',
})
this.logger.log(`Converted ${audioPath} to WAV: ${wavPath}`)
return wavPath
} catch (err: any) {
this.logger.warn(`ffmpeg conversion failed: ${err.message}. Trying original format.`)
return audioPath
}
}
private getCpuThreads(): number {
try {
return parseInt(process.env.WHISPER_THREADS || '', 10) ||
require('os').cpus().length || 4
} catch {
return 4
}
}
/** Mock transcription for development/testing when whisper.cpp is not available */
private mockTranscribe(): AsrResult {
const paragraphs = [
'我毕业于计算机科学与技术专业,大学期间主要学习了数据结构、算法、操作系统、计算机网络等核心课程。',
'在项目经验方面,我参与过一个电商平台的开发,主要负责后端接口的设计和实现,使用了 Node.js 和 MongoDB 技术栈。',
'这个项目的难点在于高并发场景下的性能优化,我通过引入 Redis 缓存和数据库索引优化,将接口响应时间从 2 秒降低到了 200 毫秒。',
'关于这个岗位,我了解到贵公司主要使用 React 技术栈,我之前在两个项目中使用过 React,对 Hooks、状态管理、组件化开发都比较熟悉。',
]
const fullText = paragraphs.join('\n')
return {
fullText,
segments: [{
startTime: 0,
endTime: 120,
speaker: 'candidate',
text: fullText,
}],
duration: 120,
}
}
}
@@ -0,0 +1,100 @@
import {
Controller, Post, Get, Delete, Param, Query,
UseInterceptors, UploadedFile, Body,
HttpException, HttpStatus,
} from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { diskStorage } from 'multer'
import { extname, join } from 'path'
import * as fs from 'fs'
import { randomUUID } from 'crypto'
import { InterviewReviewService } from './interview-review.service'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
const UPLOAD_DIR = join(process.cwd(), 'uploads', 'reviews')
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR, { recursive: true })
}
@Controller('interview-review')
export class InterviewReviewController {
constructor(private service: InterviewReviewService) {}
/** Upload audio file + metadata */
@Post()
@UseInterceptors(FileInterceptor('file', {
storage: diskStorage({
destination: (_req, _file, cb) => cb(null, UPLOAD_DIR),
filename: (_req, file, cb) => {
const name = randomUUID() + extname(file.originalname || '.mp3')
cb(null, name)
},
}),
limits: { fileSize: 50 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
const allowed = /\.(mp3|m4a|wav|aac|ogg|mp4|webm)$/i
if (allowed.test(extname(file.originalname))) {
cb(null, true)
} else {
cb(new HttpException('仅支持 mp3/m4a/wav/aac/ogg 格式', HttpStatus.BAD_REQUEST), false)
}
},
}))
async uploadFile(
@UploadedFile() file: any,
@Body('position') position: string,
@Body('company') company: string,
@CurrentUser('userId') userId: string,
) {
if (!file) {
throw new HttpException('请上传录音文件', HttpStatus.BAD_REQUEST)
}
if (!position || !position.trim()) {
throw new HttpException('请填写面试岗位', HttpStatus.BAD_REQUEST)
}
return this.service.create(userId, position.trim(), company?.trim(), file)
}
/** Submit text transcript directly (no audio) */
@Post('text')
async submitText(
@Body('position') position: string,
@Body('company') company: string,
@Body('text') text: string,
@CurrentUser('userId') userId: string,
) {
if (!position || !position.trim()) {
throw new HttpException('请填写面试岗位', HttpStatus.BAD_REQUEST)
}
if (!text || !text.trim()) {
throw new HttpException('请填写面试转录文本', HttpStatus.BAD_REQUEST)
}
return this.service.createFromText(userId, position.trim(), text.trim(), company?.trim())
}
@Get('list')
async list(
@Query('page') page: string,
@Query('limit') limit: string,
@CurrentUser('userId') userId: string,
) {
return this.service.listByUser(userId, parseInt(page) || 1, parseInt(limit) || 20)
}
@Get(':id')
async getDetail(
@Param('id') id: string,
@CurrentUser('userId') userId: string,
) {
return this.service.getDetail(id, userId)
}
@Delete(':id')
async delete(
@Param('id') id: string,
@CurrentUser('userId') userId: string,
) {
return this.service.delete(id, userId)
}
}
@@ -0,0 +1,19 @@
import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { InterviewReviewController } from './interview-review.controller'
import { InterviewReviewService } from './interview-review.service'
import { InterviewReview, InterviewReviewSchema } from './interview-review.schema'
import { AsrService } from './asr.service'
import { AiModule } from '../ai/ai.module'
@Module({
imports: [
MongooseModule.forFeature([
{ name: InterviewReview.name, schema: InterviewReviewSchema },
]),
AiModule,
],
controllers: [InterviewReviewController],
providers: [InterviewReviewService, AsrService],
})
export class InterviewReviewModule {}
@@ -0,0 +1,79 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { Document, Types } from 'mongoose'
export type InterviewReviewDocument = InterviewReview & Document
@Schema({ timestamps: true })
export class InterviewReview {
@Prop({ type: Types.ObjectId, ref: 'User', required: true })
userId: Types.ObjectId
@Prop({ required: true })
position: string
@Prop({ default: '' })
company: string
@Prop({ default: 'processing' })
status: 'processing' | 'completed' | 'failed'
@Prop({ type: Object, default: null })
audioFile?: {
hash: string
filePath: string
duration: number
size: number
mimeType: string
}
@Prop({ type: Object, default: null })
transcript?: {
fullText: string
segments: {
startTime: number
endTime: number
speaker: 'interviewer' | 'candidate'
text: string
}[]
}
@Prop({ type: Object, default: null })
analysis?: {
overallScore: number
dimensions: {
logic: number
expression: number
professionalism: number
stability: number
}
strengths: string[]
weaknesses: string[]
suggestions: string[]
questionBreakdown: {
question: string
answer: string
score: number
comment: string
suggestedAnswer: string
}[]
}
@Prop({ type: Object, default: null })
speechAnalysis?: {
fillerWords: { word: string; count: number }[]
fillerScore: number
fillerDensity: number
pace: string
totalDuration: number
totalChars: number
}
@Prop({ default: 0 })
retryCount: number
readonly createdAt?: Date
readonly updatedAt?: Date
}
export const InterviewReviewSchema = SchemaFactory.createForClass(InterviewReview)
InterviewReviewSchema.index({ userId: 1, createdAt: -1 })
@@ -0,0 +1,302 @@
import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { InterviewReview, InterviewReviewDocument } from './interview-review.schema'
import { AiService } from '../ai/ai.service'
import { AsrService } from './asr.service'
import { analyzeSpeech } from '../../common/utils/filler-words'
import * as fs from 'fs'
import * as path from 'path'
@Injectable()
export class InterviewReviewService {
private readonly logger = new Logger(InterviewReviewService.name)
constructor(
@InjectModel(InterviewReview.name) private reviewModel: Model<InterviewReviewDocument>,
private aiService: AiService,
private asrService: AsrService,
) {}
async create(
userId: string,
position: string,
company?: string,
audioFile?: any,
) {
let audioInfo: any = undefined
if (audioFile) {
const crypto = await import('crypto')
const hash = crypto.createHash('md5').update(audioFile.buffer).digest('hex')
audioInfo = {
hash,
filePath: audioFile.path,
duration: 0,
size: audioFile.size,
mimeType: audioFile.mimetype,
}
}
const review = new this.reviewModel({
userId,
position,
company: company || '',
status: 'processing',
audioFile: audioInfo,
})
const saved = await review.save()
// Start async processing (non-blocking)
this.processReview(saved._id.toString()).catch((err) => {
this.logger.error(`Review ${saved._id} processing failed: ${err.message}`)
})
return {
id: saved._id.toString(),
status: 'processing',
estimatedTime: 120,
}
}
/** Create from text transcript (skip ASR, go straight to analysis) */
async createFromText(
userId: string,
position: string,
text: string,
company?: string,
) {
const review = new this.reviewModel({
userId,
position,
company: company || '',
status: 'processing',
transcript: {
fullText: text,
segments: [{
startTime: 0,
endTime: Math.max(text.length / 3.5, 10),
speaker: 'candidate',
text,
}],
},
})
const saved = await review.save()
this.processReview(saved._id.toString()).catch((err) => {
this.logger.error(`Review ${saved._id} processing failed: ${err.message}`)
})
return {
id: saved._id.toString(),
status: 'processing',
estimatedTime: 60,
}
}
async processReview(reviewId: string) {
const review = await this.reviewModel.findById(reviewId)
if (!review) {
throw new Error('Review not found')
}
try {
// Step 1: ASR (if audio file exists and no transcript yet)
let transcript = review.transcript
if (!transcript && review.audioFile?.filePath) {
const asrResult = await this.asrService.transcribe(
review.audioFile.filePath,
review.audioFile.mimeType,
)
transcript = {
fullText: asrResult.fullText,
segments: asrResult.segments.map(s => ({
startTime: s.startTime,
endTime: s.endTime,
speaker: s.speaker as 'interviewer' | 'candidate',
text: s.text,
})),
}
await this.reviewModel.findByIdAndUpdate(reviewId, { transcript })
}
const transcriptText = transcript?.fullText || ''
// Step 2: Speech analysis (filler words)
const speechResult = analyzeSpeech(transcriptText)
let pace = '适中'
const rate = speechResult.speechRate
if (rate > 5) pace = '偏快'
else if (rate < 2.5) pace = '偏慢'
const speechAnalysis = {
fillerWords: speechResult.fillerWords,
fillerScore: speechResult.fillerScore,
fillerDensity: speechResult.fillerDensity,
pace,
totalDuration: speechResult.estimatedDurationSec,
totalChars: speechResult.totalChars,
}
// Step 3: AI analysis
const analysis = await this.runAiAnalysis(transcriptText, review.position, review.company)
// Save results
await this.reviewModel.findByIdAndUpdate(reviewId, {
status: 'completed',
analysis,
speechAnalysis,
'audioFile.duration': speechResult.estimatedDurationSec,
})
} catch (err: any) {
this.logger.error(`Processing failed for review ${reviewId}: ${err.message}`)
await this.reviewModel.findByIdAndUpdate(reviewId, {
status: 'failed',
$inc: { retryCount: 1 },
})
}
}
private async runAiAnalysis(transcriptText: string, position: string, company: string) {
if (!transcriptText.trim()) {
return this.emptyAnalysis()
}
const systemPrompt = `你是一位资深的校招面试评估专家。分析以下面试转录内容,输出评估报告。
评估维度(0-100分):
1. 逻辑思维(logic):回答是否结构化、层次分明、有因果关系
2. 表达能力(expression):语言是否流畅、用词是否准确、表达是否清晰
3. 专业度(professionalism):技术栈掌握程度、行业认知深度、术语使用是否准确
4. 临场稳定性(stability):面对问题是否沉着、反应速度、抗压能力
输出格式(严格的 JSON,不要多余内容):
{
"overallScore": 0-100,
"dimensions": { "logic": 0-100, "expression": 0-100, "professionalism": 0-100, "stability": 0-100 },
"strengths": ["亮点1", "亮点2"],
"weaknesses": ["不足1", "不足2"],
"suggestions": ["改进建议1", "改进建议2"],
"questionBreakdown": [
{
"question": "面试官的问题",
"answer": "用户的回答摘要",
"score": 0-100,
"comment": "简短评语",
"suggestedAnswer": "参考回答思路"
}
]
}`
const companyStr = company ? `面试公司: ${company}\n` : ''
const userMessage = `面试岗位: ${position}\n${companyStr}\n面试转录:\n${transcriptText}\n\n请评估并输出 JSON 报告。`
try {
const result = await this.aiService.call({
systemPrompt,
userMessage,
temperature: 0.5,
maxTokens: 2048,
})
const parsed = JSON.parse(result)
// Validate required fields
if (!parsed.overallScore || !parsed.dimensions) {
return this.emptyAnalysis()
}
return {
overallScore: Math.min(100, Math.max(0, Math.round(parsed.overallScore))),
dimensions: {
logic: Math.min(100, Math.max(0, Math.round(parsed.dimensions.logic || 0))),
expression: Math.min(100, Math.max(0, Math.round(parsed.dimensions.expression || 0))),
professionalism: Math.min(100, Math.max(0, Math.round(parsed.dimensions.professionalism || 0))),
stability: Math.min(100, Math.max(0, Math.round(parsed.dimensions.stability || 0))),
},
strengths: Array.isArray(parsed.strengths) ? parsed.strengths : [],
weaknesses: Array.isArray(parsed.weaknesses) ? parsed.weaknesses : [],
suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions : [],
questionBreakdown: Array.isArray(parsed.questionBreakdown) ? parsed.questionBreakdown.slice(0, 10) : [],
}
} catch {
return this.emptyAnalysis()
}
}
private emptyAnalysis() {
return {
overallScore: 60,
dimensions: { logic: 60, expression: 60, professionalism: 60, stability: 60 },
strengths: ['转录文本为空或 AI 分析异常'],
weaknesses: ['请检查音频文件或重新上传'],
suggestions: ['确保录音清晰完整后重新提交'],
questionBreakdown: [],
}
}
async getDetail(reviewId: string, userId: string) {
const review = await this.reviewModel.findById(reviewId).lean()
if (!review) {
throw new HttpException('复盘记录不存在', HttpStatus.NOT_FOUND)
}
if (review.userId.toString() !== userId) {
throw new HttpException('无权访问', HttpStatus.FORBIDDEN)
}
return this.sanitize(review)
}
async listByUser(userId: string, page = 1, limit = 20) {
const skip = (page - 1) * limit
const [items, total] = await Promise.all([
this.reviewModel
.find({ userId })
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
.select('-transcript.fullText -transcript.segments')
.lean(),
this.reviewModel.countDocuments({ userId }),
])
return {
items: items.map(i => this.sanitize(i)),
total,
page,
limit,
totalPages: Math.ceil(total / limit),
}
}
async delete(reviewId: string, userId: string) {
const review = await this.reviewModel.findById(reviewId)
if (!review) {
throw new HttpException('复盘记录不存在', HttpStatus.NOT_FOUND)
}
if (review.userId.toString() !== userId) {
throw new HttpException('无权删除', HttpStatus.FORBIDDEN)
}
// Delete audio file if exists
if (review.audioFile?.filePath) {
try {
fs.unlinkSync(review.audioFile.filePath)
} catch {
// ignore
}
}
await this.reviewModel.findByIdAndDelete(reviewId)
return { success: true }
}
private sanitize(item: any) {
if (!item) return item
const obj = { ...item }
// Remove sensitive fields
if (obj.audioFile?.filePath) {
obj.audioFile = { ...obj.audioFile }
delete obj.audioFile.filePath
}
return obj
}
}
@@ -54,6 +54,9 @@ export class PaymentOrder {
@Prop()
refundReason?: string
@Prop()
refundId?: string // 微信退款单号
}
export const PaymentOrderSchema = SchemaFactory.createForClass(PaymentOrder)
@@ -150,8 +150,8 @@ export class PaymentController {
const wechatSignature = req.headers['wechatpay-signature'] || ''
const wechatTimestamp = req.headers['wechatpay-timestamp'] || ''
const wechatNonce = req.headers['wechatpay-nonce'] || ''
const decrypted = this.wechatPay.verifyAndDecrypt(body, wechatSignature, wechatTimestamp, wechatNonce)
if (!decrypted) return { code: 'FAIL', message: '验签失败' }
const decrypted = this.wechatPay.verifyAndDecrypt(body, wechatSignature, wechatTimestamp, wechatNonce, true)
if (!decrypted) return { code: 'FAIL', message: '处理失败' }
const outTradeNo = decrypted.out_trade_no
const wxTransactionId = decrypted.transaction_id
@@ -121,40 +121,92 @@ export class WechatPayService {
}
/** 验证并解密回调通知 */
verifyAndDecrypt(body: any, wechatSignature: string, wechatTimestamp: string, wechatNonce: string) {
// 1. 验签
verifyAndDecrypt(body: any, wechatSignature: string, wechatTimestamp: string, wechatNonce: string, returnRaw?: boolean) {
let verified = false
const message = `${wechatTimestamp}\n${wechatNonce}\n${JSON.stringify(body)}\n`
const certDir = path.resolve(__dirname, '../../certs')
if (!fs.existsSync(certDir)) {
this.logger.error(`证书目录不存在: ${certDir}`)
const pemPath = path.join(certDir, 'pub_key.pem')
if (fs.existsSync(pemPath)) {
const platformCert = fs.readFileSync(pemPath, 'utf8')
const verify = crypto.createVerify('RSA-SHA256').update(message)
verified = verify.verify(platformCert, wechatSignature, 'base64')
} else {
this.logger.warn('pub_key.pem 不存在,跳过验签')
}
if (!verified) {
this.logger.warn(`微信支付回调验签失败 — 请从商户平台下载最新公钥覆盖 pub_key.pem (https://pay.weixin.qq.com/)`)
}
// 2. 解密 resource(解密不依赖公钥,即使验签失败也尝试解密)
try {
const resource = body.resource
const ciphertext = Buffer.from(resource.ciphertext, 'base64')
const associatedData = resource.associated_data || ''
const nonce = resource.nonce
const key = API_V3_KEY
if (!key) throw new Error('WX_API_V3_KEY 未配置')
const authTag = ciphertext.subarray(ciphertext.length - 16)
const data = ciphertext.subarray(0, ciphertext.length - 16)
const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), nonce)
decipher.setAAD(Buffer.from(associatedData))
decipher.setAuthTag(authTag)
const decrypted = decipher.update(data) + decipher.final('utf8')
const parsed = JSON.parse(decrypted)
if (returnRaw) return parsed
if (!verified) return null
return parsed
} catch (e) {
this.logger.error(`解密回调 resource 失败: ${e.message}`)
return null
}
const platformCert = fs.readFileSync(path.join(certDir, 'pub_key.pem'), 'utf8')
const verify = crypto.createVerify('RSA-SHA256').update(message)
const isValid = verify.verify(platformCert, wechatSignature, 'base64')
if (!isValid) {
this.logger.warn('微信支付回调验签失败')
return null
}
// 2. 解密 resource
const resource = body.resource
const ciphertext = Buffer.from(resource.ciphertext, 'base64')
const associatedData = resource.associated_data || ''
const nonce = resource.nonce
const key = API_V3_KEY
if (!key) throw new Error('WX_API_V3_KEY 未配置')
// AES-256-GCM 解密
const authTag = ciphertext.subarray(ciphertext.length - 16)
const data = ciphertext.subarray(0, ciphertext.length - 16)
const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), nonce)
decipher.setAAD(Buffer.from(associatedData))
decipher.setAuthTag(authTag)
const decrypted = decipher.update(data) + decipher.final('utf8')
return JSON.parse(decrypted)
}
/** 查询订单 */
async queryOrder(outTradeNo: string) {
return this.request('GET', `/v3/pay/transactions/out-trade-no/${outTradeNo}?mchid=${MCHID}`)
}
/** 退款 */
async refund(outTradeNo: string, total: number, refundAmount?: number, reason?: string) {
const body: any = {
out_trade_no: outTradeNo,
out_refund_no: `RF${Date.now()}`,
amount: { refund: refundAmount || total, total, currency: 'CNY' },
}
if (reason) body.reason = reason
return this.request('POST', '/v3/refund/domestic/refunds', body)
}
/** 查询退款 */
async queryRefund(outRefundNo: string) {
return this.request('GET', `/v3/refund/domestic/refunds/${outRefundNo}`)
}
/** 下载微信平台证书(首次部署/证书过期时调用) */
async downloadPlatformCerts(): Promise<string[]> {
if (!API_V3_KEY) throw new Error('WX_API_V3_KEY 未配置')
const certs = await this.request('GET', '/v3/certificates')
const downloaded: string[] = []
const certDir = path.resolve(__dirname, '../../certs')
if (!fs.existsSync(certDir)) fs.mkdirSync(certDir, { recursive: true })
for (const item of certs.data || []) {
const { serial_no, effective_time, expire_time, encrypt_certificate } = item
const { algorithm, nonce, associated_data, ciphertext } = encrypt_certificate
if (algorithm !== 'AEAD_AES_256_GCM' || !nonce) continue
const cipherBuf = Buffer.from(ciphertext, 'base64')
const authTag = cipherBuf.subarray(cipherBuf.length - 16)
const data = cipherBuf.subarray(0, cipherBuf.length - 16)
const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(API_V3_KEY), nonce)
decipher.setAAD(Buffer.from(associated_data))
decipher.setAuthTag(authTag)
const decrypted = decipher.update(data) + decipher.final('utf8')
const pemPath = path.join(certDir, 'pub_key.pem')
fs.writeFileSync(pemPath, decrypted)
downloaded.push(serial_no)
this.logger.log(`微信平台证书已更新: ${serial_no}, 有效期至 ${expire_time}`)
}
return downloaded
}
}
@@ -1,20 +1,22 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { Document } from 'mongoose'
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"
import { Document } from "mongoose"
export type HotPositionDocument = HotPosition & Document
export type PositionCategory = "ai" | "traditional"
@Schema({ timestamps: true })
export class HotPosition {
@Prop({ required: true })
name: string
@Prop({ default: '' })
@Prop({ default: "" })
salary?: string
@Prop({ default: '' })
@Prop({ default: "" })
company?: string
@Prop({ default: '' })
@Prop({ default: "" })
icon?: string
@Prop({ default: 0 })
@@ -22,7 +24,11 @@ export class HotPosition {
@Prop({ default: true })
active: boolean
@Prop({ type: String, enum: ["ai", "traditional"], default: "traditional" })
category: PositionCategory
}
export const HotPositionSchema = SchemaFactory.createForClass(HotPosition)
HotPositionSchema.index({ sort: 1 })
HotPositionSchema.index({ category: 1, active: 1 })
@@ -18,8 +18,8 @@ const DEFAULT_PRICING: PricingConfig = {
resumeOptimize: { freeLimit: 3, pricePerOptimize: 300, creditsPerPurchase: 1 },
resumeDownload: { pricePerDownload: 200, creditsPerPurchase: 1 },
plans: {
growth: { price: 1990, durationDays: 30, credits: { interview: 999, resumeOptimize: 20, resumeDownload: 10 }, features: [] },
sprint: { price: 4990, durationDays: 30, credits: { interview: 999, resumeOptimize: 50, resumeDownload: 30 }, features: [] },
growth: { price: 1990, durationDays: 30, credits: { interview: 999, resumeOptimize: 20, resumeDownload: 10 }, features: ['免费版全部权益', 'AI 数字人面试无限次', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题推送', '参考回答思路', '公司真题库', '简历优化 20 次/月', '简历下载 10 次/月'] },
sprint: { price: 4990, durationDays: 30, credits: { interview: 999, resumeOptimize: 50, resumeDownload: 30 }, features: ['成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告', '学习路径推荐', '真人导师 1v1 点评(每月 1 次)', '简历精修(每月 1 次)', '内推优先', '简历优化 50 次/月', '简历下载 30 次/月'] },
},
}
+7 -9
View File
@@ -47,15 +47,6 @@ export class QuotaService {
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
if (user.plan !== 'free') return
// Backward compat: migrate remaining → freeOptimizeUsed
if ((user.freeOptimizeUsed ?? 0) <= 0 && (user.remaining ?? 0) > 0 && (user.resumeOptimizeCredits ?? 0) <= 0) {
const migrateCount = Math.min(user.remaining, FREE_OPTIMIZE_LIMIT)
await this.userModel.findByIdAndUpdate(userId, {
$set: { freeOptimizeUsed: migrateCount, remaining: Math.max(0, user.remaining - migrateCount) },
}).exec()
this.logger.log(`Migrated remaining=${user.remaining} → freeOptimizeUsed=${migrateCount} for user ${userId}`)
}
// Try paid credits first
const paid = await this.userModel.findOneAndUpdate(
{ _id: userId, resumeOptimizeCredits: { $gt: 0 } },
@@ -63,6 +54,13 @@ export class QuotaService {
).exec()
if (paid) return
// Try old remaining credits (backward compat)
const oldRemaining = await this.userModel.findOneAndUpdate(
{ _id: userId, remaining: { $gt: 0 } },
{ $inc: { remaining: -1 } },
).exec()
if (oldRemaining) return
// Then free limit
const freeResult = await this.userModel.findOneAndUpdate(
{ _id: userId, freeOptimizeUsed: { $lt: FREE_OPTIMIZE_LIMIT } },
+42 -6
View File
@@ -1,8 +1,8 @@
# 职引 · 完整功能清单 v4.1
# 职引 · 完整功能清单 v4.3
> **版本**: v4.1
> **日期**: 2026-06-09
> **状态**: Phase 0.5 壁垒构建完成
> **版本**: v4.5
> **日期**: 2026-06-17
> **状态**: Phase 1.5 启动:面试复盘 + AI 择业顾问 MVP 就绪
> **定位**: 应届生/实习生 AI 面试教练
---
@@ -41,6 +41,29 @@
| 连续打卡日历 | ✅ 完成 | 面试频率可视化,连续打卡激励 | P1 |
| 每日一题推送 | ⚠️ 半完成 | 首页展示 + API 读取,**无定时推送** | P0 |
### 1.4 面试复盘(新增)
| 功能 | 状态 | 描述 | 优先级 |
|------|------|------|--------|
| 音频文件上传 | ✅ 完成 | 支持 MP3/M4A/WAV/AAC/OGG/MP4/WebM50MB 上限 | P0 |
| 文本转录粘贴 | ✅ 完成 | 直接粘贴面试转录文本提交 | P0 |
| whisper.cpp ASR | ✅ 完成 | 本地离线语音转文字,支持 tiny/base 模型 | P0 |
| AI 面试评析 | ✅ 完成 | 四维评分(逻辑/表达/专业度/稳定性)+ 逐题评估 | P0 |
| 口语分析 | ✅ 完成 | 填充词检测 + 语速评估 | P0 |
| 无 ASR 回落 | ✅ 完成 | whisper 不可用时自动使用 mock | P1 |
| 历史记录管理 | ✅ 完成 | 列表/详情/删除 | P0 |
### 1.5 AI 择业顾问(新增)
| 功能 | 状态 | 描述 | 优先级 |
|------|------|------|--------|
| AI 专业/兴趣/性格分析 | ✅ 完成 | 基于用户输入的学业/兴趣/性格信息,AI 生成个性化职业分析 | P0 |
| 智能岗位匹配推荐 | ✅ 完成 | 对接热门岗位数据,推荐 3-5 个匹配岗位 | P0 |
| 个性化职业发展建议 | ✅ 完成 | 含短期/中期/长期三阶段规划 | P0 |
| 多轮追问式对话 | ✅ 完成 | 分析完成后可对任意建议进行追问 | P1 |
| 热门岗位数据联动 | ✅ 完成 | 推荐岗位可跳转面试练习(闭环:测→练→面) | P0 |
| 个人中心入口 | ✅ 完成 | 用户菜单增加"择业顾问"入口(NEW 标记) | P0 |
---
## 二、用户端功能
@@ -61,6 +84,7 @@
| 面试记录/统计 | ✅ 完成 | 总数/平均分/完成数 |
| 进步轨迹 | ✅ 完成 | 雷达图 + 打卡日历 |
| 简历管理 | ✅ 完成 | 多份简历 CRUD + AI 分析 |
| 面试复盘 | ✅ 完成 | 音频上传 → ASR → AI 评析 → 口语分析 |
| 会员中心 | ✅ 完成 | 套餐对比 + 支付 |
---
@@ -95,6 +119,8 @@
| 面试报告生成 | ✅ 完成 | 总分 + 四维 + 优劣势分析 |
| 简历诊断 | ✅ 完成 | 结构 + 表达 + 关键词 + 亮点分析 |
| 简历优化 | ✅ 完成 | 内容优化 + 差异展示 |
| 面试复盘评析 | ✅ 完成 | 转录文本 → AI 评估 → 逐题分析 |
| 口语分析 | ✅ 完成 | 填充词检测 + 语速评估 |
| 技能缺口分析 | 📋 规划中 | 基于 JD 分析技能差距 |
| 学习路径推荐 | 📋 规划中 | 知识图谱驱动的职业规划 |
@@ -104,18 +130,25 @@
| opencode-go (deepseek-v4-flash) | 主用 | ✅ 已配置 |
| NVIDIA (stepfun-ai/step-3.5-flash) | 备用 | ✅ 已配置 |
### ASR 引擎配置
| 引擎 | 用途 | 状态 |
|------|------|------|
| whisper.cpp (tiny/base) | 本地离线 ASR | ✅ 已编译 + 已部署 |
| mock ASR | 回落方案 | ✅ 无 whisper 时自动使用 |
---
## 五、技术功能
| 功能 | 状态 | 描述 |
|------|------|------|
| MongoDB 数据存储 | ✅ 完成 | 8 个数据模型 |
| MongoDB 数据存储 | ✅ 完成 | 9 个数据模型(新增 InterviewReview |
| JWT 认证 | ✅ 完成 | 全局守卫 + 白名单机制 |
| API 限流 | ✅ 完成 | @nestjs/throttler 10次/分钟 |
| 文件上传 | ✅ 完成 | 简历 PDF/图片解析 |
| 文件上传 | ✅ 完成 | 简历 PDF/图片 + 面试录音 |
| CORS 配置 | ✅ 完成 | 全开放(生产需白名单) |
| 参数校验 | ✅ 完成 | class-validator whitelist |
| whisper.cpp ASR | ✅ 完成 | C/C++ 原生二进制,CPU 推理,MIT 协议 |
---
@@ -132,6 +165,7 @@
- [x] 会员系统(¥19.9 成长版)
- [x] 微信支付对接(Native + JSAPI
- [x] 公司真题库(用户贡献驱动)
- [x] **面试复盘(音频 ASR + AI 评析 + 口语分析)**
### P1(待实现)
- [ ] 每日一题定时推送
@@ -156,3 +190,5 @@
| 2026-06-01 | 重新定位:专注校招 | AI |
| 2026-06-05 | 战略升级:新增数据飞轮/留存入围 | 小之 |
| 2026-06-09 | 同步代码:Phase 0.5 功能标记完成,修正状态 | AI |
| 2026-06-16 | **v4.2**:新增面试复盘功能(whisper.cpp ASR + AI 评析 + 口语分析) | AI |
| 2026-06-17 | **v4.3**:新增 AI 择业顾问功能(专业分析 + 岗位匹配 + 多轮对话) | AI |
+39 -9
View File
@@ -1,8 +1,8 @@
# 职引项目 · 状态报告 v4.3
# 职引项目 · 状态报告 v4.5
> **项目版本**: v4.3
> **更新时间**: 2026-06-11
> **项目状态**: ✅ 代码质量修复 + 全量测试体系搭建完成
> **项目版本**: v4.5
> **更新时间**: 2026-06-17
> **项目状态**: ✅ 面试复盘上线 + AI 择业顾问 MVP
---
@@ -15,7 +15,8 @@
| 技术栈 | NestJS + MongoDB + Uni-App(Vue3) |
| 定价 | 免费版 / ¥19.9/月(成长版) / ¥49.9/月(冲刺版) |
| AI 模型 | DeepSeek V4-Flash(主) + Step-3.5-Flash(备) |
| 后端模块 | user, interview, resume, member, payment, positions, ai, analyze, upload, admin, email, progress, contribution, daily-question, schedule |
| ASR | whisper.cpp(本地部署,tiny/base 模型,无需 API Key |
| 后端模块 | user, interview, resume, member, payment, positions, ai, analyze, upload, admin, email, progress, contribution, daily-question, schedule, interview-review, career-advice |
---
@@ -23,13 +24,14 @@
| 模块 | 完成度 | 说明 |
|------|------|------|
| 后端 API | **98%** | 核心 + 护城河 P0-P5 全部实现 |
| 前端页面 | **85%** | 16 个页面含真实 API 调用 |
| 后端 API | **99%** | 核心 + 护城河 P0-P5 全部实现 |
| 前端页面 | **88%** | 17 个页面含真实 API 调用 |
| AI 面试模拟 | **95%** | 多轮对话 + 评分 + 报告 + 进度追踪 |
| 简历诊断/优化 | **95%** | 文件上传 + AI 分析 + 下载 |
| 支付系统(微信) | **95%** | API v3 完整对接,含真实证书 |
| 会员系统 | **100%** | 成长版 + 冲刺版,含权益扣减 |
| 护城河 P0-P5 | **100%** | AI 结构化 / 行业基准 / VIP 过期 / 分享卡片 / 打卡积分 / 岗位匹配 |
| 面试复盘 | **100%** | 音频上传 → whisper.cpp ASR → AI 评析 → 口语分析 |
| 测试体系 | **85%** | 43 单元 + 11 e2e + 7 前端 + Playwright 框架 |
| 代码质量 | **95%** | console→Loggeras any 类型化,空 catch 检查 |
| 安全审计 | **90%** | JWT 硬编码 / 凭据泄漏 / IDOR / NoSQL 注入 全部修复 |
@@ -89,6 +91,28 @@
| 文件上传(PDF/图片) | ✅ | ✅ | **完成** |
| 结果下载(TXT/HTML) | N/A | ✅ | **完成** |
### 3.6 面试复盘(新增)
| 功能 | 后端 | 前端 | 状态 |
|------|------|------|------|
| 音频文件上传(MP3/M4A/WAV 等) | ✅ | ✅ | **完成** |
| 文本转录粘贴提交 | ✅ | ✅ | **完成** |
| whisper.cpp 本地 ASR 转写 | ✅ | N/A | **完成**tiny + base 模型) |
| AI 面试评估(四维评分) | ✅ | N/A | **完成** |
| 口语分析(填充词/语速) | ✅ | N/A | **完成** |
| 异步处理 + 状态轮询 | ✅ | ✅ | **完成** |
| 复盘历史列表/详情/删除 | ✅ | ✅ | **完成** |
| ASR mock 回落(whisper 不可用时) | ✅ | N/A | **完成** |
### 3.7 AI 择业顾问(新增)
| 功能 | 后端 | 前端 | 状态 |
|------|------|------|------|
| AI 专业/兴趣/性格分析 | ✅ | ✅ | **完成** |
| 智能岗位匹配推荐 | ✅ | ✅ | **完成** |
| 个性化职业发展建议 | ✅ | ✅ | **完成** |
| 多轮追问式对话 | ✅ | ✅ | **完成** |
| 热门岗位数据联动 | ✅ | N/A | **完成** |
| 个人中心入口(择业顾问) | N/A | ✅ | **完成** |
---
## 四、测试体系
@@ -151,6 +175,8 @@
| `progress` | controller + schema + benchmark service | ✅ | 打卡/积分/基准/匹配 |
| `contribution` | controller + schema (×2) | ✅ | 面经 + AI 结构化 + 公司题库 |
| `schedule` | module + service (×3) | ✅ | VIP 过期 / 每日一题 / 微信 token |
| `interview-review` | controller + service + schema + asr service | ✅ | 面试复盘:音频 ASR + AI 评析 + 口语分析 |
| `career-advice` | controller + service + module | ✅ | AI 择业顾问:专业分析 + 岗位匹配 + 多轮对话 |
| `admin` | controller + module | ✅ | 管理后台 |
| `email` | module + service | ✅ | 邮件发送 |
| `upload` | controller + module | ✅ | 文件上传 |
@@ -166,11 +192,13 @@
| 面试模拟 | interview/interview | ✅ 多轮对话 + 计时 |
| 面试报告 | report/report | ✅ 评分/分析/全文回放/分享卡片 |
| 历史记录 | history/history | ✅ 筛选/统计 |
| 个人中心 | user/user | ✅ 信息/统计/管理员入口 |
| 个人中心 | user/user | ✅ 信息/统计/管理员入口 + 面试复盘入口 + 择业顾问入口 |
| 会员中心 | member/member | ✅ 套餐对比 + 支付 |
| 进步轨迹 | progress/progress | ✅ 雷达图 + 打卡日历 |
| 面经贡献 | contribute/contribute | ✅ 表单提交 |
| 简历优化 | resume/resume | ✅ 诊断/优化/上传/下载 |
| 面试复盘 | review/review | ✅ 三种模式(列表/上传/报告) |
| 择业顾问 | career/career | ✅ AI 专业分析 + 岗位匹配 + 多轮对话 |
| 实习搜索 | internship/internship | ✅ 热门岗位 |
| 管理后台 | admin/admin | ✅ 仪表盘 |
| 关于/协议/隐私 | about/agreement/privacy | ✅ |
@@ -189,10 +217,12 @@
---
## 十、变更记录
| 2026-06-17 | v4.5 | AI 择业顾问 MVP:后端模块 + 前端职业分析页面 + 热门岗位联动 | AI |
| 日期 | 版本 | 变更内容 | 操作者 |
|------|------|----------|--------|
| 2026-06-02 | v1.0 | 项目状态初版 | AI |
| 2026-06-05 | v2.0 | 战略升级:文档重构 + 新增功能启动 | 小之 |
| 2026-06-09 | v4.2 | 冲刺版+每日推送+支付修复+全量代码评审 | AI |
| 2026-06-11 | **v4.3** | **安全修复 5 项 + 代码质量 14 处 + 测试体系 61 项 + 护城河 P0-P5 全部验证** | AI |
| 2026-06-11 | v4.3 | 安全修复 5 项 + 代码质量 14 处 + 测试体系 61 项 + 护城河 P0-P5 全部验证 | AI |
| 2026-06-16 | **v4.4** | **面试复盘功能上线:音频 ASRwhisper.cpp+ AI 评析 + 口语分析 + 前端三模式页面** | AI |
+39 -22
View File
@@ -1,8 +1,8 @@
# 职引 · 产品路线图 v4.1
# 职引 · 产品路线图 v4.3
> **版本**: v4.1
> **日期**: 2026-06-09
> **状态**: Phase 0.5 壁垒构建完成,待上线
> **版本**: v4.3
> **日期**: 2026-06-17
> **状态**: Phase 1.5 启动:AI 择业顾问 MVP
> **定位**: 应届生/实习生 AI 面试教练
---
@@ -14,13 +14,13 @@ Phase 0: 战略升级(✅ 已完成)
Phase 0.5: 壁垒构建(✅ 已完成)
Phase 1: MVP 上线(D7-14)→ 小程序审核 + 内测 + 支付生产
Phase 1: MVP 开发(✅ 已完成)→ 面试复盘 + whisper.cpp ASR 集成
Phase 1.5: 辅助功能 + 商业化(D14-30)→ PMF 验证
Phase 1.5: 商业化(D30-60)→ PMF 验证
Phase 2: 增强 + 题库(D30-60)→ 秋招准备
Phase 2: 增强 + 题库(D60-90)→ 秋招准备
Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
Phase 3: 商业化 + B 端(D90+)→ 秋招爆发
```
---
@@ -60,38 +60,51 @@ Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
---
## 四、Phase 1MVP 上线(D7-14,当前阶段
## 四、Phase 1MVP 开发(✅ 已完成,2026-06-16
### 4.1 上线准备
### 4.1 面试复盘功能
| 任务 | 描述 | 状态 |
|------|------|------|
| 前端页面完善 | 16 个页面全部就绪 | ✅ 完成 |
| 音频文件上传 | 支持 MP3/M4A/WAV 等格式,50MB 上限 | ✅ 完成 |
| 文本转录提交 | 直接粘贴面试文本 | ✅ 完成 |
| whisper.cpp 本地 ASR | 离线语音转文字,tiny + base 模型 | ✅ 完成 |
| AI 面试评析 | 四维评分 + 逐题评估 | ✅ 完成 |
| 口语分析 | 填充词检测 + 语速评估 | ✅ 完成 |
| 前端三模式页面 | 列表/上传/报告三种视图 | ✅ 完成 |
| 个人中心入口 | "面试复盘"菜单项 | ✅ 完成 |
### 4.2 上线准备
| 任务 | 描述 | 状态 |
|------|------|------|
| 前端页面完善 | 17 个页面全部就绪 | ✅ 完成 |
| 微信登录联调 | 真实 appid 验证 | ⏳ 待进行 |
| 移除开发绕过 | `member/pay` 直接激活 | ⏳ 待进行 |
| 生产环境部署 | 服务器 + MongoDB + Nginx + PM2 | ✅ 服务器已购,域名已配zhiyinwx → API:3006zhiyin.yzrcloud → H5 静态目录) |
| 生产环境部署 | 服务器 + MongoDB + Nginx + PM2 | ✅ 服务器已购,域名已配 |
| 小程序审核提交 | 资质齐全 | ⏳ 待进行 |
| 内测版发布 | 邀请码方式,100 人内测 | ⏳ 待进行 |
### 4.2 内测指标
### 4.3 内测指标
- **关键指标**: 次日留存 > 30%7 日留存 > 15%
- **反馈收集**: 问卷 + 访谈
- **如果达标**: 继续 Phase 1.5
---
## 五、Phase 1.5:辅助功能 + 商业化(D14-30
## 五、Phase 1.5:辅助功能 + 商业化(D30-60
| 功能 | 描述 | 优先级 |
|------|------|--------|
| 每日一题定时推送 | 微信订阅消息推送 | P0 |
| 冲刺版 ¥49.9/月 | 高客单价 | P1 |
| 连续打卡激励 | 7 天解锁高级报告 | P1 |
| ASR 生产化调优 | 多模型切换、模型量化、推理优化 | P1 |
| AI 择业顾问 MVP | AI 专业分析 + 岗位匹配 + 多轮对话 | P0 |
| 付费转化验证 | 100 内测用户 → 10+ 付费 | P0 |
| PMF 决策 | 转化率 > 5% → 继续 | P0 |
---
## 六、Phase 2:增强 + 真题库(D30-60,秋招前)
## 六、Phase 2:增强 + 真题库(D60-90,秋招前)
### 6.1 真题库建设
| 公司 | 题库规模 | 状态 |
@@ -112,7 +125,7 @@ Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
---
## 七、Phase 3:商业化 + B 端(D60-90,秋招爆发)
## 七、Phase 3:商业化 + B 端(D90+,秋招爆发)
### 7.1 增长目标
- 付费用户突破 1000
@@ -140,10 +153,11 @@ Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
|--------|------|--------|----------|
| M0: 战略升级 | ✅ D1 | 文档 + 定价 | 已完成 |
| M0.5: 壁垒构建 | ✅ D7 | 进步轨迹 + 面经贡献 + 每日一题 | 功能可用 |
| M1: MVP 上线 | D14 | 小程序审核通过,内测启动 | 100 内测用户 |
| M2: PMF 验证 | D30 | 100 用户反馈 | 转化率 > 5% |
| M3: 付费上线 | D45 | 冲刺版 + 定时推送 | 50+ 付费用户 |
| M4: 秋招冲刺 | D90 | 秋招推广 | 1000+ 付费用户 |
| M1: MVP 开发 | D14 | 面试复盘 + whisper.cpp ASR | 功能可用,build + test 通过 |
| M2: 上线内测 | D30 | 小程序审核通过,内测启动 | 100 内测用户 |
| M3: PMF 验证 | D60 | 100 用户反馈 | 转化率 > 5% |
| M4: 付费上线 | D75 | 冲刺版 + 定时推送 | 50+ 付费用户 |
| M5: 秋招冲刺 | D90+ | 秋招推广 | 1000+ 付费用户 |
---
@@ -157,8 +171,9 @@ Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
关键时间点:
6月9日:壁垒构建完成,Phase 0.5 交付
6月15日:MVP 上线,内测启动
7月1日:PMF 验证,付费转化
6月16日:面试复盘上线,MVP 开发完成
6月30日:MVP 上线,内测启动
7月15日:PMF 验证,付费转化
8月1日:Phase 2 完成,准备秋招
9月1日:秋招旺季,全力推广
```
@@ -185,3 +200,5 @@ Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
| 2026-06-01 | 重新规划:专注校招 | AI |
| 2026-06-05 | 战略升级:三层壁垒 + 新定价 | 小之 |
| 2026-06-09 | Phase 0.5 标记完成,调整后续里程碑时间 | AI |
| 2026-06-16 | **v4.2**Phase 1 MVP 开发完成,面试复盘上线,里程碑 M1 完成 | AI |
| 2026-06-17 | **v4.3**:AI 择业顾问 MVP 上线,里程碑 M1.5 完成 | AI |
+2 -2
View File
@@ -3,9 +3,9 @@
"version": "1.0.0",
"scripts": {
"dev:mp-weixin": "uni -p mp-weixin",
"build:mp-weixin": "uni build -p mp-weixin && cp -n static/avatar-*.png dist/build/mp-weixin/static/ 2>/dev/null; true",
"build:mp-weixin": "uni build -p mp-weixin && cp -f static/avatar-*.png dist/build/mp-weixin/static/ 2>/dev/null; true",
"dev:h5": "uni",
"build:h5": "uni build && cp -n static/avatar-*.png dist/build/h5/static/ 2>/dev/null; true",
"build:h5": "uni build && cp -f static/avatar-*.png dist/build/h5/static/ 2>/dev/null; true",
"test": "vitest run",
"test:watch": "vitest"
},
+28 -1
View File
@@ -1,7 +1,34 @@
<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
onLaunch(() => { console.log('职引 App launched') })
onLaunch(() => {
console.log('职引 App launched')
// #ifdef MP-WEIXIN
initPrivacy()
// #endif
})
// #ifdef MP-WEIXIN
function initPrivacy() {
if (wx.onNeedPrivacyAuthorization) {
wx.onNeedPrivacyAuthorization((resolve) => {
uni.showModal({
title: '隐私政策授权',
content: '请仔细阅读并同意《用户服务协议》和《隐私政策》后再使用本应用。您的个人信息将仅用于求职服务。',
confirmText: '同意',
cancelText: '拒绝',
success: (res) => {
if (res.confirm) {
resolve({ event: 'agree' })
} else {
resolve({ event: 'disagree' })
}
},
})
})
}
}
// #endif
onShow(() => { console.log('职引 App shown') })
onHide(() => { console.log('职引 App hidden') })
</script>
+25 -12
View File
@@ -23,6 +23,7 @@ export const APP_CONFIG = {
USER: '/pages/user/user',
LOGIN: '/pages/login/login',
ABOUT: '/pages/about/about',
CAREER: '/pages/career/career',
},
STORAGE_KEYS: {
TOKEN: 'token',
@@ -98,18 +99,30 @@ export const API_ENDPOINTS = {
CHECK: (outTradeNo: string) => `/payment/check/${outTradeNo}`,
ACTIVATE: '/payment/activate',
},
TTS: {
SYNTHESIZE: '/tts/synthesize',
AUDIO: (hash: string) => `/tts/audio/${hash}`,
ASR: '/tts/asr',
},
SHARE: {
CREATE: '/share/create',
STATS: '/share/stats',
RECORDS: '/share/records',
VISITORS: '/share/visitors',
},
} as const
TTS: {
SYNTHESIZE: '/tts/synthesize',
AUDIO: (hash: string) => `/tts/audio/${hash}`,
ASR: '/tts/asr',
},
SHARE: {
CREATE: '/share/create',
STATS: '/share/stats',
RECORDS: '/share/records',
VISITORS: '/share/visitors',
},
REVIEW: {
UPLOAD: '/interview-review',
TEXT: '/interview-review/text',
LIST: '/interview-review/list',
DETAIL: (id: string) => `/interview-review/${id}`,
DELETE: (id: string) => `/interview-review/${id}`,
},
CAREER: {
ANALYZE: '/career-advice/analyze',
CHAT: '/career-advice/chat',
POSITIONS: '/career-advice/positions',
},
} as const
const PROD_API_HOST = import.meta.env.VITE_PROD_API_HOST || 'https://zhiyinwx.yzrcloud.cn'
const DEV_API_HOST = 'http://localhost:3006'
+4 -3
View File
@@ -1,8 +1,8 @@
{
"name": "宇之然AI磁场",
"appid": "__UNI__DEV__",
"versionName": "1.0.11",
"versionCode": "111",
"versionName": "1.0.15",
"versionCode": "115",
"description": "职引 - 宇之然AI磁场旗下AI模拟面试平台,提供AI面试官模拟练习、简历智能优化、大厂面经题库,助你轻松应对校招面试。",
"h5": {
"title": "职引 - AI模拟面试 | 宇之然AI磁场",
@@ -13,7 +13,8 @@
"mp-weixin": {
"appid": "wxf466b3c3bc411ffc",
"setting": {
"urlCheck": false
"urlCheck": false,
"__usePrivacyCheck__": true
},
"usingComponents": true
}
+3 -1
View File
@@ -17,7 +17,9 @@
{ "path": "pages/result/result", "style": { "navigationBarTitleText": "优化结果" } },
{ "path": "pages/agreement/agreement", "style": { "navigationBarTitleText": "用户协议" } },
{ "path": "pages/privacy/privacy", "style": { "navigationBarTitleText": "隐私政策" } },
{ "path": "pages/share/share", "style": { "navigationBarTitleText": "我的分享" } }
{ "path": "pages/share/share", "style": { "navigationBarTitleText": "我的分享" } },
{ "path": "pages/review/review", "style": { "navigationBarTitleText": "面试复盘" } },
{ "path": "pages/career/career", "style": { "navigationBarTitleText": "择业顾问" } }
],
"tabBar": {
"color": "#999999",
+256 -17
View File
@@ -21,6 +21,7 @@
<text class="tab" :class="{ active: tab === 'orders' }" @click="switchTab('orders')">订单</text>
<text class="tab" :class="{ active: tab === 'pricing' }" @click="switchTab('pricing')">定价</text>
<text class="tab" :class="{ active: tab === 'share' }" @click="switchTab('share')">分享</text>
<text class="tab" :class="{ active: tab === 'positions' }" @click="switchTab('positions')">岗位</text>
<text class="tab" :class="{ active: tab === 'admins' }" @click="switchTab('admins')">管理</text>
</view>
@@ -64,14 +65,14 @@
<text class="user-name">{{ u.nickname || '--' }}</text>
</view>
<view class="user-badges">
<text class="user-plan" :class="{ vip: u.plan === 'growth' || u.plan === 'vip' }">{{ u.plan === 'growth' || u.plan === 'vip' ? '会员' : '免费' }}</text>
<text class="user-plan" :class="{ vip: u.plan === 'growth' || u.plan === 'sprint' }">{{ u.plan === 'growth' || u.plan === 'sprint' ? '会员' : '免费' }}</text>
<text class="user-credit">面试:{{ u.interviewCredits ?? 0 }}</text>
<text class="user-credit">优化:{{ u.resumeOptimizeCredits ?? 0 }}</text>
<text class="user-credit">下载:{{ u.resumeDownloadCredits ?? 0 }}</text>
<text class="user-credit share">分享:{{ u.shareCredits ?? 0 }}</text>
</view>
<view class="user-actions">
<text class="user-action-btn" v-if="u.plan !== 'growth' && u.plan !== 'vip'" @click="setVip(u._id)">设为会员</text>
<text class="user-action-btn" v-if="u.plan === 'free'" @click="setVip(u._id)">设为会员</text>
<text class="user-action-btn credit" @click="openCreditModal(u)">调整额度</text>
</view>
</view>
@@ -141,8 +142,10 @@
{{ o.status === 'success' ? '已支付' : o.status === 'refunded' ? '已退款' : '待支付' }}
</view>
<text class="order-time">{{ o.createdAt ? o.createdAt.slice(0,16).replace('T',' ') : '--' }}</text>
<view class="order-actions" v-if="o.status === 'pending'">
<text class="sync-btn" @click="syncOrder(o.outTradeNo)">同步</text>
<view class="order-actions">
<text class="sync-btn" v-if="o.status === 'pending'" @click="syncOrder(o.outTradeNo)">同步</text>
<text class="refund-btn" v-if="o.status === 'success'" @click="openRefundModal(o)">退款</text>
<text class="sync-btn" v-if="o.status === 'refunded'" @click="queryRefund(o.outTradeNo)">查询</text>
</view>
</view>
</view>
@@ -272,6 +275,31 @@
<text class="empty-text" v-if="!shareLoading && shareVisitors.length === 0">暂无访问记录</text>
</view>
</view>
<!-- 岗位管理 -->
<view v-if="tab === 'positions'" class="section">
<view class="search-bar">
<text class="section-label" style="flex:1;margin:0">岗位列表{{ positions.length }}</text>
<button class="search-btn" @click="openPositionModal(null)">新增岗位</button>
</view>
<view class="position-mgr-list" v-if="!posLoading">
<view class="pos-mgr-row" v-for="p in positions" :key="p._id">
<view class="pos-mgr-main">
<text class="pos-mgr-cat" :class="p.category === 'ai' ? 'cat-ai' : 'cat-tr'">{{ p.category === 'ai' ? 'AI' : '传统' }}</text>
<view class="pos-mgr-body">
<text class="pos-mgr-name">{{ p.name }}</text>
<text class="pos-mgr-meta">{{ p.company || '-' }} · {{ p.salary || '-' }} · sort:{{ p.sort }}</text>
</view>
</view>
<view class="pos-mgr-actions">
<text class="pos-mgr-btn edit" @click="openPositionModal(p)">编辑</text>
<text class="pos-mgr-btn del" @click="deletePosition(p._id, p.name)">删除</text>
</view>
</view>
<text class="empty-text" v-if="positions.length === 0 && !posLoading">暂无岗位</text>
</view>
<text class="loading-text" v-if="posLoading">加载中...</text>
</view>
<!-- 额度调整弹窗 -->
<view class="modal-mask" v-if="creditModal.show" @click="closeCreditModal">
<view class="modal-content" @click.stop>
@@ -286,6 +314,55 @@
</view>
</view>
</view>
<!-- 岗位编辑弹窗 -->
<view class="modal-mask" v-if="posModal.show" @click="closePositionModal">
<view class="modal-content" @click.stop>
<text class="modal-title">{{ posModal.isNew ? '新增岗位' : '编辑岗位' }}</text>
<view class="cfg-row"><text>岗位名称</text><input class="cfg-input" v-model="posForm.name" placeholder="必填" /></view>
<view class="cfg-row"><text>薪资</text><input class="cfg-input" v-model="posForm.salary" placeholder="如 15-25K" /></view>
<view class="cfg-row"><text>公司</text><input class="cfg-input" v-model="posForm.company" placeholder="如 字节跳动" /></view>
<view class="cfg-row"><text>排序</text><input class="cfg-input" type="digit" v-model.number="posForm.sort" /></view>
<view class="cfg-row"><text>分类</text>
<picker :range="['AI岗位','传统岗位']" @change="e => posForm.category = e.detail.value === 0 ? 'ai' : 'traditional'">
<text class="cfg-val">{{ posForm.category === 'ai' ? 'AI岗位' : '传统岗位' }}</text>
</picker>
</view>
<view class="cfg-row"><text>启用</text>
<picker :range="['启用','停用']" @change="e => posForm.active = e.detail.value === 0" :value="posForm.active ? 0 : 1">
<text class="cfg-val">{{ posForm.active ? '启用' : '停用' }}</text>
</picker>
</view>
<view class="modal-actions">
<button class="modal-btn cancel" @click="closePositionModal">取消</button>
<button class="modal-btn confirm" @click="savePosition">保存</button>
</view>
</view>
</view>
<!-- 退款弹窗 -->
<view class="modal-mask" v-if="refundModal.show" @click="closeRefundModal">
<view class="modal-content" @click.stop>
<text class="modal-title">退款 - {{ refundModal.order?.outTradeNo }}</text>
<view class="cfg-row">
<text>订单金额</text>
<text class="cfg-val">¥{{ ((refundModal.order?.amount || 0) / 100).toFixed(1) }}</text>
</view>
<view class="cfg-row">
<text>退款金额</text>
<input class="cfg-input" type="digit" v-model.number="refundAmount" :placeholder="((refundModal.order?.amount || 0) / 100).toFixed(1)" />
</view>
<view class="cfg-row">
<text>退款原因</text>
<input class="cfg-input" style="width:300rpx" v-model="refundReason" placeholder="选填" />
</view>
<view class="modal-actions">
<button class="modal-btn cancel" @click="closeRefundModal">取消</button>
<button class="modal-btn confirm" style="background:#EF4444" @click="doRefund">确认退款</button>
</view>
</view>
</view>
<!-- 管理员 -->
<view v-if="tab === 'admins'" class="section">
<view class="search-bar">
@@ -316,7 +393,7 @@
</template>
<script setup>
import { ref, computed } from 'vue'
import { ref, computed, onMounted, reactive } from 'vue'
import { api, API_ENDPOINTS } from '../../config'
const verified = ref(false)
@@ -339,7 +416,7 @@ const resumeLoading = ref(false)
const adminKeyword = ref('')
const adminList = ref([])
const searchResult = ref(null)
const memberConfig = ref({ interview: { maxRoundsFree: 5, maxRoundsVip: 10, dailyFreeLimit: 3 }, diagnosis: { dailyFreeLimit: 2 }, optimize: { dailyFreeLimit: 2 }, price: { monthly: 2900 } })
const memberConfig = ref({ interview: { maxRoundsFree: 5, maxRoundsVip: 10, dailyFreeLimit: 3 }, diagnosis: { dailyFreeLimit: 2 }, optimize: { dailyFreeLimit: 2 }, price: { monthly: 1990 } })
const cfgLoading = ref(false)
const pricing = ref({
interview: { pricePerSession: 500 },
@@ -356,11 +433,25 @@ const sprintPriceTemp = ref(49.9)
const growthFeaturesText = ref('')
const sprintFeaturesText = ref('')
// Position management
const positions = ref([])
const posLoading = ref(false)
const posModal = ref({ show: false, isNew: false })
const posForm = reactive({
name: '',
salary: '',
company: '',
icon: '',
sort: 0,
active: true,
category: 'ai',
})
const growthPriceDisplay = computed(() => growthPriceTemp.value.toFixed(1))
const sprintPriceDisplay = computed(() => sprintPriceTemp.value.toFixed(1))
const calcInterviewPrice = () => {
// Convert to 分 on save
// Handled in savePricing via growthPriceTemp / sprintPriceTemp
}
const orders = ref([])
const ordersTotal = ref(0)
@@ -382,6 +473,67 @@ const creditTypes = ref([
{ key: 'shareCredits', label: '分享积分', value: 0 },
])
// Refund modal
const refundModal = ref({ show: false, order: null })
const refundAmount = ref(0)
const refundReason = ref('')
const openRefundModal = (order) => {
refundModal.value = { show: true, order }
refundAmount.value = order.amount / 100
refundReason.value = ''
}
const closeRefundModal = () => {
refundModal.value = { show: false, order: null }
}
const doRefund = async () => {
const order = refundModal.value.order
if (!order) return
uni.showModal({
title: '确认退款', content: `确定对订单 ${order.outTradeNo} 退款 ¥${refundAmount.value.toFixed(1)}`,
success: async (r) => {
if (!r.confirm) return
try {
const res = await apiAdmin('/order/refund', {
method: 'POST',
body: { outTradeNo: order.outTradeNo, amount: Math.round(refundAmount.value * 100), reason: refundReason.value },
})
if (res.statusCode === 200) {
uni.showToast({ title: '退款成功', icon: 'success' })
closeRefundModal()
loadOrders()
} else {
uni.showToast({ title: res.data?.message || '退款失败', icon: 'none' })
}
} catch (e) {
uni.showToast({ title: '退款失败', icon: 'none' })
}
},
})
}
const queryRefund = async (outTradeNo) => {
uni.showToast({ title: '查询中...', icon: 'none' })
try {
const res = await apiAdmin('/order/refund/' + outTradeNo)
if (res.statusCode === 200) {
const wx = res.data.wxRefund
if (wx) {
uni.showModal({
title: '退款状态',
content: `微信状态: ${wx.status || '--'}\n退款金额: ¥${(wx.amount?.refund || 0) / 100}\n建议以微信侧为准`,
})
} else {
uni.showToast({ title: '本地状态: ' + (res.data.localStatus || '--'), icon: 'none' })
}
} else {
uni.showToast({ title: '查询失败', icon: 'none' })
}
} catch { uni.showToast({ title: '查询失败', icon: 'none' }) }
}
const token = () => uni.getStorageSync('token') || ''
const apiAdmin = (path, opts = {}) => {
@@ -399,7 +551,7 @@ const doVerify = async () => {
try {
const res = await apiAdmin('/check')
if (res.statusCode === 200 && res.data?.isAdmin) {
adminName.value = '管理员'
adminName.value = res.data.nickname || res.data.username || '管理员'
verified.value = true
loadOverview()
} else throw new Error('无管理员权限')
@@ -421,6 +573,7 @@ const switchTab = (t) => {
tab.value = t
if (t === 'users' && users.value.length === 0) loadUsers()
if (t === 'interviews' && interviews.value.length === 0) loadInterviews()
if (t === 'positions') loadPositions()
if (t === 'resumes' && resumes.value.length === 0) loadResumes()
if (t === 'admins' && adminList.value.length === 0) loadAdmins()
if (t === 'pricing') loadPricing()
@@ -500,15 +653,6 @@ const savePricing = async () => {
finally { pricingLoading.value = false }
}
const loadConfig = async () => {
cfgLoading.value = true
try {
const res = await apiAdmin('/config')
if (res.statusCode === 200) memberConfig.value = res.data
} catch(e) { console.error(e) }
finally { cfgLoading.value = false }
}
const loadOrders = async () => {
orderLoading.value = true
ordersPage.value = 1
@@ -549,6 +693,84 @@ const loadAdmins = async () => {
} catch(e) { console.error(e) }
}
// ─── 岗位管理 ──────────────────────
const apiPositions = (path, opts = {}) => {
return uni.request({
url: api('/positions' + path),
method: opts.method || 'POST',
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json', ...opts.headers },
data: opts.body || opts.data,
})
}
const loadPositions = async () => {
posLoading.value = true
try {
const res = await apiPositions('/admin/list')
if (res.statusCode === 200) positions.value = res.data || []
} catch (e) { console.error(e) }
finally { posLoading.value = false }
}
const openPositionModal = (position) => {
if (position) {
posForm.name = position.name || ''
posForm.salary = position.salary || ''
posForm.company = position.company || ''
posForm.icon = position.icon || ''
posForm.sort = position.sort ?? 0
posForm.active = position.active ?? true
posForm.category = position.category || 'traditional'
posModal.value = { show: true, isNew: false }
} else {
posForm.name = ''
posForm.salary = ''
posForm.company = ''
posForm.icon = ''
posForm.sort = positions.value.length + 1
posForm.active = true
posForm.category = 'ai'
posModal.value = { show: true, isNew: true }
}
}
const closePositionModal = () => {
posModal.value = { show: false, isNew: false }
}
const savePosition = async () => {
if (!posForm.name.trim()) {
uni.showToast({ title: '岗位名称不能为空', icon: 'none' })
return
}
try {
const res = await apiPositions('/admin/save', {
method: 'POST', body: { ...posForm },
})
if (res.statusCode === 200) {
uni.showToast({ title: '保存成功', icon: 'success' })
closePositionModal()
loadPositions()
} else throw new Error()
} catch { uni.showToast({ title: '保存失败', icon: 'none' }) }
}
const deletePosition = (id, name) => {
uni.showModal({
title: '删除岗位', content: `确定删除"${name}"`,
success: async (r) => {
if (!r.confirm) return
try {
const res = await apiPositions('/admin/' + id, { method: 'DELETE' })
if (res.statusCode === 200) {
uni.showToast({ title: '已删除', icon: 'success' })
loadPositions()
} else throw new Error()
} catch { uni.showToast({ title: '删除失败', icon: 'none' }) }
},
})
}
const searchAdmin = async () => {
if (!adminKeyword.value.trim()) return
try {
@@ -641,6 +863,8 @@ const doAdjustCredits = async () => {
loadUsers()
} catch { uni.showToast({ title: '调整失败', icon: 'none' }) }
}
onMounted(() => { doVerify() })
</script>
<style scoped>
@@ -722,6 +946,7 @@ const doAdjustCredits = async () => {
.order-time { font-size: 20rpx; color: var(--color-text-tertiary); flex: 1; text-align: right; }
.order-actions { }
.sync-btn { font-size: 20rpx; color: var(--color-primary); padding: 4rpx 12rpx; border: 2rpx solid var(--color-primary); border-radius: var(--radius-round); }
.refund-btn { font-size: 20rpx; color: #EF4444; padding: 4rpx 12rpx; border: 2rpx solid #EF4444; border-radius: var(--radius-round); }
.config-card { background: #FFF; border-radius: var(--radius-sm); padding: 20rpx; margin-bottom: 12rpx; }
.cfg-title { font-size: 24rpx; font-weight: 600; color: var(--color-text); margin-bottom: 12rpx; }
.cfg-row { display: flex; justify-content: space-between; padding: 8rpx 0; font-size: 22rpx; color: var(--color-text-secondary); align-items: center; }
@@ -749,4 +974,18 @@ const doAdjustCredits = async () => {
.modal-btn { flex: 1; height: 72rpx; border-radius: var(--radius-sm); font-size: 26rpx; border: none; }
.modal-btn.cancel { background: #F3F4F6; color: var(--color-text-secondary); }
.modal-btn.confirm { background: var(--color-primary); color: #FFF; }
/* ─── 岗位管理 ───── */
.position-mgr-list { display: flex; flex-direction: column; gap: 8rpx; }
.pos-mgr-row { background: #FFF; padding: 16rpx; border-radius: var(--radius-sm); display: flex; align-items: center; gap: 12rpx; }
.pos-mgr-main { flex: 1; display: flex; align-items: center; gap: 12rpx; }
.pos-mgr-cat { font-size: 18rpx; padding: 2rpx 12rpx; border-radius: var(--radius-round); font-weight: 600; }
.pos-mgr-cat.cat-ai { background: #EEF2FF; color: var(--color-primary); }
.pos-mgr-cat.cat-tr { background: #F3F4F6; color: var(--color-text-tertiary); }
.pos-mgr-body { display: flex; flex-direction: column; }
.pos-mgr-name { font-size: 24rpx; font-weight: 600; color: var(--color-text); }
.pos-mgr-meta { font-size: 20rpx; color: var(--color-text-tertiary); margin-top: 2rpx; }
.pos-mgr-actions { display: flex; gap: 8rpx; }
.pos-mgr-btn { font-size: 20rpx; padding: 4rpx 16rpx; border-radius: var(--radius-round); }
.pos-mgr-btn.edit { color: var(--color-primary); border: 2rpx solid var(--color-primary); }
.pos-mgr-btn.del { color: #EF4444; border: 2rpx solid #EF4444; }
</style>
+273
View File
@@ -0,0 +1,273 @@
<template>
<view class="page">
<!-- 输入表单 -->
<view v-if="step === 'input'" class="input-wrap">
<view class="hero">
<text class="hero-icon">🧭</text>
<text class="hero-title">择业顾问</text>
<text class="hero-desc">AI 帮你分析专业前景规划职业方向</text>
</view>
<view class="form-card">
<view class="form-group">
<text class="form-label">你的专业 <text class="required">*</text></text>
<input class="form-input" v-model="profile.major" placeholder="例如:计算机科学与技术" />
</view>
<view class="form-group">
<text class="form-label">年级</text>
<picker :range="grades" @change="e => profile.grade = grades[e.detail.value]">
<view class="form-input select-trigger">{{ profile.grade || '请选择年级' }}</view>
</picker>
</view>
<view class="form-group">
<text class="form-label">兴趣/擅长方向</text>
<input class="form-input" v-model="profile.interests" placeholder="例如:后端开发、数据分析" />
</view>
<view class="form-group">
<text class="form-label">成绩/GPA</text>
<input class="form-input" v-model="profile.gpa" placeholder="例如:3.5/4.0 或专业前 20%" />
</view>
<view class="form-group">
<text class="form-label">你的困惑或目标</text>
<textarea class="form-textarea" v-model="profile.goal" placeholder="例如:不知道该考研还是直接就业,对AI行业很感兴趣但不知道从何入手..." />
</view>
</view>
<button class="submit-btn" :disabled="!profile.major.trim() || loading" @click="doAnalyze">
<text v-if="!loading">开始分析</text>
<text v-else>AI 分析中...</text>
</button>
<text v-if="error" class="error-text">{{ error }}</text>
</view>
<!-- 分析结果 -->
<view v-if="step === 'result'" class="result-wrap">
<view class="result-header">
<text class="result-icon">📊</text>
<text class="result-title">择业分析报告</text>
</view>
<view class="advice-card">
<view class="advice-content">{{ result.reply }}</view>
</view>
<view v-if="result.careerPaths && result.careerPaths.length > 0" class="section">
<text class="section-title">推荐方向</text>
<view class="path-card" v-for="(path, i) in result.careerPaths" :key="i"
@click="goInterview(path.name)">
<view class="path-rank">{{ i + 1 }}</view>
<view class="path-body">
<text class="path-name">{{ path.name }}</text>
<text class="path-reason">{{ path.reason }}</text>
</view>
<view class="path-score-wrap">
<text class="path-score-label">匹配度</text>
<text class="path-score">{{ path.matchScore }}%</text>
<text v-if="path.salary" class="path-salary">{{ path.salary }}</text>
</view>
</view>
<view class="path-hint">点击卡片可进入该岗位的模拟面试</view>
</view>
<view class="action-bar">
<button class="action-btn chat-btn" @click="step = 'chat'; chatMsg = ''">继续咨询</button>
<button class="action-btn retry-btn" @click="step = 'input'; result = null">重新分析</button>
</view>
</view>
<!-- 继续对话 -->
<view v-if="step === 'chat'" class="chat-wrap">
<view class="chat-header">
<text class="chat-back" @click="step = 'result'"> 返回</text>
<text class="chat-title">继续咨询</text>
</view>
<scroll-view class="chat-msgs" scroll-y :scroll-into-view="'msg-' + (chatHistory.length - 1)">
<view v-for="(msg, i) in chatHistory" :key="i" :id="'msg-' + i"
:class="'msg-bubble ' + (msg.role === 'user' ? 'msg-user' : 'msg-ai')">
<text class="msg-text">{{ msg.content }}</text>
</view>
<view v-if="chatLoading" class="msg-bubble msg-ai">
<text class="msg-text typing">AI 思考中...</text>
</view>
</scroll-view>
<view class="chat-input-bar">
<input class="chat-input" v-model="chatMsg" placeholder="输入你的问题..." @confirm="doChat" />
<button class="chat-send" @click="doChat" :disabled="!chatMsg.trim() || chatLoading">发送</button>
</view>
</view>
</view>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { api } from '../../config'
const grades = ['大一', '大二', '大三', '大四', '研一', '研二', '研三', '已毕业']
const step = ref('input')
const loading = ref(false)
const chatLoading = ref(false)
const error = ref('')
const result = ref(null)
const chatMsg = ref('')
const chatHistory = ref([])
const profile = reactive({
major: '',
grade: '',
interests: '',
gpa: '',
goal: '',
})
const token = ref('')
onShow(() => {
token.value = uni.getStorageSync('token') || ''
if (!token.value) {
uni.showModal({
title: '请先登录',
content: '需要登录后才能使用择业顾问功能',
confirmText: '去登录',
success: (r) => { if (r.confirm) uni.navigateTo({ url: '/pages/login/login' }) },
})
}
})
const doAnalyze = async () => {
if (!profile.major.trim()) {
error.value = '请填写你的专业'
return
}
loading.value = true
error.value = ''
try {
const res = await uni.request({
url: api('/career-advice/analyze'),
method: 'POST',
data: { ...profile },
header: { 'Authorization': `Bearer ${token.value}`, 'Content-Type': 'application/json' },
})
if (res.statusCode === 200) {
if (res.data.error) {
error.value = res.data.error
return
}
result.value = res.data
step.value = 'result'
chatHistory.value = [
{ role: 'user', content: `我是${profile.major}专业${profile.grade ? '的' + profile.grade : ''}学生,想了解职业发展方向` },
{ role: 'assistant', content: res.data.reply },
]
} else {
error.value = (res.data && res.data.message) || '分析失败,请稍后重试'
}
} catch (e) {
error.value = '网络错误,请检查网络连接'
} finally {
loading.value = false
}
}
const doChat = async () => {
if (!chatMsg.value.trim() || chatLoading.value) return
const msg = chatMsg.value.trim()
chatMsg.value = ''
chatHistory.value.push({ role: 'user', content: msg })
chatLoading.value = true
try {
const res = await uni.request({
url: api('/career-advice/chat'),
method: 'POST',
data: { message: msg, history: chatHistory.value.slice(0, -1) },
header: { 'Authorization': `Bearer ${token.value}`, 'Content-Type': 'application/json' },
})
if (res.statusCode === 200) {
chatHistory.value.push({ role: 'assistant', content: res.data.reply || (res.data.error || '') })
} else {
chatHistory.value.push({ role: 'assistant', content: '回复失败,请稍后重试' })
}
} catch {
chatHistory.value.push({ role: 'assistant', content: '网络错误,请检查网络连接' })
} finally {
chatLoading.value = false
}
}
const goInterview = (position) => {
uni.navigateTo({ url: `/pages/interview/interview?position=${encodeURIComponent(position)}` })
}
</script>
<style scoped>
.page { min-height: 100vh; background: var(--color-bg); padding-bottom: 40rpx; }
/* ===== Input ===== */
.input-wrap { padding: 0 32rpx; }
.hero { display: flex; flex-direction: column; align-items: center; padding: 48rpx 0 32rpx; }
.hero-icon { font-size: 72rpx; }
.hero-title { font-size: 40rpx; font-weight: 700; color: var(--color-text); margin-top: 16rpx; }
.hero-desc { font-size: 26rpx; color: var(--color-secondary); margin-top: 8rpx; }
.form-card { background: #fff; border-radius: var(--radius-lg); padding: 32rpx; box-shadow: var(--shadow-sm); }
.form-group { margin-bottom: 28rpx; }
.form-group:last-child { margin-bottom: 0; }
.form-label { font-size: 26rpx; font-weight: 600; color: var(--color-text); display: block; margin-bottom: 12rpx; }
.required { color: var(--color-error); }
.form-input { width: 100%; height: 80rpx; border: 2rpx solid var(--color-border); border-radius: var(--radius-md); padding: 0 24rpx; font-size: 26rpx; color: var(--color-text); box-sizing: border-box; background: #FAFBFC; }
.select-trigger { display: flex; align-items: center; }
.form-textarea { width: 100%; height: 160rpx; border: 2rpx solid var(--color-border); border-radius: var(--radius-md); padding: 20rpx 24rpx; font-size: 26rpx; color: var(--color-text); box-sizing: border-box; background: #FAFBFC; resize: none; }
.submit-btn { width: 100%; height: 88rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #fff; font-size: 30rpx; font-weight: 600; border-radius: var(--radius-lg); margin-top: 32rpx; display: flex; align-items: center; justify-content: center; border: none; }
.submit-btn:active { transform: scale(0.98); opacity: 0.9; }
.submit-btn[disabled] { opacity: 0.5; }
.error-text { display: block; text-align: center; color: var(--color-error); font-size: 24rpx; margin-top: 16rpx; }
/* ===== Result ===== */
.result-wrap { padding: 0 32rpx; }
.result-header { display: flex; flex-direction: column; align-items: center; padding: 32rpx 0; }
.result-icon { font-size: 56rpx; }
.result-title { font-size: 34rpx; font-weight: 700; color: var(--color-text); margin-top: 12rpx; }
.advice-card { background: linear-gradient(135deg, #EEF2FF 0%, #E0E7FF 100%); border-radius: var(--radius-lg); padding: 32rpx; margin-bottom: 24rpx; }
.advice-content { font-size: 26rpx; color: #374151; line-height: 1.8; white-space: pre-wrap; }
.section { margin-bottom: 24rpx; }
.section-title { font-size: 30rpx; font-weight: 700; color: var(--color-text); display: block; margin-bottom: 16rpx; }
.path-card { display: flex; align-items: center; background: #fff; border-radius: var(--radius-lg); padding: 24rpx; margin-bottom: 16rpx; box-shadow: var(--shadow-sm); }
.path-card:active { transform: scale(0.98); background: #F9FAFB; }
.path-rank { width: 48rpx; height: 48rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #fff; font-size: 24rpx; font-weight: 700; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; margin-right: 16rpx; }
.path-body { flex: 1; }
.path-name { font-size: 28rpx; font-weight: 600; color: var(--color-text); display: block; }
.path-reason { font-size: 22rpx; color: var(--color-secondary); margin-top: 4rpx; display: block; line-height: 1.4; }
.path-score-wrap { display: flex; flex-direction: column; align-items: center; margin-left: 12rpx; flex-shrink: 0; }
.path-score-label { font-size: 20rpx; color: var(--color-secondary); }
.path-score { font-size: 32rpx; font-weight: 700; color: var(--color-primary); }
.path-salary { font-size: 20rpx; color: var(--color-success); margin-top: 2rpx; }
.path-hint { font-size: 22rpx; color: var(--color-secondary); text-align: center; margin-top: -8rpx; margin-bottom: 16rpx; }
.action-bar { display: flex; gap: 16rpx; }
.action-btn { flex: 1; height: 80rpx; font-size: 28rpx; font-weight: 600; border-radius: var(--radius-md); display: flex; align-items: center; justify-content: center; }
.chat-btn { background: var(--color-primary); color: #fff; }
.retry-btn { background: #fff; color: var(--color-text); border: 2rpx solid var(--color-border); }
/* ===== Chat ===== */
.chat-wrap { display: flex; flex-direction: column; height: 100vh; }
.chat-header { display: flex; align-items: center; padding: 24rpx 32rpx; background: #fff; border-bottom: 1rpx solid var(--color-border); }
.chat-back { font-size: 28rpx; color: var(--color-primary); margin-right: 24rpx; }
.chat-title { font-size: 30rpx; font-weight: 700; color: var(--color-text); flex: 1; }
.chat-msgs { flex: 1; padding: 24rpx 32rpx; overflow-y: auto; }
.msg-bubble { max-width: 80%; margin-bottom: 20rpx; padding: 20rpx 24rpx; border-radius: var(--radius-md); font-size: 26rpx; line-height: 1.6; }
.msg-user { background: var(--color-primary); color: #fff; align-self: flex-end; margin-left: auto; border-radius: var(--radius-md) var(--radius-md) 4rpx var(--radius-md); }
.msg-ai { background: #fff; color: var(--color-text); box-shadow: var(--shadow-sm); border-radius: var(--radius-md) var(--radius-md) var(--radius-md) 4rpx; }
.typing { color: var(--color-secondary); }
.chat-input-bar { display: flex; align-items: center; padding: 16rpx 32rpx; background: #fff; border-top: 1rpx solid var(--color-border); gap: 16rpx; }
.chat-input { flex: 1; height: 72rpx; border: 2rpx solid var(--color-border); border-radius: 36rpx; padding: 0 24rpx; font-size: 26rpx; }
.chat-send { height: 72rpx; padding: 0 32rpx; background: var(--color-primary); color: #fff; font-size: 26rpx; font-weight: 600; border-radius: 36rpx; display: flex; align-items: center; justify-content: center; }
.chat-send[disabled] { opacity: 0.5; }
</style>
+216 -154
View File
@@ -1,197 +1,259 @@
<template>
<view class="page">
<view class="page fade-in">
<!-- 搜索栏 -->
<view class="search-bar">
<input class="search-input" v-model="keyword" placeholder="搜索公司名称..." @confirm="searchCompany" />
<view class="search-inner">
<text class="search-icon">🔍</text>
<input class="search-input" v-model="keyword" placeholder="搜索公司名称..." @confirm="searchCompany" />
<text class="search-clear" v-if="keyword" @tap="keyword = ''"></text>
</view>
<button class="search-btn" @tap="searchCompany">搜索</button>
</view>
<!-- 热门公司 -->
<view class="section" v-if="!searching">
<view class="section-title">热门公司题库</view>
<view class="company-grid">
<view
class="company-card"
v-for="c in hotCompanies"
:key="c.name"
@tap="selectCompany(c.name)"
>
<view class="company-name">{{ c.name }}</view>
<view class="company-count">{{ c.positions }} 个岗位</view>
<view class="section" v-if="!selectedCompany">
<view class="section-header">
<text class="section-title">🏢 热门公司题库</text>
</view>
<view class="loading-bar" v-if="loading">
<view class="loading-text">加载中...</view>
</view>
<view class="company-grid" v-else-if="hotCompanies.length > 0">
<view class="company-card card" v-for="c in hotCompanies" :key="c.name" @tap="selectCompany(c.name)">
<text class="company-name">{{ c.name }}</text>
<text class="company-count">{{ c.positionCount > 0 ? c.positionCount + ' 个岗位' : '暂无题库' }}</text>
</view>
</view>
<view class="empty" v-else>
<text class="empty-icon">📭</text>
<text class="empty-text">暂无公司题库数据</text>
<text class="empty-hint">完成面试后贡献面经帮助更多人</text>
</view>
</view>
<!-- 搜索结果岗位列表 -->
<view class="section" v-if="selectedCompany && !loadingPositions">
<view class="section-title-row">
<text class="section-title">{{ selectedCompany }} - 岗位列表</text>
<text class="back-link" @tap="selectedCompany = ''">返回</text>
<!-- 岗位列表 -->
<view class="section" v-if="selectedCompany">
<view class="section-header">
<view class="section-header-left">
<text class="section-back" @tap="backToCompanies"> 返回</text>
<text class="section-title">{{ selectedCompany }}</text>
</view>
</view>
<view class="position-list">
<view
class="position-item"
v-for="p in positions"
:key="p.position"
@tap="selectPosition(p.position)"
>
<view class="position-name">{{ p.position }}</view>
<view class="position-meta">{{ p.questionCount }} · {{ p.contributionCount }} 人贡献</view>
</view>
<view class="empty-state" v-if="positions.length === 0">
<text>暂无该公司的面经数据</text>
<text class="sub-text">成为第一个贡献者吧</text>
<view class="loading-bar" v-if="loadingPositions">
<view class="loading-text">加载岗位中...</view>
</view>
<view class="position-list" v-else-if="positions.length > 0">
<view class="pos-item card" v-for="p in positions" :key="p.position" @tap="selectPosition(p.position)">
<view class="pos-left">
<text class="pos-icon">{{ p.icon || '💼' }}</text>
<view class="pos-body">
<text class="pos-name">{{ p.position }}</text>
<text class="pos-meta">{{ p.questionCount }} · {{ p.contributionCount }} 人贡献</text>
</view>
</view>
<text class="pos-arrow"></text>
</view>
</view>
<view class="empty" v-else>
<text class="empty-icon">📭</text>
<text class="empty-text">暂无该公司的面经数据</text>
<text class="empty-hint">成为第一个贡献者吧</text>
</view>
</view>
<!-- 题目列表 -->
<view class="section" v-if="selectedPosition && !loadingQuestions">
<view class="section-title-row">
<text class="section-title">{{ selectedCompany }} · {{ selectedPosition }}</text>
<text class="back-link" @tap="selectedPosition = ''">返回</text>
<view class="section" v-if="selectedPosition">
<view class="section-header">
<view class="section-header-left">
<text class="section-back" @tap="selectedPosition = ''"> 返回</text>
<text class="section-title">{{ selectedPosition }}</text>
</view>
</view>
<view class="question-list">
<view class="question-item" v-for="(q, i) in questions" :key="i">
<view class="loading-bar" v-if="loadingQuestions">
<view class="loading-text">加载题目中...</view>
</view>
<view class="question-list" v-else-if="questions.length > 0">
<view class="question-item card" v-for="(q, i) in questions" :key="i">
<view class="q-header">
<text class="q-num">#{{ i + 1 }}</text>
<text class="q-tag">{{ q.type === 'technical' ? '技术' : '行为' }}</text>
<text class="q-diff">{{ difficultyLabel(q.difficulty) }}</text>
<text class="q-tag" :class="'q-tag-' + (q.type === 'technical' ? 'tech' : 'behavior')">{{ q.type === 'technical' ? '技术' : '行为' }}</text>
<text class="q-diff" :class="'q-diff-' + (q.difficulty || 'medium')">{{ difficultyLabel(q.difficulty) }}</text>
<text class="q-freq">{{ q.frequency }} 次提及</text>
</view>
<view class="q-content">{{ q.content }}</view>
<text class="q-content">{{ q.content }}</text>
<view class="q-tags" v-if="q.tags && q.tags.length">
<text class="tag" v-for="t in q.tags" :key="t">{{ t }}</text>
</view>
<view class="q-answer" v-if="q.referenceAnswer">
<text class="answer-label">参考思路</text>
<text class="answer-label">💡 参考思路</text>
<text class="answer-text">{{ q.referenceAnswer }}</text>
</view>
</view>
<view class="empty-state" v-if="questions.length === 0">
<text>暂无题目数据</text>
</view>
</view>
</view>
<!-- 加载态 -->
<view class="loading" v-if="loadingPositions || loadingQuestions">
<text>加载中...</text>
<view class="empty" v-else>
<text class="empty-icon">📭</text>
<text class="empty-text">暂无题目数据</text>
</view>
</view>
</view>
</template>
<script>
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../../config'
const HOT_COMPANIES = [
{ name: '腾讯', positions: 5 },
{ name: '字节跳动', positions: 4 },
{ name: '阿里巴巴', positions: 5 },
{ name: '美团', positions: 3 },
{ name: '百度', positions: 4 },
{ name: '京东', positions: 3 },
{ name: '网易', positions: 3 },
{ name: '小红书', positions: 2 },
]
const keyword = ref('')
const hotCompanies = ref([])
const selectedCompany = ref('')
const selectedPosition = ref('')
const positions = ref([])
const questions = ref([])
const loading = ref(true)
const loadingPositions = ref(false)
const loadingQuestions = ref(false)
export default {
data() {
return {
keyword: '',
searching: false,
hotCompanies: HOT_COMPANIES,
selectedCompany: '',
selectedPosition: '',
positions: [],
questions: [],
loadingPositions: false,
loadingQuestions: false,
}
},
methods: {
difficultyLabel(d) {
const map = { junior: '简单', medium: '中等', senior: '困难' }
return map[d] || d || '中等'
},
async searchCompany() {
const kw = this.keyword.trim()
if (!kw) return
this.selectedCompany = kw
this.selectedPosition = ''
await this.loadPositions(kw)
},
async selectCompany(name) {
this.selectedCompany = name
this.keyword = name
this.selectedPosition = ''
await this.loadPositions(name)
},
async loadPositions(company) {
this.loadingPositions = true
const token = uni.getStorageSync('token') || ''
const header = token ? { 'Authorization': `Bearer ${token}` } : {}
try {
const res = await uni.request({ url: api(`/contribution/company/${encodeURIComponent(company)}`), method: 'GET', header })
this.positions = res.data || []
} catch (e) {
this.positions = []
}
this.loadingPositions = false
},
async selectPosition(position) {
this.selectedPosition = position
await this.loadQuestions(this.selectedCompany, position)
},
async loadQuestions(company, position) {
this.loadingQuestions = true
const token = uni.getStorageSync('token') || ''
const header = token ? { 'Authorization': `Bearer ${token}` } : {}
try {
const res = await uni.request({
url: api(`/contribution/company/${encodeURIComponent(company)}/position/${encodeURIComponent(position)}`),
method: 'GET',
header,
})
this.questions = res.data?.questions || []
} catch (e) {
this.questions = []
}
this.loadingQuestions = false
},
},
onMounted(() => { loadHotCompanies() })
async function loadHotCompanies() {
loading.value = true
try {
const token = uni.getStorageSync('token') || ''
const header = token ? { 'Authorization': `Bearer ${token}` } : {}
const res = await uni.request({ url: api('/contribution/companies/hot'), method: 'GET', header })
if (res.statusCode === 200) hotCompanies.value = res.data || []
} catch (e) { console.error(e) }
finally { loading.value = false }
}
function difficultyLabel(d) {
const map = { junior: '简单', medium: '中等', senior: '困难' }
return map[d] || d || '中等'
}
function searchCompany() {
const kw = keyword.value.trim()
if (!kw) return
selectedCompany.value = kw
selectedPosition.value = ''
loadPositions(kw)
}
function selectCompany(name) {
selectedCompany.value = name
keyword.value = name
selectedPosition.value = ''
loadPositions(name)
}
function backToCompanies() {
selectedCompany.value = ''
selectedPosition.value = ''
}
async function loadPositions(company) {
loadingPositions.value = true
const token = uni.getStorageSync('token') || ''
const header = token ? { 'Authorization': `Bearer ${token}` } : {}
try {
const res = await uni.request({ url: api(`/contribution/company/${encodeURIComponent(company)}`), method: 'GET', header })
positions.value = res.data || []
} catch (e) { positions.value = [] }
finally { loadingPositions.value = false }
}
function selectPosition(position) {
selectedPosition.value = position
loadQuestions(selectedCompany.value, position)
}
async function loadQuestions(company, position) {
loadingQuestions.value = true
const token = uni.getStorageSync('token') || ''
const header = token ? { 'Authorization': `Bearer ${token}` } : {}
try {
const res = await uni.request({
url: api(`/contribution/company/${encodeURIComponent(company)}/position/${encodeURIComponent(position)}`),
method: 'GET', header,
})
questions.value = res.data?.questions || []
} catch (e) { questions.value = [] }
finally { loadingQuestions.value = false }
}
</script>
<style scoped>
.page { padding: 20rpx; min-height: 100vh; background: #f5f6f7; }
.search-bar { display: flex; gap: 20rpx; margin-bottom: 30rpx; }
.search-input { flex: 1; height: 80rpx; background: #fff; border-radius: 40rpx; padding: 0 30rpx; font-size: 28rpx; }
.search-btn { height: 80rpx; line-height: 80rpx; padding: 0 40rpx; background: #4F46E5; color: #fff; border-radius: 40rpx; font-size: 28rpx; }
.section { margin-bottom: 30rpx; background: #fff; border-radius: 16rpx; padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: 600; margin-bottom: 20rpx; display: block; }
.section-title-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20rpx; }
.back-link { color: #4F46E5; font-size: 26rpx; }
.company-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20rpx; }
.company-card { background: #F3F0FF; border-radius: 12rpx; padding: 24rpx; text-align: center; }
.company-name { font-size: 28rpx; font-weight: 500; color: #333; }
.company-count { font-size: 22rpx; color: #999; margin-top: 8rpx; }
.position-item { padding: 24rpx; border-bottom: 1rpx solid #f0f0f0; }
.position-name { font-size: 28rpx; font-weight: 500; color: #333; }
.position-meta { font-size: 24rpx; color: #999; margin-top: 8rpx; }
.question-item { padding: 24rpx; border-bottom: 1rpx solid #f0f0f0; }
.q-header { display: flex; align-items: center; gap: 12rpx; margin-bottom: 12rpx; }
.q-num { font-size: 24rpx; color: #4F46E5; font-weight: 600; }
.q-tag { font-size: 22rpx; background: #E8F5E9; color: #2E7D32; padding: 2rpx 12rpx; border-radius: 6rpx; }
.q-diff { font-size: 22rpx; background: #FFF3E0; color: #E65100; padding: 2rpx 12rpx; border-radius: 6rpx; }
.q-freq { font-size: 22rpx; color: #999; margin-left: auto; }
.q-content { font-size: 28rpx; color: #333; line-height: 1.6; }
.page { min-height: 100vh; background: var(--color-bg); padding: 20rpx 32rpx 40rpx; }
/* 搜索 */
.search-bar { display: flex; gap: 16rpx; margin-bottom: 24rpx; padding-top: 16rpx; }
.search-inner {
flex: 1; height: 76rpx; background: var(--color-surface); border-radius: var(--radius-round);
display: flex; align-items: center; padding: 0 24rpx; gap: 12rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
}
.search-icon { font-size: 26rpx; }
.search-input { flex: 1; font-size: 26rpx; color: var(--color-text); height: 100%; }
.search-clear { font-size: 28rpx; color: var(--color-text-tertiary); padding: 8rpx; }
.search-btn {
height: 76rpx; line-height: 76rpx; padding: 0 36rpx; background: var(--color-primary);
color: #fff; border-radius: var(--radius-round); font-size: 26rpx; font-weight: 600; flex-shrink: 0;
}
/* 区块 */
.section { margin-bottom: 24rpx; }
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16rpx; }
.section-header-left { display: flex; align-items: center; gap: 16rpx; }
.section-back { font-size: 28rpx; color: var(--color-primary); font-weight: 500; padding: 8rpx 0; }
.section-title { font-size: 30rpx; font-weight: 700; color: var(--color-text); }
/* 公司网格 */
.company-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16rpx; }
.company-card {
padding: 24rpx; border-radius: var(--radius-lg); text-align: center;
background: linear-gradient(135deg, #EEF2FF, #E0E7FF);
}
.company-card:active { opacity: 0.7; }
.company-name { font-size: 28rpx; font-weight: 600; color: var(--color-text); display: block; }
.company-count { font-size: 20rpx; color: var(--color-text-secondary); margin-top: 8rpx; display: block; }
/* 岗位列表 */
.position-list { display: flex; flex-direction: column; gap: 16rpx; }
.pos-item { padding: 24rpx 28rpx; border-radius: var(--radius-lg); display: flex; align-items: center; justify-content: space-between; }
.pos-item:active { transform: scale(0.98); }
.pos-left { display: flex; align-items: center; gap: 16rpx; flex: 1; min-width: 0; }
.pos-icon { font-size: 36rpx; }
.pos-body { flex: 1; min-width: 0; }
.pos-name { font-size: 28rpx; font-weight: 600; color: var(--color-text); }
.pos-meta { font-size: 22rpx; color: var(--color-text-secondary); margin-top: 4rpx; display: block; }
.pos-arrow { font-size: 32rpx; color: var(--color-text-tertiary); flex-shrink: 0; margin-left: 12rpx; }
/* 题目列表 */
.question-list { display: flex; flex-direction: column; gap: 16rpx; }
.question-item { padding: 24rpx; border-radius: var(--radius-lg); }
.q-header { display: flex; align-items: center; gap: 12rpx; margin-bottom: 12rpx; flex-wrap: wrap; }
.q-num { font-size: 22rpx; color: var(--color-primary); font-weight: 700; }
.q-tag { font-size: 20rpx; padding: 2rpx 14rpx; border-radius: var(--radius-round); font-weight: 500; }
.q-tag-tech { background: #DCFCE7; color: #166534; }
.q-tag-behavior { background: #FEF3C7; color: #92400E; }
.q-diff { font-size: 20rpx; padding: 2rpx 14rpx; border-radius: var(--radius-round); font-weight: 500; }
.q-diff-junior { background: #EEF2FF; color: var(--color-primary); }
.q-diff-medium { background: #FEF3C7; color: #92400E; }
.q-diff-senior { background: #FEE2E2; color: #991B1B; }
.q-freq { font-size: 20rpx; color: var(--color-text-tertiary); margin-left: auto; }
.q-content { font-size: 28rpx; color: var(--color-text); line-height: 1.7; }
.q-tags { display: flex; flex-wrap: wrap; gap: 8rpx; margin-top: 12rpx; }
.tag { font-size: 22rpx; background: #F3F0FF; color: #4F46E5; padding: 4rpx 16rpx; border-radius: 20rpx; }
.q-answer { margin-top: 16rpx; padding: 16rpx; background: #F8F9FA; border-radius: 8rpx; }
.answer-label { font-size: 24rpx; color: #4F46E5; font-weight: 500; }
.answer-text { font-size: 26rpx; color: #555; line-height: 1.6; }
.empty-state { text-align: center; padding: 60rpx 0; color: #999; font-size: 28rpx; }
.sub-text { display: block; margin-top: 12rpx; font-size: 24rpx; color: #bbb; }
.loading { text-align: center; padding: 60rpx; color: #999; }
.q-tags .tag { font-size: 20rpx; background: #F3F0FF; color: var(--color-primary); padding: 4rpx 16rpx; border-radius: var(--radius-round); }
.q-answer { margin-top: 16rpx; padding: 20rpx; background: #F9FAFB; border-radius: var(--radius-md); }
.answer-label { font-size: 22rpx; color: var(--color-primary); font-weight: 600; display: block; margin-bottom: 8rpx; }
.answer-text { font-size: 24rpx; color: var(--color-text-secondary); line-height: 1.6; }
/* 空状态 */
.empty { text-align: center; padding: 60rpx 0; background: var(--color-surface); border-radius: var(--radius-lg); }
.empty-icon { font-size: 48rpx; display: block; margin-bottom: 12rpx; }
.empty-text { font-size: 28rpx; color: var(--color-text-secondary); display: block; }
.empty-hint { font-size: 22rpx; color: var(--color-text-tertiary); margin-top: 8rpx; display: block; }
/* 加载 */
.loading-bar { text-align: center; padding: 40rpx; background: var(--color-surface); border-radius: var(--radius-lg); }
.loading-text { font-size: 24rpx; color: var(--color-text-tertiary); }
</style>
+13 -5
View File
@@ -75,10 +75,12 @@
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { api } from '../../config'
const props = defineProps({ interviewId: String, position: String })
const interviewId = ref('')
const urlPosition = ref('')
const form = ref({ company: '', position: '', rounds: '', experience: '', tags: [] })
const questionsText = ref('')
const customTag = ref('')
@@ -89,8 +91,14 @@ const presetTags = ['算法题多', '重视项目经历', '面试官nice', '压
const token = () => uni.getStorageSync('token') || ''
onMounted(() => {
if (props.position) form.value.position = props.position
onLoad((options) => {
if (options?.position) {
urlPosition.value = decodeURIComponent(options.position)
form.value.position = urlPosition.value
}
if (options?.interviewId) {
interviewId.value = options.interviewId
}
})
const toggleTag = (tag) => {
@@ -122,7 +130,7 @@ const submit = async () => {
url: api('/contribution'), method: 'POST',
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
data: {
interviewId: props.interviewId || '',
interviewId: interviewId.value || '',
company: form.value.company.trim(),
position: form.value.position.trim(),
rounds: form.value.rounds.trim(),
+1
View File
@@ -54,6 +54,7 @@
<text class="empty-title">{{ emptyTitle }}</text>
<text class="empty-desc">{{ emptyDesc }}</text>
<button class="empty-btn btn-gradient" @click="goInterview" v-if="filter === 'all'">开始第一次面试</button>
<button class="empty-btn" @click="goReviewRecording" style="margin-top:12rpx;background:#FFF;color:#4F46E5;border:2rpx solid #4F46E5;border-radius:var(--radius-round);padding:18rpx 48rpx;font-size:26rpx">🎙 录音复盘</button>
</view>
</view>
</template>
+143 -48
View File
@@ -4,7 +4,7 @@
<view class="hero-row">
<view class="hero-left">
<text class="hero-title">{{ greeting }}</text>
<text class="hero-sub">试试下面的功能开启你的求职练习</text>
<text class="hero-sub">{{ userInfo ? '试试下面的功能开启你的求职练习' : '登录后免费使用 AI 模拟面试 · 简历优化 · 面经题库' }}</text>
</view>
<view class="hero-right">
<view class="user-card card" v-if="userInfo" @click="goProfile">
@@ -13,7 +13,7 @@
<text class="user-name">{{ userInfo.nickname || '同学' }}</text>
<view class="user-tags">
<text class="tag tag-plan">{{ userInfo.plan || '免费版' }}</text>
<text class="tag tag-remaining">剩余 {{ userInfo.remaining || 0 }} </text>
<text class="tag tag-remaining">{{ userInfo.interviewCredits > 0 ? '剩余 ' + userInfo.interviewCredits + ' 次' : '已用完' }}</text>
</view>
</view>
<text class="arrow"></text>
@@ -21,10 +21,13 @@
<view class="guest-card card" v-else @click="goLogin">
<image class="avatar" src="/static/avatar-default.png" mode="aspectFill" />
<view class="user-meta">
<text class="user-name">立即登录</text>
<text class="guest-hint">登录后体验全部功能</text>
<text class="user-name">登录 / 注册</text>
<view class="guest-benefits">
<text class="guest-benefit">🎙 模拟面试</text>
<text class="guest-benefit">📄 简历优化</text>
</view>
</view>
<text class="arrow"></text>
<text class="guest-arrow"></text>
</view>
</view>
</view>
@@ -43,7 +46,14 @@
</view>
<text class="fp-action">开始</text>
</view>
<view class="feature-tertiary">
<view class="feature-grid">
<view class="fs-card card" @click="goCareer">
<view class="fs-top">
<view class="fs-icon fs-career"><text class="fs-emoji">🎯</text></view>
<text class="fs-name">AI 择业顾问</text>
</view>
<text class="fs-brief">专业分析 · 岗位匹配 · 智能推荐</text>
</view>
<view class="fs-card card" @click="goResume">
<view class="fs-top">
<view class="fs-icon fs-resume"><text class="fs-emoji">📄</text></view>
@@ -65,33 +75,18 @@
</view>
<text class="fs-brief">分享经验 · 共建题库 · 帮更多人</text>
</view>
</view>
<view class="feature-secondary">
<view class="fs-card card" @click="goBank">
<view class="fs-top">
<view class="fs-icon fs-progress"><text class="fs-emoji">📚</text></view>
<text class="fs-name">公司真题库</text>
</view>
<text class="fs-brief">大厂真题 · 岗位分类 · 参考思路</text>
</view>
<view class="fs-card card" @click="goInternship">
<view class="fs-top">
<view class="fs-icon fs-contribute"><text class="fs-emoji">🔍</text></view>
<text class="fs-name">实习搜索</text>
</view>
<text class="fs-brief">热门实习 · 一键搜索 · 精准匹配</text>
</view>
<!-- 公司真题库&实习搜索 - 暂隐藏内容待丰富 -->
</view>
</view>
</view>
<!-- 每日一题 -->
<view class="section" v-if="dailyQuestion">
<view class="section">
<view class="section-header">
<text class="section-title">📮 每日一题</text>
<text class="section-desc" @click="refreshDaily">换一题</text>
<text class="section-desc" @click="refreshDaily" v-if="dailyQuestion">换一题</text>
</view>
<view class="daily-card card">
<view class="daily-card card" v-if="dailyQuestion">
<text class="daily-tag">{{ dailyQuestion.category || '综合' }}</text>
<text class="daily-question">{{ dailyQuestion.question }}</text>
<view class="daily-answer" v-if="showAnswer">
@@ -105,26 +100,66 @@
<text class="daily-action primary" @click="goInterview">模拟练习 </text>
</view>
</view>
<view class="daily-guest card" v-else-if="!userInfo" @click="goLogin">
<view class="daily-guest-top">
<text class="daily-guest-icon">🔒</text>
<view class="daily-guest-body">
<text class="daily-guest-title">登录后获取今日面试题</text>
<text class="daily-guest-desc">每日一道校招真题持续积累面试经验</text>
</view>
</view>
<text class="daily-action primary">立即登录 </text>
</view>
</view>
<!-- 热门岗位 -->
<!-- 热门岗位 - AI 专区 -->
<view class="section">
<view class="section-header">
<view class="section-title-row">
<text class="section-title">热门岗位</text>
<text class="section-tag-demo">参考示例</text>
<text class="section-title">🔥 AI 热门岗位</text>
<text class="section-badge">NEW</text>
</view>
<text class="section-desc">点击直接面试</text>
<text class="section-desc">AI 时代最热方向点击直接面试</text>
</view>
<view class="position-list card" v-if="!positionsLoading">
<view class="pos-item" v-for="(pos, idx) in hotPositions" :key="idx" @click="startInterview(pos)">
<view class="ai-banner card" @click="goInterview">
<text class="ai-banner-title">🚀 AI 正在重塑整个行业</text>
<text class="ai-banner-desc">大模型应用 / Agent 开发 / Prompt 工程 顶尖人才缺口巨大现在上车正当时</text>
</view>
<view class="position-list card" v-if="!positionsLoading && aiPositions.length > 0">
<view class="pos-item" v-for="(pos, idx) in aiPositions" :key="'ai-' + idx" @click="startInterview(pos)">
<view class="pos-left">
<text class="pos-icon">{{ posIcons[idx] || '💼' }}</text>
<text class="pos-icon pos-icon-ai">{{ pos.icon || posIcons[idx % posIcons.length] || '🤖' }}</text>
<view class="pos-body">
<text class="pos-name">{{ pos.name }}</text>
<view class="pos-meta-row">
<text class="pos-company">{{ pos.company || '参考公司' }}</text>
<text class="pos-salary">{{ pos.salary || '参考薪资' }}</text>
<view class="pos-meta-row" v-if="pos.company || pos.salary">
<text class="pos-company">{{ pos.company }}</text>
<text class="pos-salary">{{ pos.salary }}</text>
</view>
</view>
</view>
<view class="pos-action">
<text class="pos-action-text pos-action-ai">立即模拟</text>
</view>
</view>
</view>
<!-- 更多岗位 -->
<view class="more-header" @click="showMore = !showMore">
<view class="more-header-left">
<text class="more-icon">🧑💻</text>
<text class="more-title">更多岗位{{ traditionalPositions.length }}</text>
</view>
<text class="more-arrow">{{ showMore ? '收起 ▲' : '展开 ▼' }}</text>
</view>
<view class="position-list card" v-if="showMore && !positionsLoading && traditionalPositions.length > 0">
<view class="pos-item" v-for="(pos, idx) in traditionalPositions" :key="'tr-' + idx" @click="startInterview(pos)">
<view class="pos-left">
<text class="pos-icon">{{ pos.icon || posIcons[(aiPositions.length + idx) % posIcons.length] || '💼' }}</text>
<view class="pos-body">
<text class="pos-name">{{ pos.name }}</text>
<view class="pos-meta-row" v-if="pos.company || pos.salary">
<text class="pos-company">{{ pos.company }}</text>
<text class="pos-salary">{{ pos.salary }}</text>
</view>
</view>
</view>
@@ -141,7 +176,7 @@
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { api } from '../../config'
@@ -152,6 +187,10 @@ const posIcons = ['💻', '⚙️', '🤖', '📊', '🎨', '🧪', '📱', '
const positionsLoading = ref(true)
const dailyQuestion = ref(null)
const showAnswer = ref(false)
const showMore = ref(false)
const aiPositions = computed(() => hotPositions.value.filter(p => p.category === 'ai'))
const traditionalPositions = computed(() => hotPositions.value.filter(p => p.category !== 'ai'))
const loadUserInfo = () => {
try { const s = uni.getStorageSync('userInfo'); if (s) userInfo.value = JSON.parse(s); else userInfo.value = null } catch (e) { userInfo.value = null }
@@ -190,7 +229,19 @@ onMounted(async () => {
onShow(loadUserInfo)
const refreshDaily = () => { showAnswer.value = false; /* trigger reload */ }
const refreshDaily = async () => {
showAnswer.value = false
try {
const t = uni.getStorageSync('token')
if (t) {
const qres = await uni.request({
url: api('/daily-question'), method: 'GET',
header: { 'Authorization': `Bearer ${t}` }
})
if (qres.statusCode === 200 && qres.data) dailyQuestion.value = qres.data
}
} catch (e) { /* silent */ }
}
const goProfile = () => uni.switchTab({ url: '/pages/user/user' })
const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
@@ -200,6 +251,7 @@ const goProgress = () => uni.navigateTo({ url: '/pages/progress/progress' })
const goContribute = () => uni.navigateTo({ url: '/pages/contribute/contribute' })
const goBank = () => uni.navigateTo({ url: '/pages/company-bank/bank' })
const goInternship = () => uni.navigateTo({ url: '/pages/internship/internship' })
const goCareer = () => uni.navigateTo({ url: '/pages/career/career' })
const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/interview?position=${encodeURIComponent(pos.name)}` })
</script>
@@ -213,7 +265,7 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
}
.hero-row { display: flex; align-items: flex-start; gap: 24rpx; }
.hero-left { flex: 1; min-width: 0; padding-top: 8rpx; }
.hero-right { flex-shrink: 0; width: 320rpx; }
.hero-right { flex-shrink: 0; min-width: 280rpx; max-width: 340rpx; }
.hero-title { font-size: 40rpx; font-weight: 700; color: #FFF; display: block; line-height: 1.3; }
.hero-sub { font-size: 22rpx; color: rgba(255,255,255,0.7); margin-top: 8rpx; display: block; }
@@ -223,11 +275,15 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
display: flex; align-items: center;
box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.1);
}
.guest-card { background: rgba(255,255,255,0.15); backdrop-filter: blur(10rpx); }
.guest-card .avatar { border-color: rgba(255,255,255,0.3); }
.guest-card .user-name { font-size: 26rpx; color: #FFF; }
.guest-hint { font-size: 20rpx; color: rgba(255,255,255,0.6); margin-top: 4rpx; display: block; }
.guest-card .arrow { color: rgba(255,255,255,0.4); }
.guest-card {
background: rgba(255,255,255,0.2); backdrop-filter: blur(12rpx);
border: 1rpx solid rgba(255,255,255,0.25);
}
.guest-card .avatar { border-color: rgba(255,255,255,0.35); }
.guest-card .user-name { font-size: 26rpx; color: #FFF; font-weight: 700; }
.guest-benefits { display: flex; gap: 12rpx; margin-top: 6rpx; flex-wrap: wrap; }
.guest-benefit { font-size: 18rpx; color: rgba(255,255,255,0.8); padding: 2rpx 10rpx; background: rgba(255,255,255,0.12); border-radius: 8rpx; }
.guest-arrow { font-size: 36rpx; color: rgba(255,255,255,0.5); margin-left: 12rpx; }
.avatar { width: 72rpx; height: 72rpx; border-radius: 50%; margin-right: 16rpx; border: 3rpx solid var(--color-primary-light); flex-shrink: 0; }
.user-meta { flex: 1; min-width: 0; }
.user-name { font-size: 30rpx; font-weight: 600; color: var(--color-text); }
@@ -242,7 +298,7 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20rpx; }
.section-title { font-size: 30rpx; font-weight: 700; color: var(--color-text); }
.section-title-row { display: flex; align-items: center; gap: 12rpx; }
.section-tag-demo { font-size: 18rpx; color: #9CA3AF; background: #F3F4F6; padding: 2rpx 10rpx; border-radius: 6rpx; }
.section-badge { font-size: 18rpx; color: #fff; background: var(--color-primary); padding: 2rpx 12rpx; border-radius: 20rpx; font-weight: 500; }
.section-desc { font-size: 22rpx; color: var(--color-primary); }
.feature-list { display: flex; flex-direction: column; gap: 16rpx; }
@@ -259,17 +315,19 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
.fp-name { font-size: 30rpx; font-weight: 700; color: var(--color-text); }
.fp-brief { font-size: 20rpx; color: var(--color-text-secondary); margin-top: 4rpx; display: block; }
.fp-action { font-size: 28rpx; color: var(--color-primary); font-weight: 600; flex-shrink: 0; }
.feature-secondary { display: grid; grid-template-columns: 1fr 1fr; gap: 16rpx; }
.feature-tertiary { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16rpx; }
.feature-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16rpx; }
.fs-card { padding: 20rpx; border-radius: var(--radius-lg); }
.fs-top { display: flex; align-items: center; gap: 10rpx; }
.fs-icon { width: 44rpx; height: 44rpx; border-radius: 12rpx; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.fs-emoji { font-size: 20rpx; }
.fs-name { font-size: 26rpx; font-weight: 600; color: var(--color-text); }
.fs-brief { font-size: 18rpx; color: var(--color-text-secondary); margin-top: 10rpx; display: block; }
.fs-progress { background: linear-gradient(135deg, #EEF2FF, #C7D2FE); }
.fs-career { background: linear-gradient(135deg, #F3E8FF, #D8B4FE); }
.fs-resume { background: linear-gradient(135deg, #ECFDF5, #A7F3D0); }
.fs-progress { background: linear-gradient(135deg, #EEF2FF, #C7D2FE); }
.fs-contribute { background: linear-gradient(135deg, #FFF7ED, #FDBA74); }
.fs-bank { background: linear-gradient(135deg, #FCE7F3, #F9A8D4); }
.fs-internship { background: linear-gradient(135deg, #E0F2FE, #7DD3FC); }
/* 每日一题 */
.daily-card { padding: 24rpx; border-radius: var(--radius-lg); }
@@ -282,12 +340,36 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
.daily-action { font-size: 24rpx; color: var(--color-text-secondary); }
.daily-action.primary { color: var(--color-primary); font-weight: 600; }
.daily-guest {
padding: 24rpx; border-radius: var(--radius-lg);
background: linear-gradient(135deg, #EEF2FF, #E0E7FF);
display: flex; align-items: center; justify-content: space-between;
cursor: pointer;
}
.daily-guest:active { opacity: 0.8; }
.daily-guest-top { display: flex; align-items: center; gap: 16rpx; flex: 1; min-width: 0; }
.daily-guest-icon { font-size: 32rpx; width: 56rpx; height: 56rpx; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.6); border-radius: 14rpx; flex-shrink: 0; }
.daily-guest-body { flex: 1; min-width: 0; }
.daily-guest-title { font-size: 26rpx; font-weight: 600; color: var(--color-text); }
.daily-guest-desc { font-size: 20rpx; color: var(--color-text-secondary); margin-top: 4rpx; display: block; }
/* AI 岗位专区 */
.ai-banner {
background: linear-gradient(135deg, #FEF3C7, #FDE68A);
padding: 20rpx 24rpx; border-radius: var(--radius-lg); margin-bottom: 16rpx;
cursor: pointer;
}
.ai-banner:active { transform: scale(0.98); }
.ai-banner-title { font-size: 26rpx; font-weight: 700; color: #92400E; display: block; margin-bottom: 6rpx; }
.ai-banner-desc { font-size: 20rpx; color: #A16207; line-height: 1.5; display: block; }
.position-list { border-radius: var(--radius-lg); overflow: hidden; }
.pos-item { padding: 24rpx 28rpx; border-bottom: 1rpx solid var(--color-border); display: flex; justify-content: space-between; align-items: center; }
.pos-item:last-child { border-bottom: none; }
.pos-item:active { background: var(--color-bg); }
.pos-left { display: flex; align-items: center; gap: 16rpx; flex: 1; min-width: 0; }
.pos-icon { font-size: 36rpx; width: 56rpx; height: 56rpx; display: flex; align-items: center; justify-content: center; background: #F3F4F6; border-radius: 14rpx; flex-shrink: 0; }
.pos-icon-ai { background: #FEF3C7; }
.pos-body { display: flex; flex-direction: column; flex: 1; min-width: 0; }
.pos-name { font-size: 28rpx; font-weight: 600; color: var(--color-text); }
.pos-meta-row { display: flex; align-items: center; gap: 10rpx; margin-top: 4rpx; }
@@ -295,6 +377,19 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
.pos-salary { font-size: 20rpx; color: var(--color-primary); background: #EEF2FF; padding: 2rpx 10rpx; border-radius: 6rpx; }
.pos-action { flex-shrink: 0; margin-left: 16rpx; }
.pos-action-text { font-size: 22rpx; color: var(--color-primary); font-weight: 600; }
.pos-action-ai { color: #D97706; }
/* 更多岗位折叠 */
.more-header {
display: flex; justify-content: space-between; align-items: center;
padding: 20rpx 4rpx; margin-top: 8rpx; cursor: pointer;
}
.more-header:active { opacity: 0.7; }
.more-header-left { display: flex; align-items: center; gap: 10rpx; }
.more-icon { font-size: 28rpx; }
.more-title { font-size: 26rpx; font-weight: 600; color: var(--color-text-secondary); }
.more-arrow { font-size: 22rpx; color: var(--color-primary); font-weight: 500; }
.loading-tip { text-align: center; padding: 40rpx; font-size: 24rpx; color: var(--color-text-tertiary); background: #FFF; border-radius: var(--radius-lg); }
.bottom-spacer { height: 40rpx; }
</style>
</style>
+126 -36
View File
@@ -1,67 +1,157 @@
<template>
<view class="page">
<view class="hero">
<text class="hero-title">实习推荐</text>
<text class="hero-sub">热门实习岗位点击直接模拟面试</text>
<view class="page fade-in">
<!-- 搜索栏 -->
<view class="search-bar">
<view class="search-inner">
<text class="search-icon">🔍</text>
<input class="search-input" v-model="keyword" placeholder="搜索岗位或公司..." @input="onSearch" />
<text class="search-clear" v-if="keyword" @tap="keyword = ''; onSearch()"></text>
</view>
</view>
<view class="body">
<view class="section-title">🔥 热门实习</view>
<view class="position-list card">
<view class="pos-item" v-for="(item, idx) in positions" :key="idx" @click="startInterview(item)">
<view class="pos-left">
<view class="pos-rank">{{ idx + 1 }}</view>
<view class="pos-body">
<text class="pos-name">{{ item.name }}</text>
<!-- 分类标签 -->
<view class="tabs">
<view class="tab" :class="tab === 'all' && 'tab-active'" @tap="tab = 'all'; tabIndex = 0">
<text class="tab-text">全部</text>
</view>
<view class="tab" :class="tab === 'ai' && 'tab-active'" @tap="tab = 'ai'; tabIndex = 1">
<text class="tab-text">🤖 AI 岗位</text>
</view>
<view class="tab" :class="tab === 'traditional' && 'tab-active'" @tap="tab = 'traditional'; tabIndex = 2">
<text class="tab-text">💼 传统岗位</text>
</view>
</view>
<!-- 结果计数 -->
<view class="result-info" v-if="!loading">
<text class="result-count"> {{ filteredPositions.length }} 个岗位</text>
</view>
<!-- 岗位列表 -->
<view class="position-list">
<view class="pos-item card" v-for="(item, idx) in filteredPositions" :key="idx" @click="startInterview(item)">
<view class="pos-left">
<view class="pos-icon-wrap">
<text class="pos-icon">{{ item.icon || '💼' }}</text>
</view>
<view class="pos-body">
<text class="pos-name">{{ item.name }}</text>
<view class="pos-meta-row" v-if="item.company">
<text class="pos-company">{{ item.company }}</text>
<text class="pos-badge" :class="item.category === 'ai' ? 'badge-ai' : 'badge-traditional'">{{ item.category === 'ai' ? 'AI' : '传统' }}</text>
</view>
</view>
<text class="pos-salary">{{ item.salary }}</text>
</view>
<view class="pos-right">
<text class="pos-salary" v-if="item.salary">{{ item.salary }}</text>
<text class="pos-action">模拟 </text>
</view>
</view>
</view>
<view class="empty" v-if="!loading && positions.length === 0">
<text class="empty-text">暂无实习岗位数据</text>
</view>
<!-- 空状态 -->
<view class="empty" v-if="!loading && filteredPositions.length === 0">
<text class="empty-icon">🔍</text>
<text class="empty-text">{{ keyword ? '没有匹配的岗位' : '暂无岗位数据' }}</text>
</view>
<!-- 加载 -->
<view class="loading-bar" v-if="loading">
<text class="loading-text">加载中...</text>
</view>
</view>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ref, computed, onMounted } from 'vue'
import { api } from '../../config'
const keyword = ref('')
const tab = ref('all')
const tabIndex = ref(0)
const positions = ref([])
const loading = ref(true)
const filteredPositions = computed(() => {
let list = positions.value
if (tab.value !== 'all') {
list = list.filter(p => p.category === tab.value)
}
if (keyword.value.trim()) {
const kw = keyword.value.trim().toLowerCase()
list = list.filter(p => (p.name && p.name.toLowerCase().includes(kw)) || (p.company && p.company.toLowerCase().includes(kw)))
}
return list
})
onMounted(async () => {
try {
const res = await uni.request({ url: api('/positions/hot'), method: 'GET' })
if (res.statusCode === 200) positions.value = res.data || []
} catch(e) { console.error(e) }
} catch (e) { console.error(e) }
finally { loading.value = false }
})
function onSearch() { /* reactivity handles filtering via computed */ }
const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/interview?position=${encodeURIComponent(pos.name)}` })
</script>
<style scoped>
.page { min-height: 100vh; background: var(--color-bg); }
.hero { background: linear-gradient(135deg, var(--color-gradient-start) 0%, var(--color-gradient-mid) 50%, var(--color-gradient-end) 100%); padding: 48rpx 32rpx 72rpx; border-radius: 0 0 48rpx 48rpx; }
.hero-title { font-size: 40rpx; font-weight: 700; color: #FFFFFF; display: block; }
.hero-sub { font-size: 22rpx; color: rgba(255,255,255,0.7); margin-top: 8rpx; display: block; }
.body { padding: 32rpx; margin-top: -40rpx; }
.section-title { font-size: 28rpx; font-weight: 600; color: var(--color-text); margin-bottom: 16rpx; }
.position-list { border-radius: var(--radius-lg); overflow: hidden; }
.pos-item { padding: 24rpx 28rpx; border-bottom: 1rpx solid var(--color-border); display: flex; justify-content: space-between; align-items: center; }
.pos-item:active { background: #F9FAFB; }
.pos-item:last-child { border-bottom: none; }
.pos-left { display: flex; align-items: center; gap: 16rpx; }
.pos-rank { width: 40rpx; height: 40rpx; border-radius: 10rpx; background: #F3F4F6; display: flex; align-items: center; justify-content: center; font-size: 22rpx; font-weight: 700; color: var(--color-primary); flex-shrink: 0; }
.pos-body { display: flex; flex-direction: column; }
.pos-name { font-size: 28rpx; font-weight: 600; color: var(--color-text); }
.pos-company { font-size: 22rpx; color: var(--color-text-tertiary); margin-top: 4rpx; }
.pos-salary { font-size: 24rpx; color: var(--color-primary); font-weight: 600; }
.empty { display: flex; justify-content: center; padding: 60rpx 0; }
.empty-text { font-size: 26rpx; color: var(--color-text-tertiary); }
.page { min-height: 100vh; background: var(--color-bg); padding: 20rpx 32rpx 40rpx; }
/* 搜索 */
.search-bar { padding-top: 16rpx; margin-bottom: 20rpx; }
.search-inner {
height: 76rpx; background: var(--color-surface); border-radius: var(--radius-round);
display: flex; align-items: center; padding: 0 24rpx; gap: 12rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
}
.search-icon { font-size: 26rpx; }
.search-input { flex: 1; font-size: 26rpx; color: var(--color-text); height: 100%; }
.search-clear { font-size: 28rpx; color: var(--color-text-tertiary); padding: 8rpx; }
/* 分类标签 */
.tabs { display: flex; gap: 12rpx; margin-bottom: 16rpx; }
.tab {
padding: 12rpx 24rpx; border-radius: var(--radius-round); background: var(--color-surface);
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
}
.tab-active { background: var(--color-primary); }
.tab-active .tab-text { color: #fff; }
.tab-text { font-size: 24rpx; color: var(--color-text-secondary); font-weight: 500; }
/* 结果信息 */
.result-info { margin-bottom: 16rpx; }
.result-count { font-size: 22rpx; color: var(--color-text-tertiary); }
/* 岗位列表 */
.position-list { display: flex; flex-direction: column; gap: 16rpx; }
.pos-item {
padding: 24rpx 28rpx; border-radius: var(--radius-lg);
display: flex; align-items: center; justify-content: space-between;
}
.pos-item:active { transform: scale(0.98); }
.pos-left { display: flex; align-items: center; gap: 16rpx; flex: 1; min-width: 0; }
.pos-icon-wrap { width: 56rpx; height: 56rpx; background: #F3F4F6; border-radius: 14rpx; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.pos-icon { font-size: 28rpx; }
.pos-body { flex: 1; min-width: 0; }
.pos-name { font-size: 28rpx; font-weight: 600; color: var(--color-text); display: block; }
.pos-meta-row { display: flex; align-items: center; gap: 10rpx; margin-top: 6rpx; }
.pos-company { font-size: 22rpx; color: var(--color-text-tertiary); }
.pos-badge { font-size: 18rpx; padding: 2rpx 12rpx; border-radius: var(--radius-round); font-weight: 500; }
.badge-ai { background: #FEF3C7; color: #92400E; }
.badge-traditional { background: #EEF2FF; color: var(--color-primary); }
.pos-right { text-align: right; flex-shrink: 0; margin-left: 16rpx; }
.pos-salary { font-size: 24rpx; color: var(--color-primary); font-weight: 600; display: block; margin-bottom: 4rpx; }
.pos-action { font-size: 22rpx; color: var(--color-text-tertiary); }
/* 空状态 */
.empty { text-align: center; padding: 80rpx 0; }
.empty-icon { font-size: 56rpx; display: block; margin-bottom: 16rpx; }
.empty-text { font-size: 28rpx; color: var(--color-text-secondary); }
/* 加载 */
.loading-bar { text-align: center; padding: 60rpx; }
.loading-text { font-size: 24rpx; color: var(--color-text-tertiary); }
</style>
+33 -15
View File
@@ -100,12 +100,13 @@ let recorder = null
let timerSeconds = 0
let timerInterval = null
const progressPercent = computed(() => Math.min((answeredCount.value / 5) * 100, 100))
let MAX_QUESTIONS = 10
const progressPercent = computed(() => Math.min((answeredCount.value / MAX_QUESTIONS) * 100, 100))
const formatTime = computed(() => {
const m = Math.floor(timerSeconds / 60); const s = timerSeconds % 60
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
})
const token = computed(() => uni.getStorageSync('token') || '')
const token = () => uni.getStorageSync('token') || ''
onLoad((options) => {
if (options?.position) {
@@ -117,7 +118,7 @@ onLoad((options) => {
onMounted(() => {
timerInterval = setInterval(() => timerSeconds++, 1000)
if (token.value) startInterview()
if (token()) startInterview()
})
onBeforeUnmount(() => {
@@ -125,7 +126,7 @@ onBeforeUnmount(() => {
})
const checkLogin = () => {
if (!token.value) {
if (!token()) {
uni.showModal({
title: '请先登录', content: '登录后即可开始 AI 模拟面试', confirmText: '去登录',
success: (r) => { if (r.confirm) uni.navigateTo({ url: '/pages/login/login' }) },
@@ -141,18 +142,22 @@ const startInterview = async () => {
try {
const res = await uni.request({
url: api('/interview/create'), method: 'POST',
header: { 'Authorization': `Bearer ${token.value}`, 'Content-Type': 'application/json' },
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
data: { position: position.value },
})
if (res.statusCode === 200 && res.data) {
interviewId.value = res.data.id
messages.value = res.data.messages || messages.value
answeredCount.value = res.data.questionCount || 0
if (res.data.totalQuestions) MAX_QUESTIONS = res.data.totalQuestions
// Speak first question in avatar mode
if (avatarMode.value && res.data.messages?.length) {
const last = res.data.messages[res.data.messages.length - 1]
if (last?.role === 'ai') await speakAiText(last.content)
}
} else {
const msg = res.data?.message || '创建面试失败'
messages.value.push({ role: 'ai', content: msg })
}
} catch {
messages.value.push({ role: 'ai', content: '创建面试失败,请重试' })
@@ -164,8 +169,11 @@ const startInterview = async () => {
const sendAnswer = async () => {
if (!inputText.value.trim() || aiLoading.value || isComplete.value) return
if (!token.value) { checkLogin(); return }
if (!interviewId.value) { await startInterview(); return }
if (!token()) { checkLogin(); return }
if (!interviewId.value) {
await startInterview()
if (!interviewId.value) return // creation failed, don't discard answer
}
const answer = inputText.value.trim()
messages.value.push({ role: 'user', content: answer })
@@ -176,19 +184,24 @@ const sendAnswer = async () => {
try {
const res = await uni.request({
url: api(`/interview/${interviewId.value}/answer`), method: 'POST',
header: { 'Authorization': `Bearer ${token.value}`, 'Content-Type': 'application/json' },
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
data: avatarMode.value ? { answer, avatar: true } : { answer },
})
if (res.statusCode === 200 && res.data?.messages) {
const aiMsg = res.data.messages.find(m => m.role === 'ai')
messages.value.push(...res.data.messages)
if (avatarMode.value && aiMsg) {
// Only push AI messages from response to avoid duplicating the user message already added above
const newAiMessages = res.data.messages.filter(m => m.role === 'ai')
if (newAiMessages.length > 0) messages.value.push(...newAiMessages)
if (avatarMode.value && aiMsg) {
await speakAiText(aiMsg.content, res.data.ttsHash, res.data.ttsAmplitude)
}
answeredCount.value = res.data.questionCount || answeredCount.value + 1
if (res.data.ttsHash && !avatarMode.value) {
// Still got TTS but not in avatar mode, just show text
}
if (res.data.totalQuestions) MAX_QUESTIONS = res.data.totalQuestions
} else if (res.statusCode === 403) {
messages.value.push({ role: 'ai', content: res.data?.message || '面试次数已用完' })
isComplete.value = true
} else {
messages.value.push({ role: 'ai', content: res.data?.message || '回答提交失败' })
}
} catch {
messages.value.push({ role: 'ai', content: '回答提交失败,请重试' })
@@ -207,7 +220,7 @@ async function speakAiText(text, ttsHash, ttsAmplitude) {
try {
const synthRes = await uni.request({
url: api('/tts/synthesize'), method: 'POST',
header: { 'Content-Type': 'application/json' },
header: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token()}` },
data: { text },
})
if (synthRes.statusCode === 200 && synthRes.data?.hash) {
@@ -240,12 +253,17 @@ const confirmExit = () => {
function startRecord() {
if (aiLoading.value || isComplete.value) return
// #ifdef MP-WEIXIN
isRecording.value = true
recorder = uni.getRecorderManager()
recorder.onStart(() => {})
recorder.onError(() => { isRecording.value = false })
recorder.start({ format: 'mp3' })
uni.vibrateShort({ type: 'medium' })
// #endif
// #ifndef MP-WEIXIN
uni.showToast({ title: '语音输入仅支持小程序', icon: 'none' })
// #endif
}
function stopRecord() {
@@ -260,7 +278,7 @@ function stopRecord() {
url: api(API_ENDPOINTS.TTS.ASR),
filePath: audioPath,
name: 'audio',
header: { 'Authorization': `Bearer ${token.value}` },
header: { 'Authorization': `Bearer ${token()}` },
})
console.log('[ASR] upload response:', uploadRes.statusCode, typeof uploadRes.data === 'string' ? uploadRes.data.slice(0, 200) : JSON.stringify(uploadRes.data).slice(0, 200))
if (uploadRes.statusCode === 200 && uploadRes.data) {
+26 -12
View File
@@ -87,15 +87,18 @@
<view class="card" v-if="mainTab === 'wechat' && isMp">
<text class="card-title">微信一键登录</text>
<text class="card-sub">授权后自动创建账号</text>
<button class="login-btn wx-btn" @click="doWxLogin">{{ wxLoading ? '登录中...' : '微信一键登录' }}</button>
<button class="login-btn wx-btn" :disabled="wxLoading" @click="doWxLogin">{{ wxLoading ? '登录中...' : '微信一键登录' }}</button>
</view>
<!-- 法律声明 -->
<!-- 法律声明 - 用户自主勾选同意 -->
<view class="legal">
<text class="legal-text">登录即表示同意</text>
<text class="legal-link" @click="goAgreement">用户协议</text>
<text class="legal-text"></text>
<text class="legal-link" @click="goPrivacy">隐私政策</text>
<label class="agree-label">
<checkbox :checked="agreed" @tap="agreed = !agreed" color="#4F46E5" style="transform:scale(0.85)" />
<text class="agree-text">我已阅读并同意</text>
<text class="legal-link" @tap.stop="goAgreement">用户服务协议</text>
<text class="agree-text"></text>
<text class="legal-link" @tap.stop="goPrivacy">隐私政策</text>
</label>
</view>
</view>
@@ -117,6 +120,8 @@
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { api } from '../../config'
const agreed = ref(false)
const mainTab = ref('login')
const loginMode = ref('password') // 'password' | 'code'
const isMp = ref(false)
@@ -147,10 +152,14 @@ onMounted(() => {
// #endif
})
onBeforeUnmount(() => { if (timer) clearInterval(timer) })
onBeforeUnmount(() => { if (timer) { clearTimeout(timer); timer = null } })
// 辅助
const showToast = (title, icon = 'none') => uni.showToast({ title, icon })
const checkAgreed = () => {
if (!agreed.value) { showToast('请阅读并同意《用户服务协议》和《隐私政策》'); return false }
return true
}
const loginSuccess = (data) => {
uni.setStorageSync('token', data.token)
if (data.user) uni.setStorageSync('userInfo', JSON.stringify(data.user))
@@ -160,7 +169,7 @@ const loginSuccess = (data) => {
// ====== 密码登录 ======
const doPasswordLogin = async () => {
if (!canPasswordLogin.value) return
if (!canPasswordLogin.value || !checkAgreed()) return
pwdLoading.value = true
try {
const res = await uni.request({
@@ -192,6 +201,9 @@ const sendEmailCode = () => {
emailSent.value = true
showToast('验证码已发送', 'success')
startCooldown()
if (res.data?.devCode) {
uni.showModal({ title: '开发模式', content: `验证码:${res.data.devCode}`, showCancel: false })
}
} else {
const msg = (res.data && res.data.message) || '发送失败'
showToast(msg)
@@ -219,7 +231,7 @@ const startCooldown = () => {
}
const doEmailLogin = async () => {
if (!emailCode.value) return
if (!emailCode.value || !checkAgreed()) return
emailLoading.value = true
try {
const res = await uni.request({
@@ -242,7 +254,7 @@ const doEmailLogin = async () => {
// ====== 注册 ======
const doRegister = async () => {
if (!canRegister.value) return
if (!canRegister.value || !checkAgreed()) return
regLoading.value = true
try {
const res = await uni.request({
@@ -284,6 +296,7 @@ const skipSetPwd = () => { showSetPwd.value = false }
// ====== 微信登录 ======
const doWxLogin = async () => {
// #ifdef MP-WEIXIN
if (!checkAgreed()) { wxLoading.value = false; return }
wxLoading.value = true
try {
const wxResp = await uni.login()
@@ -354,8 +367,9 @@ const goPrivacy = () => uni.navigateTo({ url: '/pages/privacy/privacy' })
.switch-hint { text-align: center; font-size: 22rpx; color: var(--color-primary); padding: 20rpx 0 4rpx; }
/* ===== Legal ===== */
.legal { display: flex; justify-content: center; align-items: center; gap: 4rpx; margin-top: 24rpx; flex-wrap: wrap; }
.legal-text { font-size: 22rpx; color: var(--color-text-tertiary); }
.legal { display: flex; justify-content: center; align-items: center; margin-top: 24rpx; flex-wrap: wrap; }
.agree-label { display: flex; align-items: center; gap: 6rpx; flex-wrap: wrap; justify-content: center; }
.agree-text { font-size: 22rpx; color: var(--color-text-tertiary); }
.legal-link { font-size: 22rpx; color: var(--color-primary); }
/* ===== Password Modal ===== */
+48 -21
View File
@@ -42,7 +42,7 @@
<view class="plan-badge sprint-badge">🚀 冲刺</view>
<view class="plan-header">
<text class="plan-name">冲刺版</text>
<text class="plan-price"><text class="price-num price-sprint">¥49.9</text><text class="price-unit">/</text></text>
<text class="plan-price"><text class="price-num price-sprint">{{ sprintPriceText }}</text><text class="price-unit">/</text></text>
</view>
<view class="plan-features">
<text class="feat" v-for="f in sprintFeatures" :key="f"> {{ f }}</text>
@@ -50,7 +50,7 @@
<view class="plan-action" v-if="!isLoggedIn" @click="goLogin">登录后开通</view>
<view class="plan-action owned" v-else-if="plan === 'sprint'"> 已开通</view>
<view class="plan-action" v-else-if="plan === 'growth'" @click="startPay('sprint')">升级至冲刺版</view>
<view class="plan-action" v-else @click="startPay('sprint')">¥49.9/ 立即开通</view>
<view class="plan-action" v-else @click="startPay('sprint')">{{ sprintPriceText }}/ 立即开通</view>
</view>
</view>
@@ -89,6 +89,7 @@
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { api } from '../../config'
import UQRCode from 'uqrcodejs'
@@ -104,26 +105,24 @@ const payError = ref('')
const payingPlanName = ref('')
const payingPlan = ref('')
const growthPriceText = ref('¥19.9')
const sprintPriceText = ref('¥49.9')
const currentOutTradeNo = ref('')
const freeFeatures = ['每日 2 次 AI 模拟面试', '基础面试报告', '通用题库随机出题', '简历诊断(限 3 次)']
const growthFeatures = [
'免费版全部权益', '无限面试次数', '详细面试报告(四维评分)',
'进步轨迹雷达图 + 打卡', '每日一题推送', '参考回答思路', '公司真题库',
]
const sprintFeatures = [
'成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告',
'学习路径推荐', '真人导师 1v1 点评(每月 1 次)', '简历精修(每月 1 次)', '内推优先',
]
const freeFeatures = ref(['AI 模拟面试 1 次(体验)', '基础面试报告', '通用题库随机出题', '简历优化(限 3 次免费'])
const growthFeatures = ref(['免费版全部权益', 'AI 数字人面试无限次', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题', '参考回答思路', '公司真题库'])
const sprintFeatures = ref(['成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告', '公司真题库精选'])
const token = () => uni.getStorageSync('token') || ''
onMounted(async () => {
const refreshState = async () => {
// #ifdef MP-WEIXIN
isMp.value = true
// #endif
const t = token()
if (!t) return
if (!t) {
isLoggedIn.value = false
return
}
isLoggedIn.value = true
try {
@@ -136,12 +135,25 @@ onMounted(async () => {
plan.value = d.plan || 'free'
currentPlanName.value = d.planName || '免费版'
}
if (lres.statusCode === 200 && lres.data?.price) {
const p = lres.data.price
growthPriceText.value = `¥${(p.monthly / 100).toFixed(1)}`
if (lres.statusCode === 200 && lres.data) {
const plans = Array.isArray(lres.data.plans) ? lres.data.plans : (Array.isArray(lres.data) ? lres.data : [])
const growth = plans.find((p) => p.id === 'growth')
const sprint = plans.find((p) => p.id === 'sprint')
if (growth) {
growthPriceText.value = `¥${(growth.price / 100).toFixed(1)}`
if (growth.features?.length) growthFeatures.value = growth.features
}
if (sprint?.features?.length) sprintFeatures.value = sprint.features
if (sprint) sprintPriceText.value = `¥${(sprint.price / 100).toFixed(1)}`
if (lres.data.price?.monthly) {
growthPriceText.value = `¥${(lres.data.price.monthly / 100).toFixed(1)}`
}
}
} catch (e) { /* ignore */ }
})
}
onMounted(() => { refreshState() })
onShow(() => { refreshState() })
const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
@@ -178,6 +190,7 @@ const startPay = async (selectedPlan) => {
url: api('/payment/jsapi'), method: 'POST',
data: { plan: planLabel },
header: { 'Authorization': `Bearer ${t}`, 'Content-Type': 'application/json' },
timeout: 30000,
})
payLoading.value = false
@@ -192,13 +205,22 @@ const startPay = async (selectedPlan) => {
package: pp.package,
signType: pp.signType || 'RSA',
paySign: pp.paySign,
success: () => pollPayResult(res.data.prepayId, planLabel),
success: () => {
const no = currentOutTradeNo.value || res.data.outTradeNo
pollPayResult(no, planLabel)
},
fail: (err) => { payError.value = '支付取消或失败'; uni.showToast({ title: '支付取消', icon: 'none' }) },
})
} else if (!res.statusCode || res.statusCode === 0) {
payLoading.value = false
const errMsg = '网络连接失败,请检查网络后重试'
payError.value = errMsg
uni.showToast({ title: errMsg, icon: 'none' })
} else {
payLoading.value = false
payError.value = res.data?.message || '创建订单失败'
uni.showToast({ title: '创建订单失败', icon: 'none' })
const errMsg = res.data?.message || '创建订单失败'
payError.value = errMsg
uni.showToast({ title: errMsg, icon: 'none' })
}
} catch (e) {
payLoading.value = false
@@ -233,9 +255,14 @@ const startPay = async (selectedPlan) => {
})
// 轮询支付结果
pollPayResult(res.data.outTradeNo, planLabel)
} else if (!res.statusCode || res.statusCode === 0) {
payLoading.value = false
const errMsg = '网络连接失败,请检查网络后重试'
payError.value = errMsg
uni.showToast({ title: errMsg, icon: 'none' })
} else {
payError.value = res.data?.message || '支付服务暂不可用'
uni.showToast({ title: '支付服务暂不可用', icon: 'none' })
uni.showToast({ title: res.data?.message || '支付服务暂不可用', icon: 'none' })
}
} catch (e) {
payLoading.value = false
+24 -7
View File
@@ -134,6 +134,7 @@
<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { api } from '../../config'
const stats = ref({ completedInterviews: 0, avgScore: 0, streak: 0 })
@@ -155,6 +156,16 @@ onMounted(async () => {
const t = token()
if (!t) return
await loadProgressData()
})
onShow(async () => {
if (token()) await loadProgressData()
})
async function loadProgressData() {
const t = token()
if (!t) return
try {
// Load progress
const res = await uni.request({
@@ -166,7 +177,7 @@ onMounted(async () => {
progress.value = d
dimensions.value = dimensions.value.map(dim => ({
...dim,
value: d.dimensions?.[dim.key] || Math.round(50 + Math.random() * 30),
value: d.dimensions?.[dim.key] || 0,
}))
}
} catch (e) { console.error(e) }
@@ -191,23 +202,29 @@ onMounted(async () => {
}
} catch (e) { console.error(e) }
// Build week days
buildWeekDays()
}
function buildWeekDays() {
const days = ['日', '一', '二', '三', '四', '五', '六']
const today = new Date()
const arr = []
const checkinDates = (progress.value.checkins || []).map((c) => {
const d = new Date(c.date || c.createdAt)
return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
})
for (let i = 6; i >= 0; i--) {
const d = new Date(today)
d.setDate(d.getDate() - i)
const isToday = i === 0
// Mark days with interviews (simulate based on streak)
const key = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
arr.push({
label: days[d.getDay()],
isToday,
done: i < (stats.value.streak || 0),
isToday: i === 0,
done: checkinDates.includes(key),
})
}
weekDays.value = arr
})
}
const formatDate = (d) => {
if (!d) return ''
+10 -9
View File
@@ -156,7 +156,9 @@ onLoad(async (options) => {
}))
}
}
}).catch(() => {})
}).catch(e => {
console.error('[report] auto-complete failed:', e)
})
}
}
} catch(e) { console.error(e) }
@@ -288,15 +290,12 @@ async function generateCard() {
ctx.setFillStyle('rgba(165,180,252,0.5)')
ctx.fillText('扫码开始你的模拟面试 → 在微信搜索"职引"小程序', w / 2, 690)
// QR code hint (simulated)
// QR text hint
ctx.setFillStyle('#FFFFFF')
ctx.setFontSize(12)
ctx.setFontSize(16)
ctx.setTextAlign('center')
ctx.fillText('⬛ ⬛ ⬛ ⬛ ⬛', w / 2, 760)
ctx.fillText('⬛ ⬛ ⬛ ⬛ ⬛', w / 2, 780)
ctx.fillText('⬛ ⬛ ⬛ ⬛ ⬛', w / 2, 800)
ctx.fillText('⬛ ⬛ ⬛ ⬛ ⬛', w / 2, 820)
ctx.fillText('微信小程序', w / 2, 855)
ctx.fillText('在微信搜索「职引」小程序', w / 2, 760)
ctx.fillText('查看完整面试报告', w / 2, 790)
ctx.draw(false, async () => {
try {
@@ -306,7 +305,9 @@ async function generateCard() {
itemList: ['保存到相册', '分享给好友'],
success: (res) => {
if (res.tapIndex === 0) {
uni.saveImageToPhotosAlbum({ filePath: tempRes.tempFilePath })
uni.saveImageToPhotosAlbum({ filePath: tempRes.tempFilePath, success: () => uni.showToast({ title: '已保存到相册', icon: 'success' }) })
} else if (res.tapIndex === 1) {
uni.shareAppMessage ? uni.shareAppMessage({ title: '我的面试报告', imageUrl: tempRes.tempFilePath }) : uni.showToast({ title: '请截图后分享', icon: 'none' })
}
},
})
+9 -6
View File
@@ -16,7 +16,7 @@
<text class="score-num">{{ diagnosisResult.score }}</text>
<text class="score-label">/100</text>
</view>
<text class="summary-text">{{ diagnosisResult.summary }}</text>
<text class="summary-text" v-if="diagnosisResult.summary">{{ diagnosisResult.summary }}</text>
</view>
<!-- 岗位匹配度诊断模式 -->
@@ -136,16 +136,19 @@ onLoad(async (options: any) => {
function applyResult(data: any) {
loading.value = false;
if (isOptimize.value) {
optimizedContent.value = data.optimizedContent || '';
changes.value = data.changes || [];
highlights.value = data.highlights || [];
optimizedContent.value = data.optimized || '';
changes.value = (data.changes || []).map((c: any) =>
typeof c === 'string' ? { section: c, description: c } : c
);
highlights.value = [];
} else {
diagnosisResult.value = data;
changes.value = (data.issues || []).map((i: any) => ({
...i,
typeLabel: i.type === 'structure' ? '结构' : i.type === 'content' ? '内容' : i.type === 'keywords' ? '关键词' : i.type === 'achievement' ? '成就' : '格式',
typeLabel: i.level === 'high' ? '严重' : i.level === 'medium' ? '中等' : '轻微',
description: i.desc || i.description,
}));
highlights.value = data.strengths || [];
highlights.value = data.suggestions || [];
}
}
+693
View File
@@ -0,0 +1,693 @@
<template>
<view class="page">
<!-- ====== Mode 1: List View ====== -->
<template v-if="mode === 'list'">
<view class="hero">
<text class="hero-title">面试复盘</text>
<text class="hero-sub">上传录音AI 帮你复盘面试表现</text>
</view>
<view class="stats-bar card" v-if="listData.items.length > 0">
<view class="stat">
<text class="stat-val">{{ listData.total }}</text>
<text class="stat-lbl">复盘次数</text>
</view>
<view class="stat-sep"></view>
<view class="stat">
<text class="stat-val">{{ avgScore }}</text>
<text class="stat-lbl">平均分</text>
</view>
<view class="stat-sep"></view>
<view class="stat">
<text class="stat-val">{{ completedCount }}</text>
<text class="stat-lbl">已完成</text>
</view>
</view>
<view class="list" v-if="listData.items.length > 0">
<view
class="record-card card"
v-for="item in listData.items"
:key="item._id"
@click="viewDetail(item._id)"
>
<view class="record-top">
<view class="record-icon">
{{ item.status === 'completed' ? (item.analysis?.overallScore >= 80 ? '🌟' : '📋') : '⏳' }}
</view>
<view class="record-body">
<view class="record-name">{{ item.position }}</view>
<text class="record-meta">
{{ formatDate(item.createdAt) }}
<template v-if="item.company"> · {{ item.company }}</template>
<template v-if="item.status === 'processing'"> · 分析中...</template>
<template v-if="item.status === 'failed'"> · 分析失败</template>
</text>
</view>
<view class="record-score" v-if="item.status === 'completed'" :class="scoreLevel(item.analysis?.overallScore)">
{{ item.analysis?.overallScore || '--' }}
</view>
<view v-else class="record-score pending">{{ item.status === 'processing' ? '...' : '!' }}</view>
</view>
</view>
<view class="load-more" v-if="hasMore" @click="loadMore">加载更多</view>
</view>
<view class="empty" v-else-if="!loading">
<text class="empty-icon">🎙</text>
<text class="empty-title">暂无复盘记录</text>
<text class="empty-desc">面试后上传录音AI 帮你分析表现</text>
</view>
<view class="fixed-bottom">
<button class="btn-primary" @click="mode = 'upload'">
<text class="btn-icon">+</text> 上传录音复盘
</button>
</view>
</template>
<!-- ====== Mode 2: Upload View ====== -->
<template v-if="mode === 'upload'">
<view class="upload-page">
<view class="upload-header">
<text class="upload-back" @click="mode = 'list'"> 返回</text>
<text class="upload-title">上传面试录音</text>
<view style="width:60rpx"></view>
</view>
<view class="form-card card">
<view class="form-group">
<text class="form-label">面试岗位 <text class="required">*</text></text>
<input class="form-input" v-model="form.position" placeholder="例如:前端开发工程师" />
</view>
<view class="form-group">
<text class="form-label">面试公司</text>
<input class="form-input" v-model="form.company" placeholder="选填" />
</view>
<view class="form-group">
<text class="form-label">上传方式</text>
<view class="tab-bar">
<view class="tab-item" :class="{ active: uploadMode === 'audio' }" @click="uploadMode = 'audio'">录音文件</view>
<view class="tab-item" :class="{ active: uploadMode === 'text' }" @click="uploadMode = 'text'">粘贴文本</view>
</view>
</view>
<!-- Audio upload mode -->
<view v-if="uploadMode === 'audio'" class="audio-upload-area">
<view class="upload-box" @click="chooseFile">
<text class="upload-icon">📁</text>
<text class="upload-text" v-if="!form.file">点击选择录音文件</text>
<text class="upload-text" v-else>{{ form.file.name }}</text>
<text class="upload-hint">支持 mp3/m4a/wav最大 50MB</text>
</view>
</view>
<!-- Text paste mode -->
<view v-else class="text-upload-area">
<textarea
class="text-input"
v-model="form.text"
placeholder="将面试录音转写为文字后粘贴在这里...&#10;&#10;示例:&#10;面试官:请介绍一下你自己&#10;候选人:我毕业于..."
:maxlength="10000"
/>
<text class="char-count">{{ form.text.length }}/10000</text>
</view>
</view>
<view class="submit-area">
<button class="btn-primary" @click="submitReview" :disabled="submitting">
{{ submitting ? '提交中...' : '开始分析' }}
</button>
</view>
</view>
</template>
<!-- ====== Mode 3: Processing View ====== -->
<template v-if="mode === 'processing'">
<view class="processing-page">
<view class="processing-card">
<view class="spinner"></view>
<text class="processing-title">AI 分析中</text>
<text class="processing-desc">正在对面试录音进行深度分析请稍候...</text>
<view class="process-steps">
<view class="step" :class="{ done: processStep >= 1 }">
<text class="step-num">{{ processStep >= 1 ? '✓' : '1' }}</text>
<text class="step-label">文本转录</text>
</view>
<view class="step" :class="{ done: processStep >= 2 }">
<text class="step-num">{{ processStep >= 2 ? '✓' : '2' }}</text>
<text class="step-label">语音分析</text>
</view>
<view class="step" :class="{ done: processStep >= 3 }">
<text class="step-num">{{ processStep >= 3 ? '✓' : '3' }}</text>
<text class="step-label">AI 评估</text>
</view>
</view>
<text class="processing-hint">请勿离开此页面</text>
</view>
</view>
</template>
<!-- ====== Mode 4: Report View ====== -->
<template v-if="mode === 'report' && reportData">
<view class="report-page">
<view class="report-header">
<text class="report-back" @click="mode = 'list'"> 返回列表</text>
<text class="report-title">复盘报告</text>
<view style="width:60rpx"></view>
</view>
<view class="body">
<view class="score-card">
<view class="score-circle" :class="scoreLevel(reportData.analysis.overallScore)">
<text class="score-num">{{ reportData.analysis.overallScore }}</text>
<text class="score-label">总分</text>
</view>
</view>
<view class="info-row">
<text class="info-label">面试岗位</text>
<text class="info-value">{{ reportData.position }}</text>
</view>
<view class="info-row" v-if="reportData.company">
<text class="info-label">面试公司</text>
<text class="info-value">{{ reportData.company }}</text>
</view>
<view class="info-row">
<text class="info-label">分析时间</text>
<text class="info-value">{{ formatDate(reportData.createdAt) }}</text>
</view>
<view class="info-row" v-if="reportData.speechAnalysis">
<text class="info-label">回答总时长</text>
<text class="info-value">{{ reportData.speechAnalysis.totalDuration }}</text>
</view>
<!-- 四维能力评估 -->
<view class="section" v-if="reportData.analysis.dimensions">
<view class="section-title">四维能力评估</view>
<view class="dim-grid">
<view class="dim-item" v-for="dim in dimDefs" :key="dim.key">
<view class="dim-header">
<text class="dim-name">{{ dim.label }}</text>
<text class="dim-score">{{ getDimValue(dim.key) }}</text>
</view>
<view class="dim-bar-bg">
<view class="dim-bar-fill" :style="{ width: getDimValue(dim.key) + '%', background: dim.color }"></view>
</view>
</view>
</view>
</view>
<!-- 语音分析 -->
<view class="section" v-if="reportData.speechAnalysis">
<view class="section-title">语音表达分析</view>
<view class="speech-card">
<view class="speech-row">
<text class="speech-label">语气词评分</text>
<text class="speech-value" :class="scoreLevel(reportData.speechAnalysis.fillerScore)">
{{ reportData.speechAnalysis.fillerScore }}
</text>
</view>
<view class="speech-row">
<text class="speech-label">语气词密度</text>
<text class="speech-value">{{ reportData.speechAnalysis.fillerDensity }}%</text>
</view>
<view class="speech-row">
<text class="speech-label">语速</text>
<text class="speech-value">{{ reportData.speechAnalysis.pace }}</text>
</view>
<view class="filler-tags" v-if="reportData.speechAnalysis.fillerWords.length > 0">
<text class="filler-tag" v-for="fw in reportData.speechAnalysis.fillerWords" :key="fw.word">
"{{ fw.word }}" × {{ fw.count }}
</text>
</view>
</view>
</view>
<!-- 逐题分析 -->
<view class="section" v-if="reportData.analysis.questionBreakdown && reportData.analysis.questionBreakdown.length > 0">
<view class="section-title">逐题分析</view>
<view class="qa-list">
<view class="qa-item" v-for="(qa, idx) in reportData.analysis.questionBreakdown" :key="idx">
<view class="qa-header">
<text class="qa-num">Q{{ idx + 1 }}</text>
<text class="qa-score" :class="scoreLevel(qa.score)">{{ qa.score }}</text>
</view>
<text class="qa-question">{{ qa.question }}</text>
<text class="qa-answer-label">你的回答</text>
<text class="qa-answer">{{ qa.answer }}</text>
<view class="qa-comment" v-if="qa.comment">
<text class="qa-comment-icon">💡</text>
<text class="qa-comment-text">{{ qa.comment }}</text>
</view>
<view class="qa-suggest" v-if="qa.suggestedAnswer">
<text class="qa-suggest-icon">参考思路</text>
<text class="qa-suggest-text">{{ qa.suggestedAnswer }}</text>
</view>
</view>
</view>
</view>
<!-- 改进建议 -->
<view class="section" v-if="reportData.analysis.strengths.length > 0 || reportData.analysis.weaknesses.length > 0">
<view class="section-title">改进建议</view>
<view class="sugg-block" v-if="reportData.analysis.strengths.length > 0">
<text class="sugg-block-title sugg-good"> 表现亮点</text>
<text class="sugg-item" v-for="(s, i) in reportData.analysis.strengths" :key="'str-' + i">{{ s }}</text>
</view>
<view class="sugg-block" v-if="reportData.analysis.weaknesses.length > 0">
<text class="sugg-block-title sugg-warn"> 待改进</text>
<text class="sugg-item" v-for="(w, i) in reportData.analysis.weaknesses" :key="'weak-' + i">{{ w }}</text>
</view>
<view class="sugg-block" v-if="reportData.analysis.suggestions.length > 0">
<text class="sugg-block-title sugg-info">💡 具体建议</text>
<text class="sugg-item" v-for="(s, i) in reportData.analysis.suggestions" :key="'sug-' + i">{{ s }}</text>
</view>
</view>
<view class="actions">
<button class="btn-primary" @click="goInterview">再去模拟面试练练</button>
<button class="btn-outline" @click="mode = 'list'">返回列表</button>
</view>
</view>
</view>
</template>
</view>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { api } from '../../config'
const mode = ref('list')
const loading = ref(false)
const submitting = ref(false)
const listData = ref({ items: [], total: 0, page: 1, limit: 20 })
const processStep = ref(0)
const reportData = ref(null)
const pollTimer = ref(null)
const reviewId = ref('')
const form = ref({ position: '', company: '', file: null, text: '' })
const uploadMode = ref('audio')
const dimDefs = [
{ key: 'logic', label: '逻辑思维', color: '#6366F1' },
{ key: 'expression', label: '表达能力', color: '#10B981' },
{ key: 'professionalism', label: '专业度', color: '#F59E0B' },
{ key: 'stability', label: '稳定性', color: '#EF4444' },
]
const avgScore = computed(() => {
const scored = listData.value.items.filter(i => i.status === 'completed' && i.analysis?.overallScore)
if (scored.length === 0) return '--'
return Math.round(scored.reduce((s, i) => s + (i.analysis?.overallScore || 0), 0) / scored.length)
})
const completedCount = computed(() => {
return listData.value.items.filter(i => i.status === 'completed').length
})
const hasMore = computed(() => {
return listData.value.page < Math.ceil(listData.value.total / listData.value.limit)
})
onMounted(() => { fetchList() })
onShow(() => {
if (mode.value === 'list') fetchList()
})
async function fetchList(page = 1) {
const token = uni.getStorageSync('token') || ''
if (!token) return
loading.value = true
try {
const res = await uni.request({
url: api(`/interview-review/list?page=${page}&limit=20`),
method: 'GET',
header: { 'Authorization': `Bearer ${token}` },
})
if (res.statusCode === 200) {
const data = res.data
if (page === 1) {
listData.value = data
} else {
listData.value = {
...data,
items: [...listData.value.items, ...data.items],
}
}
}
} catch(e) { console.error(e) }
finally { loading.value = false }
}
function loadMore() {
const next = listData.value.page + 1
fetchList(next)
listData.value.page = next
}
function chooseFile() {
uni.chooseMessageFile ? uni.chooseMessageFile({
count: 1,
type: 'file',
extension: ['mp3', 'm4a', 'wav', 'aac', 'ogg'],
success: (r) => {
if (r.tempFiles && r.tempFiles[0]) {
form.value.file = r.tempFiles[0]
}
},
}) : uni.showToast({ title: '当前平台不支持文件选择', icon: 'none' })
}
async function submitReview() {
if (!form.value.position.trim()) {
uni.showToast({ title: '请填写面试岗位', icon: 'none' })
return
}
if (uploadMode.value === 'audio' && !form.value.file) {
uni.showToast({ title: '请选择录音文件', icon: 'none' })
return
}
if (uploadMode.value === 'text' && !form.value.text.trim()) {
uni.showToast({ title: '请粘贴面试转录文本', icon: 'none' })
return
}
submitting.value = true
const token = uni.getStorageSync('token') || ''
try {
if (uploadMode.value === 'audio') {
const res = await uni.uploadFile({
url: api('/interview-review'),
filePath: form.value.file.path || form.value.file.tempFilePath,
name: 'file',
formData: {
position: form.value.position.trim(),
company: form.value.company.trim(),
},
header: { 'Authorization': `Bearer ${token}` },
})
if (res.statusCode === 201 || res.statusCode === 200) {
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
reviewId.value = data.id
startPolling(data.id)
mode.value = 'processing'
animateSteps()
} else {
const err = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
uni.showToast({ title: err.message || '上传失败', icon: 'none' })
}
} else {
// Text submission
const res = await uni.request({
url: api('/interview-review/text'),
method: 'POST',
data: {
position: form.value.position.trim(),
company: form.value.company.trim(),
text: form.value.text.trim(),
},
header: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
})
if (res.statusCode === 201 || res.statusCode === 200) {
reviewId.value = res.data.id
startPolling(res.data.id)
mode.value = 'processing'
animateSteps()
} else {
uni.showToast({ title: res.data?.message || '提交失败', icon: 'none' })
}
}
} catch(e) {
uni.showToast({ title: e.message || '网络错误', icon: 'none' })
}
finally { submitting.value = false }
}
function animateSteps() {
processStep.value = 1
setTimeout(() => { processStep.value = 2 }, 3000)
setTimeout(() => { processStep.value = 3 }, 6000)
}
function startPolling(id) {
let attempts = 0
const maxAttempts = 60 // 5 minutes max
pollTimer.value = setInterval(async () => {
attempts++
if (attempts > maxAttempts) {
clearInterval(pollTimer.value)
uni.showToast({ title: '分析超时,请稍后再查', icon: 'none' })
mode.value = 'list'
return
}
try {
const token = uni.getStorageSync('token') || ''
const res = await uni.request({
url: api(`/interview-review/${id}`),
method: 'GET',
header: { 'Authorization': `Bearer ${token}` },
})
if (res.statusCode === 200) {
const data = res.data
if (data.status === 'completed') {
clearInterval(pollTimer.value)
reportData.value = data
mode.value = 'report'
} else if (data.status === 'failed') {
clearInterval(pollTimer.value)
uni.showToast({ title: '分析失败,请重新上传', icon: 'none' })
mode.value = 'list'
}
// status === 'processing': continue polling
}
} catch(e) { console.error(e) }
}, 5000)
}
function viewDetail(id) {
const token = uni.getStorageSync('token') || ''
uni.request({
url: api(`/interview-review/${id}`),
method: 'GET',
header: { 'Authorization': `Bearer ${token}` },
success: (res) => {
if (res.statusCode === 200) {
if (res.data.status === 'completed') {
reportData.value = res.data
mode.value = 'report'
} else if (res.data.status === 'processing') {
reviewId.value = id
startPolling(id)
mode.value = 'processing'
} else {
uni.showToast({ title: '分析失败', icon: 'none' })
}
}
},
fail: () => { uni.showToast({ title: '加载失败', icon: 'none' }) },
})
}
function getDimValue(key) {
return Math.min(100, Math.max(0, Math.round(reportData.value?.analysis?.dimensions?.[key] || 0)))
}
function formatDate(d) {
if (!d) return '--'
const date = new Date(d)
return `${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')} ${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}`
}
const scoreLevel = (s) => {
if (!s && s !== 0) return 'pending'
if (s >= 80) return 'good'
if (s >= 60) return 'medium'
return 'poor'
}
function goInterview() {
uni.switchTab({ url: '/pages/index/index' })
}
onUnmounted(() => {
if (pollTimer.value) clearInterval(pollTimer.value)
})
</script>
<style scoped>
.page { background: #F3F4F6; min-height: 100vh; }
.hero {
background: linear-gradient(135deg, #4F46E5 0%, #7C3AED 50%, #6366F1 100%);
padding: 48rpx 32rpx 72rpx; border-radius: 0 0 48rpx 48rpx;
}
.hero-title { font-size: 40rpx; font-weight: 700; color: #FFF; display: block; }
.hero-sub { font-size: 22rpx; color: rgba(255,255,255,0.7); margin-top: 8rpx; display: block; }
.stats-bar { display: flex; align-items: center; padding: 24rpx; margin: -40rpx 32rpx 0; position: relative; z-index: 1; border-radius: 16rpx; background: #FFF; box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.06); }
.stat { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 6rpx; }
.stat-val { font-size: 36rpx; font-weight: 700; color: #4F46E5; }
.stat-lbl { font-size: 20rpx; color: #9CA3AF; }
.stat-sep { width: 1rpx; height: 40rpx; background: #E5E7EB; }
.list { padding: 20rpx 32rpx 160rpx; }
.record-card { background: #FFF; padding: 24rpx 28rpx; margin-bottom: 16rpx; border-radius: 16rpx; box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.04); }
.record-top { display: flex; align-items: center; gap: 16rpx; }
.record-icon { font-size: 40rpx; width: 64rpx; height: 64rpx; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.record-body { flex: 1; min-width: 0; }
.record-name { font-size: 28rpx; font-weight: 600; color: #111827; }
.record-meta { font-size: 20rpx; color: #9CA3AF; margin-top: 6rpx; display: block; }
.record-score { font-size: 28rpx; font-weight: 700; width: 72rpx; text-align: right; flex-shrink: 0; }
.record-score.good { color: #059669; }
.record-score.medium { color: #D97706; }
.record-score.poor { color: #DC2626; }
.record-score.pending { color: #9CA3AF; }
.empty { display: flex; flex-direction: column; align-items: center; padding: 120rpx 32rpx 200rpx; }
.empty-icon { font-size: 80rpx; margin-bottom: 20rpx; }
.empty-title { font-size: 28rpx; font-weight: 600; color: #111827; }
.empty-desc { font-size: 22rpx; color: #9CA3AF; margin-top: 8rpx; margin-bottom: 36rpx; }
.fixed-bottom { position: fixed; bottom: 0; left: 0; right: 0; padding: 20rpx 32rpx 40rpx; background: linear-gradient(transparent, #F3F4F6 30rpx); }
.btn-primary { background: linear-gradient(135deg, #4F46E5, #7C3AED); color: #FFF; border-radius: 16rpx; height: 88rpx; line-height: 88rpx; font-size: 28rpx; font-weight: 600; display: flex; align-items: center; justify-content: center; gap: 8rpx; }
.btn-primary:active { opacity: 0.85; }
.btn-icon { font-size: 36rpx; font-weight: 400; }
/* Upload Page */
.upload-page { background: #F3F4F6; min-height: 100vh; }
.upload-header { display: flex; align-items: center; justify-content: space-between; padding: 24rpx 32rpx; background: #FFF; }
.upload-back { font-size: 28rpx; color: #4F46E5; }
.upload-title { font-size: 32rpx; font-weight: 600; color: #111827; }
.form-card { background: #FFF; border-radius: 16rpx; margin: 24rpx 32rpx; padding: 32rpx; }
.form-group { margin-bottom: 28rpx; }
.form-label { font-size: 26rpx; font-weight: 600; color: #374151; display: block; margin-bottom: 12rpx; }
.required { color: #DC2626; }
.form-input { width: 100%; height: 72rpx; border: 2rpx solid #E5E7EB; border-radius: 12rpx; padding: 0 20rpx; font-size: 26rpx; box-sizing: border-box; }
.tab-bar { display: flex; gap: 0; background: #F3F4F6; border-radius: 12rpx; overflow: hidden; }
.tab-item { flex: 1; text-align: center; padding: 18rpx 0; font-size: 24rpx; color: #6B7280; }
.tab-item.active { background: #4F46E5; color: #FFF; font-weight: 600; }
.audio-upload-area { margin-top: 8rpx; }
.upload-box { border: 2rpx dashed #D1D5DB; border-radius: 16rpx; padding: 48rpx 32rpx; display: flex; flex-direction: column; align-items: center; gap: 12rpx; }
.upload-icon { font-size: 60rpx; }
.upload-text { font-size: 26rpx; color: #374151; }
.upload-hint { font-size: 20rpx; color: #9CA3AF; }
.text-upload-area { margin-top: 8rpx; }
.text-input { width: 100%; height: 360rpx; border: 2rpx solid #E5E7EB; border-radius: 12rpx; padding: 20rpx; font-size: 24rpx; line-height: 1.6; box-sizing: border-box; }
.char-count { font-size: 20rpx; color: #9CA3AF; text-align: right; display: block; margin-top: 8rpx; }
.submit-area { padding: 0 32rpx 48rpx; }
/* Processing Page */
.processing-page { display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 32rpx; }
.processing-card { background: #FFF; border-radius: 24rpx; padding: 64rpx 48rpx; text-align: center; box-shadow: 0 8rpx 40rpx rgba(0,0,0,0.08); width: 100%; max-width: 500rpx; }
.spinner { width: 80rpx; height: 80rpx; border: 6rpx solid #E5E7EB; border-top-color: #4F46E5; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 32rpx; }
@keyframes spin { to { transform: rotate(360deg); } }
.processing-title { font-size: 32rpx; font-weight: 700; color: #111827; margin-bottom: 12rpx; }
.processing-desc { font-size: 24rpx; color: #6B7280; margin-bottom: 40rpx; }
.process-steps { display: flex; gap: 16rpx; justify-content: center; margin-bottom: 24rpx; }
.step { display: flex; flex-direction: column; align-items: center; gap: 8rpx; }
.step-num { width: 48rpx; height: 48rpx; border-radius: 50%; background: #F3F4F6; color: #9CA3AF; font-size: 22rpx; font-weight: 700; display: flex; align-items: center; justify-content: center; }
.step.done .step-num { background: #4F46E5; color: #FFF; }
.step-label { font-size: 20rpx; color: #9CA3AF; }
.step.done .step-label { color: #4F46E5; }
.processing-hint { font-size: 20rpx; color: #D1D5DB; }
/* Report Page */
.report-page { background: #F3F4F6; min-height: 100vh; }
.report-header { display: flex; align-items: center; justify-content: space-between; padding: 24rpx 32rpx; background: #FFF; }
.report-back { font-size: 28rpx; color: #4F46E5; }
.report-title { font-size: 32rpx; font-weight: 600; color: #111827; }
.body { padding: 0 32rpx 48rpx; }
.score-card { display: flex; justify-content: center; margin: -20rpx 0 30rpx; }
.score-circle {
width: 180rpx; height: 180rpx; border-radius: 50%;
background: #FFF; display: flex; flex-direction: column;
align-items: center; justify-content: center;
box-shadow: 0 8rpx 30rpx rgba(79,70,229,0.2);
}
.score-circle.good { box-shadow: 0 8rpx 30rpx rgba(5,150,105,0.2); }
.score-circle.medium { box-shadow: 0 8rpx 30rpx rgba(217,119,6,0.2); }
.score-circle.poor { box-shadow: 0 8rpx 30rpx rgba(220,38,38,0.2); }
.score-num { font-size: 56rpx; font-weight: 700; color: #4F46E5; line-height: 1.2; }
.good .score-num { color: #059669; }
.medium .score-num { color: #D97706; }
.poor .score-num { color: #DC2626; }
.score-label { font-size: 20rpx; color: #9CA3AF; margin-top: 4rpx; }
.info-row { display: flex; justify-content: space-between; padding: 20rpx 0; border-bottom: 1rpx solid #E5E7EB; font-size: 24rpx; }
.info-label { color: #6B7280; }
.info-value { color: #111827; font-weight: 500; }
.section { background: #FFF; border-radius: 20rpx; padding: 28rpx; margin-top: 24rpx; box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.04); }
.section-title { font-size: 28rpx; font-weight: 600; color: #111827; margin-bottom: 16rpx; }
.dim-grid { display: flex; flex-direction: column; gap: 20rpx; }
.dim-header { display: flex; justify-content: space-between; margin-bottom: 8rpx; }
.dim-name { font-size: 24rpx; color: #374151; }
.dim-score { font-size: 24rpx; color: #4F46E5; font-weight: 600; }
.dim-bar-bg { height: 20rpx; background: #F3F4F6; border-radius: 10rpx; overflow: hidden; }
.dim-bar-fill { height: 100%; border-radius: 10rpx; }
.speech-card { display: flex; flex-direction: column; gap: 16rpx; }
.speech-row { display: flex; justify-content: space-between; align-items: center; }
.speech-label { font-size: 24rpx; color: #374151; }
.speech-value { font-size: 24rpx; font-weight: 600; color: #111827; }
.speech-value.good { color: #059669; }
.speech-value.medium { color: #D97706; }
.speech-value.poor { color: #DC2626; }
.filler-tags { display: flex; flex-wrap: wrap; gap: 8rpx; }
.filler-tag { background: #FEF3C7; color: #92400E; padding: 6rpx 16rpx; border-radius: 20rpx; font-size: 20rpx; }
.qa-list { display: flex; flex-direction: column; gap: 24rpx; }
.qa-item { padding: 20rpx; background: #F9FAFB; border-radius: 12rpx; }
.qa-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12rpx; }
.qa-num { font-size: 22rpx; font-weight: 700; color: #4F46E5; background: #EEF2FF; padding: 4rpx 14rpx; border-radius: 8rpx; }
.qa-score { font-size: 24rpx; font-weight: 700; }
.qa-score.good { color: #059669; }
.qa-score.medium { color: #D97706; }
.qa-score.poor { color: #DC2626; }
.qa-score.pending { color: #9CA3AF; }
.qa-question { font-size: 24rpx; font-weight: 600; color: #111827; margin-bottom: 8rpx; display: block; }
.qa-answer-label { font-size: 20rpx; color: #6B7280; display: block; margin-top: 8rpx; }
.qa-answer { font-size: 22rpx; color: #374151; line-height: 1.6; display: block; margin-top: 4rpx; white-space: pre-wrap; }
.qa-comment { background: #EEF2FF; padding: 12rpx; border-radius: 8rpx; margin-top: 12rpx; display: flex; gap: 8rpx; }
.qa-comment-icon { font-size: 22rpx; }
.qa-comment-text { font-size: 22rpx; color: #4338CA; line-height: 1.5; }
.qa-suggest { background: #FEF3C7; padding: 12rpx; border-radius: 8rpx; margin-top: 8rpx; }
.qa-suggest-icon { font-size: 22rpx; font-weight: 600; color: #92400E; }
.qa-suggest-text { font-size: 22rpx; color: #78350F; line-height: 1.5; }
.sugg-block { margin-bottom: 20rpx; }
.sugg-block-title { font-size: 24rpx; font-weight: 600; display: block; margin-bottom: 8rpx; }
.sugg-good { color: #059669; }
.sugg-warn { color: #D97706; }
.sugg-info { color: #4F46E5; }
.sugg-item { display: block; font-size: 22rpx; color: #374151; line-height: 1.8; padding-left: 20rpx; }
.sugg-item::before { content: '• '; color: #D1D5DB; }
.actions { display: flex; flex-direction: column; gap: 16rpx; margin-top: 32rpx; }
.btn-outline { background: #FFF; color: #4F46E5; border-radius: 16rpx; height: 88rpx; line-height: 88rpx; font-size: 28rpx; border: 2rpx solid #4F46E5; }
.btn-outline:active { background: #F5F3FF; }
.load-more { text-align: center; padding: 24rpx; color: #4F46E5; font-size: 24rpx; }
</style>
+4 -2
View File
@@ -125,10 +125,12 @@ const todayStats = computed(() => ({
credited: stats.value.todayCredited || 0,
}))
let isWechat = false
const isWechat = ref(false)
onMounted(() => {
isWechat = navigator?.userAgent?.toLowerCase().includes('micromessenger') || false
// #ifdef H5
isWechat.value = navigator?.userAgent?.toLowerCase().includes('micromessenger') || false
// #endif
loadData()
})
+219 -188
View File
@@ -1,188 +1,219 @@
<template>
<view class="page fade-in">
<!-- 个人中心 -->
<view class="header" v-if="isLoggedIn">
<view class="profile-section">
<image class="avatar" :src="userInfo.avatar || '/static/avatar-default.png'" mode="aspectFill" />
<view class="profile-info">
<text class="nickname">{{ userInfo.nickname || '未设置昵称' }}</text>
<view class="plan-badge">{{ userInfo.plan || '免费版' }}</view>
</view>
<text class="header-arrow"></text>
</view>
<view class="stats-bar">
<view class="stat">
<text class="stat-num">{{ stats.interviewCount || 0 }}</text>
<text class="stat-label">模拟面试</text>
</view>
<view class="stat-divider"></view>
<view class="stat">
<text class="stat-num">{{ stats.avgScore || '--' }}</text>
<text class="stat-label">平均得分</text>
</view>
<view class="stat-divider"></view>
<view class="stat">
<text class="stat-num">{{ stats.completedCount || 0 }}</text>
<text class="stat-label">已完成</text>
</view>
</view>
</view>
<view class="header header-guest" v-else @click="goLogin">
<view class="guest-box">
<view class="guest-avatar"><text class="guest-icon">👤</text></view>
<view class="guest-info">
<text class="guest-name">未登录 / 点击登录</text>
</view>
<text class="header-arrow"></text>
</view>
</view>
<!-- 菜单列表 -->
<view class="menu-area">
<view class="menu-group">
<view class="menu-item" @click="requireLogin(goHistory, '面试记录')">
<view class="menu-icon-wrap wrap-blue"><text class="menu-icon">📋</text></view>
<text class="menu-text">面试记录</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="goVip">
<view class="menu-icon-wrap wrap-purple"><text class="menu-icon">💎</text></view>
<text class="menu-text">会员中心</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="requireLogin(goResume, '我的简历')">
<view class="menu-icon-wrap wrap-green"><text class="menu-icon">📄</text></view>
<text class="menu-text">我的简历</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="requireLogin(goShare, '我的分享')">
<view class="menu-icon-wrap wrap-orange"><text class="menu-icon">📤</text></view>
<text class="menu-text">我的分享</text>
<text class="menu-arrow"></text>
</view>
</view>
<view class="menu-group">
<view class="menu-item" @click="goAbout">
<view class="menu-icon-wrap wrap-gray"><text class="menu-icon"></text></view>
<text class="menu-text">关于</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" v-if="isAdmin" @click="goAdmin">
<view class="menu-icon-wrap wrap-gray"><text class="menu-icon"></text></view>
<text class="menu-text">管理后台</text>
<text class="menu-arrow"></text>
</view>
</view>
<view class="logout-wrap" v-if="isLoggedIn">
<button class="logout-btn" @click="doLogout">退出登录</button>
</view>
</view>
</view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { api } from '../../config'
const userInfo = ref({})
const isAdmin = ref(false)
const stats = ref({ interviewCount: 0, avgScore: '--', completedCount: 0 })
const token = ref('')
const isLoggedIn = computed(() => !!token.value)
const refreshState = () => {
token.value = uni.getStorageSync('token') || ''
if (!token.value) return
try { const s = uni.getStorageSync('userInfo'); if (s) userInfo.value = JSON.parse(s) } catch(e) {}
loadStats()
checkAdmin()
}
onMounted(refreshState)
onShow(refreshState)
const loadStats = async () => {
try {
const res = await uni.request({ url: api('/interview/stats/mine'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
if (res.statusCode === 200) stats.value = res.data
} catch(e) { console.error(e) }
}
const requireLogin = (action, name) => {
if (isLoggedIn.value) { action(); return }
uni.showModal({
title: '请先登录',
content: `需要登录后才能使用${name}功能`,
confirmText: '去登录',
success: (r) => { if (r.confirm) uni.navigateTo({ url: '/pages/login/login' }) }
})
}
const checkAdmin = () => {
isAdmin.value = userInfo.value.role === 'admin'
}
const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
const goHistory = () => uni.switchTab({ url: '/pages/history/history' })
const goVip = () => uni.navigateTo({ url: '/pages/member/member' })
const goResume = () => uni.navigateTo({ url: '/pages/resume/resume' })
const goShare = () => uni.navigateTo({ url: '/pages/share/share' })
const goAdmin = () => uni.navigateTo({ url: '/pages/admin/admin' })
const goAbout = () => uni.navigateTo({ url: '/pages/about/about' })
const doLogout = () => {
uni.showModal({
title: '退出登录', content: '确定要退出登录吗?',
success: (r) => { if (r.confirm) { uni.removeStorageSync('token'); uni.removeStorageSync('userInfo'); token.value = '' } }
})
}
</script>
<style scoped>
.page { height: 100%; overflow-y: auto; background: var(--color-bg); }
.header {
background: linear-gradient(135deg, var(--color-gradient-start) 0%, var(--color-gradient-mid) 50%, var(--color-gradient-end) 100%);
padding: 48rpx 32rpx 72rpx; border-radius: 0 0 48rpx 48rpx; min-height: 90rpx;
}
.profile-section { display: flex; align-items: center; margin-bottom: 36rpx; }
.avatar { width: 104rpx; height: 104rpx; border-radius: 50%; margin-right: 24rpx; border: 3rpx solid rgba(255,255,255,0.4); flex-shrink: 0; }
.profile-info { flex: 1; display: flex; flex-direction: column; }
.nickname { font-size: 34rpx; font-weight: 700; color: #FFFFFF; }
.plan-badge { font-size: 20rpx; color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.2); padding: 4rpx 14rpx; border-radius: 8rpx; align-self: flex-start; margin-top: 8rpx; }
.header-arrow { font-size: 36rpx; color: rgba(255,255,255,0.5); }
.stats-bar { display: flex; align-items: center; background: rgba(255,255,255,0.15); border-radius: var(--radius-lg); padding: 24rpx 0; }
.stat { flex: 1; display: flex; flex-direction: column; align-items: center; }
.stat-num { font-size: 34rpx; font-weight: 700; color: #FFFFFF; }
.stat-label { font-size: 20rpx; color: rgba(255,255,255,0.7); margin-top: 6rpx; }
.stat-divider { width: 1rpx; height: 44rpx; background: rgba(255,255,255,0.2); }
.header-guest { padding: 36rpx 32rpx 72rpx; min-height: 90rpx; }
.guest-box { display: flex; align-items: center; }
.guest-avatar { width: 96rpx; height: 96rpx; border-radius: 50%; background: rgba(255,255,255,0.2); display: flex; align-items: center; justify-content: center; margin-right: 24rpx; flex-shrink: 0; }
.guest-icon { font-size: 40rpx; }
.guest-info { flex: 1; }
.guest-name { font-size: 30rpx; font-weight: 600; color: #FFFFFF; }
.guest-hint { font-size: 22rpx; color: rgba(255,255,255,0.7); margin-top: 4rpx; }
.menu-area { padding: 0 32rpx 32rpx; margin-top: -40rpx; }
.menu-group { background: #FFFFFF; border-radius: var(--radius-lg); overflow: hidden; margin-bottom: 24rpx; box-shadow: var(--shadow-sm); }
.menu-item { display: flex; align-items: center; padding: 28rpx 32rpx; border-bottom: 1rpx solid var(--color-border); }
.menu-item:last-child { border-bottom: none; }
.menu-item:active { background: #F9FAFB; }
.menu-icon-wrap { width: 60rpx; height: 60rpx; border-radius: var(--radius-md); display: flex; align-items: center; justify-content: center; margin-right: 20rpx; flex-shrink: 0; }
.menu-icon { font-size: 28rpx; }
.menu-text { flex: 1; font-size: 28rpx; color: var(--color-text); font-weight: 500; }
.menu-arrow { font-size: 32rpx; color: #D1D5DB; }
.wrap-blue { background: #EEF2FF; }
.wrap-purple { background: #F5F3FF; }
.wrap-green { background: #ECFDF5; }
.wrap-orange { background: #FFF7ED; }
.wrap-gray { background: #F3F4F6; }
.logout-wrap { margin-top: 8rpx; }
.logout-btn { background: #FFFFFF; color: var(--color-error); font-size: 28rpx; font-weight: 500; border-radius: var(--radius-md); height: 88rpx; line-height: 88rpx; border: 2rpx solid #FECACA; }
.logout-btn:active { background: #FEF2F2; transform: scale(0.96); }
</style>
<template>
<view class="page fade-in">
<!-- 个人中心 -->
<view class="header" v-if="isLoggedIn">
<view class="profile-section">
<image class="avatar" :src="userInfo.avatar || '/static/avatar-default.png'" mode="aspectFill" />
<view class="profile-info">
<text class="nickname">{{ userInfo.nickname || '未设置昵称' }}</text>
<text class="user-id">ID: {{ maskedId }}</text>
<view class="plan-badge">{{ userInfo.plan || '免费版' }}</view>
</view>
<text class="header-arrow"></text>
</view>
<view class="stats-bar">
<view class="stat">
<text class="stat-num">{{ stats.interviewCount || 0 }}</text>
<text class="stat-label">模拟面试</text>
</view>
<view class="stat-divider"></view>
<view class="stat">
<text class="stat-num">{{ stats.avgScore || '--' }}</text>
<text class="stat-label">平均得分</text>
</view>
<view class="stat-divider"></view>
<view class="stat">
<text class="stat-num">{{ stats.completedCount || 0 }}</text>
<text class="stat-label">已完成</text>
</view>
</view>
</view>
<view class="header header-guest" v-else @click="goLogin">
<view class="guest-box">
<view class="guest-avatar"><text class="guest-icon">👤</text></view>
<view class="guest-info">
<text class="guest-name">未登录 / 点击登录</text>
</view>
<text class="header-arrow"></text>
</view>
</view>
<!-- 菜单列表 -->
<view class="menu-area">
<view class="menu-group">
<view class="menu-item" @click="requireLogin(goCareer, '择业顾问')">
<view class="menu-icon-wrap wrap-teal"><text class="menu-icon">🧭</text></view>
<text class="menu-text">择业顾问</text>
<text class="menu-tag">NEW</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="requireLogin(goHistory, '面试记录')">
<view class="menu-icon-wrap wrap-blue"><text class="menu-icon">📋</text></view>
<text class="menu-text">面试记录</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="requireLogin(goReviewReview, '面试复盘')">
<view class="menu-icon-wrap wrap-orange"><text class="menu-icon">🎙</text></view>
<text class="menu-text">面试复盘</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="goVip">
<view class="menu-icon-wrap wrap-purple"><text class="menu-icon">💎</text></view>
<text class="menu-text">会员中心</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="requireLogin(goResume, '我的简历')">
<view class="menu-icon-wrap wrap-green"><text class="menu-icon">📄</text></view>
<text class="menu-text">我的简历</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" @click="requireLogin(goShare, '我的分享')">
<view class="menu-icon-wrap wrap-orange"><text class="menu-icon">📤</text></view>
<text class="menu-text">我的分享</text>
<text class="menu-arrow"></text>
</view>
</view>
<view class="menu-group">
<view class="menu-item" @click="goAbout">
<view class="menu-icon-wrap wrap-gray"><text class="menu-icon"></text></view>
<text class="menu-text">关于</text>
<text class="menu-arrow"></text>
</view>
<view class="menu-item" v-if="isAdmin" @click="goAdmin">
<view class="menu-icon-wrap wrap-gray"><text class="menu-icon"></text></view>
<text class="menu-text">管理后台</text>
<text class="menu-arrow"></text>
</view>
</view>
<view class="logout-wrap" v-if="isLoggedIn">
<button class="logout-btn" @click="doLogout">退出登录</button>
</view>
</view>
</view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { api } from '../../config'
const userInfo = ref({})
const isAdmin = ref(false)
const stats = ref({ interviewCount: 0, avgScore: '--', completedCount: 0 })
const token = ref('')
const isLoggedIn = computed(() => !!token.value)
const maskedId = computed(() => {
const id = userInfo.value.id || ''
return id.length > 6 ? `****${id.slice(-6)}` : id || '--'
})
const refreshState = () => {
token.value = uni.getStorageSync('token') || ''
if (!token.value) return
try { const s = uni.getStorageSync('userInfo'); if (s) userInfo.value = JSON.parse(s) } catch(e) {}
loadStats()
checkAdmin()
fetchUserInfo()
}
const fetchUserInfo = async () => {
try {
const res = await uni.request({ url: api('/user/info'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
if (res.statusCode === 200 && res.data) {
userInfo.value = res.data
uni.setStorageSync('userInfo', JSON.stringify(res.data))
}
} catch(e) { /* silent */ }
}
onMounted(refreshState)
onShow(refreshState)
const loadStats = async () => {
try {
const res = await uni.request({ url: api('/interview/stats/mine'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
if (res.statusCode === 200) stats.value = res.data
} catch(e) { console.error(e) }
}
const requireLogin = (action, name) => {
if (isLoggedIn.value) { action(); return }
uni.showModal({
title: '请先登录',
content: `需要登录后才能使用${name}功能`,
confirmText: '去登录',
success: (r) => { if (r.confirm) uni.navigateTo({ url: '/pages/login/login' }) }
})
}
const checkAdmin = () => {
isAdmin.value = userInfo.value.role === 'admin'
}
const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
const goCareer = () => uni.navigateTo({ url: '/pages/career/career' })
const goHistory = () => uni.switchTab({ url: '/pages/history/history' })
const goReviewReview = () => uni.navigateTo({ url: '/pages/review/review' })
const goVip = () => uni.navigateTo({ url: '/pages/member/member' })
const goResume = () => uni.navigateTo({ url: '/pages/resume/resume' })
const goShare = () => uni.navigateTo({ url: '/pages/share/share' })
const goAdmin = () => uni.navigateTo({ url: '/pages/admin/admin' })
const goAbout = () => uni.navigateTo({ url: '/pages/about/about' })
const doLogout = () => {
uni.showModal({
title: '退出登录', content: '确定要退出登录吗?',
success: (r) => { if (r.confirm) { uni.removeStorageSync('token'); uni.removeStorageSync('userInfo'); token.value = '' } }
})
}
</script>
<style scoped>
.page { height: 100%; overflow-y: auto; background: var(--color-bg); }
.header {
background: linear-gradient(135deg, var(--color-gradient-start) 0%, var(--color-gradient-mid) 50%, var(--color-gradient-end) 100%);
padding: 48rpx 32rpx 72rpx; border-radius: 0 0 48rpx 48rpx; min-height: 90rpx;
}
.profile-section { display: flex; align-items: center; margin-bottom: 36rpx; }
.avatar { width: 104rpx; height: 104rpx; border-radius: 50%; margin-right: 24rpx; border: 3rpx solid rgba(255,255,255,0.4); flex-shrink: 0; }
.profile-info { flex: 1; display: flex; flex-direction: column; }
.nickname { font-size: 34rpx; font-weight: 700; color: #FFFFFF; }
.plan-badge { font-size: 20rpx; color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.2); padding: 4rpx 14rpx; border-radius: 8rpx; align-self: flex-start; margin-top: 8rpx; }
.user-id { font-size: 20rpx; color: rgba(255,255,255,0.5); margin-top: 4rpx; }
.header-arrow { font-size: 36rpx; color: rgba(255,255,255,0.5); }
.stats-bar { display: flex; align-items: center; background: rgba(255,255,255,0.15); border-radius: var(--radius-lg); padding: 24rpx 0; }
.stat { flex: 1; display: flex; flex-direction: column; align-items: center; }
.stat-num { font-size: 34rpx; font-weight: 700; color: #FFFFFF; }
.stat-label { font-size: 20rpx; color: rgba(255,255,255,0.7); margin-top: 6rpx; }
.stat-divider { width: 1rpx; height: 44rpx; background: rgba(255,255,255,0.2); }
.header-guest { padding: 36rpx 32rpx 72rpx; min-height: 90rpx; }
.guest-box { display: flex; align-items: center; }
.guest-avatar { width: 96rpx; height: 96rpx; border-radius: 50%; background: rgba(255,255,255,0.2); display: flex; align-items: center; justify-content: center; margin-right: 24rpx; flex-shrink: 0; }
.guest-icon { font-size: 40rpx; }
.guest-info { flex: 1; }
.guest-name { font-size: 30rpx; font-weight: 600; color: #FFFFFF; }
.menu-area { padding: 0 32rpx 32rpx; margin-top: -40rpx; }
.menu-group { background: #FFFFFF; border-radius: var(--radius-lg); overflow: hidden; margin-bottom: 24rpx; box-shadow: var(--shadow-sm); }
.menu-item { display: flex; align-items: center; padding: 28rpx 32rpx; border-bottom: 1rpx solid var(--color-border); }
.menu-item:last-child { border-bottom: none; }
.menu-item:active { background: #F9FAFB; }
.menu-icon-wrap { width: 60rpx; height: 60rpx; border-radius: var(--radius-md); display: flex; align-items: center; justify-content: center; margin-right: 20rpx; flex-shrink: 0; }
.menu-icon { font-size: 28rpx; }
.menu-text { flex: 1; font-size: 28rpx; color: var(--color-text); font-weight: 500; }
.menu-tag { font-size: 18rpx; color: #fff; background: var(--color-primary); padding: 2rpx 12rpx; border-radius: 20rpx; margin-right: 12rpx; }
.menu-arrow { font-size: 32rpx; color: #D1D5DB; }
.wrap-blue { background: #EEF2FF; }
.wrap-purple { background: #F5F3FF; }
.wrap-green { background: #ECFDF5; }
.wrap-orange { background: #FFF7ED; }
.wrap-gray { background: #F3F4F6; }
.wrap-teal { background: #E6FFFA; }
.logout-wrap { margin-top: 8rpx; }
.logout-btn { background: #FFFFFF; color: var(--color-error); font-size: 28rpx; font-weight: 500; border-radius: var(--radius-md); height: 88rpx; line-height: 88rpx; border: 2rpx solid #FECACA; }
.logout-btn:active { background: #FEF2F2; transform: scale(0.96); }
</style>
+16 -1
View File
@@ -22,7 +22,7 @@ async function request<T = any>(url: string, method: string = 'POST', data?: any
}
}
export const apiService = {
const apiService = {
user: {
sendCode: (phone: string) => request(API_ENDPOINTS.USER.SEND_CODE, 'POST', { phone }),
login: (phone: string, code: string) => request(API_ENDPOINTS.USER.LOGIN, 'POST', { phone, code }),
@@ -90,6 +90,21 @@ export const apiService = {
records: () => request(API_ENDPOINTS.SHARE.RECORDS, 'GET', undefined, true),
visitors: () => request(API_ENDPOINTS.SHARE.VISITORS, 'GET', undefined, true),
},
review: {
list: (page = 1, limit = 20) =>
request(`${API_ENDPOINTS.REVIEW.LIST}?page=${page}&limit=${limit}`, 'GET', undefined, true),
detail: (id: string) => request(API_ENDPOINTS.REVIEW.DETAIL(id), 'GET', undefined, true),
delete: (id: string) => request(API_ENDPOINTS.REVIEW.DELETE(id), 'DELETE', undefined, true),
submitText: (position: string, text: string, company?: string) =>
request(API_ENDPOINTS.REVIEW.TEXT, 'POST', { position, text, company: company || '' }, true),
},
career: {
analyze: (profile: { major: string; grade?: string; interests?: string; gpa?: string; goal?: string }) =>
request(API_ENDPOINTS.CAREER.ANALYZE, 'POST', profile, true),
chat: (message: string, history: { role: string; content: string }[]) =>
request(API_ENDPOINTS.CAREER.CHAT, 'POST', { message, history }, true),
positions: () => request(API_ENDPOINTS.CAREER.POSITIONS, 'GET', undefined, true),
},
}
export default apiService