Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e9036d2979 | |||
| 4180eae944 | |||
| 4e4e1ca271 | |||
| 50bb3c45ed | |||
| db1b3baa60 | |||
| df7d51d888 | |||
| 462884a321 | |||
| 48354e634b | |||
| 8152278b86 | |||
| b38b38d0c8 | |||
| 07b81f57a6 | |||
| 1422c04b2c | |||
| 656dfabb29 | |||
| fe688096a4 | |||
| 31703af4f2 | |||
| 4023c789b1 | |||
| a9c6b03c67 | |||
| d8e8bcc9a0 | |||
| 2230a95b45 | |||
| d8a7872cd2 | |||
| 59fc35dad9 | |||
| bd398f154a | |||
| f955ecc71d | |||
| b8aaa51eb1 | |||
| 9b1c92464e | |||
| 2fddd39301 | |||
| 52e5350ba0 | |||
| 81f86d995d | |||
| 1a45822a58 | |||
| d74fc74f28 | |||
| b6323f02eb | |||
| 04b30d0024 | |||
| 13b2a764ef | |||
| 70c4f28eb5 | |||
| d37bbd7a61 | |||
| 4d54c8088c |
@@ -96,14 +96,15 @@ zhiyin/
|
|||||||
- 主用不可用时自动切换(在 `ai` 模块处理)
|
- 主用不可用时自动切换(在 `ai` 模块处理)
|
||||||
- 环境变量: `AI_PRIMARY_KEY`, `AI_BACKUP_KEY`
|
- 环境变量: `AI_PRIMARY_KEY`, `AI_BACKUP_KEY`
|
||||||
|
|
||||||
### 支付(微信支付 v3)
|
### 支付(微信支付 v3 + 虚拟支付)
|
||||||
- Native 支付(H5 扫码): `POST /payment/create-product`(按量购买引力值)
|
- Native 支付(H5 扫码): `POST /payment/create-product`(按量购买引力值)
|
||||||
- JSAPI 支付(小程序内): `POST /payment/jsapi-product`(按量购买引力值)
|
- JSAPI 支付(小程序内): `POST /payment/jsapi-product`(按量购买引力值)
|
||||||
|
- 虚拟支付(小程序内直接购买): `POST /virtual-payment/create`(mode=`short_series_coin`,代币名「引力值」,1 币 = 1 元)
|
||||||
- 支付回调: `POST /payment/notify`(@Public,验签 + 解密 + 自动到账)
|
- 支付回调: `POST /payment/notify`(@Public,验签 + 解密 + 自动到账)
|
||||||
- 支付结果轮询: `GET /payment/check/:outTradeNo`
|
- 支付结果轮询: `GET /payment/check/:outTradeNo`
|
||||||
- 产品定价: `GET /member/plans`(含 products 字段,定义引力值单价和赠送量)
|
- 产品定价: `GET /member/plans`(含 products 字段,定义引力值单价和赠送量)
|
||||||
- 需要微信商户证书文件(通过 postbuild 复制到 dist)
|
- 需要微信商户证书文件(通过 postbuild 复制到 dist)
|
||||||
- **注意**: 当前会员体系已从按月订阅制改为按量购买引力值制(小程序内复制链接到浏览器打开购买,H5 直接扫码支付)
|
- **注意**: 当前会员体系已从按月订阅制改为按量购买引力值制(小程序内虚拟支付直接购买,H5 扫码支付)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -202,7 +203,7 @@ cd zhiyin-app && npm run build:mp-weixin && node scripts/upload-mp.js
|
|||||||
|
|
||||||
## 六、项目状态与开发阶段
|
## 六、项目状态与开发阶段
|
||||||
|
|
||||||
**当前**: Phase 1.5(商业化 + 全量部署)— v1.0.17
|
**当前**: Phase 1.5(商业化 + 全量部署)— v1.0.18(开发中)
|
||||||
|
|
||||||
| 阶段 | 状态 | 关键交付 |
|
| 阶段 | 状态 | 关键交付 |
|
||||||
|------|------|---------|
|
|------|------|---------|
|
||||||
@@ -259,7 +260,7 @@ VITE_APP_NAME=AI磁场
|
|||||||
| 账号 | 密码 | 角色 | 说明 |
|
| 账号 | 密码 | 角色 | 说明 |
|
||||||
|------|------|------|------|
|
|------|------|------|------|
|
||||||
| `13701190814@139.com` | `Zhiyin2024!` | admin | 管理员,可访问管理后台 |
|
| `13701190814@139.com` | `Zhiyin2024!` | admin | 管理员,可访问管理后台 |
|
||||||
| `test@yzrcloud.cn` | `123456` | user | 测试账号 |
|
| `test@yzrcloud.cn` | `123456` | user | 测试账号(普通用户,含 5 引力值) |
|
||||||
| `test@test.com` | 验证码 `123456` | admin | 旧管理员(dev 模式可用) |
|
| `test@test.com` | 验证码 `123456` | admin | 旧管理员(dev 模式可用) |
|
||||||
|
|
||||||
管理后台路径:`/pages/admin/admin`,进入后自动验证管理员身份(`onMounted` → `doVerify`)。
|
管理后台路径:`/pages/admin/admin`,进入后自动验证管理员身份(`onMounted` → `doVerify`)。
|
||||||
@@ -270,7 +271,7 @@ VITE_APP_NAME=AI磁场
|
|||||||
|
|
||||||
- 远程仓库: `http://127.0.0.1:2999/txai-dev/zhiyin.git`(本机 Gitea,带 token 认证)
|
- 远程仓库: `http://127.0.0.1:2999/txai-dev/zhiyin.git`(本机 Gitea,带 token 认证)
|
||||||
- 默认分支: `master`
|
- 默认分支: `master`
|
||||||
- 最新 tag: `v1.0.16`(小程序上传版本 v1.0.17 源自 git tag + 末位自增 1)
|
- 最新 tag: `v1.0.17`(小程序上传版本 v1.0.18 源自 git tag v1.0.17 + 末位自增 1)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -284,7 +285,7 @@ VITE_APP_NAME=AI磁场
|
|||||||
6. **API 限流**: 100 次/60 秒(在 `app.module.ts` 中配置),注意避免在定时任务和批量操作中被限
|
6. **API 限流**: 100 次/60 秒(在 `app.module.ts` 中配置),注意避免在定时任务和批量操作中被限
|
||||||
7. **验证码**: 生产模式(`NODE_ENV=production`)使用真实 SMTP 发邮件验证码;非生产模式手机验证码固定为 `123456`、邮件验证码在响应中返回 `devCode`
|
7. **验证码**: 生产模式(`NODE_ENV=production`)使用真实 SMTP 发邮件验证码;非生产模式手机验证码固定为 `123456`、邮件验证码在响应中返回 `devCode`
|
||||||
8. **MongoDB**: 8 个核心集合 + 2 个分享集合
|
8. **MongoDB**: 8 个核心集合 + 2 个分享集合
|
||||||
9. **引力值体系**: 所有计划统一走引力值消耗(面试 5、优化 3、下载 2)。VIP 不再免额度,成长版每月 250 引力值,冲刺版每月 600 引力值,每日凌晨 2 点定时补给。免费用户注册送 5 引力值。小程序内通过分享得引力值/贡献面经/复制官网链接到浏览器打开购买三种方式获取引力值;H5 直接扫码支付按量购买(¥5/份)。
|
9. **引力值体系**: 所有计划统一走引力值消耗(面试 5、优化 3、下载 2)。VIP 不再免额度,成长版每月赠送 80 引力值,冲刺版每月赠送 200 引力值,每日凌晨 2 点定时补给。免费用户注册送 5 引力值。小程序内通过分享得引力值/贡献面经/虚拟支付购买三种方式获取引力值;H5 直接扫码支付按量购买(¥5/份)。
|
||||||
10. **api.ts 陷阱**: 对象字面量必须在 `export const apiService = {` 或 `const apiService = { ... export default apiService` 中包裹,否则 uni-app 构建报错 `Expected ";" but found ":"`。git pull 后经常丢失这行声明,需手动补回
|
10. **api.ts 陷阱**: 对象字面量必须在 `export const apiService = {` 或 `const apiService = { ... export default apiService` 中包裹,否则 uni-app 构建报错 `Expected ";" but found ":"`。git pull 后经常丢失这行声明,需手动补回
|
||||||
11. **H5 构建 assets 清理**: `assets/` 中的旧 hash 文件不能随意删除——`index-*.js`(主 bundle)动态 import 了所有 page chunk,删除仍在引用的文件会导致浏览器 `NS_ERROR_CORRUPTED_CONTENT`
|
11. **H5 构建 assets 清理**: `assets/` 中的旧 hash 文件不能随意删除——`index-*.js`(主 bundle)动态 import 了所有 page chunk,删除仍在引用的文件会导致浏览器 `NS_ERROR_CORRUPTED_CONTENT`
|
||||||
12. **管理后台自动验证**: `admin.vue` 中 `onMounted` 自动调用 `doVerify()`,进入后台即检测 JWT 中 `role` 是否为 `admin`,不再需要手动点击"验证管理员身份"按钮
|
12. **管理后台自动验证**: `admin.vue` 中 `onMounted` 自动调用 `doVerify()`,进入后台即检测 JWT 中 `role` 是否为 `admin`,不再需要手动点击"验证管理员身份"按钮
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { connect, disconnect } from 'mongoose'
|
||||||
|
import * as bcrypt from 'bcrypt'
|
||||||
|
import * as dotenv from 'dotenv'
|
||||||
|
import * as path from 'path'
|
||||||
|
|
||||||
|
dotenv.config({ path: path.resolve(__dirname, '../.env') })
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const uri = process.env.MONGODB_URI
|
||||||
|
if (!uri) {
|
||||||
|
console.error('MONGODB_URI not set')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const conn = await connect(uri)
|
||||||
|
console.log('Connected to MongoDB')
|
||||||
|
|
||||||
|
const users = conn.connection.db!.collection('users')
|
||||||
|
|
||||||
|
const email = 'test@yzrcloud.cn'
|
||||||
|
const password = '123456'
|
||||||
|
const hashed = await bcrypt.hash(password, 10)
|
||||||
|
|
||||||
|
const existing = await users.findOne({ email })
|
||||||
|
if (existing) {
|
||||||
|
await users.updateOne(
|
||||||
|
{ email },
|
||||||
|
{ $set: { password: hashed, nickname: '测试用户', role: 'user', gravity: 5, interviewCredits: 1, remaining: 3 } }
|
||||||
|
)
|
||||||
|
console.log(`Updated test user: ${email}`)
|
||||||
|
} else {
|
||||||
|
await users.insertOne({
|
||||||
|
email,
|
||||||
|
password: hashed,
|
||||||
|
nickname: '测试用户',
|
||||||
|
role: 'user',
|
||||||
|
gravity: 5,
|
||||||
|
interviewCredits: 1,
|
||||||
|
remaining: 3,
|
||||||
|
interviewCount: 0,
|
||||||
|
plan: 'free',
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
})
|
||||||
|
console.log(`Created test user: ${email}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
await disconnect()
|
||||||
|
console.log('Done')
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(err => {
|
||||||
|
console.error('Failed:', err)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
@@ -9,6 +9,7 @@ import { APP_GUARD } from '@nestjs/core'
|
|||||||
import { JwtStrategy } from './common/strategies/jwt.strategy'
|
import { JwtStrategy } from './common/strategies/jwt.strategy'
|
||||||
import { JwtAuthGuard } from './common/guards/jwt-auth.guard'
|
import { JwtAuthGuard } from './common/guards/jwt-auth.guard'
|
||||||
import { AiModule } from './modules/ai/ai.module'
|
import { AiModule } from './modules/ai/ai.module'
|
||||||
|
import { FeedbackModule } from './modules/feedback/feedback.module'
|
||||||
import { UserModule } from './modules/user/user.module'
|
import { UserModule } from './modules/user/user.module'
|
||||||
import { InterviewModule } from './modules/interview/interview.module'
|
import { InterviewModule } from './modules/interview/interview.module'
|
||||||
import { ResumeModule } from './modules/resume/resume.module'
|
import { ResumeModule } from './modules/resume/resume.module'
|
||||||
@@ -25,9 +26,11 @@ import { DailyQuestionModule } from './modules/daily-question/daily-question.mod
|
|||||||
import { ScheduleModule } from './modules/schedule/schedule.module'
|
import { ScheduleModule } from './modules/schedule/schedule.module'
|
||||||
import { TtsModule } from './modules/tts/tts.module'
|
import { TtsModule } from './modules/tts/tts.module'
|
||||||
import { PricingModule } from './modules/schemas/pricing.module'
|
import { PricingModule } from './modules/schemas/pricing.module'
|
||||||
|
import { GravityTransactionModule } from './modules/schemas/gravity-transaction.module'
|
||||||
import { ShareModule } from './modules/share/share.module'
|
import { ShareModule } from './modules/share/share.module'
|
||||||
import { InterviewReviewModule } from './modules/interview-review/interview-review.module'
|
import { InterviewReviewModule } from './modules/interview-review/interview-review.module'
|
||||||
import { CareerAdviceModule } from './modules/career-advice/career-advice.module'
|
import { CareerAdviceModule } from './modules/career-advice/career-advice.module'
|
||||||
|
import { VirtualPaymentModule } from './modules/virtual-payment/virtual-payment.module'
|
||||||
|
|
||||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin'
|
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin'
|
||||||
|
|
||||||
@@ -45,6 +48,7 @@ const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin
|
|||||||
}]),
|
}]),
|
||||||
NestScheduleModule.forRoot(),
|
NestScheduleModule.forRoot(),
|
||||||
UserModule,
|
UserModule,
|
||||||
|
FeedbackModule,
|
||||||
AiModule,
|
AiModule,
|
||||||
InterviewModule,
|
InterviewModule,
|
||||||
AnalyzeModule,
|
AnalyzeModule,
|
||||||
@@ -64,6 +68,8 @@ const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhiyin
|
|||||||
ShareModule,
|
ShareModule,
|
||||||
InterviewReviewModule,
|
InterviewReviewModule,
|
||||||
CareerAdviceModule,
|
CareerAdviceModule,
|
||||||
|
VirtualPaymentModule,
|
||||||
|
GravityTransactionModule,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
JwtStrategy,
|
JwtStrategy,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
|||||||
|
|
||||||
const message = exception instanceof HttpException
|
const message = exception instanceof HttpException
|
||||||
? exception.getResponse()
|
? exception.getResponse()
|
||||||
: '服务器内部错误';
|
: (exception as Error)?.message || '服务器内部错误';
|
||||||
|
|
||||||
const errorResponse = {
|
const errorResponse = {
|
||||||
code: status,
|
code: status,
|
||||||
|
|||||||
@@ -85,7 +85,13 @@ export class AdminController {
|
|||||||
filter.$or = [
|
filter.$or = [
|
||||||
{ phone: { $regex: escaped, $options: 'i' } },
|
{ phone: { $regex: escaped, $options: 'i' } },
|
||||||
{ nickname: { $regex: escaped, $options: 'i' } },
|
{ nickname: { $regex: escaped, $options: 'i' } },
|
||||||
|
{ email: { $regex: escaped, $options: 'i' } },
|
||||||
|
{ wxOpenid: { $regex: escaped, $options: 'i' } },
|
||||||
]
|
]
|
||||||
|
// 支持按 _id 模糊搜索(ObjectId → string → regex)
|
||||||
|
filter.$or.push({
|
||||||
|
$expr: { $regexMatch: { input: { $toString: '$_id' }, regex: escaped, options: 'i' } },
|
||||||
|
})
|
||||||
}
|
}
|
||||||
const skip = (Math.max(1, +page) - 1) * +limit
|
const skip = (Math.max(1, +page) - 1) * +limit
|
||||||
const [users, total] = await Promise.all([
|
const [users, total] = await Promise.all([
|
||||||
@@ -245,7 +251,7 @@ export class AdminController {
|
|||||||
|
|
||||||
@Get('admins')
|
@Get('admins')
|
||||||
async getAdmins() {
|
async getAdmins() {
|
||||||
const admins = await this.userModel.find({ role: 'admin' }).select('phone nickname email createdAt isSystemAdmin').lean().exec()
|
const admins = await this.userModel.find({ role: 'admin' }).select('phone nickname email wxOpenid gravity plan role createdAt isSystemAdmin').lean().exec()
|
||||||
return { admins }
|
return { admins }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -422,8 +428,8 @@ const DEFAULT_CONFIG = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_PRICING = {
|
const DEFAULT_PRICING = {
|
||||||
interview: { pricePerSession: 500, creditsPerPurchase: 1 },
|
interview: { pricePerSession: 600, creditsPerPurchase: 1 },
|
||||||
resumeOptimize: { freeLimit: 3, pricePerOptimize: 300, creditsPerPurchase: 1 },
|
resumeOptimize: { freeLimit: 3, pricePerOptimize: 400, creditsPerPurchase: 1 },
|
||||||
resumeDownload: { pricePerDownload: 200, creditsPerPurchase: 1 },
|
resumeDownload: { pricePerDownload: 200, creditsPerPurchase: 1 },
|
||||||
plans: {
|
plans: {
|
||||||
growth: {
|
growth: {
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { Controller, Post, Get, Patch, Param, Body, Query, UseGuards, HttpException, HttpStatus } from '@nestjs/common'
|
||||||
|
import { FeedbackService } from './feedback.service'
|
||||||
|
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
|
||||||
|
import { AdminGuard } from '../../common/guards/admin.guard'
|
||||||
|
import { CurrentUser } from '../../common/decorators/current-user.decorator'
|
||||||
|
|
||||||
|
@Controller('feedback')
|
||||||
|
export class FeedbackController {
|
||||||
|
constructor(private service: FeedbackService) {}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Post()
|
||||||
|
async create(@CurrentUser('userId') userId: string, @Body() body: { type?: string; content: string; contact?: string }) {
|
||||||
|
if (!body.content || body.content.length < 2) {
|
||||||
|
throw new HttpException('请填写反馈内容', HttpStatus.BAD_REQUEST)
|
||||||
|
}
|
||||||
|
return this.service.create({ userId, type: body.type || 'suggestion', content: body.content, contact: body.contact })
|
||||||
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard, AdminGuard)
|
||||||
|
@Get()
|
||||||
|
async list(@Query('page') page?: string, @Query('limit') limit?: string) {
|
||||||
|
return this.service.findAll(Number(page) || 1, Number(limit) || 20)
|
||||||
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard, AdminGuard)
|
||||||
|
@Patch(':id/resolve')
|
||||||
|
async resolve(@Param('id') id: string) {
|
||||||
|
return this.service.markResolved(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Module } from '@nestjs/common'
|
||||||
|
import { MongooseModule } from '@nestjs/mongoose'
|
||||||
|
import { FeedbackController } from './feedback.controller'
|
||||||
|
import { FeedbackService } from './feedback.service'
|
||||||
|
import { Feedback, FeedbackSchema } from './feedback.schema'
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [MongooseModule.forFeature([{ name: Feedback.name, schema: FeedbackSchema }])],
|
||||||
|
controllers: [FeedbackController],
|
||||||
|
providers: [FeedbackService],
|
||||||
|
exports: [FeedbackService],
|
||||||
|
})
|
||||||
|
export class FeedbackModule {}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
|
||||||
|
import { Document, Types } from 'mongoose'
|
||||||
|
|
||||||
|
export type FeedbackDocument = Feedback & Document
|
||||||
|
|
||||||
|
@Schema({ timestamps: true })
|
||||||
|
export class Feedback {
|
||||||
|
@Prop({ type: Types.ObjectId, ref: 'User', required: true })
|
||||||
|
userId: Types.ObjectId
|
||||||
|
|
||||||
|
@Prop({ default: 'suggestion' })
|
||||||
|
type: string
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
content: string
|
||||||
|
|
||||||
|
@Prop({ default: '' })
|
||||||
|
contact: string
|
||||||
|
|
||||||
|
@Prop({ default: 'pending' })
|
||||||
|
status: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FeedbackSchema = SchemaFactory.createForClass(Feedback)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { Injectable } from '@nestjs/common'
|
||||||
|
import { InjectModel } from '@nestjs/mongoose'
|
||||||
|
import { Model } from 'mongoose'
|
||||||
|
import { Feedback } from './feedback.schema'
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class FeedbackService {
|
||||||
|
constructor(@InjectModel(Feedback.name) private model: Model<Feedback>) {}
|
||||||
|
|
||||||
|
async create(data: { userId: string; type: string; content: string; contact?: string }) {
|
||||||
|
return this.model.create(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(page = 1, limit = 20) {
|
||||||
|
const skip = (page - 1) * limit
|
||||||
|
const items = await this.model.find().sort({ createdAt: -1 }).skip(skip).limit(limit).lean()
|
||||||
|
let populated: any[] = items
|
||||||
|
try {
|
||||||
|
populated = await this.model.populate(items, { path: 'userId', select: 'nickname phone email' })
|
||||||
|
} catch {}
|
||||||
|
const total = await this.model.countDocuments()
|
||||||
|
return { items: populated, total, page, limit }
|
||||||
|
}
|
||||||
|
|
||||||
|
async markResolved(id: string) {
|
||||||
|
return this.model.findByIdAndUpdate(id, { status: 'resolved' }, { new: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 { InjectModel } from '@nestjs/mongoose'
|
||||||
import { Model } from 'mongoose'
|
import { Model } from 'mongoose'
|
||||||
import { Interview, InterviewDocument } from './interview.schema'
|
import { Interview, InterviewDocument } from './interview.schema'
|
||||||
@@ -11,6 +11,8 @@ import { analyzeSpeech } from '../../common/utils/filler-words'
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class InterviewService {
|
export class InterviewService {
|
||||||
|
private readonly logger = new Logger(InterviewService.name)
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@InjectModel(Interview.name) private interviewModel: Model<InterviewDocument>,
|
@InjectModel(Interview.name) private interviewModel: Model<InterviewDocument>,
|
||||||
@InjectModel(Progress.name) private progressModel: Model<ProgressDocument>,
|
@InjectModel(Progress.name) private progressModel: Model<ProgressDocument>,
|
||||||
@@ -21,13 +23,24 @@ export class InterviewService {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
async create(userId: string, position: string) {
|
async create(userId: string, position: string) {
|
||||||
await this.quotaService.checkAndDeductInterview(userId)
|
// Step 1: 先检查引力值是否足够(不扣除)
|
||||||
|
const cost = await this.quotaService.checkInterview(userId)
|
||||||
|
|
||||||
const firstQuestion = await this.aiService.call({
|
// Step 2: AI 生成第一个问题
|
||||||
systemPrompt: `你是一位专业的${position}面试官。请针对校招该岗位提出第一个面试问题,要求具体且有针对性。直接输出问题,不要多余内容。`,
|
let firstQuestion: string
|
||||||
userMessage: `请为${position}岗位的校招候选人提出第一个面试问题。`,
|
try {
|
||||||
temperature: 0.8,
|
firstQuestion = await this.aiService.call({
|
||||||
})
|
systemPrompt: `你是一位专业的${position}面试官。请针对校招该岗位提出第一个面试问题,要求具体且有针对性。直接输出问题,不要多余内容。`,
|
||||||
|
userMessage: `请为${position}岗位的校招候选人提出第一个面试问题。`,
|
||||||
|
temperature: 0.8,
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.error(`AI call failed for interview create: ${(e as Error).message}`)
|
||||||
|
throw new HttpException('AI 服务暂时不可用,请稍后重试', HttpStatus.SERVICE_UNAVAILABLE)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 3: AI 调用成功后,扣除引力值并创建面试记录
|
||||||
|
await this.quotaService.deductInterview(userId, cost)
|
||||||
|
|
||||||
const interview = await this.interviewModel.create({
|
const interview = await this.interviewModel.create({
|
||||||
userId,
|
userId,
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ export class MemberController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
registrationGravity: pricing.registrationGravity,
|
||||||
interview: { dailyFreeLimit: FREE_DAILY_LIMIT, maxRoundsFree: 5, maxRoundsVip: 10 },
|
interview: { dailyFreeLimit: FREE_DAILY_LIMIT, maxRoundsFree: 5, maxRoundsVip: 10 },
|
||||||
gravityRates: pricing.gravityRates,
|
gravityRates: pricing.gravityRates,
|
||||||
products: {
|
products: {
|
||||||
|
|||||||
@@ -36,12 +36,12 @@ describe('PaymentController', () => {
|
|||||||
}
|
}
|
||||||
mockPricingService = {
|
mockPricingService = {
|
||||||
getConfig: jest.fn().mockResolvedValue({
|
getConfig: jest.fn().mockResolvedValue({
|
||||||
interview: { pricePerSession: 500, creditsPerPurchase: 1 },
|
interview: { pricePerSession: 600, creditsPerPurchase: 1 },
|
||||||
resumeOptimize: { freeLimit: 3, pricePerOptimize: 300, creditsPerPurchase: 1 },
|
resumeOptimize: { freeLimit: 3, pricePerOptimize: 400, creditsPerPurchase: 1 },
|
||||||
resumeDownload: { pricePerDownload: 200, creditsPerPurchase: 1 },
|
resumeDownload: { pricePerDownload: 200, creditsPerPurchase: 1 },
|
||||||
plans: {
|
plans: {
|
||||||
growth: { price: 1990, durationDays: 30, gravityPerMonth: 250, credits: { interview: 999, resumeOptimize: 20, resumeDownload: 10 }, features: [] },
|
growth: { price: 1990, durationDays: 30, gravityPerMonth: 80, credits: { interview: 999, resumeOptimize: 20, resumeDownload: 10 }, features: [] },
|
||||||
sprint: { price: 4990, durationDays: 30, gravityPerMonth: 600, credits: { interview: 999, resumeOptimize: 50, resumeDownload: 30 }, features: [] },
|
sprint: { price: 4990, durationDays: 30, gravityPerMonth: 200, credits: { interview: 999, resumeOptimize: 50, resumeDownload: 30 }, features: [] },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
@@ -51,6 +51,7 @@ describe('PaymentController', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
{ provide: getModelToken('User'), useValue: mockUserModel },
|
{ provide: getModelToken('User'), useValue: mockUserModel },
|
||||||
{ provide: getModelToken('PaymentOrder'), useValue: mockOrderModel },
|
{ provide: getModelToken('PaymentOrder'), useValue: mockOrderModel },
|
||||||
|
{ provide: getModelToken('GravityTransaction'), useValue: { create: jest.fn() } },
|
||||||
{ provide: WechatPayService, useValue: mockWechatPay },
|
{ provide: WechatPayService, useValue: mockWechatPay },
|
||||||
{ provide: QuotaService, useValue: mockQuotaService },
|
{ provide: QuotaService, useValue: mockQuotaService },
|
||||||
{ provide: PricingService, useValue: mockPricingService },
|
{ provide: PricingService, useValue: mockPricingService },
|
||||||
@@ -158,7 +159,7 @@ describe('PaymentController', () => {
|
|||||||
expect(result.plan).toBe('growth')
|
expect(result.plan).toBe('growth')
|
||||||
expect(mockUser.save).toHaveBeenCalled()
|
expect(mockUser.save).toHaveBeenCalled()
|
||||||
expect(mockUser.plan).toBe('growth')
|
expect(mockUser.plan).toBe('growth')
|
||||||
expect(mockUser.gravity).toBe(250)
|
expect(mockUser.gravity).toBe(80)
|
||||||
expect(mockUser.freeOptimizeUsed).toBe(3)
|
expect(mockUser.freeOptimizeUsed).toBe(3)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { WechatPayService } from './wechat-pay.service'
|
|||||||
import { QuotaService } from '../user/quota.service'
|
import { QuotaService } from '../user/quota.service'
|
||||||
import { PricingService } from '../schemas/pricing.service'
|
import { PricingService } from '../schemas/pricing.service'
|
||||||
import { Public } from '../../common/decorators/public.decorator'
|
import { Public } from '../../common/decorators/public.decorator'
|
||||||
|
import { GravityTransaction } from '../schemas/gravity-transaction.schema'
|
||||||
|
|
||||||
@Controller('payment')
|
@Controller('payment')
|
||||||
export class PaymentController {
|
export class PaymentController {
|
||||||
@@ -17,6 +18,7 @@ export class PaymentController {
|
|||||||
constructor(
|
constructor(
|
||||||
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
||||||
@InjectModel(PaymentOrder.name) private orderModel: Model<PaymentOrderDocument>,
|
@InjectModel(PaymentOrder.name) private orderModel: Model<PaymentOrderDocument>,
|
||||||
|
@InjectModel(GravityTransaction.name) private gravityTxModel: Model<GravityTransaction>,
|
||||||
private wechatPay: WechatPayService,
|
private wechatPay: WechatPayService,
|
||||||
private quotaService: QuotaService,
|
private quotaService: QuotaService,
|
||||||
private pricingService: PricingService,
|
private pricingService: PricingService,
|
||||||
@@ -226,6 +228,14 @@ export class PaymentController {
|
|||||||
user.gravity = planCfg.gravityPerMonth
|
user.gravity = planCfg.gravityPerMonth
|
||||||
user.freeOptimizeUsed = 3
|
user.freeOptimizeUsed = 3
|
||||||
await user.save()
|
await user.save()
|
||||||
|
await this.gravityTxModel.create({
|
||||||
|
userId: order.userId,
|
||||||
|
amount: planCfg.gravityPerMonth,
|
||||||
|
balance: planCfg.gravityPerMonth,
|
||||||
|
type: 'plan_set',
|
||||||
|
description: `开通${isSprint ? '冲刺版' : '成长版'}会员,获得 ${planCfg.gravityPerMonth} 引力值`,
|
||||||
|
refId: order.outTradeNo,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private async activateProduct(order: PaymentOrderDocument) {
|
private async activateProduct(order: PaymentOrderDocument) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { InjectModel } from '@nestjs/mongoose'
|
|||||||
import { Model } from 'mongoose'
|
import { Model } from 'mongoose'
|
||||||
import { User, UserDocument } from '../user/user.schema'
|
import { User, UserDocument } from '../user/user.schema'
|
||||||
import { PricingService } from '../schemas/pricing.service'
|
import { PricingService } from '../schemas/pricing.service'
|
||||||
|
import { GravityTransaction } from '../schemas/gravity-transaction.schema'
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class GravityTopUpService {
|
export class GravityTopUpService {
|
||||||
@@ -11,9 +12,24 @@ export class GravityTopUpService {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
||||||
|
@InjectModel(GravityTransaction.name) private gravityTxModel: Model<GravityTransaction>,
|
||||||
private pricingService: PricingService,
|
private pricingService: PricingService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
private async logBulkTopUp(userIds: string[], amount: number, type: string) {
|
||||||
|
const users = await this.userModel.find({ _id: { $in: userIds } }).select('gravity').exec()
|
||||||
|
const docs = users.map(u => ({
|
||||||
|
userId: u._id.toString(),
|
||||||
|
amount,
|
||||||
|
balance: u.gravity,
|
||||||
|
type,
|
||||||
|
description: `月度补给 ${amount} 引力值`,
|
||||||
|
}))
|
||||||
|
if (docs.length > 0) {
|
||||||
|
await this.gravityTxModel.insertMany(docs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Cron(CronExpression.EVERY_DAY_AT_2AM)
|
@Cron(CronExpression.EVERY_DAY_AT_2AM)
|
||||||
async topUpVipGravity() {
|
async topUpVipGravity() {
|
||||||
this.logger.log('Topping up gravity for active VIP members...')
|
this.logger.log('Topping up gravity for active VIP members...')
|
||||||
@@ -22,28 +38,32 @@ export class GravityTopUpService {
|
|||||||
|
|
||||||
// 成长版 —— vipExpireAt 未过期
|
// 成长版 —— vipExpireAt 未过期
|
||||||
const growthPlan = pricing.plans.growth
|
const growthPlan = pricing.plans.growth
|
||||||
const growthResult = await this.userModel.updateMany(
|
const growthUsers = await this.userModel.find(
|
||||||
{
|
{ plan: 'growth', vipExpireAt: { $gt: now } },
|
||||||
plan: 'growth',
|
).select('_id').exec()
|
||||||
vipExpireAt: { $gt: now },
|
const growthIds = growthUsers.map(u => u._id.toString())
|
||||||
},
|
if (growthIds.length > 0) {
|
||||||
{ $inc: { gravity: growthPlan.gravityPerMonth } },
|
await this.userModel.updateMany(
|
||||||
).exec()
|
{ _id: { $in: growthIds } },
|
||||||
if (growthResult.modifiedCount > 0) {
|
{ $inc: { gravity: growthPlan.gravityPerMonth } },
|
||||||
this.logger.log(`Growth plan: topped up ${growthResult.modifiedCount} users with ${growthPlan.gravityPerMonth} gravity each`)
|
).exec()
|
||||||
|
await this.logBulkTopUp(growthIds, growthPlan.gravityPerMonth, 'monthly_topup')
|
||||||
|
this.logger.log(`Growth plan: topped up ${growthIds.length} users with ${growthPlan.gravityPerMonth} gravity each`)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 冲刺版 —— sprintExpireAt 未过期
|
// 冲刺版 —— sprintExpireAt 未过期
|
||||||
const sprintPlan = pricing.plans.sprint
|
const sprintPlan = pricing.plans.sprint
|
||||||
const sprintResult = await this.userModel.updateMany(
|
const sprintUsers = await this.userModel.find(
|
||||||
{
|
{ plan: 'sprint', sprintExpireAt: { $gt: now } },
|
||||||
plan: 'sprint',
|
).select('_id').exec()
|
||||||
sprintExpireAt: { $gt: now },
|
const sprintIds = sprintUsers.map(u => u._id.toString())
|
||||||
},
|
if (sprintIds.length > 0) {
|
||||||
{ $inc: { gravity: sprintPlan.gravityPerMonth } },
|
await this.userModel.updateMany(
|
||||||
).exec()
|
{ _id: { $in: sprintIds } },
|
||||||
if (sprintResult.modifiedCount > 0) {
|
{ $inc: { gravity: sprintPlan.gravityPerMonth } },
|
||||||
this.logger.log(`Sprint plan: topped up ${sprintResult.modifiedCount} users with ${sprintPlan.gravityPerMonth} gravity each`)
|
).exec()
|
||||||
|
await this.logBulkTopUp(sprintIds, sprintPlan.gravityPerMonth, 'monthly_topup')
|
||||||
|
this.logger.log(`Sprint plan: topped up ${sprintIds.length} users with ${sprintPlan.gravityPerMonth} gravity each`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module, Global } from '@nestjs/common'
|
||||||
|
import { MongooseModule } from '@nestjs/mongoose'
|
||||||
|
import { GravityTransaction, GravityTransactionSchema } from './gravity-transaction.schema'
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
imports: [MongooseModule.forFeature([{ name: GravityTransaction.name, schema: GravityTransactionSchema }])],
|
||||||
|
exports: [MongooseModule],
|
||||||
|
})
|
||||||
|
export class GravityTransactionModule {}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
|
||||||
|
import { Document } from 'mongoose'
|
||||||
|
|
||||||
|
export type GravityTransactionDocument = GravityTransaction & Document
|
||||||
|
|
||||||
|
export type GravityTransactionType =
|
||||||
|
| 'registration' // 注册赠送
|
||||||
|
| 'interview_deduct' // AI 面试消耗
|
||||||
|
| 'optimize_deduct' // 简历优化消耗
|
||||||
|
| 'download_deduct' // 简历下载消耗
|
||||||
|
| 'purchase' // 充值购买
|
||||||
|
| 'monthly_topup' // 月度补给
|
||||||
|
| 'migration' // 旧额度迁移
|
||||||
|
| 'plan_set' // 套餐设置
|
||||||
|
| 'share' // 分享所得
|
||||||
|
| 'contribution' // 面经贡献奖励
|
||||||
|
| 'share_credits_fallback' // 分享币后备抵扣
|
||||||
|
| 'admin_adjust' // 管理员调整
|
||||||
|
|
||||||
|
@Schema({ timestamps: true })
|
||||||
|
export class GravityTransaction {
|
||||||
|
@Prop({ required: true, index: true })
|
||||||
|
userId: string
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
amount: number // 变动数量(正=增加,负=减少)
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
balance: number // 变动后余额
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
type: GravityTransactionType
|
||||||
|
|
||||||
|
@Prop({ default: '' })
|
||||||
|
description: string // 描述(如 "AI 模拟面试消耗")
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
refId?: string // 关联 ID(订单号、面试ID 等)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GravityTransactionSchema = SchemaFactory.createForClass(GravityTransaction)
|
||||||
|
|
||||||
|
GravityTransactionSchema.index({ userId: 1, createdAt: -1 })
|
||||||
@@ -10,6 +10,8 @@ export interface GravityRates {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface PricingConfig {
|
interface PricingConfig {
|
||||||
|
/** 新用户注册赠送引力值 */
|
||||||
|
registrationGravity: number
|
||||||
interview: { pricePerSession: number; creditsPerPurchase: number }
|
interview: { pricePerSession: number; creditsPerPurchase: number }
|
||||||
resumeOptimize: { freeLimit: number; pricePerOptimize: number; creditsPerPurchase: number }
|
resumeOptimize: { freeLimit: number; pricePerOptimize: number; creditsPerPurchase: number }
|
||||||
resumeDownload: { pricePerDownload: number; creditsPerPurchase: number }
|
resumeDownload: { pricePerDownload: number; creditsPerPurchase: number }
|
||||||
@@ -21,13 +23,14 @@ interface PricingConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_PRICING: PricingConfig = {
|
const DEFAULT_PRICING: PricingConfig = {
|
||||||
interview: { pricePerSession: 500, creditsPerPurchase: 1 },
|
registrationGravity: 50,
|
||||||
resumeOptimize: { freeLimit: 3, pricePerOptimize: 300, creditsPerPurchase: 1 },
|
interview: { pricePerSession: 600, creditsPerPurchase: 1 },
|
||||||
|
resumeOptimize: { freeLimit: 3, pricePerOptimize: 400, creditsPerPurchase: 1 },
|
||||||
resumeDownload: { pricePerDownload: 200, creditsPerPurchase: 1 },
|
resumeDownload: { pricePerDownload: 200, creditsPerPurchase: 1 },
|
||||||
gravityRates: { interviewPerUse: 5, optimizePerUse: 3, downloadPerUse: 2 },
|
gravityRates: { interviewPerUse: 5, optimizePerUse: 3, downloadPerUse: 2 },
|
||||||
plans: {
|
plans: {
|
||||||
growth: { price: 1990, durationDays: 30, gravityPerMonth: 250, credits: { interview: 999, resumeOptimize: 20, resumeDownload: 10 }, features: ['免费版全部权益', 'AI 数字人面试每次 3 引力值(折扣价)', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题推送', '参考回答思路', '公司真题库', '简历优化 20 次/月', '简历下载 10 次/月'] },
|
growth: { price: 1900, durationDays: 30, gravityPerMonth: 80, credits: { interview: 999, resumeOptimize: 20, resumeDownload: 10 }, features: ['免费版全部权益', 'AI 模拟面试(每次消耗 5 引力值,无限次)', '详细面试报告(四维评分 + 语音复盘)', '进步轨迹雷达图 + 打卡日历', '每日一题推送 + 参考思路', '公司真题库', '每月赠送 80 引力值,可用于面试/优化/下载'] },
|
||||||
sprint: { price: 4990, durationDays: 30, gravityPerMonth: 600, credits: { interview: 999, resumeOptimize: 50, resumeDownload: 30 }, features: ['成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告', '学习路径推荐', '真人导师 1v1 点评(每月 1 次)', '简历精修(每月 1 次)', '内推优先', '简历优化 50 次/月', '简历下载 30 次/月'] },
|
sprint: { price: 4900, durationDays: 30, gravityPerMonth: 200, credits: { interview: 999, resumeOptimize: 50, resumeDownload: 30 }, features: ['成长版全部权益', 'AI 语音深度分析(语气词/语速/停顿检测)', '技能缺口分析报告', '公司真题库精选', '每月赠送 200 引力值,可用于面试/优化/下载'] },
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,6 +65,7 @@ export class PricingService {
|
|||||||
|
|
||||||
private mergeDefaults(value: any): PricingConfig {
|
private mergeDefaults(value: any): PricingConfig {
|
||||||
return {
|
return {
|
||||||
|
registrationGravity: value?.registrationGravity ?? DEFAULT_PRICING.registrationGravity,
|
||||||
interview: { ...DEFAULT_PRICING.interview, ...value?.interview },
|
interview: { ...DEFAULT_PRICING.interview, ...value?.interview },
|
||||||
resumeOptimize: { ...DEFAULT_PRICING.resumeOptimize, ...value?.resumeOptimize },
|
resumeOptimize: { ...DEFAULT_PRICING.resumeOptimize, ...value?.resumeOptimize },
|
||||||
resumeDownload: { ...DEFAULT_PRICING.resumeDownload, ...value?.resumeDownload },
|
resumeDownload: { ...DEFAULT_PRICING.resumeDownload, ...value?.resumeDownload },
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Controller, Get, Post, Body, Param, Res, HttpException, HttpStatus, UseGuards, UploadedFile, UseInterceptors } from '@nestjs/common'
|
import { Controller, Get, Post, Body, Param, Res, HttpException, HttpStatus, UseGuards, UploadedFile, UseInterceptors, Logger } from '@nestjs/common'
|
||||||
import { FileInterceptor } from '@nestjs/platform-express'
|
import { FileInterceptor } from '@nestjs/platform-express'
|
||||||
import { Response } from 'express'
|
import { Response } from 'express'
|
||||||
import * as fs from 'fs'
|
import * as fs from 'fs'
|
||||||
@@ -10,6 +10,7 @@ import { Public } from '../../common/decorators/public.decorator'
|
|||||||
|
|
||||||
@Controller('tts')
|
@Controller('tts')
|
||||||
export class TtsController {
|
export class TtsController {
|
||||||
|
private readonly logger = new Logger(TtsController.name)
|
||||||
constructor(private ttsService: TtsService) {}
|
constructor(private ttsService: TtsService) {}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@@ -42,28 +43,64 @@ export class TtsController {
|
|||||||
if (!file) throw new HttpException('请上传音频文件', HttpStatus.BAD_REQUEST)
|
if (!file) throw new HttpException('请上传音频文件', HttpStatus.BAD_REQUEST)
|
||||||
const uploadDir = '/tmp/asr_uploads'
|
const uploadDir = '/tmp/asr_uploads'
|
||||||
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true })
|
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true })
|
||||||
const ext = path.extname(file.originalname) || '.mp3'
|
const ext = file.originalname ? path.extname(file.originalname) || '.aac' : '.aac'
|
||||||
const dest = path.join(uploadDir, file.filename + ext)
|
const dest = path.join(uploadDir, file.filename + ext)
|
||||||
fs.renameSync(file.path, dest)
|
fs.renameSync(file.path, dest)
|
||||||
|
|
||||||
|
// 拒绝损坏/空音频文件,避免 whisper 调用 ffmpeg 解码失败刷错误日志
|
||||||
|
const stat = fs.statSync(dest)
|
||||||
|
if (!stat.size || stat.size < 500) {
|
||||||
|
this.logger.warn(`ASR: empty audio upload (size=${stat.size}), ext=${ext}`)
|
||||||
|
try { fs.unlinkSync(dest) } catch {}
|
||||||
|
return { text: '' }
|
||||||
|
}
|
||||||
|
|
||||||
|
let wavPath = dest
|
||||||
|
if (ext.toLowerCase() !== '.wav') {
|
||||||
|
const potentialWav = dest.replace(/\.[^.]+$/, '.wav')
|
||||||
|
try {
|
||||||
|
execSync(`ffmpeg -y -i "${dest}" -ar 16000 -ac 1 -c:a pcm_s16le "${potentialWav}"`, {
|
||||||
|
timeout: 30000, encoding: 'utf8', stdio: 'pipe',
|
||||||
|
})
|
||||||
|
wavPath = potentialWav
|
||||||
|
} catch (e: any) {
|
||||||
|
this.logger.warn(`FFmpeg conversion failed: ${e.message}, using original format`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
let text = ''
|
||||||
if (process.env.OPENAI_API_KEY) {
|
if (process.env.OPENAI_API_KEY) {
|
||||||
const result = execSync(
|
try {
|
||||||
`curl -s -X POST https://api.openai.com/v1/audio/transcriptions \
|
const result = execSync(
|
||||||
-H "Authorization: Bearer ${process.env.OPENAI_API_KEY}" \
|
`curl -s -X POST https://api.openai.com/v1/audio/transcriptions \
|
||||||
-H "Content-Type: multipart/form-data" \
|
-H "Authorization: Bearer ${process.env.OPENAI_API_KEY}" \
|
||||||
-F "file=@${dest}" \
|
-H "Content-Type: multipart/form-data" \
|
||||||
-F "model=whisper-1" \
|
-F "file=@${wavPath}" \
|
||||||
-F "language=zh"`,
|
-F "model=whisper-1" \
|
||||||
{ encoding: 'utf8', timeout: 30000 },
|
-F "language=zh"`,
|
||||||
|
{ encoding: 'utf8', timeout: 30000 },
|
||||||
|
)
|
||||||
|
const parsed = JSON.parse(result)
|
||||||
|
if (parsed.text) text = parsed.text.trim()
|
||||||
|
} catch (e: any) {
|
||||||
|
this.logger.warn(`OpenAI ASR failed, falling back to local: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!text) {
|
||||||
|
const whisperResult = execSync(
|
||||||
|
`python3 -c 'import sys, whisper; model = whisper.load_model("tiny"); print(model.transcribe(sys.argv[1], language="zh")["text"].strip())' "${wavPath}"`,
|
||||||
|
{ encoding: 'utf8', timeout: 60000 },
|
||||||
)
|
)
|
||||||
const parsed = JSON.parse(result)
|
if (whisperResult?.trim()) text = whisperResult.trim()
|
||||||
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 })
|
return { text }
|
||||||
if (whisperResult && whisperResult.trim()) {
|
} catch (e: any) {
|
||||||
return { text: whisperResult.trim() }
|
this.logger.error(`ASR failed: ${e?.message || e}`)
|
||||||
}
|
return { text: '' }
|
||||||
} catch {}
|
} finally {
|
||||||
return { text: '' }
|
try { if (dest) fs.unlinkSync(dest) } catch {}
|
||||||
|
try { if (wavPath && wavPath !== dest) fs.unlinkSync(wavPath) } catch {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { InjectModel } from '@nestjs/mongoose'
|
|||||||
import { Model } from 'mongoose'
|
import { Model } from 'mongoose'
|
||||||
import { User, UserDocument } from './user.schema'
|
import { User, UserDocument } from './user.schema'
|
||||||
import { PricingService } from '../schemas/pricing.service'
|
import { PricingService } from '../schemas/pricing.service'
|
||||||
|
import { GravityTransaction, GravityTransactionType } from '../schemas/gravity-transaction.schema'
|
||||||
|
|
||||||
const FREE_OPTIMIZE_LIMIT = 3
|
const FREE_OPTIMIZE_LIMIT = 3
|
||||||
|
|
||||||
@@ -12,9 +13,46 @@ export class QuotaService {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
||||||
|
@InjectModel(GravityTransaction.name) private gravityTxModel: Model<GravityTransaction>,
|
||||||
private pricingService: PricingService,
|
private pricingService: PricingService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
private async logTransaction(userId: string, amount: number, type: GravityTransactionType, description: string, refId?: string) {
|
||||||
|
const u = await this.userModel.findById(userId).select('gravity').exec()
|
||||||
|
const balance = u?.gravity ?? 0
|
||||||
|
await this.gravityTxModel.create({ userId, amount, balance, type, description, refId })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 仅检查面试引力值是否充足,不扣除(用于先 AI 后扣款模式) */
|
||||||
|
async checkInterview(userId: string): Promise<number> {
|
||||||
|
const user = await this.userModel.findById(userId).exec()
|
||||||
|
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||||
|
|
||||||
|
// 迁移旧字段到 gravity
|
||||||
|
if ((user.gravity ?? 0) <= 0 && this.hasOldCredits(user)) {
|
||||||
|
await this.migrateOldCredits(userId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const rates = (await this.pricingService.getConfig()).gravityRates
|
||||||
|
const cost = rates.interviewPerUse
|
||||||
|
|
||||||
|
// 检查 gravity 或 shareCredits 是否足够
|
||||||
|
const gravOk = (user.gravity ?? 0) >= cost
|
||||||
|
const shareOk = (user.shareCredits ?? 0) > 0
|
||||||
|
if (!gravOk && !shareOk) {
|
||||||
|
throw new HttpException('引力值不足,请充值或分享获取', HttpStatus.FORBIDDEN)
|
||||||
|
}
|
||||||
|
return cost
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 扣除面试引力值(在 AI 调用成功后调用) */
|
||||||
|
async deductInterview(userId: string, cost: number) {
|
||||||
|
const result = await this.deductGravityOrFallback(userId, cost)
|
||||||
|
if (!result) {
|
||||||
|
throw new HttpException('引力值不足', HttpStatus.FORBIDDEN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 检查并扣除面试引力值(所有计划统一走引力值) */
|
/** 检查并扣除面试引力值(所有计划统一走引力值) */
|
||||||
async checkAndDeductInterview(userId: string) {
|
async checkAndDeductInterview(userId: string) {
|
||||||
const user = await this.userModel.findById(userId).exec()
|
const user = await this.userModel.findById(userId).exec()
|
||||||
@@ -76,19 +114,23 @@ export class QuotaService {
|
|||||||
|
|
||||||
/** 从 gravity 扣除,后备从 shareCredits 扣除(兼容旧数据) */
|
/** 从 gravity 扣除,后备从 shareCredits 扣除(兼容旧数据) */
|
||||||
private async deductGravityOrFallback(userId: string, cost: number): Promise<boolean> {
|
private async deductGravityOrFallback(userId: string, cost: number): Promise<boolean> {
|
||||||
// 主路径:gravity
|
|
||||||
const gravResult = await this.userModel.findOneAndUpdate(
|
const gravResult = await this.userModel.findOneAndUpdate(
|
||||||
{ _id: userId, gravity: { $gte: cost } },
|
{ _id: userId, gravity: { $gte: cost } },
|
||||||
{ $inc: { gravity: -cost } },
|
{ $inc: { gravity: -cost } },
|
||||||
).exec()
|
).exec()
|
||||||
if (gravResult) return true
|
if (gravResult) {
|
||||||
|
await this.logTransaction(userId, -cost, 'interview_deduct', `AI 模拟面试消耗 ${cost} 引力值`)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// 后备:旧 shareCredits
|
|
||||||
const shareResult = await this.userModel.findOneAndUpdate(
|
const shareResult = await this.userModel.findOneAndUpdate(
|
||||||
{ _id: userId, shareCredits: { $gt: 0 } },
|
{ _id: userId, shareCredits: { $gt: 0 } },
|
||||||
{ $inc: { shareCredits: -1 } },
|
{ $inc: { shareCredits: -1 } },
|
||||||
).exec()
|
).exec()
|
||||||
if (shareResult) return true
|
if (shareResult) {
|
||||||
|
await this.logTransaction(userId, 0, 'share_credits_fallback', '分享币后备抵扣 1 次')
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -101,6 +143,7 @@ export class QuotaService {
|
|||||||
{ $inc: { gravity: amount } },
|
{ $inc: { gravity: amount } },
|
||||||
).exec()
|
).exec()
|
||||||
if (!result) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
if (!result) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||||
|
await this.logTransaction(userId, amount, 'purchase', `充值获得 ${amount} 引力值`)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 设置 VIP 套餐引力值额度 */
|
/** 设置 VIP 套餐引力值额度 */
|
||||||
@@ -112,6 +155,7 @@ export class QuotaService {
|
|||||||
},
|
},
|
||||||
}).exec()
|
}).exec()
|
||||||
if (!result) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
if (!result) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||||
|
await this.logTransaction(userId, gravityAmount, 'plan_set', `套餐开通,获得 ${gravityAmount} 引力值`)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 是否为非会员用户授予初始引力值 */
|
/** 是否为非会员用户授予初始引力值 */
|
||||||
@@ -119,6 +163,7 @@ export class QuotaService {
|
|||||||
await this.userModel.findByIdAndUpdate(userId, {
|
await this.userModel.findByIdAndUpdate(userId, {
|
||||||
$set: { interviewCredits: 1, gravity: 5 },
|
$set: { interviewCredits: 1, gravity: 5 },
|
||||||
}).exec()
|
}).exec()
|
||||||
|
await this.logTransaction(userId, 5, 'registration', '注册赠送 5 引力值')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 判断是否有旧额度需要迁移 */
|
/** 判断是否有旧额度需要迁移 */
|
||||||
@@ -150,5 +195,6 @@ export class QuotaService {
|
|||||||
shareCredits: 0,
|
shareCredits: 0,
|
||||||
},
|
},
|
||||||
}).exec()
|
}).exec()
|
||||||
|
await this.logTransaction(userId, total, 'migration', `旧额度迁移,获得 ${total} 引力值`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Controller, Post, Get, Put, Body, Req, HttpCode, HttpStatus, UseGuards } from '@nestjs/common'
|
import { Controller, Post, Get, Put, Query, Body, Req, HttpCode, HttpStatus, UseGuards } from '@nestjs/common'
|
||||||
import { UserService } from './user.service'
|
import { UserService } from './user.service'
|
||||||
import { Public } from '../../common/decorators/public.decorator'
|
import { Public } from '../../common/decorators/public.decorator'
|
||||||
import { CurrentUser } from '../../common/decorators/current-user.decorator'
|
import { CurrentUser } from '../../common/decorators/current-user.decorator'
|
||||||
@@ -18,8 +18,8 @@ export class UserController {
|
|||||||
@Public()
|
@Public()
|
||||||
@Post('login')
|
@Post('login')
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async login(@Body('phone') phone: string, @Body('code') code: string) {
|
async login(@Body('phone') phone: string, @Body('code') code: string, @Req() req) {
|
||||||
return this.userService.loginByPhone(phone, code)
|
return this.userService.loginByPhone(phone, code, req.ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 📧 邮箱验证码登录(H5 用)
|
// 📧 邮箱验证码登录(H5 用)
|
||||||
@@ -41,32 +41,32 @@ export class UserController {
|
|||||||
@Public()
|
@Public()
|
||||||
@Post('email-login')
|
@Post('email-login')
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async emailLogin(@Body('email') email: string, @Body('code') code: string) {
|
async emailLogin(@Body('email') email: string, @Body('code') code: string, @Req() req) {
|
||||||
return this.userService.loginByEmail(email, code)
|
return this.userService.loginByEmail(email, code, req.ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 密码登录
|
// 密码登录
|
||||||
@Public()
|
@Public()
|
||||||
@Post('password-login')
|
@Post('password-login')
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async passwordLogin(@Body('email') email: string, @Body('password') password: string) {
|
async passwordLogin(@Body('email') email: string, @Body('password') password: string, @Req() req) {
|
||||||
return this.userService.loginByPassword(email, password)
|
return this.userService.loginByPassword(email, password, req.ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 邮箱+密码注册
|
// 邮箱+密码注册
|
||||||
@Public()
|
@Public()
|
||||||
@Post('register')
|
@Post('register')
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async register(@Body('email') email: string, @Body('password') password: string) {
|
async register(@Body('email') email: string, @Body('password') password: string, @Req() req) {
|
||||||
return this.userService.registerWithPassword(email, password)
|
return this.userService.registerWithPassword(email, password, req.ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 微信静默登录
|
// 微信静默登录
|
||||||
@Public()
|
@Public()
|
||||||
@Post('wx-login')
|
@Post('wx-login')
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
async wxLogin(@Body('code') code: string) {
|
async wxLogin(@Body('code') code: string, @Req() req) {
|
||||||
return this.userService.loginByWx(code)
|
return this.userService.loginByWx(code, undefined, req.ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('info')
|
@Get('info')
|
||||||
@@ -88,4 +88,13 @@ export class UserController {
|
|||||||
async setPassword(@CurrentUser('userId') userId: string, @Body('password') password: string) {
|
async setPassword(@CurrentUser('userId') userId: string, @Body('password') password: string) {
|
||||||
return this.userService.setPassword(userId, password)
|
return this.userService.setPassword(userId, password)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('gravity-transactions')
|
||||||
|
async getGravityTransactions(
|
||||||
|
@CurrentUser('userId') userId: string,
|
||||||
|
@Query('page') page = '1',
|
||||||
|
@Query('limit') limit = '20',
|
||||||
|
) {
|
||||||
|
return this.userService.getGravityTransactions(userId, parseInt(page), parseInt(limit))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,13 +65,21 @@ export class User {
|
|||||||
|
|
||||||
@Prop({ default: '', select: false })
|
@Prop({ default: '', select: false })
|
||||||
password?: string
|
password?: string
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
lastLoginAt?: Date
|
||||||
|
|
||||||
|
@Prop({ default: '' })
|
||||||
|
lastLoginIp?: string
|
||||||
|
|
||||||
|
@Prop({ default: '' })
|
||||||
|
lastLoginLocation?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const UserSchema = SchemaFactory.createForClass(User)
|
export const UserSchema = SchemaFactory.createForClass(User)
|
||||||
|
|
||||||
UserSchema.pre('save', function (next) {
|
UserSchema.pre('save', async function () {
|
||||||
if (!this.phone && !this.wxOpenid && !this.email) {
|
if (!this.phone && !this.wxOpenid && !this.email) {
|
||||||
return next(new Error('用户必须至少有一个联系方式(手机号/微信/邮箱)'))
|
throw new Error('用户必须至少有一个联系方式(手机号/微信/邮箱)')
|
||||||
}
|
}
|
||||||
next()
|
|
||||||
})
|
})
|
||||||
@@ -4,6 +4,7 @@ import { JwtService } from '@nestjs/jwt'
|
|||||||
import { HttpException } from '@nestjs/common'
|
import { HttpException } from '@nestjs/common'
|
||||||
import { UserService } from './user.service'
|
import { UserService } from './user.service'
|
||||||
import { EmailService } from '../email/email.service'
|
import { EmailService } from '../email/email.service'
|
||||||
|
import { PricingService } from '../schemas/pricing.service'
|
||||||
|
|
||||||
describe('UserService', () => {
|
describe('UserService', () => {
|
||||||
let service: UserService
|
let service: UserService
|
||||||
@@ -44,8 +45,10 @@ describe('UserService', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
UserService,
|
UserService,
|
||||||
{ provide: getModelToken('User'), useValue: mockUserModel },
|
{ provide: getModelToken('User'), useValue: mockUserModel },
|
||||||
|
{ provide: getModelToken('GravityTransaction'), useValue: { create: jest.fn() } },
|
||||||
{ provide: JwtService, useValue: mockJwtService },
|
{ provide: JwtService, useValue: mockJwtService },
|
||||||
{ provide: EmailService, useValue: mockEmailService },
|
{ provide: EmailService, useValue: mockEmailService },
|
||||||
|
{ provide: PricingService, useValue: { getConfig: jest.fn().mockResolvedValue({ registrationGravity: 50, gravityRates: { interviewPerUse: 5, optimizePerUse: 3, downloadPerUse: 2 }, plans: { growth: { gravityPerMonth: 80 }, sprint: { gravityPerMonth: 200 } } }) } },
|
||||||
],
|
],
|
||||||
}).compile()
|
}).compile()
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,23 @@
|
|||||||
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common'
|
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common'
|
||||||
import { InjectModel } from '@nestjs/mongoose'
|
import { InjectModel } from '@nestjs/mongoose'
|
||||||
import { Model } from 'mongoose'
|
import { Model } from 'mongoose'
|
||||||
import { JwtService } from '@nestjs/jwt'
|
|
||||||
import { User, UserDocument } from './user.schema'
|
import { User, UserDocument } from './user.schema'
|
||||||
|
import { JwtService } from '@nestjs/jwt'
|
||||||
import { EmailService } from '../email/email.service'
|
import { EmailService } from '../email/email.service'
|
||||||
|
import { PricingService } from '../schemas/pricing.service'
|
||||||
|
import { GravityTransaction, GravityTransactionType } from '../schemas/gravity-transaction.schema'
|
||||||
|
|
||||||
|
/** 通过 IP 查询粗略地理位置(ip-api.com 免费接口) */
|
||||||
|
async function lookupIpLocation(ip: string): Promise<string> {
|
||||||
|
if (!ip || ip === '127.0.0.1' || ip === '::1' || ip.startsWith('192.168.') || ip.startsWith('10.')) return ''
|
||||||
|
try {
|
||||||
|
const res = await fetch(`http://ip-api.com/json/${ip}?fields=country,regionName,city&lang=zh-CN`, { signal: AbortSignal.timeout(3000) })
|
||||||
|
if (!res.ok) return ''
|
||||||
|
const data: any = await res.json()
|
||||||
|
if (data.status !== 'success') return ''
|
||||||
|
return [data.country, data.regionName, data.city].filter(Boolean).join(' ')
|
||||||
|
} catch { return '' }
|
||||||
|
}
|
||||||
|
|
||||||
// In-memory stores
|
// In-memory stores
|
||||||
const codeStore = new Map<string, { code: string; expiresAt: number }>()
|
const codeStore = new Map<string, { code: string; expiresAt: number }>()
|
||||||
@@ -16,10 +30,18 @@ export class UserService {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
||||||
|
@InjectModel(GravityTransaction.name) private gravityTxModel: Model<GravityTransaction>,
|
||||||
private jwtService: JwtService,
|
private jwtService: JwtService,
|
||||||
private emailService: EmailService,
|
private emailService: EmailService,
|
||||||
|
private pricingService: PricingService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
private async logTransaction(userId: string, amount: number, type: GravityTransactionType, description: string) {
|
||||||
|
const u = await this.userModel.findById(userId).select('gravity').exec()
|
||||||
|
const balance = u?.gravity ?? 0
|
||||||
|
await this.gravityTxModel.create({ userId, amount, balance, type, description })
|
||||||
|
}
|
||||||
|
|
||||||
async sendCode(phone: string) {
|
async sendCode(phone: string) {
|
||||||
const code = process.env.NODE_ENV === 'production'
|
const code = process.env.NODE_ENV === 'production'
|
||||||
? String(Math.floor(100000 + Math.random() * 900000))
|
? String(Math.floor(100000 + Math.random() * 900000))
|
||||||
@@ -33,7 +55,7 @@ export class UserService {
|
|||||||
return { message: '验证码已发送' }
|
return { message: '验证码已发送' }
|
||||||
}
|
}
|
||||||
|
|
||||||
async loginByPhone(phone: string, code: string) {
|
async loginByPhone(phone: string, code: string, ip?: string) {
|
||||||
const record = codeStore.get(phone)
|
const record = codeStore.get(phone)
|
||||||
if (!record || record.code !== code) {
|
if (!record || record.code !== code) {
|
||||||
throw new HttpException('验证码错误', HttpStatus.UNAUTHORIZED)
|
throw new HttpException('验证码错误', HttpStatus.UNAUTHORIZED)
|
||||||
@@ -45,14 +67,21 @@ export class UserService {
|
|||||||
codeStore.delete(phone)
|
codeStore.delete(phone)
|
||||||
|
|
||||||
let user = await this.userModel.findOne({ phone }).exec()
|
let user = await this.userModel.findOne({ phone }).exec()
|
||||||
|
let isNew = false
|
||||||
if (!user) {
|
if (!user) {
|
||||||
user = await this.userModel.create({ phone, nickname: `用户${phone.slice(-4)}`, gravity: 5 })
|
isNew = true
|
||||||
|
user = await this.userModel.create({ phone, nickname: `用户${phone.slice(-4)}`, gravity: (await this.pricingService.getConfig()).registrationGravity })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await this.recordLogin(user._id.toString(), ip)
|
||||||
|
if (isNew) {
|
||||||
|
const amount = (await this.pricingService.getConfig()).registrationGravity
|
||||||
|
await this.logTransaction(user._id.toString(), amount, 'registration', '注册赠送引力值')
|
||||||
|
}
|
||||||
return this.generateAuthResponse(user)
|
return this.generateAuthResponse(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
async loginByWx(code: string, userId?: string) {
|
async loginByWx(code: string, userId?: string, ip?: string) {
|
||||||
const appid = process.env.WX_APPID
|
const appid = process.env.WX_APPID
|
||||||
const secret = process.env.WX_SECRET
|
const secret = process.env.WX_SECRET
|
||||||
if (!appid || !secret) {
|
if (!appid || !secret) {
|
||||||
@@ -80,10 +109,17 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let user = await this.userModel.findOne({ wxOpenid: openid }).exec()
|
let user = await this.userModel.findOne({ wxOpenid: openid }).exec()
|
||||||
|
let isNew = false
|
||||||
if (!user) {
|
if (!user) {
|
||||||
user = await this.userModel.create({ wxOpenid: openid, nickname: '微信用户', gravity: 5 })
|
isNew = true
|
||||||
|
user = await this.userModel.create({ wxOpenid: openid, nickname: '微信用户', gravity: (await this.pricingService.getConfig()).registrationGravity })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await this.recordLogin(user._id.toString(), ip)
|
||||||
|
if (isNew) {
|
||||||
|
const amount = (await this.pricingService.getConfig()).registrationGravity
|
||||||
|
await this.logTransaction(user._id.toString(), amount, 'registration', '注册赠送引力值')
|
||||||
|
}
|
||||||
return this.generateAuthResponse(user)
|
return this.generateAuthResponse(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,7 +175,7 @@ export class UserService {
|
|||||||
return { message: '验证码已发送,请查收邮件' }
|
return { message: '验证码已发送,请查收邮件' }
|
||||||
}
|
}
|
||||||
|
|
||||||
async loginByEmail(email: string, code: string) {
|
async loginByEmail(email: string, code: string, ip?: string) {
|
||||||
const record = emailCodeStore.get(email)
|
const record = emailCodeStore.get(email)
|
||||||
if (!record || record.code !== code) {
|
if (!record || record.code !== code) {
|
||||||
throw new HttpException('验证码错误', HttpStatus.UNAUTHORIZED)
|
throw new HttpException('验证码错误', HttpStatus.UNAUTHORIZED)
|
||||||
@@ -156,23 +192,29 @@ export class UserService {
|
|||||||
if (!user) {
|
if (!user) {
|
||||||
isNew = true
|
isNew = true
|
||||||
const nick = email.split('@')[0]
|
const nick = email.split('@')[0]
|
||||||
user = await this.userModel.create({ email, nickname: nick, remaining: 0, gravity: 5 })
|
user = await this.userModel.create({ email, nickname: nick, remaining: 0, gravity: (await this.pricingService.getConfig()).registrationGravity })
|
||||||
|
}
|
||||||
|
await this.recordLogin(user._id.toString(), ip)
|
||||||
|
if (isNew) {
|
||||||
|
const amount = (await this.pricingService.getConfig()).registrationGravity
|
||||||
|
await this.logTransaction(user._id.toString(), amount, 'registration', '注册赠送引力值')
|
||||||
}
|
}
|
||||||
return { ...this.generateAuthResponse(user), isNew, hasPassword: !!user.password }
|
return { ...this.generateAuthResponse(user), isNew, hasPassword: !!user.password }
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔐 密码登录
|
// 🔐 密码登录
|
||||||
async loginByPassword(email: string, password: string) {
|
async loginByPassword(email: string, password: string, ip?: string) {
|
||||||
const user = await this.userModel.findOne({ email }).select('+password').exec()
|
const user = await this.userModel.findOne({ email }).select('+password').exec()
|
||||||
if (!user) throw new HttpException('账号不存在', HttpStatus.NOT_FOUND)
|
if (!user) throw new HttpException('账号不存在', HttpStatus.NOT_FOUND)
|
||||||
if (!user.password) throw new HttpException('该账号未设置密码,请使用验证码登录', HttpStatus.UNAUTHORIZED)
|
if (!user.password) throw new HttpException('该账号未设置密码,请使用验证码登录', HttpStatus.UNAUTHORIZED)
|
||||||
const match = await bcrypt.compare(password, user.password)
|
const match = await bcrypt.compare(password, user.password)
|
||||||
if (!match) throw new HttpException('密码错误', HttpStatus.UNAUTHORIZED)
|
if (!match) throw new HttpException('密码错误', HttpStatus.UNAUTHORIZED)
|
||||||
|
await this.recordLogin(user._id.toString(), ip)
|
||||||
return this.generateAuthResponse(user)
|
return this.generateAuthResponse(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 📝 邮箱+密码注册
|
// 📝 邮箱+密码注册
|
||||||
async registerWithPassword(email: string, password: string) {
|
async registerWithPassword(email: string, password: string, ip?: string) {
|
||||||
if (!email || !email.includes('@')) {
|
if (!email || !email.includes('@')) {
|
||||||
throw new HttpException('请输入正确的邮箱地址', HttpStatus.BAD_REQUEST)
|
throw new HttpException('请输入正确的邮箱地址', HttpStatus.BAD_REQUEST)
|
||||||
}
|
}
|
||||||
@@ -187,11 +229,15 @@ export class UserService {
|
|||||||
// 已有验证码注册的用户,补充设置密码
|
// 已有验证码注册的用户,补充设置密码
|
||||||
existing.password = await bcrypt.hash(password, 10)
|
existing.password = await bcrypt.hash(password, 10)
|
||||||
await existing.save()
|
await existing.save()
|
||||||
|
await this.recordLogin(existing._id.toString(), ip)
|
||||||
return this.generateAuthResponse(existing)
|
return this.generateAuthResponse(existing)
|
||||||
}
|
}
|
||||||
const nick = email.split('@')[0]
|
const nick = email.split('@')[0]
|
||||||
const hashed = await bcrypt.hash(password, 10)
|
const hashed = await bcrypt.hash(password, 10)
|
||||||
const user = await this.userModel.create({ email, nickname: nick, password: hashed, remaining: 0, gravity: 5 })
|
const user = await this.userModel.create({ email, nickname: nick, password: hashed, remaining: 0, gravity: (await this.pricingService.getConfig()).registrationGravity })
|
||||||
|
const amount = (await this.pricingService.getConfig()).registrationGravity
|
||||||
|
await this.logTransaction(user._id.toString(), amount, 'registration', '注册赠送引力值')
|
||||||
|
await this.recordLogin(user._id.toString(), ip)
|
||||||
return this.generateAuthResponse(user)
|
return this.generateAuthResponse(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,6 +265,17 @@ export class UserService {
|
|||||||
|
|
||||||
getModel() { return this.userModel }
|
getModel() { return this.userModel }
|
||||||
|
|
||||||
|
/** 记录登录时间/IP/归属地 */
|
||||||
|
async recordLogin(userId: string, ip?: string) {
|
||||||
|
const update: any = { lastLoginAt: new Date() }
|
||||||
|
if (ip) {
|
||||||
|
update.lastLoginIp = ip
|
||||||
|
const location = await lookupIpLocation(ip)
|
||||||
|
if (location) update.lastLoginLocation = location
|
||||||
|
}
|
||||||
|
await this.userModel.findByIdAndUpdate(userId, { $set: update }).exec()
|
||||||
|
}
|
||||||
|
|
||||||
async getUsage(userId: string) {
|
async getUsage(userId: string) {
|
||||||
const user = await this.userModel.findById(userId).exec()
|
const user = await this.userModel.findById(userId).exec()
|
||||||
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||||
@@ -234,6 +291,15 @@ export class UserService {
|
|||||||
await user.save()
|
await user.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getGravityTransactions(userId: string, page = 1, limit = 20) {
|
||||||
|
const skip = (page - 1) * limit
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
this.gravityTxModel.find({ userId }).sort({ createdAt: -1 }).skip(skip).limit(limit).exec(),
|
||||||
|
this.gravityTxModel.countDocuments({ userId }),
|
||||||
|
])
|
||||||
|
return { items, total, page, limit, totalPages: Math.ceil(total / limit) }
|
||||||
|
}
|
||||||
|
|
||||||
private generateAuthResponse(user: UserDocument) {
|
private generateAuthResponse(user: UserDocument) {
|
||||||
const payload = { userId: user._id.toString(), phone: user.phone || '', role: user.role || 'user' }
|
const payload = { userId: user._id.toString(), phone: user.phone || '', role: user.role || 'user' }
|
||||||
return {
|
return {
|
||||||
@@ -260,6 +326,9 @@ export class UserService {
|
|||||||
freeOptimizeUsed: user.freeOptimizeUsed ?? 0,
|
freeOptimizeUsed: user.freeOptimizeUsed ?? 0,
|
||||||
shareCredits: user.shareCredits ?? 0,
|
shareCredits: user.shareCredits ?? 0,
|
||||||
gravity: user.gravity ?? 0,
|
gravity: user.gravity ?? 0,
|
||||||
|
lastLoginAt: user.lastLoginAt,
|
||||||
|
lastLoginIp: user.lastLoginIp,
|
||||||
|
lastLoginLocation: user.lastLoginLocation,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
import { Controller, Post, Get, Param, Body, Query, UseGuards, HttpException, HttpStatus, Logger, Req, HttpCode } from '@nestjs/common'
|
||||||
|
import { InjectModel } from '@nestjs/mongoose'
|
||||||
|
import { Model } from 'mongoose'
|
||||||
|
import { User, UserDocument } from '../user/user.schema'
|
||||||
|
import { PaymentOrder, PaymentOrderDocument } from '../payment/payment-order.schema'
|
||||||
|
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
|
||||||
|
import { CurrentUser } from '../../common/decorators/current-user.decorator'
|
||||||
|
import { VirtualPaymentService } from './virtual-payment.service'
|
||||||
|
import { PricingService } from '../schemas/pricing.service'
|
||||||
|
import { QuotaService } from '../user/quota.service'
|
||||||
|
import { Public } from '../../common/decorators/public.decorator'
|
||||||
|
|
||||||
|
@Controller('virtual-payment')
|
||||||
|
export class VirtualPaymentController {
|
||||||
|
private readonly logger = new Logger(VirtualPaymentController.name)
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectModel(User.name) private userModel: Model<UserDocument>,
|
||||||
|
@InjectModel(PaymentOrder.name) private orderModel: Model<PaymentOrderDocument>,
|
||||||
|
private vpService: VirtualPaymentService,
|
||||||
|
private pricingService: PricingService,
|
||||||
|
private quotaService: QuotaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建虚拟支付订单(小程序代币充值)
|
||||||
|
* 返回前端调起 wx.requestVirtualPayment 所需的全部参数
|
||||||
|
*/
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Post('create')
|
||||||
|
@HttpCode(200)
|
||||||
|
async create(
|
||||||
|
@CurrentUser('userId') userId: string,
|
||||||
|
@Body('type') type: string,
|
||||||
|
@Body('quantity') quantity: number = 1,
|
||||||
|
@Body('wxCode') wxCode: string,
|
||||||
|
@Req() req: any,
|
||||||
|
) {
|
||||||
|
if (!['interview', 'optimize', 'download', 'growth', 'sprint'].includes(type)) {
|
||||||
|
throw new HttpException('无效产品类型', HttpStatus.BAD_REQUEST)
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await this.userModel.findById(userId).exec()
|
||||||
|
if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
|
||||||
|
if (!user.wxOpenid) {
|
||||||
|
throw new HttpException({ message: '未绑定微信', needBindWx: true }, HttpStatus.BAD_REQUEST)
|
||||||
|
}
|
||||||
|
if (!wxCode) {
|
||||||
|
throw new HttpException('缺少 wxCode,请先调用 wx.login()', HttpStatus.BAD_REQUEST)
|
||||||
|
}
|
||||||
|
|
||||||
|
const isPlan = type === 'growth' || type === 'sprint'
|
||||||
|
if (isPlan && user.plan !== 'free') {
|
||||||
|
throw new HttpException('已是会员', HttpStatus.BAD_REQUEST)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pricing = await this.pricingService.getConfig()
|
||||||
|
|
||||||
|
let totalFee: number
|
||||||
|
let qty = 1
|
||||||
|
let productQty = Math.max(1, Math.min(99, quantity || 1))
|
||||||
|
|
||||||
|
if (isPlan) {
|
||||||
|
const planCfg = pricing.plans[type]
|
||||||
|
if (!planCfg) throw new HttpException('套餐未配置', HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
|
totalFee = planCfg.price
|
||||||
|
} else {
|
||||||
|
const priceMap: Record<string, number> = {
|
||||||
|
interview: pricing.interview.pricePerSession,
|
||||||
|
optimize: pricing.resumeOptimize.pricePerOptimize,
|
||||||
|
download: pricing.resumeDownload.pricePerDownload,
|
||||||
|
}
|
||||||
|
qty = productQty
|
||||||
|
totalFee = priceMap[type] * qty
|
||||||
|
if (!totalFee) throw new HttpException('价格未配置', HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
|
||||||
|
const mode = 'short_series_coin'
|
||||||
|
const buyQuantity = totalFee / 100 // 控制台配 1 币 = 1 元,totalFee 单位分
|
||||||
|
const outTradeNo = `VP${type.slice(0, 2).toUpperCase()}${Date.now()}${userId.slice(-6)}`
|
||||||
|
const env = process.env.VP_SANDBOX === 'true' ? 1 : (process.env.NODE_ENV === 'production' ? 0 : 1)
|
||||||
|
const userIp = req.ip || '127.0.0.1'
|
||||||
|
|
||||||
|
// 1. 用 wx.login code 换取 session_key + openid,计算用户态签名
|
||||||
|
let openid: string
|
||||||
|
let signature: string
|
||||||
|
try {
|
||||||
|
const signData = this.vpService.buildSignData(outTradeNo, user.wxOpenid, totalFee, userIp, env, mode, buyQuantity)
|
||||||
|
const result = await this.vpService.exchangeCodeAndSign(wxCode, signData)
|
||||||
|
openid = result.openid
|
||||||
|
signature = result.signature
|
||||||
|
} catch (e: any) {
|
||||||
|
this.logger.error(`[VP] code2session 失败: userId=${userId}, wxCode=${wxCode?.slice(0, 20)}, error=${e.message}, stack=${e.stack?.slice(0, 300)}`)
|
||||||
|
throw new HttpException(`微信身份验证失败: ${e.message}`, HttpStatus.BAD_REQUEST)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验 openid 一致
|
||||||
|
this.logger.log(`[VP] code2session 成功: userId=${userId}, wxOpenid=${user.wxOpenid}, code2session_openid=${openid}`)
|
||||||
|
if (openid !== user.wxOpenid) {
|
||||||
|
this.logger.warn(`[VP] openid 不匹配: userId=${userId}, stored=${user.wxOpenid}, got=${openid}`)
|
||||||
|
throw new HttpException('微信身份不匹配', HttpStatus.FORBIDDEN)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 计算支付签名 pay_sig
|
||||||
|
const signData = this.vpService.buildSignData(outTradeNo, openid, totalFee, userIp, env, mode, buyQuantity)
|
||||||
|
const paySig = this.vpService.computePaySig('requestVirtualPayment', signData, env)
|
||||||
|
|
||||||
|
// 3. 创建本地订单
|
||||||
|
let title: string
|
||||||
|
const titles: Record<string, string> = {
|
||||||
|
interview: 'AI 模拟面试',
|
||||||
|
optimize: '简历优化',
|
||||||
|
download: '简历下载',
|
||||||
|
growth: '成长版月度会员',
|
||||||
|
sprint: '冲刺版月度会员',
|
||||||
|
}
|
||||||
|
if (isPlan) {
|
||||||
|
title = titles[type]
|
||||||
|
} else {
|
||||||
|
title = qty > 1 ? `${titles[type]} ×${qty}` : titles[type]
|
||||||
|
}
|
||||||
|
await this.orderModel.create({
|
||||||
|
outTradeNo,
|
||||||
|
userId,
|
||||||
|
userPhone: user.phone || '',
|
||||||
|
amount: totalFee,
|
||||||
|
title,
|
||||||
|
status: 'pending',
|
||||||
|
channel: 'virtual',
|
||||||
|
type,
|
||||||
|
plan: isPlan ? type : 'growth',
|
||||||
|
metadata: { quantity: qty },
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
outTradeNo,
|
||||||
|
env,
|
||||||
|
mode,
|
||||||
|
offerId: this.vpService.getOfferId(),
|
||||||
|
signData,
|
||||||
|
paySig,
|
||||||
|
signature,
|
||||||
|
openid,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信消息推送回调——虚拟支付通知
|
||||||
|
* 在小程序管理后台 → 开发 → 开发管理 → 消息推送 中配置服务器地址指向此接口
|
||||||
|
*/
|
||||||
|
@Public()
|
||||||
|
@Post('callback')
|
||||||
|
async callback(@Body() body: any, @Req() req: any) {
|
||||||
|
try {
|
||||||
|
// 微信消息体可能是 XML 或 JSON
|
||||||
|
const msg = body.xml || body
|
||||||
|
const event = msg.Event || msg.event
|
||||||
|
|
||||||
|
this.logger.log(`[vp-callback] event=${event}, body=${JSON.stringify(body).slice(0, 500)}`)
|
||||||
|
|
||||||
|
if (event === 'xpay_coin_pay_notify') {
|
||||||
|
await this.handleCoinPayNotify(msg)
|
||||||
|
} else if (event === 'xpay_goods_deliver_notify') {
|
||||||
|
await this.handleGoodsDeliverNotify(msg)
|
||||||
|
} else if (event === 'xpay_refund_notify') {
|
||||||
|
await this.handleRefundNotify(msg)
|
||||||
|
} else {
|
||||||
|
this.logger.warn(`[vp-callback] 未知事件: ${event}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ErrCode: 0, ErrMsg: 'success' }
|
||||||
|
} catch (e: any) {
|
||||||
|
this.logger.error(`[vp-callback] 处理失败: ${e.message}`)
|
||||||
|
return { ErrCode: -1, ErrMsg: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleCoinPayNotify(msg: any) {
|
||||||
|
const outTradeNo = msg.OutTradeNo || msg.out_trade_no
|
||||||
|
if (!outTradeNo) {
|
||||||
|
this.logger.warn('[vp-callback] 代币支付通知缺少 outTradeNo')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const order = await this.orderModel.findOne({ outTradeNo }).exec()
|
||||||
|
if (!order) {
|
||||||
|
this.logger.warn(`[vp-callback] 订单不存在: ${outTradeNo}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (order.status !== 'pending') {
|
||||||
|
this.logger.log(`[vp-callback] 订单已处理: ${outTradeNo} status=${order.status}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
order.status = 'success'
|
||||||
|
order.paidAt = new Date()
|
||||||
|
order.description = `虚拟支付代币充值成功 env=${msg.Env ?? ''}`
|
||||||
|
await order.save()
|
||||||
|
|
||||||
|
const pricing = await this.pricingService.getConfig()
|
||||||
|
|
||||||
|
if (order.type === 'growth' || order.type === 'sprint') {
|
||||||
|
// 套餐激活
|
||||||
|
const planCfg = pricing.plans[order.type]
|
||||||
|
if (!planCfg) return
|
||||||
|
const expireAt = new Date()
|
||||||
|
expireAt.setDate(expireAt.getDate() + planCfg.durationDays)
|
||||||
|
await this.userModel.findByIdAndUpdate(order.userId, {
|
||||||
|
$set: {
|
||||||
|
plan: order.type,
|
||||||
|
[order.type === 'sprint' ? 'sprintExpireAt' : 'vipExpireAt']: expireAt,
|
||||||
|
...(order.type === 'sprint' ? { sprintRemaining: 10 } : {}),
|
||||||
|
},
|
||||||
|
}).exec()
|
||||||
|
await this.quotaService.setPlanQuota(order.userId, planCfg.gravityPerMonth)
|
||||||
|
this.logger.log(`[vp-callback] 套餐已激活: userId=${order.userId}, plan=${order.type}, gravityPerMonth=${planCfg.gravityPerMonth}`)
|
||||||
|
} else {
|
||||||
|
// 发放引力值(按次购买)
|
||||||
|
const gravityMap: Record<string, number> = {
|
||||||
|
interview: pricing.gravityRates.interviewPerUse,
|
||||||
|
optimize: pricing.gravityRates.optimizePerUse,
|
||||||
|
download: pricing.gravityRates.downloadPerUse,
|
||||||
|
}
|
||||||
|
const g = gravityMap[order.type]
|
||||||
|
const quantity = order.metadata?.quantity || 1
|
||||||
|
if (g) {
|
||||||
|
await this.quotaService.grantGravity(order.userId, g * quantity)
|
||||||
|
this.logger.log(`[vp-callback] 引力值已发放: userId=${order.userId}, gravity=${g * quantity}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleGoodsDeliverNotify(msg: any) {
|
||||||
|
// 道具发货通知——代币模式下通常不需要额外处理
|
||||||
|
this.logger.log(`[vp-callback] 道具发货通知: outTradeNo=${msg.OutTradeNo}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleRefundNotify(msg: any) {
|
||||||
|
const outTradeNo = msg.MchOrderId || msg.MchOrderNo
|
||||||
|
if (!outTradeNo) return
|
||||||
|
const order = await this.orderModel.findOne({ outTradeNo }).exec()
|
||||||
|
if (!order) return
|
||||||
|
|
||||||
|
order.status = 'refunded'
|
||||||
|
order.refundAmount = msg.RefundFee || order.amount
|
||||||
|
order.refundedAt = new Date()
|
||||||
|
await order.save()
|
||||||
|
this.logger.log(`[vp-callback] 订单已退款: ${outTradeNo}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查询本地订单状态(前端轮询) */
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Get('check/:outTradeNo')
|
||||||
|
async checkOrder(@Param('outTradeNo') outTradeNo: string, @CurrentUser('userId') userId: string) {
|
||||||
|
const order = await this.orderModel.findOne({ outTradeNo, userId }).exec()
|
||||||
|
if (!order) throw new HttpException('订单不存在', HttpStatus.NOT_FOUND)
|
||||||
|
return { status: order.status, type: order.type, paidAt: order.paidAt }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Module } from '@nestjs/common'
|
||||||
|
import { MongooseModule } from '@nestjs/mongoose'
|
||||||
|
import { VirtualPaymentController } from './virtual-payment.controller'
|
||||||
|
import { VirtualPaymentService } from './virtual-payment.service'
|
||||||
|
import { User, UserSchema } from '../user/user.schema'
|
||||||
|
import { PaymentOrder, PaymentOrderSchema } from '../payment/payment-order.schema'
|
||||||
|
import { PricingModule } from '../schemas/pricing.module'
|
||||||
|
import { UserModule } from '../user/user.module'
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
MongooseModule.forFeature([
|
||||||
|
{ name: User.name, schema: UserSchema },
|
||||||
|
{ name: PaymentOrder.name, schema: PaymentOrderSchema },
|
||||||
|
]),
|
||||||
|
PricingModule,
|
||||||
|
UserModule,
|
||||||
|
],
|
||||||
|
controllers: [VirtualPaymentController],
|
||||||
|
providers: [VirtualPaymentService],
|
||||||
|
})
|
||||||
|
export class VirtualPaymentModule {}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { Injectable, Logger, InternalServerErrorException } from '@nestjs/common'
|
||||||
|
import * as crypto from 'crypto'
|
||||||
|
import axios from 'axios'
|
||||||
|
|
||||||
|
const WX_APPID = requireEnv('WX_APPID')
|
||||||
|
const WX_SECRET = requireEnv('WX_SECRET')
|
||||||
|
const VP_APPKEY = requireEnv('VP_APPKEY')
|
||||||
|
const VP_APPKEY_SANDBOX = requireEnv('VP_APPKEY_SANDBOX')
|
||||||
|
const VP_OFFER_ID = requireEnv('VP_OFFER_ID')
|
||||||
|
|
||||||
|
function requireEnv(name: string): string {
|
||||||
|
const val = process.env[name]
|
||||||
|
if (!val) throw new InternalServerErrorException(`环境变量 ${name} 未配置`)
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class VirtualPaymentService {
|
||||||
|
private readonly logger = new Logger(VirtualPaymentService.name)
|
||||||
|
|
||||||
|
/** 计算支付签名 pay_sig */
|
||||||
|
computePaySig(uri: string, postBody: string, env: number): string {
|
||||||
|
const appKey = env === 1 ? VP_APPKEY_SANDBOX : VP_APPKEY
|
||||||
|
const data = `${uri}&${postBody}`
|
||||||
|
return crypto.createHmac('sha256', appKey).update(data).digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 通过 wx.login code 换取 session_key 并计算用户态签名 */
|
||||||
|
async exchangeCodeAndSign(code: string, signData: string): Promise<{ openid: string; signature: string }> {
|
||||||
|
const res = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
|
||||||
|
params: { appid: WX_APPID, secret: WX_SECRET, js_code: code, grant_type: 'authorization_code' },
|
||||||
|
timeout: 10000,
|
||||||
|
})
|
||||||
|
if (res.data.errcode) {
|
||||||
|
throw new Error(`code2session 失败: ${res.data.errmsg}`)
|
||||||
|
}
|
||||||
|
const { openid, session_key } = res.data
|
||||||
|
if (!session_key) {
|
||||||
|
throw new Error('未获取到 session_key')
|
||||||
|
}
|
||||||
|
const signature = crypto.createHmac('sha256', session_key).update(signData).digest('hex')
|
||||||
|
return { openid, signature }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 构建 signData JSON 字符串(与 wx.requestVirtualPayment 要求的格式一致) */
|
||||||
|
buildSignData(outTradeNo: string, openid: string, totalFee: number, userIp: string, env: number, mode: string, buyQuantity?: number): string {
|
||||||
|
const base = {
|
||||||
|
offerId: VP_OFFER_ID,
|
||||||
|
env,
|
||||||
|
outTradeNo,
|
||||||
|
attach: outTradeNo,
|
||||||
|
currencyType: 'CNY' as const,
|
||||||
|
platform: 'android' as const,
|
||||||
|
zoneId: '',
|
||||||
|
}
|
||||||
|
if (mode === 'short_series_coin') {
|
||||||
|
// 代币充值
|
||||||
|
return JSON.stringify({
|
||||||
|
...base,
|
||||||
|
buyQuantity: buyQuantity || 1,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// short_series_goods — 道具直购
|
||||||
|
return JSON.stringify({
|
||||||
|
...base,
|
||||||
|
productId: openid,
|
||||||
|
goodsPrice: totalFee,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
getOfferId(): string { return VP_OFFER_ID }
|
||||||
|
|
||||||
|
/** 验证消息推送签名(可选,依赖配置的 Token) */
|
||||||
|
verifyPushSignature(signature: string, timestamp: string, nonce: string, token: string): boolean {
|
||||||
|
const arr = [token, timestamp, nonce].sort()
|
||||||
|
const sha1 = crypto.createHash('sha1').update(arr.join('')).digest('hex')
|
||||||
|
return sha1 === signature
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,26 @@
|
|||||||
import { test, expect } from '@playwright/test'
|
import { test, expect } from '@playwright/test'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import * as path from 'path'
|
||||||
|
import * as jwt from 'jsonwebtoken'
|
||||||
|
|
||||||
const BASE = 'http://localhost:3006/api'
|
const BASE = 'http://localhost:3006/api'
|
||||||
|
|
||||||
|
function getJwtSecret(): string {
|
||||||
|
const envPath = path.resolve(__dirname, '..', '.env')
|
||||||
|
const envContent = fs.readFileSync(envPath, 'utf8')
|
||||||
|
const match = envContent.match(/^JWT_SECRET=(.+)$/m)
|
||||||
|
return match ? match[1].trim() : 'test-jwt-secret-for-e2e-tests'
|
||||||
|
}
|
||||||
|
|
||||||
|
function signToken(payload: object): string {
|
||||||
|
return jwt.sign(payload, getJwtSecret(), { expiresIn: '1h' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const testUserId = '000000000000000000000001'
|
||||||
|
const testAdminId = '000000000000000000000002'
|
||||||
|
const userToken = signToken({ userId: testUserId, phone: '13800138000', role: 'user' })
|
||||||
|
const adminToken = signToken({ userId: testAdminId, phone: '13800138001', role: 'admin' })
|
||||||
|
|
||||||
test.describe('Backend API (Playwright)', () => {
|
test.describe('Backend API (Playwright)', () => {
|
||||||
test('GET /api/user/info returns 401 without token', async ({ request }) => {
|
test('GET /api/user/info returns 401 without token', async ({ request }) => {
|
||||||
const res = await request.get(`${BASE}/user/info`)
|
const res = await request.get(`${BASE}/user/info`)
|
||||||
@@ -12,7 +31,7 @@ test.describe('Backend API (Playwright)', () => {
|
|||||||
const res = await request.post(`${BASE}/user/send-code`, {
|
const res = await request.post(`${BASE}/user/send-code`, {
|
||||||
data: { phone: '13800138000' },
|
data: { phone: '13800138000' },
|
||||||
})
|
})
|
||||||
expect(res.status()).toBe(201)
|
expect(res.status()).toBe(200)
|
||||||
const body = await res.json()
|
const body = await res.json()
|
||||||
expect(body.message).toBe('验证码已发送')
|
expect(body.message).toBe('验证码已发送')
|
||||||
})
|
})
|
||||||
@@ -45,4 +64,47 @@ test.describe('Backend API (Playwright)', () => {
|
|||||||
const res = await request.get(`${BASE}/admin/check`)
|
const res = await request.get(`${BASE}/admin/check`)
|
||||||
expect(res.status()).toBe(401)
|
expect(res.status()).toBe(401)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// --- Feedback API ---
|
||||||
|
|
||||||
|
test('POST /api/feedback returns 401 without token', async ({ request }) => {
|
||||||
|
const res = await request.post(`${BASE}/feedback`, {
|
||||||
|
data: { type: 'suggestion', content: 'test feedback' },
|
||||||
|
})
|
||||||
|
expect(res.status()).toBe(401)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('POST /api/feedback returns 400 with empty content', async ({ request }) => {
|
||||||
|
const res = await request.post(`${BASE}/feedback`, {
|
||||||
|
data: { content: '' },
|
||||||
|
headers: { Authorization: `Bearer ${userToken}` },
|
||||||
|
})
|
||||||
|
expect(res.status()).toBe(400)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('POST /api/feedback returns 201 with valid data', async ({ request }) => {
|
||||||
|
const res = await request.post(`${BASE}/feedback`, {
|
||||||
|
data: { type: 'bug', content: 'Playwright浏览器端测试提交的问题反馈', contact: 'test@test.com' },
|
||||||
|
headers: { Authorization: `Bearer ${userToken}` },
|
||||||
|
})
|
||||||
|
expect(res.status()).toBe(201)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('GET /api/feedback returns 403 for non-admin', async ({ request }) => {
|
||||||
|
const res = await request.get(`${BASE}/feedback`, {
|
||||||
|
headers: { Authorization: `Bearer ${userToken}` },
|
||||||
|
})
|
||||||
|
expect(res.status()).toBe(403)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('GET /api/feedback returns 200 for admin', async ({ request }) => {
|
||||||
|
const res = await request.get(`${BASE}/feedback`, {
|
||||||
|
headers: { Authorization: `Bearer ${adminToken}` },
|
||||||
|
})
|
||||||
|
expect(res.status()).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
expect(body.items).toBeDefined()
|
||||||
|
expect(Array.isArray(body.items)).toBe(true)
|
||||||
|
expect(body.total).toBeGreaterThanOrEqual(0)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+4
-2
@@ -1,6 +1,6 @@
|
|||||||
# 职引 - 部署文档
|
# 职引 - 部署文档
|
||||||
|
|
||||||
> **最后更新**: 2026-06-21
|
> **最后更新**: 2026-07-04 12:51
|
||||||
> **生产环境**: 已部署(服务器已购 + 域名已配)
|
> **生产环境**: 已部署(服务器已购 + 域名已配)
|
||||||
|
|
||||||
## 目录
|
## 目录
|
||||||
@@ -227,7 +227,7 @@ node scripts/upload-mp.js
|
|||||||
```
|
```
|
||||||
|
|
||||||
### 版本号
|
### 版本号
|
||||||
当前线上版本:**1.0.17**(git tag v1.0.16,脚本自动末位自增 → 上传版本 1.0.17)
|
当前线上版本:**1.0.22**(小程序上传版本,git tag v1.0.21 + 脚本末位自增 1)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -255,3 +255,5 @@ node scripts/upload-mp.js
|
|||||||
| 2026-06-09 | 更新生产域名:zhiyinwx.yzrcloud.cn(API :3006)、zhiyin.yzrcloud.cn(H5 静态目录) | 小之 |
|
| 2026-06-09 | 更新生产域名:zhiyinwx.yzrcloud.cn(API :3006)、zhiyin.yzrcloud.cn(H5 静态目录) | 小之 |
|
||||||
| 2026-06-21 | 更新部署版本至 v1.0.16;小程序上传工具使用 git tag 自动获取版本号 | 小之 |
|
| 2026-06-21 | 更新部署版本至 v1.0.16;小程序上传工具使用 git tag 自动获取版本号 | 小之 |
|
||||||
| 2026-06-21 | v4.8 SEO + 分享全面优化:部署新增 robots.txt、sitemap.xml、static/ 目录;版本号自动注入(Vite define);13 页面微信分享全部开启;上传脚本版本号末位自增 1 | AI |
|
| 2026-06-21 | v4.8 SEO + 分享全面优化:部署新增 robots.txt、sitemap.xml、static/ 目录;版本号自动注入(Vite define);13 页面微信分享全部开启;上传脚本版本号末位自增 1 | AI |
|
||||||
|
| 2026-07-04 | v4.10 引力值变动记录系统 + 前端 401/错误处理完善;v1.0.21 发布;H5 + 小程序全量部署 | AI |
|
||||||
|
| 2026-07-04 | ASR 语音识别 AAC→WAV 转换修复 + share.vue 分享记录去重修复;后端 + H5 + 小程序 v1.0.22 部署 | AI |
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 职引 · 完整功能清单 v4.7
|
# 职引 · 完整功能清单 v4.10
|
||||||
|
|
||||||
> **版本**: v4.7
|
> **版本**: v4.10
|
||||||
> **日期**: 2026-06-21
|
> **日期**: 2026-07-04
|
||||||
> **状态**: Phase 1.5 按量购买引力值 + 全量生产部署
|
> **状态**: Phase 1.5 引力值变动记录 + 前端错误处理完善
|
||||||
> **定位**: 应届生/实习生 AI 面试教练
|
> **定位**: 应届生/实习生 AI 面试教练
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -86,6 +86,7 @@
|
|||||||
| 简历管理 | ✅ 完成 | 多份简历 CRUD + AI 分析 |
|
| 简历管理 | ✅ 完成 | 多份简历 CRUD + AI 分析 |
|
||||||
| 面试复盘 | ✅ 完成 | 音频上传 → ASR → AI 评析 → 口语分析 |
|
| 面试复盘 | ✅ 完成 | 音频上传 → ASR → AI 评析 → 口语分析 |
|
||||||
| 会员中心 | ✅ 完成 | 套餐对比 + 支付 |
|
| 会员中心 | ✅ 完成 | 套餐对比 + 支付 |
|
||||||
|
| 引力值明细 | ✅ 完成 | 分页查看引力值变动记录(注册/消耗/购买/补给/迁移) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -162,14 +163,14 @@
|
|||||||
- [x] 面经贡献系统 + 公司题库
|
- [x] 面经贡献系统 + 公司题库
|
||||||
- [x] 每日一题(API 读取)
|
- [x] 每日一题(API 读取)
|
||||||
- [x] 手机/邮箱/密码/微信登录
|
- [x] 手机/邮箱/密码/微信登录
|
||||||
- [x] 会员系统(¥19.9 成长版)
|
- [x] 会员系统(¥19 成长版)
|
||||||
- [x] 微信支付对接(Native + JSAPI)
|
- [x] 微信支付对接(Native + JSAPI)
|
||||||
- [x] 公司真题库(用户贡献驱动)
|
- [x] 公司真题库(用户贡献驱动)
|
||||||
- [x] **面试复盘(音频 ASR + AI 评析 + 口语分析)**
|
- [x] **面试复盘(音频 ASR + AI 评析 + 口语分析)**
|
||||||
|
|
||||||
### P1(待实现)
|
### P1(待实现)
|
||||||
- [ ] 每日一题定时推送
|
- [ ] 每日一题定时推送
|
||||||
- [ ] 冲刺版 ¥49.9/月
|
- [ ] 冲刺版 ¥49/月
|
||||||
- [ ] AI 岗位专属题库
|
- [ ] AI 岗位专属题库
|
||||||
- [ ] 连续打卡激励(7 天解锁高级报告)
|
- [ ] 连续打卡激励(7 天解锁高级报告)
|
||||||
- [ ] 生产环境部署
|
- [ ] 生产环境部署
|
||||||
@@ -193,3 +194,4 @@
|
|||||||
| 2026-06-16 | **v4.2**:新增面试复盘功能(whisper.cpp ASR + AI 评析 + 口语分析) | AI |
|
| 2026-06-16 | **v4.2**:新增面试复盘功能(whisper.cpp ASR + AI 评析 + 口语分析) | AI |
|
||||||
| 2026-06-17 | **v4.3**:新增 AI 择业顾问功能(专业分析 + 岗位匹配 + 多轮对话) | AI |
|
| 2026-06-17 | **v4.3**:新增 AI 择业顾问功能(专业分析 + 岗位匹配 + 多轮对话) | AI |
|
||||||
| 2026-06-21 | **v4.7**:按量购买引力值重构(¥5/份取代月订阅);微信小程序剪贴板购买链路;客服按钮;管理后台全面完善;生产环境全量部署上线 | AI |
|
| 2026-06-21 | **v4.7**:按量购买引力值重构(¥5/份取代月订阅);微信小程序剪贴板购买链路;客服按钮;管理后台全面完善;生产环境全量部署上线 | AI |
|
||||||
|
| 2026-07-04 | **v4.10**:引力值变动记录系统(GravityTransaction schema + 全埋点 + 用户端分页明细弹窗);前端 401/错误处理完善;面试创建 201 兼容;AI 错误友好提示 | AI |
|
||||||
|
|||||||
@@ -58,7 +58,7 @@
|
|||||||
},
|
},
|
||||||
"plans": {
|
"plans": {
|
||||||
"growth": {
|
"growth": {
|
||||||
"price": 1990,
|
"price": 1900,
|
||||||
"durationDays": 30,
|
"durationDays": 30,
|
||||||
"credits": {
|
"credits": {
|
||||||
"interview": 999,
|
"interview": 999,
|
||||||
@@ -76,7 +76,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"sprint": {
|
"sprint": {
|
||||||
"price": 4990,
|
"price": 4900,
|
||||||
"durationDays": 30,
|
"durationDays": 30,
|
||||||
"credits": {
|
"credits": {
|
||||||
"interview": 999,
|
"interview": 999,
|
||||||
@@ -267,7 +267,7 @@ Puppeteer PDF 生成 (`resume-pdf.service.ts`):
|
|||||||
│ 首次面试免费 [✓] │
|
│ 首次面试免费 [✓] │
|
||||||
│ │
|
│ │
|
||||||
│ ─── 成长版 ─── │
|
│ ─── 成长版 ─── │
|
||||||
│ 价格 ¥ [ 19.9 ] /月 │
|
│ 价格 ¥ [ 19 ] /月 │
|
||||||
│ 面试额度 [ 999 ] 次 │
|
│ 面试额度 [ 999 ] 次 │
|
||||||
│ 优化额度 [ 20 ] 次 │
|
│ 优化额度 [ 20 ] 次 │
|
||||||
│ 下载额度 [ 10 ] 次 │
|
│ 下载额度 [ 10 ] 次 │
|
||||||
|
|||||||
@@ -65,14 +65,14 @@
|
|||||||
| 版本 | 价格 | 核心权益 | 定位 |
|
| 版本 | 价格 | 核心权益 | 定位 |
|
||||||
|------|------|------|------|
|
|------|------|------|------|
|
||||||
| 免费版 | ¥0 | 日 2 次基础面试(通用题库,5 轮/次) | 引流 |
|
| 免费版 | ¥0 | 日 2 次基础面试(通用题库,5 轮/次) | 引流 |
|
||||||
| **成长版** | **¥19.9/月** | 无限面试 + 高级报告 + 进步轨迹 + 真题库 | **主力** |
|
| **成长版** | **¥19/月** | 无限面试 + 高级报告 + 进步轨迹 + 真题库 | **主力** |
|
||||||
|
|
||||||
> 冲刺版 ¥49.9/月(含真人导师点评 + 简历精修)待实现
|
> 冲刺版 ¥49/月(含真人导师点评 + 简历精修)待实现
|
||||||
|
|
||||||
### 3.2 收入来源
|
### 3.2 收入来源
|
||||||
|
|
||||||
```
|
```
|
||||||
C 端订阅收入(基本盘:¥19.9 × 付费用户数)
|
C 端订阅收入(基本盘:¥19 × 付费用户数)
|
||||||
↓
|
↓
|
||||||
├── B 端合作(高校就业办/求职机构)
|
├── B 端合作(高校就业办/求职机构)
|
||||||
├── 内容变现(面经课程)
|
├── 内容变现(面经课程)
|
||||||
@@ -83,9 +83,9 @@ C 端订阅收入(基本盘:¥19.9 × 付费用户数)
|
|||||||
|
|
||||||
| 阶段 | C 端 | B 端 | 月收入 |
|
| 阶段 | C 端 | B 端 | 月收入 |
|
||||||
|------|------|------|--------|
|
|------|------|------|--------|
|
||||||
| MVP 上线(6-8月) | 200 付费 × ¥19.9 | 0 | ¥3,980 |
|
| MVP 上线(6-8月) | 200 付费 × ¥19 | 0 | ¥3,800 |
|
||||||
| 秋招旺季(9-11月) | 1000 付费 × ¥19.9 | 2 高校 ¥5000 | ¥29,900 |
|
| 秋招旺季(9-11月) | 1000 付费 × ¥19 | 2 高校 ¥5000 | ¥24,000 |
|
||||||
| 稳定运营(次年) | 2000 付费 × ¥19.9 | 5 机构 + 企业 | ¥60,000+ |
|
| 稳定运营(次年) | 2000 付费 × ¥19 | 5 机构 + 企业 | ¥48,000+ |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -103,14 +103,14 @@ C 端订阅收入(基本盘:¥19.9 × 付费用户数)
|
|||||||
| 面经贡献系统 + 公司题库 | ✅ 完成 |
|
| 面经贡献系统 + 公司题库 | ✅ 完成 |
|
||||||
| 每日一题(API) | ✅ 完成 |
|
| 每日一题(API) | ✅ 完成 |
|
||||||
| 简历诊断 + 优化 | ✅ 完成 |
|
| 简历诊断 + 优化 | ✅ 完成 |
|
||||||
| 会员系统(成长版 ¥19.9/月) | ✅ 完成 |
|
| 会员系统(成长版 ¥19/月) | ✅ 完成 |
|
||||||
| 微信支付(Native + JSAPI) | ✅ 完成 |
|
| 微信支付(Native + JSAPI) | ✅ 完成 |
|
||||||
|
|
||||||
### 待实现
|
### 待实现
|
||||||
| 功能 | 计划 |
|
| 功能 | 计划 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| 每日一题定时推送(微信订阅消息) | Phase 1 |
|
| 每日一题定时推送(微信订阅消息) | Phase 1 |
|
||||||
| 冲刺版 ¥49.9/月 | Phase 1.5 |
|
| 冲刺版 ¥49/月 | Phase 1.5 |
|
||||||
| 微信登录真实 appid 联调 | Phase 1 |
|
| 微信登录真实 appid 联调 | Phase 1 |
|
||||||
| 生产环境部署 | Phase 1 |
|
| 生产环境部署 | Phase 1 |
|
||||||
| AI 岗位专属题库 | Phase 2 |
|
| AI 岗位专属题库 | Phase 2 |
|
||||||
|
|||||||
+11
-6
@@ -1,8 +1,8 @@
|
|||||||
# 职引项目 · 状态报告 v4.8
|
# 职引项目 · 状态报告 v4.10
|
||||||
|
|
||||||
> **项目版本**: v4.8
|
> **项目版本**: v4.10
|
||||||
> **更新时间**: 2026-06-21
|
> **更新时间**: 2026-07-04
|
||||||
> **项目状态**: ✅ SEO 优化 + 微信分享全面开启 + 全量部署
|
> **项目状态**: ✅ 引力值变动记录系统 + 前端 401/错误处理完善 + v1.0.21 发布
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
| 定价 | 免费版 / 按量购买引力值(¥5/份) |
|
| 定价 | 免费版 / 按量购买引力值(¥5/份) |
|
||||||
| AI 模型 | DeepSeek V4-Flash(主) + Step-3.5-Flash(备) |
|
| AI 模型 | DeepSeek V4-Flash(主) + Step-3.5-Flash(备) |
|
||||||
| ASR | whisper.cpp(本地部署,tiny/base 模型,无需 API Key) |
|
| ASR | whisper.cpp(本地部署,tiny/base 模型,无需 API Key) |
|
||||||
| 后端模块 | user, interview, resume, member, payment, positions, ai, analyze, upload, admin, email, progress, contribution, daily-question, schedule, interview-review, career-advice |
|
| 后端模块 | user, interview, resume, member, payment, positions, ai, analyze, upload, admin, email, progress, contribution, daily-question, schedule, interview-review, career-advice, gravity-transaction |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -29,6 +29,7 @@
|
|||||||
| AI 面试模拟 | **95%** | 多轮对话 + 评分 + 报告 + 进度追踪 |
|
| AI 面试模拟 | **95%** | 多轮对话 + 评分 + 报告 + 进度追踪 |
|
||||||
| 简历诊断/优化 | **95%** | 文件上传 + AI 分析 + 下载 |
|
| 简历诊断/优化 | **95%** | 文件上传 + AI 分析 + 下载 |
|
||||||
| 支付系统(微信) | **95%** | API v3 完整对接,含真实证书,H5 扫码支付可用 |
|
| 支付系统(微信) | **95%** | API v3 完整对接,含真实证书,H5 扫码支付可用 |
|
||||||
|
| 引力值变动记录 | **100%** | 全量日志(注册/消耗/购买/补给/迁移)+ 前端分页查看 |
|
||||||
| 会员系统 | **100%** | 改为按量购买引力值体系(¥5/份),免费版注册送 5 引力值 |
|
| 会员系统 | **100%** | 改为按量购买引力值体系(¥5/份),免费版注册送 5 引力值 |
|
||||||
| 护城河 P0-P5 | **100%** | AI 结构化 / 行业基准 / VIP 过期 / 分享卡片 / 打卡积分 / 岗位匹配 |
|
| 护城河 P0-P5 | **100%** | AI 结构化 / 行业基准 / VIP 过期 / 分享卡片 / 打卡积分 / 岗位匹配 |
|
||||||
| 面试复盘 | **100%** | 音频上传 → whisper.cpp ASR → AI 评析 → 口语分析 |
|
| 面试复盘 | **100%** | 音频上传 → whisper.cpp ASR → AI 评析 → 口语分析 |
|
||||||
@@ -182,6 +183,7 @@
|
|||||||
| `interview-review` | controller + service + schema + asr service | ✅ | 面试复盘:音频 ASR + AI 评析 + 口语分析 |
|
| `interview-review` | controller + service + schema + asr service | ✅ | 面试复盘:音频 ASR + AI 评析 + 口语分析 |
|
||||||
| `career-advice` | controller + service + module | ✅ | AI 择业顾问:专业分析 + 岗位匹配 + 多轮对话 |
|
| `career-advice` | controller + service + module | ✅ | AI 择业顾问:专业分析 + 岗位匹配 + 多轮对话 |
|
||||||
| `admin` | controller + module | ✅ | 管理后台 |
|
| `admin` | controller + module | ✅ | 管理后台 |
|
||||||
|
| `gravity-transaction` | schema (shared) | ✅ | 引力值变动全量日志:注册/面试消耗/购买/月度补给/迁移等 |
|
||||||
| `email` | module + service | ✅ | 邮件发送 |
|
| `email` | module + service | ✅ | 邮件发送 |
|
||||||
| `upload` | controller + module | ✅ | 文件上传 |
|
| `upload` | controller + module | ✅ | 文件上传 |
|
||||||
|
|
||||||
@@ -196,7 +198,7 @@
|
|||||||
| 面试模拟 | interview/interview | ✅ 多轮对话 + 计时 |
|
| 面试模拟 | interview/interview | ✅ 多轮对话 + 计时 |
|
||||||
| 面试报告 | report/report | ✅ 评分/分析/全文回放/分享卡片 |
|
| 面试报告 | report/report | ✅ 评分/分析/全文回放/分享卡片 |
|
||||||
| 历史记录 | history/history | ✅ 筛选/统计 |
|
| 历史记录 | history/history | ✅ 筛选/统计 |
|
||||||
| 个人中心 | user/user | ✅ 引力值卡片 + 信息/统计/管理员入口 + 面试复盘入口 + 择业顾问入口 + 客服按钮 |
|
| 个人中心 | user/user | ✅ 引力值卡片(含明细弹窗)+ 信息/统计/管理员入口 + 面试复盘入口 + 择业顾问入口 + 客服按钮 |
|
||||||
| 会员中心 | member/member | ✅ 引力值按量购买(H5 扫码支付/小程序剪贴板链路) |
|
| 会员中心 | member/member | ✅ 引力值按量购买(H5 扫码支付/小程序剪贴板链路) |
|
||||||
| 进步轨迹 | progress/progress | ✅ 雷达图 + 打卡日历 |
|
| 进步轨迹 | progress/progress | ✅ 雷达图 + 打卡日历 |
|
||||||
| 面经贡献 | contribute/contribute | ✅ 表单提交 |
|
| 面经贡献 | contribute/contribute | ✅ 表单提交 |
|
||||||
@@ -224,6 +226,9 @@
|
|||||||
|
|
||||||
| 日期 | 版本 | 变更内容 | 操作者 |
|
| 日期 | 版本 | 变更内容 | 操作者 |
|
||||||
|------|------|----------|--------|
|
|------|------|----------|--------|
|
||||||
|
| 2026-07-04 | **v4.11** | **ASR 语音识别修复**(TTS controller AAC→WAV 转换,解决小程序录音格式不兼容 whisper);**分享记录去重**(share.vue loadData 有缓存时不再创建新分享);**引力值明细**后端部署;**用户端 401/错误处理**完善 | AI |
|
||||||
|
| 2026-07-04 | **v4.10** | **引力值变动记录系统**:新建 GravityTransaction schema + 全量日志埋点(注册/面试消耗/购买/月度补给/迁移/套餐设置等);新增 `GET /user/gravity-transactions` 接口;用户端「引力值明细」弹窗(分页);前端 401/错误处理完善(checkAuth 全局检测);面试创建 201 状态码兼容 fix;AI 错误友好提示 | AI |
|
||||||
|
| 2026-06-22 | **v4.9** | **Mongoose 8 兼容修复**(pre-save hook 回调→async);v1.0.17 tag 发布;测试账号 test@yzrcloud.cn 重建 | AI |
|
||||||
| 2026-06-21 | **v4.8** | **SEO 全量优化**(canonical URL、robots.txt、sitemap.xml、结构化数据);**微信分享全面开启**(13 个页面 onShareAppMessage + onShareTimeline);**版本号自动注入**(Vite define __APP_VERSION__);**导航栏/Tab标题关键词优化**;manifest 描述更新;页面描述统一增强 | AI |
|
| 2026-06-21 | **v4.8** | **SEO 全量优化**(canonical URL、robots.txt、sitemap.xml、结构化数据);**微信分享全面开启**(13 个页面 onShareAppMessage + onShareTimeline);**版本号自动注入**(Vite define __APP_VERSION__);**导航栏/Tab标题关键词优化**;manifest 描述更新;页面描述统一增强 | AI |
|
||||||
| 2026-06-21 | v4.7 | 按量购买引力值体系重构(¥5/份取代月订阅);member.vue 完全重写;微信小程序剪贴板购买链路;客服按钮;管理后台字段全面完善;代码清理;测试数据清理;后端/H5/小程序全量部署上线 | AI |
|
| 2026-06-21 | v4.7 | 按量购买引力值体系重构(¥5/份取代月订阅);member.vue 完全重写;微信小程序剪贴板购买链路;客服按钮;管理后台字段全面完善;代码清理;测试数据清理;后端/H5/小程序全量部署上线 | AI |
|
||||||
| 2026-06-19 | v4.6 | 引力值体系统一:VIP 取消无限面试改为月度引力值消耗;管理后台全面完善(搜索/筛选/分页/CRUD/分析tab/岗位描述字段) | AI |
|
| 2026-06-19 | v4.6 | 引力值体系统一:VIP 取消无限面试改为月度引力值消耗;管理后台全面完善(搜索/筛选/分页/CRUD/分析tab/岗位描述字段) | AI |
|
||||||
|
|||||||
+2
-2
@@ -28,7 +28,7 @@ Phase 3: 商业化 + B 端(D90+)→ 秋招爆发
|
|||||||
## 二、Phase 0: 战略升级(✅ 已完成)
|
## 二、Phase 0: 战略升级(✅ 已完成)
|
||||||
|
|
||||||
**已完成**:
|
**已完成**:
|
||||||
- [x] 定价重构:免费 + ¥19.9/月 两段式
|
- [x] 定价重构:免费 + ¥19/月 两段式
|
||||||
- [x] 三层壁垒设计(数据飞轮 + 留存入围 + 合规信任)
|
- [x] 三层壁垒设计(数据飞轮 + 留存入围 + 合规信任)
|
||||||
- [x] 收入来源多元化策略
|
- [x] 收入来源多元化策略
|
||||||
- [x] 文档体系全面更新
|
- [x] 文档体系全面更新
|
||||||
@@ -54,7 +54,7 @@ Phase 3: 商业化 + B 端(D90+)→ 秋招爆发
|
|||||||
### 3.3 会员系统重构
|
### 3.3 会员系统重构
|
||||||
| 功能 | 描述 | 状态 |
|
| 功能 | 描述 | 状态 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| 定价更新 | ¥19.9/月 成长版 | ✅ 完成 |
|
| 定价更新 | ¥19/月 成长版 | ✅ 完成 |
|
||||||
| 会员权益对比 | 三版对比展示 | ✅ 完成 |
|
| 会员权益对比 | 三版对比展示 | ✅ 完成 |
|
||||||
| 微信支付对接 | Native + JSAPI 支付 | ✅ 完成 |
|
| 微信支付对接 | Native + JSAPI 支付 | ✅ 完成 |
|
||||||
|
|
||||||
|
|||||||
+23
-2
@@ -1,15 +1,24 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onLaunch } from '@dcloudio/uni-app'
|
import { onLaunch, onShow } from '@dcloudio/uni-app'
|
||||||
|
|
||||||
onLaunch(() => {
|
onLaunch((options) => {
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
initPrivacy()
|
initPrivacy()
|
||||||
|
handleLaunchParams(options?.query)
|
||||||
// #endif
|
// #endif
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
handleH5UrlParams()
|
handleH5UrlParams()
|
||||||
// #endif
|
// #endif
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
onShow((options) => {
|
||||||
|
if (options?.query) {
|
||||||
|
handleLaunchParams(options.query)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// #endif
|
||||||
|
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
function handleH5UrlParams() {
|
function handleH5UrlParams() {
|
||||||
const params = new URLSearchParams(window.location.search)
|
const params = new URLSearchParams(window.location.search)
|
||||||
@@ -28,6 +37,18 @@ function handleH5UrlParams() {
|
|||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
|
function handleLaunchParams(query?: Record<string, string>) {
|
||||||
|
if (!query) return
|
||||||
|
const token = query.token
|
||||||
|
if (token) {
|
||||||
|
uni.setStorageSync('token', token)
|
||||||
|
}
|
||||||
|
const shareCode = query.share || query.shareCode
|
||||||
|
if (shareCode) {
|
||||||
|
uni.setStorageSync('shareCode', shareCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function initPrivacy() {
|
function initPrivacy() {
|
||||||
if (wx.onNeedPrivacyAuthorization) {
|
if (wx.onNeedPrivacyAuthorization) {
|
||||||
wx.onNeedPrivacyAuthorization((resolve) => {
|
wx.onNeedPrivacyAuthorization((resolve) => {
|
||||||
|
|||||||
@@ -81,31 +81,41 @@ export function useGravityPurchase(onPaymentSuccess?: () => void) {
|
|||||||
|
|
||||||
if (isMp.value) {
|
if (isMp.value) {
|
||||||
try {
|
try {
|
||||||
let res = await uni.request({
|
const loginRes = await new Promise<{ code: string }>((resolve, reject) => {
|
||||||
url: api('/payment/jsapi-product'), method: 'POST',
|
uni.login({ provider: 'weixin', success: r => resolve(r), fail: reject })
|
||||||
data: { type, quantity },
|
})
|
||||||
|
if (!loginRes.code) {
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = '微信登录失败,请重试'
|
||||||
|
uni.showToast({ title: '微信登录失败', icon: 'none' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api('/virtual-payment/create'), method: 'POST',
|
||||||
|
data: { type, quantity, wxCode: loginRes.code },
|
||||||
header: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
|
header: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||||
timeout: 30000,
|
timeout: 30000,
|
||||||
})
|
})
|
||||||
payLoading.value = false
|
payLoading.value = false
|
||||||
|
|
||||||
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.payParams) {
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.paySig) {
|
||||||
const pp = res.data.payParams as any
|
const vp = res.data as any
|
||||||
currentOutTradeNo.value = res.data.outTradeNo || ''
|
currentOutTradeNo.value = vp.outTradeNo
|
||||||
uni.requestPayment({
|
|
||||||
provider: 'wxpay',
|
;(wx as any).requestVirtualPayment({
|
||||||
timeStamp: pp.timeStamp,
|
env: vp.env,
|
||||||
nonceStr: pp.nonceStr,
|
offerId: vp.offerId,
|
||||||
package: pp.package,
|
signData: vp.signData,
|
||||||
signType: pp.signType || 'RSA',
|
paySig: vp.paySig,
|
||||||
paySign: pp.paySign,
|
signature: vp.signature,
|
||||||
success: () => {
|
success: () => {
|
||||||
const no = currentOutTradeNo.value || res.data.outTradeNo
|
const no = currentOutTradeNo.value || vp.outTradeNo
|
||||||
pollPayResult(no)
|
pollPayResult(no)
|
||||||
},
|
},
|
||||||
fail: () => {
|
fail: (err: any) => {
|
||||||
payError.value = '支付未完成'
|
payError.value = '支付未完成'
|
||||||
uni.showToast({ title: '支付未完成', icon: 'none' })
|
uni.showToast({ title: err?.errMsg || '支付未完成', icon: 'none' })
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
} else if (!res.statusCode || res.statusCode === 0) {
|
} else if (!res.statusCode || res.statusCode === 0) {
|
||||||
@@ -116,9 +126,9 @@ export function useGravityPurchase(onPaymentSuccess?: () => void) {
|
|||||||
payError.value = errMsg
|
payError.value = errMsg
|
||||||
uni.showToast({ title: errMsg, icon: 'none' })
|
uni.showToast({ title: errMsg, icon: 'none' })
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
payLoading.value = false
|
payLoading.value = false
|
||||||
payError.value = '网络错误,请重试'
|
payError.value = e?.errMsg || '网络错误,请重试'
|
||||||
uni.showToast({ title: '网络错误', icon: 'none' })
|
uni.showToast({ title: '网络错误', icon: 'none' })
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -122,6 +122,10 @@ export const API_ENDPOINTS = {
|
|||||||
CHAT: '/career-advice/chat',
|
CHAT: '/career-advice/chat',
|
||||||
POSITIONS: '/career-advice/positions',
|
POSITIONS: '/career-advice/positions',
|
||||||
},
|
},
|
||||||
|
VIRTUAL_PAYMENT: {
|
||||||
|
CREATE: '/virtual-payment/create',
|
||||||
|
CHECK: (outTradeNo: string) => `/virtual-payment/check/${outTradeNo}`,
|
||||||
|
},
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
const PROD_API_HOST = import.meta.env.VITE_PROD_API_HOST || 'https://zhiyinwx.yzrcloud.cn'
|
const PROD_API_HOST = import.meta.env.VITE_PROD_API_HOST || 'https://zhiyinwx.yzrcloud.cn'
|
||||||
|
|||||||
@@ -16,6 +16,17 @@
|
|||||||
"urlCheck": false,
|
"urlCheck": false,
|
||||||
"__usePrivacyCheck__": true
|
"__usePrivacyCheck__": true
|
||||||
},
|
},
|
||||||
"usingComponents": true
|
"usingComponents": true,
|
||||||
|
"plugins": {
|
||||||
|
"WechatSI": {
|
||||||
|
"version": "0.3.6",
|
||||||
|
"provider": "wx069ba97219f66d99"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"permission": {
|
||||||
|
"scope.record": {
|
||||||
|
"desc": "用于语音输入回答面试问题"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,8 @@
|
|||||||
{ "path": "pages/privacy/privacy", "style": { "navigationBarTitleText": "隐私政策" } },
|
{ "path": "pages/privacy/privacy", "style": { "navigationBarTitleText": "隐私政策" } },
|
||||||
{ "path": "pages/share/share", "style": { "navigationBarTitleText": "我的分享" } },
|
{ "path": "pages/share/share", "style": { "navigationBarTitleText": "我的分享" } },
|
||||||
{ "path": "pages/review/review", "style": { "navigationBarTitleText": "面试复盘分析" } },
|
{ "path": "pages/review/review", "style": { "navigationBarTitleText": "面试复盘分析" } },
|
||||||
{ "path": "pages/career/career", "style": { "navigationBarTitleText": "AI择业顾问" } }
|
{ "path": "pages/career/career", "style": { "navigationBarTitleText": "AI择业顾问" } },
|
||||||
|
{ "path": "pages/feedback/feedback", "style": { "navigationBarTitleText": "意见反馈" } }
|
||||||
],
|
],
|
||||||
"tabBar": {
|
"tabBar": {
|
||||||
"color": "#999999",
|
"color": "#999999",
|
||||||
|
|||||||
@@ -73,7 +73,7 @@
|
|||||||
<!-- 用户 -->
|
<!-- 用户 -->
|
||||||
<view v-if="tab === 'users'" class="section">
|
<view v-if="tab === 'users'" class="section">
|
||||||
<view class="search-bar">
|
<view class="search-bar">
|
||||||
<input v-model="userKeyword" placeholder="搜索手机号/昵称" class="search-input" @confirm="loadUsers" />
|
<input v-model="userKeyword" placeholder="搜索手机号/邮箱/昵称/ID" class="search-input" @confirm="loadUsers" />
|
||||||
<button class="search-btn" @click="loadUsers">搜索</button>
|
<button class="search-btn" @click="loadUsers">搜索</button>
|
||||||
</view>
|
</view>
|
||||||
<view class="user-list" v-if="!usersLoading">
|
<view class="user-list" v-if="!usersLoading">
|
||||||
@@ -87,6 +87,9 @@
|
|||||||
<text class="meta-tag email" v-if="u.email">{{ u.email }}</text>
|
<text class="meta-tag email" v-if="u.email">{{ u.email }}</text>
|
||||||
<text class="meta-tag" v-if="u.wxOpenid">openid:{{ u.wxOpenid.slice(0,12) }}..</text>
|
<text class="meta-tag" v-if="u.wxOpenid">openid:{{ u.wxOpenid.slice(0,12) }}..</text>
|
||||||
</view>
|
</view>
|
||||||
|
<view class="user-meta-row">
|
||||||
|
<text class="meta-tag id-tag" @click="copyId(u._id)">ID: {{ u._id }}</text>
|
||||||
|
</view>
|
||||||
<view class="user-meta-row">
|
<view class="user-meta-row">
|
||||||
<text class="meta-tag">引力:{{ u.gravity ?? 0 }}</text>
|
<text class="meta-tag">引力:{{ u.gravity ?? 0 }}</text>
|
||||||
<text class="meta-tag">面试:{{ u.interviewCount ?? 0 }}次</text>
|
<text class="meta-tag">面试:{{ u.interviewCount ?? 0 }}次</text>
|
||||||
@@ -94,10 +97,15 @@
|
|||||||
<text class="meta-tag share" v-if="u.shareCredits > 0">分享:{{ u.shareCredits }}</text>
|
<text class="meta-tag share" v-if="u.shareCredits > 0">分享:{{ u.shareCredits }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="user-meta-row time-row">
|
<view class="user-meta-row time-row">
|
||||||
<text class="time-label">注册:{{ u.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label">注册:{{ toBeijing(u.createdAt) }}</text>
|
||||||
<text class="time-label" v-if="u.vipExpireAt">到期:{{ u.vipExpireAt?.slice(0,10) }}</text>
|
<text class="time-label" v-if="u.vipExpireAt">到期:{{ u.vipExpireAt?.slice(0,10) }}</text>
|
||||||
<text class="time-label" v-if="u.sprintExpireAt">冲刺到期:{{ u.sprintExpireAt?.slice(0,10) }}</text>
|
<text class="time-label" v-if="u.sprintExpireAt">冲刺到期:{{ u.sprintExpireAt?.slice(0,10) }}</text>
|
||||||
</view>
|
</view>
|
||||||
|
<view class="user-meta-row time-row" v-if="u.lastLoginAt">
|
||||||
|
<text class="time-label">最后登录:{{ toBeijing(u.lastLoginAt) }}</text>
|
||||||
|
<text class="meta-tag" v-if="u.lastLoginIp">IP:{{ u.lastLoginIp }}</text>
|
||||||
|
<text class="meta-tag" v-if="u.lastLoginLocation">{{ u.lastLoginLocation }}</text>
|
||||||
|
</view>
|
||||||
<view class="user-actions">
|
<view class="user-actions">
|
||||||
<text class="user-action-btn" v-if="u.plan === 'free'" @click="setVip(u._id)">设为会员</text>
|
<text class="user-action-btn" v-if="u.plan === 'free'" @click="setVip(u._id)">设为会员</text>
|
||||||
<text class="user-action-btn credit" @click="openCreditModal(u)">调整额度</text>
|
<text class="user-action-btn credit" @click="openCreditModal(u)">调整额度</text>
|
||||||
@@ -130,8 +138,8 @@
|
|||||||
<text class="iv-tag filler" v-if="iv.fillerScore != null && iv.fillerScore > 0">语气 {{ iv.fillerScore }}/{{ iv.fillerDensity ?? '-' }}</text>
|
<text class="iv-tag filler" v-if="iv.fillerScore != null && iv.fillerScore > 0">语气 {{ iv.fillerScore }}/{{ iv.fillerDensity ?? '-' }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="iv-meta">
|
<view class="iv-meta">
|
||||||
<text class="time-label">开始:{{ iv.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label">开始:{{ toBeijing(iv.createdAt) }}</text>
|
||||||
<text class="time-label" v-if="iv.updatedAt && iv.updatedAt !== iv.createdAt">更新:{{ iv.updatedAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label" v-if="iv.updatedAt && iv.updatedAt !== iv.createdAt">更新:{{ toBeijing(iv.updatedAt) }}</text>
|
||||||
</view>
|
</view>
|
||||||
<text class="iv-summary" v-if="iv.summary">{{ iv.summary.slice(0,60) }}{{ iv.summary.length > 60 ? '...' : '' }}</text>
|
<text class="iv-summary" v-if="iv.summary">{{ iv.summary.slice(0,60) }}{{ iv.summary.length > 60 ? '...' : '' }}</text>
|
||||||
</view>
|
</view>
|
||||||
@@ -160,8 +168,8 @@
|
|||||||
<text class="resume-tag paid" v-if="r.paidDownload">付费下载</text>
|
<text class="resume-tag paid" v-if="r.paidDownload">付费下载</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="resume-meta time-row">
|
<view class="resume-meta time-row">
|
||||||
<text class="time-label">创建:{{ r.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label">创建:{{ toBeijing(r.createdAt) }}</text>
|
||||||
<text class="time-label" v-if="r.updatedAt && r.updatedAt !== r.createdAt">更新:{{ r.updatedAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label" v-if="r.updatedAt && r.updatedAt !== r.createdAt">更新:{{ toBeijing(r.updatedAt) }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="resume-actions">
|
<view class="resume-actions">
|
||||||
<text class="admin-action-btn del" @click="deleteResume(r._id, r.title)">删除</text>
|
<text class="admin-action-btn del" @click="deleteResume(r._id, r.title)">删除</text>
|
||||||
@@ -200,14 +208,14 @@
|
|||||||
<text class="meta-tag">渠道:{{ o.channel || '--' }}</text>
|
<text class="meta-tag">渠道:{{ o.channel || '--' }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="order-meta-row time-row">
|
<view class="order-meta-row time-row">
|
||||||
<text class="time-label">创建:{{ o.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label">创建:{{ toBeijing(o.createdAt) }}</text>
|
||||||
<text class="time-label" v-if="o.paidAt">支付:{{ o.paidAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label" v-if="o.paidAt">支付:{{ toBeijing(o.paidAt) }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="order-meta-row" v-if="o.wxTransactionId">
|
<view class="order-meta-row" v-if="o.wxTransactionId">
|
||||||
<text class="time-label">微信单号:{{ o.wxTransactionId }}</text>
|
<text class="time-label">微信单号:{{ o.wxTransactionId }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="order-meta-row" v-if="o.status === 'refunded'">
|
<view class="order-meta-row" v-if="o.status === 'refunded'">
|
||||||
<text class="time-label refund-label">退款:¥{{ (o.refundAmount/100).toFixed(1) }} {{ o.refundedAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label refund-label">退款:¥{{ (o.refundAmount/100).toFixed(1) }} {{ toBeijing(o.refundedAt) }}</text>
|
||||||
<text class="time-label" v-if="o.refundReason">原因:{{ o.refundReason }}</text>
|
<text class="time-label" v-if="o.refundReason">原因:{{ o.refundReason }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="order-actions-bar">
|
<view class="order-actions-bar">
|
||||||
@@ -297,6 +305,8 @@
|
|||||||
<text>每月引力值</text>
|
<text>每月引力值</text>
|
||||||
<input class="cfg-input" type="digit" v-model.number="pricing.plans.sprint.gravityPerMonth" />
|
<input class="cfg-input" type="digit" v-model.number="pricing.plans.sprint.gravityPerMonth" />
|
||||||
</view>
|
</view>
|
||||||
|
<view class="cfg-row">
|
||||||
|
<text>面试额度/月</text>
|
||||||
<input class="cfg-input" type="digit" v-model.number="pricing.plans.sprint.credits.interview" />
|
<input class="cfg-input" type="digit" v-model.number="pricing.plans.sprint.credits.interview" />
|
||||||
</view>
|
</view>
|
||||||
<view class="cfg-row">
|
<view class="cfg-row">
|
||||||
@@ -346,7 +356,7 @@
|
|||||||
<text class="share-credited">有效 {{ r.creditedCount }}</text>
|
<text class="share-credited">有效 {{ r.creditedCount }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="share-meta-row time-row">
|
<view class="share-meta-row time-row">
|
||||||
<text class="time-label">创建:{{ r.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label">创建:{{ toBeijing(r.createdAt) }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -365,8 +375,8 @@
|
|||||||
<text class="meta-tag" :class="v.credited ? 'badge-done' : 'badge-pend'">{{ v.credited ? '已积分' : '未积分' }}</text>
|
<text class="meta-tag" :class="v.credited ? 'badge-done' : 'badge-pend'">{{ v.credited ? '已积分' : '未积分' }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="share-meta-row time-row">
|
<view class="share-meta-row time-row">
|
||||||
<text class="time-label">访问:{{ v.createdAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label">访问:{{ toBeijing(v.createdAt) }}</text>
|
||||||
<text class="time-label" v-if="v.creditedAt">积分:{{ v.creditedAt?.slice(0,16).replace('T',' ') }}</text>
|
<text class="time-label" v-if="v.creditedAt">积分:{{ toBeijing(v.creditedAt) }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -488,24 +498,55 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="section-label">当前管理员</view>
|
<view class="section-label">当前管理员</view>
|
||||||
<view class="user-list">
|
<view class="user-list">
|
||||||
<view class="admin-row" v-for="a in adminList" :key="a._id">
|
<view class="user-row" v-for="a in adminList" :key="a._id">
|
||||||
<text class="admin-phone">{{ a.phone || '--' }}</text>
|
<view class="user-main">
|
||||||
<text class="admin-name">{{ a.nickname || '--' }}</text>
|
<text class="user-phone">{{ a.phone || '--' }}</text>
|
||||||
<text class="admin-email" v-if="a.email">{{ a.email }}</text>
|
<text class="user-name">{{ a.nickname || '--' }}</text>
|
||||||
<text class="admin-badge" v-if="a.isSystemAdmin">系统</text>
|
<text class="user-badge-role">管理</text>
|
||||||
<text class="time-label" style="margin-left:auto">设置:{{ a.createdAt?.slice(0,10) }}</text>
|
<text class="admin-badge" v-if="a.isSystemAdmin">系统</text>
|
||||||
|
</view>
|
||||||
|
<view class="user-meta-row">
|
||||||
|
<text class="meta-tag email" v-if="a.email">{{ a.email }}</text>
|
||||||
|
<text class="meta-tag" v-if="a.wxOpenid">openid:{{ a.wxOpenid.slice(0,12) }}..</text>
|
||||||
|
</view>
|
||||||
|
<view class="user-meta-row">
|
||||||
|
<text class="meta-tag id-tag" @click="copyId(a._id)">ID: {{ a._id }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="user-meta-row">
|
||||||
|
<text class="meta-tag">引力:{{ a.gravity ?? 0 }}</text>
|
||||||
|
<text class="user-plan" :class="{ vip: a.plan === 'growth' || a.plan === 'sprint' }">{{ a.plan === 'growth' || a.plan === 'sprint' ? a.plan==='sprint'?'冲刺':'会员' : '免费' }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="user-meta-row time-row">
|
||||||
|
<text class="time-label">设置:{{ toBeijing(a.createdAt) }}</text>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<text class="empty-text" v-if="adminList.length === 0">暂无管理员</text>
|
<text class="empty-text" v-if="adminList.length === 0">暂无管理员</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="section-label" v-if="searchResult">搜索结果</view>
|
<view class="section-label" v-if="searchResult" style="margin-top:24rpx">搜索结果</view>
|
||||||
<view class="user-list" v-if="searchResult">
|
<view class="user-list" v-if="searchResult">
|
||||||
<view class="admin-row">
|
<view class="user-row">
|
||||||
<text class="admin-phone">{{ searchResult.phone || '--' }}</text>
|
<view class="user-main">
|
||||||
<text class="admin-name">{{ searchResult.nickname || '--' }}</text>
|
<text class="user-phone">{{ searchResult.phone || '--' }}</text>
|
||||||
<text class="admin-email" v-if="searchResult.email">{{ searchResult.email }}</text>
|
<text class="user-name">{{ searchResult.nickname || '--' }}</text>
|
||||||
<text class="admin-set-btn" v-if="searchResult.role !== 'admin'" @click="setAdmin(searchResult._id)">设为管理员</text>
|
<text class="user-badge-role" v-if="searchResult.role === 'admin'">管理</text>
|
||||||
<text class="admin-set-btn done" v-else>已是管理员</text>
|
</view>
|
||||||
|
<view class="user-meta-row">
|
||||||
|
<text class="meta-tag email" v-if="searchResult.email">{{ searchResult.email }}</text>
|
||||||
|
<text class="meta-tag" v-if="searchResult.wxOpenid">openid:{{ searchResult.wxOpenid.slice(0,12) }}..</text>
|
||||||
|
</view>
|
||||||
|
<view class="user-meta-row">
|
||||||
|
<text class="meta-tag id-tag" @click="copyId(searchResult._id)">ID: {{ searchResult._id }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="user-meta-row">
|
||||||
|
<text class="meta-tag">引力:{{ searchResult.gravity ?? 0 }}</text>
|
||||||
|
<text class="user-plan" :class="{ vip: searchResult.plan === 'growth' || searchResult.plan === 'sprint' }">{{ searchResult.plan === 'growth' || searchResult.plan === 'sprint' ? searchResult.plan==='sprint'?'冲刺':'会员' : '免费' }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="user-actions" style="margin-top:8rpx">
|
||||||
|
<text class="admin-set-btn" v-if="searchResult.role !== 'admin'" @click="setAdmin(searchResult._id)">设为管理员</text>
|
||||||
|
<text class="admin-set-btn done" v-else>已是管理员</text>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -514,6 +555,7 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, onMounted, reactive } from 'vue'
|
import { ref, computed, onMounted, reactive } from 'vue'
|
||||||
import { api, API_ENDPOINTS } from '../../config'
|
import { api, API_ENDPOINTS } from '../../config'
|
||||||
|
import { toBeijing } from '../../utils/format'
|
||||||
|
|
||||||
const verified = ref(false)
|
const verified = ref(false)
|
||||||
const adminName = ref('')
|
const adminName = ref('')
|
||||||
@@ -703,6 +745,7 @@ const switchTab = (t) => {
|
|||||||
if (t === 'pricing') loadPricing()
|
if (t === 'pricing') loadPricing()
|
||||||
if (t === 'orders') loadOrders()
|
if (t === 'orders') loadOrders()
|
||||||
if (t === 'analysis') loadAnalysis()
|
if (t === 'analysis') loadAnalysis()
|
||||||
|
if (t === 'share') loadShareRecords()
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadUsers = async () => {
|
const loadUsers = async () => {
|
||||||
@@ -1028,6 +1071,13 @@ const doAdjustCredits = async () => {
|
|||||||
} catch { uni.showToast({ title: '调整失败', icon: 'none' }) }
|
} catch { uni.showToast({ title: '调整失败', icon: 'none' }) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const copyId = (id) => {
|
||||||
|
uni.setClipboardData({
|
||||||
|
data: id,
|
||||||
|
success: () => uni.showToast({ title: 'ID 已复制', icon: 'success' }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(() => { doVerify() })
|
onMounted(() => { doVerify() })
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -1080,9 +1130,6 @@ onMounted(() => { doVerify() })
|
|||||||
.iv-tag.score { background: #EEF2FF; color: var(--color-primary); }
|
.iv-tag.score { background: #EEF2FF; color: var(--color-primary); }
|
||||||
.iv-tag.filler { background: #FFF7ED; color: #D97706; }
|
.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; }
|
.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); }
|
|
||||||
.admin-name { font-size: 22rpx; color: var(--color-text-secondary); flex: 1; }
|
|
||||||
.admin-set-btn { font-size: 22rpx; color: var(--color-primary); padding: 4rpx 16rpx; border: 2rpx solid var(--color-primary); border-radius: var(--radius-round); }
|
.admin-set-btn { font-size: 22rpx; color: var(--color-primary); padding: 4rpx 16rpx; border: 2rpx solid var(--color-primary); border-radius: var(--radius-round); }
|
||||||
.admin-set-btn.done { color: var(--color-success); border-color: var(--color-success); }
|
.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); }
|
.admin-badge { font-size: 18rpx; background: var(--color-primary); color: #FFF; padding: 2rpx 10rpx; border-radius: var(--radius-round); }
|
||||||
@@ -1162,6 +1209,7 @@ onMounted(() => { doVerify() })
|
|||||||
.meta-tag { font-size: 18rpx; background: #F3F4F6; color: var(--color-text-tertiary); padding: 2rpx 10rpx; border-radius: var(--radius-round); }
|
.meta-tag { font-size: 18rpx; background: #F3F4F6; color: var(--color-text-tertiary); padding: 2rpx 10rpx; border-radius: var(--radius-round); }
|
||||||
.meta-tag.email { background: #EEF2FF; color: var(--color-primary); }
|
.meta-tag.email { background: #EEF2FF; color: var(--color-primary); }
|
||||||
.meta-tag.share { background: #FFF7ED; color: #D97706; }
|
.meta-tag.share { background: #FFF7ED; color: #D97706; }
|
||||||
|
.meta-tag.id-tag { background: #F5F3FF; color: #7C3AED; font-family: monospace; font-size: 16rpx; }
|
||||||
.meta-tag.badge-done { background: #ECFDF5; color: #059669; }
|
.meta-tag.badge-done { background: #ECFDF5; color: #059669; }
|
||||||
.meta-tag.badge-pend { background: #FEF3C7; color: #D97706; }
|
.meta-tag.badge-pend { background: #FEF3C7; color: #D97706; }
|
||||||
.time-row { display: flex; flex-wrap: wrap; gap: 12rpx; }
|
.time-row { display: flex; flex-wrap: wrap; gap: 12rpx; }
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<template>
|
||||||
|
<view class="page">
|
||||||
|
<view class="form-card">
|
||||||
|
<text class="section-title">反馈类型</text>
|
||||||
|
<view class="type-row">
|
||||||
|
<view class="type-option" :class="{ active: type === 'bug' }" @click="type = 'bug'">
|
||||||
|
<text class="type-icon">🐛</text>
|
||||||
|
<text class="type-label">问题反馈</text>
|
||||||
|
</view>
|
||||||
|
<view class="type-option" :class="{ active: type === 'suggestion' }" @click="type = 'suggestion'">
|
||||||
|
<text class="type-icon">💡</text>
|
||||||
|
<text class="type-label">改进建议</text>
|
||||||
|
</view>
|
||||||
|
<view class="type-option" :class="{ active: type === 'praise' }" @click="type = 'praise'">
|
||||||
|
<text class="type-icon">👍</text>
|
||||||
|
<text class="type-label">点赞鼓励</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view class="form-card">
|
||||||
|
<text class="section-title">反馈内容 <text class="required">*</text></text>
|
||||||
|
<textarea class="content-input" v-model="content" placeholder="请详细描述您的问题或建议,这将帮助我们持续改进产品..." :maxlength="1000" :auto-height="true" />
|
||||||
|
<text class="char-count">{{ content.length }}/1000</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view class="form-card">
|
||||||
|
<text class="section-title">联系方式(选填)</text>
|
||||||
|
<input class="contact-input" v-model="contact" placeholder="手机号或微信号,方便我们联系您" />
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<button class="submit-btn" :class="{ disabled: !content.trim() || submitting }" @click="submitFeedback" :disabled="submitting">
|
||||||
|
{{ submitting ? '提交中...' : '提交反馈' }}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<view class="toast-success" v-if="submitted">
|
||||||
|
<text class="toast-icon">✅</text>
|
||||||
|
<text class="toast-text">感谢您的反馈!我们会认真处理。</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { api } from '../../config'
|
||||||
|
|
||||||
|
const type = ref('suggestion')
|
||||||
|
const content = ref('')
|
||||||
|
const contact = ref('')
|
||||||
|
const submitting = ref(false)
|
||||||
|
const submitted = ref(false)
|
||||||
|
|
||||||
|
const submitFeedback = async () => {
|
||||||
|
if (!content.value.trim() || submitting.value) return
|
||||||
|
submitting.value = true
|
||||||
|
try {
|
||||||
|
const token = uni.getStorageSync('token')
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api('/feedback'),
|
||||||
|
method: 'POST',
|
||||||
|
header: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||||
|
data: { type: type.value, content: content.value.trim(), contact: contact.value.trim() },
|
||||||
|
})
|
||||||
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||||
|
submitted.value = true
|
||||||
|
} else {
|
||||||
|
uni.showToast({ title: res.data?.message || '提交失败', icon: 'none' })
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
uni.showToast({ title: '提交失败,请重试', icon: 'none' })
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
|
||||||
|
onShareAppMessage(() => ({ title: '意见反馈 - 职引', path: '/pages/feedback/feedback' }))
|
||||||
|
onShareTimeline(() => ({ title: '意见反馈 - 职引' }))
|
||||||
|
// #endif
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.page { background: var(--color-bg); min-height: 100vh; padding: 32rpx; }
|
||||||
|
.form-card { background: #FFF; border-radius: var(--radius-lg); padding: 28rpx 32rpx; margin-bottom: 20rpx; }
|
||||||
|
.section-title { font-size: 26rpx; font-weight: 600; color: var(--color-text); display: block; margin-bottom: 20rpx; }
|
||||||
|
.required { color: #EF4444; }
|
||||||
|
.type-row { display: flex; gap: 16rpx; }
|
||||||
|
.type-option {
|
||||||
|
flex: 1; display: flex; flex-direction: column; align-items: center; gap: 8rpx;
|
||||||
|
padding: 20rpx 12rpx; border-radius: var(--radius-md); border: 2rpx solid var(--color-border);
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
.type-option.active { border-color: var(--color-primary); background: #EEF2FF; }
|
||||||
|
.type-icon { font-size: 36rpx; }
|
||||||
|
.type-label { font-size: 22rpx; color: var(--color-text-secondary); }
|
||||||
|
.type-option.active .type-label { color: var(--color-primary); font-weight: 600; }
|
||||||
|
.content-input { width: 100%; font-size: 26rpx; color: var(--color-text); line-height: 1.7; min-height: 200rpx; padding: 0; }
|
||||||
|
.char-count { text-align: right; font-size: 20rpx; color: var(--color-text-tertiary); margin-top: 8rpx; }
|
||||||
|
.contact-input { width: 100%; font-size: 26rpx; color: var(--color-text); padding: 8rpx 0; }
|
||||||
|
.submit-btn {
|
||||||
|
width: 100%; height: 88rpx; line-height: 88rpx;
|
||||||
|
background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid));
|
||||||
|
color: #FFF; border-radius: var(--radius-md); font-size: 28rpx; font-weight: 600; border: none;
|
||||||
|
}
|
||||||
|
.submit-btn.disabled { background: var(--color-border); }
|
||||||
|
.toast-success {
|
||||||
|
margin-top: 32rpx; background: #ECFDF5; border-radius: var(--radius-md);
|
||||||
|
padding: 24rpx; display: flex; align-items: center; gap: 12rpx;
|
||||||
|
}
|
||||||
|
.toast-icon { font-size: 32rpx; }
|
||||||
|
.toast-text { font-size: 26rpx; color: #065F46; line-height: 1.5; }
|
||||||
|
</style>
|
||||||
@@ -38,9 +38,14 @@
|
|||||||
<!-- Chat area (both modes) -->
|
<!-- Chat area (both modes) -->
|
||||||
<scroll-view class="chat-area" scroll-y :scroll-into-view="scrollToId" :scroll-with-animation="true" :class="{ 'chat-compact': avatarMode }">
|
<scroll-view class="chat-area" scroll-y :scroll-into-view="scrollToId" :scroll-with-animation="true" :class="{ 'chat-compact': avatarMode }">
|
||||||
<view v-for="(msg, idx) in messages" :key="idx" :id="'msg-' + idx" class="msg-row" :class="msg.role">
|
<view v-for="(msg, idx) in messages" :key="idx" :id="'msg-' + idx" class="msg-row" :class="msg.role">
|
||||||
<view class="msg-bubble" :class="msg.role">
|
<view v-if="msg.role === 'ai'" class="msg-avatar ai-avatar">🤖</view>
|
||||||
<text>{{ msg.content }}</text>
|
<view class="msg-body">
|
||||||
|
<view class="msg-label">{{ msg.role === 'ai' ? '面试官' : '我' }}</view>
|
||||||
|
<view class="msg-bubble" :class="msg.role">
|
||||||
|
<text>{{ msg.content }}</text>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
<view v-if="msg.role === 'user'" class="msg-avatar user-avatar">👤</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<view class="msg-row ai" v-if="aiLoading">
|
<view class="msg-row ai" v-if="aiLoading">
|
||||||
@@ -55,14 +60,18 @@
|
|||||||
</scroll-view>
|
</scroll-view>
|
||||||
|
|
||||||
<view class="input-bar" v-if="!isComplete">
|
<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">
|
<view class="mic-wrap">
|
||||||
<text class="mic-icon">🎤</text>
|
<view class="mic-btn" :class="{ recording: isRecording }" @click="toggleRecord">
|
||||||
|
<text class="mic-icon">{{ isRecording ? '🔴' : '🎤' }}</text>
|
||||||
|
<text class="mic-label" v-if="isRecording">{{ recordingDuration }}s</text>
|
||||||
|
</view>
|
||||||
|
<text class="mic-hint" v-if="isRecording">点击结束</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="input-box">
|
<view class="input-box">
|
||||||
<textarea class="input-area" v-model="inputText" placeholder="输入你的回答..." :auto-height="true" :maxlength="2000" :disabled="aiLoading" @confirm="sendAnswer" />
|
<textarea class="input-area" v-model="inputText" placeholder="点击🎤开始录音或输入回答..." :auto-height="true" :maxlength="2000" :disabled="aiLoading || isRecording" @confirm="sendAnswer" />
|
||||||
</view>
|
</view>
|
||||||
<view class="send-btn" :class="{ disabled: (!inputText.trim() && !isRecording) || aiLoading }" @click="sendAnswer">
|
<view class="send-btn" :class="{ disabled: !inputText.trim() || isRecording || aiLoading }" @click="sendAnswer">
|
||||||
<text class="send-icon">{{ isRecording ? '◉' : '➤' }}</text>
|
<text class="send-icon">➤</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
@@ -90,22 +99,22 @@
|
|||||||
|
|
||||||
<view class="complete-bar" v-else>
|
<view class="complete-bar" v-else>
|
||||||
<button class="cta-btn" @click="goResult">查看面试报告</button>
|
<button class="cta-btn" @click="goResult">查看面试报告</button>
|
||||||
<button class="buy-btn" v-if="completedReason === 'noCredits'" @click="goH5Buy">引力值不足,官网购买 ›</button>
|
<button class="buy-btn" v-if="completedReason === 'noCredits'" @click="goGravityBuy">引力值不足,立即补充 ›</button>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<!-- 官网购买弹窗 -->
|
<!-- 引力值不足弹窗 -->
|
||||||
<view class="modal-overlay" v-if="showH5BuyModal" @click="showH5BuyModal = false">
|
<view class="modal-overlay" v-if="showGravityBuyModal" @click="showGravityBuyModal = false">
|
||||||
<view class="modal-content" @click.stop>
|
<view class="modal-content" @click.stop>
|
||||||
<text class="modal-title">引力值不足</text>
|
<text class="modal-title">引力值不足</text>
|
||||||
<text class="modal-hint">您的引力值不足,请补充后继续面试(每次面试消耗 5 引力值)</text>
|
<text class="modal-hint">您的引力值不足,请补充后继续面试(每次面试消耗 5 引力值)</text>
|
||||||
<view class="purchase-options">
|
<view class="purchase-options">
|
||||||
<view class="purchase-option" @click="goH5BuyAndClose">
|
<view class="purchase-option" @click="goGravityBuyAndClose">
|
||||||
<text class="purchase-name">官网购买引力值</text>
|
<text class="purchase-name">购买引力值</text>
|
||||||
<text class="purchase-price">前往网页版充值</text>
|
<text class="purchase-price">前往充值</text>
|
||||||
<text class="purchase-desc">打开官网 H5 页面,支持多种支付方式</text>
|
<text class="purchase-desc">小程序内直接购买,微信支付安全便捷</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<text class="modal-close" @click="showH5BuyModal = false">取消</text>
|
<text class="modal-close" @click="showGravityBuyModal = false">取消</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -120,6 +129,7 @@ import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
|
|||||||
import { onLoad } from '@dcloudio/uni-app'
|
import { onLoad } from '@dcloudio/uni-app'
|
||||||
// #endif
|
// #endif
|
||||||
import { api, API_ENDPOINTS } from '../../config'
|
import { api, API_ENDPOINTS } from '../../config'
|
||||||
|
import { checkAuth } from '../../utils/auth'
|
||||||
import DigitalHuman from '../../components/digital-human.vue'
|
import DigitalHuman from '../../components/digital-human.vue'
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
onShareAppMessage(() => ({ title: '职引 - AI模拟面试 | 数字人面试官实战练习', path: '/pages/interview/interview' }))
|
onShareAppMessage(() => ({ title: '职引 - AI模拟面试 | 数字人面试官实战练习', path: '/pages/interview/interview' }))
|
||||||
@@ -136,7 +146,7 @@ const scrollToId = ref('')
|
|||||||
const position = ref('')
|
const position = ref('')
|
||||||
const avatarMode = ref(true)
|
const avatarMode = ref(true)
|
||||||
const showPositionPicker = ref(false)
|
const showPositionPicker = ref(false)
|
||||||
const showH5BuyModal = ref(false)
|
const showGravityBuyModal = ref(false)
|
||||||
const positions = ref([])
|
const positions = ref([])
|
||||||
const positionsLoading = ref(false)
|
const positionsLoading = ref(false)
|
||||||
const aiSpeechText = ref('')
|
const aiSpeechText = ref('')
|
||||||
@@ -145,11 +155,59 @@ const aiAmplitudeData = ref([])
|
|||||||
const isSpeaking = ref(false)
|
const isSpeaking = ref(false)
|
||||||
const dhRef = ref(null)
|
const dhRef = ref(null)
|
||||||
const isRecording = ref(false)
|
const isRecording = ref(false)
|
||||||
let recorder = null
|
const recordingDuration = ref(0)
|
||||||
|
let manager = null
|
||||||
|
let recordTimer = null
|
||||||
|
|
||||||
|
|
||||||
|
function initRecorder() {
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
if (manager) return
|
||||||
|
try {
|
||||||
|
const plugin = requirePlugin('WechatSI')
|
||||||
|
manager = plugin.getRecordRecognitionManager()
|
||||||
|
manager.onStart = () => {
|
||||||
|
console.log('[WechatSI] start')
|
||||||
|
isRecording.value = true
|
||||||
|
inputText.value = ''
|
||||||
|
recordingDuration.value = 0
|
||||||
|
recordTimer = setInterval(() => { recordingDuration.value++ }, 1000)
|
||||||
|
}
|
||||||
|
manager.onRecognize = (res) => {
|
||||||
|
if (res?.result?.trim()) inputText.value = res.result.trim()
|
||||||
|
}
|
||||||
|
manager.onStop = (res) => {
|
||||||
|
isRecording.value = false
|
||||||
|
recordingDuration.value = 0
|
||||||
|
if (recordTimer) { clearInterval(recordTimer); recordTimer = null }
|
||||||
|
const text = res?.result?.trim()
|
||||||
|
if (text && text.length >= 2) {
|
||||||
|
inputText.value = text
|
||||||
|
sendAnswer()
|
||||||
|
} else if (text && text.length === 1) {
|
||||||
|
uni.showToast({ title: '语音过短,请重试', icon: 'none' })
|
||||||
|
} else if (!text) {
|
||||||
|
uni.showToast({ title: '未检测到语音,请重试', icon: 'none' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
manager.onError = (res) => {
|
||||||
|
console.error('[WechatSI] error:', JSON.stringify(res))
|
||||||
|
isRecording.value = false
|
||||||
|
recordingDuration.value = 0
|
||||||
|
if (recordTimer) { clearInterval(recordTimer); recordTimer = null }
|
||||||
|
const msg = res?.errMsg?.includes('permission') ? '请允许录音权限' : '语音识别失败,请重试'
|
||||||
|
uni.showToast({ title: msg, icon: 'none' })
|
||||||
|
manager = null
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('WechatSI plugin init failed:', e)
|
||||||
|
manager = null
|
||||||
|
}
|
||||||
|
// #endif
|
||||||
|
}
|
||||||
|
|
||||||
let timerSeconds = 0
|
let timerSeconds = 0
|
||||||
let timerInterval = null
|
let timerInterval = null
|
||||||
|
|
||||||
let MAX_QUESTIONS = 10
|
let MAX_QUESTIONS = 10
|
||||||
const progressPercent = computed(() => Math.min((answeredCount.value / MAX_QUESTIONS) * 100, 100))
|
const progressPercent = computed(() => Math.min((answeredCount.value / MAX_QUESTIONS) * 100, 100))
|
||||||
const formatTime = computed(() => {
|
const formatTime = computed(() => {
|
||||||
@@ -162,7 +220,7 @@ onLoad((options) => {
|
|||||||
if (options?.position) {
|
if (options?.position) {
|
||||||
const pos = decodeURIComponent(options.position)
|
const pos = decodeURIComponent(options.position)
|
||||||
position.value = pos
|
position.value = pos
|
||||||
messages.value = [{ role: 'ai', content: `你好!我是你的专属 ${pos} 面试官,准备好了就开始吧!` }]
|
messages.value = [{ role: 'ai', content: `你好!我是你的专属 ${pos} 面试官。准备好后发送任意消息,我会立即开始面试并给出第一个问题。` }]
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -184,18 +242,15 @@ const loadPositions = async () => {
|
|||||||
const selectPosition = (pos) => {
|
const selectPosition = (pos) => {
|
||||||
position.value = pos.name
|
position.value = pos.name
|
||||||
showPositionPicker.value = false
|
showPositionPicker.value = false
|
||||||
messages.value = [{ role: 'ai', content: `你好!我是你的专属 ${pos.name} 面试官,准备好了就开始吧!` }]
|
messages.value = [{ role: 'ai', content: `你好!我是你的专属 ${pos.name} 面试官。准备好后发送任意消息,我会立即开始面试并给出第一个问题。` }]
|
||||||
startInterview()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
|
initRecorder()
|
||||||
timerInterval = setInterval(() => timerSeconds++, 1000)
|
timerInterval = setInterval(() => timerSeconds++, 1000)
|
||||||
if (!position.value) {
|
if (!position.value) {
|
||||||
// 未传入岗位,展示选择弹窗(无论是否登录)
|
|
||||||
loadPositions()
|
loadPositions()
|
||||||
showPositionPicker.value = true
|
showPositionPicker.value = true
|
||||||
} else if (token()) {
|
|
||||||
startInterview()
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -223,11 +278,15 @@ const startInterview = async () => {
|
|||||||
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
|
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
|
||||||
data: { position: position.value },
|
data: { position: position.value },
|
||||||
})
|
})
|
||||||
if (res.statusCode === 200 && res.data) {
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data) {
|
||||||
interviewId.value = res.data.id
|
interviewId.value = res.data.id
|
||||||
messages.value = res.data.messages || messages.value
|
|
||||||
answeredCount.value = res.data.questionCount || 0
|
answeredCount.value = res.data.questionCount || 0
|
||||||
if (res.data.totalQuestions) MAX_QUESTIONS = res.data.totalQuestions
|
if (res.data.totalQuestions) MAX_QUESTIONS = res.data.totalQuestions
|
||||||
|
// 将后端返回的 AI 消息追加入对话,不替换已有消息(保留用户已发的准备消息)
|
||||||
|
if (res.data.messages?.length) {
|
||||||
|
const aiMsgs = res.data.messages.filter(m => m.role === 'ai')
|
||||||
|
if (aiMsgs.length > 0) messages.value.push(...aiMsgs)
|
||||||
|
}
|
||||||
// Speak first question in avatar mode
|
// Speak first question in avatar mode
|
||||||
if (avatarMode.value && res.data.messages?.length) {
|
if (avatarMode.value && res.data.messages?.length) {
|
||||||
const last = res.data.messages[res.data.messages.length - 1]
|
const last = res.data.messages[res.data.messages.length - 1]
|
||||||
@@ -238,8 +297,11 @@ const startInterview = async () => {
|
|||||||
messages.value.push({ role: 'ai', content: errMsg + ' 👉 购买后可继续面试' })
|
messages.value.push({ role: 'ai', content: errMsg + ' 👉 购买后可继续面试' })
|
||||||
isComplete.value = true
|
isComplete.value = true
|
||||||
completedReason.value = 'noCredits'
|
completedReason.value = 'noCredits'
|
||||||
|
} else if (checkAuth(res)) {
|
||||||
|
return // token 过期,已清除并跳转登录
|
||||||
} else {
|
} else {
|
||||||
const msg = res.data?.message || '创建面试失败'
|
const errMsg = typeof res.data === 'string' ? res.data : (res.data?.message || '')
|
||||||
|
const msg = errMsg || `创建面试失败(${res.statusCode})`
|
||||||
messages.value.push({ role: 'ai', content: msg })
|
messages.value.push({ role: 'ai', content: msg })
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -251,14 +313,20 @@ const startInterview = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const sendAnswer = async () => {
|
const sendAnswer = async () => {
|
||||||
if (!inputText.value.trim() || aiLoading.value || isComplete.value) return
|
if (!inputText.value.trim() || aiLoading.value || isRecording.value || isComplete.value) return
|
||||||
if (!token()) { checkLogin(); return }
|
if (!token()) { checkLogin(); return }
|
||||||
|
const answer = inputText.value.trim()
|
||||||
|
|
||||||
|
// 首次发送:不把用户消息当答案提交,而是先创建面试获取第一个问题
|
||||||
if (!interviewId.value) {
|
if (!interviewId.value) {
|
||||||
|
messages.value.push({ role: 'user', content: answer })
|
||||||
|
inputText.value = ''
|
||||||
|
scrollToBottom()
|
||||||
await startInterview()
|
await startInterview()
|
||||||
if (!interviewId.value) return // creation failed, don't discard answer
|
// startInterview 成功后已经把第一个问题追加到 messages 了
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const answer = inputText.value.trim()
|
|
||||||
messages.value.push({ role: 'user', content: answer })
|
messages.value.push({ role: 'user', content: answer })
|
||||||
inputText.value = ''
|
inputText.value = ''
|
||||||
scrollToBottom()
|
scrollToBottom()
|
||||||
@@ -270,7 +338,7 @@ const sendAnswer = async () => {
|
|||||||
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
|
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
|
||||||
data: avatarMode.value ? { answer, avatar: true } : { answer },
|
data: avatarMode.value ? { answer, avatar: true } : { answer },
|
||||||
})
|
})
|
||||||
if (res.statusCode === 200 && res.data?.messages) {
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.messages) {
|
||||||
const aiMsg = res.data.messages.find(m => m.role === 'ai')
|
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
|
// 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')
|
const newAiMessages = res.data.messages.filter(m => m.role === 'ai')
|
||||||
@@ -285,6 +353,8 @@ const sendAnswer = async () => {
|
|||||||
messages.value.push({ role: 'ai', content: errMsg + ' 👉 购买后可继续面试' })
|
messages.value.push({ role: 'ai', content: errMsg + ' 👉 购买后可继续面试' })
|
||||||
isComplete.value = true
|
isComplete.value = true
|
||||||
completedReason.value = 'noCredits'
|
completedReason.value = 'noCredits'
|
||||||
|
} else if (checkAuth(res)) {
|
||||||
|
return
|
||||||
} else {
|
} else {
|
||||||
messages.value.push({ role: 'ai', content: res.data?.message || '回答提交失败' })
|
messages.value.push({ role: 'ai', content: res.data?.message || '回答提交失败' })
|
||||||
}
|
}
|
||||||
@@ -311,6 +381,8 @@ async function speakAiText(text, ttsHash, ttsAmplitude) {
|
|||||||
if (synthRes.statusCode === 200 && synthRes.data?.hash) {
|
if (synthRes.statusCode === 200 && synthRes.data?.hash) {
|
||||||
aiAudioUrl.value = api(API_ENDPOINTS.TTS.AUDIO(synthRes.data.hash))
|
aiAudioUrl.value = api(API_ENDPOINTS.TTS.AUDIO(synthRes.data.hash))
|
||||||
aiAmplitudeData.value = synthRes.data?.amplitudeData || []
|
aiAmplitudeData.value = synthRes.data?.amplitudeData || []
|
||||||
|
} else {
|
||||||
|
checkAuth(synthRes)
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
@@ -326,25 +398,13 @@ function onAvatarSilent() {
|
|||||||
|
|
||||||
const goResult = () => uni.navigateTo({ url: `/pages/report/report?interviewId=${interviewId.value}` })
|
const goResult = () => uni.navigateTo({ url: `/pages/report/report?interviewId=${interviewId.value}` })
|
||||||
|
|
||||||
// 官网购买引力值
|
// 购买引力值
|
||||||
const goH5Buy = () => {
|
const goGravityBuy = () => {
|
||||||
showH5BuyModal.value = true
|
showGravityBuyModal.value = true
|
||||||
}
|
}
|
||||||
const goH5BuyAndClose = () => {
|
const goGravityBuyAndClose = () => {
|
||||||
showH5BuyModal.value = false
|
showGravityBuyModal.value = false
|
||||||
const token = uni.getStorageSync('token') || ''
|
uni.navigateTo({ url: '/pages/member/member' })
|
||||||
const url = `https://zhiyin.yzrcloud.cn/?buy=gravity${token ? '&token=' + token : ''}`
|
|
||||||
// #ifdef MP-WEIXIN
|
|
||||||
uni.setClipboardData({
|
|
||||||
data: url,
|
|
||||||
success: () => {
|
|
||||||
uni.showToast({ title: '链接已复制,请在手机浏览器中打开', icon: 'none', duration: 3000 })
|
|
||||||
},
|
|
||||||
fail: () => {
|
|
||||||
uni.showToast({ title: '复制失败,请手动访问 zhiyin.yzrcloud.cn', icon: 'none', duration: 3000 })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
// #endif
|
|
||||||
}
|
}
|
||||||
const scrollToBottom = () => {
|
const scrollToBottom = () => {
|
||||||
nextTick(() => { scrollToId.value = ''; setTimeout(() => { scrollToId.value = 'msg-bottom' }, 100) })
|
nextTick(() => { scrollToId.value = ''; setTimeout(() => { scrollToId.value = 'msg-bottom' }, 100) })
|
||||||
@@ -357,49 +417,28 @@ const confirmExit = () => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function startRecord() {
|
function toggleRecord() {
|
||||||
if (aiLoading.value || isComplete.value) return
|
if (aiLoading.value || isComplete.value) return
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
isRecording.value = true
|
if (!isRecording.value) {
|
||||||
recorder = uni.getRecorderManager()
|
if (!manager) initRecorder()
|
||||||
recorder.onStart(() => {})
|
if (!manager) {
|
||||||
recorder.onError(() => { isRecording.value = false })
|
uni.showToast({ title: '语音功能初始化失败', icon: 'none' })
|
||||||
recorder.start({ format: 'mp3' })
|
return
|
||||||
uni.vibrateShort({ type: 'medium' })
|
}
|
||||||
|
manager.start({ lang: 'zh_CN', duration: 60000 })
|
||||||
|
uni.vibrateShort({ type: 'medium' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!manager) { isRecording.value = false; return }
|
||||||
|
if (recordTimer) { clearInterval(recordTimer); recordTimer = null }
|
||||||
|
recordingDuration.value = 0
|
||||||
|
manager.stop()
|
||||||
// #endif
|
// #endif
|
||||||
// #ifndef MP-WEIXIN
|
// #ifndef MP-WEIXIN
|
||||||
uni.showToast({ title: '语音输入仅支持小程序', icon: 'none' })
|
uni.showToast({ title: '语音输入仅支持小程序', icon: 'none' })
|
||||||
// #endif
|
// #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()}` },
|
|
||||||
})
|
|
||||||
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>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@@ -436,11 +475,20 @@ function stopRecord() {
|
|||||||
/* Chat */
|
/* Chat */
|
||||||
.chat-area { flex: 1; padding: 24rpx 20rpx; overflow-y: auto; }
|
.chat-area { flex: 1; padding: 24rpx 20rpx; overflow-y: auto; }
|
||||||
.chat-compact { max-height: 40vh; }
|
.chat-compact { max-height: 40vh; }
|
||||||
.msg-row { display: flex; margin-bottom: 24rpx; }
|
.msg-row { display: flex; margin-bottom: 32rpx; align-items: flex-start; gap: 12rpx; }
|
||||||
.msg-row.ai { justify-content: flex-start; }
|
.msg-row.ai { justify-content: flex-start; }
|
||||||
.msg-row.user { justify-content: flex-end; }
|
.msg-row.user { justify-content: flex-end; }
|
||||||
|
|
||||||
.msg-bubble { max-width: 560rpx; padding: 20rpx 24rpx; line-height: 1.7; font-size: 26rpx; }
|
.msg-avatar { width: 48rpx; height: 48rpx; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 24rpx; flex-shrink: 0; }
|
||||||
|
.ai-avatar { background: #EEF2FF; }
|
||||||
|
.user-avatar { background: #FEF3C7; }
|
||||||
|
|
||||||
|
.msg-body { max-width: 70%; display: flex; flex-direction: column; gap: 6rpx; }
|
||||||
|
.msg-row.user .msg-body { align-items: flex-end; }
|
||||||
|
|
||||||
|
.msg-label { font-size: 20rpx; color: #9CA3AF; padding: 0 8rpx; }
|
||||||
|
|
||||||
|
.msg-bubble { padding: 20rpx 24rpx; line-height: 1.7; font-size: 26rpx; word-break: break-word; }
|
||||||
.msg-bubble.ai {
|
.msg-bubble.ai {
|
||||||
background: #FFFFFF; color: var(--color-text);
|
background: #FFFFFF; color: var(--color-text);
|
||||||
border-radius: 0 var(--radius-lg) var(--radius-lg) var(--radius-lg);
|
border-radius: 0 var(--radius-lg) var(--radius-lg) var(--radius-lg);
|
||||||
@@ -473,14 +521,18 @@ function stopRecord() {
|
|||||||
}
|
}
|
||||||
.input-box { flex: 1; background: var(--color-bg); border-radius: var(--radius-md); padding: 12rpx 20rpx; }
|
.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; }
|
.input-area { width: 100%; font-size: 26rpx; color: var(--color-text); max-height: 160rpx; line-height: 1.5; }
|
||||||
|
.mic-wrap { display: flex; flex-direction: column; align-items: center; gap: 4rpx; flex-shrink: 0; }
|
||||||
.mic-btn {
|
.mic-btn {
|
||||||
width: 64rpx; height: 64rpx; border-radius: 50%; background: #F3F4F6;
|
width: 80rpx; height: 80rpx; border-radius: 50%; background: #F3F4F6;
|
||||||
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
|
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||||
transition: all 0.2s;
|
transition: all 0.2s; gap: 2rpx;
|
||||||
}
|
}
|
||||||
.mic-btn:active { transform: scale(0.9); }
|
.mic-btn:active { transform: scale(0.9); }
|
||||||
.mic-btn.recording { background: #FEE2E2; animation: mic-pulse 1s infinite; }
|
.mic-btn.recording { background: #FEE2E2; animation: mic-pulse 1s infinite; }
|
||||||
.mic-icon { font-size: 28rpx; }
|
.mic-icon { font-size: 28rpx; line-height: 1; }
|
||||||
|
.mic-label { font-size: 16rpx; color: #9CA3AF; line-height: 1; }
|
||||||
|
.mic-btn.recording .mic-label { color: #EF4444; font-weight: 600; }
|
||||||
|
.mic-hint { font-size: 18rpx; color: #EF4444; font-weight: 500; line-height: 1; white-space: nowrap; }
|
||||||
@keyframes mic-pulse {
|
@keyframes mic-pulse {
|
||||||
0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
|
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); }
|
50% { box-shadow: 0 0 0 16rpx rgba(239, 68, 68, 0); }
|
||||||
|
|||||||
@@ -65,6 +65,13 @@
|
|||||||
<view class="card" v-if="mainTab === 'register'">
|
<view class="card" v-if="mainTab === 'register'">
|
||||||
<text class="card-title">创建账号</text>
|
<text class="card-title">创建账号</text>
|
||||||
<text class="card-sub">注册后享受 AI 面试模拟服务</text>
|
<text class="card-sub">注册后享受 AI 面试模拟服务</text>
|
||||||
|
<view class="promo-banner">
|
||||||
|
<text class="promo-icon">🎁</text>
|
||||||
|
<view class="promo-texts">
|
||||||
|
<text class="promo-title">注册即送 {{ registrationGravity }} 引力值</text>
|
||||||
|
<text class="promo-desc">免费体验 AI 面试模拟</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
<view class="field">
|
<view class="field">
|
||||||
<text class="field-label">邮箱</text>
|
<text class="field-label">邮箱</text>
|
||||||
<input class="input" type="text" v-model="email" placeholder="请输入邮箱" />
|
<input class="input" type="text" v-model="email" placeholder="请输入邮箱" />
|
||||||
@@ -133,6 +140,7 @@ const agreed = ref(false)
|
|||||||
const mainTab = ref('login')
|
const mainTab = ref('login')
|
||||||
const loginMode = ref('password') // 'password' | 'code'
|
const loginMode = ref('password') // 'password' | 'code'
|
||||||
const isMp = ref(false)
|
const isMp = ref(false)
|
||||||
|
const registrationGravity = ref(50)
|
||||||
|
|
||||||
const email = ref('')
|
const email = ref('')
|
||||||
const password = ref('')
|
const password = ref('')
|
||||||
@@ -158,6 +166,17 @@ onMounted(() => {
|
|||||||
isMp.value = true
|
isMp.value = true
|
||||||
mainTab.value = 'wechat'
|
mainTab.value = 'wechat'
|
||||||
// #endif
|
// #endif
|
||||||
|
// 获取注册赠送引力值配置
|
||||||
|
uni.request({
|
||||||
|
url: api('/member/plans'),
|
||||||
|
method: 'GET',
|
||||||
|
success: (res) => {
|
||||||
|
if (res.statusCode === 200 && res.data?.registrationGravity) {
|
||||||
|
registrationGravity.value = res.data.registrationGravity
|
||||||
|
}
|
||||||
|
},
|
||||||
|
fail: () => {} // 使用默认值 50
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
onBeforeUnmount(() => { if (timer) { clearTimeout(timer); timer = null } })
|
onBeforeUnmount(() => { if (timer) { clearTimeout(timer); timer = null } })
|
||||||
@@ -355,6 +374,12 @@ const goPrivacy = () => uni.navigateTo({ url: '/pages/privacy/privacy' })
|
|||||||
.card-title { font-size: 30rpx; font-weight: 700; color: var(--color-text); display: block; }
|
.card-title { font-size: 30rpx; font-weight: 700; color: var(--color-text); display: block; }
|
||||||
.card-sub { font-size: 22rpx; color: var(--color-text-tertiary); margin-top: 6rpx; margin-bottom: 24rpx; display: block; }
|
.card-sub { font-size: 22rpx; color: var(--color-text-tertiary); margin-top: 6rpx; margin-bottom: 24rpx; display: block; }
|
||||||
|
|
||||||
|
/* ===== Promo Banner ===== */
|
||||||
|
.promo-banner { background: linear-gradient(135deg, #FEF3C7, #FDE68A); border-radius: var(--radius-md); padding: 20rpx 24rpx; margin-bottom: 24rpx; display: flex; align-items: center; gap: 16rpx; }
|
||||||
|
.promo-icon { font-size: 36rpx; }
|
||||||
|
.promo-title { font-size: 26rpx; font-weight: 700; color: #92400E; display: block; }
|
||||||
|
.promo-desc { font-size: 22rpx; color: #B45309; display: block; margin-top: 4rpx; }
|
||||||
|
|
||||||
/* ===== Fields ===== */
|
/* ===== Fields ===== */
|
||||||
.field { margin-bottom: 20rpx; }
|
.field { margin-bottom: 20rpx; }
|
||||||
.field-label { font-size: 22rpx; color: var(--color-text-secondary); margin-bottom: 8rpx; display: block; }
|
.field-label { font-size: 22rpx; color: var(--color-text-secondary); margin-bottom: 8rpx; display: block; }
|
||||||
|
|||||||
@@ -1,229 +1,533 @@
|
|||||||
<template>
|
<template>
|
||||||
<!-- #ifdef MP-WEIXIN -->
|
|
||||||
<view class="page fade-in">
|
<view class="page fade-in">
|
||||||
<view class="placeholder-wrap">
|
<!-- 状态栏:当前方案 + 引力值 -->
|
||||||
<text class="placeholder-icon">✨</text>
|
<view class="status-bar">
|
||||||
<text class="placeholder-text">功能已整合到各模块</text>
|
<view class="status-left">
|
||||||
<text class="placeholder-hint">请返回使用引力值充值功能</text>
|
<text class="status-label">当前方案</text>
|
||||||
<text class="placeholder-back" @click="goBack">返回首页</text>
|
<text class="status-plan">{{ currentPlanName || '免费版' }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
<view class="status-right">
|
||||||
<!-- #endif -->
|
<text class="grav-label">⚡ 引力值</text>
|
||||||
<!-- #ifdef H5 -->
|
<text class="grav-num">{{ gravity }}</text>
|
||||||
<view class="page fade-in">
|
</view>
|
||||||
<view class="hero">
|
|
||||||
<text class="hero-icon">⚡</text>
|
|
||||||
<text class="hero-title">补充引力值</text>
|
|
||||||
<text class="hero-desc">购买后可获得相应引力值,用于面试、简历优化、下载</text>
|
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<view class="product-card">
|
<!-- 未登录提示 -->
|
||||||
<view class="qty-section">
|
<view class="login-bar" v-if="!isLoggedIn">
|
||||||
<text class="section-label">购买数量</text>
|
<text class="login-text">登录后可购买引力值、查看套餐</text>
|
||||||
<view class="qty-controls">
|
<text class="login-btn" @click="goLogin">去登录</text>
|
||||||
<text class="qty-btn" :class="{ disabled: buyQty <= 1 }" @click="changeQty(-1)">−</text>
|
</view>
|
||||||
<input class="qty-input" type="number" v-model.number="buyQty" min="1" max="99" @blur="clampQty" />
|
|
||||||
<text class="qty-btn" :class="{ disabled: buyQty >= 99 }" @click="changeQty(1)">+</text>
|
<!-- 购买引力值(最上面,登录后可见) -->
|
||||||
|
<view class="section" v-if="isLoggedIn">
|
||||||
|
<text class="section-title">⚡ 补充引力值</text>
|
||||||
|
<view class="buy-card">
|
||||||
|
<view class="qty-row">
|
||||||
|
<text class="qty-label">购买数量</text>
|
||||||
|
<view class="qty-controls">
|
||||||
|
<text class="qty-btn" :class="{ disabled: buyQty <= 1 }" @click="buyQty = Math.max(1, buyQty - 1)">−</text>
|
||||||
|
<input class="qty-input" type="number" v-model.number="buyQty" min="1" max="99" @blur="buyQty = Math.max(1, Math.min(99, buyQty || 1))" />
|
||||||
|
<text class="qty-btn" :class="{ disabled: buyQty >= 99 }" @click="buyQty = Math.min(99, buyQty + 1)">+</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
<view class="summary">
|
||||||
|
<view class="summary-row">
|
||||||
|
<text class="summary-label">单价</text>
|
||||||
|
<text class="summary-val">¥{{ (unitPrice / 100).toFixed(1) }} / 份</text>
|
||||||
|
</view>
|
||||||
|
<view class="summary-row">
|
||||||
|
<text class="summary-label">可得引力值</text>
|
||||||
|
<text class="summary-val highlight">{{ buyQty * gravityPerUnit }} ⚡</text>
|
||||||
|
</view>
|
||||||
|
<view class="summary-row total">
|
||||||
|
<text class="summary-label">合计</text>
|
||||||
|
<text class="summary-val total-price">¥{{ (buyQty * unitPrice / 100).toFixed(2) }}</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
<button class="buy-btn" :disabled="payLoading" @click="startGravityPay">
|
||||||
|
{{ payLoading ? '处理中...' : '立即购买' }}
|
||||||
|
</button>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<!-- 套餐对比 -->
|
||||||
|
<view class="section">
|
||||||
|
<text class="section-title">📋 套餐对比</text>
|
||||||
|
<view class="plan-list">
|
||||||
|
<view v-for="p in planList" :key="p.id" class="plan-card"
|
||||||
|
:class="{ current: p.id === plan, popular: p.popular }">
|
||||||
|
<view class="plan-header">
|
||||||
|
<text class="plan-name">{{ p.name }}</text>
|
||||||
|
<view class="plan-price">
|
||||||
|
<text class="price-num">{{ p.priceDisplay }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="plan-badge" v-if="p.id === plan">
|
||||||
|
<text>当前方案</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
<view class="plan-features">
|
||||||
|
<text class="feature" v-for="(f, i) in p.features" :key="i">✓ {{ f }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="plan-footer" v-if="p.id !== 'free'">
|
||||||
|
<view class="plan-action owned" v-if="p.id === plan">✅ 已开通</view>
|
||||||
|
<view class="plan-action" v-else-if="!isLoggedIn" @click="goLogin">登录后开通</view>
|
||||||
|
<view class="plan-action" v-else-if="plan === 'free'" @click="startPlanPay(p.id)">
|
||||||
|
{{ p.priceDisplay }} 开通
|
||||||
|
</view>
|
||||||
|
<view class="plan-action" v-else @click="startPlanPay(p.id)">
|
||||||
|
升级至{{ p.name }}
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<view class="summary">
|
|
||||||
<view class="summary-row">
|
|
||||||
<text class="summary-label">单价</text>
|
|
||||||
<text class="summary-val">¥{{ (unitPrice / 100).toFixed(1) }} / 份</text>
|
|
||||||
</view>
|
|
||||||
<view class="summary-row">
|
|
||||||
<text class="summary-label">可得引力值</text>
|
|
||||||
<text class="summary-val highlight">{{ buyQty * gravityPerUnit }} 引力值</text>
|
|
||||||
</view>
|
|
||||||
<view class="summary-row total">
|
|
||||||
<text class="summary-label">合计</text>
|
|
||||||
<text class="summary-val total-price">¥{{ (buyQty * unitPrice / 100).toFixed(2) }}</text>
|
|
||||||
</view>
|
|
||||||
</view>
|
|
||||||
|
|
||||||
<button class="buy-btn" :disabled="payLoading" @click="startPay">
|
|
||||||
<text v-if="!payLoading">立即购买</text>
|
|
||||||
<text v-else>处理中...</text>
|
|
||||||
</button>
|
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<!-- 支付弹窗 -->
|
<!-- 支付弹窗 -->
|
||||||
<view class="modal-overlay" v-if="showPayModal" @click="cancelPay">
|
<view class="modal-overlay" v-if="showPayModal" @click="cancelPay">
|
||||||
<view class="modal-content" @click.stop>
|
<view class="modal-content" @click.stop>
|
||||||
<template v-if="payLoading">
|
<template v-if="payLoading">
|
||||||
<text class="modal-title">正在创建订单...</text>
|
<text class="modal-title">正在创建支付...</text>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="payCodeUrl">
|
<template v-else-if="!isMp && payCodeUrl">
|
||||||
<text class="modal-title">微信扫码支付</text>
|
<text class="modal-title">微信扫码支付</text>
|
||||||
<image class="qrcode" :src="'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' + encodeURIComponent(payCodeUrl)" mode="widthFix" />
|
<canvas canvas-id="payQrcode" class="qr-canvas"></canvas>
|
||||||
<text class="modal-hint">请使用微信扫描二维码完成支付</text>
|
<text class="modal-hint">请用微信扫码完成支付</text>
|
||||||
<text class="modal-close" @click="cancelPay">取消支付</text>
|
<text class="modal-close" @click="cancelPay">取消支付</text>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="paySuccess">
|
<template v-else-if="vpStatus">
|
||||||
<text class="modal-title">✅ 支付成功</text>
|
<text class="modal-title" :class="vpSuccess ? '' : 'pay-error'">{{ vpSuccess ? '✅ 支付成功' : '支付失败' }}</text>
|
||||||
<text class="modal-hint">引力值已到账,返回继续使用吧</text>
|
<text class="modal-hint">{{ vpStatusText }}</text>
|
||||||
<text class="modal-close" @click="cancelPay">关闭</text>
|
<text class="modal-close" @click="cancelPay">关闭</text>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="payError">
|
<template v-if="payError && !vpStatus">
|
||||||
<text class="modal-title pay-error">支付失败</text>
|
<text class="modal-title pay-error">支付异常</text>
|
||||||
<text class="modal-hint">{{ payError }}</text>
|
<text class="modal-hint">{{ payError }}</text>
|
||||||
<text class="modal-close" @click="cancelPay">关闭</text>
|
<text class="modal-close" @click="cancelPay">关闭</text>
|
||||||
</template>
|
</template>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<!-- #endif -->
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, computed, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
// #ifdef MP-WEIXIN
|
import { onLoad, onShow } from '@dcloudio/uni-app'
|
||||||
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
|
|
||||||
// #endif
|
|
||||||
import { api } from '../../config'
|
import { api } from '../../config'
|
||||||
|
import { checkAuth, friendlyVpError } from '../../utils/auth'
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
const isLoggedIn = ref(false)
|
||||||
onShareAppMessage(() => ({ title: '职引 - 引力值购买 | AI模拟面试', path: '/pages/member/member' }))
|
const isMp = ref(false)
|
||||||
onShareTimeline(() => ({ title: '职引 - 引力值购买 | AI模拟面试' }))
|
const plan = ref('free')
|
||||||
// #endif
|
const currentPlanName = ref('免费版')
|
||||||
|
const gravity = ref(0)
|
||||||
|
const planList = ref([])
|
||||||
|
|
||||||
const goBack = () => uni.switchTab({ url: '/pages/user/user' })
|
// 购买引力值
|
||||||
|
|
||||||
// #ifdef H5
|
|
||||||
const buyQty = ref(1)
|
const buyQty = ref(1)
|
||||||
const unitPrice = ref(500)
|
const unitPrice = ref(500)
|
||||||
const gravityPerUnit = ref(5)
|
const gravityPerUnit = ref(5)
|
||||||
const payLoading = ref(false)
|
const payLoading = ref(false)
|
||||||
|
|
||||||
|
// 支付弹窗
|
||||||
const showPayModal = ref(false)
|
const showPayModal = ref(false)
|
||||||
const payCodeUrl = ref('')
|
const payCodeUrl = ref('')
|
||||||
const paySuccess = ref(false)
|
|
||||||
const payError = ref('')
|
const payError = ref('')
|
||||||
|
const currentOutTradeNo = ref('')
|
||||||
|
const payingPlan = ref('')
|
||||||
|
const paySuccess = ref(false)
|
||||||
|
const vpStatus = ref(false)
|
||||||
|
const vpSuccess = ref(false)
|
||||||
|
const vpStatusText = ref('')
|
||||||
|
|
||||||
onMounted(async () => {
|
// 套餐特征后备值(API 取不到时使用)
|
||||||
|
const defaultFreeFeatures = ['AI 模拟面试 1 次(体验)', '基础面试报告', '通用题库随机出题', '简历优化(限 3 次免费)']
|
||||||
|
const defaultGrowthFeatures = ['免费版全部权益', 'AI 数字人面试无限次', '详细面试报告(四维评分)', '进步轨迹雷达图 + 打卡', '每日一题', '参考回答思路', '公司真题库']
|
||||||
|
const defaultSprintFeatures = ['成长版全部权益', 'AI 语音分析(语气词/语速检测)', '技能缺口分析报告', '公司真题库精选']
|
||||||
|
|
||||||
|
const token = () => uni.getStorageSync('token') || ''
|
||||||
|
|
||||||
|
const refreshState = async () => {
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
isMp.value = true
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
const t = token()
|
||||||
|
isLoggedIn.value = !!t
|
||||||
|
|
||||||
|
// 1. 先拉套餐配置(公开接口,未登录也拉)
|
||||||
try {
|
try {
|
||||||
const res = await uni.request({ url: api('/member/plans'), method: 'GET' })
|
const pres = await uni.request({ url: api('/member/plans'), method: 'GET' })
|
||||||
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.products) {
|
if (pres.statusCode >= 200 && pres.statusCode < 300 && pres.data) {
|
||||||
const prod = res.data.products.interview
|
const d = pres.data
|
||||||
if (prod) {
|
if (d.products?.interview) {
|
||||||
unitPrice.value = prod.price || 500
|
unitPrice.value = d.products.interview.price || 500
|
||||||
gravityPerUnit.value = prod.gravity || 5
|
gravityPerUnit.value = d.products.interview.gravity || 5
|
||||||
}
|
}
|
||||||
|
planList.value = buildPlanList(d.plans)
|
||||||
|
} else {
|
||||||
|
planList.value = buildPlanList(null)
|
||||||
}
|
}
|
||||||
} catch (e) { /* silent */ }
|
} catch (e) { /* silent */ }
|
||||||
})
|
|
||||||
|
|
||||||
const changeQty = (delta: number) => {
|
// 2. 用户信息需要登录
|
||||||
const next = buyQty.value + delta
|
if (!t) return
|
||||||
if (next >= 1 && next <= 99) buyQty.value = next
|
try {
|
||||||
}
|
const ures = await uni.request({ url: api('/user/info'), method: 'GET', header: { 'Authorization': `Bearer ${t}` } })
|
||||||
const clampQty = () => {
|
if (ures.statusCode >= 200 && ures.statusCode < 300 && ures.data) {
|
||||||
if (buyQty.value < 1) buyQty.value = 1
|
const u = ures.data
|
||||||
if (buyQty.value > 99) buyQty.value = 99
|
plan.value = u.plan || 'free'
|
||||||
|
gravity.value = u.gravity ?? 0
|
||||||
|
currentPlanName.value = ({ free: '免费版', growth: '成长版', sprint: '冲刺版' })[plan.value] || '免费版'
|
||||||
|
} else if (checkAuth(ures)) {
|
||||||
|
return // token 过期,已清除并跳转登录
|
||||||
|
}
|
||||||
|
} catch (e) { /* silent */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
const startPay = async () => {
|
const buildPlanList = (plans) => {
|
||||||
const token = uni.getStorageSync('token') || ''
|
const growth = plans?.find?.(p => p.id === 'growth')
|
||||||
if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
|
const sprint = plans?.find?.(p => p.id === 'sprint')
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 'free', name: '免费版', priceDisplay: '免费',
|
||||||
|
features: defaultFreeFeatures,
|
||||||
|
popular: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'growth', name: '成长版',
|
||||||
|
priceDisplay: growth ? `¥${(growth.price / 100).toFixed(1)}/月` : '¥19/月',
|
||||||
|
features: growth?.features || defaultGrowthFeatures,
|
||||||
|
popular: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sprint', name: '冲刺版',
|
||||||
|
priceDisplay: sprint ? `¥${(sprint.price / 100).toFixed(1)}/月` : '¥49/月',
|
||||||
|
features: sprint?.features || defaultSprintFeatures,
|
||||||
|
popular: false,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
onLoad(() => { /* silent */ })
|
||||||
|
onMounted(refreshState)
|
||||||
|
onShow(refreshState)
|
||||||
|
|
||||||
|
const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
|
||||||
|
|
||||||
|
const cancelPay = () => {
|
||||||
|
showPayModal.value = false
|
||||||
|
payCodeUrl.value = ''
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = ''
|
||||||
|
paySuccess.value = false
|
||||||
|
vpStatus.value = false
|
||||||
|
vpSuccess.value = false
|
||||||
|
vpStatusText.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 购买引力值 → MP 用 VP / H5 用扫码 */
|
||||||
|
const startGravityPay = async () => {
|
||||||
|
const t = token()
|
||||||
|
if (!t) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
|
||||||
|
|
||||||
showPayModal.value = true
|
showPayModal.value = true
|
||||||
payLoading.value = true
|
payLoading.value = true
|
||||||
payCodeUrl.value = ''
|
|
||||||
payError.value = ''
|
payError.value = ''
|
||||||
paySuccess.value = false
|
vpStatus.value = false
|
||||||
|
|
||||||
try {
|
if (isMp.value) {
|
||||||
const res = await uni.request({
|
// 小程序:虚拟支付 VP
|
||||||
url: api('/payment/create-product'), method: 'POST',
|
try {
|
||||||
data: { type: 'interview', quantity: buyQty.value },
|
console.log('[VP] wx.login...')
|
||||||
header: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
|
const [loginErr, loginRes] = await new Promise((resolve) => {
|
||||||
})
|
uni.login({
|
||||||
payLoading.value = false
|
provider: 'weixin',
|
||||||
|
success: r => { console.log('[VP] wx.login 成功:', JSON.stringify(r)); resolve([null, r]) },
|
||||||
|
fail: e => { console.error('[VP] wx.login 失败:', JSON.stringify(e)); resolve([e, null]) },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if (loginErr || !loginRes?.code) {
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = '微信登录失败: ' + (loginErr?.errMsg || 'no code')
|
||||||
|
console.error('[VP] login failed', loginErr, loginRes)
|
||||||
|
uni.showToast({ title: '微信登录失败', icon: 'none' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
console.log('[VP] code:', loginRes.code.slice(0, 20) + '...')
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api('/virtual-payment/create'), method: 'POST',
|
||||||
|
data: { type: 'interview', quantity: buyQty.value, wxCode: loginRes.code },
|
||||||
|
header: { 'Authorization': `Bearer ${t}`, 'Content-Type': 'application/json' },
|
||||||
|
timeout: 30000,
|
||||||
|
})
|
||||||
|
console.log('[VP] 创建订单:', res.statusCode, JSON.stringify(res.data).slice(0, 500))
|
||||||
|
payLoading.value = false
|
||||||
|
|
||||||
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.codeUrl) {
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.paySig) {
|
||||||
payCodeUrl.value = res.data.codeUrl
|
const vp = res.data
|
||||||
pollPayResult(res.data.outTradeNo)
|
currentOutTradeNo.value = vp.outTradeNo
|
||||||
} else {
|
wx.requestVirtualPayment({
|
||||||
payError.value = res.data?.message || '创建订单失败'
|
env: vp.env, mode: vp.mode, offerId: vp.offerId,
|
||||||
|
signData: vp.signData,
|
||||||
|
paySig: vp.paySig, signature: vp.signature,
|
||||||
|
success: () => {
|
||||||
|
console.log('[VP] 支付成功')
|
||||||
|
vpStatus.value = true
|
||||||
|
vpSuccess.value = true
|
||||||
|
vpStatusText.value = '引力值已到账'
|
||||||
|
uni.showToast({ title: '充值成功!', icon: 'success' })
|
||||||
|
refreshState()
|
||||||
|
},
|
||||||
|
fail: (err2) => {
|
||||||
|
console.error('[VP] 支付失败:', JSON.stringify(err2))
|
||||||
|
vpStatus.value = true
|
||||||
|
vpSuccess.value = false
|
||||||
|
vpStatusText.value = friendlyVpError(err2?.errMsg) || '你已取消支付'
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const msg = res.data?.message || res.data?.msg || `请求失败(${res.statusCode})`
|
||||||
|
if (checkAuth(res)) return
|
||||||
|
payError.value = msg
|
||||||
|
console.error('[VP] 订单创建失败:', res.statusCode, JSON.stringify(res.data))
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = '网络错误,请重试'
|
||||||
|
console.error('[VP] 异常:', e)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// H5:扫码支付
|
||||||
|
try {
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api('/payment/create-product'), method: 'POST',
|
||||||
|
data: { type: 'interview', quantity: buyQty.value },
|
||||||
|
header: { 'Authorization': `Bearer ${t}`, 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
payLoading.value = false
|
||||||
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.codeUrl) {
|
||||||
|
payCodeUrl.value = res.data.codeUrl
|
||||||
|
currentOutTradeNo.value = res.data.outTradeNo
|
||||||
|
pollPayResult(res.data.outTradeNo, 'growth')
|
||||||
|
} else {
|
||||||
|
if (checkAuth(res)) return
|
||||||
|
payError.value = res.data?.message || '创建订单失败'
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = '网络错误,请重试'
|
||||||
}
|
}
|
||||||
} catch (e) {
|
|
||||||
payLoading.value = false
|
|
||||||
payError.value = '网络错误,请重试'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const pollPayResult = (outTradeNo: string) => {
|
/** 套餐升级 → MP 用虚拟支付 VP / H5 用扫码支付 */
|
||||||
|
const startPlanPay = async (selectedPlan) => {
|
||||||
|
const t = token()
|
||||||
|
if (!t) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
|
||||||
|
|
||||||
|
payingPlan.value = selectedPlan
|
||||||
|
showPayModal.value = true
|
||||||
|
payLoading.value = true
|
||||||
|
payError.value = ''
|
||||||
|
vpStatus.value = false
|
||||||
|
|
||||||
|
if (isMp.value) {
|
||||||
|
// 小程序:虚拟支付 VP(套餐升级)
|
||||||
|
try {
|
||||||
|
console.log('[VP-plan] wx.login...')
|
||||||
|
const [loginErr, loginRes] = await new Promise((resolve) => {
|
||||||
|
uni.login({
|
||||||
|
provider: 'weixin',
|
||||||
|
success: r => { console.log('[VP-plan] wx.login 成功:', JSON.stringify(r)); resolve([null, r]) },
|
||||||
|
fail: e => { console.error('[VP-plan] wx.login 失败:', JSON.stringify(e)); resolve([e, null]) },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if (loginErr || !loginRes?.code) {
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = '微信登录失败: ' + (loginErr?.errMsg || 'no code')
|
||||||
|
console.error('[VP-plan] login failed', loginErr, loginRes)
|
||||||
|
uni.showToast({ title: '微信登录失败', icon: 'none' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
console.log('[VP-plan] code:', loginRes.code.slice(0, 20) + '...')
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api('/virtual-payment/create'), method: 'POST',
|
||||||
|
data: { type: selectedPlan, quantity: 1, wxCode: loginRes.code },
|
||||||
|
header: { 'Authorization': `Bearer ${t}`, 'Content-Type': 'application/json' },
|
||||||
|
timeout: 30000,
|
||||||
|
})
|
||||||
|
console.log('[VP-plan] 创建订单:', res.statusCode, JSON.stringify(res.data).slice(0, 500))
|
||||||
|
payLoading.value = false
|
||||||
|
|
||||||
|
if (checkAuth(res)) return
|
||||||
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.paySig) {
|
||||||
|
const vp = res.data
|
||||||
|
currentOutTradeNo.value = vp.outTradeNo
|
||||||
|
wx.requestVirtualPayment({
|
||||||
|
env: vp.env, mode: vp.mode, offerId: vp.offerId,
|
||||||
|
signData: vp.signData,
|
||||||
|
paySig: vp.paySig, signature: vp.signature,
|
||||||
|
success: () => {
|
||||||
|
console.log('[VP-plan] 支付成功')
|
||||||
|
vpStatus.value = true
|
||||||
|
vpSuccess.value = true
|
||||||
|
vpStatusText.value = '套餐已激活'
|
||||||
|
uni.showToast({ title: '开通成功!', icon: 'success' })
|
||||||
|
plan.value = selectedPlan
|
||||||
|
currentPlanName.value = selectedPlan === 'sprint' ? '冲刺版' : '成长版'
|
||||||
|
refreshState()
|
||||||
|
},
|
||||||
|
fail: (err2) => {
|
||||||
|
console.error('[VP-plan] 支付失败:', JSON.stringify(err2))
|
||||||
|
vpStatus.value = true
|
||||||
|
vpSuccess.value = false
|
||||||
|
vpStatusText.value = friendlyVpError(err2?.errMsg) || '你已取消支付'
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const msg = res.data?.message || res.data?.msg || `请求失败(${res.statusCode})`
|
||||||
|
payError.value = msg
|
||||||
|
console.error('[VP-plan] 订单创建失败:', res.statusCode, JSON.stringify(res.data))
|
||||||
|
uni.showToast({ title: msg, icon: 'none' })
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = '网络错误,请重试'
|
||||||
|
console.error('[VP-plan] 异常:', e)
|
||||||
|
uni.showToast({ title: '网络错误', icon: 'none' })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api('/payment/create'), method: 'POST',
|
||||||
|
data: { plan: selectedPlan },
|
||||||
|
header: { 'Authorization': `Bearer ${t}`, 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
payLoading.value = false
|
||||||
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.codeUrl) {
|
||||||
|
payCodeUrl.value = res.data.codeUrl
|
||||||
|
currentOutTradeNo.value = res.data.outTradeNo
|
||||||
|
pollPayResult(res.data.outTradeNo, selectedPlan)
|
||||||
|
} else {
|
||||||
|
if (checkAuth(res)) return
|
||||||
|
payError.value = res.data?.message || '创建订单失败'
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
payLoading.value = false
|
||||||
|
payError.value = '网络错误,请重试'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 轮询订单状态 */
|
||||||
|
const pollPayResult = (outTradeNo, selectedPlan) => {
|
||||||
if (!outTradeNo) return
|
if (!outTradeNo) return
|
||||||
const token = uni.getStorageSync('token') || ''
|
|
||||||
let attempts = 0
|
let attempts = 0
|
||||||
const poll = async () => {
|
const poll = async () => {
|
||||||
attempts++
|
attempts++
|
||||||
try {
|
try {
|
||||||
const res = await uni.request({
|
const res = await uni.request({
|
||||||
url: api(`/payment/check/${outTradeNo}`), method: 'GET',
|
url: api(`/payment/check/${outTradeNo}`), method: 'GET',
|
||||||
header: { 'Authorization': `Bearer ${token}` },
|
header: { 'Authorization': `Bearer ${token()}` },
|
||||||
})
|
})
|
||||||
|
if (checkAuth(res)) return
|
||||||
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.status === 'success') {
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.status === 'success') {
|
||||||
paySuccess.value = true
|
await activatePlan(outTradeNo, selectedPlan)
|
||||||
payCodeUrl.value = ''
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} catch (e) { /* ignore */ }
|
} catch (e) { /* ignore */ }
|
||||||
if (attempts < 30) setTimeout(poll, 2000)
|
if (attempts < 30) setTimeout(poll, 2000)
|
||||||
|
else { payError.value = '支付结果查询超时,请联系客服' }
|
||||||
}
|
}
|
||||||
setTimeout(poll, 2000)
|
setTimeout(poll, 2000)
|
||||||
}
|
}
|
||||||
|
|
||||||
const cancelPay = () => {
|
/** 激活套餐 */
|
||||||
showPayModal.value = false
|
const activatePlan = async (outTradeNo, selectedPlan) => {
|
||||||
payCodeUrl.value = ''
|
try {
|
||||||
payError.value = ''
|
const res = await uni.request({
|
||||||
payLoading.value = false
|
url: api('/payment/activate'), method: 'POST',
|
||||||
|
data: { outTradeNo },
|
||||||
|
header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.success) {
|
||||||
|
paySuccess.value = true
|
||||||
|
showPayModal.value = false
|
||||||
|
plan.value = selectedPlan
|
||||||
|
currentPlanName.value = selectedPlan === 'sprint' ? '冲刺版' : '成长版'
|
||||||
|
uni.showToast({ title: '🎉 开通成功!', icon: 'success' })
|
||||||
|
refreshState()
|
||||||
|
} else {
|
||||||
|
if (checkAuth(res)) return
|
||||||
|
uni.showToast({ title: res.data?.message || '激活失败', icon: 'none' })
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
payError.value = '激活失败,请联系客服'
|
||||||
|
uni.showToast({ title: '激活失败', icon: 'none' })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// #endif
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.page { min-height: 100vh; background: var(--color-bg); }
|
.page { min-height: 100vh; background: var(--color-bg); padding-bottom: 40rpx; }
|
||||||
.placeholder-wrap { display: flex; flex-direction: column; align-items: center; gap: 16rpx; padding: 80rpx 40rpx; }
|
|
||||||
.placeholder-icon { font-size: 80rpx; }
|
|
||||||
.placeholder-text { font-size: 30rpx; font-weight: 600; color: var(--color-text); }
|
|
||||||
.placeholder-hint { font-size: 24rpx; color: var(--color-text-tertiary); }
|
|
||||||
.placeholder-back { font-size: 26rpx; color: var(--color-primary); padding: 16rpx 40rpx; border-radius: var(--radius-md); background: #F3F4F6; margin-top: 24rpx; }
|
|
||||||
|
|
||||||
/* H5 购买页 */
|
/* 状态栏 */
|
||||||
.hero { display: flex; flex-direction: column; align-items: center; padding: 48rpx 32rpx 24rpx; }
|
.status-bar { display: flex; justify-content: space-between; align-items: center; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); padding: 32rpx; color: #fff; }
|
||||||
.hero-icon { font-size: 72rpx; }
|
.status-left { display: flex; flex-direction: column; gap: 4rpx; }
|
||||||
.hero-title { font-size: 36rpx; font-weight: 700; color: var(--color-text); margin-top: 12rpx; }
|
.status-label { font-size: 22rpx; opacity: 0.85; }
|
||||||
.hero-desc { font-size: 24rpx; color: var(--color-text-secondary); margin-top: 8rpx; text-align: center; }
|
.status-plan { font-size: 34rpx; font-weight: 700; }
|
||||||
|
.status-right { display: flex; flex-direction: column; align-items: flex-end; gap: 4rpx; }
|
||||||
|
.grav-label { font-size: 22rpx; opacity: 0.85; }
|
||||||
|
.grav-num { font-size: 40rpx; font-weight: 800; }
|
||||||
|
|
||||||
.product-card { background: #fff; border-radius: var(--radius-lg); margin: 0 32rpx; padding: 32rpx; box-shadow: var(--shadow-sm); }
|
/* 登录提示 */
|
||||||
|
.login-bar { display: flex; align-items: center; justify-content: space-between; margin: 24rpx 24rpx 0; background: #FEF3C7; border-radius: var(--radius-lg); padding: 20rpx 24rpx; }
|
||||||
|
.login-text { font-size: 24rpx; color: #92400E; }
|
||||||
|
.login-btn { font-size: 24rpx; color: #FFF; background: var(--color-primary); padding: 8rpx 24rpx; border-radius: var(--radius-sm); }
|
||||||
|
|
||||||
.qty-section { margin-bottom: 24rpx; }
|
/* 区块 */
|
||||||
.section-label { font-size: 26rpx; font-weight: 600; color: var(--color-text); display: block; margin-bottom: 16rpx; }
|
.section { padding: 0 24rpx; margin-top: 24rpx; }
|
||||||
|
.section-title { font-size: 28rpx; font-weight: 700; color: var(--color-text); display: block; margin-bottom: 16rpx; }
|
||||||
|
|
||||||
|
/* 购买区 */
|
||||||
|
.buy-card { background: #fff; border-radius: var(--radius-lg); padding: 24rpx; box-shadow: var(--shadow-sm); }
|
||||||
|
.qty-row { margin-bottom: 16rpx; }
|
||||||
|
.qty-label { font-size: 24rpx; font-weight: 600; color: var(--color-text); display: block; margin-bottom: 12rpx; }
|
||||||
.qty-controls { display: flex; align-items: center; justify-content: center; gap: 24rpx; }
|
.qty-controls { display: flex; align-items: center; justify-content: center; gap: 24rpx; }
|
||||||
.qty-btn { width: 64rpx; height: 64rpx; border-radius: 50%; background: #F3F4F6; display: flex; align-items: center; justify-content: center; font-size: 36rpx; font-weight: 500; color: var(--color-text); }
|
.qty-btn { width: 60rpx; height: 60rpx; border-radius: 50%; background: #F3F4F6; display: flex; align-items: center; justify-content: center; font-size: 32rpx; font-weight: 500; color: var(--color-text); }
|
||||||
.qty-btn.disabled { color: #D1D5DB; background: #F9FAFB; }
|
.qty-btn.disabled { color: #D1D5DB; background: #F9FAFB; }
|
||||||
.qty-input { width: 120rpx; height: 72rpx; text-align: center; font-size: 36rpx; font-weight: 700; color: var(--color-text); border: 2rpx solid #E5E7EB; border-radius: var(--radius-sm); }
|
.qty-input { width: 120rpx; height: 64rpx; text-align: center; font-size: 32rpx; font-weight: 700; color: var(--color-text); border: 2rpx solid #E5E7EB; border-radius: var(--radius-sm); }
|
||||||
|
.summary { margin-bottom: 20rpx; }
|
||||||
.summary { margin-bottom: 32rpx; }
|
.summary-row { display: flex; justify-content: space-between; padding: 8rpx 0; border-bottom: 1rpx solid #F3F4F6; }
|
||||||
.summary-row { display: flex; justify-content: space-between; padding: 12rpx 0; border-bottom: 1rpx solid #F3F4F6; }
|
.summary-row.total { border-bottom: none; padding-top: 12rpx; }
|
||||||
.summary-row.total { border-bottom: none; padding-top: 16rpx; }
|
.summary-label { font-size: 22rpx; color: var(--color-text-secondary); }
|
||||||
.summary-label { font-size: 24rpx; color: var(--color-text-secondary); }
|
.summary-val { font-size: 24rpx; font-weight: 600; color: var(--color-text); }
|
||||||
.summary-val { font-size: 26rpx; font-weight: 600; color: var(--color-text); }
|
|
||||||
.summary-val.highlight { color: var(--color-primary); }
|
.summary-val.highlight { color: var(--color-primary); }
|
||||||
.total-price { font-size: 36rpx; font-weight: 800; color: var(--color-primary); }
|
.total-price { font-size: 32rpx; font-weight: 800; color: var(--color-primary); }
|
||||||
|
.buy-btn { width: 100%; height: 80rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #fff; font-size: 28rpx; font-weight: 600; border-radius: var(--radius-lg); display: flex; align-items: center; justify-content: center; border: none; }
|
||||||
.buy-btn { width: 100%; height: 88rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #fff; font-size: 30rpx; font-weight: 600; border-radius: var(--radius-lg); display: flex; align-items: center; justify-content: center; border: none; }
|
.buy-btn:active { opacity: 0.85; }
|
||||||
.buy-btn:active { opacity: 0.85; transform: scale(0.98); }
|
|
||||||
.buy-btn[disabled] { opacity: 0.5; }
|
.buy-btn[disabled] { opacity: 0.5; }
|
||||||
|
|
||||||
/* 支付弹窗 */
|
/* 套餐列表 */
|
||||||
|
.plan-list { display: flex; flex-direction: column; gap: 16rpx; }
|
||||||
|
.plan-card { background: #fff; border-radius: var(--radius-lg); padding: 24rpx; box-shadow: var(--shadow-sm); position: relative; }
|
||||||
|
.plan-card.popular { border: 2rpx solid var(--color-primary); }
|
||||||
|
.plan-card.current { background: #F0F7FF; border: 2rpx solid var(--color-primary); }
|
||||||
|
.plan-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 12rpx; }
|
||||||
|
.plan-name { font-size: 30rpx; font-weight: 700; color: var(--color-text); }
|
||||||
|
.price-num { font-size: 32rpx; font-weight: 800; color: var(--color-primary); }
|
||||||
|
.plan-badge { background: var(--color-primary); color: #fff; font-size: 20rpx; padding: 4rpx 14rpx; border-radius: 20rpx; }
|
||||||
|
.plan-features { display: flex; flex-direction: column; gap: 8rpx; margin-bottom: 16rpx; }
|
||||||
|
.feature { font-size: 22rpx; color: var(--color-text-secondary); }
|
||||||
|
.plan-action { text-align: center; padding: 16rpx; border-radius: var(--radius-md); font-size: 26rpx; font-weight: 600; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #fff; }
|
||||||
|
.plan-action.owned { background: #ECFDF5; color: var(--color-success); }
|
||||||
|
|
||||||
|
/* 弹窗 */
|
||||||
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 100; }
|
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 100; }
|
||||||
.modal-content { background: #FFF; border-radius: var(--radius-xl); padding: 40rpx 32rpx; width: 600rpx; display: flex; flex-direction: column; align-items: center; gap: 16rpx; }
|
.modal-content { background: #FFF; border-radius: var(--radius-xl); padding: 40rpx; width: 70%; display: flex; flex-direction: column; align-items: center; gap: 20rpx; }
|
||||||
.modal-title { font-size: 30rpx; font-weight: 700; color: var(--color-text); }
|
.modal-title { font-size: 28rpx; font-weight: 600; color: var(--color-text); }
|
||||||
.pay-error { color: var(--color-error); }
|
.pay-error { color: var(--color-error); }
|
||||||
.modal-hint { font-size: 22rpx; color: #6B7280; text-align: center; }
|
.qr-canvas { width: 400rpx; height: 400rpx; }
|
||||||
.modal-close { font-size: 24rpx; color: #9CA3AF; padding: 12rpx 24rpx; }
|
.modal-hint { font-size: 22rpx; color: var(--color-text-tertiary); }
|
||||||
.qrcode { width: 300rpx; height: 300rpx; margin: 8rpx 0; }
|
.modal-close { font-size: 22rpx; color: var(--color-text-tertiary); padding: 8rpx; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -178,20 +178,22 @@ async function loadData() {
|
|||||||
if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
|
if (!token) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
|
||||||
const header = { Authorization: `Bearer ${token}` }
|
const header = { Authorization: `Bearer ${token}` }
|
||||||
|
|
||||||
// 先创建分享链接,缓存下来供复制使用
|
// 仅在无缓存分享链接时创建新分享记录
|
||||||
try {
|
if (!shareUrlCached.value) {
|
||||||
const res = await uni.request({
|
try {
|
||||||
url: api('/share/create'), method: 'POST',
|
const res = await uni.request({
|
||||||
data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化,快来一起提升吧' },
|
url: api('/share/create'), method: 'POST',
|
||||||
header,
|
data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化,快来一起提升吧' },
|
||||||
})
|
header,
|
||||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
})
|
||||||
const data = res.data?.data || res.data
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||||
if (data.shareCode) {
|
const data = res.data?.data || res.data
|
||||||
shareUrlCached.value = `https://zhiyinwx.yzrcloud.cn/api/share/${data.shareCode}`
|
if (data.shareCode) {
|
||||||
|
shareUrlCached.value = `https://zhiyinwx.yzrcloud.cn/api/share/${data.shareCode}`
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (e) { /* create share is best-effort */ }
|
||||||
} catch (e) { /* create share is best-effort */ }
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const [statsRes, recordsRes, visitorsRes] = await Promise.all([
|
const [statsRes, recordsRes, visitorsRes] = await Promise.all([
|
||||||
|
|||||||
@@ -49,11 +49,12 @@
|
|||||||
</view>
|
</view>
|
||||||
<text class="gravity-num">{{ memberInfo.gravity ?? 0 }}</text>
|
<text class="gravity-num">{{ memberInfo.gravity ?? 0 }}</text>
|
||||||
</view>
|
</view>
|
||||||
<text class="gravity-hint">每次面试消耗 5 引力值 · 分享可获得更多</text>
|
<text class="gravity-hint">每次面试消耗 5 引力值 · 分享好友、贡献面经可获得更多</text>
|
||||||
<view class="gravity-actions">
|
<view class="gravity-actions">
|
||||||
<text class="gravity-btn share" @click="goSharePage">分享得引力值</text>
|
<text class="gravity-btn share" @click="goSharePage">分享得引力值</text>
|
||||||
<text class="gravity-btn contribute" @click="goContributePage">贡献面经</text>
|
<text class="gravity-btn contribute" @click="goContributePage">贡献面经</text>
|
||||||
<text class="gravity-btn h5buy" @click="goH5Buy">官网购买</text>
|
<text class="gravity-btn h5buy" @click="goH5Buy">购买引力值</text>
|
||||||
|
<text class="gravity-btn detail" @click="showGravityDetail = true">明细</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -77,14 +78,11 @@
|
|||||||
<text class="menu-text">面试复盘</text>
|
<text class="menu-text">面试复盘</text>
|
||||||
<text class="menu-arrow">›</text>
|
<text class="menu-arrow">›</text>
|
||||||
</view>
|
</view>
|
||||||
<!-- 会员中心菜单注释隐藏(微信审核) -->
|
|
||||||
<!--
|
|
||||||
<view class="menu-item" @click="goVip">
|
<view class="menu-item" @click="goVip">
|
||||||
<view class="menu-icon-wrap wrap-purple"><text class="menu-icon">💎</text></view>
|
<view class="menu-icon-wrap wrap-purple"><text class="menu-icon">💎</text></view>
|
||||||
<text class="menu-text">会员中心</text>
|
<text class="menu-text">会员中心</text>
|
||||||
<text class="menu-arrow">›</text>
|
<text class="menu-arrow">›</text>
|
||||||
</view>
|
</view>
|
||||||
-->
|
|
||||||
<view class="menu-item" @click="requireLogin(goResume, '我的简历')">
|
<view class="menu-item" @click="requireLogin(goResume, '我的简历')">
|
||||||
<view class="menu-icon-wrap wrap-green"><text class="menu-icon">📄</text></view>
|
<view class="menu-icon-wrap wrap-green"><text class="menu-icon">📄</text></view>
|
||||||
<text class="menu-text">我的简历</text>
|
<text class="menu-text">我的简历</text>
|
||||||
@@ -106,6 +104,11 @@
|
|||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
<!-- #endif -->
|
<!-- #endif -->
|
||||||
|
<view class="menu-item" @click="goFeedback">
|
||||||
|
<view class="menu-icon-wrap wrap-gray"><text class="menu-icon">📝</text></view>
|
||||||
|
<text class="menu-text">意见反馈</text>
|
||||||
|
<text class="menu-arrow">›</text>
|
||||||
|
</view>
|
||||||
<view class="menu-item" @click="goAbout">
|
<view class="menu-item" @click="goAbout">
|
||||||
<view class="menu-icon-wrap wrap-gray"><text class="menu-icon">ℹ️</text></view>
|
<view class="menu-icon-wrap wrap-gray"><text class="menu-icon">ℹ️</text></view>
|
||||||
<text class="menu-text">关于</text>
|
<text class="menu-text">关于</text>
|
||||||
@@ -148,12 +151,12 @@
|
|||||||
<text class="gp-method-arrow">›</text>
|
<text class="gp-method-arrow">›</text>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<!-- 官网购买 -->
|
<!-- 购买引力值 -->
|
||||||
<view class="gp-get-method" @click="goH5Buy">
|
<view class="gp-get-method" @click="goH5Buy">
|
||||||
<view class="gp-method-icon-wrap"><text class="gp-method-icon">🛒</text></view>
|
<view class="gp-method-icon-wrap"><text class="gp-method-icon">🛒</text></view>
|
||||||
<view class="gp-method-info">
|
<view class="gp-method-info">
|
||||||
<text class="gp-method-name">官网购买</text>
|
<text class="gp-method-name">购买引力值</text>
|
||||||
<text class="gp-method-desc">通过官网网页端可购买引力值套餐,支持更多支付方式</text>
|
<text class="gp-method-desc">¥5 一份,微信支付安全便捷</text>
|
||||||
</view>
|
</view>
|
||||||
<text class="gp-method-arrow">›</text>
|
<text class="gp-method-arrow">›</text>
|
||||||
</view>
|
</view>
|
||||||
@@ -161,11 +164,40 @@
|
|||||||
<text class="modal-close" @click="showGetGravityModal = false">关闭</text>
|
<text class="modal-close" @click="showGetGravityModal = false">关闭</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
|
<!-- 引力值明细 -->
|
||||||
|
<view class="modal-overlay" v-if="showGravityDetail" @click="showGravityDetail = false">
|
||||||
|
<view class="modal-content detail-content" @click.stop>
|
||||||
|
<text class="modal-title">引力值明细</text>
|
||||||
|
<text class="modal-hint">购买、消耗、补给的引力值变动记录</text>
|
||||||
|
<scroll-view class="detail-list" scroll-y>
|
||||||
|
<view v-if="gravityTxs.length === 0" class="detail-empty">暂无记录</view>
|
||||||
|
<view v-for="tx in gravityTxs" :key="tx._id" class="detail-item">
|
||||||
|
<view class="detail-item-left">
|
||||||
|
<text class="detail-item-desc">{{ tx.description }}</text>
|
||||||
|
<text class="detail-item-time">{{ formatTime(tx.createdAt) }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="detail-item-right">
|
||||||
|
<text :class="['detail-item-amount', tx.amount > 0 ? 'amount-positive' : 'amount-negative']">
|
||||||
|
{{ tx.amount > 0 ? '+' : '' }}{{ tx.amount }}
|
||||||
|
</text>
|
||||||
|
<text class="detail-item-balance">余额 {{ tx.balance }}</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</scroll-view>
|
||||||
|
<view v-if="gravityTxTotalPages > 1" class="detail-pagination">
|
||||||
|
<text class="detail-page-btn" @click="loadGravityTxs(gravityTxPage - 1)" v-if="gravityTxPage > 1">上一页</text>
|
||||||
|
<text class="detail-page-info">{{ gravityTxPage }} / {{ gravityTxTotalPages }}</text>
|
||||||
|
<text class="detail-page-btn" @click="loadGravityTxs(gravityTxPage + 1)" v-if="gravityTxPage < gravityTxTotalPages">下一页</text>
|
||||||
|
</view>
|
||||||
|
<text class="modal-close" @click="showGravityDetail = false">关闭</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, computed, onMounted } from 'vue'
|
import { ref, computed, watch, onMounted } from 'vue'
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
|
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
|
||||||
// #endif
|
// #endif
|
||||||
@@ -173,9 +205,16 @@ import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
|
|||||||
import { onShow } from '@dcloudio/uni-app'
|
import { onShow } from '@dcloudio/uni-app'
|
||||||
// #endif
|
// #endif
|
||||||
import { api } from '../../config'
|
import { api } from '../../config'
|
||||||
|
import { checkAuth } from '../../utils/auth'
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
onShareAppMessage(() => ({ title: '职引 - 个人中心 | AI模拟面试', path: '/pages/user/user' }))
|
const shareCodeRef = ref('')
|
||||||
|
onShareAppMessage(() => {
|
||||||
|
const path = shareCodeRef.value
|
||||||
|
? `/pages/user/user?share=${shareCodeRef.value}`
|
||||||
|
: '/pages/user/user'
|
||||||
|
return { title: '职引 - 个人中心 | AI模拟面试', path }
|
||||||
|
})
|
||||||
onShareTimeline(() => ({ title: '职引 - 个人中心 | AI模拟面试' }))
|
onShareTimeline(() => ({ title: '职引 - 个人中心 | AI模拟面试' }))
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
@@ -199,14 +238,40 @@ const refreshState = () => {
|
|||||||
loadMemberStatus()
|
loadMemberStatus()
|
||||||
checkAdmin()
|
checkAdmin()
|
||||||
fetchUserInfo()
|
fetchUserInfo()
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
preCreateShare()
|
||||||
|
// #endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
async function preCreateShare() {
|
||||||
|
if (shareCodeRef.value) return // already have one
|
||||||
|
try {
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api('/share/create'), method: 'POST',
|
||||||
|
data: { type: 'app', title: '我在AI磁场·职引练习面试', description: 'AI模拟面试+简历优化,快来一起提升吧' },
|
||||||
|
header: { Authorization: `Bearer ${token.value}` },
|
||||||
|
})
|
||||||
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||||
|
checkAuth(res)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const data = res.data?.data || res.data
|
||||||
|
if (data.shareCode) {
|
||||||
|
shareCodeRef.value = data.shareCode
|
||||||
|
}
|
||||||
|
} catch(e) { /* silent */ }
|
||||||
|
}
|
||||||
|
// #endif
|
||||||
|
|
||||||
const fetchUserInfo = async () => {
|
const fetchUserInfo = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await uni.request({ url: api('/user/info'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
|
const res = await uni.request({ url: api('/user/info'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
|
||||||
if (res.statusCode === 200 && res.data) {
|
if (res.statusCode === 200 && res.data) {
|
||||||
userInfo.value = res.data
|
userInfo.value = res.data
|
||||||
uni.setStorageSync('userInfo', JSON.stringify(res.data))
|
uni.setStorageSync('userInfo', JSON.stringify(res.data))
|
||||||
|
} else if (checkAuth(res)) {
|
||||||
|
return // token 过期,已清除并跳转登录
|
||||||
}
|
}
|
||||||
} catch(e) { /* silent */ }
|
} catch(e) { /* silent */ }
|
||||||
}
|
}
|
||||||
@@ -220,6 +285,8 @@ const loadMemberStatus = async () => {
|
|||||||
const res = await uni.request({ url: api('/member/status'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
|
const res = await uni.request({ url: api('/member/status'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
|
||||||
if (res.statusCode >= 200 && res.statusCode < 300 && res.data) {
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data) {
|
||||||
memberInfo.value = { plan: res.data.plan || 'free', planName: res.data.planName || '免费版', remaining: res.data.remaining ?? 0, gravity: res.data.gravity ?? 0 }
|
memberInfo.value = { plan: res.data.plan || 'free', planName: res.data.planName || '免费版', remaining: res.data.remaining ?? 0, gravity: res.data.gravity ?? 0 }
|
||||||
|
} else if (checkAuth(res)) {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
} catch(e) { /* silent */ }
|
} catch(e) { /* silent */ }
|
||||||
}
|
}
|
||||||
@@ -227,7 +294,11 @@ const loadMemberStatus = async () => {
|
|||||||
const loadStats = async () => {
|
const loadStats = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await uni.request({ url: api('/interview/stats/mine'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
|
const res = await uni.request({ url: api('/interview/stats/mine'), method: 'GET', header: { 'Authorization': `Bearer ${token.value}` } })
|
||||||
if (res.statusCode === 200) stats.value = res.data
|
if (res.statusCode === 200) {
|
||||||
|
stats.value = res.data
|
||||||
|
} else if (checkAuth(res)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
} catch(e) { console.error(e) }
|
} catch(e) { console.error(e) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,24 +322,39 @@ const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })
|
|||||||
const showGetGravityModal = ref(false)
|
const showGetGravityModal = ref(false)
|
||||||
const openBuyModal = () => { showGetGravityModal.value = true }
|
const openBuyModal = () => { showGetGravityModal.value = true }
|
||||||
const goH5Buy = () => {
|
const goH5Buy = () => {
|
||||||
const token = uni.getStorageSync('token') || ''
|
|
||||||
const url = `https://zhiyin.yzrcloud.cn/?buy=gravity${token ? '&token=' + token : ''}`
|
|
||||||
// #ifdef H5
|
|
||||||
uni.navigateTo({ url: '/pages/member/member' })
|
uni.navigateTo({ url: '/pages/member/member' })
|
||||||
// #endif
|
|
||||||
// #ifdef MP-WEIXIN
|
|
||||||
uni.setClipboardData({
|
|
||||||
data: url,
|
|
||||||
success: () => {
|
|
||||||
uni.showToast({ title: '链接已复制,请在手机浏览器中打开', icon: 'none', duration: 3000 })
|
|
||||||
},
|
|
||||||
fail: () => {
|
|
||||||
uni.showToast({ title: '复制失败,请手动访问 zhiyin.yzrcloud.cn', icon: 'none', duration: 3000 })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
// #endif
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 引力值明细
|
||||||
|
const showGravityDetail = ref(false)
|
||||||
|
const gravityTxs = ref([])
|
||||||
|
const gravityTxPage = ref(1)
|
||||||
|
const gravityTxTotalPages = ref(1)
|
||||||
|
const loadGravityTxs = async (page = 1) => {
|
||||||
|
try {
|
||||||
|
const res = await uni.request({
|
||||||
|
url: api(`/user/gravity-transactions?page=${page}&limit=20`),
|
||||||
|
method: 'GET',
|
||||||
|
header: { Authorization: `Bearer ${token.value}` },
|
||||||
|
})
|
||||||
|
if (res.statusCode >= 200 && res.statusCode < 300 && res.data) {
|
||||||
|
gravityTxs.value = res.data.items || []
|
||||||
|
gravityTxPage.value = res.data.page || 1
|
||||||
|
gravityTxTotalPages.value = res.data.totalPages || 1
|
||||||
|
} else if (checkAuth(res)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} catch(e) { /* silent */ }
|
||||||
|
}
|
||||||
|
const 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')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 点击明细时打开弹窗并加载数据
|
||||||
|
watch(showGravityDetail, (v) => { if (v) loadGravityTxs() })
|
||||||
|
|
||||||
const goCareer = () => uni.navigateTo({ url: '/pages/career/career' })
|
const goCareer = () => uni.navigateTo({ url: '/pages/career/career' })
|
||||||
const goHistory = () => uni.switchTab({ url: '/pages/history/history' })
|
const goHistory = () => uni.switchTab({ url: '/pages/history/history' })
|
||||||
const goReviewReview = () => uni.navigateTo({ url: '/pages/review/review' })
|
const goReviewReview = () => uni.navigateTo({ url: '/pages/review/review' })
|
||||||
@@ -277,6 +363,7 @@ const goResume = () => uni.navigateTo({ url: '/pages/resume/resume' })
|
|||||||
const goSharePage = () => uni.navigateTo({ url: '/pages/share/share' })
|
const goSharePage = () => uni.navigateTo({ url: '/pages/share/share' })
|
||||||
const goContributePage = () => uni.navigateTo({ url: '/pages/contribute/contribute' })
|
const goContributePage = () => uni.navigateTo({ url: '/pages/contribute/contribute' })
|
||||||
const goAdmin = () => uni.navigateTo({ url: '/pages/admin/admin' })
|
const goAdmin = () => uni.navigateTo({ url: '/pages/admin/admin' })
|
||||||
|
const goFeedback = () => uni.navigateTo({ url: '/pages/feedback/feedback' })
|
||||||
const goAbout = () => uni.navigateTo({ url: '/pages/about/about' })
|
const goAbout = () => uni.navigateTo({ url: '/pages/about/about' })
|
||||||
|
|
||||||
const doLogout = () => {
|
const doLogout = () => {
|
||||||
@@ -336,6 +423,7 @@ const doLogout = () => {
|
|||||||
.gravity-btn.share { background: rgba(255,255,255,0.2); color: #FFFFFF; border: 2rpx solid rgba(255,255,255,0.3); }
|
.gravity-btn.share { background: rgba(255,255,255,0.2); color: #FFFFFF; border: 2rpx solid rgba(255,255,255,0.3); }
|
||||||
.gravity-btn.h5buy { background: #FFFFFF; color: #667eea; }
|
.gravity-btn.h5buy { background: #FFFFFF; color: #667eea; }
|
||||||
.gravity-btn.contribute { background: rgba(255,255,255,0.15); color: #FFFFFF; border: 2rpx solid rgba(255,255,255,0.2); }
|
.gravity-btn.contribute { background: rgba(255,255,255,0.15); color: #FFFFFF; border: 2rpx solid rgba(255,255,255,0.2); }
|
||||||
|
.gravity-btn.detail { background: rgba(255,255,255,0.15); color: #FFFFFF; border: 2rpx solid rgba(255,255,255,0.2); font-size: 22rpx; padding: 18rpx 16rpx; flex: 0.5; }
|
||||||
.gravity-btn:active { transform: scale(0.96); }
|
.gravity-btn:active { transform: scale(0.96); }
|
||||||
|
|
||||||
.menu-area { padding: 0 32rpx 32rpx; margin-top: 8rpx; }
|
.menu-area { padding: 0 32rpx 32rpx; margin-top: 8rpx; }
|
||||||
@@ -383,4 +471,23 @@ const doLogout = () => {
|
|||||||
.gp-method-name { font-size: 26rpx; font-weight: 600; color: var(--color-text); }
|
.gp-method-name { font-size: 26rpx; font-weight: 600; color: var(--color-text); }
|
||||||
.gp-method-desc { font-size: 20rpx; color: #6B7280; line-height: 1.4; }
|
.gp-method-desc { font-size: 20rpx; color: #6B7280; line-height: 1.4; }
|
||||||
.gp-method-arrow { font-size: 32rpx; color: #D1D5DB; }
|
.gp-method-arrow { font-size: 32rpx; color: #D1D5DB; }
|
||||||
|
|
||||||
|
/* 引力值明细弹窗 */
|
||||||
|
.detail-content { width: 650rpx; max-height: 70vh; }
|
||||||
|
.detail-list { width: 100%; max-height: 500rpx; }
|
||||||
|
.detail-empty { text-align: center; padding: 40rpx 0; font-size: 24rpx; color: #9CA3AF; }
|
||||||
|
.detail-item { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 20rpx 0; border-bottom: 1rpx solid #F3F4F6; }
|
||||||
|
.detail-item:last-child { border-bottom: none; }
|
||||||
|
.detail-item-left { display: flex; flex-direction: column; gap: 4rpx; flex: 1; min-width: 0; }
|
||||||
|
.detail-item-desc { font-size: 26rpx; color: var(--color-text); font-weight: 500; }
|
||||||
|
.detail-item-time { font-size: 20rpx; color: #9CA3AF; }
|
||||||
|
.detail-item-amount { font-size: 30rpx; font-weight: 700; }
|
||||||
|
.detail-item-right { display: flex; flex-direction: column; align-items: flex-end; gap: 4rpx; flex-shrink: 0; margin-left: 16rpx; }
|
||||||
|
.detail-item-balance { font-size: 20rpx; color: #9CA3AF; font-weight: 400; }
|
||||||
|
.amount-positive { color: #10B981; }
|
||||||
|
.amount-negative { color: #EF4444; }
|
||||||
|
.detail-pagination { display: flex; align-items: center; justify-content: center; gap: 24rpx; width: 100%; margin-top: 8rpx; }
|
||||||
|
.detail-page-btn { font-size: 24rpx; color: var(--color-primary); padding: 8rpx 16rpx; }
|
||||||
|
.detail-page-btn:active { opacity: 0.6; }
|
||||||
|
.detail-page-info { font-size: 24rpx; color: #6B7280; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -105,6 +105,12 @@ const apiService = {
|
|||||||
request(API_ENDPOINTS.CAREER.CHAT, 'POST', { message, history }, true),
|
request(API_ENDPOINTS.CAREER.CHAT, 'POST', { message, history }, true),
|
||||||
positions: () => request(API_ENDPOINTS.CAREER.POSITIONS, 'GET', undefined, true),
|
positions: () => request(API_ENDPOINTS.CAREER.POSITIONS, 'GET', undefined, true),
|
||||||
},
|
},
|
||||||
|
virtualPayment: {
|
||||||
|
create: (data: { type: string; quantity: number; wxCode: string }) =>
|
||||||
|
request(API_ENDPOINTS.VIRTUAL_PAYMENT.CREATE, 'POST', data, true),
|
||||||
|
check: (outTradeNo: string) =>
|
||||||
|
request(API_ENDPOINTS.VIRTUAL_PAYMENT.CHECK(outTradeNo), 'GET', undefined, true),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
export default apiService
|
export default apiService
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
/**
|
||||||
|
* 清除登录状态 —— token 过期 / 未授权时调用
|
||||||
|
*/
|
||||||
|
export function clearAuth() {
|
||||||
|
uni.removeStorageSync('token')
|
||||||
|
uni.removeStorageSync('userInfo')
|
||||||
|
uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' })
|
||||||
|
// 延迟跳转,避免和当前页面操作冲突
|
||||||
|
setTimeout(() => {
|
||||||
|
uni.navigateTo({ url: '/pages/login/login' })
|
||||||
|
}, 800)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查 uni.request 的响应是否为 401,是则自动清除登录态
|
||||||
|
* 返回 true 表示已处理 401(调用方应停止后续逻辑)
|
||||||
|
*/
|
||||||
|
export function checkAuth(res: any): boolean {
|
||||||
|
if (res.statusCode === 401) {
|
||||||
|
clearAuth()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 微信虚拟支付(VP)错误消息 → 用户友好中文提示
|
||||||
|
* 覆盖 wx.requestVirtualPayment fail 回调中的常见错误码
|
||||||
|
*/
|
||||||
|
export function friendlyVpError(errMsg: string): string {
|
||||||
|
if (!errMsg) return '支付失败,请重试'
|
||||||
|
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
'pay cancel': '你已取消支付',
|
||||||
|
'cancel': '你已取消支付',
|
||||||
|
'access denied': '支付权限不足,请联系客服',
|
||||||
|
'商户收款功能受限': '商户暂不支持收款,请联系客服',
|
||||||
|
'PRODUCT_ID_EMPTY': '商品信息错误',
|
||||||
|
'PRODUCT_NOT_EXIST': '商品不存在',
|
||||||
|
'PRODUCT_NOT_ONLINE': '商品未上架',
|
||||||
|
'PAY_SIG_INVALID': '支付签名异常,请重试',
|
||||||
|
'SIGNATURE_INVALID': '支付验证失败,请重试',
|
||||||
|
'BALANCE_NOT_ENOUGH': '余额不足',
|
||||||
|
'ORDER_NOT_EXIST': '订单不存在',
|
||||||
|
'ORDER_EXPIRED': '订单已过期,请重新下单',
|
||||||
|
'ORDER_PAYED': '订单已支付',
|
||||||
|
'ORDER_CANCELED': '订单已取消',
|
||||||
|
'PRICE_NOT_MATCH': '价格异常,请联系客服',
|
||||||
|
'TOKEN_NOT_EXIST': '登录态失效,请重新登录',
|
||||||
|
'TOKEN_EXPIRED': '登录态已过期,请重新登录',
|
||||||
|
'TOKEN_NOT_MATCH': '登录态不匹配,请重新登录',
|
||||||
|
'internal error': '支付异常,请稍后重试',
|
||||||
|
'system error': '系统繁忙,请稍后重试',
|
||||||
|
'payment limit exceeded': '已超出支付限额',
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试精确匹配
|
||||||
|
const lower = errMsg.toLowerCase()
|
||||||
|
for (const [key, msg] of Object.entries(map)) {
|
||||||
|
if (lower.includes(key.toLowerCase())) return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// fallback:去前缀(requestVirtualPayment:fail xxx → xxx)
|
||||||
|
const cleaned = errMsg.replace(/^requestVirtualPayment:fail\s*/i, '').replace(/^requestPayment:fail\s*/i, '').trim()
|
||||||
|
if (cleaned && cleaned !== errMsg) {
|
||||||
|
for (const [key, msg] of Object.entries(map)) {
|
||||||
|
if (cleaned.toLowerCase().includes(key.toLowerCase())) return msg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `支付失败(${cleaned || '未知错误'})`
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/** 将 ISO 时间字符串转为北京时间(UTC+8)显示 */
|
||||||
|
export function toBeijing(iso?: string): string {
|
||||||
|
if (!iso) return '--'
|
||||||
|
try {
|
||||||
|
return new Date(iso).toLocaleString('zh-CN', {
|
||||||
|
timeZone: 'Asia/Shanghai',
|
||||||
|
hour12: false,
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
return iso.slice(0, 16).replace('T', ' ')
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user