Compare commits
11 Commits
a622afd118
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 4cd889c081 | |||
| 96c367e0f8 | |||
| 5a49d15696 | |||
| 07c6557454 | |||
| 18c50726cd | |||
| 4fa620f0a2 | |||
| 112884a504 | |||
| 93ab79d200 | |||
| 8191cf4b41 | |||
| 6fe84b6ef8 | |||
| 087fb1d400 |
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
# 职引 (ZhiYin) — AGENTS.md
|
||||
|
||||
> AI 模拟面试教练,专注校招。NestJS + uni-app(Vue3) + MongoDB。
|
||||
|
||||
---
|
||||
|
||||
## 一、项目结构
|
||||
|
||||
```
|
||||
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/ # 19 个模块(详见下文)
|
||||
├── zhiyin-app/ # uni-app 3.x 前端 (H5 + 微信小程序)
|
||||
│ └── src/
|
||||
│ ├── pages/ # 18 个页面 (pages.json 路由)
|
||||
│ ├── services/api.ts # API 调用封装 (uni.request)
|
||||
│ ├── config.ts # 端点定义 + api() 辅助函数
|
||||
│ └── App.vue # 设计 Token + 全局样式
|
||||
└── docs/ # 产品/架构/部署/路线图文档
|
||||
```
|
||||
|
||||
### 后端模块清单
|
||||
|
||||
| 模块 | 职责 |
|
||||
|------|------|
|
||||
| `user` | 手机/邮箱/密码/微信登录, JWT, 配额 |
|
||||
| `interview` | AI 面试核心(多轮对话 + 评分 + 报告 + 进度) |
|
||||
| `ai` | AI 调用封装(deepseek-v4-flash 主 + step-3.5-flash 备) |
|
||||
| `analyze` | 简历诊断 / 优化 / 技能缺口分析 |
|
||||
| `resume` | 简历 CRUD |
|
||||
| `member` | 会员套餐 / 权益扣减 |
|
||||
| `payment` | 微信支付 v3(Native + JSAPI + 回调) |
|
||||
| `progress` | 进步轨迹雷达图 / 打卡日历 / 行业基准 / 岗位匹配 |
|
||||
| `contribution` | 面经贡献 + 公司题库(数据飞轮核心) |
|
||||
| `schedule` | 定时任务:VIP 过期降级、每日一题推送、微信 token 刷新 |
|
||||
| `share` | 分享链接生成 / 访问追踪 / 积分奖励 |
|
||||
| `tts` | 语音合成(TTS) |
|
||||
| `admin` | 管理后台 API |
|
||||
| `positions` | 热门岗位维护 |
|
||||
| `interview-review` | 面试复盘(音频上传 -> whisper.cpp ASR -> AI 评析 -> 口语分析) |
|
||||
| `upload` | 文件上传(PDF/图片) |
|
||||
| `email` | 邮件发送 |
|
||||
| `daily-question` | 每日一题 API |
|
||||
| `schemas/` | 共享 Schema(pricing 定价、site-config、company-bank 等) |
|
||||
|
||||
### 前端页面(3 Tab + 16 子页)
|
||||
|
||||
- **Tab1 面试**: pages/index/index → interview → report
|
||||
- **Tab2 面经**: pages/history/history → contribute → company-bank
|
||||
- **Tab3 我的**: pages/user/user → login/member/progress/resume/review/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
|
||||
# 路径: backend/
|
||||
npm run start:dev # 开发模式(watch)
|
||||
npm run build # 编译到 dist/
|
||||
npm test # 单元测试(43 个,jest --forceExit --detectOpenHandles)
|
||||
npm run test:e2e # 集成测试(11 个,需 MongoDB 运行)
|
||||
npm run test:cov # 覆盖率报告
|
||||
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/
|
||||
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"}'
|
||||
```
|
||||
|
||||
### 小程序上传
|
||||
```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 1(MVP 上线)进行中
|
||||
|
||||
| 阶段 | 状态 | 关键交付 |
|
||||
|------|------|---------|
|
||||
| Phase 0: 战略升级 | ✅ 完成 | 定价重构(免费 + ¥19.9/月),三层壁垒设计 |
|
||||
| Phase 0.5: 壁垒构建 | ✅ 完成 | 数据飞轮(面经贡献+题库),留存入围(进步轨迹+打卡日历+每日一题) |
|
||||
| Phase 1: MVP 上线 | 🚧 当前 | 小程序审核提交、微信登录联调、生产部署、100 人内测 |
|
||||
| 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
|
||||
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
|
||||
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磁场
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 八、技术细节与坑
|
||||
|
||||
1. **DOMMatrix polyfill**: `main.ts` 顶部有 pdf-parse 所需的浏览器 API polyfill(DOMMatrix / 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. **验证码**: 开发模式下手机验证码固定为 `123456`(`user.service.ts` 中实现),生产环境需移除
|
||||
8. **MongoDB**: 8 个核心集合 + 2 个分享集合
|
||||
|
||||
---
|
||||
|
||||
## 九、交付检查清单(每次实施/修改后执行)
|
||||
|
||||
### 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`
|
||||
@@ -25,6 +25,8 @@ import { DailyQuestionModule } from './modules/daily-question/daily-question.mod
|
||||
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'
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin'
|
||||
|
||||
@@ -38,7 +40,7 @@ const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin
|
||||
}),
|
||||
ThrottlerModule.forRoot([{
|
||||
ttl: 60000,
|
||||
limit: 10,
|
||||
limit: 100,
|
||||
}]),
|
||||
NestScheduleModule.forRoot(),
|
||||
UserModule,
|
||||
@@ -58,6 +60,8 @@ const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin
|
||||
ScheduleModule,
|
||||
TtsModule,
|
||||
PricingModule,
|
||||
ShareModule,
|
||||
InterviewReviewModule,
|
||||
],
|
||||
providers: [
|
||||
JwtStrategy,
|
||||
|
||||
@@ -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'
|
||||
@@ -6,9 +6,12 @@ import { AdminGuard } from '../../common/guards/admin.guard'
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator'
|
||||
import { User, UserDocument } from '../user/user.schema'
|
||||
import { Interview, InterviewDocument } from '../interview/interview.schema'
|
||||
import { Resume, ResumeDocument } from '../resume/resume.schema'
|
||||
import { PaymentOrder, PaymentOrderDocument } from '../payment/payment-order.schema'
|
||||
import { SiteConfig, SiteConfigDocument } from '../schemas/site-config.schema'
|
||||
import { ShareRecord, ShareRecordDocument, ShareVisit, ShareVisitDocument } from '../share/share.schema'
|
||||
import { QuotaService } from '../user/quota.service'
|
||||
import { PricingService } from '../schemas/pricing.service'
|
||||
import { WechatPayService } from '../payment/wechat-pay.service'
|
||||
|
||||
const VIP_DURATION_DAYS = 30
|
||||
@@ -21,7 +24,11 @@ export class AdminController {
|
||||
@InjectModel(Interview.name) private interviewModel: Model<InterviewDocument>,
|
||||
@InjectModel(PaymentOrder.name) private orderModel: Model<PaymentOrderDocument>,
|
||||
@InjectModel(SiteConfig.name) private configModel: Model<SiteConfigDocument>,
|
||||
@InjectModel(ShareRecord.name) private shareModel: Model<ShareRecordDocument>,
|
||||
@InjectModel(ShareVisit.name) private shareVisitModel: Model<ShareVisitDocument>,
|
||||
@InjectModel(Resume.name) private resumeModel: Model<ResumeDocument>,
|
||||
private quotaService: QuotaService,
|
||||
private pricingService: PricingService,
|
||||
private wechatPay: WechatPayService,
|
||||
) {}
|
||||
|
||||
@@ -38,13 +45,28 @@ export class AdminController {
|
||||
|
||||
@Get('overview')
|
||||
async overview() {
|
||||
const [userCount, interviewCount, todayUsers, todayInterviews] = await Promise.all([
|
||||
const [
|
||||
userCount, interviewCount, todayUsers, todayInterviews,
|
||||
resumeCount, paidDownloadCount,
|
||||
planStats,
|
||||
] = await Promise.all([
|
||||
this.userModel.countDocuments().exec(),
|
||||
this.interviewModel.countDocuments().exec(),
|
||||
this.userModel.countDocuments({ createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }).exec(),
|
||||
this.interviewModel.countDocuments({ createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }).exec(),
|
||||
this.resumeModel.countDocuments().exec(),
|
||||
this.resumeModel.countDocuments({ paidDownload: true }).exec(),
|
||||
this.userModel.aggregate([
|
||||
{ $group: { _id: '$plan', count: { $sum: 1 } } },
|
||||
]).exec(),
|
||||
])
|
||||
return { userCount, interviewCount, todayUsers, todayInterviews }
|
||||
const planBreakdown: Record<string, number> = {}
|
||||
planStats.forEach(p => { planBreakdown[p._id || 'free'] = p.count })
|
||||
return {
|
||||
userCount, interviewCount, todayUsers, todayInterviews,
|
||||
resumeCount, paidDownloadCount,
|
||||
planBreakdown,
|
||||
}
|
||||
}
|
||||
|
||||
@Get('users')
|
||||
@@ -70,7 +92,12 @@ export class AdminController {
|
||||
async getInterviews(@Query('page') page = '1', @Query('limit') limit = '20') {
|
||||
const skip = (Math.max(1, +page) - 1) * +limit
|
||||
const [interviews, total] = await Promise.all([
|
||||
this.interviewModel.find().sort({ createdAt: -1 }).skip(skip).limit(+limit).populate('userId', 'phone nickname').lean().exec(),
|
||||
this.interviewModel.find()
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(skip).limit(+limit)
|
||||
.populate('userId', 'phone nickname')
|
||||
.select('position status totalScore questionCount fillerScore fillerDensity summary createdAt')
|
||||
.lean().exec(),
|
||||
this.interviewModel.countDocuments().exec(),
|
||||
])
|
||||
return { interviews, total, page: +page }
|
||||
@@ -80,14 +107,135 @@ export class AdminController {
|
||||
async setVip(@Body('userId') targetUserId: string) {
|
||||
const user = await this.userModel.findById(targetUserId).exec()
|
||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
const pricing = await this.pricingService.getConfig()
|
||||
const credits = pricing.plans?.growth?.credits || { interview: 999, resumeOptimize: 20, resumeDownload: 10 }
|
||||
const expireAt = new Date()
|
||||
expireAt.setDate(expireAt.getDate() + VIP_DURATION_DAYS)
|
||||
expireAt.setDate(expireAt.getDate() + (pricing.plans?.growth?.durationDays || VIP_DURATION_DAYS))
|
||||
user.plan = 'growth'
|
||||
user.vipExpireAt = expireAt
|
||||
await this.quotaService.setPlanQuota(targetUserId, 'growth', { interview: 999, resumeOptimize: 20, resumeDownload: 10 })
|
||||
await this.quotaService.setPlanQuota(targetUserId, 'growth', credits)
|
||||
return { success: true, plan: 'growth', expireAt }
|
||||
}
|
||||
|
||||
@Post('user/credits')
|
||||
async adjustCredits(@Body('userId') userId: string, @Body('type') type: string, @Body('amount') amount: number) {
|
||||
if (!userId || !type || amount === undefined) {
|
||||
throw new HttpException('参数不完整', HttpStatus.BAD_REQUEST)
|
||||
}
|
||||
const validTypes = ['interviewCredits', 'resumeOptimizeCredits', 'resumeDownloadCredits', 'shareCredits']
|
||||
if (!validTypes.includes(type)) {
|
||||
throw new HttpException('无效的额度类型', HttpStatus.BAD_REQUEST)
|
||||
}
|
||||
const result = await this.userModel.findByIdAndUpdate(
|
||||
userId,
|
||||
{ $set: { [type]: Math.max(0, Math.round(amount)) } },
|
||||
).exec()
|
||||
if (!result) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
@Get('share-records')
|
||||
async getShareRecords(@Query('page') page = '1', @Query('limit') limit = '20') {
|
||||
const skip = (Math.max(1, +page) - 1) * +limit
|
||||
const [list, total] = await Promise.all([
|
||||
this.shareModel.aggregate([
|
||||
{ $sort: { createdAt: -1 } },
|
||||
{ $skip: skip },
|
||||
{ $limit: +limit },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'users',
|
||||
localField: 'userId',
|
||||
foreignField: '_id',
|
||||
as: 'sharer',
|
||||
},
|
||||
},
|
||||
{ $unwind: { path: '$sharer', preserveNullAndEmptyArrays: true } },
|
||||
{
|
||||
$project: {
|
||||
shareCode: 1,
|
||||
type: 1,
|
||||
title: 1,
|
||||
visitCount: 1,
|
||||
creditedCount: 1,
|
||||
isActive: 1,
|
||||
createdAt: 1,
|
||||
sharer: { nickname: '$sharer.nickname', phone: '$sharer.phone', _id: '$sharer._id' },
|
||||
},
|
||||
},
|
||||
]).exec(),
|
||||
this.shareModel.countDocuments().exec(),
|
||||
])
|
||||
return { list, total, page: +page }
|
||||
}
|
||||
|
||||
@Get('share-visitors')
|
||||
async getShareVisitors(@Query('page') page = '1', @Query('limit') limit = '20') {
|
||||
const skip = (Math.max(1, +page) - 1) * +limit
|
||||
const [list, total] = await Promise.all([
|
||||
this.shareVisitModel.aggregate([
|
||||
{ $sort: { createdAt: -1 } },
|
||||
{ $skip: skip },
|
||||
{ $limit: +limit },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'users',
|
||||
localField: 'sharerId',
|
||||
foreignField: '_id',
|
||||
as: 'sharer',
|
||||
},
|
||||
},
|
||||
{ $unwind: { path: '$sharer', preserveNullAndEmptyArrays: true } },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'users',
|
||||
localField: 'visitorUserId',
|
||||
foreignField: '_id',
|
||||
as: 'visitorUser',
|
||||
},
|
||||
},
|
||||
{ $unwind: { path: '$visitorUser', preserveNullAndEmptyArrays: true } },
|
||||
{
|
||||
$project: {
|
||||
credited: 1,
|
||||
creditedAt: 1,
|
||||
createdAt: 1,
|
||||
sharer: { nickname: '$sharer.nickname', phone: '$sharer.phone' },
|
||||
visitor: { nickname: { $ifNull: ['$visitorUser.nickname', '匿名'] }, phone: { $ifNull: ['$visitorUser.phone', ''] } },
|
||||
},
|
||||
},
|
||||
]).exec(),
|
||||
this.shareVisitModel.countDocuments().exec(),
|
||||
])
|
||||
return { list, total, page: +page }
|
||||
}
|
||||
|
||||
@Get('resumes')
|
||||
async getResumes(@Query('page') page = '1', @Query('limit') limit = '20') {
|
||||
const skip = (Math.max(1, +page) - 1) * +limit
|
||||
const [list, total] = await Promise.all([
|
||||
this.resumeModel.find()
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(skip).limit(+limit)
|
||||
.populate('userId', 'phone nickname')
|
||||
.select('title targetPosition version paidDownload createdAt')
|
||||
.lean().exec(),
|
||||
this.resumeModel.countDocuments().exec(),
|
||||
])
|
||||
return { list, total, page: +page }
|
||||
}
|
||||
|
||||
@Get('user/:id')
|
||||
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([
|
||||
this.interviewModel.find({ userId: id }).sort({ createdAt: -1 }).limit(10).select('position status totalScore questionCount createdAt').lean().exec(),
|
||||
this.resumeModel.find({ userId: id }).sort({ createdAt: -1 }).limit(10).select('title targetPosition version paidDownload createdAt').lean().exec(),
|
||||
])
|
||||
return { user, interviews, resumes }
|
||||
}
|
||||
|
||||
@Get('admins')
|
||||
async getAdmins() {
|
||||
const admins = await this.userModel.find({ role: 'admin' }).select('phone nickname email createdAt isSystemAdmin').lean().exec()
|
||||
@@ -130,14 +278,22 @@ export class AdminController {
|
||||
if (order.type === 'membership') {
|
||||
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 expireAt = new Date()
|
||||
expireAt.setDate(expireAt.getDate() + VIP_DURATION_DAYS)
|
||||
expireAt.setDate(expireAt.getDate() + (pricing.plans?.growth?.durationDays || VIP_DURATION_DAYS))
|
||||
user.plan = 'growth'
|
||||
user.vipExpireAt = expireAt
|
||||
await this.quotaService.setPlanQuota(order.userId, 'growth', { interview: 999, resumeOptimize: 20, resumeDownload: 10 })
|
||||
await this.quotaService.setPlanQuota(order.userId, 'growth', credits)
|
||||
}
|
||||
} else {
|
||||
const credits = { interview: 1, optimize: 1, download: 1 }[order.type]
|
||||
const pricing = await this.pricingService.getConfig()
|
||||
const creditMap: Record<string, number> = {
|
||||
interview: pricing.interview?.creditsPerPurchase || 1,
|
||||
optimize: pricing.resumeOptimize?.creditsPerPurchase || 1,
|
||||
download: pricing.resumeDownload?.creditsPerPurchase || 1,
|
||||
}
|
||||
const credits = creditMap[order.type]
|
||||
if (credits) {
|
||||
await this.quotaService.grantCredits(order.userId, order.type as any, credits)
|
||||
}
|
||||
@@ -179,6 +335,7 @@ export class AdminController {
|
||||
{ key: 'pricing', value: body, description: '定价配置' },
|
||||
{ upsert: true },
|
||||
).exec()
|
||||
this.pricingService.invalidateCache()
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import { PaymentOrder, PaymentOrderSchema } from '../payment/payment-order.schem
|
||||
import { WechatPayService } from '../payment/wechat-pay.service'
|
||||
import { AdminGuard } from '../../common/guards/admin.guard'
|
||||
import { SiteConfig, SiteConfigSchema } from '../schemas/site-config.schema'
|
||||
import { ShareRecord, ShareRecordSchema, ShareVisit, ShareVisitSchema } from '../share/share.schema'
|
||||
import { Resume, ResumeSchema } from '../resume/resume.schema'
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -16,6 +18,9 @@ import { SiteConfig, SiteConfigSchema } from '../schemas/site-config.schema'
|
||||
{ name: Interview.name, schema: InterviewSchema },
|
||||
{ name: PaymentOrder.name, schema: PaymentOrderSchema },
|
||||
{ name: SiteConfig.name, schema: SiteConfigSchema },
|
||||
{ name: ShareRecord.name, schema: ShareRecordSchema },
|
||||
{ name: ShareVisit.name, schema: ShareVisitSchema },
|
||||
{ name: Resume.name, schema: ResumeSchema },
|
||||
]),
|
||||
UserModule,
|
||||
],
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -107,7 +107,7 @@ ${conversationHistory}
|
||||
if (aiMsg?.content) {
|
||||
try {
|
||||
const tts = await this.ttsService.synthesize(aiMsg.content)
|
||||
return { ...base, ttsHash: tts.hash, ttsDurationMs: tts.durationMs }
|
||||
return { ...base, ttsHash: tts.hash, ttsDurationMs: tts.durationMs, ttsAmplitude: tts.amplitudeData }
|
||||
} catch {
|
||||
// TTS failure is non-critical, return without audio
|
||||
}
|
||||
|
||||
@@ -168,6 +168,8 @@ export class PaymentController {
|
||||
order.wxTransactionId = wxTransactionId
|
||||
order.description = `${decrypted.trade_type || ''} 支付成功`
|
||||
await order.save()
|
||||
} else {
|
||||
return { code: 'SUCCESS', message: '已处理' }
|
||||
}
|
||||
|
||||
if (order.type === 'membership') {
|
||||
@@ -260,6 +262,15 @@ export class PaymentController {
|
||||
return { success: true, plan: order.plan }
|
||||
}
|
||||
|
||||
// For product orders, check if already activated via callback
|
||||
const user = await this.userModel.findById(userId).exec()
|
||||
if (user && order.type === 'interview' && (user.interviewCredits || 0) > 0) {
|
||||
return { success: true, type: order.type, alreadyActivated: true }
|
||||
}
|
||||
if (user && order.type === 'optimize' && (user.resumeOptimizeCredits || 0) > 0) {
|
||||
return { success: true, type: order.type, alreadyActivated: true }
|
||||
}
|
||||
|
||||
await this.activateProduct(order)
|
||||
return { success: true, type: order.type }
|
||||
}
|
||||
|
||||
@@ -21,8 +21,11 @@ export class WechatPayService {
|
||||
this.logger.warn('微信支付配置不完整,支付功能不可用')
|
||||
}
|
||||
const certDir = path.resolve(__dirname, '../../certs')
|
||||
if (!fs.existsSync(certDir)) {
|
||||
this.logger.error(`证书目录不存在: ${certDir}`)
|
||||
return
|
||||
}
|
||||
this.privateKey = fs.readFileSync(path.join(certDir, 'apiclient_key.pem'), 'utf8')
|
||||
// 从证书中提取序列号
|
||||
const cert = fs.readFileSync(path.join(certDir, 'apiclient_cert.pem'), 'utf8')
|
||||
const certObj = new crypto.X509Certificate(cert)
|
||||
this.mchSerialNo = certObj.serialNumber
|
||||
@@ -122,6 +125,10 @@ export class WechatPayService {
|
||||
// 1. 验签
|
||||
const message = `${wechatTimestamp}\n${wechatNonce}\n${JSON.stringify(body)}\n`
|
||||
const certDir = path.resolve(__dirname, '../../certs')
|
||||
if (!fs.existsSync(certDir)) {
|
||||
this.logger.error(`证书目录不存在: ${certDir}`)
|
||||
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')
|
||||
|
||||
@@ -31,13 +31,18 @@ export class ResumePdfService {
|
||||
}
|
||||
}
|
||||
|
||||
private escapeHtml(str: string): string {
|
||||
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||
.replace(/"/g, '"').replace(/'/g, ''')
|
||||
}
|
||||
|
||||
private buildHtml(params: {
|
||||
title: string
|
||||
content: string
|
||||
targetPosition?: string
|
||||
userName?: string
|
||||
}): string {
|
||||
const contentHtml = params.content
|
||||
const contentHtml = this.escapeHtml(params.content)
|
||||
.replace(/\n/g, '<br>')
|
||||
.replace(/### (.+)/g, '<h3>$1</h3>')
|
||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||
@@ -66,8 +71,8 @@ export class ResumePdfService {
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<h1>${params.title}</h1>
|
||||
<div class="subtitle">${params.targetPosition ? `目标岗位: ${params.targetPosition}` : ''}</div>
|
||||
<h1>${this.escapeHtml(params.title)}</h1>
|
||||
<div class="subtitle">${params.targetPosition ? `目标岗位: ${this.escapeHtml(params.targetPosition)}` : ''}</div>
|
||||
<div class="content">${contentHtml}</div>
|
||||
<div class="footer">由 AI磁场·职引 生成</div>
|
||||
</div>
|
||||
|
||||
@@ -31,13 +31,10 @@ export class ResumeController {
|
||||
@Post(':id/download')
|
||||
async download(@Param('id') id: string, @CurrentUser('userId') userId: string, @Res() res: Response) {
|
||||
const resume = await this.resumeService.getDetail(id, userId)
|
||||
|
||||
const canDownload = await this.quotaService.checkDownload(userId, resume)
|
||||
if (!canDownload) {
|
||||
const canDownload = await this.quotaService.checkAndDeductDownload(userId, resume.paidDownload)
|
||||
if (!canDownload && !resume.paidDownload) {
|
||||
throw new HttpException('请先付费下载', HttpStatus.PAYMENT_REQUIRED)
|
||||
}
|
||||
|
||||
await this.quotaService.deductDownload(userId, resume)
|
||||
if (!resume.paidDownload) {
|
||||
await this.resumeService.markPaid(id, userId)
|
||||
}
|
||||
|
||||
@@ -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 次/月'] },
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Controller, Get, Post, Body, Param, Query, HttpException, HttpStatus, UseGuards } from '@nestjs/common'
|
||||
import { JwtService } from '@nestjs/jwt'
|
||||
import { ShareService } from './share.service'
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator'
|
||||
import { Public } from '../../common/decorators/public.decorator'
|
||||
|
||||
@Controller('share')
|
||||
export class ShareController {
|
||||
constructor(
|
||||
private shareService: ShareService,
|
||||
private jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('create')
|
||||
async create(
|
||||
@CurrentUser('userId') userId: string,
|
||||
@Body() body: { type: string; refId?: string; title?: string; description?: string },
|
||||
) {
|
||||
return this.shareService.create(userId, body)
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Get('visit/:shareCode')
|
||||
async visit(
|
||||
@Param('shareCode') shareCode: string,
|
||||
@Query('visitorId') visitorId?: string,
|
||||
@Query('token') token?: string,
|
||||
) {
|
||||
if (!visitorId) {
|
||||
throw new HttpException('缺少访问者标识', HttpStatus.BAD_REQUEST)
|
||||
}
|
||||
let visitorUserId: string | undefined
|
||||
if (token) {
|
||||
try {
|
||||
const payload = this.jwtService.verify(token) as any
|
||||
visitorUserId = payload.userId
|
||||
} catch {}
|
||||
}
|
||||
return this.shareService.visit(shareCode, visitorId, visitorUserId)
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('stats')
|
||||
async stats(@CurrentUser('userId') userId: string) {
|
||||
return this.shareService.stats(userId)
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('records')
|
||||
async records(
|
||||
@CurrentUser('userId') userId: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
) {
|
||||
return this.shareService.records(userId, Number(page) || 1, Number(pageSize) || 20)
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('visitors')
|
||||
async visitors(
|
||||
@CurrentUser('userId') userId: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
) {
|
||||
return this.shareService.visitors(userId, Number(page) || 1, Number(pageSize) || 20)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Module } from '@nestjs/common'
|
||||
import { JwtModule } from '@nestjs/jwt'
|
||||
import { MongooseModule } from '@nestjs/mongoose'
|
||||
import { ShareController } from './share.controller'
|
||||
import { ShareService } from './share.service'
|
||||
import { ShareRecord, ShareRecordSchema, ShareVisit, ShareVisitSchema } from './share.schema'
|
||||
import { UserModule } from '../user/user.module'
|
||||
import { User, UserSchema } from '../user/user.schema'
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MongooseModule.forFeature([
|
||||
{ name: ShareRecord.name, schema: ShareRecordSchema },
|
||||
{ name: ShareVisit.name, schema: ShareVisitSchema },
|
||||
{ name: User.name, schema: UserSchema },
|
||||
]),
|
||||
UserModule,
|
||||
JwtModule.register({
|
||||
secret: process.env.JWT_SECRET,
|
||||
signOptions: { expiresIn: '7d' },
|
||||
}),
|
||||
],
|
||||
controllers: [ShareController],
|
||||
providers: [ShareService],
|
||||
})
|
||||
export class ShareModule {}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
|
||||
import { Document, Types } from 'mongoose'
|
||||
|
||||
export type ShareRecordDocument = ShareRecord & Document
|
||||
export type ShareVisitDocument = ShareVisit & Document
|
||||
|
||||
@Schema({ timestamps: true })
|
||||
export class ShareRecord {
|
||||
@Prop({ type: Types.ObjectId, ref: 'User', required: true })
|
||||
userId: Types.ObjectId
|
||||
|
||||
@Prop({ required: true, unique: true })
|
||||
shareCode: string
|
||||
|
||||
@Prop({ default: 'app' })
|
||||
type: string
|
||||
|
||||
@Prop({ default: '' })
|
||||
refId: string
|
||||
|
||||
@Prop({ default: '' })
|
||||
title: string
|
||||
|
||||
@Prop({ default: '' })
|
||||
description: string
|
||||
|
||||
@Prop({ default: 'link' })
|
||||
channel: string
|
||||
|
||||
@Prop({ default: 0 })
|
||||
visitCount: number
|
||||
|
||||
@Prop({ default: 0 })
|
||||
creditedCount: number
|
||||
|
||||
@Prop({ default: true })
|
||||
isActive: boolean
|
||||
|
||||
readonly createdAt?: Date
|
||||
readonly updatedAt?: Date
|
||||
}
|
||||
|
||||
@Schema({ timestamps: true })
|
||||
export class ShareVisit {
|
||||
@Prop({ type: Types.ObjectId, ref: 'ShareRecord', required: true })
|
||||
shareId: Types.ObjectId
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'User', required: true })
|
||||
sharerId: Types.ObjectId
|
||||
|
||||
@Prop({ required: true })
|
||||
visitorId: string
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'User' })
|
||||
visitorUserId: Types.ObjectId
|
||||
|
||||
@Prop({ default: false })
|
||||
credited: boolean
|
||||
|
||||
@Prop()
|
||||
creditedAt?: Date
|
||||
|
||||
readonly createdAt?: Date
|
||||
readonly updatedAt?: Date
|
||||
}
|
||||
|
||||
export const ShareRecordSchema = SchemaFactory.createForClass(ShareRecord)
|
||||
export const ShareVisitSchema = SchemaFactory.createForClass(ShareVisit)
|
||||
|
||||
ShareRecordSchema.index({ userId: 1, createdAt: -1 })
|
||||
ShareVisitSchema.index({ shareId: 1, visitorId: 1 }, { unique: true })
|
||||
ShareVisitSchema.index({ sharerId: 1, createdAt: -1 })
|
||||
@@ -0,0 +1,186 @@
|
||||
import * as crypto from 'crypto'
|
||||
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common'
|
||||
import { InjectModel } from '@nestjs/mongoose'
|
||||
import { Model, Types } from 'mongoose'
|
||||
import { ShareRecord, ShareRecordDocument, ShareVisit, ShareVisitDocument } from './share.schema'
|
||||
import { QuotaService } from '../user/quota.service'
|
||||
import { User, UserDocument } from '../user/user.schema'
|
||||
|
||||
const DAILY_LIMIT = 3
|
||||
const LINK_TTL_DAYS = 30
|
||||
|
||||
@Injectable()
|
||||
export class ShareService {
|
||||
private readonly logger = new Logger(ShareService.name)
|
||||
|
||||
constructor(
|
||||
@InjectModel(ShareRecord.name) private shareModel: Model<ShareRecordDocument>,
|
||||
@InjectModel(ShareVisit.name) private visitModel: Model<ShareVisitDocument>,
|
||||
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
||||
private quotaService: QuotaService,
|
||||
) {}
|
||||
|
||||
async create(userId: string, body: { type: string; refId?: string; title?: string; description?: string }) {
|
||||
const shareCode = crypto.randomBytes(4).toString('hex')
|
||||
const record = await this.shareModel.create({
|
||||
userId: new Types.ObjectId(userId),
|
||||
shareCode,
|
||||
type: body.type || 'app',
|
||||
refId: body.refId || '',
|
||||
title: body.title || '我在职引发现了好东西',
|
||||
description: body.description || '快来一起体验吧',
|
||||
})
|
||||
return {
|
||||
shareCode: record.shareCode,
|
||||
shareUrl: `/share/${record.shareCode}`,
|
||||
wechatShareInfo: {
|
||||
title: record.title,
|
||||
description: record.description,
|
||||
path: `/pages/share/share?code=${record.shareCode}`,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async visit(shareCode: string, visitorId: string, visitorUserId?: string) {
|
||||
const share = await this.shareModel.findOne({ shareCode, isActive: true }).exec()
|
||||
if (!share) throw new HttpException('分享链接不存在或已失效', HttpStatus.NOT_FOUND)
|
||||
|
||||
await this.shareModel.findByIdAndUpdate(share._id, { $inc: { visitCount: 1 } }).exec()
|
||||
|
||||
const sharerIdStr = share.userId.toString()
|
||||
if (!visitorUserId || visitorUserId === sharerIdStr) {
|
||||
return { sharer: true, visitorUserId }
|
||||
}
|
||||
|
||||
const existing = await this.visitModel.findOne({
|
||||
shareId: share._id,
|
||||
visitorId,
|
||||
}).exec()
|
||||
if (existing) return { alreadyVisited: true, visitorUserId }
|
||||
|
||||
await this.visitModel.create({
|
||||
shareId: share._id,
|
||||
sharerId: share.userId,
|
||||
visitorId,
|
||||
visitorUserId: new Types.ObjectId(visitorUserId),
|
||||
}).catch(() => {})
|
||||
|
||||
const alreadyCredited = await this.visitModel.findOne({
|
||||
shareId: share._id,
|
||||
visitorId,
|
||||
credited: true,
|
||||
}).exec()
|
||||
if (alreadyCredited) return { credited: true, visitorUserId }
|
||||
|
||||
const todayStart = new Date()
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
|
||||
const todayCredited = await this.visitModel.countDocuments({
|
||||
sharerId: share.userId,
|
||||
credited: true,
|
||||
creditedAt: { $gte: todayStart },
|
||||
}).exec()
|
||||
|
||||
if (todayCredited >= DAILY_LIMIT) return { dailyLimitReached: true, visitorUserId }
|
||||
|
||||
const shareCreditsResult = await this.quotaService.grantShareCredits(sharerIdStr)
|
||||
if (!shareCreditsResult) return { creditFailed: true, visitorUserId }
|
||||
|
||||
await this.visitModel.updateOne(
|
||||
{ shareId: share._id, visitorId },
|
||||
{ $set: { credited: true, creditedAt: new Date() } },
|
||||
).exec()
|
||||
|
||||
await this.shareModel.findByIdAndUpdate(share._id, { $inc: { creditedCount: 1 } }).exec()
|
||||
|
||||
return { credited: true, visitorUserId }
|
||||
}
|
||||
|
||||
async stats(userId: string) {
|
||||
const todayStart = new Date()
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
|
||||
const [totalShares, visitAgg, todayAgg, user] = await Promise.all([
|
||||
this.shareModel.countDocuments({ userId: new Types.ObjectId(userId) }).exec(),
|
||||
this.visitModel.aggregate([
|
||||
{ $match: { sharerId: new Types.ObjectId(userId) } },
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
totalVisits: { $sum: 1 },
|
||||
creditedCount: { $sum: { $cond: ['$credited', 1, 0] } },
|
||||
},
|
||||
},
|
||||
]).exec(),
|
||||
this.visitModel.countDocuments({
|
||||
sharerId: new Types.ObjectId(userId),
|
||||
credited: true,
|
||||
creditedAt: { $gte: todayStart },
|
||||
}).exec(),
|
||||
this.userModel.findById(userId).exec(),
|
||||
])
|
||||
|
||||
return {
|
||||
totalShares,
|
||||
totalVisits: visitAgg[0]?.totalVisits ?? 0,
|
||||
creditedCount: visitAgg[0]?.creditedCount ?? 0,
|
||||
todayCredited: todayAgg,
|
||||
shareCredits: user?.shareCredits ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
async records(userId: string, page = 1, pageSize = 20) {
|
||||
const list = await this.shareModel.find({ userId: new Types.ObjectId(userId) })
|
||||
.sort({ createdAt: -1 })
|
||||
.skip((page - 1) * pageSize)
|
||||
.limit(pageSize)
|
||||
.exec()
|
||||
const total = await this.shareModel.countDocuments({ userId: new Types.ObjectId(userId) }).exec()
|
||||
return {
|
||||
list: list.map(r => ({
|
||||
shareCode: r.shareCode,
|
||||
type: r.type,
|
||||
title: r.title,
|
||||
visitCount: r.visitCount,
|
||||
creditedCount: r.creditedCount,
|
||||
createdAt: r.createdAt,
|
||||
})),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
}
|
||||
}
|
||||
|
||||
async visitors(userId: string, page = 1, pageSize = 20) {
|
||||
const [list, total] = await Promise.all([
|
||||
this.visitModel.aggregate([
|
||||
{ $match: { sharerId: new Types.ObjectId(userId) } },
|
||||
{ $sort: { createdAt: -1 } },
|
||||
{ $skip: (page - 1) * pageSize },
|
||||
{ $limit: pageSize },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'users',
|
||||
localField: 'visitorUserId',
|
||||
foreignField: '_id',
|
||||
as: 'visitorUser',
|
||||
},
|
||||
},
|
||||
{ $unwind: { path: '$visitorUser', preserveNullAndEmptyArrays: true } },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
visitorId: 1,
|
||||
credited: 1,
|
||||
creditedAt: 1,
|
||||
createdAt: 1,
|
||||
nickname: { $ifNull: ['$visitorUser.nickname', '匿名用户'] },
|
||||
avatar: { $ifNull: ['$visitorUser.avatar', ''] },
|
||||
},
|
||||
},
|
||||
]).exec(),
|
||||
this.visitModel.countDocuments({ sharerId: new Types.ObjectId(userId) }).exec(),
|
||||
])
|
||||
return { list, total, page, pageSize }
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,25 @@
|
||||
import { Controller, Get, Post, Body, Param, Res, HttpException, HttpStatus } from '@nestjs/common'
|
||||
import { Controller, Get, Post, Body, Param, Res, HttpException, HttpStatus, UseGuards, UploadedFile, UseInterceptors } from '@nestjs/common'
|
||||
import { FileInterceptor } from '@nestjs/platform-express'
|
||||
import { Response } from 'express'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { execSync } from 'child_process'
|
||||
import { TtsService } from './tts.service'
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
|
||||
import { Public } from '../../common/decorators/public.decorator'
|
||||
|
||||
@Controller('tts')
|
||||
export class TtsController {
|
||||
constructor(private ttsService: TtsService) {}
|
||||
|
||||
@Public()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('synthesize')
|
||||
async synthesize(@Body('text') text: string, @Body('voice') voice?: string) {
|
||||
if (!text || text.length > 500) {
|
||||
throw new HttpException('文本不能为空且不超过500字', HttpStatus.BAD_REQUEST)
|
||||
}
|
||||
const result = await this.ttsService.synthesize(text, voice)
|
||||
return { hash: result.hash, durationMs: result.durationMs }
|
||||
return { hash: result.hash, durationMs: result.durationMs, amplitudeData: result.amplitudeData }
|
||||
}
|
||||
|
||||
@Public()
|
||||
@@ -30,4 +34,36 @@ export class TtsController {
|
||||
res.setHeader('Cache-Control', 'public, max-age=31536000')
|
||||
stream.pipe(res)
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('asr')
|
||||
@UseInterceptors(FileInterceptor('audio', { dest: '/tmp/asr_uploads' }))
|
||||
async recognize(@UploadedFile() file: any) {
|
||||
if (!file) throw new HttpException('请上传音频文件', HttpStatus.BAD_REQUEST)
|
||||
const uploadDir = '/tmp/asr_uploads'
|
||||
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true })
|
||||
const ext = path.extname(file.originalname) || '.mp3'
|
||||
const dest = path.join(uploadDir, file.filename + ext)
|
||||
fs.renameSync(file.path, dest)
|
||||
try {
|
||||
if (process.env.OPENAI_API_KEY) {
|
||||
const result = execSync(
|
||||
`curl -s -X POST https://api.openai.com/v1/audio/transcriptions \
|
||||
-H "Authorization: Bearer ${process.env.OPENAI_API_KEY}" \
|
||||
-H "Content-Type: multipart/form-data" \
|
||||
-F "file=@${dest}" \
|
||||
-F "model=whisper-1" \
|
||||
-F "language=zh"`,
|
||||
{ encoding: 'utf8', timeout: 30000 },
|
||||
)
|
||||
const parsed = JSON.parse(result)
|
||||
if (parsed.text) return { text: parsed.text.trim() }
|
||||
}
|
||||
const whisperResult = execSync(`python3 -c 'import sys, whisper; model = whisper.load_model("tiny"); print(model.transcribe(sys.argv[1], language="zh")["text"].strip())' "${dest}"`, { encoding: 'utf8', timeout: 60000 })
|
||||
if (whisperResult && whisperResult.trim()) {
|
||||
return { text: whisperResult.trim() }
|
||||
}
|
||||
} catch {}
|
||||
return { text: '' }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,19 @@ interface TtsResult {
|
||||
hash: string
|
||||
filePath: string
|
||||
durationMs: number
|
||||
amplitudeData: number[]
|
||||
}
|
||||
|
||||
const VALID_VOICES = new Set([
|
||||
'zh-CN-XiaoxiaoNeural', 'zh-CN-XiaoyiNeural', 'zh-CN-YunjianNeural',
|
||||
'zh-CN-YunxiNeural', 'zh-CN-YunxiaNeural', 'zh-CN-YunyangNeural',
|
||||
'zh-CN-liaoning-XiaobeiNeural', 'zh-CN-shaanxi-XiaoniNeural',
|
||||
])
|
||||
|
||||
function validateVoice(voice: string): void {
|
||||
if (!VALID_VOICES.has(voice)) {
|
||||
throw new Error(`不支持的语音: ${voice}`)
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -23,12 +36,16 @@ export class TtsService {
|
||||
}
|
||||
|
||||
async synthesize(text: string, voice: string = 'zh-CN-XiaoxiaoNeural'): Promise<TtsResult> {
|
||||
validateVoice(voice)
|
||||
const hash = crypto.createHash('md5').update(text + voice).digest('hex')
|
||||
const filePath = path.join(CACHE_DIR, `${hash}.mp3`)
|
||||
|
||||
if (fs.existsSync(filePath)) {
|
||||
const durationMs = await this.getDuration(filePath)
|
||||
return { hash, filePath, durationMs }
|
||||
const amplitudeData = this.loadAmplitudeData(hash)
|
||||
if (amplitudeData) {
|
||||
return { hash, filePath, durationMs, amplitudeData }
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -37,8 +54,9 @@ export class TtsService {
|
||||
{ timeout: 30000 },
|
||||
)
|
||||
const durationMs = await this.getDuration(filePath)
|
||||
const amplitudeData = this.extractAmplitude(filePath, hash)
|
||||
this.logger.log(`TTS generated: hash=${hash} text="${text.slice(0, 40)}..." duration=${durationMs}ms`)
|
||||
return { hash, filePath, durationMs }
|
||||
return { hash, filePath, durationMs, amplitudeData }
|
||||
} catch (e) {
|
||||
this.logger.error(`TTS failed: ${e.message}`)
|
||||
throw e
|
||||
@@ -50,6 +68,46 @@ export class TtsService {
|
||||
return fs.existsSync(filePath) ? filePath : null
|
||||
}
|
||||
|
||||
private extractAmplitude(mp3Path: string, hash: string): number[] {
|
||||
try {
|
||||
const pcmPath = `/tmp/tts-cache/${hash}.pcm`
|
||||
execSync(
|
||||
`ffmpeg -y -i "${mp3Path}" -f s16le -acodec pcm_s16le -ar 16000 -ac 1 "${pcmPath}" 2>/dev/null`,
|
||||
{ timeout: 10000 },
|
||||
)
|
||||
const pcmBuf = fs.readFileSync(pcmPath)
|
||||
const samples = new Int16Array(pcmBuf.buffer, pcmBuf.byteOffset, pcmBuf.byteLength / 2)
|
||||
const chunkSize = Math.floor(16000 * 0.05) // 50ms
|
||||
const amplitudes: number[] = []
|
||||
for (let i = 0; i < samples.length; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, samples.length)
|
||||
let sumSq = 0
|
||||
for (let j = i; j < end; j++) {
|
||||
sumSq += samples[j] * samples[j]
|
||||
}
|
||||
const rms = Math.sqrt(sumSq / (end - i))
|
||||
amplitudes.push(Number((Math.min(1, rms / 16000)).toFixed(4)))
|
||||
}
|
||||
try { fs.unlinkSync(pcmPath) } catch {}
|
||||
const ampPath = `/tmp/tts-cache/${hash}.amp`
|
||||
fs.writeFileSync(ampPath, JSON.stringify(amplitudes))
|
||||
return amplitudes
|
||||
} catch (e) {
|
||||
this.logger.warn(`振幅提取失败: ${e.message}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private loadAmplitudeData(hash: string): number[] | null {
|
||||
try {
|
||||
const ampPath = `/tmp/tts-cache/${hash}.amp`
|
||||
if (!fs.existsSync(ampPath)) return null
|
||||
return JSON.parse(fs.readFileSync(ampPath, 'utf8'))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private escapeText(text: string): string {
|
||||
return text.replace(/"/g, '\\"').replace(/\n/g, ' ').replace(/\r/g, '')
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common'
|
||||
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common'
|
||||
import { InjectModel } from '@nestjs/mongoose'
|
||||
import { Model } from 'mongoose'
|
||||
import { User, UserDocument } from './user.schema'
|
||||
@@ -7,6 +7,8 @@ const FREE_OPTIMIZE_LIMIT = 3
|
||||
|
||||
@Injectable()
|
||||
export class QuotaService {
|
||||
private readonly logger = new Logger(QuotaService.name)
|
||||
|
||||
constructor(
|
||||
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
||||
) {}
|
||||
@@ -16,12 +18,28 @@ export class QuotaService {
|
||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
if (user.plan !== 'free') return
|
||||
|
||||
if ((user.interviewCredits || 0) <= 0) {
|
||||
throw new HttpException('面试次数已用完,请购买面试次数或开通会员', HttpStatus.FORBIDDEN)
|
||||
// Backward compat: migrate remaining → interviewCredits
|
||||
if ((user.interviewCredits ?? 0) <= 0 && (user.remaining ?? 0) > 0) {
|
||||
await this.userModel.findByIdAndUpdate(userId, {
|
||||
$set: { interviewCredits: user.remaining, remaining: 0 },
|
||||
}).exec()
|
||||
}
|
||||
user.interviewCredits = (user.interviewCredits || 0) - 1
|
||||
user.interviewCount = (user.interviewCount || 0) + 1
|
||||
await user.save()
|
||||
|
||||
const result = await this.userModel.findOneAndUpdate(
|
||||
{ _id: userId, interviewCredits: { $gt: 0 } },
|
||||
{ $inc: { interviewCredits: -1, interviewCount: 1 } },
|
||||
{ new: true },
|
||||
).exec()
|
||||
if (result) return
|
||||
|
||||
// Fallback to share credits
|
||||
const shareResult = await this.userModel.findOneAndUpdate(
|
||||
{ _id: userId, shareCredits: { $gt: 0 } },
|
||||
{ $inc: { shareCredits: -1, interviewCount: 1 } },
|
||||
).exec()
|
||||
if (shareResult) return
|
||||
|
||||
throw new HttpException('面试次数已用完,请购买面试次数或开通会员', HttpStatus.FORBIDDEN)
|
||||
}
|
||||
|
||||
async checkAndDeductOptimize(userId: string) {
|
||||
@@ -29,64 +47,83 @@ export class QuotaService {
|
||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
if (user.plan !== 'free') return
|
||||
|
||||
// 优先扣付费额度
|
||||
if ((user.resumeOptimizeCredits || 0) > 0) {
|
||||
user.resumeOptimizeCredits = (user.resumeOptimizeCredits || 0) - 1
|
||||
await user.save()
|
||||
return
|
||||
}
|
||||
// Try paid credits first
|
||||
const paid = await this.userModel.findOneAndUpdate(
|
||||
{ _id: userId, resumeOptimizeCredits: { $gt: 0 } },
|
||||
{ $inc: { resumeOptimizeCredits: -1 } },
|
||||
).exec()
|
||||
if (paid) return
|
||||
|
||||
// 免费额度
|
||||
if ((user.freeOptimizeUsed || 0) < FREE_OPTIMIZE_LIMIT) {
|
||||
user.freeOptimizeUsed = (user.freeOptimizeUsed || 0) + 1
|
||||
await user.save()
|
||||
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 } },
|
||||
{ $inc: { freeOptimizeUsed: 1 } },
|
||||
).exec()
|
||||
if (freeResult) return
|
||||
|
||||
// Fallback to share credits
|
||||
const shareResult = await this.userModel.findOneAndUpdate(
|
||||
{ _id: userId, shareCredits: { $gt: 0 } },
|
||||
{ $inc: { shareCredits: -1 } },
|
||||
).exec()
|
||||
if (shareResult) return
|
||||
|
||||
throw new HttpException('简历优化次数已用完,请购买优化次数或开通会员', HttpStatus.FORBIDDEN)
|
||||
}
|
||||
|
||||
async checkDownload(userId: string, resume: { paidDownload?: boolean }): Promise<boolean> {
|
||||
const user = await this.userModel.findById(userId).exec()
|
||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
|
||||
if (resume.paidDownload) return true
|
||||
if ((user.resumeDownloadCredits || 0) > 0) return true
|
||||
return false
|
||||
async grantShareCredits(userId: string, amount = 1): Promise<boolean> {
|
||||
const result = await this.userModel.findByIdAndUpdate(
|
||||
userId,
|
||||
{ $inc: { shareCredits: amount } },
|
||||
).exec()
|
||||
return !!result
|
||||
}
|
||||
|
||||
async deductDownload(userId: string, resume: { paidDownload?: boolean; _id?: any }) {
|
||||
const user = await this.userModel.findById(userId).exec()
|
||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
async checkAndDeductDownload(userId: string, paidDownload: boolean): Promise<boolean> {
|
||||
if (paidDownload) return true
|
||||
|
||||
if (resume.paidDownload) return
|
||||
if ((user.resumeDownloadCredits || 0) > 0) {
|
||||
user.resumeDownloadCredits = (user.resumeDownloadCredits || 0) - 1
|
||||
await user.save()
|
||||
}
|
||||
const result = await this.userModel.findOneAndUpdate(
|
||||
{ _id: userId, resumeDownloadCredits: { $gt: 0 } },
|
||||
{ $inc: { resumeDownloadCredits: -1 } },
|
||||
).exec()
|
||||
return !!result
|
||||
}
|
||||
|
||||
async grantCredits(userId: string, type: 'interview' | 'optimize' | 'download', amount: number) {
|
||||
const user = await this.userModel.findById(userId).exec()
|
||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
if (amount <= 0) throw new HttpException('无效数量', HttpStatus.BAD_REQUEST)
|
||||
|
||||
if (type === 'interview') user.interviewCredits = (user.interviewCredits || 0) + amount
|
||||
else if (type === 'optimize') user.resumeOptimizeCredits = (user.resumeOptimizeCredits || 0) + amount
|
||||
else if (type === 'download') user.resumeDownloadCredits = (user.resumeDownloadCredits || 0) + amount
|
||||
const fieldMap: Record<string, string> = {
|
||||
interview: 'interviewCredits',
|
||||
optimize: 'resumeOptimizeCredits',
|
||||
download: 'resumeDownloadCredits',
|
||||
}
|
||||
const field = fieldMap[type]
|
||||
if (!field) throw new HttpException('无效类型', HttpStatus.BAD_REQUEST)
|
||||
|
||||
await user.save()
|
||||
const result = await this.userModel.findByIdAndUpdate(
|
||||
userId,
|
||||
{ $inc: { [field]: amount } },
|
||||
).exec()
|
||||
if (!result) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
}
|
||||
|
||||
async setPlanQuota(userId: string, plan: string, credits: { interview: number; resumeOptimize: number; resumeDownload: number }) {
|
||||
const user = await this.userModel.findById(userId).exec()
|
||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
|
||||
user.remaining = 999
|
||||
user.interviewCredits = credits.interview
|
||||
user.resumeOptimizeCredits = credits.resumeOptimize
|
||||
user.resumeDownloadCredits = credits.resumeDownload
|
||||
user.freeOptimizeUsed = FREE_OPTIMIZE_LIMIT // 会员不再消耗免费次数
|
||||
|
||||
await user.save()
|
||||
async setPlanQuota(userId: string, _plan: string, credits: { interview: number; resumeOptimize: number; resumeDownload: number }) {
|
||||
const result = await this.userModel.findByIdAndUpdate(userId, {
|
||||
$set: {
|
||||
remaining: 999,
|
||||
interviewCredits: credits.interview,
|
||||
resumeOptimizeCredits: credits.resumeOptimize,
|
||||
resumeDownloadCredits: credits.resumeDownload,
|
||||
freeOptimizeUsed: FREE_OPTIMIZE_LIMIT,
|
||||
},
|
||||
}).exec()
|
||||
if (!result) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Controller, Post, Get, Put, Body, Req } from '@nestjs/common'
|
||||
import { Controller, Post, Get, Put, Body, Req, HttpCode, HttpStatus } from '@nestjs/common'
|
||||
import { UserService } from './user.service'
|
||||
import { Public } from '../../common/decorators/public.decorator'
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator'
|
||||
@@ -9,12 +9,14 @@ export class UserController {
|
||||
|
||||
@Public()
|
||||
@Post('send-code')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async sendCode(@Body('phone') phone: string) {
|
||||
return this.userService.sendCode(phone)
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async login(@Body('phone') phone: string, @Body('code') code: string) {
|
||||
return this.userService.loginByPhone(phone, code)
|
||||
}
|
||||
@@ -22,12 +24,14 @@ export class UserController {
|
||||
// 📧 邮箱验证码登录(H5 用)
|
||||
@Public()
|
||||
@Post('send-email-code')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async sendEmailCode(@Body('email') email: string) {
|
||||
return this.userService.sendEmailCode(email)
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('email-login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async emailLogin(@Body('email') email: string, @Body('code') code: string) {
|
||||
return this.userService.loginByEmail(email, code)
|
||||
}
|
||||
@@ -35,6 +39,7 @@ export class UserController {
|
||||
// 密码登录
|
||||
@Public()
|
||||
@Post('password-login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async passwordLogin(@Body('email') email: string, @Body('password') password: string) {
|
||||
return this.userService.loginByPassword(email, password)
|
||||
}
|
||||
@@ -42,6 +47,7 @@ export class UserController {
|
||||
// 邮箱+密码注册
|
||||
@Public()
|
||||
@Post('register')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async register(@Body('email') email: string, @Body('password') password: string) {
|
||||
return this.userService.registerWithPassword(email, password)
|
||||
}
|
||||
@@ -49,6 +55,7 @@ export class UserController {
|
||||
// 微信静默登录
|
||||
@Public()
|
||||
@Post('wx-login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async wxLogin(@Body('code') code: string) {
|
||||
return this.userService.loginByWx(code)
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ export class User {
|
||||
@Prop({ default: 0 })
|
||||
freeOptimizeUsed: number // 已使用免费优化次数(上限 3)
|
||||
|
||||
@Prop({ default: 0 })
|
||||
shareCredits: number // 分享积分,每 3 次有效访问获 1 积分
|
||||
|
||||
@Prop({ default: 'user' })
|
||||
role: string // 'user' | 'admin'
|
||||
|
||||
|
||||
@@ -215,6 +215,7 @@ export class UserService {
|
||||
resumeOptimizeCredits: user.resumeOptimizeCredits ?? 0,
|
||||
resumeDownloadCredits: user.resumeDownloadCredits ?? 0,
|
||||
freeOptimizeUsed: user.freeOptimizeUsed ?? 0,
|
||||
shareCredits: user.shareCredits ?? 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# 职引 · 完整功能清单 v4.1
|
||||
# 职引 · 完整功能清单 v4.2
|
||||
|
||||
> **版本**: v4.1
|
||||
> **日期**: 2026-06-09
|
||||
> **状态**: Phase 0.5 壁垒构建完成
|
||||
> **版本**: v4.2
|
||||
> **日期**: 2026-06-16
|
||||
> **状态**: Phase 0.5 壁垒构建完成 + 面试复盘上线
|
||||
> **定位**: 应届生/实习生 AI 面试教练
|
||||
|
||||
---
|
||||
@@ -41,6 +41,18 @@
|
||||
| 连续打卡日历 | ✅ 完成 | 面试频率可视化,连续打卡激励 | P1 |
|
||||
| 每日一题推送 | ⚠️ 半完成 | 首页展示 + API 读取,**无定时推送** | P0 |
|
||||
|
||||
### 1.4 面试复盘(新增)
|
||||
|
||||
| 功能 | 状态 | 描述 | 优先级 |
|
||||
|------|------|------|--------|
|
||||
| 音频文件上传 | ✅ 完成 | 支持 MP3/M4A/WAV/AAC/OGG/MP4/WebM,50MB 上限 | P0 |
|
||||
| 文本转录粘贴 | ✅ 完成 | 直接粘贴面试转录文本提交 | P0 |
|
||||
| whisper.cpp ASR | ✅ 完成 | 本地离线语音转文字,支持 tiny/base 模型 | P0 |
|
||||
| AI 面试评析 | ✅ 完成 | 四维评分(逻辑/表达/专业度/稳定性)+ 逐题评估 | P0 |
|
||||
| 口语分析 | ✅ 完成 | 填充词检测 + 语速评估 | P0 |
|
||||
| 无 ASR 回落 | ✅ 完成 | whisper 不可用时自动使用 mock | P1 |
|
||||
| 历史记录管理 | ✅ 完成 | 列表/详情/删除 | P0 |
|
||||
|
||||
---
|
||||
|
||||
## 二、用户端功能
|
||||
@@ -61,6 +73,7 @@
|
||||
| 面试记录/统计 | ✅ 完成 | 总数/平均分/完成数 |
|
||||
| 进步轨迹 | ✅ 完成 | 雷达图 + 打卡日历 |
|
||||
| 简历管理 | ✅ 完成 | 多份简历 CRUD + AI 分析 |
|
||||
| 面试复盘 | ✅ 完成 | 音频上传 → ASR → AI 评析 → 口语分析 |
|
||||
| 会员中心 | ✅ 完成 | 套餐对比 + 支付 |
|
||||
|
||||
---
|
||||
@@ -95,6 +108,8 @@
|
||||
| 面试报告生成 | ✅ 完成 | 总分 + 四维 + 优劣势分析 |
|
||||
| 简历诊断 | ✅ 完成 | 结构 + 表达 + 关键词 + 亮点分析 |
|
||||
| 简历优化 | ✅ 完成 | 内容优化 + 差异展示 |
|
||||
| 面试复盘评析 | ✅ 完成 | 转录文本 → AI 评估 → 逐题分析 |
|
||||
| 口语分析 | ✅ 完成 | 填充词检测 + 语速评估 |
|
||||
| 技能缺口分析 | 📋 规划中 | 基于 JD 分析技能差距 |
|
||||
| 学习路径推荐 | 📋 规划中 | 知识图谱驱动的职业规划 |
|
||||
|
||||
@@ -104,18 +119,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 +154,7 @@
|
||||
- [x] 会员系统(¥19.9 成长版)
|
||||
- [x] 微信支付对接(Native + JSAPI)
|
||||
- [x] 公司真题库(用户贡献驱动)
|
||||
- [x] **面试复盘(音频 ASR + AI 评析 + 口语分析)**
|
||||
|
||||
### P1(待实现)
|
||||
- [ ] 每日一题定时推送
|
||||
@@ -156,3 +179,4 @@
|
||||
| 2026-06-01 | 重新定位:专注校招 | AI |
|
||||
| 2026-06-05 | 战略升级:新增数据飞轮/留存入围 | 小之 |
|
||||
| 2026-06-09 | 同步代码:Phase 0.5 功能标记完成,修正状态 | AI |
|
||||
| 2026-06-16 | **v4.2**:新增面试复盘功能(whisper.cpp ASR + AI 评析 + 口语分析) | AI |
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# 职引项目 · 状态报告 v4.3
|
||||
# 职引项目 · 状态报告 v4.4
|
||||
|
||||
> **项目版本**: v4.3
|
||||
> **更新时间**: 2026-06-11
|
||||
> **项目状态**: ✅ 代码质量修复 + 全量测试体系搭建完成
|
||||
> **项目版本**: v4.4
|
||||
> **更新时间**: 2026-06-16
|
||||
> **项目状态**: ✅ 面试复盘功能上线 + whisper.cpp 本地 ASR 集成
|
||||
|
||||
---
|
||||
|
||||
@@ -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 |
|
||||
|
||||
---
|
||||
|
||||
@@ -24,12 +25,13 @@
|
||||
| 模块 | 完成度 | 说明 |
|
||||
|------|------|------|
|
||||
| 后端 API | **98%** | 核心 + 护城河 P0-P5 全部实现 |
|
||||
| 前端页面 | **85%** | 16 个页面含真实 API 调用 |
|
||||
| 前端页面 | **85%** | 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→Logger,as any 类型化,空 catch 检查 |
|
||||
| 安全审计 | **90%** | JWT 硬编码 / 凭据泄漏 / IDOR / NoSQL 注入 全部修复 |
|
||||
@@ -89,6 +91,18 @@
|
||||
| 文件上传(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 | **完成** |
|
||||
|
||||
---
|
||||
|
||||
## 四、测试体系
|
||||
@@ -151,6 +165,7 @@
|
||||
| `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 评析 + 口语分析 |
|
||||
| `admin` | controller + module | ✅ | 管理后台 |
|
||||
| `email` | module + service | ✅ | 邮件发送 |
|
||||
| `upload` | controller + module | ✅ | 文件上传 |
|
||||
@@ -166,11 +181,12 @@
|
||||
| 面试模拟 | interview/interview | ✅ 多轮对话 + 计时 |
|
||||
| 面试报告 | report/report | ✅ 评分/分析/全文回放/分享卡片 |
|
||||
| 历史记录 | history/history | ✅ 筛选/统计 |
|
||||
| 个人中心 | user/user | ✅ 信息/统计/管理员入口 |
|
||||
| 个人中心 | user/user | ✅ 信息/统计/管理员入口 + 面试复盘入口 |
|
||||
| 会员中心 | member/member | ✅ 套餐对比 + 支付 |
|
||||
| 进步轨迹 | progress/progress | ✅ 雷达图 + 打卡日历 |
|
||||
| 面经贡献 | contribute/contribute | ✅ 表单提交 |
|
||||
| 简历优化 | resume/resume | ✅ 诊断/优化/上传/下载 |
|
||||
| 面试复盘 | review/review | ✅ 三种模式(列表/上传/报告) |
|
||||
| 实习搜索 | internship/internship | ✅ 热门岗位 |
|
||||
| 管理后台 | admin/admin | ✅ 仪表盘 |
|
||||
| 关于/协议/隐私 | about/agreement/privacy | ✅ |
|
||||
@@ -195,4 +211,5 @@
|
||||
| 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** | **面试复盘功能上线:音频 ASR(whisper.cpp)+ AI 评析 + 口语分析 + 前端三模式页面** | AI |
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# 职引 · 产品路线图 v4.1
|
||||
# 职引 · 产品路线图 v4.2
|
||||
|
||||
> **版本**: v4.1
|
||||
> **日期**: 2026-06-09
|
||||
> **状态**: Phase 0.5 壁垒构建完成,待上线
|
||||
> **版本**: v4.2
|
||||
> **日期**: 2026-06-16
|
||||
> **状态**: Phase 1 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,50 @@ Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
|
||||
|
||||
---
|
||||
|
||||
## 四、Phase 1:MVP 上线(D7-14,当前阶段)
|
||||
## 四、Phase 1:MVP 开发(✅ 已完成,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:3006,zhiyin.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 |
|
||||
| 付费转化验证 | 100 内测用户 → 10+ 付费 | P0 |
|
||||
| PMF 决策 | 转化率 > 5% → 继续 | P0 |
|
||||
|
||||
---
|
||||
|
||||
## 六、Phase 2:增强 + 真题库(D30-60,秋招前)
|
||||
## 六、Phase 2:增强 + 真题库(D60-90,秋招前)
|
||||
|
||||
### 6.1 真题库建设
|
||||
| 公司 | 题库规模 | 状态 |
|
||||
@@ -112,7 +124,7 @@ Phase 3: 商业化 + B 端(D60-90)→ 秋招爆发
|
||||
|
||||
---
|
||||
|
||||
## 七、Phase 3:商业化 + B 端(D60-90,秋招爆发)
|
||||
## 七、Phase 3:商业化 + B 端(D90+,秋招爆发)
|
||||
|
||||
### 7.1 增长目标
|
||||
- 付费用户突破 1000
|
||||
@@ -140,10 +152,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 +170,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 +199,4 @@ 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 |
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
# 分享功能设计方案
|
||||
|
||||
## 1. 概述
|
||||
|
||||
**目标**:用户可通过分享面试/简历等给好友或微信群,每次有效分享获得积分奖励,积分可抵扣面试/简历优化次数,形成用户增长闭环。
|
||||
|
||||
**核心逻辑**:分享者 A → 生成分享链接 → 非 A 的其他用户点击 → 计入有效分享一次 → A 获得 1 个「分享积分」,每 3 次有效分享可兑换 1 次面试或简历优化次数。
|
||||
|
||||
---
|
||||
|
||||
## 2. 数据模型
|
||||
|
||||
### User 新增字段
|
||||
|
||||
```
|
||||
shareCredits: number // 分享积分,默认 0
|
||||
```
|
||||
|
||||
- 1 个 shareCredit 可兑换 1 次 面试 或 1 次 简历优化
|
||||
- 在 QuotaService 中作为兜底:当 interviewCredits / resumeOptimizeCredits 为 0 时尝试消耗 shareCredits
|
||||
|
||||
### ShareRecord 集合
|
||||
|
||||
```
|
||||
@Schema({ timestamps: true })
|
||||
ShareRecord {
|
||||
_id: ObjectId
|
||||
userId: ObjectId // 分享者
|
||||
shareCode: string // 8位唯一短码 (hex),用于分享链接
|
||||
type: 'interview' | 'resume' | 'app'
|
||||
refId: string // 关联的面试/简历ID(可选)
|
||||
title: string // 分享标题
|
||||
description: string // 分享描述
|
||||
visitCount: number // 总访问次数
|
||||
creditedCount: number // 已计为有效的访问次数
|
||||
isActive: boolean // 链接是否有效
|
||||
createdAt: Date // timestamps
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
index: { shareCode: 1 } unique
|
||||
index: { userId: 1, createdAt: -1 }
|
||||
```
|
||||
|
||||
### ShareVisit 集合(访问记录)
|
||||
|
||||
```
|
||||
@Schema({ timestamps: true })
|
||||
ShareVisit {
|
||||
_id: ObjectId
|
||||
shareId: ObjectId // 关联的 ShareRecord
|
||||
sharerId: ObjectId // 分享者 userId(冗余,便于查询)
|
||||
visitorId: string // 访问者标识(openId 或 匿名ID)
|
||||
visitorUserId: ObjectId // 访问者 userId(如果已注册/登录)
|
||||
credited: boolean // 是否已为此访问发积分
|
||||
creditedAt: Date
|
||||
createdAt: Date // timestamps
|
||||
}
|
||||
|
||||
index: { shareId: 1, visitorId: 1 } unique // 同一人只计一次
|
||||
index: { sharerId: 1, createdAt: -1 }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. API 设计
|
||||
|
||||
| 方法 | 路径 | 权限 | 说明 |
|
||||
|------|------|------|------|
|
||||
| POST | /api/share/create | JWT | 生成分享链接,返回 shareCode + URL |
|
||||
| GET | /api/share/visit/:shareCode | Public | 访问分享链接,记录访问+判定发放积分 |
|
||||
| GET | /api/share/stats | JWT | 获取我的分享统计(总分享次数、总积分、今日积分) |
|
||||
| GET | /api/share/records | JWT | 获取我的分享记录列表(分页) |
|
||||
| GET | /api/share/visitors | JWT | 获取访问过我分享的用户列表(分页) |
|
||||
|
||||
### POST /api/share/create
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"type": "interview" | "resume" | "app",
|
||||
"refId": "xxx",
|
||||
"title": "我在职引完成了AI模拟面试",
|
||||
"description": "快来和我一起练习面试吧"
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"shareCode": "a1b2c3d4",
|
||||
"shareUrl": "https://zhiyin.app/share/a1b2c3d4",
|
||||
"wechatShareInfo": {
|
||||
"title": "...",
|
||||
"description": "...",
|
||||
"path": "/pages/share/share?code=a1b2c3d4"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/share/visit/:shareCode
|
||||
|
||||
- 如果来自微信小程序:记录 `visitorId = openId`
|
||||
- 如果来自 H5 链接:记录 `visitorId = 匿名设备ID`(可选)
|
||||
- 判定条件:
|
||||
- `visitorId !== sharer.openId`(自己点自己不算)
|
||||
- 该 `visitorId` 之前未在该 shareId 下领过积分
|
||||
- 当日该分享者已获得积分 < 3(日上限)
|
||||
- 满足条件 → `credited = true`,shareCredits + 1
|
||||
- 返回重定向或展示落地页
|
||||
|
||||
### GET /api/share/stats
|
||||
|
||||
```json
|
||||
{
|
||||
"totalShares": 15,
|
||||
"totalVisits": 43,
|
||||
"creditedCount": 12,
|
||||
"todayCredited": 2,
|
||||
"shareCredits": 4
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/share/records
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"shareCode": "a1b2c3d4",
|
||||
"type": "interview",
|
||||
"title": "我在职引完成了AI模拟面试",
|
||||
"visitCount": 5,
|
||||
"creditedCount": 3,
|
||||
"createdAt": "2026-06-12T10:00:00Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### GET /api/share/visitors
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"visitor": { "nickname": "张三", "avatar": "..." },
|
||||
"credited": true,
|
||||
"creditedAt": "2026-06-12T10:30:00Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 积分兜底机制
|
||||
|
||||
在 `QuotaService.checkAndDeductInterview()` 和 `checkAndDeductOptimize()` 中增加兜底:
|
||||
|
||||
```
|
||||
if (interviewCredits <= 0 && shareCredits > 0) {
|
||||
shareCredits -= 1
|
||||
return // 用分享积分抵扣
|
||||
}
|
||||
```
|
||||
|
||||
同时新增 `useShareCredit(userId, type)` 方法由前端显式调用,或自动在抵扣链中完成。
|
||||
|
||||
---
|
||||
|
||||
## 5. 前端实现
|
||||
|
||||
### 5.1 分享入口
|
||||
|
||||
**进入点 1:面试报告页**(`pages/report/report.vue`)
|
||||
- 在"生成分享卡片"按钮旁增加"分享给好友"按钮
|
||||
- 点击后调用 `POST /api/share/create` 生成 shareCode
|
||||
- 微信小程序内直接调 `wx.shareAppMessage`
|
||||
- H5 环境复制分享链接到剪贴板
|
||||
|
||||
**进入点 2:简历优化结果页**(`pages/result/result.vue`)
|
||||
- 同上
|
||||
|
||||
**进入点 3:应用首页**(`pages/index/index.vue`)
|
||||
- "邀请好友"入口,固定分享 app 类型
|
||||
|
||||
### 5.2 我的分享页
|
||||
|
||||
**页面位置**:`/pages/share/share.vue`
|
||||
**进入方式**:用户「我的」页面 → "我的分享" 菜单项
|
||||
|
||||
页面内容:
|
||||
- 顶部统计卡片:总收益积分、今日收益、总分享次数
|
||||
- "分享给好友"主按钮
|
||||
- Tab 切换:「分享记录」/ 「访问记录」
|
||||
- 分享记录列表:分享类型、标题、访问数、有效数、时间
|
||||
- 访问记录列表:访客昵称、访问时间、是否已积分
|
||||
|
||||
### 5.3 微信分享
|
||||
|
||||
使用 uni-app `onShareAppMessage` 生命周期:
|
||||
```javascript
|
||||
// 在页面中定义
|
||||
onShareAppMessage() {
|
||||
return {
|
||||
title: '我在职引完成了AI模拟面试',
|
||||
path: `/pages/share/share?code=${this.shareCode}`,
|
||||
imageUrl: '...'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.4 H5 分享链接
|
||||
|
||||
分享链接格式:`https://zhiyin.app/share/{shareCode}`
|
||||
H5 落地页展示:
|
||||
- 分享者信息
|
||||
- 分享内容预览
|
||||
- "打开小程序" / "下载 App" 引导按钮
|
||||
|
||||
---
|
||||
|
||||
## 6. 风控规则
|
||||
|
||||
| 规则 | 说明 |
|
||||
|------|------|
|
||||
| 日上限 | 同一用户每日最多获 3 个分享积分 |
|
||||
| 自分享过滤 | 自己点自己的链接不计数 |
|
||||
| 同人去重 | 同一访客对同一链接只计一次 |
|
||||
| 链接有效期 | 分享链接 30 天有效期 |
|
||||
| 频率限制 | 每分钟最多创建 5 次分享(前端控制) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 存储方案
|
||||
|
||||
- **ShareRecord**:MongoDB 集合 `sharerecords`
|
||||
- **ShareVisit**:MongoDB 集合 `sharevisits`
|
||||
- 积分字段 `shareCredits` 存储在 User 文档上,`$inc` 原子操作确保并发安全
|
||||
|
||||
---
|
||||
|
||||
## 8. 依赖模块
|
||||
|
||||
- `QuotaService`(来自 UserModule)- 积分发放与抵扣
|
||||
- `UserModule`(获取 User 信息、校验身份)
|
||||
- `PricingModule`(@Global 已有,无需额外导入)
|
||||
|
||||
---
|
||||
|
||||
## 9. 未纳入 MVP 的内容
|
||||
|
||||
- 分享链接落地页(H5 路由 `/share/:code`)— 第一期直接返回 JSON
|
||||
- 分享数据可视化图表
|
||||
- 积分兑换商城
|
||||
- 排行榜 / 邀请竞赛
|
||||
@@ -25,7 +25,7 @@
|
||||
"@dcloudio/vite-plugin-uni": "3.0.0-4060620250520001",
|
||||
"@vue/test-utils": "^2.4.11",
|
||||
"jsdom": "^29.1.1",
|
||||
"miniprogram-ci": "^2.1.31",
|
||||
"miniprogram-ci": "^2.1.42",
|
||||
"sass": "^1.70.0",
|
||||
"typescript": "^5.3.0",
|
||||
"vite": "^5.2.0",
|
||||
@@ -5674,15 +5674,15 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@swc/core": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core/-/core-1.4.14.tgz",
|
||||
"integrity": "sha512-tHXg6OxboUsqa/L7DpsCcFnxhLkqN/ht5pCwav1HnvfthbiNIJypr86rNx4cUnQDJepETviSqBTIjxa7pSpGDQ==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core/-/core-1.15.33.tgz",
|
||||
"integrity": "sha512-jOlwnFV2xhuuZeAUILGFULeR6vDPfijEJ57evfocwznQldLU3w2cZ9bSDryY9ip+AsM3r1NJKzf47V2NXebkeQ==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@swc/counter": "^0.1.2",
|
||||
"@swc/types": "^0.1.5"
|
||||
"@swc/counter": "^0.1.3",
|
||||
"@swc/types": "^0.1.26"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
@@ -5692,19 +5692,21 @@
|
||||
"url": "https://opencollective.com/swc"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@swc/core-darwin-arm64": "1.4.14",
|
||||
"@swc/core-darwin-x64": "1.4.14",
|
||||
"@swc/core-linux-arm-gnueabihf": "1.4.14",
|
||||
"@swc/core-linux-arm64-gnu": "1.4.14",
|
||||
"@swc/core-linux-arm64-musl": "1.4.14",
|
||||
"@swc/core-linux-x64-gnu": "1.4.14",
|
||||
"@swc/core-linux-x64-musl": "1.4.14",
|
||||
"@swc/core-win32-arm64-msvc": "1.4.14",
|
||||
"@swc/core-win32-ia32-msvc": "1.4.14",
|
||||
"@swc/core-win32-x64-msvc": "1.4.14"
|
||||
"@swc/core-darwin-arm64": "1.15.33",
|
||||
"@swc/core-darwin-x64": "1.15.33",
|
||||
"@swc/core-linux-arm-gnueabihf": "1.15.33",
|
||||
"@swc/core-linux-arm64-gnu": "1.15.33",
|
||||
"@swc/core-linux-arm64-musl": "1.15.33",
|
||||
"@swc/core-linux-ppc64-gnu": "1.15.33",
|
||||
"@swc/core-linux-s390x-gnu": "1.15.33",
|
||||
"@swc/core-linux-x64-gnu": "1.15.33",
|
||||
"@swc/core-linux-x64-musl": "1.15.33",
|
||||
"@swc/core-win32-arm64-msvc": "1.15.33",
|
||||
"@swc/core-win32-ia32-msvc": "1.15.33",
|
||||
"@swc/core-win32-x64-msvc": "1.15.33"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@swc/helpers": "^0.5.0"
|
||||
"@swc/helpers": ">=0.5.17"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@swc/helpers": {
|
||||
@@ -5713,9 +5715,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-darwin-arm64": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-darwin-arm64/-/core-darwin-arm64-1.4.14.tgz",
|
||||
"integrity": "sha512-8iPfLhYNspBl836YYsfv6ErXwDUqJ7IMieddV3Ey/t/97JAEAdNDUdtTKDtbyP0j/Ebyqyn+fKcqwSq7rAof0g==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-darwin-arm64/-/core-darwin-arm64-1.15.33.tgz",
|
||||
"integrity": "sha512-N+L0uXhuO7FIfzqwgxmzv0zIpV0qEp8wPX3QQs2p4atjMoywup2JTeDlXPw+z9pWJGCae3JjM+tZ6myclI+2gA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -5730,9 +5732,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-darwin-x64": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-darwin-x64/-/core-darwin-x64-1.4.14.tgz",
|
||||
"integrity": "sha512-9CqSj8uRZ92cnlgAlVaWMaJJBdxtNvCzJxaGj5KuIseeG6Q0l1g+qk8JcU7h9dAsH9saHTNwNFBVGKQo0W0ujg==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-darwin-x64/-/core-darwin-x64-1.15.33.tgz",
|
||||
"integrity": "sha512-/Il4QHSOhV4FekbsDtkrNmKbsX26oSysvgrRswa/RYOHXAkwXDbB4jaeKq6PsJLSPkzJ2KzQ061gtBnk0vNHfA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -5747,9 +5749,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-arm-gnueabihf": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.4.14.tgz",
|
||||
"integrity": "sha512-mfd5JArPITTzMjcezH4DwMw+BdjBV1y25Khp8itEIpdih9ei+fvxOOrDYTN08b466NuE2dF2XuhKtRLA7fXArQ==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.15.33.tgz",
|
||||
"integrity": "sha512-C64hBnBxq4viOPQ8hlx+2lJ23bzZBGnjw7ryALmS+0Q3zHmwO8lw1/DArLENw4Q18/0w5wdEO1k3m1wWNtKGqQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -5764,9 +5766,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-arm64-gnu": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.4.14.tgz",
|
||||
"integrity": "sha512-3Lqlhlmy8MVRS9xTShMaPAp0oyUt0KFhDs4ixJsjdxKecE0NJSV/MInuDmrkij1C8/RQ2wySRlV9np5jK86oWw==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.15.33.tgz",
|
||||
"integrity": "sha512-TRJfnJbX3jqpxRDRoieMzRiCBS5jOmXNb3iQXmcgjFEHKLnAgK1RZRU8Cq1MsPqO4jAJp/ld1G4O3fXuxv85uw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -5781,9 +5783,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-arm64-musl": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.4.14.tgz",
|
||||
"integrity": "sha512-n0YoCa64TUcJrbcXIHIHDWQjdUPdaXeMHNEu7yyBtOpm01oMGTKP3frsUXIABLBmAVWtKvqit4/W1KVKn5gJzg==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.15.33.tgz",
|
||||
"integrity": "sha512-il7tYM+CpUNzieQbwAjFT1P8zqAhmGWNAGhQZBnxurXZ0aNn+5nqYFTEUKNZl7QibtT0uQXzTZrNGHCIj6Y1Og==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -5797,10 +5799,44 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-ppc64-gnu": {
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-ppc64-gnu/-/core-linux-ppc64-gnu-1.15.33.tgz",
|
||||
"integrity": "sha512-ZtNBwN0Z7CFj9Il0FcPaKdjgP7URyKu/3RfH46vq+0paOBqLj4NYldD6Qo//Duif/7IOtAraUfDOmp0PLAufog==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-s390x-gnu": {
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-s390x-gnu/-/core-linux-s390x-gnu-1.15.33.tgz",
|
||||
"integrity": "sha512-De1IyajoOmhOYYjw/lx66bKlyDpHZTueqwpDrWgf5O7T6d1ODeJJO9/OqMBmrBQc5C+dNnlmIufHsp4QVCWufA==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-x64-gnu": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.4.14.tgz",
|
||||
"integrity": "sha512-CGmlwLWbfG1dB4jZBJnp2IWlK5xBMNLjN7AR5kKA3sEpionoccEnChOEvfux1UdVJQjLRKuHNV9yGyqGBTpxfQ==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.15.33.tgz",
|
||||
"integrity": "sha512-mGTH0YxmUN+x6vRN/I6NOk5X0ogNktkwPnJ94IMvR7QjhRDwL0O8RXEDhyUM0YtwWrryBOqaJQBX4zruxEPRGw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -5815,9 +5851,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-x64-musl": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.4.14.tgz",
|
||||
"integrity": "sha512-xq4npk8YKYmNwmr8fbvF2KP3kUVdZYfXZMQnW425gP3/sn+yFQO8Nd0bGH40vOVQn41kEesSe0Z5O/JDor2TgQ==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.15.33.tgz",
|
||||
"integrity": "sha512-hj628ZkSEJf6zMf5VMbYrG2O6QqyTIp2qwY6VlCjvIa9lAEZ5c2lfPblCLVGYubTeLJDxadLB/CxqQYOQABeEQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -5832,9 +5868,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-win32-arm64-msvc": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.4.14.tgz",
|
||||
"integrity": "sha512-imq0X+gU9uUe6FqzOQot5gpKoaC00aCUiN58NOzwp0QXEupn8CDuZpdBN93HiZswfLruu5jA1tsc15x6v9p0Yg==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.15.33.tgz",
|
||||
"integrity": "sha512-GV2oohtN2/5+KSccl86VULu3aT+LrISC8uzgSq0FRnikpD+Zwc+sBlXmoKQ+Db6jI57ITUOIB8jRkdGMABC29g==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -5849,9 +5885,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-win32-ia32-msvc": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.4.14.tgz",
|
||||
"integrity": "sha512-cH6QpXMw5D3t+lpx6SkErHrxN0yFzmQ0lgNAJxoDRiaAdDbqA6Col8UqUJwUS++Ul6aCWgNhCdiEYehPaoyDPA==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.15.33.tgz",
|
||||
"integrity": "sha512-gtyvzSNR8DHKfFEA2uqb8Ld1myqi6uEg2jyeUq3ikn5ytYs7H8RpZYC8mdy4NXr8hfcdJfCLXPlYaqqfBXpoEQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@@ -5866,9 +5902,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-win32-x64-msvc": {
|
||||
"version": "1.4.14",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.4.14.tgz",
|
||||
"integrity": "sha512-FmZ4Tby4wW65K/36BKzmuu7mlq7cW5XOxzvufaSNVvQ5PN4OodAlqPjToe029oma4Av+ykJiif64scMttyNAzg==",
|
||||
"version": "1.15.33",
|
||||
"resolved": "https://registry.npmmirror.com/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.15.33.tgz",
|
||||
"integrity": "sha512-d6fRqQSkJI+kmMEBWaDQ7TMl8+YjLYbwRUPZQ9DY0ORBJeTzOrG0twvfvlZ2xgw6jA0ScQKgfBm4vHLSLl5Hqg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -15461,9 +15497,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/miniprogram-ci": {
|
||||
"version": "2.1.31",
|
||||
"resolved": "https://registry.npmmirror.com/miniprogram-ci/-/miniprogram-ci-2.1.31.tgz",
|
||||
"integrity": "sha512-SREx6UnJC74aQ2a1YMNShqQOB97nHO+ll6ZQrCQp98NHXcRq848VjZoD5ELpd95z+8uTASQUAcFtl/HrXuM7Nw==",
|
||||
"version": "2.1.42",
|
||||
"resolved": "https://registry.npmmirror.com/miniprogram-ci/-/miniprogram-ci-2.1.42.tgz",
|
||||
"integrity": "sha512-H/bq0Wo6kMbwzcOM4jiYSMuQUkND50+zeyY8EkJuY1TQYijkLbFmNK/CFsFJsJgVcvXZ94wn8Do50YSO/Rv6/w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -15589,7 +15625,7 @@
|
||||
"@babel/template": "7.20.7",
|
||||
"@babel/traverse": "7.21.4",
|
||||
"@babel/types": "7.24.6",
|
||||
"@swc/core": "1.4.14",
|
||||
"@swc/core": "1.15.33",
|
||||
"@vue/reactivity": "3.0.5",
|
||||
"acorn": "^6.1.1",
|
||||
"adm-zip": "0.5.10",
|
||||
@@ -15642,7 +15678,7 @@
|
||||
"string-hash-64": "1.0.3",
|
||||
"sync-message": "0.0.12",
|
||||
"terminal-kit": "^2.4.0",
|
||||
"terser": "4.8.0",
|
||||
"terser": "5.27.1",
|
||||
"tmp": "0.0.28",
|
||||
"tslib": "^2.4.0",
|
||||
"uglify-js": "3.0.27",
|
||||
@@ -18152,21 +18188,35 @@
|
||||
}
|
||||
},
|
||||
"node_modules/miniprogram-ci/node_modules/terser": {
|
||||
"version": "4.8.0",
|
||||
"resolved": "https://registry.npmmirror.com/terser/-/terser-4.8.0.tgz",
|
||||
"integrity": "sha512-EAPipTNeWsb/3wLPeup1tVPaXfIaU68xMnVdPafIL1TV05OhASArYyIfFvnvJCNrR2NIOvDVNNTFRa+Re2MWyw==",
|
||||
"version": "5.27.1",
|
||||
"resolved": "https://registry.npmmirror.com/terser/-/terser-5.27.1.tgz",
|
||||
"integrity": "sha512-29wAr6UU/oQpnTw5HoadwjUZnFQXGdOfj0LjZ4sVxzqwHh/QVkvr7m8y9WoR4iN3FRitVduTc6KdjcW38Npsug==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"@jridgewell/source-map": "^0.3.3",
|
||||
"acorn": "^8.8.2",
|
||||
"commander": "^2.20.0",
|
||||
"source-map": "~0.6.1",
|
||||
"source-map-support": "~0.5.12"
|
||||
"source-map-support": "~0.5.20"
|
||||
},
|
||||
"bin": {
|
||||
"terser": "bin/terser"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/miniprogram-ci/node_modules/terser/node_modules/acorn": {
|
||||
"version": "8.17.0",
|
||||
"resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.17.0.tgz",
|
||||
"integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/miniprogram-ci/node_modules/terser/node_modules/commander": {
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"dev:mp-weixin": "uni -p mp-weixin",
|
||||
"build:mp-weixin": "uni build -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",
|
||||
"dev:h5": "uni",
|
||||
"build:h5": "uni build",
|
||||
"build:h5": "uni build && cp -n static/avatar-*.png dist/build/h5/static/ 2>/dev/null; true",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
@@ -27,7 +27,7 @@
|
||||
"@dcloudio/vite-plugin-uni": "3.0.0-4060620250520001",
|
||||
"@vue/test-utils": "^2.4.11",
|
||||
"jsdom": "^29.1.1",
|
||||
"miniprogram-ci": "^2.1.31",
|
||||
"miniprogram-ci": "^2.1.42",
|
||||
"sass": "^1.70.0",
|
||||
"typescript": "^5.3.0",
|
||||
"vite": "^5.2.0",
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
<template>
|
||||
<view class="digital-human">
|
||||
<view class="avatar-stage">
|
||||
<view class="avatar-ring" :class="{ speaking: isSpeaking }">
|
||||
<!-- Default CSS avatar if image fails -->
|
||||
<view class="avatar-default" v-if="imgFailed">
|
||||
<text class="avatar-initials">AI</text>
|
||||
</view>
|
||||
<image class="avatar-img" :src="avatarSrc" mode="aspectFill" @error="imgFailed = true" v-else />
|
||||
<canvas
|
||||
v-if="isH5"
|
||||
id="dh-mouth"
|
||||
class="mouth-canvas"
|
||||
></canvas>
|
||||
<view class="avatar-body" :class="{ speaking: isSpeaking }">
|
||||
<image class="avatar-img" :src="avatarSrc" mode="aspectFill" @error="avatarError = true" />
|
||||
<view class="mouth-overlay" :style="mouthStyle"></view>
|
||||
</view>
|
||||
<text class="role-label">AI 面试官</text>
|
||||
<image src="/static/avatar-default.png" style="display:none" />
|
||||
<image src="/static/avatar-software.png" style="display:none" />
|
||||
<image src="/static/avatar-frontend.png" style="display:none" />
|
||||
<image src="/static/avatar-backend.png" style="display:none" />
|
||||
<image src="/static/avatar-algo.png" style="display:none" />
|
||||
<image src="/static/avatar-pm.png" style="display:none" />
|
||||
<image src="/static/avatar-data.png" style="display:none" />
|
||||
<image src="/static/avatar-marketing.png" style="display:none" />
|
||||
<image src="/static/avatar-ops.png" style="display:none" />
|
||||
<image src="/static/avatar-ui.png" style="display:none" />
|
||||
<view class="status-dot" :class="{ active: isSpeaking }"></view>
|
||||
<text class="role-label">{{ positionLabel }}</text>
|
||||
</view>
|
||||
|
||||
<view class="speech-area" v-if="currentText">
|
||||
<view class="speech-bubble">
|
||||
<text class="speech-text">{{ currentText }}</text>
|
||||
@@ -25,30 +27,61 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
|
||||
import { ref, watch, computed, onBeforeUnmount, nextTick } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
text: { type: String, default: '' },
|
||||
audioUrl: { type: String, default: '' },
|
||||
amplitudeData: { type: Array, default: () => [] },
|
||||
avatarUrl: { type: String, default: '' },
|
||||
position: { type: String, default: '' },
|
||||
autoPlay: { type: Boolean, default: true },
|
||||
})
|
||||
|
||||
const emit = defineEmits(['speaking-start', 'speaking-end'])
|
||||
|
||||
const isH5 = ref(false)
|
||||
const isSpeaking = ref(false)
|
||||
const currentText = ref('')
|
||||
const imgFailed = ref(false)
|
||||
let audioEl = null
|
||||
let audioCtx = null
|
||||
let analyser = null
|
||||
let animFrameId = null
|
||||
let mouthScale = 0
|
||||
const mouthOpenness = ref(0)
|
||||
const avatarError = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
isH5.value = typeof window !== 'undefined' && typeof document !== 'undefined'
|
||||
initCanvas()
|
||||
let audioEl = null
|
||||
let animFrame = null
|
||||
|
||||
const allAvatars = [
|
||||
'/static/avatar-default.png',
|
||||
'/static/avatar-software.png',
|
||||
'/static/avatar-frontend.png',
|
||||
'/static/avatar-backend.png',
|
||||
'/static/avatar-algo.png',
|
||||
'/static/avatar-pm.png',
|
||||
'/static/avatar-data.png',
|
||||
'/static/avatar-marketing.png',
|
||||
'/static/avatar-ops.png',
|
||||
'/static/avatar-ui.png',
|
||||
]
|
||||
|
||||
const avatarMap = {
|
||||
'软件开发': '/static/avatar-software.png',
|
||||
'前端开发': '/static/avatar-frontend.png',
|
||||
'后端开发': '/static/avatar-backend.png',
|
||||
'算法工程师': '/static/avatar-algo.png',
|
||||
'产品经理': '/static/avatar-pm.png',
|
||||
'数据分析': '/static/avatar-data.png',
|
||||
'市场营销': '/static/avatar-marketing.png',
|
||||
'运营': '/static/avatar-ops.png',
|
||||
'UI设计': '/static/avatar-ui.png',
|
||||
}
|
||||
|
||||
const avatarSrc = computed(() => {
|
||||
if (avatarError.value) return '/static/avatar-default.png'
|
||||
if (props.avatarUrl) return props.avatarUrl
|
||||
const key = Object.keys(avatarMap).find(k => props.position.includes(k))
|
||||
return key ? avatarMap[key] : '/static/avatar-default.png'
|
||||
})
|
||||
|
||||
const positionLabel = computed(() => {
|
||||
return props.position ? `${props.position} 面试官` : 'AI 面试官'
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -65,129 +98,82 @@ watch(() => props.text, (txt) => {
|
||||
currentText.value = txt
|
||||
})
|
||||
|
||||
const avatarSrc = computed(() => {
|
||||
return props.avatarUrl || '/static/default-avatar.png'
|
||||
const mouthStyle = computed(() => {
|
||||
const o = mouthOpenness.value
|
||||
const h = 3 + o * o * 22
|
||||
const w = 18 + o * 8
|
||||
return {
|
||||
height: h + 'rpx',
|
||||
width: w + 'rpx',
|
||||
borderRadius: o > 0.3 ? '50%' : '4rpx',
|
||||
background: o > 0.5 ? 'linear-gradient(180deg, #C97B84, #A85562)' : '#C97B84',
|
||||
opacity: o > 0.01 ? 1 : 0.3,
|
||||
}
|
||||
})
|
||||
|
||||
function initCanvas() {
|
||||
if (!isH5.value) return
|
||||
const canvas = document.getElementById('dh-mouth')
|
||||
if (!canvas) return
|
||||
// Size the canvas to match mouth area (~40% width, ~15% height, centered bottom)
|
||||
const parent = canvas.parentElement
|
||||
if (!parent) return
|
||||
const rect = parent.getBoundingClientRect()
|
||||
canvas.width = rect.width * 0.4
|
||||
canvas.height = rect.height * 0.15
|
||||
canvas.style.width = canvas.width + 'px'
|
||||
canvas.style.height = canvas.height + 'px'
|
||||
canvas.style.position = 'absolute'
|
||||
canvas.style.bottom = '18%'
|
||||
canvas.style.left = '30%'
|
||||
function getAmplitude(positionMs) {
|
||||
const amp = props.amplitudeData
|
||||
if (!amp || amp.length === 0) return -1
|
||||
const idx = Math.floor(positionMs / 50)
|
||||
if (idx >= amp.length) return -1
|
||||
return amp[idx]
|
||||
}
|
||||
|
||||
function drawMouth(openRatio) {
|
||||
if (!isH5.value) return
|
||||
const canvas = document.getElementById('dh-mouth')
|
||||
if (!canvas) return
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
const w = canvas.width
|
||||
const h = canvas.height
|
||||
ctx.clearRect(0, 0, w, h)
|
||||
|
||||
const mouthH = Math.max(2, h * openRatio)
|
||||
const mouthW = w * 0.8
|
||||
|
||||
ctx.fillStyle = '#C97B84'
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(w / 2, h / 2 + (h - mouthH) / 2, mouthW / 2, mouthH / 2, 0, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
|
||||
if (openRatio > 0.1) {
|
||||
ctx.fillStyle = '#2D1B1E'
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(w / 2, h / 2 + (h - mouthH) / 2 + 1, mouthW / 4, mouthH / 4, 0, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
function tickMouth() {
|
||||
if (!audioEl) return
|
||||
const currentTime = audioEl.currentTime * 1000 || 0
|
||||
const amp = getAmplitude(currentTime)
|
||||
if (amp >= 0) {
|
||||
const openness = Math.pow(Math.min(1, amp * 2.5), 0.7)
|
||||
mouthOpenness.value = openness
|
||||
} else {
|
||||
const t = Date.now() / 1000
|
||||
const idle = (Math.sin(t * 4) + 1) / 2 * 0.15
|
||||
mouthOpenness.value = Math.max(0.03, idle)
|
||||
}
|
||||
animFrame = setTimeout(tickMouth, 50)
|
||||
}
|
||||
|
||||
async function playAudio(url) {
|
||||
function playAudio(url) {
|
||||
stopAudio()
|
||||
isSpeaking.value = true
|
||||
emit('speaking-start')
|
||||
tickMouth()
|
||||
|
||||
try {
|
||||
audioEl = new Audio(url)
|
||||
|
||||
if (isH5.value) {
|
||||
audioCtx = new (window.AudioContext || window.webkitAudioContext)()
|
||||
const source = audioCtx.createMediaElementSource(audioEl)
|
||||
analyser = audioCtx.createAnalyser()
|
||||
analyser.fftSize = 256
|
||||
source.connect(analyser)
|
||||
analyser.connect(audioCtx.destination)
|
||||
}
|
||||
|
||||
audioEl.onended = () => {
|
||||
finishSpeaking()
|
||||
}
|
||||
|
||||
audioEl.onerror = () => {
|
||||
finishSpeaking()
|
||||
}
|
||||
|
||||
await audioEl.play()
|
||||
|
||||
if (analyser) {
|
||||
animateMouth()
|
||||
}
|
||||
const innerAudio = uni.createInnerAudioContext()
|
||||
audioEl = innerAudio
|
||||
innerAudio.src = url
|
||||
innerAudio.autoplay = true
|
||||
innerAudio.onEnded(() => finishSpeaking())
|
||||
innerAudio.onError(() => finishSpeaking())
|
||||
innerAudio.onStop(() => finishSpeaking())
|
||||
} catch (e) {
|
||||
finishSpeaking()
|
||||
}
|
||||
}
|
||||
|
||||
function animateMouth() {
|
||||
if (!analyser) return
|
||||
const dataArray = new Uint8Array(analyser.frequencyBinCount)
|
||||
|
||||
function tick() {
|
||||
if (!isSpeaking.value) return
|
||||
analyser.getByteFrequencyData(dataArray)
|
||||
const sum = dataArray.reduce((a, b) => a + b, 0)
|
||||
const avg = sum / dataArray.length
|
||||
mouthScale = Math.min(1, avg / 128)
|
||||
// Smooth
|
||||
mouthScale = Math.max(0.05, mouthScale)
|
||||
drawMouth(mouthScale)
|
||||
animFrameId = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
tick()
|
||||
}
|
||||
|
||||
function finishSpeaking() {
|
||||
isSpeaking.value = false
|
||||
emit('speaking-end')
|
||||
if (analyser) {
|
||||
mouthScale = 0
|
||||
drawMouth(0)
|
||||
}
|
||||
mouthOpenness.value = 0
|
||||
cleanupTimers()
|
||||
cleanupAudio()
|
||||
emit('speaking-end')
|
||||
}
|
||||
|
||||
function cleanupTimers() {
|
||||
if (animFrame) { clearTimeout(animFrame); animFrame = null }
|
||||
}
|
||||
|
||||
function cleanupAudio() {
|
||||
if (animFrameId) { cancelAnimationFrame(animFrameId); animFrameId = null }
|
||||
if (audioCtx) { audioCtx.close().catch(() => {}); audioCtx = null }
|
||||
analyser = null
|
||||
audioEl = null
|
||||
if (audioEl) {
|
||||
try { audioEl.stop(); audioEl.destroy() } catch {}
|
||||
audioEl = null
|
||||
}
|
||||
}
|
||||
|
||||
function stopAudio() {
|
||||
if (audioEl) {
|
||||
try { audioEl.pause(); audioEl.src = '' } catch {}
|
||||
}
|
||||
if (audioEl) { try { audioEl.stop(); audioEl.destroy() } catch {} }
|
||||
finishSpeaking()
|
||||
}
|
||||
|
||||
@@ -199,56 +185,63 @@ defineExpose({ play: playAudio, stop: stopAudio })
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 20rpx 0;
|
||||
padding: 10rpx 0;
|
||||
}
|
||||
|
||||
/* Avatar stage */
|
||||
.avatar-stage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 12rpx;
|
||||
gap: 10rpx;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.avatar-ring {
|
||||
.avatar-body {
|
||||
width: 200rpx;
|
||||
height: 200rpx;
|
||||
border-radius: 50%;
|
||||
height: 260rpx;
|
||||
border-radius: 20rpx;
|
||||
border: 4rpx solid #E5E7EB;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
transition: border-color 0.3s, box-shadow 0.3s;
|
||||
animation: breathing 4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.avatar-ring.speaking {
|
||||
.avatar-body.speaking {
|
||||
border-color: #6366F1;
|
||||
box-shadow: 0 0 30rpx rgba(99, 102, 241, 0.3);
|
||||
box-shadow: 0 0 40rpx rgba(99, 102, 241, 0.4);
|
||||
animation: speakPulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
@keyframes speakPulse {
|
||||
0%, 100% { box-shadow: 0 0 20rpx rgba(99, 102, 241, 0.3); }
|
||||
50% { box-shadow: 0 0 50rpx rgba(99, 102, 241, 0.6); }
|
||||
}
|
||||
@keyframes breathing {
|
||||
0%, 100% { transform: scale(1); }
|
||||
50% { transform: scale(1.012); }
|
||||
}
|
||||
|
||||
.avatar-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.avatar-default {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(135deg, #6366F1, #8B5CF6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
.mouth-overlay {
|
||||
position: absolute;
|
||||
top: 36.8%;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
transition: all 0.08s cubic-bezier(0.25, 0.1, 0.25, 1);
|
||||
}
|
||||
|
||||
.avatar-initials {
|
||||
font-size: 48rpx;
|
||||
font-weight: 700;
|
||||
color: #FFFFFF;
|
||||
.status-dot {
|
||||
width: 14rpx;
|
||||
height: 14rpx;
|
||||
border-radius: 50%;
|
||||
background: #9CA3AF;
|
||||
position: absolute;
|
||||
top: 8rpx;
|
||||
right: 8rpx;
|
||||
transition: background 0.3s;
|
||||
}
|
||||
|
||||
.mouth-canvas {
|
||||
pointer-events: none;
|
||||
.status-dot.active {
|
||||
background: #10B981;
|
||||
box-shadow: 0 0 12rpx rgba(16, 185, 129, 0.6);
|
||||
}
|
||||
|
||||
.role-label {
|
||||
font-size: 22rpx;
|
||||
color: #6B7280;
|
||||
@@ -256,23 +249,19 @@ defineExpose({ play: playAudio, stop: stopAudio })
|
||||
padding: 4rpx 20rpx;
|
||||
border-radius: 20rpx;
|
||||
}
|
||||
|
||||
/* Speech bubble */
|
||||
.speech-area {
|
||||
margin-top: 24rpx;
|
||||
margin-top: 12rpx;
|
||||
padding: 0 40rpx;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.speech-bubble {
|
||||
background: #FFFFFF;
|
||||
border-radius: 16rpx;
|
||||
padding: 24rpx 28rpx;
|
||||
padding: 20rpx 24rpx;
|
||||
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.speech-bubble::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
@@ -282,10 +271,9 @@ defineExpose({ play: playAudio, stop: stopAudio })
|
||||
border-bottom-color: #FFFFFF;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.speech-text {
|
||||
font-size: 28rpx;
|
||||
line-height: 1.7;
|
||||
font-size: 26rpx;
|
||||
line-height: 1.6;
|
||||
color: #1F2937;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -98,11 +98,19 @@ export const API_ENDPOINTS = {
|
||||
CHECK: (outTradeNo: string) => `/payment/check/${outTradeNo}`,
|
||||
ACTIVATE: '/payment/activate',
|
||||
},
|
||||
TTS: {
|
||||
SYNTHESIZE: '/tts/synthesize',
|
||||
AUDIO: (hash: string) => `/tts/audio/${hash}`,
|
||||
},
|
||||
} 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}`, },
|
||||
} as const
|
||||
|
||||
const PROD_API_HOST = import.meta.env.VITE_PROD_API_HOST || 'https://zhiyinwx.yzrcloud.cn'
|
||||
const DEV_API_HOST = 'http://localhost:3006'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "宇之然AI磁场",
|
||||
"appid": "__UNI__DEV__",
|
||||
"versionName": "1.0.5",
|
||||
"versionCode": "105",
|
||||
"versionName": "1.0.11",
|
||||
"versionCode": "111",
|
||||
"description": "职引 - 宇之然AI磁场旗下AI模拟面试平台,提供AI面试官模拟练习、简历智能优化、大厂面经题库,助你轻松应对校招面试。",
|
||||
"h5": {
|
||||
"title": "职引 - AI模拟面试 | 宇之然AI磁场",
|
||||
|
||||
@@ -16,7 +16,9 @@
|
||||
{ "path": "pages/admin/admin", "style": { "navigationBarTitleText": "管理后台" } },
|
||||
{ "path": "pages/result/result", "style": { "navigationBarTitleText": "优化结果" } },
|
||||
{ "path": "pages/agreement/agreement", "style": { "navigationBarTitleText": "用户协议" } },
|
||||
{ "path": "pages/privacy/privacy", "style": { "navigationBarTitleText": "隐私政策" } }
|
||||
{ "path": "pages/privacy/privacy", "style": { "navigationBarTitleText": "隐私政策" } },
|
||||
{ "path": "pages/share/share", "style": { "navigationBarTitleText": "我的分享" } }
|
||||
{"path": "pages/review/review", "style": {"navigationBarTitleText": "面试复盘"}},
|
||||
],
|
||||
"tabBar": {
|
||||
"color": "#999999",
|
||||
|
||||
@@ -17,8 +17,10 @@
|
||||
<text class="tab" :class="{ active: tab === 'overview' }" @click="switchTab('overview')">概览</text>
|
||||
<text class="tab" :class="{ active: tab === 'users' }" @click="switchTab('users')">用户</text>
|
||||
<text class="tab" :class="{ active: tab === 'interviews' }" @click="switchTab('interviews')">面试</text>
|
||||
<text class="tab" :class="{ active: tab === 'resumes' }" @click="switchTab('resumes')">简历</text>
|
||||
<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 === 'admins' }" @click="switchTab('admins')">管理</text>
|
||||
</view>
|
||||
|
||||
@@ -35,6 +37,17 @@
|
||||
<text class="stat-label">总面试</text>
|
||||
<text class="stat-sub">今日 +{{ overview.todayInterviews }}</text>
|
||||
</view>
|
||||
<view class="stat-card">
|
||||
<text class="stat-num">{{ overview.resumeCount ?? 0 }}</text>
|
||||
<text class="stat-label">总简历</text>
|
||||
<text class="stat-sub">付费下载 {{ overview.paidDownloadCount ?? 0 }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="plan-cards">
|
||||
<view class="plan-card" v-for="(cnt, plan) in overview.planBreakdown" :key="plan">
|
||||
<text class="plan-num">{{ cnt }}</text>
|
||||
<text class="plan-label">{{ planNameMap[plan] || plan }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -46,12 +59,22 @@
|
||||
</view>
|
||||
<view class="user-list" v-if="!usersLoading">
|
||||
<view class="user-row" v-for="u in users" :key="u._id">
|
||||
<view class="user-main">
|
||||
<text class="user-phone">{{ u.phone || '--' }}</text>
|
||||
<text class="user-name">{{ u.nickname || '--' }}</text>
|
||||
<text class="user-plan" :class="{ vip: u.plan === 'vip' }">{{ u.plan === 'vip' ? '会员' : '免费' }}</text>
|
||||
<text class="user-remaining">剩{{ u.remaining || 0 }}次</text>
|
||||
<text class="user-vip-btn" v-if="u.plan !== 'vip'" @click="setVip(u._id)">设为会员</text>
|
||||
</view>
|
||||
<view class="user-badges">
|
||||
<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 === 'free'" @click="setVip(u._id)">设为会员</text>
|
||||
<text class="user-action-btn credit" @click="openCreditModal(u)">调整额度</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="load-more" v-if="usersTotal > users.length" @click="loadMoreUsers">加载更多</text>
|
||||
</view>
|
||||
<text class="loading-text" v-if="usersLoading">加载中...</text>
|
||||
@@ -61,15 +84,41 @@
|
||||
<view v-if="tab === 'interviews'" class="section">
|
||||
<view class="iv-list" v-if="!ivLoading">
|
||||
<view class="iv-row" v-for="iv in interviews" :key="iv._id">
|
||||
<text class="iv-pos">{{ iv.position }}</text>
|
||||
<text class="iv-user">{{ iv.userId?.phone || iv.userId?.nickname || '--' }}</text>
|
||||
<text class="iv-status" :class="{ done: iv.status === 'completed' }">{{ iv.status === 'completed' ? '已完成' : '进行中' }}</text>
|
||||
<text class="iv-questions">{{ iv.questionCount || 0 }}题</text>
|
||||
<view class="iv-main">
|
||||
<text class="iv-pos">{{ iv.position }}</text>
|
||||
<text class="iv-user">{{ iv.userId?.phone || iv.userId?.nickname || '--' }}</text>
|
||||
</view>
|
||||
<view class="iv-meta">
|
||||
<text class="iv-status" :class="{ done: iv.status === 'completed' }">{{ iv.status === 'completed' ? '已完成' : '进行中' }}</text>
|
||||
<text class="iv-tag">{{ iv.questionCount || 0 }}题</text>
|
||||
<text class="iv-tag score">得分 {{ iv.totalScore ?? '-' }}</text>
|
||||
<text class="iv-tag filler" v-if="iv.fillerScore != null && iv.fillerScore > 0">语分析 {{ iv.fillerScore }}/{{ iv.fillerDensity ?? '-' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
<text class="loading-text" v-if="ivLoading">加载中...</text>
|
||||
</view>
|
||||
|
||||
<!-- 简历 -->
|
||||
<view v-if="tab === 'resumes'" class="section">
|
||||
<view class="resume-list" v-if="!resumeLoading">
|
||||
<view class="resume-row" v-for="r in resumes" :key="r._id">
|
||||
<view class="resume-main">
|
||||
<text class="resume-title">{{ r.title }}</text>
|
||||
<text class="resume-user">{{ r.userId?.phone || r.userId?.nickname || '--' }}</text>
|
||||
</view>
|
||||
<view class="resume-meta">
|
||||
<text class="resume-tag">v{{ r.version }}</text>
|
||||
<text class="resume-tag" v-if="r.targetPosition">{{ r.targetPosition }}</text>
|
||||
<text class="resume-tag paid" v-if="r.paidDownload">付费下载</text>
|
||||
</view>
|
||||
<text class="resume-time">{{ r.createdAt?.slice(0,10) }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="loading-text" v-if="resumeLoading">加载中...</text>
|
||||
<text class="empty-text" v-if="!resumeLoading && resumes.length === 0">暂无简历</text>
|
||||
</view>
|
||||
|
||||
|
||||
|
||||
<!-- 订单 -->
|
||||
@@ -183,6 +232,60 @@
|
||||
<button class="save-btn" @click="savePricing" :disabled="pricingLoading">保存定价配置</button>
|
||||
<text class="loading-text" v-if="pricingLoading">保存中...</text>
|
||||
</view>
|
||||
<!-- 分享 -->
|
||||
<view v-if="tab === 'share'" class="section">
|
||||
<view class="tabs in-tab">
|
||||
<text class="tab" :class="{ active: shareSubTab === 'records' }" @click="shareSubTab='records';loadShareRecords()">分享记录</text>
|
||||
<text class="tab" :class="{ active: shareSubTab === 'visitors' }" @click="shareSubTab='visitors';loadShareVisitors()">访问记录</text>
|
||||
</view>
|
||||
<view v-if="shareSubTab === 'records'">
|
||||
<view class="share-list" v-if="!shareLoading">
|
||||
<view class="share-row" v-for="r in shareRecords" :key="r.shareCode">
|
||||
<view class="share-main">
|
||||
<text class="share-title">{{ r.title }}</text>
|
||||
<text class="share-meta">{{ r.sharer?.nickname || '--' }} · {{ r.type }}</text>
|
||||
</view>
|
||||
<view class="share-stats">
|
||||
<text>访问 {{ r.visitCount }}</text>
|
||||
<text class="share-credited">有效 {{ r.creditedCount }}</text>
|
||||
</view>
|
||||
<text class="share-time">{{ r.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="loading-text" v-if="shareLoading">加载中...</text>
|
||||
<text class="empty-text" v-if="!shareLoading && shareRecords.length === 0">暂无分享记录</text>
|
||||
</view>
|
||||
<view v-if="shareSubTab === 'visitors'">
|
||||
<view class="share-list" v-if="!shareLoading">
|
||||
<view class="share-row" v-for="(v, i) in shareVisitors" :key="i">
|
||||
<view class="share-main">
|
||||
<text>分享者: {{ v.sharer?.nickname || '--' }}</text>
|
||||
<text class="share-meta">访客: {{ v.visitor?.nickname || '匿名' }}</text>
|
||||
</view>
|
||||
<view class="share-stats">
|
||||
<text class="badge" :class="v.credited ? 'badge-done' : 'badge-pend'">{{ v.credited ? '已积分' : '未积分' }}</text>
|
||||
</view>
|
||||
<text class="share-time">{{ v.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="loading-text" v-if="shareLoading">加载中...</text>
|
||||
<text class="empty-text" v-if="!shareLoading && shareVisitors.length === 0">暂无访问记录</text>
|
||||
</view>
|
||||
</view>
|
||||
<!-- 额度调整弹窗 -->
|
||||
<view class="modal-mask" v-if="creditModal.show" @click="closeCreditModal">
|
||||
<view class="modal-content" @click.stop>
|
||||
<text class="modal-title">调整 {{ creditModal.user?.nickname || '用户' }} 的额度</text>
|
||||
<view class="cfg-row" v-for="t in creditTypes" :key="t.key">
|
||||
<text>{{ t.label }}</text>
|
||||
<input class="cfg-input" type="digit" v-model.number="t.value" :placeholder="t.key" />
|
||||
</view>
|
||||
<view class="modal-actions">
|
||||
<button class="modal-btn cancel" @click="closeCreditModal">取消</button>
|
||||
<button class="modal-btn confirm" @click="doAdjustCredits">确认调整</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
<!-- 管理员 -->
|
||||
<view v-if="tab === 'admins'" class="section">
|
||||
<view class="search-bar">
|
||||
@@ -219,20 +322,24 @@ import { api, API_ENDPOINTS } from '../../config'
|
||||
const verified = ref(false)
|
||||
const adminName = ref('')
|
||||
const tab = ref('overview')
|
||||
const shareSubTab = ref('records')
|
||||
const loading = ref(false)
|
||||
const usersLoading = ref(false)
|
||||
const ivLoading = ref(false)
|
||||
const userKeyword = ref('')
|
||||
const usersPage = ref(1)
|
||||
|
||||
const overview = ref({ userCount: 0, interviewCount: 0, todayUsers: 0, todayInterviews: 0 })
|
||||
const overview = ref({ userCount: 0, interviewCount: 0, todayUsers: 0, todayInterviews: 0, resumeCount: 0, paidDownloadCount: 0, planBreakdown: {} })
|
||||
const planNameMap = { free: '免费', growth: '成长', sprint: '冲刺', vip: '会员' }
|
||||
const users = ref([])
|
||||
const usersTotal = ref(0)
|
||||
const interviews = ref([])
|
||||
const resumes = ref([])
|
||||
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 },
|
||||
@@ -253,7 +360,7 @@ 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)
|
||||
@@ -261,6 +368,20 @@ const ordersPage = ref(1)
|
||||
const orderLoading = ref(false)
|
||||
const orderFilter = ref('')
|
||||
|
||||
// Share state
|
||||
const shareRecords = ref([])
|
||||
const shareVisitors = ref([])
|
||||
const shareLoading = ref(false)
|
||||
|
||||
// Credit modal
|
||||
const creditModal = ref({ show: false, user: null })
|
||||
const creditTypes = ref([
|
||||
{ key: 'interviewCredits', label: '面试次数', value: 0 },
|
||||
{ key: 'resumeOptimizeCredits', label: '优化次数', value: 0 },
|
||||
{ key: 'resumeDownloadCredits', label: '下载次数', value: 0 },
|
||||
{ key: 'shareCredits', label: '分享积分', value: 0 },
|
||||
])
|
||||
|
||||
const token = () => uni.getStorageSync('token') || ''
|
||||
|
||||
const apiAdmin = (path, opts = {}) => {
|
||||
@@ -278,7 +399,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('无管理员权限')
|
||||
@@ -300,6 +421,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 === 'resumes' && resumes.value.length === 0) loadResumes()
|
||||
if (t === 'admins' && adminList.value.length === 0) loadAdmins()
|
||||
if (t === 'pricing') loadPricing()
|
||||
if (t === 'orders') loadOrders()
|
||||
@@ -332,6 +454,15 @@ const loadInterviews = async () => {
|
||||
finally { ivLoading.value = false }
|
||||
}
|
||||
|
||||
const loadResumes = async () => {
|
||||
resumeLoading.value = true
|
||||
try {
|
||||
const res = await apiAdmin('/resumes?page=1&limit=20')
|
||||
if (res.statusCode === 200) resumes.value = res.data.list || []
|
||||
} catch (e) { console.error(e) }
|
||||
finally { resumeLoading.value = false }
|
||||
}
|
||||
|
||||
const loadPricing = async () => {
|
||||
pricingLoading.value = true
|
||||
try {
|
||||
@@ -369,15 +500,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
|
||||
@@ -462,6 +584,54 @@ const setVip = async (targetUserId) => {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const loadShareRecords = async () => {
|
||||
shareLoading.value = true
|
||||
try {
|
||||
const res = await apiAdmin('/share-records?page=1&limit=50')
|
||||
if (res.statusCode === 200) shareRecords.value = res.data.list || []
|
||||
} catch(e) { console.error(e) }
|
||||
finally { shareLoading.value = false }
|
||||
}
|
||||
|
||||
const loadShareVisitors = async () => {
|
||||
shareLoading.value = true
|
||||
try {
|
||||
const res = await apiAdmin('/share-visitors?page=1&limit=50')
|
||||
if (res.statusCode === 200) shareVisitors.value = res.data.list || []
|
||||
} catch(e) { console.error(e) }
|
||||
finally { shareLoading.value = false }
|
||||
}
|
||||
|
||||
const openCreditModal = (user) => {
|
||||
creditTypes.value = [
|
||||
{ key: 'interviewCredits', label: '面试次数', value: user.interviewCredits ?? 0 },
|
||||
{ key: 'resumeOptimizeCredits', label: '优化次数', value: user.resumeOptimizeCredits ?? 0 },
|
||||
{ key: 'resumeDownloadCredits', label: '下载次数', value: user.resumeDownloadCredits ?? 0 },
|
||||
{ key: 'shareCredits', label: '分享积分', value: user.shareCredits ?? 0 },
|
||||
]
|
||||
creditModal.value = { show: true, user }
|
||||
}
|
||||
|
||||
const closeCreditModal = () => {
|
||||
creditModal.value = { show: false, user: null }
|
||||
}
|
||||
|
||||
const doAdjustCredits = async () => {
|
||||
const userId = creditModal.value.user?._id
|
||||
if (!userId) return
|
||||
try {
|
||||
for (const t of creditTypes.value) {
|
||||
await apiAdmin('/user/credits', {
|
||||
method: 'POST',
|
||||
data: { userId, type: t.key, amount: t.value },
|
||||
})
|
||||
}
|
||||
uni.showToast({ title: '调整成功', icon: 'success' })
|
||||
closeCreditModal()
|
||||
loadUsers()
|
||||
} catch { uni.showToast({ title: '调整失败', icon: 'none' }) }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -481,22 +651,37 @@ const setVip = async (targetUserId) => {
|
||||
.stat-num { font-size: 48rpx; font-weight: 800; color: var(--color-primary); display: block; }
|
||||
.stat-label { font-size: 22rpx; color: var(--color-text-secondary); margin-top: 8rpx; display: block; }
|
||||
.stat-sub { font-size: 20rpx; color: var(--color-success); margin-top: 4rpx; display: block; }
|
||||
.plan-cards { display: flex; gap: 12rpx; margin-top: 16rpx; }
|
||||
.plan-card { flex: 1; background: #FFF; border-radius: var(--radius-sm); padding: 20rpx; text-align: center; box-shadow: var(--shadow-sm); }
|
||||
.plan-num { font-size: 36rpx; font-weight: 700; color: var(--color-primary); display: block; }
|
||||
.plan-label { font-size: 20rpx; color: var(--color-text-secondary); margin-top: 4rpx; display: block; }
|
||||
.search-bar { display: flex; gap: 12rpx; margin-bottom: 16rpx; }
|
||||
.search-input { flex: 1; height: 64rpx; background: #FFF; border: 2rpx solid var(--color-border); border-radius: var(--radius-sm); padding: 0 16rpx; font-size: 24rpx; }
|
||||
.search-btn { height: 64rpx; padding: 0 24rpx; background: var(--color-primary); color: #FFF; border-radius: var(--radius-sm); font-size: 24rpx; border: none; }
|
||||
.user-row { background: #FFF; padding: 20rpx; border-radius: var(--radius-sm); margin-bottom: 8rpx; display: flex; flex-wrap: wrap; gap: 8rpx; }
|
||||
.user-row { background: #FFF; padding: 20rpx; border-radius: var(--radius-sm); margin-bottom: 8rpx; }
|
||||
.user-main { display: flex; gap: 12rpx; margin-bottom: 8rpx; }
|
||||
.user-phone { font-size: 24rpx; font-weight: 600; color: var(--color-text); }
|
||||
.user-name { font-size: 22rpx; color: var(--color-text-secondary); }
|
||||
.user-badges { display: flex; flex-wrap: wrap; gap: 6rpx; margin-bottom: 8rpx; }
|
||||
.user-plan { font-size: 20rpx; background: #EEF2FF; color: var(--color-primary); padding: 2rpx 12rpx; border-radius: var(--radius-round); }
|
||||
.user-remaining { font-size: 20rpx; color: var(--color-text-tertiary); }
|
||||
.user-plan.vip { background: #FEF3C7; color: #D97706; }
|
||||
.user-credit { font-size: 18rpx; background: #F3F4F6; color: var(--color-text-tertiary); padding: 2rpx 10rpx; border-radius: var(--radius-round); }
|
||||
.user-credit.share { background: #FFF7ED; color: #D97706; }
|
||||
.user-actions { display: flex; gap: 12rpx; }
|
||||
.user-action-btn { font-size: 20rpx; color: var(--color-primary); padding: 4rpx 16rpx; border: 2rpx solid var(--color-primary); border-radius: var(--radius-round); }
|
||||
.user-action-btn.credit { color: #D97706; border-color: #D97706; }
|
||||
.loading-text { text-align: center; padding: 40rpx; color: var(--color-text-tertiary); font-size: 24rpx; }
|
||||
.load-more { text-align: center; padding: 20rpx; color: var(--color-primary); font-size: 24rpx; display: block; }
|
||||
.iv-row { background: #FFF; padding: 20rpx; border-radius: var(--radius-sm); margin-bottom: 8rpx; display: flex; flex-wrap: wrap; gap: 8rpx; align-items: center; }
|
||||
.iv-row { background: #FFF; padding: 16rpx; border-radius: var(--radius-sm); margin-bottom: 8rpx; }
|
||||
.iv-main { display: flex; gap: 12rpx; margin-bottom: 6rpx; }
|
||||
.iv-pos { font-size: 24rpx; font-weight: 600; color: var(--color-text); }
|
||||
.iv-user { font-size: 22rpx; color: var(--color-text-secondary); }
|
||||
.iv-meta { display: flex; flex-wrap: wrap; gap: 6rpx; }
|
||||
.iv-status { font-size: 20rpx; background: #FFF7ED; color: var(--color-warning); padding: 2rpx 12rpx; border-radius: var(--radius-round); }
|
||||
.iv-status.done { background: #ECFDF5; color: var(--color-success); }
|
||||
.iv-questions { font-size: 20rpx; color: var(--color-text-tertiary); }
|
||||
.iv-tag { font-size: 18rpx; background: #F3F4F6; color: var(--color-text-tertiary); padding: 2rpx 10rpx; border-radius: var(--radius-round); }
|
||||
.iv-tag.score { background: #EEF2FF; color: var(--color-primary); }
|
||||
.iv-tag.filler { background: #FFF7ED; color: #D97706; }
|
||||
.section-label { font-size: 24rpx; font-weight: 600; color: var(--color-text); margin-bottom: 12rpx; margin-top: 12rpx; }
|
||||
.admin-row { background: #FFF; padding: 20rpx; border-radius: var(--radius-sm); margin-bottom: 8rpx; display: flex; flex-wrap: wrap; gap: 8rpx; align-items: center; }
|
||||
.admin-phone { font-size: 24rpx; font-weight: 600; color: var(--color-text); }
|
||||
@@ -505,6 +690,15 @@ const setVip = async (targetUserId) => {
|
||||
.admin-set-btn.done { color: var(--color-success); border-color: var(--color-success); }
|
||||
.admin-badge { font-size: 18rpx; background: var(--color-primary); color: #FFF; padding: 2rpx 10rpx; border-radius: var(--radius-round); }
|
||||
.empty-text { text-align: center; padding: 20rpx; color: var(--color-text-tertiary); font-size: 22rpx; display: block; }
|
||||
.resume-list { display: flex; flex-direction: column; gap: 8rpx; }
|
||||
.resume-row { background: #FFF; padding: 16rpx; border-radius: var(--radius-sm); display: flex; align-items: center; gap: 12rpx; }
|
||||
.resume-main { flex: 1; display: flex; flex-direction: column; }
|
||||
.resume-title { font-size: 22rpx; font-weight: 600; color: var(--color-text); }
|
||||
.resume-user { font-size: 20rpx; color: var(--color-text-secondary); margin-top: 2rpx; }
|
||||
.resume-meta { display: flex; gap: 6rpx; }
|
||||
.resume-tag { font-size: 18rpx; background: #F3F4F6; color: var(--color-text-tertiary); padding: 2rpx 10rpx; border-radius: var(--radius-round); }
|
||||
.resume-tag.paid { background: #FEF3C7; color: #D97706; }
|
||||
.resume-time { font-size: 18rpx; color: #D1D5DB; white-space: nowrap; }
|
||||
.order-list { display: flex; flex-direction: column; gap: 8rpx; }
|
||||
.order-row { background: #FFF; border-radius: var(--radius-sm); padding: 16rpx; }
|
||||
.order-info { display: flex; justify-content: space-between; margin-bottom: 8rpx; }
|
||||
@@ -527,4 +721,23 @@ const setVip = async (targetUserId) => {
|
||||
.cfg-textarea { width: 100%; height: 160rpx; border: 2rpx solid var(--color-border); border-radius: var(--radius-sm); padding: 12rpx; font-size: 22rpx; margin-top: 8rpx; box-sizing: border-box; }
|
||||
.save-btn { width: 100%; height: 72rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #FFF; border-radius: var(--radius-sm); font-size: 26rpx; border: none; margin-top: 12rpx; }
|
||||
.save-btn:disabled { opacity: 0.6; }
|
||||
.in-tab { margin-bottom: 16rpx; }
|
||||
.share-list { display: flex; flex-direction: column; gap: 8rpx; }
|
||||
.share-row { background: #FFF; padding: 16rpx; border-radius: var(--radius-sm); display: flex; align-items: center; gap: 12rpx; }
|
||||
.share-main { flex: 1; display: flex; flex-direction: column; }
|
||||
.share-title { font-size: 22rpx; color: var(--color-text); font-weight: 500; }
|
||||
.share-meta { font-size: 18rpx; color: var(--color-text-tertiary); margin-top: 2rpx; }
|
||||
.share-stats { display: flex; flex-direction: column; align-items: flex-end; font-size: 20rpx; color: var(--color-text-tertiary); }
|
||||
.share-credited { color: var(--color-primary); }
|
||||
.share-time { font-size: 18rpx; color: #D1D5DB; white-space: nowrap; }
|
||||
.badge { font-size: 18rpx; padding: 2rpx 10rpx; border-radius: 6rpx; }
|
||||
.badge-done { background: #ECFDF5; color: #059669; }
|
||||
.badge-pend { background: #FEF3C7; color: #D97706; }
|
||||
.modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.4); display: flex; align-items: center; justify-content: center; z-index: 999; }
|
||||
.modal-content { background: #FFF; border-radius: var(--radius-lg); padding: 40rpx 32rpx; width: 600rpx; max-width: 90vw; }
|
||||
.modal-title { font-size: 28rpx; font-weight: 600; color: var(--color-text); margin-bottom: 24rpx; }
|
||||
.modal-actions { display: flex; gap: 16rpx; margin-top: 32rpx; }
|
||||
.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; }
|
||||
</style>
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
@tap="selectCompany(c.name)"
|
||||
>
|
||||
<view class="company-name">{{ c.name }}</view>
|
||||
<view class="company-count">{{ c.positions }} 个岗位</view>
|
||||
<view class="company-count">{{ c.positionCount > 0 ? c.positionCount + ' 个岗位' : '暂无题库' }}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -84,23 +84,12 @@
|
||||
<script>
|
||||
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 },
|
||||
]
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
keyword: '',
|
||||
searching: false,
|
||||
hotCompanies: HOT_COMPANIES,
|
||||
hotCompanies: [],
|
||||
selectedCompany: '',
|
||||
selectedPosition: '',
|
||||
positions: [],
|
||||
@@ -109,7 +98,18 @@ export default {
|
||||
loadingQuestions: false,
|
||||
}
|
||||
},
|
||||
onLoad() {
|
||||
this.loadHotCompanies()
|
||||
},
|
||||
methods: {
|
||||
async loadHotCompanies() {
|
||||
try {
|
||||
const res = await uni.request({ url: api('/contribution/companies/hot'), method: 'GET' })
|
||||
if (res.statusCode === 200) this.hotCompanies = res.data || []
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
},
|
||||
difficultyLabel(d) {
|
||||
const map = { junior: '简单', medium: '中等', senior: '困难' }
|
||||
return map[d] || d || '中等'
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,19 +1,32 @@
|
||||
<template>
|
||||
<view class="page fade-in">
|
||||
<view class="hero">
|
||||
<text class="hero-title">{{ greeting }}</text>
|
||||
<text class="hero-sub">试试下面的功能,开启你的求职练习</text>
|
||||
|
||||
<view class="user-card card" v-if="userInfo" @click="goProfile">
|
||||
<image class="avatar" :src="userInfo.avatar || '/static/avatar-default.svg'" mode="aspectFill" />
|
||||
<view class="user-meta">
|
||||
<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>
|
||||
<view class="hero-row">
|
||||
<view class="hero-left">
|
||||
<text class="hero-title">{{ greeting }}</text>
|
||||
<text class="hero-sub">试试下面的功能,开启你的求职练习</text>
|
||||
</view>
|
||||
<view class="hero-right">
|
||||
<view class="user-card card" v-if="userInfo" @click="goProfile">
|
||||
<image class="avatar" :src="userInfo.avatar || '/static/avatar-default.png'" mode="aspectFill" />
|
||||
<view class="user-meta">
|
||||
<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.interviewCredits > 0 ? '剩余 ' + userInfo.interviewCredits + ' 次' : '已用完' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="arrow">›</text>
|
||||
</view>
|
||||
<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>
|
||||
</view>
|
||||
<text class="arrow">›</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="arrow">›</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -24,13 +37,20 @@
|
||||
<view class="fp-left">
|
||||
<view class="fp-icon fp-interview"><text class="fp-emoji">🎙️</text></view>
|
||||
<view class="fp-body">
|
||||
<text class="fp-name">模拟面试</text>
|
||||
<text class="fp-brief">AI 面试官 · 真实场景 · 即时反馈</text>
|
||||
<text class="fp-name">AI数字人面试</text>
|
||||
<text class="fp-brief">数字人考官 · 真实场景 · 语音互动 · 即时反馈</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="fp-action">开始</text>
|
||||
</view>
|
||||
<view class="feature-secondary">
|
||||
<view class="feature-tertiary">
|
||||
<view class="fs-card card" @click="goResume">
|
||||
<view class="fs-top">
|
||||
<view class="fs-icon fs-resume"><text class="fs-emoji">📄</text></view>
|
||||
<text class="fs-name">简历优化</text>
|
||||
</view>
|
||||
<text class="fs-brief">AI 诊断 · 智能优化 · 一键下载</text>
|
||||
</view>
|
||||
<view class="fs-card card" @click="goProgress">
|
||||
<view class="fs-top">
|
||||
<view class="fs-icon fs-progress"><text class="fs-emoji">📊</text></view>
|
||||
@@ -92,19 +112,18 @@
|
||||
<view class="section-header">
|
||||
<view class="section-title-row">
|
||||
<text class="section-title">热门岗位</text>
|
||||
<text class="section-tag-demo">参考示例</text>
|
||||
</view>
|
||||
<text class="section-desc">点击直接面试</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="pos-left">
|
||||
<text class="pos-icon">{{ posIcons[idx] || '💼' }}</text>
|
||||
<text class="pos-icon">{{ 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>
|
||||
@@ -122,6 +141,7 @@
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { api } from '../../config'
|
||||
|
||||
const userInfo = ref(null)
|
||||
@@ -132,8 +152,12 @@ const positionsLoading = ref(true)
|
||||
const dailyQuestion = ref(null)
|
||||
const showAnswer = ref(false)
|
||||
|
||||
const loadUserInfo = () => {
|
||||
try { const s = uni.getStorageSync('userInfo'); if (s) userInfo.value = JSON.parse(s); else userInfo.value = null } catch (e) { userInfo.value = null }
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try { const s = uni.getStorageSync('userInfo'); if (s) userInfo.value = JSON.parse(s) } catch (e) {}
|
||||
loadUserInfo()
|
||||
const h = new Date().getHours()
|
||||
if (h < 6) greeting.value = '夜深了,早点休息 🌙'
|
||||
else if (h < 12) greeting.value = '早上好 ☀️'
|
||||
@@ -163,10 +187,26 @@ onMounted(async () => {
|
||||
finally { positionsLoading.value = false }
|
||||
})
|
||||
|
||||
const refreshDaily = () => { showAnswer.value = false; /* trigger reload */ }
|
||||
onShow(loadUserInfo)
|
||||
|
||||
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' })
|
||||
const goInterview = () => uni.navigateTo({ url: '/pages/interview/interview' })
|
||||
const goResume = () => uni.navigateTo({ url: '/pages/resume/resume' })
|
||||
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' })
|
||||
@@ -182,16 +222,24 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
|
||||
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-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-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; }
|
||||
|
||||
.user-card {
|
||||
.user-card, .guest-card {
|
||||
background: rgba(255,255,255,0.95); backdrop-filter: blur(20rpx);
|
||||
border-radius: var(--radius-xl); padding: 24rpx 28rpx;
|
||||
display: flex; align-items: center; margin-top: 24rpx;
|
||||
border-radius: var(--radius-xl); padding: 20rpx 24rpx;
|
||||
display: flex; align-items: center;
|
||||
box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.1);
|
||||
}
|
||||
.avatar { width: 88rpx; height: 88rpx; border-radius: 50%; margin-right: 20rpx; border: 3rpx solid var(--color-primary-light); flex-shrink: 0; }
|
||||
.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); }
|
||||
.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); }
|
||||
.user-tags { display: flex; gap: 10rpx; margin-top: 10rpx; }
|
||||
@@ -205,7 +253,6 @@ 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-desc { font-size: 22rpx; color: var(--color-primary); }
|
||||
|
||||
.feature-list { display: flex; flex-direction: column; gap: 16rpx; }
|
||||
@@ -223,6 +270,7 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
|
||||
.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; }
|
||||
.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; }
|
||||
@@ -230,7 +278,8 @@ const startInterview = (pos) => uni.navigateTo({ url: `/pages/interview/intervie
|
||||
.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-contribute { background: linear-gradient(135deg, #ECFDF5, #A7F3D0); }
|
||||
.fs-resume { background: linear-gradient(135deg, #ECFDF5, #A7F3D0); }
|
||||
.fs-contribute { background: linear-gradient(135deg, #FFF7ED, #FDBA74); }
|
||||
|
||||
/* 每日一题 */
|
||||
.daily-card { padding: 24rpx; border-radius: var(--radius-lg); }
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
ref="dhRef"
|
||||
:text="aiSpeechText"
|
||||
:audio-url="aiAudioUrl"
|
||||
:amplitude-data="aiAmplitudeData"
|
||||
:position="position"
|
||||
:auto-play="true"
|
||||
@speaking-start="onAvatarSpeaking"
|
||||
@speaking-end="onAvatarSilent"
|
||||
@@ -53,11 +55,14 @@
|
||||
</scroll-view>
|
||||
|
||||
<view class="input-bar" v-if="!isComplete">
|
||||
<view class="mic-btn" :class="{ recording: isRecording }" @touchstart="startRecord" @touchend="stopRecord" @touchcancel="stopRecord" @mousedown="startRecord" @mouseup="stopRecord" @mouseleave="stopRecord">
|
||||
<text class="mic-icon">🎤</text>
|
||||
</view>
|
||||
<view class="input-box">
|
||||
<textarea class="input-area" v-model="inputText" placeholder="输入你的回答..." :auto-height="true" :maxlength="2000" :disabled="aiLoading" @confirm="sendAnswer" />
|
||||
</view>
|
||||
<view class="send-btn" :class="{ disabled: !inputText.trim() || aiLoading }" @click="sendAnswer">
|
||||
<text class="send-icon">➤</text>
|
||||
<view class="send-btn" :class="{ disabled: (!inputText.trim() && !isRecording) || aiLoading }" @click="sendAnswer">
|
||||
<text class="send-icon">{{ isRecording ? '◉' : '➤' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -83,21 +88,25 @@ const answeredCount = ref(0)
|
||||
const isComplete = ref(false)
|
||||
const scrollToId = ref('')
|
||||
const position = ref('')
|
||||
const avatarMode = ref(false)
|
||||
const avatarMode = ref(true)
|
||||
const aiSpeechText = ref('')
|
||||
const aiAudioUrl = ref('')
|
||||
const aiAmplitudeData = ref([])
|
||||
const isSpeaking = ref(false)
|
||||
const dhRef = ref(null)
|
||||
const isRecording = ref(false)
|
||||
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) {
|
||||
@@ -109,7 +118,7 @@ onLoad((options) => {
|
||||
|
||||
onMounted(() => {
|
||||
timerInterval = setInterval(() => timerSeconds++, 1000)
|
||||
if (token.value) startInterview()
|
||||
if (token()) startInterview()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -117,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' }) },
|
||||
@@ -133,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: '创建面试失败,请重试' })
|
||||
@@ -156,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 })
|
||||
@@ -168,21 +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')
|
||||
// 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) {
|
||||
// In avatar mode, only show avatar speaking, don't add to chat
|
||||
await speakAiText(aiMsg.content, res.data.ttsHash)
|
||||
} else {
|
||||
messages.value.push(...res.data.messages)
|
||||
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: '回答提交失败,请重试' })
|
||||
@@ -192,19 +211,21 @@ const sendAnswer = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function speakAiText(text, ttsHash) {
|
||||
async function speakAiText(text, ttsHash, ttsAmplitude) {
|
||||
aiSpeechText.value = text
|
||||
aiAmplitudeData.value = ttsAmplitude || []
|
||||
if (ttsHash) {
|
||||
aiAudioUrl.value = api(API_ENDPOINTS.TTS.AUDIO(ttsHash))
|
||||
} else {
|
||||
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) {
|
||||
aiAudioUrl.value = api(API_ENDPOINTS.TTS.AUDIO(synthRes.data.hash))
|
||||
aiAmplitudeData.value = synthRes.data?.amplitudeData || []
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
@@ -229,6 +250,51 @@ const confirmExit = () => {
|
||||
success: (r) => { if (r.confirm) uni.navigateBack() },
|
||||
})
|
||||
}
|
||||
|
||||
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() {
|
||||
if (!recorder || !isRecording.value) return
|
||||
isRecording.value = false
|
||||
recorder.stop()
|
||||
recorder.onStop(async (res) => {
|
||||
if (!res.tempFilePath) return
|
||||
const audioPath = res.tempFilePath
|
||||
try {
|
||||
const uploadRes = await uni.uploadFile({
|
||||
url: api(API_ENDPOINTS.TTS.ASR),
|
||||
filePath: audioPath,
|
||||
name: 'audio',
|
||||
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) {
|
||||
const data = typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data
|
||||
if (data.text) {
|
||||
inputText.value = data.text
|
||||
uni.vibrateShort({ type: 'light' })
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[ASR] upload error:', e?.message || e)
|
||||
}
|
||||
uni.showToast({ title: '语音识别失败,请手动输入', icon: 'none' })
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -302,6 +368,18 @@ const confirmExit = () => {
|
||||
}
|
||||
.input-box { flex: 1; background: var(--color-bg); border-radius: var(--radius-md); padding: 12rpx 20rpx; }
|
||||
.input-area { width: 100%; font-size: 26rpx; color: var(--color-text); max-height: 160rpx; line-height: 1.5; }
|
||||
.mic-btn {
|
||||
width: 64rpx; height: 64rpx; border-radius: 50%; background: #F3F4F6;
|
||||
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.mic-btn:active { transform: scale(0.9); }
|
||||
.mic-btn.recording { background: #FEE2E2; animation: mic-pulse 1s infinite; }
|
||||
.mic-icon { font-size: 28rpx; }
|
||||
@keyframes mic-pulse {
|
||||
0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
|
||||
50% { box-shadow: 0 0 0 16rpx rgba(239, 68, 68, 0); }
|
||||
}
|
||||
.send-btn {
|
||||
width: 80rpx; height: 80rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid));
|
||||
border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
|
||||
|
||||
@@ -147,7 +147,7 @@ onMounted(() => {
|
||||
// #endif
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => { if (timer) clearInterval(timer) })
|
||||
onBeforeUnmount(() => { if (timer) { clearTimeout(timer); timer = null } })
|
||||
|
||||
// 辅助
|
||||
const showToast = (title, icon = 'none') => uni.showToast({ title, icon })
|
||||
@@ -286,12 +286,25 @@ const doWxLogin = async () => {
|
||||
// #ifdef MP-WEIXIN
|
||||
wxLoading.value = true
|
||||
try {
|
||||
const { code } = await uni.login()
|
||||
const res = await uni.request({ url: api('/user/wx-login'), method: 'POST', data: { code } })
|
||||
const wxResp = await uni.login()
|
||||
console.log('[wxLogin] uni.login success:', JSON.stringify(wxResp).slice(0, 300))
|
||||
const { code, errMsg } = wxResp
|
||||
if (!code) { console.error('[wxLogin] no code:', errMsg); showToast('获取微信凭证失败'); return }
|
||||
const res = await uni.request({
|
||||
url: api('/user/wx-login'), method: 'POST',
|
||||
header: { 'Content-Type': 'application/json' },
|
||||
data: { code },
|
||||
})
|
||||
console.log('[wxLogin] server response:', res.statusCode, JSON.stringify(res.data).slice(0, 500))
|
||||
if (res.statusCode === 200 && res.data?.token) {
|
||||
loginSuccess(res.data)
|
||||
} else { showToast('微信登录失败') }
|
||||
} catch { showToast('微信登录失败') }
|
||||
} else {
|
||||
showToast(res.data?.message || `登录失败(${res.statusCode})`)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[wxLogin] error:', JSON.stringify(e).slice(0, 500))
|
||||
showToast('微信登录失败')
|
||||
}
|
||||
finally { wxLoading.value = false }
|
||||
// #endif
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -104,16 +104,11 @@ 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 数字人面试无限次', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题推送', '参考回答思路', '公司真题库', '每场最多 10 轮 AI 对话'])
|
||||
const sprintFeatures = ref(['成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告', '学习路径推荐', '真人导师 1v1 点评(每月 1 次)', '简历精修(每月 1 次)', '内推优先', 'AI 实时提示功能'])
|
||||
|
||||
const token = () => uni.getStorageSync('token') || ''
|
||||
|
||||
@@ -136,9 +131,19 @@ 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 */ }
|
||||
})
|
||||
|
||||
@@ -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 ''
|
||||
|
||||
@@ -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' })
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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 || [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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="将面试录音转写为文字后粘贴在这里... 示例: 面试官:请介绍一下你自己 候选人:我毕业于..."
|
||||
: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>
|
||||
@@ -0,0 +1,275 @@
|
||||
<template>
|
||||
<view class="page fade-in">
|
||||
<!-- 统计卡片 -->
|
||||
<view class="stats-card">
|
||||
<view class="stat-row">
|
||||
<view class="stat-item">
|
||||
<text class="stat-value">{{ stats.shareCredits || 0 }}</text>
|
||||
<text class="stat-label">📦 我的积分</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="stat-sub-row">
|
||||
<view class="stat-sub-item">
|
||||
<text class="stat-sub-value">{{ stats.totalVisits || 0 }}</text>
|
||||
<text class="stat-sub-label">总点击</text>
|
||||
</view>
|
||||
<view class="stat-arrow">→</view>
|
||||
<view class="stat-sub-item">
|
||||
<text class="stat-sub-value">{{ stats.creditedCount || 0 }}</text>
|
||||
<text class="stat-sub-label">有效注册</text>
|
||||
</view>
|
||||
<view class="stat-arrow">→</view>
|
||||
<view class="stat-sub-item">
|
||||
<text class="stat-sub-value">{{ stats.shareCredits || 0 }}</text>
|
||||
<text class="stat-sub-label">获得积分</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="hint">
|
||||
💡 好友通过你的链接打开并 <text class="hint-em">登录/注册</text> 才算有效,每次有效得 1 积分
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 今日数据 -->
|
||||
<view class="today-card">
|
||||
<text class="today-title">今日数据</text>
|
||||
<view class="today-row">
|
||||
<view class="today-item">
|
||||
<text class="today-value">{{ todayStats.visits }}</text>
|
||||
<text class="today-label">点击</text>
|
||||
</view>
|
||||
<view class="today-item">
|
||||
<text class="today-value">{{ todayStats.credited }}</text>
|
||||
<text class="today-label">有效</text>
|
||||
</view>
|
||||
<view class="today-item">
|
||||
<text class="today-value">{{ 3 - todayStats.credited > 0 ? 3 - todayStats.credited : 0 }}</text>
|
||||
<text class="today-label">今日剩余</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="today-bar">
|
||||
<view class="today-bar-fill" :style="{ width: Math.min(100, (todayStats.credited / 3) * 100) + '%' }"></view>
|
||||
</view>
|
||||
<text class="today-hint">每日最多 3 次有效积分</text>
|
||||
</view>
|
||||
|
||||
<!-- 分享按钮 -->
|
||||
<view class="share-actions">
|
||||
<button class="share-btn wx-share" @click="shareToWechat" v-if="isWechat">
|
||||
<text class="btn-icon">💬</text>
|
||||
<text>分享给微信好友</text>
|
||||
</button>
|
||||
<button class="share-btn link-share" @click="copyLink">
|
||||
<text class="btn-icon">🔗</text>
|
||||
<text>复制分享链接</text>
|
||||
</button>
|
||||
</view>
|
||||
|
||||
<!-- Tab 切换 -->
|
||||
<view class="tab-bar">
|
||||
<view class="tab-item" :class="{ active: tab === 'records' }" @click="tab = 'records'">分享记录</view>
|
||||
<view class="tab-item" :class="{ active: tab === 'visitors' }" @click="tab = 'visitors'">访问明细</view>
|
||||
</view>
|
||||
|
||||
<!-- 分享记录 -->
|
||||
<view class="list" v-if="tab === 'records'">
|
||||
<view class="list-item" v-for="item in records" :key="item.shareCode">
|
||||
<view class="item-main">
|
||||
<text class="item-type">{{ typeLabel(item.type) }}</text>
|
||||
<text class="item-title">{{ item.title }}</text>
|
||||
</view>
|
||||
<view class="item-stats">
|
||||
<text class="item-stat">👀 {{ item.visitCount }}点击</text>
|
||||
<text class="item-stat active">✅ {{ item.creditedCount }}有效</text>
|
||||
</view>
|
||||
<text class="item-time">{{ formatTime(item.createdAt) }}</text>
|
||||
</view>
|
||||
<view class="empty" v-if="records.length === 0">
|
||||
<text class="empty-icon">📤</text>
|
||||
<text class="empty-text">还没有分享记录</text>
|
||||
<text class="empty-hint">点击上方按钮分享给好友吧</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 访问明细 -->
|
||||
<view class="list" v-if="tab === 'visitors'">
|
||||
<view class="list-item" v-for="(item, idx) in visitors" :key="idx">
|
||||
<image class="visitor-avatar" :src="item.avatar || '/static/avatar-default.svg'" />
|
||||
<view class="item-main">
|
||||
<text class="item-title">{{ item.nickname || '👤 未登录访客' }}</text>
|
||||
<text class="item-time">{{ formatTime(item.createdAt) }}</text>
|
||||
</view>
|
||||
<view class="badge" :class="item.credited ? 'badge-done' : 'badge-pending'">
|
||||
{{ item.credited ? '✅ 已积分' : '⏳ 未注册' }}
|
||||
</view>
|
||||
</view>
|
||||
<view class="empty" v-if="visitors.length === 0">
|
||||
<text class="empty-icon">👀</text>
|
||||
<text class="empty-text">还没有访问记录</text>
|
||||
<text class="empty-hint">分享后好友访问就会出现在这里</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { api } from '../../config'
|
||||
|
||||
const tab = ref('records')
|
||||
const stats = ref({ totalShares: 0, totalVisits: 0, creditedCount: 0, todayCredited: 0, shareCredits: 0 })
|
||||
const records = ref([])
|
||||
const visitors = ref([])
|
||||
|
||||
const todayStats = computed(() => ({
|
||||
visits: stats.value.todayCredited + Math.round(Math.random() * 0),
|
||||
credited: stats.value.todayCredited || 0,
|
||||
}))
|
||||
|
||||
const isWechat = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
// #ifdef H5
|
||||
isWechat.value = navigator?.userAgent?.toLowerCase().includes('micromessenger') || false
|
||||
// #endif
|
||||
loadData()
|
||||
})
|
||||
|
||||
async function loadData() {
|
||||
const token = uni.getStorageSync('token')
|
||||
if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
|
||||
const header = { Authorization: `Bearer ${token}` }
|
||||
|
||||
try {
|
||||
const [statsRes, recordsRes, visitorsRes] = await Promise.all([
|
||||
uni.request({ url: api('/share/stats'), method: 'GET', header }),
|
||||
uni.request({ url: api('/share/records'), method: 'GET', header }),
|
||||
uni.request({ url: api('/share/visitors'), method: 'GET', header }),
|
||||
])
|
||||
if (statsRes.statusCode === 200) stats.value = statsRes.data
|
||||
if (recordsRes.statusCode === 200) records.value = recordsRes.data.list || []
|
||||
if (visitorsRes.statusCode === 200) visitors.value = visitorsRes.data.list || []
|
||||
} catch (e) { console.error(e) }
|
||||
}
|
||||
|
||||
async function shareToWechat() {
|
||||
const token = uni.getStorageSync('token')
|
||||
if (!token) return
|
||||
|
||||
try {
|
||||
const res = await uni.request({
|
||||
url: api('/share/create'),
|
||||
method: 'POST',
|
||||
data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化,快来一起提升吧' },
|
||||
header: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (res.statusCode !== 200) return
|
||||
|
||||
const data = res.data
|
||||
const path = data.wechatShareInfo?.path || `/pages/share/share?code=${data.shareCode}`
|
||||
|
||||
uni.shareAppMessage({
|
||||
provider: 'weixin',
|
||||
title: data.wechatShareInfo?.title || 'AI磁场·职引',
|
||||
description: data.wechatShareInfo?.description || '',
|
||||
path,
|
||||
imageUrl: 'https://zhiyinwx.yzrcloud.cn/static/share-card.png',
|
||||
success: () => { uni.showToast({ title: '分享成功', icon: 'success' }); loadData() },
|
||||
fail: () => { uni.showToast({ title: '分享取消', icon: 'none' }) },
|
||||
})
|
||||
} catch (e) { console.error(e) }
|
||||
}
|
||||
|
||||
async function copyLink() {
|
||||
const token = uni.getStorageSync('token')
|
||||
if (!token) return
|
||||
|
||||
try {
|
||||
const res = await uni.request({
|
||||
url: api('/share/create'),
|
||||
method: 'POST',
|
||||
data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化,快来一起提升吧' },
|
||||
header: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (res.statusCode !== 200) return
|
||||
const shareUrl = `https://zhiyinwx.yzrcloud.cn/share/${res.data.shareCode}`
|
||||
uni.setClipboardData({ data: shareUrl, success: () => { uni.showToast({ title: '链接已复制' }); loadData() } })
|
||||
} catch (e) { console.error(e) }
|
||||
}
|
||||
|
||||
function typeLabel(type) {
|
||||
const map = { app: '应用', interview: '面试', resume: '简历' }
|
||||
return map[type] || type
|
||||
}
|
||||
|
||||
function formatTime(t) {
|
||||
if (!t) return ''
|
||||
const d = new Date(t)
|
||||
return `${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page { min-height: 100vh; background: var(--color-bg); padding-bottom: 48rpx; }
|
||||
|
||||
/* Stats card */
|
||||
.stats-card { background: linear-gradient(135deg, #4F46E5 0%, #7C3AED 100%); margin: 24rpx 32rpx; border-radius: var(--radius-lg); padding: 32rpx; }
|
||||
.stat-row { display: flex; justify-content: center; margin-bottom: 20rpx; }
|
||||
.stat-item { display: flex; flex-direction: column; align-items: center; }
|
||||
.stat-value { font-size: 56rpx; font-weight: 800; color: #FFFFFF; }
|
||||
.stat-label { font-size: 22rpx; color: rgba(255,255,255,0.75); margin-top: 6rpx; }
|
||||
|
||||
.stat-sub-row { display: flex; align-items: center; justify-content: center; gap: 12rpx; padding: 16rpx 0; border-top: 1rpx solid rgba(255,255,255,0.15); border-bottom: 1rpx solid rgba(255,255,255,0.15); margin-bottom: 16rpx; }
|
||||
.stat-sub-item { display: flex; flex-direction: column; align-items: center; }
|
||||
.stat-sub-value { font-size: 32rpx; font-weight: 700; color: #FFFFFF; }
|
||||
.stat-sub-label { font-size: 18rpx; color: rgba(255,255,255,0.6); margin-top: 4rpx; }
|
||||
.stat-arrow { font-size: 24rpx; color: rgba(255,255,255,0.4); }
|
||||
.hint { font-size: 20rpx; color: rgba(255,255,255,0.7); text-align: center; line-height: 1.6; }
|
||||
.hint-em { color: #FCD34D; font-weight: 600; }
|
||||
|
||||
/* Today card */
|
||||
.today-card { background: #FFFFFF; margin: 0 32rpx 24rpx; border-radius: var(--radius-md); padding: 24rpx; box-shadow: var(--shadow-sm); }
|
||||
.today-title { font-size: 24rpx; font-weight: 600; color: var(--color-text); margin-bottom: 16rpx; }
|
||||
.today-row { display: flex; gap: 24rpx; margin-bottom: 16rpx; }
|
||||
.today-item { flex: 1; display: flex; flex-direction: column; align-items: center; }
|
||||
.today-value { font-size: 36rpx; font-weight: 700; color: var(--color-primary); }
|
||||
.today-label { font-size: 20rpx; color: var(--color-text-tertiary); margin-top: 4rpx; }
|
||||
.today-bar { height: 8rpx; background: #F3F4F6; border-radius: 4rpx; overflow: hidden; margin-bottom: 8rpx; }
|
||||
.today-bar-fill { height: 100%; background: linear-gradient(90deg, #4F46E5, #7C3AED); border-radius: 4rpx; transition: width 0.3s; }
|
||||
.today-hint { font-size: 18rpx; color: var(--color-text-tertiary); text-align: center; }
|
||||
|
||||
/* Share buttons */
|
||||
.share-actions { padding: 0 32rpx; display: flex; gap: 20rpx; }
|
||||
.share-btn { flex: 1; display: flex; align-items: center; justify-content: center; height: 88rpx; border-radius: var(--radius-md); font-size: 26rpx; font-weight: 500; border: none; }
|
||||
.share-btn:active { transform: scale(0.96); }
|
||||
.btn-icon { margin-right: 8rpx; font-size: 28rpx; }
|
||||
.wx-share { background: #07C160; color: #FFFFFF; }
|
||||
.link-share { background: #FFFFFF; color: var(--color-text); border: 2rpx solid var(--color-border); }
|
||||
|
||||
/* Tabs */
|
||||
.tab-bar { display: flex; margin: 32rpx 32rpx 0; border-bottom: 2rpx solid var(--color-border); }
|
||||
.tab-item { flex: 1; text-align: center; padding: 20rpx 0; font-size: 28rpx; color: #9CA3AF; font-weight: 500; position: relative; }
|
||||
.tab-item.active { color: var(--color-primary); }
|
||||
.tab-item.active::after { content: ''; position: absolute; bottom: -2rpx; left: 30%; right: 30%; height: 4rpx; background: var(--color-primary); border-radius: 2rpx; }
|
||||
|
||||
/* List */
|
||||
.list { padding: 0 32rpx; }
|
||||
.list-item { background: #FFFFFF; border-radius: var(--radius-md); padding: 24rpx 28rpx; margin-top: 16rpx; display: flex; align-items: center; box-shadow: var(--shadow-sm); }
|
||||
.item-main { flex: 1; display: flex; flex-direction: column; }
|
||||
.item-type { font-size: 20rpx; color: var(--color-primary); background: #EEF2FF; padding: 2rpx 12rpx; border-radius: 6rpx; align-self: flex-start; margin-bottom: 4rpx; }
|
||||
.item-title { font-size: 26rpx; color: var(--color-text); font-weight: 500; }
|
||||
.item-stats { display: flex; flex-direction: column; align-items: flex-end; margin-left: 12rpx; }
|
||||
.item-stat { font-size: 22rpx; color: #9CA3AF; white-space: nowrap; }
|
||||
.item-stat.active { color: var(--color-primary); }
|
||||
.item-time { font-size: 20rpx; color: #D1D5DB; white-space: nowrap; margin-left: 12rpx; }
|
||||
|
||||
.visitor-avatar { width: 56rpx; height: 56rpx; border-radius: 50%; margin-right: 16rpx; flex-shrink: 0; }
|
||||
.badge { font-size: 20rpx; padding: 4rpx 16rpx; border-radius: 8rpx; white-space: nowrap; }
|
||||
.badge-done { background: #ECFDF5; color: #059669; }
|
||||
.badge-pending { background: #FEF3C7; color: #D97706; }
|
||||
|
||||
/* Empty state */
|
||||
.empty { display: flex; flex-direction: column; align-items: center; padding: 80rpx 0; }
|
||||
.empty-icon { font-size: 64rpx; margin-bottom: 16rpx; }
|
||||
.empty-text { font-size: 28rpx; color: #9CA3AF; }
|
||||
.empty-hint { font-size: 24rpx; color: #D1D5DB; margin-top: 8rpx; }
|
||||
</style>
|
||||
@@ -3,7 +3,7 @@
|
||||
<!-- 个人中心 -->
|
||||
<view class="header" v-if="isLoggedIn">
|
||||
<view class="profile-section">
|
||||
<image class="avatar" :src="userInfo.avatar || '/static/avatar-default.svg'" mode="aspectFill" />
|
||||
<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>
|
||||
@@ -33,7 +33,6 @@
|
||||
<view class="guest-avatar"><text class="guest-icon">👤</text></view>
|
||||
<view class="guest-info">
|
||||
<text class="guest-name">未登录 / 点击登录</text>
|
||||
<text class="guest-hint">登录后体验全部功能</text>
|
||||
</view>
|
||||
<text class="header-arrow">›</text>
|
||||
</view>
|
||||
@@ -47,6 +46,11 @@
|
||||
<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>
|
||||
@@ -57,6 +61,11 @@
|
||||
<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">
|
||||
@@ -79,6 +88,7 @@
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { api } from '../../config'
|
||||
|
||||
const userInfo = ref({})
|
||||
@@ -88,13 +98,28 @@ const token = ref('')
|
||||
|
||||
const isLoggedIn = computed(() => !!token.value)
|
||||
|
||||
onMounted(() => {
|
||||
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()
|
||||
})
|
||||
// Fetch fresh user info from API to update stale cache (e.g. credits changed after interview)
|
||||
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 - cached data is fallback */ }
|
||||
}
|
||||
|
||||
onMounted(refreshState)
|
||||
onShow(refreshState)
|
||||
|
||||
const loadStats = async () => {
|
||||
try {
|
||||
@@ -119,8 +144,10 @@ const checkAdmin = () => {
|
||||
|
||||
const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
|
||||
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' })
|
||||
|
||||
@@ -171,6 +198,7 @@ const doLogout = () => {
|
||||
.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; }
|
||||
|
||||
@@ -22,7 +22,6 @@ async function request<T = any>(url: string, method: string = 'POST', data?: any
|
||||
}
|
||||
}
|
||||
|
||||
export 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 }),
|
||||
@@ -83,6 +82,22 @@ export const apiService = {
|
||||
byPosition: (position: string) =>
|
||||
request(API_ENDPOINTS.DAILY_QUESTION.BY_POSITION(position), 'GET', undefined, true),
|
||||
},
|
||||
share: {
|
||||
create: (data: { type: string; refId?: string; title?: string; description?: string }) =>
|
||||
request(API_ENDPOINTS.SHARE.CREATE, 'POST', data, true),
|
||||
stats: () => request(API_ENDPOINTS.SHARE.STATS, 'GET', undefined, true),
|
||||
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),
|
||||
},
|
||||
}
|
||||
|
||||
export default apiService
|
||||
|
||||
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 180" fill="none" shape-rendering="auto"><metadata xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/"><rdf:RDF><rdf:Description><dc:title>Bottts</dc:title><dc:creator>Pablo Stanley</dc:creator><dc:source xsi:type="dcterms:URI">https://bottts.com/</dc:source><dcterms:license xsi:type="dcterms:URI">https://bottts.com/</dcterms:license><dc:rights>Remix of „Bottts” (https://bottts.com/) by „Pablo Stanley”, licensed under „Free for personal and commercial use” (https://bottts.com/)</dc:rights></rdf:Description></rdf:RDF></metadata><mask id="viewboxMask"><rect width="180" height="180" rx="0" ry="0" x="0" y="0" fill="#fff" /></mask><g mask="url(#viewboxMask)"><rect fill="#b6e3f4" width="180" height="180" x="0" y="0" /><g transform="translate(0 66)"><path d="M38 12c-2.95 11.7-19.9 6.67-23.37 18-3.46 11.35 8.03 20 17.53 20" stroke="#2A3544" stroke-width="6" opacity=".9"/><path d="M150 55c8.4 3.49 20.1-7.6 16-16.5-4.1-8.9-16-6.7-16-19.3" stroke="#2A3544" stroke-width="4" opacity=".9"/><mask id="sidesCables01-a" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="21" y="6" width="138" height="58"><g fill="#fff"><rect x="21" y="35" width="16" height="22" rx="2"/><rect x="136" y="42" width="23" height="22" rx="2"/><rect x="136" y="6" width="23" height="18" rx="2"/></g></mask><g mask="url(#sidesCables01-a)"><path d="M0 0h180v76H0V0Z" fill="#546e7a"/><path d="M0 0h180v76H0V0Z" fill="#fff" fill-opacity=".3"/></g></g><g transform="translate(41)"><g filter="url(#topGlowingBulb01-a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M32 24A16 16 0 0 1 48 8h4a16 16 0 0 1 16 16v8a8 8 0 0 1-8 8H40a8 8 0 0 1-8-8v-8Z" fill="#fff" fill-opacity=".3"/></g><path d="M49 11.5c4.93 0 9.37 2.13 12.44 5.52" stroke="#fff" stroke-width="2" stroke-linecap="round"/><path d="m49.83 29-9-9L38 22.83l10 10V40h4v-7.03l10.14-10.14L59.31 20l-9 9h-.48Z" fill="#fff" fill-opacity=".8"/><rect x="22" y="40" width="56" height="12" rx="1" fill="#48494B"/><defs><filter id="topGlowingBulb01-a" x="24" y="0" width="52" height="48" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset/><feGaussianBlur stdDeviation="4"/><feColorMatrix values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.5 0"/><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_617_621"/><feBlend in="SourceGraphic" in2="effect1_dropShadow_617_621" result="shape"/><feColorMatrix in="SourceAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset/><feGaussianBlur stdDeviation="2"/><feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1"/><feColorMatrix values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.5 0"/><feBlend in2="shape" result="effect2_innerShadow_617_621"/></filter></defs></g><g transform="translate(25 44)"><mask id="faceRound01-a" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="0" y="0" width="130" height="120"><path fill-rule="evenodd" clip-rule="evenodd" d="M66 0c58.35 0 64 40.69 64 78 0 33.31-25.47 42-64 42-37.46 0-66-8.69-66-42C0 40.69 7.65 0 66 0Z" fill="#fff"/></mask><g mask="url(#faceRound01-a)"><path d="M-4-2h138v124H-4V-2Z" fill="#546e7a"/><g transform="translate(-1 -1)"></g></g></g><g transform="translate(52 124)"><g fill="#000" fill-opacity=".6"><rect x="12" y="12" width="4" height="8" rx="2"/><rect x="36" y="12" width="4" height="8" rx="2"/><rect x="24" y="12" width="4" height="8" rx="2"/><rect x="48" y="12" width="4" height="8" rx="2"/><rect x="60" y="12" width="4" height="8" rx="2"/></g></g><g transform="translate(38 76)"><rect y="11" width="104" height="34" rx="17" fill="#000" fill-opacity=".8"/><circle cx="29" cy="28" r="13" fill="#F1EEDA"/><circle cx="75" cy="28" r="13" fill="#F1EEDA"/><rect x="24" y="23" width="10" height="10" rx="2" fill="#000" fill-opacity=".8"/><rect x="70" y="23" width="10" height="10" rx="2" fill="#000" fill-opacity=".8"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
@@ -0,0 +1,83 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">
|
||||
<defs>
|
||||
<radialGradient id="skinGrad" cx="50%" cy="40%">
|
||||
<stop offset="0%" stop-color="#FDE8D0"/>
|
||||
<stop offset="100%" stop-color="#F0D0A8"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="hairGrad" cx="50%" cy="80%">
|
||||
<stop offset="0%" stop-color="#4A3728"/>
|
||||
<stop offset="100%" stop-color="#2D1B1E"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="eyeWhite" cx="50%" cy="40%">
|
||||
<stop offset="0%" stop-color="#FFFFFF"/>
|
||||
<stop offset="100%" stop-color="#F0F0F0"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="irisGrad" cx="40%" cy="35%">
|
||||
<stop offset="0%" stop-color="#6B4E37"/>
|
||||
<stop offset="70%" stop-color="#3D2B1F"/>
|
||||
<stop offset="100%" stop-color="#1A1108"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="shirtGrad" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stop-color="#4B5563"/>
|
||||
<stop offset="100%" stop-color="#374151"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Background -->
|
||||
<circle cx="200" cy="200" r="200" fill="#F0F2F5"/>
|
||||
|
||||
<!-- Hair back -->
|
||||
<ellipse cx="200" cy="120" rx="120" ry="100" fill="url(#hairGrad)"/>
|
||||
|
||||
<!-- Neck -->
|
||||
<rect x="165" y="270" width="70" height="50" rx="10" fill="url(#skinGrad)"/>
|
||||
|
||||
<!-- Shirt -->
|
||||
<ellipse cx="200" cy="350" rx="140" ry="80" fill="url(#shirtGrad)"/>
|
||||
<path d="M165 300 L200 340 L235 300" fill="none" stroke="#FFFFFF" stroke-width="2" opacity="0.3"/>
|
||||
|
||||
<!-- Face -->
|
||||
<ellipse cx="200" cy="195" rx="100" ry="120" fill="url(#skinGrad)"/>
|
||||
|
||||
<!-- Hair front -->
|
||||
<path d="M100 160 Q100 80 200 70 Q300 80 300 160 Q280 130 200 125 Q120 130 100 160 Z" fill="url(#hairGrad)"/>
|
||||
<path d="M95 170 Q90 130 120 110 Q110 160 95 170 Z" fill="url(#hairGrad)"/>
|
||||
<path d="M305 170 Q310 130 280 110 Q290 160 305 170 Z" fill="url(#hairGrad)"/>
|
||||
|
||||
<!-- Left eyebrow -->
|
||||
<path d="M135 155 Q150 145 170 148" fill="none" stroke="#3D2B1F" stroke-width="3" stroke-linecap="round"/>
|
||||
|
||||
<!-- Right eyebrow -->
|
||||
<path d="M265 155 Q250 145 230 148" fill="none" stroke="#3D2B1F" stroke-width="3" stroke-linecap="round"/>
|
||||
|
||||
<!-- Left eye -->
|
||||
<ellipse cx="158" cy="175" rx="24" ry="18" fill="url(#eyeWhite)" stroke="#D4C4B0" stroke-width="1"/>
|
||||
<circle cx="158" cy="175" r="12" fill="url(#irisGrad)"/>
|
||||
<circle cx="158" cy="175" r="6" fill="#0A0A0A"/>
|
||||
<circle cx="153" cy="170" r="4" fill="#FFFFFF" opacity="0.8"/>
|
||||
<circle cx="163" cy="178" r="2" fill="#FFFFFF" opacity="0.5"/>
|
||||
|
||||
<!-- Right eye -->
|
||||
<ellipse cx="242" cy="175" rx="24" ry="18" fill="url(#eyeWhite)" stroke="#D4C4B0" stroke-width="1"/>
|
||||
<circle cx="242" cy="175" r="12" fill="url(#irisGrad)"/>
|
||||
<circle cx="242" cy="175" r="6" fill="#0A0A0A"/>
|
||||
<circle cx="237" cy="170" r="4" fill="#FFFFFF" opacity="0.8"/>
|
||||
<circle cx="247" cy="178" r="2" fill="#FFFFFF" opacity="0.5"/>
|
||||
|
||||
<!-- Nose -->
|
||||
<path d="M195 195 Q190 220 185 228 Q195 232 200 232 Q205 232 215 228 Q210 220 205 195" fill="none" stroke="#D4B896" stroke-width="1.5" stroke-linecap="round"/>
|
||||
<ellipse cx="200" cy="230" rx="6" ry="3" fill="#E8C8A8" opacity="0.6"/>
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M178 260 Q189 268 200 268 Q211 268 222 260" fill="none" stroke="#C97B84" stroke-width="2.5" stroke-linecap="round"/>
|
||||
|
||||
<!-- Cheek blush -->
|
||||
<ellipse cx="125" cy="225" rx="22" ry="14" fill="#FFB0A0" opacity="0.25"/>
|
||||
<ellipse cx="275" cy="225" rx="22" ry="14" fill="#FFB0A0" opacity="0.25"/>
|
||||
|
||||
<!-- Ear left -->
|
||||
<ellipse cx="100" cy="185" rx="12" ry="20" fill="url(#skinGrad)"/>
|
||||
|
||||
<!-- Ear right -->
|
||||
<ellipse cx="300" cy="185" rx="12" ry="20" fill="url(#skinGrad)"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.6 KiB |