forked from wangziqi/gongxue-base
feat: add AI school recommendation foundation
This commit is contained in:
@@ -14,7 +14,7 @@
|
|||||||
- `apps/api` 独立业务 API,后续供 H5、Taro 小程序、管理后台统一调用;已支持 Supabase Auth JWT 和迁移期 `tk_` session 双入口。
|
- `apps/api` 独立业务 API,后续供 H5、Taro 小程序、管理后台统一调用;已支持 Supabase Auth JWT 和迁移期 `tk_` session 双入口。
|
||||||
- 租户后台能力:品牌、主题模板/草稿/发布、域名、公开设置、支付账户、登录配置、私密密钥掩码、活动内容、考试日期、题目反馈处理、激活码、优惠券、勋章管理/发放、成员权限、自定义角色模板、班级/教师/学生范围权限、学生批量导入、批量分班、学生备注、跟进任务、审计日志。
|
- 租户后台能力:品牌、主题模板/草稿/发布、域名、公开设置、支付账户、登录配置、私密密钥掩码、活动内容、考试日期、题目反馈处理、激活码、优惠券、勋章管理/发放、成员权限、自定义角色模板、班级/教师/学生范围权限、学生批量导入、批量分班、学生备注、跟进任务、审计日志。
|
||||||
- 租户内容能力:可配置题库入口、任意深度分类树、考试意向标记、题目集合、顺序/随机/全真模拟蓝图、题目录入/更新、视频绑定、分数线、单词、知识手册、资料资源台账、题目/单词/知识手册/分数线/视频 JSON/CSV/Excel 批量导入。
|
- 租户内容能力:可配置题库入口、任意深度分类树、考试意向标记、题目集合、顺序/随机/全真模拟蓝图、题目录入/更新、视频绑定、分数线、单词、知识手册、资料资源台账、题目/单词/知识手册/分数线/视频 JSON/CSV/Excel 批量导入。
|
||||||
- 学生端能力:题库入口、分类树、题目集合、顺序/随机/模考 session 组卷快照、答题、错题本、收藏夹、背单词进度、个人中心、勋章、考试倒计时、签到积分、题目反馈、排行榜、分数线、题目视频、订单详情/状态轮询、优惠券领取/抵扣、权益、激活码预检查/兑换、资料下载。
|
- 学生端能力:题库入口、分类树、题目集合、顺序/随机/模考 session 组卷快照、答题、错题本、收藏夹、背单词进度、个人中心、勋章、考试倒计时、签到积分、题目反馈、排行榜、分数线、AI 择校推荐、题目视频、订单详情/状态轮询、优惠券领取/抵扣、权益、激活码预检查/兑换、资料下载。
|
||||||
- 平台后台能力:租户管理、SaaS 套餐、订阅、账单、服务费收款、用量记录、公共题库授权。
|
- 平台后台能力:租户管理、SaaS 套餐、订阅、账单、服务费收款、用量记录、公共题库授权。
|
||||||
- 公共题库商业化能力:租户可采纳平台授权题库为本租户副本,并可手动或由 worker 自动同步平台新增/更新题目;同步会保护租户自改题目,返回冲突而不覆盖,后台可查询冲突明细。
|
- 公共题库商业化能力:租户可采纳平台授权题库为本租户副本,并可手动或由 worker 自动同步平台新增/更新题目;同步会保护租户自改题目,返回冲突而不覆盖,后台可查询冲突明细。
|
||||||
- 题库导出能力:租户内容编辑可按题目集合、内容入口或分类节点导出 JSON、`paper_json`、打印 payload、PDF、Word 和每日一练图片 ZIP 素材包,后端强制租户隔离、答案/解析开关、复合题子题脱敏、导出 job 和审计;PDF/Word/ZIP 由 exports worker 生成水印文件或运营素材并发布到 `content_assets`;`daily_practice` 支持每日一练九宫格 metadata、PDF/Word 版式、9 张 PNG/SVG 卡片和拼图包。
|
- 题库导出能力:租户内容编辑可按题目集合、内容入口或分类节点导出 JSON、`paper_json`、打印 payload、PDF、Word 和每日一练图片 ZIP 素材包,后端强制租户隔离、答案/解析开关、复合题子题脱敏、导出 job 和审计;PDF/Word/ZIP 由 exports worker 生成水印文件或运营素材并发布到 `content_assets`;`daily_practice` 支持每日一练九宫格 metadata、PDF/Word 版式、9 张 PNG/SVG 卡片和拼图包。
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
- Excel/CSV 导入解析已完成并复用 `content_import_jobs/items/issues` 管线;大批量异步导入 worker 基础已接入,支持 queued job 消费、重试和审计;导入后复检、模板下载和字段映射 API 已完成,前端 UI 待接。
|
- Excel/CSV 导入解析已完成并复用 `content_import_jobs/items/issues` 管线;大批量异步导入 worker 基础已接入,支持 queued job 消费、重试和审计;导入后复检、模板下载和字段映射 API 已完成,前端 UI 待接。
|
||||||
- 题库导出已完成服务端结构化 payload、PDF/Word 二进制 worker、每日一练基础导出和每日一练 ZIP 图片素材包;后续还要补更精细试卷模板、多模板排版和导出操作台体验。
|
- 题库导出已完成服务端结构化 payload、PDF/Word 二进制 worker、每日一练基础导出和每日一练 ZIP 图片素材包;后续还要补更精细试卷模板、多模板排版和导出操作台体验。
|
||||||
- 勋章管理/手动发放已可联调;自动发放规则、积分活动联动、分佣真实打款 provider、发票、批量凭证上传、CRM 富卡片模板、失败告警、死信运营台、销售转化看板、公共题库版本通知和冲突处理操作台还没完成。
|
- 勋章管理/手动发放已可联调;自动发放规则、积分活动联动、分佣真实打款 provider、发票、批量凭证上传、CRM 富卡片模板、失败告警、死信运营台、销售转化看板、公共题库版本通知和冲突处理操作台还没完成。
|
||||||
- `apps/taro` 已建立 Taro 4 React 跨端前端地基,包含 H5 学生端、租户后台、平台后台三套构建入口、租户解析、统一 API client 和 Supabase Auth client 初始化;学生端第一批页面已接入登录、首页、题库、练习、背单词、知识手册、分数线、资料和个人中心;租户后台第一批页面已接入工作台、数据看板、学生/班级、题库内容、营销中心和租户设置,设置页已接主题模板、草稿预览/发布、角色模板和成员绑定第一版;平台后台已接入工作台、租户管理、账务中心、公共题库授权,以及创建租户、状态变更、订阅、账单、收款、用量和题库授权第一版写操作。
|
- `apps/taro` 已建立 Taro 4 React 跨端前端地基,包含 H5 学生端、租户后台、平台后台三套构建入口、租户解析、统一 API client 和 Supabase Auth client 初始化;学生端第一批页面已接入登录、首页、题库、练习、背单词、知识手册、分数线、AI 择校推荐、资料和个人中心;租户后台第一批页面已接入工作台、数据看板、学生/班级、题库内容、营销中心和租户设置,设置页已接主题模板、草稿预览/发布、角色模板和成员绑定第一版;平台后台已接入工作台、租户管理、账务中心、公共题库授权,以及创建租户、状态变更、订阅、账单、收款、用量和题库授权第一版写操作。
|
||||||
- 根目录已清理为新 Supabase SaaS monorepo 编排层;旧 PocketBase/React 项目和旧构建产物仅保留在 `参考/` 目录作为迁移参考,不进入 Git 提交。
|
- 根目录已清理为新 Supabase SaaS monorepo 编排层;旧 PocketBase/React 项目和旧构建产物仅保留在 `参考/` 目录作为迁移参考,不进入 Git 提交。
|
||||||
|
|
||||||
更完整的进度看这些文档:
|
更完整的进度看这些文档:
|
||||||
@@ -128,6 +128,7 @@ apps/taro/src/pages/student/practice
|
|||||||
apps/taro/src/pages/student/vocabulary
|
apps/taro/src/pages/student/vocabulary
|
||||||
apps/taro/src/pages/student/handbook
|
apps/taro/src/pages/student/handbook
|
||||||
apps/taro/src/pages/student/scoreline
|
apps/taro/src/pages/student/scoreline
|
||||||
|
apps/taro/src/pages/student/ai-school
|
||||||
apps/taro/src/pages/student/assets
|
apps/taro/src/pages/student/assets
|
||||||
apps/taro/src/pages/student/profile
|
apps/taro/src/pages/student/profile
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { Handler } from './http.js';
|
import type { Handler } from './http.js';
|
||||||
import { routeKey } from './http.js';
|
import { routeKey } from './http.js';
|
||||||
|
import { aiRoutes } from '../features/ai/index.js';
|
||||||
import { authRoutes } from '../features/auth/index.js';
|
import { authRoutes } from '../features/auth/index.js';
|
||||||
import { catalogRoutes } from '../features/catalog/index.js';
|
import { catalogRoutes } from '../features/catalog/index.js';
|
||||||
import { commerceRoutes } from '../features/commerce/index.js';
|
import { commerceRoutes } from '../features/commerce/index.js';
|
||||||
@@ -31,6 +32,7 @@ const allRoutes: RouteDefinition[] = [
|
|||||||
...healthRoutes,
|
...healthRoutes,
|
||||||
...authRoutes,
|
...authRoutes,
|
||||||
...tenantRoutes,
|
...tenantRoutes,
|
||||||
|
...aiRoutes,
|
||||||
...catalogRoutes,
|
...catalogRoutes,
|
||||||
...learningRoutes,
|
...learningRoutes,
|
||||||
...profileRoutes,
|
...profileRoutes,
|
||||||
|
|||||||
12
apps/api/src/features/ai/index.ts
Normal file
12
apps/api/src/features/ai/index.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import type { RouteDefinition } from '../../core/router.js';
|
||||||
|
import {
|
||||||
|
generateSchoolRecommendationRoute,
|
||||||
|
schoolRecommendationReportDetailRoute,
|
||||||
|
schoolRecommendationReportsRoute,
|
||||||
|
} from './routes.js';
|
||||||
|
|
||||||
|
export const aiRoutes: RouteDefinition[] = [
|
||||||
|
['GET', '/api/ai/school-recommendations', schoolRecommendationReportsRoute],
|
||||||
|
['GET', '/api/ai/school-recommendations/detail', schoolRecommendationReportDetailRoute],
|
||||||
|
['POST', '/api/ai/school-recommendations/generate', generateSchoolRecommendationRoute],
|
||||||
|
];
|
||||||
546
apps/api/src/features/ai/routes.ts
Normal file
546
apps/api/src/features/ai/routes.ts
Normal file
@@ -0,0 +1,546 @@
|
|||||||
|
import { HttpError, type RequestContext } from '../../core/http.js';
|
||||||
|
import { intParam, readJsonBody, stringParam, tenantIdFrom, userIdFrom } from '../../core/request.js';
|
||||||
|
import { query, queryOne, transaction } from '../../core/db.js';
|
||||||
|
|
||||||
|
type JsonObject = Record<string, unknown>;
|
||||||
|
|
||||||
|
interface StudentProfileContext {
|
||||||
|
regionId: string | null;
|
||||||
|
regionName: string | null;
|
||||||
|
selectedSchoolId: string | null;
|
||||||
|
selectedSchoolName: string | null;
|
||||||
|
selectedMajorId: string | null;
|
||||||
|
selectedMajorName: string | null;
|
||||||
|
stats: JsonObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RegionRow {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
code: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EntitlementRow {
|
||||||
|
id: string;
|
||||||
|
scopeType: string;
|
||||||
|
scopeId: string | null;
|
||||||
|
expiresAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScorelineFieldRow {
|
||||||
|
fieldKey: string;
|
||||||
|
fieldName: string;
|
||||||
|
fieldType: string | null;
|
||||||
|
unit: string | null;
|
||||||
|
isTrend: boolean;
|
||||||
|
sortOrder: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScorelineRecordRow {
|
||||||
|
id: string;
|
||||||
|
year: number;
|
||||||
|
schoolId: string | null;
|
||||||
|
schoolName: string | null;
|
||||||
|
majorId: string | null;
|
||||||
|
majorName: string | null;
|
||||||
|
fieldValues: JsonObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RecommendationCandidate {
|
||||||
|
schoolId: string | null;
|
||||||
|
schoolName: string;
|
||||||
|
majorId: string | null;
|
||||||
|
majorName: string | null;
|
||||||
|
latestYear: number | null;
|
||||||
|
latestScore: number | null;
|
||||||
|
averageScore: number | null;
|
||||||
|
scoreGap: number | null;
|
||||||
|
riskLevel: 'safe' | 'balanced' | 'sprint' | 'unknown';
|
||||||
|
confidence: number;
|
||||||
|
reason: string;
|
||||||
|
scorelineTrend: {
|
||||||
|
years: number[];
|
||||||
|
scores: (number | null)[];
|
||||||
|
direction: 'up' | 'down' | 'flat' | 'unknown';
|
||||||
|
};
|
||||||
|
tags: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const RISK_PREFERENCES = new Set(['safe', 'balanced', 'sprint']);
|
||||||
|
const PROMPT_VERSION = 'school-recommendation-v1';
|
||||||
|
const LOCAL_MODEL = 'local-scoreline-rules-v1';
|
||||||
|
const DISCLAIMER = [
|
||||||
|
'推荐结果仅用于择校和备考规划参考,不构成录取承诺。',
|
||||||
|
'分数线、招生计划和考试政策可能变化,正式报考前应以院校和考试院官方信息为准。',
|
||||||
|
'当地区或院校数据覆盖不足时,应结合人工咨询和最新招生简章复核。',
|
||||||
|
];
|
||||||
|
|
||||||
|
function objectValue(value: unknown): JsonObject {
|
||||||
|
return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function nullableString(value: unknown) {
|
||||||
|
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function boundedNumber(value: unknown, min: number, max: number) {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (!Number.isFinite(parsed)) return null;
|
||||||
|
return Math.min(Math.max(parsed, min), max);
|
||||||
|
}
|
||||||
|
|
||||||
|
function boundedText(value: unknown, maxLength: number) {
|
||||||
|
const text = nullableString(value);
|
||||||
|
if (!text) return null;
|
||||||
|
return text.slice(0, maxLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeRiskPreference(value: unknown) {
|
||||||
|
const riskPreference = nullableString(value) || 'balanced';
|
||||||
|
if (!RISK_PREFERENCES.has(riskPreference)) {
|
||||||
|
throw new HttpError(400, 'riskPreference must be safe, balanced, or sprint', 'INVALID_AI_RISK_PREFERENCE');
|
||||||
|
}
|
||||||
|
return riskPreference as 'safe' | 'balanced' | 'sprint';
|
||||||
|
}
|
||||||
|
|
||||||
|
function numericField(value: unknown) {
|
||||||
|
const parsed = Number(value);
|
||||||
|
return Number.isFinite(parsed) ? parsed : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickScoreValue(values: JsonObject) {
|
||||||
|
const preferredKeys = [
|
||||||
|
'minScore',
|
||||||
|
'minimumScore',
|
||||||
|
'score',
|
||||||
|
'admissionScore',
|
||||||
|
'lowestScore',
|
||||||
|
'投档线',
|
||||||
|
'最低分',
|
||||||
|
];
|
||||||
|
for (const key of preferredKeys) {
|
||||||
|
const score = numericField(values[key]);
|
||||||
|
if (score !== null) return score;
|
||||||
|
}
|
||||||
|
for (const [key, value] of Object.entries(values)) {
|
||||||
|
if (/score|分|线/i.test(key)) {
|
||||||
|
const score = numericField(value);
|
||||||
|
if (score !== null) return score;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function riskFromGap(gap: number | null, preference: 'safe' | 'balanced' | 'sprint') {
|
||||||
|
if (gap === null) return 'unknown';
|
||||||
|
const safeFloor = preference === 'safe' ? 18 : preference === 'sprint' ? 8 : 12;
|
||||||
|
const sprintFloor = preference === 'safe' ? -2 : preference === 'sprint' ? -15 : -8;
|
||||||
|
if (gap >= safeFloor) return 'safe';
|
||||||
|
if (gap >= sprintFloor) return 'balanced';
|
||||||
|
return 'sprint';
|
||||||
|
}
|
||||||
|
|
||||||
|
function confidenceFromGap(gap: number | null, recordsCount: number, riskLevel: string) {
|
||||||
|
if (gap === null) return recordsCount > 1 ? 0.45 : 0.35;
|
||||||
|
const base = riskLevel === 'safe' ? 0.78 : riskLevel === 'balanced' ? 0.62 : 0.42;
|
||||||
|
const gapBonus = Math.min(Math.abs(gap) / 100, 0.12);
|
||||||
|
const coverageBonus = Math.min(recordsCount * 0.025, 0.1);
|
||||||
|
return Number(Math.min(base + gapBonus + coverageBonus, 0.95).toFixed(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
function trendDirection(scores: (number | null)[]) {
|
||||||
|
const numericScores = scores.filter((score): score is number => typeof score === 'number');
|
||||||
|
if (numericScores.length < 2) return 'unknown';
|
||||||
|
const first = numericScores[0];
|
||||||
|
const last = numericScores[numericScores.length - 1];
|
||||||
|
const diff = last - first;
|
||||||
|
if (Math.abs(diff) <= 3) return 'flat';
|
||||||
|
return diff > 0 ? 'up' : 'down';
|
||||||
|
}
|
||||||
|
|
||||||
|
function groupKey(record: ScorelineRecordRow) {
|
||||||
|
return `${record.schoolId || record.schoolName || 'unknown'}:${record.majorId || record.majorName || 'unknown'}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCandidates(
|
||||||
|
records: ScorelineRecordRow[],
|
||||||
|
input: ReturnType<typeof normalizeRecommendationInput>,
|
||||||
|
) {
|
||||||
|
const groups = new Map<string, ScorelineRecordRow[]>();
|
||||||
|
for (const record of records) {
|
||||||
|
const key = groupKey(record);
|
||||||
|
groups.set(key, [...(groups.get(key) || []), record]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidates = [...groups.values()].map(group => {
|
||||||
|
const sorted = group.slice().sort((left, right) => left.year - right.year);
|
||||||
|
const latest = sorted.at(-1) || null;
|
||||||
|
const scores = sorted.map(record => pickScoreValue(record.fieldValues));
|
||||||
|
const numericScores = scores.filter((score): score is number => typeof score === 'number');
|
||||||
|
const latestScore = latest ? pickScoreValue(latest.fieldValues) : null;
|
||||||
|
const averageScore = numericScores.length
|
||||||
|
? Number((numericScores.reduce((sum, score) => sum + score, 0) / numericScores.length).toFixed(1))
|
||||||
|
: null;
|
||||||
|
const baseline = latestScore ?? averageScore;
|
||||||
|
const scoreGap = baseline === null || input.estimatedScore === null
|
||||||
|
? null
|
||||||
|
: Number((input.estimatedScore - baseline).toFixed(1));
|
||||||
|
const riskLevel = riskFromGap(scoreGap, input.riskPreference);
|
||||||
|
const direction = trendDirection(scores);
|
||||||
|
const confidence = confidenceFromGap(scoreGap, sorted.length, riskLevel);
|
||||||
|
const tags = [
|
||||||
|
riskLevel === 'safe' ? '稳妥' : riskLevel === 'balanced' ? '匹配' : riskLevel === 'sprint' ? '冲刺' : '数据不足',
|
||||||
|
direction === 'up' ? '分数线上升' : direction === 'down' ? '分数线下降' : direction === 'flat' ? '分数线稳定' : '趋势不足',
|
||||||
|
sorted.length >= 3 ? '多年数据' : '样本较少',
|
||||||
|
];
|
||||||
|
const schoolName = latest?.schoolName || group[0]?.schoolName || '未知院校';
|
||||||
|
const majorName = latest?.majorName || group[0]?.majorName || null;
|
||||||
|
const reasonParts = [
|
||||||
|
input.estimatedScore === null
|
||||||
|
? '未提供预估分,按历年分数线和数据覆盖度排序。'
|
||||||
|
: `预估分与最新参考线差值约 ${scoreGap ?? '未知'} 分。`,
|
||||||
|
direction === 'up'
|
||||||
|
? '近年参考线有上升趋势,建议预留安全分差。'
|
||||||
|
: direction === 'down'
|
||||||
|
? '近年参考线略有下降,可作为匹配或冲刺备选。'
|
||||||
|
: direction === 'flat'
|
||||||
|
? '近年参考线相对稳定,适合纳入重点比较。'
|
||||||
|
: '历史数据不足,建议结合招生计划复核。',
|
||||||
|
];
|
||||||
|
|
||||||
|
return {
|
||||||
|
schoolId: latest?.schoolId || group[0]?.schoolId || null,
|
||||||
|
schoolName,
|
||||||
|
majorId: latest?.majorId || group[0]?.majorId || null,
|
||||||
|
majorName,
|
||||||
|
latestYear: latest?.year || null,
|
||||||
|
latestScore,
|
||||||
|
averageScore,
|
||||||
|
scoreGap,
|
||||||
|
riskLevel,
|
||||||
|
confidence,
|
||||||
|
reason: reasonParts.join(' '),
|
||||||
|
scorelineTrend: {
|
||||||
|
years: sorted.map(record => record.year),
|
||||||
|
scores,
|
||||||
|
direction,
|
||||||
|
},
|
||||||
|
tags,
|
||||||
|
} satisfies RecommendationCandidate;
|
||||||
|
});
|
||||||
|
|
||||||
|
const riskOrder = {
|
||||||
|
safe: input.riskPreference === 'safe' ? 0 : 1,
|
||||||
|
balanced: input.riskPreference === 'balanced' ? 0 : 2,
|
||||||
|
sprint: input.riskPreference === 'sprint' ? 0 : 3,
|
||||||
|
unknown: 4,
|
||||||
|
};
|
||||||
|
|
||||||
|
return candidates
|
||||||
|
.sort((left, right) => {
|
||||||
|
const riskDiff = riskOrder[left.riskLevel] - riskOrder[right.riskLevel];
|
||||||
|
if (riskDiff !== 0) return riskDiff;
|
||||||
|
if (right.confidence !== left.confidence) return right.confidence - left.confidence;
|
||||||
|
return (right.latestYear || 0) - (left.latestYear || 0);
|
||||||
|
})
|
||||||
|
.slice(0, input.recommendationLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeRecommendationInput(body: JsonObject) {
|
||||||
|
const estimatedScore = boundedNumber(body.estimatedScore, 0, 1000);
|
||||||
|
const recommendationLimit = Math.trunc(boundedNumber(body.recommendationLimit, 1, 12) || 5);
|
||||||
|
return {
|
||||||
|
regionId: nullableString(body.regionId),
|
||||||
|
estimatedScore,
|
||||||
|
examTrack: boundedText(body.examTrack, 80),
|
||||||
|
preferredCity: boundedText(body.preferredCity, 80),
|
||||||
|
targetSchoolId: nullableString(body.targetSchoolId),
|
||||||
|
targetMajorId: nullableString(body.targetMajorId),
|
||||||
|
riskPreference: normalizeRiskPreference(body.riskPreference),
|
||||||
|
constraints: boundedText(body.constraints, 500),
|
||||||
|
notes: boundedText(body.notes, 500),
|
||||||
|
recommendationLimit,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadStudentProfile(tenantId: string, userId: string) {
|
||||||
|
return queryOne<StudentProfileContext>(
|
||||||
|
`
|
||||||
|
select sp.region_id as "regionId", r.name as "regionName",
|
||||||
|
sp.selected_school_id as "selectedSchoolId", s.name as "selectedSchoolName",
|
||||||
|
sp.selected_major_id as "selectedMajorId", m.name as "selectedMajorName",
|
||||||
|
sp.stats
|
||||||
|
from public.student_profiles sp
|
||||||
|
left join public.regions r on r.id = sp.region_id and r.tenant_id = sp.tenant_id
|
||||||
|
left join public.schools s on s.id = sp.selected_school_id and s.tenant_id = sp.tenant_id
|
||||||
|
left join public.majors m on m.id = sp.selected_major_id and m.tenant_id = sp.tenant_id
|
||||||
|
where sp.tenant_id = $1 and sp.user_id = $2
|
||||||
|
limit 1
|
||||||
|
`,
|
||||||
|
[tenantId, userId],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertRegionAccess(tenantId: string, regionId: string) {
|
||||||
|
const region = await queryOne<RegionRow>(
|
||||||
|
`
|
||||||
|
select id, name, code
|
||||||
|
from public.regions
|
||||||
|
where tenant_id = $1 and id = $2 and is_active = true
|
||||||
|
limit 1
|
||||||
|
`,
|
||||||
|
[tenantId, regionId],
|
||||||
|
);
|
||||||
|
if (!region) throw new HttpError(404, 'Region not found for this tenant', 'AI_REGION_NOT_FOUND');
|
||||||
|
return region;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function activeSvipEntitlement(tenantId: string, userId: string, regionId: string | null) {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
return queryOne<EntitlementRow>(
|
||||||
|
`
|
||||||
|
select id, scope_type as "scopeType", scope_id as "scopeId", expires_at as "expiresAt"
|
||||||
|
from public.entitlements
|
||||||
|
where tenant_id = $1
|
||||||
|
and user_id = $2
|
||||||
|
and entitlement_type = 'svip'
|
||||||
|
and status = 'active'
|
||||||
|
and starts_at <= $3::timestamptz
|
||||||
|
and (expires_at is null or expires_at > $3::timestamptz)
|
||||||
|
and (
|
||||||
|
scope_type = 'tenant'
|
||||||
|
or ($4::uuid is not null and scope_type = 'region' and scope_id = $4::uuid)
|
||||||
|
)
|
||||||
|
order by case when scope_type = 'region' then 0 else 1 end, expires_at desc nulls first
|
||||||
|
limit 1
|
||||||
|
`,
|
||||||
|
[tenantId, userId, now, regionId],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadScorelineFields(tenantId: string, regionId: string) {
|
||||||
|
return query<ScorelineFieldRow>(
|
||||||
|
`
|
||||||
|
select field_key as "fieldKey", field_name as "fieldName",
|
||||||
|
field_type as "fieldType", unit, is_trend as "isTrend",
|
||||||
|
sort_order as "sortOrder"
|
||||||
|
from public.scoreline_fields
|
||||||
|
where tenant_id = $1
|
||||||
|
and (region_id is null or region_id = $2::uuid)
|
||||||
|
and is_visible = true
|
||||||
|
order by sort_order asc, field_name asc
|
||||||
|
`,
|
||||||
|
[tenantId, regionId],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadScorelineRecords(tenantId: string, regionId: string, input: ReturnType<typeof normalizeRecommendationInput>) {
|
||||||
|
const params: unknown[] = [tenantId, regionId, input.targetSchoolId, input.targetMajorId, 180];
|
||||||
|
return query<ScorelineRecordRow>(
|
||||||
|
`
|
||||||
|
select id, year, school_id as "schoolId", school_name as "schoolName",
|
||||||
|
major_id as "majorId", major_name as "majorName",
|
||||||
|
field_values as "fieldValues"
|
||||||
|
from public.scoreline_records
|
||||||
|
where tenant_id = $1
|
||||||
|
and region_id = $2::uuid
|
||||||
|
and ($3::uuid is null or school_id = $3::uuid)
|
||||||
|
and ($4::uuid is null or major_id = $4::uuid)
|
||||||
|
order by year desc, school_name asc nulls last, major_name asc nulls last
|
||||||
|
limit $5
|
||||||
|
`,
|
||||||
|
params,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildReportResult(input: ReturnType<typeof normalizeRecommendationInput>, context: JsonObject, candidates: RecommendationCandidate[]) {
|
||||||
|
const region = objectValue(context.region);
|
||||||
|
const dataCoverage = objectValue(context.dataCoverage);
|
||||||
|
const safeCount = candidates.filter(candidate => candidate.riskLevel === 'safe').length;
|
||||||
|
const balancedCount = candidates.filter(candidate => candidate.riskLevel === 'balanced').length;
|
||||||
|
const sprintCount = candidates.filter(candidate => candidate.riskLevel === 'sprint').length;
|
||||||
|
const top = candidates[0] || null;
|
||||||
|
const riskLevel =
|
||||||
|
safeCount >= 2 ? 'safe' :
|
||||||
|
balancedCount >= 2 || top?.riskLevel === 'balanced' ? 'balanced' :
|
||||||
|
sprintCount ? 'sprint' : 'unknown';
|
||||||
|
|
||||||
|
return {
|
||||||
|
schemaVersion: 'school-recommendation-report-v1',
|
||||||
|
summary: top
|
||||||
|
? `基于当前地区历年分数线,优先推荐 ${top.schoolName}${top.majorName ? `-${top.majorName}` : ''} 等 ${candidates.length} 个方案。`
|
||||||
|
: '当前地区分数线数据不足,暂无法生成可靠院校推荐。',
|
||||||
|
riskLevel,
|
||||||
|
recommendedSchools: candidates,
|
||||||
|
actionPlan: [
|
||||||
|
'先确认目标地区、考试类别和预估分是否准确。',
|
||||||
|
'重点比较推荐院校近三年分数线、招生计划和专业限制。',
|
||||||
|
'把稳妥、匹配、冲刺院校分别保留 2-3 个备选,并跟进最新招生简章。',
|
||||||
|
input.constraints ? '结合个人限制条件逐项排除不符合报考条件的院校或专业。' : '补充个人限制条件后可再次生成更精细的推荐。',
|
||||||
|
],
|
||||||
|
disclaimers: DISCLAIMER,
|
||||||
|
dataCoverage: {
|
||||||
|
regionId: region.id || null,
|
||||||
|
regionName: region.name || null,
|
||||||
|
scorelineRecordCount: dataCoverage.scorelineRecordCount || 0,
|
||||||
|
schoolMajorGroupCount: candidates.length,
|
||||||
|
years: dataCoverage.years || [],
|
||||||
|
fields: dataCoverage.fields || [],
|
||||||
|
provider: 'local_rules',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportSelectSql() {
|
||||||
|
return `
|
||||||
|
select id, tenant_id as "tenantId", user_id as "userId", region_id as "regionId",
|
||||||
|
status, provider, model, prompt_version as "promptVersion",
|
||||||
|
input_payload as "inputPayload", context_payload as "contextPayload",
|
||||||
|
result_payload as "resultPayload", error_message as "errorMessage",
|
||||||
|
generated_at as "generatedAt", created_at as "createdAt", updated_at as "updatedAt"
|
||||||
|
from public.ai_recommendation_reports
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateSchoolRecommendationRoute(ctx: RequestContext) {
|
||||||
|
const body = await readJsonBody(ctx);
|
||||||
|
const tenantId = await tenantIdFrom(ctx);
|
||||||
|
const userId = await userIdFrom(ctx, body);
|
||||||
|
const input = normalizeRecommendationInput(body);
|
||||||
|
const profile = await loadStudentProfile(tenantId, userId);
|
||||||
|
if (!profile) throw new HttpError(404, 'Student profile not found', 'PROFILE_NOT_FOUND');
|
||||||
|
|
||||||
|
const regionId = input.regionId || profile.regionId;
|
||||||
|
if (!regionId) throw new HttpError(400, 'regionId is required before generating a recommendation', 'AI_REGION_REQUIRED');
|
||||||
|
const region = await assertRegionAccess(tenantId, regionId);
|
||||||
|
const entitlement = await activeSvipEntitlement(tenantId, userId, regionId);
|
||||||
|
if (!entitlement) {
|
||||||
|
throw new HttpError(403, 'SVIP entitlement is required for AI school recommendation', 'AI_SVIP_REQUIRED');
|
||||||
|
}
|
||||||
|
|
||||||
|
const [fields, records] = await Promise.all([
|
||||||
|
loadScorelineFields(tenantId, regionId),
|
||||||
|
loadScorelineRecords(tenantId, regionId, input),
|
||||||
|
]);
|
||||||
|
const years = [...new Set(records.map(record => record.year))].sort((left, right) => right - left);
|
||||||
|
const candidates = buildCandidates(records, input);
|
||||||
|
const contextPayload = {
|
||||||
|
region,
|
||||||
|
studentProfile: {
|
||||||
|
regionId: profile.regionId,
|
||||||
|
regionName: profile.regionName,
|
||||||
|
selectedSchoolId: profile.selectedSchoolId,
|
||||||
|
selectedSchoolName: profile.selectedSchoolName,
|
||||||
|
selectedMajorId: profile.selectedMajorId,
|
||||||
|
selectedMajorName: profile.selectedMajorName,
|
||||||
|
},
|
||||||
|
entitlement: {
|
||||||
|
id: entitlement.id,
|
||||||
|
scopeType: entitlement.scopeType,
|
||||||
|
scopeId: entitlement.scopeId,
|
||||||
|
expiresAt: entitlement.expiresAt,
|
||||||
|
},
|
||||||
|
dataCoverage: {
|
||||||
|
scorelineRecordCount: records.length,
|
||||||
|
years,
|
||||||
|
fields: fields.map(field => ({
|
||||||
|
fieldKey: field.fieldKey,
|
||||||
|
fieldName: field.fieldName,
|
||||||
|
fieldType: field.fieldType,
|
||||||
|
unit: field.unit,
|
||||||
|
isTrend: field.isTrend,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const resultPayload = buildReportResult(input, contextPayload, candidates);
|
||||||
|
|
||||||
|
const item = await transaction(async client => {
|
||||||
|
const result = await client.query(
|
||||||
|
`
|
||||||
|
insert into public.ai_recommendation_reports (
|
||||||
|
tenant_id, user_id, region_id, status, provider, model, prompt_version,
|
||||||
|
input_payload, context_payload, result_payload, generated_at
|
||||||
|
)
|
||||||
|
values (
|
||||||
|
$1, $2, $3::uuid, 'generated', 'local_rules', $4, $5,
|
||||||
|
$6::jsonb, $7::jsonb, $8::jsonb, now()
|
||||||
|
)
|
||||||
|
returning id, tenant_id as "tenantId", user_id as "userId", region_id as "regionId",
|
||||||
|
status, provider, model, prompt_version as "promptVersion",
|
||||||
|
input_payload as "inputPayload", context_payload as "contextPayload",
|
||||||
|
result_payload as "resultPayload", error_message as "errorMessage",
|
||||||
|
generated_at as "generatedAt", created_at as "createdAt", updated_at as "updatedAt"
|
||||||
|
`,
|
||||||
|
[
|
||||||
|
tenantId,
|
||||||
|
userId,
|
||||||
|
regionId,
|
||||||
|
LOCAL_MODEL,
|
||||||
|
PROMPT_VERSION,
|
||||||
|
JSON.stringify(input),
|
||||||
|
JSON.stringify(contextPayload),
|
||||||
|
JSON.stringify(resultPayload),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
await client.query(
|
||||||
|
`
|
||||||
|
insert into public.audit_logs (tenant_id, actor_user_id, action, target_type, target_id, details)
|
||||||
|
values ($1, $2, 'ai.school_recommendation.generated', 'ai_recommendation_report', $3, $4::jsonb)
|
||||||
|
`,
|
||||||
|
[
|
||||||
|
tenantId,
|
||||||
|
userId,
|
||||||
|
result.rows[0].id,
|
||||||
|
JSON.stringify({
|
||||||
|
provider: 'local_rules',
|
||||||
|
model: LOCAL_MODEL,
|
||||||
|
promptVersion: PROMPT_VERSION,
|
||||||
|
regionId,
|
||||||
|
scorelineRecordCount: records.length,
|
||||||
|
recommendationCount: candidates.length,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
return result.rows[0];
|
||||||
|
});
|
||||||
|
|
||||||
|
return { item };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function schoolRecommendationReportsRoute(ctx: RequestContext) {
|
||||||
|
const tenantId = await tenantIdFrom(ctx);
|
||||||
|
const userId = await userIdFrom(ctx);
|
||||||
|
const limit = intParam(ctx, 'limit', 20, 100);
|
||||||
|
const regionId = stringParam(ctx, 'regionId');
|
||||||
|
|
||||||
|
const items = await query(
|
||||||
|
`
|
||||||
|
${reportSelectSql()}
|
||||||
|
where tenant_id = $1
|
||||||
|
and user_id = $2
|
||||||
|
and ($3::uuid is null or region_id = $3::uuid)
|
||||||
|
order by created_at desc
|
||||||
|
limit $4
|
||||||
|
`,
|
||||||
|
[tenantId, userId, regionId || null, limit],
|
||||||
|
);
|
||||||
|
return { items };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function schoolRecommendationReportDetailRoute(ctx: RequestContext) {
|
||||||
|
const tenantId = await tenantIdFrom(ctx);
|
||||||
|
const userId = await userIdFrom(ctx);
|
||||||
|
const reportId = stringParam(ctx, 'reportId');
|
||||||
|
if (!reportId) throw new HttpError(400, 'reportId is required', 'AI_REPORT_ID_REQUIRED');
|
||||||
|
|
||||||
|
const item = await queryOne(
|
||||||
|
`
|
||||||
|
${reportSelectSql()}
|
||||||
|
where tenant_id = $1 and user_id = $2 and id = $3::uuid
|
||||||
|
limit 1
|
||||||
|
`,
|
||||||
|
[tenantId, userId, reportId],
|
||||||
|
);
|
||||||
|
if (!item) throw new HttpError(404, 'AI recommendation report not found', 'AI_REPORT_NOT_FOUND');
|
||||||
|
return { item };
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ export default defineAppConfig({
|
|||||||
'pages/student/vocabulary/index',
|
'pages/student/vocabulary/index',
|
||||||
'pages/student/handbook/index',
|
'pages/student/handbook/index',
|
||||||
'pages/student/scoreline/index',
|
'pages/student/scoreline/index',
|
||||||
|
'pages/student/ai-school/index',
|
||||||
'pages/student/assets/index',
|
'pages/student/assets/index',
|
||||||
'pages/student/profile/index',
|
'pages/student/profile/index',
|
||||||
'pages/tenant-admin/workbench/index',
|
'pages/tenant-admin/workbench/index',
|
||||||
|
|||||||
3
apps/taro/src/pages/student/ai-school/index.config.ts
Normal file
3
apps/taro/src/pages/student/ai-school/index.config.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export default definePageConfig({
|
||||||
|
navigationBarTitleText: 'AI择校推荐',
|
||||||
|
});
|
||||||
154
apps/taro/src/pages/student/ai-school/index.tsx
Normal file
154
apps/taro/src/pages/student/ai-school/index.tsx
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Button, Input, Picker, Text, Textarea, View } from '@tarojs/components';
|
||||||
|
import {
|
||||||
|
generateSchoolRecommendation,
|
||||||
|
loadSchoolRecommendationReports,
|
||||||
|
type SchoolRecommendationReport,
|
||||||
|
} from '@/services/ai';
|
||||||
|
import { loadProfile, type StudentProfile } from '@/services/profile';
|
||||||
|
import '../student.css';
|
||||||
|
|
||||||
|
const riskOptions = [
|
||||||
|
{ label: '均衡', value: 'balanced' },
|
||||||
|
{ label: '稳妥', value: 'safe' },
|
||||||
|
{ label: '冲刺', value: 'sprint' },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function riskLabel(value?: string) {
|
||||||
|
return riskOptions.find(item => item.value === value)?.label || '未知';
|
||||||
|
}
|
||||||
|
|
||||||
|
function recommendationRows(report: SchoolRecommendationReport | null) {
|
||||||
|
return report?.resultPayload?.recommendedSchools || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function StudentAiSchoolPage() {
|
||||||
|
const [profile, setProfile] = useState<StudentProfile | null>(null);
|
||||||
|
const [reports, setReports] = useState<SchoolRecommendationReport[]>([]);
|
||||||
|
const [current, setCurrent] = useState<SchoolRecommendationReport | null>(null);
|
||||||
|
const [estimatedScore, setEstimatedScore] = useState('');
|
||||||
|
const [constraints, setConstraints] = useState('');
|
||||||
|
const [riskIndex, setRiskIndex] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadProfile().then(payload => setProfile(payload.item || null)).catch(() => setProfile(null));
|
||||||
|
loadSchoolRecommendationReports({ limit: 5 })
|
||||||
|
.then(payload => {
|
||||||
|
const items = payload.items || [];
|
||||||
|
setReports(items);
|
||||||
|
setCurrent(items[0] || null);
|
||||||
|
})
|
||||||
|
.catch(() => setReports([]));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function handleGenerate() {
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
const payload = await generateSchoolRecommendation({
|
||||||
|
regionId: profile?.target?.regionId || undefined,
|
||||||
|
estimatedScore: estimatedScore ? Number(estimatedScore) : undefined,
|
||||||
|
riskPreference: riskOptions[riskIndex].value,
|
||||||
|
constraints: constraints || undefined,
|
||||||
|
recommendationLimit: 5,
|
||||||
|
});
|
||||||
|
if (payload.item) {
|
||||||
|
setCurrent(payload.item);
|
||||||
|
setReports(previous => [payload.item!, ...previous.filter(item => item.id !== payload.item!.id)].slice(0, 5));
|
||||||
|
}
|
||||||
|
} catch (nextError) {
|
||||||
|
setError(nextError instanceof Error ? nextError.message : '生成失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = recommendationRows(current);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View className='student-page'>
|
||||||
|
<View className='student-topbar'>
|
||||||
|
<View className='student-title-block'>
|
||||||
|
<Text className='student-kicker'>AI Advisor</Text>
|
||||||
|
<Text className='student-title'>AI择校推荐</Text>
|
||||||
|
<Text className='student-subtitle'>
|
||||||
|
{profile?.target?.regionName ? `${profile.target.regionName} · ${profile.membership?.isSvip ? 'SVIP' : '需SVIP'}` : '先在个人中心选择目标地区'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
<View className='section'>
|
||||||
|
<Text className='section-title'>生成报告</Text>
|
||||||
|
<View className='list-stack'>
|
||||||
|
<View className='list-row'>
|
||||||
|
<Text className='row-meta'>预估分</Text>
|
||||||
|
<Input
|
||||||
|
type='number'
|
||||||
|
value={estimatedScore}
|
||||||
|
placeholder='例如 210'
|
||||||
|
onInput={event => setEstimatedScore(String(event.detail.value || ''))}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
<View className='list-row'>
|
||||||
|
<Text className='row-meta'>偏好</Text>
|
||||||
|
<Picker
|
||||||
|
mode='selector'
|
||||||
|
range={riskOptions.map(item => item.label)}
|
||||||
|
value={riskIndex}
|
||||||
|
onChange={event => setRiskIndex(Number(event.detail.value || 0))}
|
||||||
|
>
|
||||||
|
<Text className='row-main'>{riskOptions[riskIndex].label}</Text>
|
||||||
|
</Picker>
|
||||||
|
</View>
|
||||||
|
<View className='list-row'>
|
||||||
|
<Text className='row-meta'>限制条件</Text>
|
||||||
|
<Textarea
|
||||||
|
value={constraints}
|
||||||
|
placeholder='例如城市、专业限制、跨考顾虑'
|
||||||
|
maxlength={500}
|
||||||
|
onInput={event => setConstraints(String(event.detail.value || ''))}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<Button className='primary-button' loading={loading} onClick={handleGenerate}>生成推荐</Button>
|
||||||
|
{error ? <Text className='error-text'>{error}</Text> : null}
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{current ? (
|
||||||
|
<View className='section'>
|
||||||
|
<Text className='section-title'>推荐结果</Text>
|
||||||
|
<View className='hero-band'>
|
||||||
|
<Text className='hero-title'>{riskLabel(current.resultPayload.riskLevel)}方案</Text>
|
||||||
|
<Text className='hero-copy'>{current.resultPayload.summary}</Text>
|
||||||
|
</View>
|
||||||
|
<View className='list-stack'>
|
||||||
|
{rows.map(item => (
|
||||||
|
<View className='list-row' key={`${item.schoolId || item.schoolName}:${item.majorId || item.majorName || ''}`}>
|
||||||
|
<Text className='row-main'>{item.schoolName}{item.majorName ? ` · ${item.majorName}` : ''}</Text>
|
||||||
|
<Text className='row-meta'>
|
||||||
|
{riskLabel(item.riskLevel)} · 置信度 {Math.round((item.confidence || 0) * 100)}% · 差值 {item.scoreGap ?? '未知'} 分
|
||||||
|
</Text>
|
||||||
|
<Text className='row-meta'>{item.reason}</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<View className='section'>
|
||||||
|
<Text className='section-title'>历史报告</Text>
|
||||||
|
<View className='list-stack'>
|
||||||
|
{reports.map(item => (
|
||||||
|
<View className='list-row' key={item.id} onClick={() => setCurrent(item)}>
|
||||||
|
<Text className='row-main'>{item.resultPayload?.summary || '择校推荐报告'}</Text>
|
||||||
|
<Text className='row-meta'>{item.generatedAt || item.createdAt}</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
{!reports.length ? <View className='empty-state'>暂无历史报告。</View> : null}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@ export default function StudentHomePage() {
|
|||||||
{ name: '背单词', path: '/pages/student/vocabulary/index', meta: '复习计划' },
|
{ name: '背单词', path: '/pages/student/vocabulary/index', meta: '复习计划' },
|
||||||
{ name: '知识手册', path: '/pages/student/handbook/index', meta: '章节阅读' },
|
{ name: '知识手册', path: '/pages/student/handbook/index', meta: '章节阅读' },
|
||||||
{ name: '分数线', path: '/pages/student/scoreline/index', meta: '院校趋势' },
|
{ name: '分数线', path: '/pages/student/scoreline/index', meta: '院校趋势' },
|
||||||
|
{ name: 'AI择校', path: '/pages/student/ai-school/index', meta: 'SVIP报告' },
|
||||||
{ name: '资料', path: '/pages/student/assets/index', meta: 'PDF 预览' },
|
{ name: '资料', path: '/pages/student/assets/index', meta: 'PDF 预览' },
|
||||||
{ name: '个人中心', path: '/pages/student/profile/index', meta: '会员 / 订单' },
|
{ name: '个人中心', path: '/pages/student/profile/index', meta: '会员 / 订单' },
|
||||||
];
|
];
|
||||||
|
|||||||
83
apps/taro/src/services/ai.ts
Normal file
83
apps/taro/src/services/ai.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { apiRequest } from './api';
|
||||||
|
|
||||||
|
export type SchoolRecommendationRisk = 'safe' | 'balanced' | 'sprint' | 'unknown';
|
||||||
|
|
||||||
|
export interface GenerateSchoolRecommendationInput {
|
||||||
|
regionId?: string;
|
||||||
|
estimatedScore?: number;
|
||||||
|
examTrack?: string;
|
||||||
|
preferredCity?: string;
|
||||||
|
targetSchoolId?: string;
|
||||||
|
targetMajorId?: string;
|
||||||
|
riskPreference?: 'safe' | 'balanced' | 'sprint';
|
||||||
|
constraints?: string;
|
||||||
|
notes?: string;
|
||||||
|
recommendationLimit?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SchoolRecommendationCandidate {
|
||||||
|
schoolId?: string | null;
|
||||||
|
schoolName: string;
|
||||||
|
majorId?: string | null;
|
||||||
|
majorName?: string | null;
|
||||||
|
latestYear?: number | null;
|
||||||
|
latestScore?: number | null;
|
||||||
|
averageScore?: number | null;
|
||||||
|
scoreGap?: number | null;
|
||||||
|
riskLevel: SchoolRecommendationRisk;
|
||||||
|
confidence: number;
|
||||||
|
reason: string;
|
||||||
|
scorelineTrend?: {
|
||||||
|
years: number[];
|
||||||
|
scores: Array<number | null>;
|
||||||
|
direction: 'up' | 'down' | 'flat' | 'unknown';
|
||||||
|
};
|
||||||
|
tags?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SchoolRecommendationReportResult {
|
||||||
|
schemaVersion: 'school-recommendation-report-v1';
|
||||||
|
summary: string;
|
||||||
|
riskLevel: SchoolRecommendationRisk;
|
||||||
|
recommendedSchools: SchoolRecommendationCandidate[];
|
||||||
|
actionPlan: string[];
|
||||||
|
disclaimers: string[];
|
||||||
|
dataCoverage: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SchoolRecommendationReport {
|
||||||
|
id: string;
|
||||||
|
tenantId: string;
|
||||||
|
userId: string;
|
||||||
|
regionId?: string | null;
|
||||||
|
status: 'draft' | 'generated' | 'failed';
|
||||||
|
provider: string;
|
||||||
|
model?: string | null;
|
||||||
|
promptVersion: string;
|
||||||
|
inputPayload: GenerateSchoolRecommendationInput;
|
||||||
|
contextPayload: Record<string, unknown>;
|
||||||
|
resultPayload: SchoolRecommendationReportResult;
|
||||||
|
errorMessage?: string | null;
|
||||||
|
generatedAt?: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateSchoolRecommendation(input: GenerateSchoolRecommendationInput) {
|
||||||
|
return apiRequest<{ item?: SchoolRecommendationReport }>('/api/ai/school-recommendations/generate', {
|
||||||
|
method: 'POST',
|
||||||
|
body: input,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadSchoolRecommendationReports(query: { regionId?: string; limit?: number } = {}) {
|
||||||
|
return apiRequest<{ items?: SchoolRecommendationReport[] }>('/api/ai/school-recommendations', {
|
||||||
|
query,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadSchoolRecommendationReport(reportId: string) {
|
||||||
|
return apiRequest<{ item?: SchoolRecommendationReport }>('/api/ai/school-recommendations/detail', {
|
||||||
|
query: { reportId },
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -81,6 +81,7 @@
|
|||||||
| 知识手册 JSON 导入 | 可联调 | `/api/tenant-content/imports/*/handbook` |
|
| 知识手册 JSON 导入 | 可联调 | `/api/tenant-content/imports/*/handbook` |
|
||||||
| 分数线字段/院校/专业/记录/趋势 | 可联调 | `/api/scoreline/*` |
|
| 分数线字段/院校/专业/记录/趋势 | 可联调 | `/api/scoreline/*` |
|
||||||
| 分数线 JSON 导入 | 可联调 | `/api/tenant-content/imports/preview/scoreline`、`/api/tenant-content/imports/scoreline`;支持字段、院校、专业、记录、动态字段值、逐行 issue、幂等和审计 |
|
| 分数线 JSON 导入 | 可联调 | `/api/tenant-content/imports/preview/scoreline`、`/api/tenant-content/imports/scoreline`;支持字段、院校、专业、记录、动态字段值、逐行 issue、幂等和审计 |
|
||||||
|
| AI 择校推荐 | 可联调 | `ai_recommendation_reports` + `/api/ai/school-recommendations*`;默认要求当前学生有有效 SVIP,后端读取学生目标地区和分数线上下文,使用 `local_rules` 生成稳定 JSON 报告并写入报告台账和审计;真实 AI provider、人工 prompt 编排和 PDF 报告渲染待补 |
|
||||||
| 题目视频/批量预加载/搜索 | 可联调 | `/api/questions/*/videos`、`/api/videos/search`;付费视频列表不返回可播放 URL |
|
| 题目视频/批量预加载/搜索 | 可联调 | `/api/questions/*/videos`、`/api/videos/search`;付费视频列表不返回可播放 URL |
|
||||||
| 视频会员播放次数 | 可联调 | `POST /api/videos/play` 支持 SVIP/视频次数校验、签名播放、次数扣减、播放日志和动态水印上下文;`POST /api/videos/progress` 支持播放开始、心跳、完成上报;租户后台媒体报表已可按视频、用户、traceId 查询播放事件、观看秒数和完成率;深度防盗链和转码级水印继续补 |
|
| 视频会员播放次数 | 可联调 | `POST /api/videos/play` 支持 SVIP/视频次数校验、签名播放、次数扣减、播放日志和动态水印上下文;`POST /api/videos/progress` 支持播放开始、心跳、完成上报;租户后台媒体报表已可按视频、用户、traceId 查询播放事件、观看秒数和完成率;深度防盗链和转码级水印继续补 |
|
||||||
| 视频 JSON 导入和批量绑定 | 可联调 | `/api/tenant-content/imports/preview/videos`、`/api/tenant-content/imports/videos`;支持视频元数据、资源引用、播放模式、题目绑定和题目视频标记 |
|
| 视频 JSON 导入和批量绑定 | 可联调 | `/api/tenant-content/imports/preview/videos`、`/api/tenant-content/imports/videos`;支持视频元数据、资源引用、播放模式、题目绑定和题目视频标记 |
|
||||||
|
|||||||
@@ -31,7 +31,7 @@
|
|||||||
| 数据看板 | 可联调 | 租户 dashboard 聚合接口,收益、注册、学习、内容、激活码、反馈、趋势、24h 活跃、套餐销量和运营动态 | 预聚合 worker、缓存、慢 SQL 监控和销售转化看板 |
|
| 数据看板 | 可联调 | 租户 dashboard 聚合接口,收益、注册、学习、内容、激活码、反馈、趋势、24h 活跃、套餐销量和运营动态 | 预聚合 worker、缓存、慢 SQL 监控和销售转化看板 |
|
||||||
| 登录认证 | 可联调 | 短信 mock、阿里云/腾讯云短信 adapter、迁移期 session、Supabase Auth JWT、微信小程序登录、微信网页登录、QQ 登录、手机号绑定/换绑、OAuth 配置表 | 真实生产账号和回调域名联调 |
|
| 登录认证 | 可联调 | 短信 mock、阿里云/腾讯云短信 adapter、迁移期 session、Supabase Auth JWT、微信小程序登录、微信网页登录、QQ 登录、手机号绑定/换绑、OAuth 配置表 | 真实生产账号和回调域名联调 |
|
||||||
| 支付 | 可联调 | 订单、支付记录、手动确认权限保护、权益发放、租户商户配置、微信支付 JSAPI、支付宝 WAP/H5、webhook 幂等、退款状态机、退款通知、补偿 worker、资金对账导入比对、异常查询、差错工单和事件轨迹 | 官方账单自动下载、异常订单运营台、服务商/平台代收模式 |
|
| 支付 | 可联调 | 订单、支付记录、手动确认权限保护、权益发放、租户商户配置、微信支付 JSAPI、支付宝 WAP/H5、webhook 幂等、退款状态机、退款通知、补偿 worker、资金对账导入比对、异常查询、差错工单和事件轨迹 | 官方账单自动下载、异常订单运营台、服务商/平台代收模式 |
|
||||||
| AI 择校推荐 | 未开始 | 暂无 | 数据上下文、AI provider、JSON 报告 schema、PDF 报告生成 |
|
| AI 择校推荐 | 部分完成 | SVIP 门禁、学生输入 schema、地区/分数线上下文、`local_rules` 稳定 JSON 报告、报告台账/列表/详情、Taro 学生端基础页 | 真实 AI provider、prompt 版本管理后台、PDF 报告生成、人工复核和运营配置 |
|
||||||
| Taro 跨端 | 未开始 | 旧 Web 新 API 适配开始 | `apps/taro`、共享 API client、H5/小程序统一构建 |
|
| Taro 跨端 | 未开始 | 旧 Web 新 API 适配开始 | `apps/taro`、共享 API client、H5/小程序统一构建 |
|
||||||
|
|
||||||
## 接下来优先级
|
## 接下来优先级
|
||||||
|
|||||||
@@ -33,7 +33,7 @@
|
|||||||
| 商城/SVIP | `Store.tsx`、`SvipModal.tsx` | 部分覆盖 | 套餐、订单、订单详情/状态轮询、权益、激活码预检查/兑换、优惠券领取/下单抵扣、微信支付/支付宝 provider 主链路、内部退款状态机、微信/支付宝发起退款、退款查询确认、退款通知 webhook、支付/退款补偿 worker、全额退款权益撤销、资金对账手工/API 导入比对、异常查询、差错工单和事件轨迹已有;缺微信/支付宝官方账单自动下载、异常订单运营台和前端收银台/售后体验 |
|
| 商城/SVIP | `Store.tsx`、`SvipModal.tsx` | 部分覆盖 | 套餐、订单、订单详情/状态轮询、权益、激活码预检查/兑换、优惠券领取/下单抵扣、微信支付/支付宝 provider 主链路、内部退款状态机、微信/支付宝发起退款、退款查询确认、退款通知 webhook、支付/退款补偿 worker、全额退款权益撤销、资金对账手工/API 导入比对、异常查询、差错工单和事件轨迹已有;缺微信/支付宝官方账单自动下载、异常订单运营台和前端收银台/售后体验 |
|
||||||
| 个人中心 | `Profile.tsx` | 部分覆盖 | 基本资料、手机号绑定/换绑、权益、订单统计、练习历史、学习统计、签到积分、考试倒计时、趋势和勋章展示 API 已有;缺学习报告可视化 |
|
| 个人中心 | `Profile.tsx` | 部分覆盖 | 基本资料、手机号绑定/换绑、权益、订单统计、练习历史、学习统计、签到积分、考试倒计时、趋势和勋章展示 API 已有;缺学习报告可视化 |
|
||||||
| 资料下载 | `QuestionExporterPublishModal.tsx` 等 | 部分覆盖 | 资源台账、上传确认、签名下载、PDF/图片预览、动态水印上下文、worker 复检、内置安全扫描和外部 HTTP scanner 接入层已有;缺前端水印渲染、深度防盗链、真实 AV/内容安全服务联调和生命周期策略 |
|
| 资料下载 | `QuestionExporterPublishModal.tsx` 等 | 部分覆盖 | 资源台账、上传确认、签名下载、PDF/图片预览、动态水印上下文、worker 复检、内置安全扫描和外部 HTTP scanner 接入层已有;缺前端水印渲染、深度防盗链、真实 AV/内容安全服务联调和生命周期策略 |
|
||||||
| AI 择校推荐 | 业务规划新增 | 未覆盖 | 需设计学生输入 schema、地区数据上下文、AI JSON 输出、PDF 报告 |
|
| AI 择校推荐 | 业务规划新增 | 部分覆盖 | 已有 SVIP 门禁、学生输入 schema、地区/分数线上下文、稳定 JSON 输出、报告台账、审计和 Taro 学生端基础页;真实 AI provider、prompt 版本管理后台、报告 PDF 渲染和更细推荐算法待补 |
|
||||||
| 题目反馈 | `02-API接口.md` 用户反馈 | 部分覆盖 | 学生提交、本人列表、租户后台处理、状态事件、反馈奖励积分已覆盖;缺处理通知、前端消息提醒和批量统计 |
|
| 题目反馈 | `02-API接口.md` 用户反馈 | 部分覆盖 | 学生提交、本人列表、租户后台处理、状态事件、反馈奖励积分已覆盖;缺处理通知、前端消息提醒和批量统计 |
|
||||||
| 签到积分 | `Profile.tsx`、`02-API接口.md` | 部分覆盖 | 每日签到、连续签到基础、积分流水、重复签到幂等已覆盖;缺积分兑换、活动任务和更完整的运营规则 |
|
| 签到积分 | `Profile.tsx`、`02-API接口.md` | 部分覆盖 | 每日签到、连续签到基础、积分流水、重复签到幂等已覆盖;缺积分兑换、活动任务和更完整的运营规则 |
|
||||||
| 排行榜 | `leaderboard.pb.js`、`02-API接口.md` | 部分覆盖 | 已有刷题数、积分、背单词、模考最高分排行榜,支持租户/地区/班级范围和当前用户排名;后续补防刷、日/周榜预聚合、运营后台排名看板 |
|
| 排行榜 | `leaderboard.pb.js`、`02-API接口.md` | 部分覆盖 | 已有刷题数、积分、背单词、模考最高分排行榜,支持租户/地区/班级范围和当前用户排名;后续补防刷、日/周榜预聚合、运营后台排名看板 |
|
||||||
@@ -102,9 +102,10 @@
|
|||||||
5. 导入扩展:题目/单词/知识手册/分数线/视频已支持 JSON、CSV 和 Excel 预览导入,并可用 `executionMode=async` 进入 imports worker;导入后复检、导入任务详情、模板下载按钮、字段映射 API、Taro 字段别名编辑、异步轮询和 PocketBase JSON dry-run 报告已补,仍缺真实数据执行验收。
|
5. 导入扩展:题目/单词/知识手册/分数线/视频已支持 JSON、CSV 和 Excel 预览导入,并可用 `executionMode=async` 进入 imports worker;导入后复检、导入任务详情、模板下载按钮、字段映射 API、Taro 字段别名编辑、异步轮询和 PocketBase JSON dry-run 报告已补,仍缺真实数据执行验收。
|
||||||
6. 公共题库商业化:平台公共/地区题库授权、租户快照采纳、手动同步、自动同步 worker、同步通知、冲突查询、租户自改冲突保护和单条/批量冲突处理已完成基础闭环;还需生产定时调度、失败告警和更完整运营后台消息。
|
6. 公共题库商业化:平台公共/地区题库授权、租户快照采纳、手动同步、自动同步 worker、同步通知、冲突查询、租户自改冲突保护和单条/批量冲突处理已完成基础闭环;还需生产定时调度、失败告警和更完整运营后台消息。
|
||||||
7. CRM/销售结算:CRM worker、跟进分配策略、分佣规则、结算单、审核、打款状态、导出和凭证复核基础闭环已完成;仍缺富卡片模板、失败告警、死信运营台、真实打款 provider、发票和销售结算看板。
|
7. CRM/销售结算:CRM worker、跟进分配策略、分佣规则、结算单、审核、打款状态、导出和凭证复核基础闭环已完成;仍缺富卡片模板、失败告警、死信运营台、真实打款 provider、发票和销售结算看板。
|
||||||
8. 题目反馈增强:处理通知、消息提醒、问题聚合统计和内容修复闭环。
|
8. AI 择校推荐增强:后端 `local_rules` 地基、SVIP 门禁、报告列表/详情和 Taro 基础页已完成;仍缺真实 AI provider、prompt 编排、PDF 报告和后台运营配置。
|
||||||
9. 积分活动增强:积分兑换、活动任务、连续签到奖励规则和风控。
|
9. 题目反馈增强:处理通知、消息提醒、问题聚合统计和内容修复闭环。
|
||||||
10. 勋章增强:后台维护和手动发放已有;仍缺按学习行为、签到、积分、活动任务自动发放,以及发放通知。
|
10. 积分活动增强:积分兑换、活动任务、连续签到奖励规则和风控。
|
||||||
|
11. 勋章增强:后台维护和手动发放已有;仍缺按学习行为、签到、积分、活动任务自动发放,以及发放通知。
|
||||||
|
|
||||||
### P0:前端联调到云端前
|
### P0:前端联调到云端前
|
||||||
|
|
||||||
|
|||||||
@@ -138,10 +138,8 @@
|
|||||||
- 继续补批量 CRM 推送、学习督导自动化、跟进效果统计和更细导入模板体验。
|
- 继续补批量 CRM 推送、学习督导自动化、跟进效果统计和更细导入模板体验。
|
||||||
|
|
||||||
13. AI 择校推荐
|
13. AI 择校推荐
|
||||||
- 地区考试数据上下文。
|
- 已完成 `ai_recommendation_reports` 报告台账、SVIP 门禁、学生输入 schema、地区/分数线上下文、`local_rules` 稳定 JSON 输出、报告列表/详情接口和 Taro 学生端基础页。
|
||||||
- 学生输入 schema。
|
- 继续补真实 AI provider adapter、租户级 `app_private.tenant_secrets(secret_scope='ai')` 密钥联调、prompt 版本管理、运营后台配置、报告 PDF 渲染和人工复核流程。
|
||||||
- AI 返回 JSON schema。
|
|
||||||
- 报告渲染和 PDF 生成。
|
|
||||||
|
|
||||||
### P2 运营体验和企业交付
|
### P2 运营体验和企业交付
|
||||||
|
|
||||||
|
|||||||
@@ -2055,7 +2055,9 @@ ACTIVATION_CODE_REGION_MISMATCH
|
|||||||
- 手册目录和阅读。
|
- 手册目录和阅读。
|
||||||
9. `pages/scoreline/index`
|
9. `pages/scoreline/index`
|
||||||
- 动态字段筛选和趋势。
|
- 动态字段筛选和趋势。
|
||||||
10. `pages/profile/index`
|
10. `pages/ai-school/index`
|
||||||
|
- SVIP AI 择校推荐、报告历史和 JSON 报告渲染。
|
||||||
|
11. `pages/profile/index`
|
||||||
- 会员、订单、激活码、学习数据、勋章。
|
- 会员、订单、激活码、学习数据、勋章。
|
||||||
|
|
||||||
## 当前 Taro 实现进度
|
## 当前 Taro 实现进度
|
||||||
@@ -2076,6 +2078,7 @@ pages/student/order-detail/index
|
|||||||
pages/student/vocabulary/index
|
pages/student/vocabulary/index
|
||||||
pages/student/handbook/index
|
pages/student/handbook/index
|
||||||
pages/student/scoreline/index
|
pages/student/scoreline/index
|
||||||
|
pages/student/ai-school/index
|
||||||
pages/student/assets/index
|
pages/student/assets/index
|
||||||
pages/student/profile/index
|
pages/student/profile/index
|
||||||
```
|
```
|
||||||
@@ -2088,6 +2091,7 @@ src/services/learning.ts 练习 session、答题、收藏、错题/收藏复
|
|||||||
src/services/commerce.ts 套餐、优惠券、下单、支付参数、订单详情、权益、激活码
|
src/services/commerce.ts 套餐、优惠券、下单、支付参数、订单详情、权益、激活码
|
||||||
src/services/profile.ts 个人中心、地区目标、签到、反馈、勋章、倒计时
|
src/services/profile.ts 个人中心、地区目标、签到、反馈、勋章、倒计时
|
||||||
src/services/video.ts 题目视频列表、播放签名
|
src/services/video.ts 题目视频列表、播放签名
|
||||||
|
src/services/ai.ts AI 择校推荐生成、报告列表、报告详情
|
||||||
src/services/tenantAdmin.ts 租户后台看板、权限矩阵、成员、学生创建/批量导入/分班/备注/跟进、内容、营销、设置、角色模板写操作、公共题库采纳/同步/单条和批量冲突处理、导入详情/复检、CRM 配置/队列、分佣规则/成员比例/订单/结算
|
src/services/tenantAdmin.ts 租户后台看板、权限矩阵、成员、学生创建/批量导入/分班/备注/跟进、内容、营销、设置、角色模板写操作、公共题库采纳/同步/单条和批量冲突处理、导入详情/复检、CRM 配置/队列、分佣规则/成员比例/订单/结算
|
||||||
src/services/platformAdmin.ts 平台后台租户、套餐账单、用量、公共题库授权
|
src/services/platformAdmin.ts 平台后台租户、套餐账单、用量、公共题库授权
|
||||||
```
|
```
|
||||||
@@ -2110,6 +2114,87 @@ npm run build:taro:h5:platform
|
|||||||
- 平台后台:租户创建、状态变更、订阅开通、账单生成、人工收款确认、用量录入、公共题库授权编辑已接第一版;继续补租户详情/编辑、平台审计、自动计费和批量账单操作。
|
- 平台后台:租户创建、状态变更、订阅开通、账单生成、人工收款确认、用量录入、公共题库授权编辑已接第一版;继续补租户详情/编辑、平台审计、自动计费和批量账单操作。
|
||||||
- 小程序:验证 `Taro.login`、微信支付、分享 scene/referral、Supabase client 兼容性;如不稳定,保留 `apps/api/auth/*` 作为小程序登录适配层。
|
- 小程序:验证 `Taro.login`、微信支付、分享 scene/referral、Supabase client 兼容性;如不稳定,保留 `apps/api/auth/*` 作为小程序登录适配层。
|
||||||
|
|
||||||
|
## AI 择校推荐接入
|
||||||
|
|
||||||
|
AI 择校推荐是学生端 SVIP 功能,前端只调用 `apps/api`,不要在 H5/小程序内保存任何 AI provider key、prompt secret 或服务端模型配置。当前后端默认使用 deterministic `local_rules` provider,基于学生目标地区和 `scoreline_records` 生成稳定 JSON 报告;后续真实 AI provider 仍保持同一接口和 JSON schema。
|
||||||
|
|
||||||
|
生成报告:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/ai/school-recommendations/generate
|
||||||
|
```
|
||||||
|
|
||||||
|
请求体:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"regionId": "<regionId>",
|
||||||
|
"estimatedScore": 210,
|
||||||
|
"riskPreference": "balanced",
|
||||||
|
"constraints": "优先考虑计算机相关专业",
|
||||||
|
"recommendationLimit": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`riskPreference` 支持 `safe`、`balanced`、`sprint`。`regionId` 不传时后端会使用 `/api/profile/me` 中学生档案的目标地区。后端会校验该地区属于当前租户,并要求当前学生有有效 SVIP;无权限时返回 `AI_SVIP_REQUIRED`。
|
||||||
|
|
||||||
|
响应核心结构:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"item": {
|
||||||
|
"id": "<reportId>",
|
||||||
|
"status": "generated",
|
||||||
|
"provider": "local_rules",
|
||||||
|
"model": "local-scoreline-rules-v1",
|
||||||
|
"promptVersion": "school-recommendation-v1",
|
||||||
|
"resultPayload": {
|
||||||
|
"schemaVersion": "school-recommendation-report-v1",
|
||||||
|
"summary": "基于当前地区历年分数线...",
|
||||||
|
"riskLevel": "balanced",
|
||||||
|
"recommendedSchools": [
|
||||||
|
{
|
||||||
|
"schoolId": "<schoolId>",
|
||||||
|
"schoolName": "烟测学院",
|
||||||
|
"majorId": "<majorId>",
|
||||||
|
"majorName": "计算机科学与技术",
|
||||||
|
"latestYear": 2026,
|
||||||
|
"latestScore": 188,
|
||||||
|
"scoreGap": 22,
|
||||||
|
"riskLevel": "safe",
|
||||||
|
"confidence": 0.9,
|
||||||
|
"reason": "预估分与最新参考线差值约 22 分...",
|
||||||
|
"scorelineTrend": {
|
||||||
|
"years": [2026],
|
||||||
|
"scores": [188],
|
||||||
|
"direction": "unknown"
|
||||||
|
},
|
||||||
|
"tags": ["稳妥", "趋势不足", "样本较少"]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"actionPlan": [],
|
||||||
|
"disclaimers": [],
|
||||||
|
"dataCoverage": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
报告历史:
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/ai/school-recommendations?regionId=<regionId>&limit=20
|
||||||
|
GET /api/ai/school-recommendations/detail?reportId=<reportId>
|
||||||
|
```
|
||||||
|
|
||||||
|
前端渲染建议:
|
||||||
|
|
||||||
|
- `resultPayload.schemaVersion` 必须等于 `school-recommendation-report-v1`,未知版本先降级为只展示 summary 和原始 JSON。
|
||||||
|
- `recommendedSchools` 是服务端已排序结果,前端不要重新按分数线做业务排序。
|
||||||
|
- `disclaimers` 必须展示在报告底部或导出 PDF 中。
|
||||||
|
- 报告详情只能展示当前登录学生自己的报告,遇到 `AI_REPORT_NOT_FOUND` 按“报告不存在或无权访问”处理。
|
||||||
|
- 当前 Taro 基础页在 `pages/student/ai-school/index`,service 在 `src/services/ai.ts`。
|
||||||
|
|
||||||
## 租户后台前端建议
|
## 租户后台前端建议
|
||||||
|
|
||||||
租户后台可以先做 H5 管理台,也可以后续使用 Taro H5 复用部分组件。优先页面:
|
租户后台可以先做 H5 管理台,也可以后续使用 Taro H5 复用部分组件。优先页面:
|
||||||
|
|||||||
@@ -1649,6 +1649,70 @@ async function testScoreline() {
|
|||||||
assert.ok(years.items?.includes(2026), 'scoreline years should include 2026');
|
assert.ok(years.items?.includes(2026), 'scoreline years should include 2026');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function testAiSchoolRecommendationRequiresSvip() {
|
||||||
|
const denied = await request('/api/ai/school-recommendations/generate', {
|
||||||
|
userId: SECOND_STUDENT_USER_ID,
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
regionId: ids.region,
|
||||||
|
estimatedScore: 210,
|
||||||
|
riskPreference: 'balanced',
|
||||||
|
},
|
||||||
|
expectStatus: 403,
|
||||||
|
});
|
||||||
|
assert.equal(denied.code, 'AI_SVIP_REQUIRED', 'AI school recommendation should require SVIP entitlement');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testAiSchoolRecommendationAfterSvip() {
|
||||||
|
const generated = await request('/api/ai/school-recommendations/generate', {
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
regionId: ids.region,
|
||||||
|
estimatedScore: 210,
|
||||||
|
riskPreference: 'balanced',
|
||||||
|
constraints: '优先考虑计算机相关专业',
|
||||||
|
recommendationLimit: 5,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(generated.item?.status, 'generated', 'AI school recommendation should generate report');
|
||||||
|
assert.equal(generated.item?.provider, 'local_rules', 'AI recommendation should use deterministic local provider in tests');
|
||||||
|
assert.equal(generated.item?.resultPayload?.schemaVersion, 'school-recommendation-report-v1', 'AI report should use stable schema');
|
||||||
|
assert.ok(
|
||||||
|
generated.item?.resultPayload?.recommendedSchools?.some(item => item.schoolName === '烟测学院'),
|
||||||
|
'AI report should recommend from tenant scoreline context',
|
||||||
|
);
|
||||||
|
assert.ok(!JSON.stringify(generated).includes('secret'), 'AI recommendation response should not leak provider secrets');
|
||||||
|
|
||||||
|
const reports = await request('/api/ai/school-recommendations', {
|
||||||
|
query: { limit: 5 },
|
||||||
|
});
|
||||||
|
assert.ok(reports.items?.some(item => item.id === generated.item.id), 'AI report list should include generated report');
|
||||||
|
|
||||||
|
const detail = await request('/api/ai/school-recommendations/detail', {
|
||||||
|
query: { reportId: generated.item.id },
|
||||||
|
});
|
||||||
|
assert.equal(detail.item?.id, generated.item.id, 'AI report detail should load own report');
|
||||||
|
|
||||||
|
const otherStudentDenied = await request('/api/ai/school-recommendations/detail', {
|
||||||
|
userId: SECOND_STUDENT_USER_ID,
|
||||||
|
query: { reportId: generated.item.id },
|
||||||
|
expectStatus: 404,
|
||||||
|
});
|
||||||
|
assert.equal(otherStudentDenied.code, 'AI_REPORT_NOT_FOUND', 'students must not read other students AI reports');
|
||||||
|
|
||||||
|
const partnerTenantDenied = await request('/api/ai/school-recommendations/generate', {
|
||||||
|
tenantId: PARTNER_TENANT_ID,
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
regionId: ids.region,
|
||||||
|
estimatedScore: 210,
|
||||||
|
riskPreference: 'balanced',
|
||||||
|
},
|
||||||
|
expectStatus: 404,
|
||||||
|
});
|
||||||
|
assert.equal(partnerTenantDenied.code, 'PROFILE_NOT_FOUND', 'AI recommendation must not use a student profile from another tenant');
|
||||||
|
}
|
||||||
|
|
||||||
async function testVideos() {
|
async function testVideos() {
|
||||||
const single = await request(`/api/questions/${ids.question}/videos`);
|
const single = await request(`/api/questions/${ids.question}/videos`);
|
||||||
assert.ok(single.total >= 1, 'question should have videos');
|
assert.ok(single.total >= 1, 'question should have videos');
|
||||||
@@ -7181,9 +7245,11 @@ async function main() {
|
|||||||
await check('profile', testProfile);
|
await check('profile', testProfile);
|
||||||
await check('learning leaderboard', testLearningLeaderboard);
|
await check('learning leaderboard', testLearningLeaderboard);
|
||||||
await check('scoreline', testScoreline);
|
await check('scoreline', testScoreline);
|
||||||
|
await check('AI school recommendation SVIP gate', testAiSchoolRecommendationRequiresSvip);
|
||||||
await check('question videos', testVideos);
|
await check('question videos', testVideos);
|
||||||
await check('vocabulary', testVocabulary);
|
await check('vocabulary', testVocabulary);
|
||||||
await check('commerce', testCommerce);
|
await check('commerce', testCommerce);
|
||||||
|
await check('AI school recommendation', testAiSchoolRecommendationAfterSvip);
|
||||||
await check('tenant isolation', testTenantIsolation);
|
await check('tenant isolation', testTenantIsolation);
|
||||||
await check('tenant content admin', testTenantContentAdmin);
|
await check('tenant content admin', testTenantContentAdmin);
|
||||||
await check('tenant content assets and imports', testTenantContentAssetsAndImports);
|
await check('tenant content assets and imports', testTenantContentAssetsAndImports);
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
create table if not exists public.ai_recommendation_reports (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
tenant_id uuid not null references public.tenants(id) on delete cascade,
|
||||||
|
user_id uuid not null references public.platform_users(id) on delete cascade,
|
||||||
|
region_id uuid references public.regions(id) on delete set null,
|
||||||
|
status text not null default 'generated'
|
||||||
|
check (status in ('draft', 'generated', 'failed')),
|
||||||
|
provider text not null default 'local_rules',
|
||||||
|
model text,
|
||||||
|
prompt_version text not null default 'school-recommendation-v1',
|
||||||
|
input_payload jsonb not null default '{}'::jsonb,
|
||||||
|
context_payload jsonb not null default '{}'::jsonb,
|
||||||
|
result_payload jsonb not null default '{}'::jsonb,
|
||||||
|
error_message text,
|
||||||
|
generated_at timestamptz,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
create index if not exists idx_ai_recommendation_reports_user
|
||||||
|
on public.ai_recommendation_reports(tenant_id, user_id, created_at desc);
|
||||||
|
|
||||||
|
create index if not exists idx_ai_recommendation_reports_region
|
||||||
|
on public.ai_recommendation_reports(tenant_id, region_id, created_at desc);
|
||||||
|
|
||||||
|
alter table public.ai_recommendation_reports enable row level security;
|
||||||
|
|
||||||
|
drop policy if exists tenant_isolation on public.ai_recommendation_reports;
|
||||||
|
create policy tenant_isolation on public.ai_recommendation_reports
|
||||||
|
for all
|
||||||
|
using (tenant_id = app.current_tenant_id() or app.is_platform_admin())
|
||||||
|
with check (tenant_id = app.current_tenant_id() or app.is_platform_admin());
|
||||||
|
|
||||||
|
drop trigger if exists set_updated_at on public.ai_recommendation_reports;
|
||||||
|
create trigger set_updated_at
|
||||||
|
before update on public.ai_recommendation_reports
|
||||||
|
for each row execute function app.touch_updated_at();
|
||||||
Reference in New Issue
Block a user