Add CRUD support for training videos
这个提交包含在:
397
server/db.ts
397
server/db.ts
@@ -27,6 +27,7 @@ import {
|
||||
visionTestRuns, InsertVisionTestRun,
|
||||
} from "../drizzle/schema";
|
||||
import { ENV } from './_core/env';
|
||||
import { fetchTutorialMetrics, shouldRefreshTutorialMetrics } from "./tutorialMetrics";
|
||||
|
||||
let _db: ReturnType<typeof drizzle> | null = null;
|
||||
|
||||
@@ -94,6 +95,11 @@ export const ACHIEVEMENT_DEFINITION_SEED_DATA: Omit<InsertAchievementDefinition,
|
||||
{ key: "ntrp_3_0", name: "NTRP 3.0", description: "综合评分达到 3.0", category: "rating", rarity: "epic", icon: "🚀", metricKey: "ntrp_rating", targetValue: 3.0, tier: 2, sortOrder: 51, isHidden: 0, isActive: 1 },
|
||||
{ key: "pk_session_1", name: "训练 PK", description: "完成首个 PK 会话", category: "pk", rarity: "rare", icon: "⚔️", metricKey: "pk_count", targetValue: 1, tier: 1, sortOrder: 60, isHidden: 0, isActive: 1 },
|
||||
{ key: "plan_link_5", name: "按计划训练", description: "累计 5 次训练匹配训练计划", category: "plan", rarity: "rare", icon: "🗂️", metricKey: "plan_matches", targetValue: 5, tier: 1, sortOrder: 70, isHidden: 0, isActive: 1 },
|
||||
{ key: "ai_tutorial_1", name: "AI 教程开箱", description: "完成首个 AI 部署或测试教程", category: "tutorial", rarity: "common", icon: "🧭", metricKey: "tutorial_completed_count", targetValue: 1, tier: 1, sortOrder: 80, isHidden: 0, isActive: 1 },
|
||||
{ key: "ai_tutorial_3", name: "AI 学习加速", description: "累计完成 3 个 AI 部署或测试教程", category: "tutorial", rarity: "rare", icon: "🚧", metricKey: "tutorial_completed_count", targetValue: 3, tier: 2, sortOrder: 81, isHidden: 0, isActive: 1 },
|
||||
{ key: "ai_deploy_path", name: "部署通关", description: "完成全部 AI 部署专题教程", category: "tutorial", rarity: "epic", icon: "🚀", metricKey: "ai_deploy_completed_count", targetValue: 5, tier: 3, sortOrder: 82, isHidden: 0, isActive: 1 },
|
||||
{ key: "ai_testing_path", name: "测试通关", description: "完成全部 AI 测试专题教程", category: "tutorial", rarity: "epic", icon: "🧪", metricKey: "ai_testing_completed_count", targetValue: 5, tier: 3, sortOrder: 83, isHidden: 0, isActive: 1 },
|
||||
{ key: "ai_tutorial_master", name: "实战运维学徒", description: "完成全部 AI 学习路径", category: "tutorial", rarity: "legendary", icon: "🏗️", metricKey: "tutorial_completed_count", targetValue: 10, tier: 4, sortOrder: 84, isHidden: 0, isActive: 1 },
|
||||
];
|
||||
|
||||
export async function getDb() {
|
||||
@@ -291,6 +297,13 @@ export async function getUserByOpenId(openId: string) {
|
||||
return result.length > 0 ? result[0] : undefined;
|
||||
}
|
||||
|
||||
export async function getUserById(userId: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return undefined;
|
||||
const result = await db.select().from(users).where(eq(users.id, userId)).limit(1);
|
||||
return result.length > 0 ? result[0] : undefined;
|
||||
}
|
||||
|
||||
export async function getUserByUsername(username: string) {
|
||||
const db = await getDb();
|
||||
if (!db) return undefined;
|
||||
@@ -352,6 +365,19 @@ export async function updateUserProfile(userId: number, data: {
|
||||
skillLevel?: "beginner" | "intermediate" | "advanced";
|
||||
trainingGoals?: string;
|
||||
ntrpRating?: number;
|
||||
manualNtrpRating?: number | null;
|
||||
manualNtrpCapturedAt?: Date | null;
|
||||
heightCm?: number | null;
|
||||
weightKg?: number | null;
|
||||
sprintSpeedScore?: number | null;
|
||||
explosivePowerScore?: number | null;
|
||||
agilityScore?: number | null;
|
||||
enduranceScore?: number | null;
|
||||
flexibilityScore?: number | null;
|
||||
coreStabilityScore?: number | null;
|
||||
shoulderMobilityScore?: number | null;
|
||||
hipMobilityScore?: number | null;
|
||||
assessmentNotes?: string | null;
|
||||
totalSessions?: number;
|
||||
totalMinutes?: number;
|
||||
currentStreak?: number;
|
||||
@@ -363,6 +389,81 @@ export async function updateUserProfile(userId: number, data: {
|
||||
await db.update(users).set(data).where(eq(users.id, userId));
|
||||
}
|
||||
|
||||
export const TRAINING_PROFILE_FIELD_LABELS = {
|
||||
heightCm: "身高",
|
||||
weightKg: "体重",
|
||||
sprintSpeedScore: "速度",
|
||||
explosivePowerScore: "爆发力",
|
||||
agilityScore: "敏捷性",
|
||||
enduranceScore: "耐力",
|
||||
flexibilityScore: "柔韧性",
|
||||
coreStabilityScore: "核心稳定性",
|
||||
shoulderMobilityScore: "肩部灵活性",
|
||||
hipMobilityScore: "髋部灵活性",
|
||||
manualNtrpRating: "人工 NTRP 基线",
|
||||
} as const;
|
||||
|
||||
export type TrainingProfileFieldKey = keyof typeof TRAINING_PROFILE_FIELD_LABELS;
|
||||
|
||||
const TRAINING_PROFILE_REQUIRED_FIELDS: TrainingProfileFieldKey[] = [
|
||||
"heightCm",
|
||||
"weightKg",
|
||||
"sprintSpeedScore",
|
||||
"explosivePowerScore",
|
||||
"agilityScore",
|
||||
"enduranceScore",
|
||||
"flexibilityScore",
|
||||
"coreStabilityScore",
|
||||
"shoulderMobilityScore",
|
||||
"hipMobilityScore",
|
||||
];
|
||||
|
||||
export function getMissingTrainingProfileFields(
|
||||
user: typeof users.$inferSelect,
|
||||
hasSystemNtrp: boolean,
|
||||
) {
|
||||
const missing = TRAINING_PROFILE_REQUIRED_FIELDS.filter((field) => user[field] == null);
|
||||
if (!hasSystemNtrp && user.manualNtrpRating == null) {
|
||||
missing.push("manualNtrpRating");
|
||||
}
|
||||
return missing;
|
||||
}
|
||||
|
||||
export function getTrainingProfileStatus(
|
||||
user: typeof users.$inferSelect,
|
||||
latestSnapshot?: { rating?: number | null } | null,
|
||||
) {
|
||||
const hasSystemNtrp = latestSnapshot?.rating != null;
|
||||
const missingFields = getMissingTrainingProfileFields(user, hasSystemNtrp);
|
||||
const effectiveNtrp = latestSnapshot?.rating ?? user.manualNtrpRating ?? user.ntrpRating ?? 1.5;
|
||||
const ntrpSource: "system" | "manual" | "default" = hasSystemNtrp
|
||||
? "system"
|
||||
: user.manualNtrpRating != null
|
||||
? "manual"
|
||||
: "default";
|
||||
|
||||
return {
|
||||
hasSystemNtrp,
|
||||
isComplete: missingFields.length === 0,
|
||||
missingFields,
|
||||
effectiveNtrp,
|
||||
ntrpSource,
|
||||
assessmentSnapshot: {
|
||||
heightCm: user.heightCm ?? null,
|
||||
weightKg: user.weightKg ?? null,
|
||||
sprintSpeedScore: user.sprintSpeedScore ?? null,
|
||||
explosivePowerScore: user.explosivePowerScore ?? null,
|
||||
agilityScore: user.agilityScore ?? null,
|
||||
enduranceScore: user.enduranceScore ?? null,
|
||||
flexibilityScore: user.flexibilityScore ?? null,
|
||||
coreStabilityScore: user.coreStabilityScore ?? null,
|
||||
shoulderMobilityScore: user.shoulderMobilityScore ?? null,
|
||||
hipMobilityScore: user.hipMobilityScore ?? null,
|
||||
assessmentNotes: user.assessmentNotes ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ===== TRAINING PLAN OPERATIONS =====
|
||||
|
||||
export async function createTrainingPlan(plan: InsertTrainingPlan) {
|
||||
@@ -450,6 +551,15 @@ export async function getVideoById(videoId: number) {
|
||||
return result.length > 0 ? result[0] : undefined;
|
||||
}
|
||||
|
||||
export async function getUserVideoById(userId: number, videoId: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return undefined;
|
||||
const result = await db.select().from(trainingVideos)
|
||||
.where(and(eq(trainingVideos.userId, userId), eq(trainingVideos.id, videoId)))
|
||||
.limit(1);
|
||||
return result.length > 0 ? result[0] : undefined;
|
||||
}
|
||||
|
||||
export async function getVideoByFileKey(userId: number, fileKey: string) {
|
||||
const db = await getDb();
|
||||
if (!db) return undefined;
|
||||
@@ -465,6 +575,54 @@ export async function updateVideoStatus(videoId: number, status: "pending" | "an
|
||||
await db.update(trainingVideos).set({ analysisStatus: status }).where(eq(trainingVideos.id, videoId));
|
||||
}
|
||||
|
||||
export async function updateUserVideo(
|
||||
userId: number,
|
||||
videoId: number,
|
||||
patch: {
|
||||
title?: string;
|
||||
exerciseType?: string | null;
|
||||
},
|
||||
) {
|
||||
const db = await getDb();
|
||||
if (!db) return false;
|
||||
|
||||
const video = await getUserVideoById(userId, videoId);
|
||||
if (!video) return false;
|
||||
|
||||
await db.update(trainingVideos)
|
||||
.set({
|
||||
title: patch.title ?? video.title,
|
||||
exerciseType: patch.exerciseType === undefined ? video.exerciseType : patch.exerciseType,
|
||||
})
|
||||
.where(and(eq(trainingVideos.userId, userId), eq(trainingVideos.id, videoId)));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function deleteUserVideo(userId: number, videoId: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return false;
|
||||
|
||||
const video = await getUserVideoById(userId, videoId);
|
||||
if (!video) return false;
|
||||
|
||||
await db.delete(poseAnalyses)
|
||||
.where(and(eq(poseAnalyses.userId, userId), eq(poseAnalyses.videoId, videoId)));
|
||||
|
||||
await db.update(trainingRecords)
|
||||
.set({ videoId: null })
|
||||
.where(and(eq(trainingRecords.userId, userId), eq(trainingRecords.videoId, videoId)));
|
||||
|
||||
await db.update(liveAnalysisSessions)
|
||||
.set({ videoId: null, videoUrl: null })
|
||||
.where(and(eq(liveAnalysisSessions.userId, userId), eq(liveAnalysisSessions.videoId, videoId)));
|
||||
|
||||
await db.delete(trainingVideos)
|
||||
.where(and(eq(trainingVideos.userId, userId), eq(trainingVideos.id, videoId)));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ===== POSE ANALYSIS OPERATIONS =====
|
||||
|
||||
export async function createPoseAnalysis(analysis: InsertPoseAnalysis) {
|
||||
@@ -864,6 +1022,9 @@ function metricValueFromContext(metricKey: string, context: {
|
||||
ntrpRating: number;
|
||||
pkCount: number;
|
||||
planMatches: number;
|
||||
tutorialCompletedCount: number;
|
||||
aiDeployCompletedCount: number;
|
||||
aiTestingCompletedCount: number;
|
||||
}) {
|
||||
const metricMap: Record<string, number> = {
|
||||
training_days: context.trainingDays,
|
||||
@@ -877,6 +1038,9 @@ function metricValueFromContext(metricKey: string, context: {
|
||||
ntrp_rating: context.ntrpRating,
|
||||
pk_count: context.pkCount,
|
||||
plan_matches: context.planMatches,
|
||||
tutorial_completed_count: context.tutorialCompletedCount,
|
||||
ai_deploy_completed_count: context.aiDeployCompletedCount,
|
||||
ai_testing_completed_count: context.aiTestingCompletedCount,
|
||||
};
|
||||
return metricMap[metricKey] ?? 0;
|
||||
}
|
||||
@@ -890,8 +1054,22 @@ export async function refreshAchievementsForUser(userId: number) {
|
||||
const records = await db.select().from(trainingRecords).where(and(eq(trainingRecords.userId, userId), eq(trainingRecords.completed, 1)));
|
||||
const aggregates = await db.select().from(dailyTrainingAggregates).where(eq(dailyTrainingAggregates.userId, userId));
|
||||
const liveSessions = await db.select().from(liveAnalysisSessions).where(eq(liveAnalysisSessions.userId, userId));
|
||||
const tutorialRows = await db.select({
|
||||
id: tutorialVideos.id,
|
||||
topicArea: tutorialVideos.topicArea,
|
||||
}).from(tutorialVideos);
|
||||
const tutorialProgressRows = await db.select().from(tutorialProgress).where(eq(tutorialProgress.userId, userId));
|
||||
const [userRow] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
|
||||
|
||||
const tutorialTopicById = new Map(tutorialRows.map((row) => [row.id, row.topicArea || "tennis_skill"]));
|
||||
const completedTutorials = tutorialProgressRows.filter((row) => row.completed === 1 || row.watched === 1);
|
||||
const tutorialCompletedCount = completedTutorials.filter((row) => {
|
||||
const topicArea = tutorialTopicById.get(row.tutorialId);
|
||||
return topicArea === "ai_deploy" || topicArea === "ai_testing";
|
||||
}).length;
|
||||
const aiDeployCompletedCount = completedTutorials.filter((row) => tutorialTopicById.get(row.tutorialId) === "ai_deploy").length;
|
||||
const aiTestingCompletedCount = completedTutorials.filter((row) => tutorialTopicById.get(row.tutorialId) === "ai_testing").length;
|
||||
|
||||
const bestScore = Math.max(
|
||||
0,
|
||||
...records.map((record) => record.poseScore || 0),
|
||||
@@ -910,6 +1088,9 @@ export async function refreshAchievementsForUser(userId: number) {
|
||||
ntrpRating: userRow?.ntrpRating || 1.5,
|
||||
pkCount: records.filter(record => ((record.metadata as Record<string, unknown> | null)?.sessionMode) === "pk").length,
|
||||
planMatches,
|
||||
tutorialCompletedCount,
|
||||
aiDeployCompletedCount,
|
||||
aiTestingCompletedCount,
|
||||
};
|
||||
|
||||
const unlockedKeys: string[] = [];
|
||||
@@ -1364,143 +1545,236 @@ export async function failVisionTestRun(taskId: string, error: string) {
|
||||
|
||||
// ===== TUTORIAL OPERATIONS =====
|
||||
|
||||
export const TUTORIAL_SEED_DATA: Omit<InsertTutorialVideo, "id">[] = [
|
||||
function tutorialSection(title: string, items: string[]) {
|
||||
return { title, items };
|
||||
}
|
||||
|
||||
const TENNIS_TUTORIAL_BASE = [
|
||||
{
|
||||
slug: "forehand-fundamentals",
|
||||
title: "正手击球基础",
|
||||
category: "forehand",
|
||||
skillLevel: "beginner",
|
||||
skillLevel: "beginner" as const,
|
||||
description: "学习正手击球的基本站位、握拍方式和挥拍轨迹,建立稳定的正手基础。",
|
||||
keyPoints: JSON.stringify(["东方式或半西方式握拍", "侧身引拍,肩膀转动90度", "从低到高的挥拍轨迹", "随挥至对侧肩膀", "重心转移从后脚到前脚"]),
|
||||
commonMistakes: JSON.stringify(["手腕过度发力", "没有转体", "击球点太靠后", "随挥不充分"]),
|
||||
keyPoints: ["东方式或半西方式握拍", "侧身引拍,肩膀转动90度", "从低到高的挥拍轨迹", "随挥至对侧肩膀", "重心转移从后脚到前脚"],
|
||||
commonMistakes: ["手腕过度发力", "没有转体", "击球点太靠后", "随挥不充分"],
|
||||
duration: 300,
|
||||
sortOrder: 1,
|
||||
sortOrder: 101,
|
||||
},
|
||||
{
|
||||
slug: "backhand-fundamentals",
|
||||
title: "反手击球基础",
|
||||
category: "backhand",
|
||||
skillLevel: "beginner",
|
||||
skillLevel: "beginner" as const,
|
||||
description: "掌握单手和双手反手的核心技术,包括握拍转换和击球时机。",
|
||||
keyPoints: JSON.stringify(["双手反手更适合初学者", "早引拍,肩膀充分转动", "击球点在身体前方", "保持手臂伸展"]),
|
||||
commonMistakes: JSON.stringify(["只用手臂发力", "击球点太迟", "缺少随挥", "脚步不到位"]),
|
||||
keyPoints: ["双手反手更适合初学者", "早引拍,肩膀充分转动", "击球点在身体前方", "保持手臂伸展"],
|
||||
commonMistakes: ["只用手臂发力", "击球点太迟", "缺少随挥", "脚步不到位"],
|
||||
duration: 300,
|
||||
sortOrder: 2,
|
||||
sortOrder: 102,
|
||||
},
|
||||
{
|
||||
slug: "serve-fundamentals",
|
||||
title: "发球技术",
|
||||
category: "serve",
|
||||
skillLevel: "beginner",
|
||||
skillLevel: "beginner" as const,
|
||||
description: "从抛球、引拍到击球的完整发球动作分解与练习。",
|
||||
keyPoints: JSON.stringify(["稳定的抛球是关键", "大陆式握拍", "引拍时身体充分弓身", "最高点击球", "手腕内旋加速"]),
|
||||
commonMistakes: JSON.stringify(["抛球不稳定", "手臂弯曲击球", "重心没有向前", "发力时机不对"]),
|
||||
keyPoints: ["稳定的抛球是关键", "大陆式握拍", "引拍时身体充分弓身", "最高点击球", "手腕内旋加速"],
|
||||
commonMistakes: ["抛球不稳定", "手臂弯曲击球", "重心没有向前", "发力时机不对"],
|
||||
duration: 360,
|
||||
sortOrder: 3,
|
||||
sortOrder: 103,
|
||||
},
|
||||
{
|
||||
slug: "volley-fundamentals",
|
||||
title: "截击技术",
|
||||
category: "volley",
|
||||
skillLevel: "intermediate",
|
||||
skillLevel: "intermediate" as const,
|
||||
description: "网前截击的站位、准备姿势和击球技巧。",
|
||||
keyPoints: JSON.stringify(["分腿弯膝准备姿势", "拍头保持在视线前方", "短促的击球动作", "步伐迎向球"]),
|
||||
commonMistakes: JSON.stringify(["挥拍幅度太大", "站位太远", "拍面角度不对", "重心太高"]),
|
||||
keyPoints: ["分腿弯膝准备姿势", "拍头保持在视线前方", "短促的击球动作", "步伐迎向球"],
|
||||
commonMistakes: ["挥拍幅度太大", "站位太远", "拍面角度不对", "重心太高"],
|
||||
duration: 240,
|
||||
sortOrder: 4,
|
||||
sortOrder: 104,
|
||||
},
|
||||
{
|
||||
slug: "footwork-fundamentals",
|
||||
title: "脚步移动训练",
|
||||
category: "footwork",
|
||||
skillLevel: "beginner",
|
||||
skillLevel: "beginner" as const,
|
||||
description: "网球基础脚步训练,包括分步、交叉步、滑步和回位。",
|
||||
keyPoints: JSON.stringify(["分步判断球的方向", "交叉步快速移动", "小碎步调整位置", "击球后快速回中"]),
|
||||
commonMistakes: JSON.stringify(["脚步懒散不移动", "重心太高", "回位太慢", "没有分步"]),
|
||||
keyPoints: ["分步判断球的方向", "交叉步快速移动", "小碎步调整位置", "击球后快速回中"],
|
||||
commonMistakes: ["脚步懒散不移动", "重心太高", "回位太慢", "没有分步"],
|
||||
duration: 240,
|
||||
sortOrder: 5,
|
||||
sortOrder: 105,
|
||||
},
|
||||
{
|
||||
slug: "forehand-topspin",
|
||||
title: "正手上旋",
|
||||
category: "forehand",
|
||||
skillLevel: "intermediate",
|
||||
skillLevel: "intermediate" as const,
|
||||
description: "掌握正手上旋球的发力技巧和拍面角度控制。",
|
||||
keyPoints: JSON.stringify(["半西方式或西方式握拍", "从低到高的刷球动作", "加速手腕内旋", "随挥结束在头部上方"]),
|
||||
commonMistakes: JSON.stringify(["拍面太开放", "没有刷球动作", "随挥不充分"]),
|
||||
keyPoints: ["半西方式或西方式握拍", "从低到高的刷球动作", "加速手腕内旋", "随挥结束在头部上方"],
|
||||
commonMistakes: ["拍面太开放", "没有刷球动作", "随挥不充分"],
|
||||
duration: 300,
|
||||
sortOrder: 6,
|
||||
sortOrder: 106,
|
||||
},
|
||||
{
|
||||
slug: "serve-spin-variations",
|
||||
title: "发球变化(切削/上旋)",
|
||||
category: "serve",
|
||||
skillLevel: "advanced",
|
||||
description: "高级发球技术,包括切削发球和Kick发球的动作要领。",
|
||||
keyPoints: JSON.stringify(["切削发球:侧旋切球", "Kick发球:从下到上刷球", "抛球位置根据发球类型调整", "手腕加速是关键"]),
|
||||
commonMistakes: JSON.stringify(["抛球位置没有变化", "旋转不足", "发力方向错误"]),
|
||||
skillLevel: "advanced" as const,
|
||||
description: "高级发球技术,包括切削发球和 Kick 发球的动作要领。",
|
||||
keyPoints: ["切削发球:侧旋切球", "Kick 发球:从下到上刷球", "抛球位置根据发球类型调整", "手腕加速是关键"],
|
||||
commonMistakes: ["抛球位置没有变化", "旋转不足", "发力方向错误"],
|
||||
duration: 360,
|
||||
sortOrder: 7,
|
||||
sortOrder: 107,
|
||||
},
|
||||
{
|
||||
slug: "shadow-swing",
|
||||
title: "影子挥拍练习",
|
||||
category: "shadow",
|
||||
skillLevel: "beginner",
|
||||
skillLevel: "beginner" as const,
|
||||
description: "不需要球的挥拍练习,专注于动作轨迹和肌肉记忆。",
|
||||
keyPoints: JSON.stringify(["慢动作分解每个环节", "关注脚步和重心转移", "对着镜子检查姿势", "逐渐加快速度"]),
|
||||
commonMistakes: JSON.stringify(["动作太快不规范", "忽略脚步", "没有完整的随挥"]),
|
||||
keyPoints: ["慢动作分解每个环节", "关注脚步和重心转移", "对着镜子检查姿势", "逐渐加快速度"],
|
||||
commonMistakes: ["动作太快不规范", "忽略脚步", "没有完整的随挥"],
|
||||
duration: 180,
|
||||
sortOrder: 8,
|
||||
sortOrder: 108,
|
||||
},
|
||||
{
|
||||
slug: "wall-drills",
|
||||
title: "墙壁练习技巧",
|
||||
category: "wall",
|
||||
skillLevel: "beginner",
|
||||
skillLevel: "beginner" as const,
|
||||
description: "利用墙壁进行的各种练习方法,提升控球和反应能力。",
|
||||
keyPoints: JSON.stringify(["保持适当距离", "控制力量和方向", "交替练习正反手", "注意脚步移动"]),
|
||||
commonMistakes: JSON.stringify(["力量太大控制不住", "站位太近或太远", "只练习一种击球"]),
|
||||
keyPoints: ["保持适当距离", "控制力量和方向", "交替练习正反手", "注意脚步移动"],
|
||||
commonMistakes: ["力量太大控制不住", "站位太近或太远", "只练习一种击球"],
|
||||
duration: 240,
|
||||
sortOrder: 9,
|
||||
sortOrder: 109,
|
||||
},
|
||||
{
|
||||
slug: "tennis-fitness",
|
||||
title: "体能训练",
|
||||
category: "fitness",
|
||||
skillLevel: "beginner",
|
||||
skillLevel: "beginner" as const,
|
||||
description: "网球专项体能训练,提升爆发力、敏捷性和耐力。",
|
||||
keyPoints: JSON.stringify(["核心力量训练", "下肢爆发力练习", "敏捷性梯子训练", "拉伸和灵活性"]),
|
||||
commonMistakes: JSON.stringify(["忽略热身", "训练过度", "动作不标准"]),
|
||||
keyPoints: ["核心力量训练", "下肢爆发力练习", "敏捷性梯子训练", "拉伸和灵活性"],
|
||||
commonMistakes: ["忽略热身", "训练过度", "动作不标准"],
|
||||
duration: 300,
|
||||
sortOrder: 10,
|
||||
sortOrder: 110,
|
||||
},
|
||||
{
|
||||
slug: "match-strategy",
|
||||
title: "比赛策略基础",
|
||||
category: "strategy",
|
||||
skillLevel: "intermediate",
|
||||
skillLevel: "intermediate" as const,
|
||||
description: "网球比赛中的基本战术和策略运用。",
|
||||
keyPoints: JSON.stringify(["控制球场深度", "变换节奏和方向", "利用对手弱点", "网前战术时机"]),
|
||||
commonMistakes: JSON.stringify(["打法单一", "没有计划", "心态波动大"]),
|
||||
keyPoints: ["控制球场深度", "变换节奏和方向", "利用对手弱点", "网前战术时机"],
|
||||
commonMistakes: ["打法单一", "没有计划", "心态波动大"],
|
||||
duration: 300,
|
||||
sortOrder: 11,
|
||||
sortOrder: 111,
|
||||
},
|
||||
];
|
||||
|
||||
const TENNIS_TUTORIAL_SEED_DATA: Omit<InsertTutorialVideo, "id">[] = TENNIS_TUTORIAL_BASE.map((tutorial) => ({
|
||||
...tutorial,
|
||||
topicArea: "tennis_skill",
|
||||
contentFormat: "video",
|
||||
sourcePlatform: "none",
|
||||
heroSummary: tutorial.description,
|
||||
estimatedEffortMinutes: Math.round((tutorial.duration || 0) / 60),
|
||||
stepSections: [
|
||||
tutorialSection("训练目标", tutorial.keyPoints),
|
||||
tutorialSection("常见错误", tutorial.commonMistakes),
|
||||
],
|
||||
deliverables: [
|
||||
"明确当前动作的关键检查点",
|
||||
"完成一轮自评并记录练习感受",
|
||||
],
|
||||
relatedDocPaths: [],
|
||||
isFeatured: 0,
|
||||
featuredOrder: 0,
|
||||
}));
|
||||
|
||||
export const TUTORIAL_SEED_DATA: Omit<InsertTutorialVideo, "id">[] = TENNIS_TUTORIAL_SEED_DATA;
|
||||
|
||||
export async function seedTutorials() {
|
||||
const db = await getDb();
|
||||
if (!db) return;
|
||||
const existing = await db.select().from(tutorialVideos).limit(1);
|
||||
if (existing.length > 0) return; // Already seeded
|
||||
for (const t of TUTORIAL_SEED_DATA) {
|
||||
await db.insert(tutorialVideos).values(t);
|
||||
|
||||
const existingRows = await db.select({
|
||||
id: tutorialVideos.id,
|
||||
slug: tutorialVideos.slug,
|
||||
title: tutorialVideos.title,
|
||||
}).from(tutorialVideos);
|
||||
|
||||
const bySlug = new Map(existingRows.filter((row) => row.slug).map((row) => [row.slug as string, row]));
|
||||
const byTitle = new Map(existingRows.map((row) => [row.title, row]));
|
||||
|
||||
for (const tutorial of TUTORIAL_SEED_DATA) {
|
||||
const existing = (tutorial.slug ? bySlug.get(tutorial.slug) : undefined) || byTitle.get(tutorial.title);
|
||||
if (existing) {
|
||||
await db.update(tutorialVideos).set(tutorial).where(eq(tutorialVideos.id, existing.id));
|
||||
continue;
|
||||
}
|
||||
await db.insert(tutorialVideos).values(tutorial);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getTutorials(category?: string, skillLevel?: string) {
|
||||
async function refreshTutorialMetricsCache<T extends {
|
||||
id: number;
|
||||
sourcePlatform?: string | null;
|
||||
platformVideoId?: string | null;
|
||||
metricsFetchedAt?: Date | string | null;
|
||||
viewCount?: number | null;
|
||||
commentCount?: number | null;
|
||||
thumbnailUrl?: string | null;
|
||||
}>(rows: T[]) {
|
||||
const db = await getDb();
|
||||
if (!db) return rows;
|
||||
|
||||
return Promise.all(rows.map(async (row) => {
|
||||
if (!shouldRefreshTutorialMetrics(row)) return row;
|
||||
|
||||
try {
|
||||
const metrics = await fetchTutorialMetrics(row.sourcePlatform || "", row.platformVideoId || "");
|
||||
if (!metrics) return row;
|
||||
|
||||
const patch = {
|
||||
viewCount: metrics.viewCount ?? row.viewCount ?? null,
|
||||
commentCount: metrics.commentCount ?? row.commentCount ?? null,
|
||||
thumbnailUrl: metrics.thumbnailUrl ?? row.thumbnailUrl ?? null,
|
||||
metricsFetchedAt: metrics.fetchedAt,
|
||||
};
|
||||
|
||||
await db.update(tutorialVideos).set(patch).where(eq(tutorialVideos.id, row.id));
|
||||
return { ...row, ...patch };
|
||||
} catch (error) {
|
||||
console.warn(`[TutorialMetrics] Failed to refresh tutorial ${row.id}:`, error);
|
||||
return row;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getTutorials(category?: string, skillLevel?: string, topicArea?: string) {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
let conditions = [eq(tutorialVideos.isPublished, 1)];
|
||||
if (category) conditions.push(eq(tutorialVideos.category, category));
|
||||
if (skillLevel) conditions.push(eq(tutorialVideos.skillLevel, skillLevel as any));
|
||||
return db.select().from(tutorialVideos).where(and(...conditions)).orderBy(tutorialVideos.sortOrder);
|
||||
if (topicArea) conditions.push(eq(tutorialVideos.topicArea, topicArea));
|
||||
|
||||
const tutorials = await db.select().from(tutorialVideos)
|
||||
.where(and(...conditions))
|
||||
.orderBy(asc(tutorialVideos.featuredOrder), asc(tutorialVideos.sortOrder), asc(tutorialVideos.id));
|
||||
|
||||
return refreshTutorialMetricsCache(tutorials);
|
||||
}
|
||||
|
||||
export async function getTutorialById(id: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return undefined;
|
||||
const result = await db.select().from(tutorialVideos).where(eq(tutorialVideos.id, id)).limit(1);
|
||||
return result.length > 0 ? result[0] : undefined;
|
||||
if (result.length === 0) return undefined;
|
||||
const [hydrated] = await refreshTutorialMetricsCache(result);
|
||||
return hydrated;
|
||||
}
|
||||
|
||||
export async function getUserTutorialProgress(userId: number) {
|
||||
@@ -1509,16 +1783,23 @@ export async function getUserTutorialProgress(userId: number) {
|
||||
return db.select().from(tutorialProgress).where(eq(tutorialProgress.userId, userId));
|
||||
}
|
||||
|
||||
export async function updateTutorialProgress(userId: number, tutorialId: number, data: { watched?: number; selfScore?: number; notes?: string; comparisonVideoId?: number }) {
|
||||
export async function updateTutorialProgress(userId: number, tutorialId: number, data: { watched?: number; completed?: number; selfScore?: number; notes?: string; comparisonVideoId?: number }) {
|
||||
const db = await getDb();
|
||||
if (!db) return;
|
||||
const nextData: { watched?: number; completed?: number; completedAt?: Date | null; selfScore?: number; notes?: string; comparisonVideoId?: number } = { ...data };
|
||||
if (data.completed === 1 || data.watched === 1) {
|
||||
nextData.completed = 1;
|
||||
nextData.completedAt = new Date();
|
||||
} else if (data.completed === 0) {
|
||||
nextData.completedAt = null;
|
||||
}
|
||||
const existing = await db.select().from(tutorialProgress)
|
||||
.where(and(eq(tutorialProgress.userId, userId), eq(tutorialProgress.tutorialId, tutorialId)))
|
||||
.limit(1);
|
||||
if (existing.length > 0) {
|
||||
await db.update(tutorialProgress).set(data).where(eq(tutorialProgress.id, existing[0].id));
|
||||
await db.update(tutorialProgress).set(nextData).where(eq(tutorialProgress.id, existing[0].id));
|
||||
} else {
|
||||
await db.insert(tutorialProgress).values({ userId, tutorialId, ...data });
|
||||
await db.insert(tutorialProgress).values({ userId, tutorialId, ...nextData });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1729,8 +2010,10 @@ export async function retryBackgroundTask(userId: number, taskId: string) {
|
||||
message: "任务已重新排队",
|
||||
error: null,
|
||||
result: null,
|
||||
attempts: 0,
|
||||
workerId: null,
|
||||
lockedAt: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
runAfter: new Date(),
|
||||
}).where(eq(backgroundTasks.id, taskId));
|
||||
@@ -1784,6 +2067,7 @@ export async function getUserStats(userId: number) {
|
||||
const liveSessions = await db.select().from(liveAnalysisSessions).where(eq(liveAnalysisSessions.userId, userId)).orderBy(desc(liveAnalysisSessions.createdAt)).limit(10);
|
||||
const latestSnapshot = await getLatestNtrpSnapshot(userId);
|
||||
const achievements = await listUserAchievements(userId);
|
||||
const trainingProfileStatus = getTrainingProfileStatus(userRow, latestSnapshot);
|
||||
|
||||
const completedRecords = records.filter(r => r.completed === 1);
|
||||
const totalShots = Math.max(
|
||||
@@ -1807,5 +2091,6 @@ export async function getUserStats(userId: number) {
|
||||
dailyTraining: daily.reverse(),
|
||||
achievements,
|
||||
latestNtrpSnapshot: latestSnapshot ?? null,
|
||||
trainingProfileStatus,
|
||||
};
|
||||
}
|
||||
|
||||
在新工单中引用
屏蔽一个用户