学习闭环增强:错题本+每周能力检测+学习概览日历+模板日历+课程管理
- 错题本:所有检测错题自动入库,带详细讲解,可标记掌握,孩子端可查 - 每周能力检测:从已学知识点确定性组卷10题,计分记录,达标关联当日 英语打卡,错题进错题本,家长可见成绩 - 家长"今日概览"改"学习概览",月日历展示每日打卡/语法点亮/周检测 - 任务模板改日历展示,灵活添加:某一天/每周X/本周/日期区间批量,可删 - 家长中心新增"课程管理"栏目(语法课程编辑+周测成绩),设备管理弱化为 栏目内二级区块 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
f98a21672d
commit
d84d827202
@@ -62,6 +62,27 @@ export default async function KidPage() {
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Link href="/weekly" className="block">
|
||||
<div className="flex items-center gap-2 rounded-xl border border-slate-100 bg-white p-3 shadow-soft transition-transform duration-200 hover:-translate-y-0.5">
|
||||
<span className="text-xl">📝</span>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-slate-900">每周能力检测</p>
|
||||
<p className="text-xs text-muted-foreground">看看这周掌握得怎样</p>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
<Link href="/wrongbook" className="block">
|
||||
<div className="flex items-center gap-2 rounded-xl border border-slate-100 bg-white p-3 shadow-soft transition-transform duration-200 hover:-translate-y-0.5">
|
||||
<span className="text-xl">📒</span>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-slate-900">我的错题本</p>
|
||||
<p className="text-xs text-muted-foreground">错题都有详细讲解</p>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{tasks.length === 0 ? (
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-8 text-center shadow-soft">
|
||||
<p className="text-3xl">🎉</p>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getSessionUser } from "@/lib/auth";
|
||||
import { completePoint, extractQuiz, getPoint, gradeAnswers, type AnswerValue } from "@/lib/grammar";
|
||||
import { recordWrong } from "@/lib/wrongbook";
|
||||
|
||||
export type QuizResult =
|
||||
| { score: number; passed: boolean; correct: number; total: number; detail: boolean[] }
|
||||
@@ -20,11 +21,16 @@ export async function submitQuiz(pointId: string, answers: AnswerValue[]): Promi
|
||||
if (questions.length === 0) return { error: "本课暂无练习题" };
|
||||
|
||||
const g = gradeAnswers(questions, answers);
|
||||
// 错题进错题本(带详细讲解)
|
||||
questions.forEach((q, i) => {
|
||||
if (!g.detail[i]) void recordWrong(user.id, "lesson", pointId, point.title, q, answers[i]);
|
||||
});
|
||||
await completePoint(user.id, pointId, point.title, g.score, g.passed);
|
||||
|
||||
revalidatePath("/learn");
|
||||
revalidatePath(`/learn/${pointId}`);
|
||||
revalidatePath("/kid");
|
||||
revalidatePath("/parent");
|
||||
revalidatePath("/wrongbook");
|
||||
return g;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,15 @@ import { submitQuiz, type QuizResult } from "./actions";
|
||||
type AV = AnswerValue | null;
|
||||
|
||||
// 结课检验:选择/判断/填空/连词成句/连线,提交后服务端判分,达标点亮并联动打卡
|
||||
export function QuizBlock({ pointId, questions }: { pointId: string; questions: QuizQ[] }) {
|
||||
export function QuizBlock({
|
||||
pointId,
|
||||
questions,
|
||||
submitter,
|
||||
}: {
|
||||
pointId: string;
|
||||
questions: QuizQ[];
|
||||
submitter?: (a: AnswerValue[]) => Promise<QuizResult>;
|
||||
}) {
|
||||
const [answers, setAnswers] = useState<AV[]>(questions.map(() => null));
|
||||
const [result, setResult] = useState<Extract<QuizResult, { score: number }> | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
@@ -35,7 +43,9 @@ export function QuizBlock({ pointId, questions }: { pointId: string; questions:
|
||||
const submit = () => {
|
||||
setError("");
|
||||
startTransition(async () => {
|
||||
const r = await submitQuiz(pointId, answers.map((a) => a as AnswerValue));
|
||||
const r = submitter
|
||||
? await submitter(answers.map((a) => a as AnswerValue))
|
||||
: await submitQuiz(pointId, answers.map((a) => a as AnswerValue));
|
||||
if ("error" in r) setError(r.error);
|
||||
else setResult(r);
|
||||
});
|
||||
|
||||
@@ -76,8 +76,11 @@ export async function makeupTask(instanceId: number, done: boolean) {
|
||||
|
||||
const templateSchema = z.object({
|
||||
childId: z.coerce.number().int().positive(),
|
||||
dow: z.coerce.number().int().min(0).max(6),
|
||||
dow: z.coerce.number().int().min(0).max(6).catch(0),
|
||||
subject: z.enum(SUBJECT_VALUES).catch("other"),
|
||||
mode: z.enum(["weekly", "date", "range", "week"]).catch("weekly"),
|
||||
dateStart: z.string().optional(),
|
||||
dateEnd: z.string().optional(),
|
||||
title: z.string().trim().min(1, "任务内容不能为空").max(100, "最多 100 字"),
|
||||
requiresPhoto: z.boolean(),
|
||||
});
|
||||
@@ -100,6 +103,9 @@ export async function addTemplate(formData: FormData) {
|
||||
childId: formData.get("childId"),
|
||||
dow: formData.get("dow"),
|
||||
subject: formData.get("subject"),
|
||||
mode: formData.get("mode"),
|
||||
dateStart: formData.get("dateStart") || null,
|
||||
dateEnd: formData.get("dateEnd") || null,
|
||||
title: formData.get("title"),
|
||||
requiresPhoto: formData.get("requiresPhoto") === "on",
|
||||
});
|
||||
@@ -109,17 +115,15 @@ export async function addTemplate(formData: FormData) {
|
||||
const [maxRow] = await db
|
||||
.select({ maxSort: sql<number>`COALESCE(MAX(${taskTemplates.sortOrder}), -1)` })
|
||||
.from(taskTemplates)
|
||||
.where(
|
||||
and(
|
||||
eq(taskTemplates.childUserId, parsed.data.childId),
|
||||
eq(taskTemplates.dow, parsed.data.dow),
|
||||
),
|
||||
);
|
||||
.where(eq(taskTemplates.childUserId, parsed.data.childId));
|
||||
|
||||
await db.insert(taskTemplates).values({
|
||||
childUserId: parsed.data.childId,
|
||||
dow: parsed.data.dow,
|
||||
subject: parsed.data.subject,
|
||||
mode: parsed.data.mode,
|
||||
dateStart: parsed.data.dateStart || null,
|
||||
dateEnd: parsed.data.dateEnd || null,
|
||||
title: parsed.data.title,
|
||||
requiresPhoto: parsed.data.requiresPhoto,
|
||||
sortOrder: maxRow.maxSort + 1,
|
||||
|
||||
@@ -9,18 +9,15 @@ import { DevicesTab } from "./devices-tab";
|
||||
import { OverviewTab } from "./overview-tab";
|
||||
import { TemplatesTab } from "./templates-tab";
|
||||
|
||||
export type DayCell = { done: number; total: number; grammar: number; weekly: number | null };
|
||||
export type OverviewData = {
|
||||
kids: {
|
||||
id: number;
|
||||
name: string;
|
||||
streak: number;
|
||||
today: { done: number; total: number };
|
||||
grammar: { done: number; total: number };
|
||||
week: {
|
||||
date: string;
|
||||
isToday: boolean;
|
||||
tasks: { id: number; title: string; subject: string; status: "pending" | "done"; isMakeup: boolean }[];
|
||||
}[];
|
||||
wrongOpen: number;
|
||||
weeklyLatest: { weekKey: string; score: number; passed: boolean } | null;
|
||||
days: Record<string, DayCell>;
|
||||
}[];
|
||||
};
|
||||
|
||||
@@ -28,7 +25,16 @@ export type TemplatesData = {
|
||||
kids: {
|
||||
id: number;
|
||||
name: string;
|
||||
items: { id: number; dow: number; title: string; subject: string; requiresPhoto: boolean }[];
|
||||
items: {
|
||||
id: number;
|
||||
dow: number;
|
||||
title: string;
|
||||
subject: string;
|
||||
requiresPhoto: boolean;
|
||||
mode: string;
|
||||
dateStart: string | null;
|
||||
dateEnd: string | null;
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
|
||||
@@ -43,67 +49,77 @@ export type DevicesData = {
|
||||
}[];
|
||||
};
|
||||
|
||||
export type WeeklyRow = { childName: string; weekKey: string; score: number; passed: boolean };
|
||||
|
||||
const tabCls = "data-[state=active]:bg-white data-[state=active]:text-indigo-600 data-[state=active]:shadow-soft";
|
||||
|
||||
export function ParentDashboard({
|
||||
overview,
|
||||
templates,
|
||||
devices,
|
||||
weekly,
|
||||
}: {
|
||||
overview: OverviewData;
|
||||
templates: TemplatesData;
|
||||
devices: DevicesData;
|
||||
weekly: WeeklyRow[];
|
||||
}) {
|
||||
const kids = overview.kids.map((k) => ({ id: k.id, name: k.name }));
|
||||
|
||||
return (
|
||||
<main className="relative mx-auto max-w-2xl space-y-5 p-4 pb-10">
|
||||
<main className="relative mx-auto max-w-3xl space-y-5 p-4 pb-10">
|
||||
<BackgroundBlobs />
|
||||
<header className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-extrabold tracking-tight">
|
||||
家长<span className="text-gradient">中心</span>
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href="/parent/grammar">
|
||||
<Button variant="outline" size="sm">
|
||||
编辑英语课程
|
||||
</Button>
|
||||
</Link>
|
||||
<form action={logout}>
|
||||
<Button type="submit" variant="outline" size="sm">
|
||||
退出登录
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<Tabs defaultValue="overview">
|
||||
<TabsList className="grid w-full grid-cols-3 bg-slate-100/80">
|
||||
<TabsTrigger
|
||||
value="overview"
|
||||
className="data-[state=active]:bg-white data-[state=active]:text-indigo-600 data-[state=active]:shadow-soft"
|
||||
>
|
||||
今日概览
|
||||
<TabsTrigger value="overview" className={tabCls}>
|
||||
学习概览
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="templates"
|
||||
className="data-[state=active]:bg-white data-[state=active]:text-indigo-600 data-[state=active]:shadow-soft"
|
||||
>
|
||||
<TabsTrigger value="templates" className={tabCls}>
|
||||
任务模板
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="devices"
|
||||
className="data-[state=active]:bg-white data-[state=active]:text-indigo-600 data-[state=active]:shadow-soft"
|
||||
>
|
||||
设备管理
|
||||
<TabsTrigger value="courses" className={tabCls}>
|
||||
课程管理
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="overview" className="mt-4">
|
||||
<OverviewTab data={overview} />
|
||||
</TabsContent>
|
||||
<TabsContent value="templates" className="mt-4">
|
||||
<TemplatesTab data={templates} />
|
||||
</TabsContent>
|
||||
<TabsContent value="devices" className="mt-4">
|
||||
<DevicesTab data={devices} kids={kids} />
|
||||
<TabsContent value="courses" className="mt-4">
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<Link href="/parent/grammar" className="block">
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft transition-transform duration-200 hover:-translate-y-0.5">
|
||||
<p className="font-bold text-slate-900">✏️ 编辑英语语法课程</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">改标题/目标/课文,保存即生效</p>
|
||||
</div>
|
||||
</Link>
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft">
|
||||
<p className="font-bold text-slate-900">📝 每周检测成绩</p>
|
||||
<div className="mt-2 space-y-1">
|
||||
{weekly.length === 0 && <p className="text-xs text-muted-foreground">暂无检测记录</p>}
|
||||
{weekly.map((w, i) => (
|
||||
<p key={i} className="text-xs text-slate-600">
|
||||
{w.childName} · {w.weekKey} · {w.score} 分 {w.passed ? "✅" : "❌"}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DevicesTab data={devices} kids={overview.kids.map((k) => ({ id: k.id, name: k.name }))} />
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</main>
|
||||
|
||||
@@ -1,108 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { Flame } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { subjectMeta } from "@/lib/subjects";
|
||||
import { makeupTask } from "./actions";
|
||||
import { addDays, dowOf, todayStr } from "@/lib/dates";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { OverviewData } from "./dashboard";
|
||||
|
||||
const DOW_LABELS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
|
||||
|
||||
function dateLabel(date: string) {
|
||||
const [y, m, d] = date.split("-").map(Number);
|
||||
const dow = new Date(Date.UTC(y, m - 1, d)).getUTCDay();
|
||||
return `${m}月${d}日 ${DOW_LABELS[dow]}`;
|
||||
}
|
||||
|
||||
// 学习概览:按孩子的月日历,展示每日 打卡/语法/周检测 情况
|
||||
export function OverviewTab({ data }: { data: OverviewData }) {
|
||||
const [, startTransition] = useTransition();
|
||||
const [kidId, setKidId] = useState(data.kids[0]?.id);
|
||||
const kid = data.kids.find((k) => k.id === kidId) ?? data.kids[0];
|
||||
if (!kid) return null;
|
||||
|
||||
const today = todayStr();
|
||||
const ym = today.slice(0, 7);
|
||||
const first = `${ym}-01`;
|
||||
const daysInMonth = new Date(Number(ym.slice(0, 4)), Number(ym.slice(5, 7)), 0).getDate();
|
||||
const lead = (dowOf(first) + 6) % 7; // 周一开头的前导空位数
|
||||
const dates = Array.from({ length: daysInMonth }, (_, i) => `${ym}-${String(i + 1).padStart(2, "0")}`);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{data.kids.map((kid) => (
|
||||
<Card key={kid.id}>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-lg">{kid.name}</CardTitle>
|
||||
<div className="flex items-center gap-1 text-orange-600">
|
||||
<Flame className="size-5" fill="currentColor" />
|
||||
<span className="font-bold">{kid.streak}</span>
|
||||
<span className="text-xs">天连击</span>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{data.kids.map((k) => (
|
||||
<Button
|
||||
key={k.id}
|
||||
size="sm"
|
||||
variant={k.id === kid.id ? "default" : "outline"}
|
||||
onClick={() => setKidId(k.id)}
|
||||
>
|
||||
{k.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
今日完成 {kid.today.done} / {kid.today.total} 项
|
||||
</p>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="shrink-0">英语语法</span>
|
||||
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-slate-100">
|
||||
<div
|
||||
className="h-full rounded-full bg-gradient-to-r from-indigo-500 to-violet-500"
|
||||
style={{
|
||||
width: `${kid.grammar.total ? (kid.grammar.done / kid.grammar.total) * 100 : 0}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span className="shrink-0 font-medium text-indigo-600">
|
||||
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-3 text-center shadow-soft">
|
||||
<p className="text-xs text-muted-foreground">语法进度</p>
|
||||
<p className="text-lg font-extrabold text-indigo-600">
|
||||
{kid.grammar.done}/{kid.grammar.total}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{kid.week.map((day) => (
|
||||
<div key={day.date} className="rounded-lg border p-2">
|
||||
<p className="mb-1 text-xs font-medium text-muted-foreground">
|
||||
{dateLabel(day.date)}
|
||||
{day.isToday && " · 今天"}
|
||||
</p>
|
||||
{day.tasks.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">无任务(自动保持连击)</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{day.tasks.map((t) => (
|
||||
<span key={t.id} className="inline-flex items-center gap-1">
|
||||
<Badge variant={t.status === "done" ? "default" : "secondary"}>
|
||||
<span className={cn("size-1.5 rounded-full", subjectMeta(t.subject).dot)} />
|
||||
{t.title}
|
||||
{t.isMakeup && " · 补"}
|
||||
</Badge>
|
||||
{!day.isToday && t.status === "pending" && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-5 px-1.5 text-xs"
|
||||
onClick={() =>
|
||||
startTransition(() => makeupTask(t.id, true))
|
||||
}
|
||||
>
|
||||
补卡
|
||||
</Button>
|
||||
</div>
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-3 text-center shadow-soft">
|
||||
<p className="text-xs text-muted-foreground">待掌握错题</p>
|
||||
<p className="text-lg font-extrabold text-rose-600">{kid.wrongOpen}</p>
|
||||
</div>
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-3 text-center shadow-soft">
|
||||
<p className="text-xs text-muted-foreground">最近周测</p>
|
||||
<p className="text-lg font-extrabold text-violet-600">
|
||||
{kid.weeklyLatest ? `${kid.weeklyLatest.score}分` : "—"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft">
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-xs font-medium text-muted-foreground">
|
||||
{["一", "二", "三", "四", "五", "六", "日"].map((w) => (
|
||||
<div key={w}>周{w}</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-1 grid grid-cols-7 gap-1">
|
||||
{Array.from({ length: lead }).map((_, i) => (
|
||||
<div key={`e${i}`} />
|
||||
))}
|
||||
{dates.map((d) => {
|
||||
const c = kid.days[d];
|
||||
const isToday = d === today;
|
||||
const check = c && c.total > 0 ? (c.done >= c.total && c.done > 0 ? 2 : c.done > 0 ? 1 : 0) : 0;
|
||||
return (
|
||||
<div
|
||||
key={d}
|
||||
title={`${d} 打卡${c?.done ?? 0}/${c?.total ?? 0} 语法${c?.grammar ?? 0} ${c?.weekly != null ? `周测${c.weekly}` : ""}`}
|
||||
className={cn(
|
||||
"flex aspect-square flex-col items-center justify-center rounded-lg border text-sm",
|
||||
isToday ? "border-indigo-400 ring-1 ring-indigo-300" : "border-slate-100",
|
||||
"bg-white",
|
||||
)}
|
||||
{!day.isToday && t.isMakeup && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-5 px-1.5 text-xs"
|
||||
onClick={() =>
|
||||
startTransition(() => makeupTask(t.id, false))
|
||||
}
|
||||
>
|
||||
撤销
|
||||
</Button>
|
||||
)}
|
||||
<span className={cn("leading-none", isToday ? "font-extrabold text-indigo-600" : "text-slate-600")}>
|
||||
{Number(d.slice(8))}
|
||||
</span>
|
||||
<span className="mt-1 flex h-2 items-center gap-0.5">
|
||||
{check === 2 && <span className="size-2 rounded-full bg-emerald-500" />}
|
||||
{check === 1 && <span className="size-2 rounded-full bg-amber-400" />}
|
||||
{(c?.grammar ?? 0) > 0 && <span className="size-2 rounded-full bg-indigo-500" />}
|
||||
{c?.weekly != null && <span className="size-2 rounded-full bg-violet-500" />}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
<p className="mt-3 text-xs text-muted-foreground">
|
||||
<span className="mr-2 inline-flex items-center gap-1"><span className="size-2 rounded-full bg-emerald-500" />打卡完成</span>
|
||||
<span className="mr-2 inline-flex items-center gap-1"><span className="size-2 rounded-full bg-amber-400" />打卡部分</span>
|
||||
<span className="mr-2 inline-flex items-center gap-1"><span className="size-2 rounded-full bg-indigo-500" />语法点亮</span>
|
||||
<span className="inline-flex items-center gap-1"><span className="size-2 rounded-full bg-violet-500" />周检测</span>
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+82
-44
@@ -1,19 +1,30 @@
|
||||
import crypto from "node:crypto";
|
||||
import { and, asc, desc, eq, inArray } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, gte, lte, inArray } from "drizzle-orm";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { db } from "@/db";
|
||||
import { sessions, taskInstances, taskTemplates, users } from "@/db/schema";
|
||||
import {
|
||||
sessions,
|
||||
taskInstances,
|
||||
taskTemplates,
|
||||
users,
|
||||
grammarProgress,
|
||||
weeklyTest,
|
||||
wrongBook,
|
||||
} from "@/db/schema";
|
||||
import { SESSION_COOKIE, getSessionUser } from "@/lib/auth";
|
||||
import { daysAgo, todayStr } from "@/lib/dates";
|
||||
import { ensureDay } from "@/lib/tasks";
|
||||
import { streakOf } from "@/lib/streak";
|
||||
import { addDays, dowOf, todayStr } from "@/lib/dates";
|
||||
import { passedCount, totalPoints } from "@/lib/grammar";
|
||||
import { ParentDashboard, type DevicesData, type OverviewData, type TemplatesData } from "./dashboard";
|
||||
import {
|
||||
ParentDashboard,
|
||||
type DevicesData,
|
||||
type OverviewData,
|
||||
type TemplatesData,
|
||||
type WeeklyRow,
|
||||
} from "./dashboard";
|
||||
|
||||
const SHANGHAI = { timeZone: "Asia/Shanghai" } as const;
|
||||
const fmtDateTime = (d: Date) =>
|
||||
d.toLocaleString("zh-CN", { ...SHANGHAI, hour12: false }).replace(/\//g, "-");
|
||||
const SH = { timeZone: "Asia/Shanghai" } as const;
|
||||
const dstr = (d: Date) => d.toLocaleDateString("en-CA", SH);
|
||||
|
||||
export default async function ParentPage() {
|
||||
const parent = await getSessionUser();
|
||||
@@ -27,58 +38,62 @@ export default async function ParentPage() {
|
||||
.orderBy(asc(users.sortOrder));
|
||||
|
||||
const today = todayStr();
|
||||
const weekDates = Array.from({ length: 7 }, (_, i) => daysAgo(i)); // 今天在前
|
||||
const ym = today.slice(0, 7);
|
||||
const daysInMonth = new Date(Number(ym.slice(0, 4)), Number(ym.slice(5, 7)), 0).getDate();
|
||||
const mStart = `${ym}-01`;
|
||||
const mEnd = `${ym}-${String(daysInMonth).padStart(2, "0")}`;
|
||||
const gTotal = await totalPoints();
|
||||
|
||||
// ===== 今日概览 =====
|
||||
// ===== 学习概览(日历) =====
|
||||
const overview: OverviewData = { kids: [] };
|
||||
for (const kid of kids) {
|
||||
await ensureDay(kid.id, today); // 家长先看时也要生成今天的快照
|
||||
const [streak, gDone, rows] = await Promise.all([
|
||||
streakOf(kid.id),
|
||||
passedCount(kid.id),
|
||||
const [instRows, gRows, wRows, wrongRow, gDone] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: taskInstances.id,
|
||||
date: taskInstances.date,
|
||||
title: taskInstances.title,
|
||||
subject: taskInstances.subject,
|
||||
status: taskInstances.status,
|
||||
isMakeup: taskInstances.isMakeup,
|
||||
sortOrder: taskInstances.sortOrder,
|
||||
})
|
||||
.select({ date: taskInstances.date, status: taskInstances.status })
|
||||
.from(taskInstances)
|
||||
.where(and(eq(taskInstances.childUserId, kid.id), inArray(taskInstances.date, weekDates)))
|
||||
.orderBy(desc(taskInstances.date), asc(taskInstances.sortOrder)),
|
||||
.where(and(eq(taskInstances.childUserId, kid.id), gte(taskInstances.date, mStart), lte(taskInstances.date, mEnd))),
|
||||
db
|
||||
.select({ completedAt: grammarProgress.completedAt, passed: grammarProgress.passed })
|
||||
.from(grammarProgress)
|
||||
.where(and(eq(grammarProgress.childUserId, kid.id), eq(grammarProgress.passed, true))),
|
||||
db.select().from(weeklyTest).where(eq(weeklyTest.childUserId, kid.id)).orderBy(desc(weeklyTest.takenAt)),
|
||||
db
|
||||
.select({ id: wrongBook.id })
|
||||
.from(wrongBook)
|
||||
.where(and(eq(wrongBook.childUserId, kid.id), eq(wrongBook.mastered, false))),
|
||||
passedCount(kid.id),
|
||||
]);
|
||||
|
||||
const week = weekDates.map((date) => ({
|
||||
date,
|
||||
isToday: date === today,
|
||||
tasks: rows.filter((r) => r.date === date),
|
||||
}));
|
||||
const todayTasks = week.find((w) => w.isToday)?.tasks ?? [];
|
||||
|
||||
const days: OverviewData["kids"][number]["days"] = {};
|
||||
for (let i = 1; i <= daysInMonth; i++) {
|
||||
const d = `${ym}-${String(i).padStart(2, "0")}`;
|
||||
const inst = instRows.filter((r) => r.date === d);
|
||||
const grammar = gRows.filter((r) => dstr(r.completedAt) === d).length;
|
||||
const w = wRows.find((r) => dstr(r.takenAt) === d);
|
||||
days[d] = {
|
||||
done: inst.filter((r) => r.status === "done").length,
|
||||
total: inst.length,
|
||||
grammar,
|
||||
weekly: w ? w.score : null,
|
||||
};
|
||||
}
|
||||
overview.kids.push({
|
||||
id: kid.id,
|
||||
name: kid.name,
|
||||
streak,
|
||||
today: {
|
||||
total: todayTasks.length,
|
||||
done: todayTasks.filter((t) => t.status === "done").length,
|
||||
},
|
||||
grammar: { done: gDone, total: gTotal },
|
||||
week,
|
||||
wrongOpen: wrongRow.length,
|
||||
weeklyLatest: wRows[0] ? { weekKey: wRows[0].weekKey, score: wRows[0].score ?? 0, passed: wRows[0].passed } : null,
|
||||
days,
|
||||
});
|
||||
}
|
||||
|
||||
// ===== 周模板 =====
|
||||
// ===== 任务模板 =====
|
||||
const templateRows = kids.length
|
||||
? await db
|
||||
.select()
|
||||
.from(taskTemplates)
|
||||
.where(inArray(taskTemplates.childUserId, kids.map((k) => k.id)))
|
||||
.orderBy(asc(taskTemplates.childUserId), asc(taskTemplates.dow), asc(taskTemplates.sortOrder))
|
||||
.orderBy(asc(taskTemplates.childUserId), asc(taskTemplates.sortOrder))
|
||||
: [];
|
||||
const templates: TemplatesData = {
|
||||
kids: kids.map((kid) => ({
|
||||
@@ -92,6 +107,9 @@ export default async function ParentPage() {
|
||||
title: t.title,
|
||||
subject: t.subject,
|
||||
requiresPhoto: t.requiresPhoto,
|
||||
mode: t.mode,
|
||||
dateStart: t.dateStart,
|
||||
dateEnd: t.dateEnd,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
@@ -118,11 +136,31 @@ export default async function ParentPage() {
|
||||
id: s.id,
|
||||
owner: s.role === "parent" ? `${s.owner}(家长)` : s.owner,
|
||||
deviceLabel: s.deviceLabel,
|
||||
createdAt: fmtDateTime(s.createdAt),
|
||||
expiresAt: fmtDateTime(s.expiresAt),
|
||||
createdAt: dstr(s.createdAt),
|
||||
expiresAt: dstr(s.expiresAt),
|
||||
isCurrent: s.tokenHash === tokenHash,
|
||||
})),
|
||||
};
|
||||
|
||||
return <ParentDashboard overview={overview} templates={templates} devices={devices} />;
|
||||
// ===== 周测成绩(课程管理) =====
|
||||
const weeklyRows = await db
|
||||
.select({
|
||||
childName: users.displayName,
|
||||
weekKey: weeklyTest.weekKey,
|
||||
score: weeklyTest.score,
|
||||
passed: weeklyTest.passed,
|
||||
})
|
||||
.from(weeklyTest)
|
||||
.innerJoin(users, eq(users.id, weeklyTest.childUserId))
|
||||
.where(eq(users.familyId, parent.familyId))
|
||||
.orderBy(desc(weeklyTest.takenAt))
|
||||
.limit(10);
|
||||
const weekly: WeeklyRow[] = weeklyRows.map((w) => ({
|
||||
childName: w.childName,
|
||||
weekKey: w.weekKey,
|
||||
score: w.score ?? 0,
|
||||
passed: w.passed,
|
||||
}));
|
||||
|
||||
return <ParentDashboard overview={overview} templates={templates} devices={devices} weekly={weekly} />;
|
||||
}
|
||||
|
||||
@@ -3,121 +3,178 @@
|
||||
import { useState, useTransition } from "react";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { addDays, dowOf, mondayOf, todayStr } from "@/lib/dates";
|
||||
import { SUBJECTS, type Subject, subjectMeta } from "@/lib/subjects";
|
||||
import { addTemplate, deleteTemplate } from "./actions";
|
||||
import type { TemplatesData } from "./dashboard";
|
||||
|
||||
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0]; // 展示顺序:周一到周日
|
||||
const DOW_LABELS = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
|
||||
type Item = TemplatesData["kids"][number]["items"][number];
|
||||
|
||||
export function TemplatesTab({ data }: { data: TemplatesData }) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
模板改动从第二天起生效,不影响已生成的历史任务。
|
||||
</p>
|
||||
{data.kids.map((kid) => (
|
||||
<KidTemplateCard key={kid.id} kid={kid} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
function covers(t: Item, date: string): boolean {
|
||||
if (t.mode === "weekly") return t.dow === dowOf(date);
|
||||
if (t.mode === "date") return t.dateStart === date;
|
||||
if (t.mode === "range") return !!t.dateStart && !!t.dateEnd && date >= t.dateStart && date <= t.dateEnd;
|
||||
if (t.mode === "week") return !!t.dateStart && mondayOf(t.dateStart) === mondayOf(date);
|
||||
return false;
|
||||
}
|
||||
|
||||
function KidTemplateCard({
|
||||
kid,
|
||||
}: {
|
||||
kid: TemplatesData["kids"][number];
|
||||
}) {
|
||||
const [dow, setDow] = useState(1);
|
||||
// 任务模板:日历展示 + 灵活添加(某一天/每周X/本周/日期区间)
|
||||
export function TemplatesTab({ data }: { data: TemplatesData }) {
|
||||
const [kidId, setKidId] = useState(data.kids[0]?.id);
|
||||
const kid = data.kids.find((k) => k.id === kidId) ?? data.kids[0];
|
||||
const [selected, setSelected] = useState(todayStr());
|
||||
const [mode, setMode] = useState<"date" | "weekly" | "week" | "range">("weekly");
|
||||
const [subject, setSubject] = useState<Subject>("other");
|
||||
const [title, setTitle] = useState("");
|
||||
const [requiresPhoto, setRequiresPhoto] = useState(false);
|
||||
const [photo, setPhoto] = useState(false);
|
||||
const [rangeStart, setRangeStart] = useState(todayStr());
|
||||
const [rangeEnd, setRangeEnd] = useState(addDays(todayStr(), 6));
|
||||
const [error, setError] = useState("");
|
||||
const [pending, startTransition] = useTransition();
|
||||
if (!kid) return null;
|
||||
|
||||
function onAdd(e: React.FormEvent) {
|
||||
const today = todayStr();
|
||||
const ym = today.slice(0, 7);
|
||||
const daysInMonth = new Date(Number(ym.slice(0, 4)), Number(ym.slice(5, 7)), 0).getDate();
|
||||
const lead = (dowOf(`${ym}-01`) + 6) % 7;
|
||||
const dates = Array.from({ length: daysInMonth }, (_, i) => `${ym}-${String(i + 1).padStart(2, "0")}`);
|
||||
const dayTasks = (d: string) => kid.items.filter((t) => covers(t, d));
|
||||
|
||||
const submit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
const fd = new FormData();
|
||||
fd.set("childId", String(kid.id));
|
||||
fd.set("dow", String(dow));
|
||||
fd.set("subject", subject);
|
||||
fd.set("title", title);
|
||||
if (requiresPhoto) fd.set("requiresPhoto", "on");
|
||||
fd.set("mode", mode);
|
||||
fd.set("dow", String(dowOf(selected)));
|
||||
if (mode === "date" || mode === "week") fd.set("dateStart", selected);
|
||||
if (mode === "range") {
|
||||
fd.set("dateStart", rangeStart);
|
||||
fd.set("dateEnd", rangeEnd);
|
||||
}
|
||||
if (photo) fd.set("requiresPhoto", "on");
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await addTemplate(fd);
|
||||
setTitle("");
|
||||
setRequiresPhoto(false);
|
||||
setPhoto(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "添加失败");
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const modeLabel: Record<string, string> = {
|
||||
date: "某一天",
|
||||
weekly: "每周X",
|
||||
week: "某一周",
|
||||
range: "日期区间",
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-lg">{kid.name}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
{WEEK_ORDER.map((d) => {
|
||||
const items = kid.items.filter((i) => i.dow === d);
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{data.kids.map((k) => (
|
||||
<Button key={k.id} size="sm" variant={k.id === kid.id ? "default" : "outline"} onClick={() => setKidId(k.id)}>
|
||||
{k.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft">
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-xs font-medium text-muted-foreground">
|
||||
{["一", "二", "三", "四", "五", "六", "日"].map((w) => (
|
||||
<div key={w}>周{w}</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-1 grid grid-cols-7 gap-1">
|
||||
{Array.from({ length: lead }).map((_, i) => (
|
||||
<div key={`e${i}`} />
|
||||
))}
|
||||
{dates.map((d) => {
|
||||
const ts = dayTasks(d);
|
||||
return (
|
||||
<div key={d} className="flex items-start gap-3">
|
||||
<span className="w-10 shrink-0 pt-1 text-sm font-medium text-muted-foreground">
|
||||
{DOW_LABELS[d]}
|
||||
</span>
|
||||
<div className="flex flex-1 flex-wrap gap-1.5">
|
||||
{items.length === 0 && (
|
||||
<span className="text-sm text-muted-foreground">休息日(自动保持连击)</span>
|
||||
)}
|
||||
{items.map((item) => {
|
||||
const sm = subjectMeta(item.subject);
|
||||
return (
|
||||
<span
|
||||
key={item.id}
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
onClick={() => setSelected(d)}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm ring-1",
|
||||
sm.soft,
|
||||
sm.ring,
|
||||
"flex aspect-square flex-col items-center justify-center rounded-lg border text-sm transition-colors",
|
||||
selected === d ? "border-indigo-400 ring-1 ring-indigo-300" : "border-slate-100 hover:border-indigo-300",
|
||||
"bg-white",
|
||||
)}
|
||||
>
|
||||
<span className={cn("leading-none", d === today ? "font-extrabold text-indigo-600" : "text-slate-600")}>
|
||||
{Number(d.slice(8))}
|
||||
</span>
|
||||
<span className="mt-1 flex max-w-full flex-wrap justify-center gap-0.5">
|
||||
{ts.slice(0, 4).map((t) => (
|
||||
<span key={t.id} className={cn("size-1.5 rounded-full", subjectMeta(t.subject).dot)} />
|
||||
))}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft">
|
||||
<h3 className="font-bold text-slate-900">{selected} 的任务</h3>
|
||||
<div className="mt-2 space-y-1.5">
|
||||
{dayTasks(selected).length === 0 && <p className="text-sm text-muted-foreground">这一天没有任务(休息日)</p>}
|
||||
{dayTasks(selected).map((t) => {
|
||||
const sm = subjectMeta(t.subject);
|
||||
return (
|
||||
<div key={t.id} className={cn("flex items-center gap-2 rounded-full px-3 py-1 text-sm ring-1", sm.soft, sm.ring)}>
|
||||
<span className={cn("size-1.5 rounded-full", sm.dot)} />
|
||||
<span className="font-medium">{sm.label}</span>
|
||||
<span className="text-slate-600">{item.title}</span>
|
||||
{item.requiresPhoto && <span className="text-muted-foreground">· 拍照</span>}
|
||||
<span className="text-slate-600">{t.title}</span>
|
||||
<span className="text-xs text-muted-foreground">({modeLabel[t.mode] ?? t.mode})</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`删除 ${item.title}`}
|
||||
className="ml-1 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => startTransition(() => deleteTemplate(item.id))}
|
||||
aria-label={`删除 ${t.title}`}
|
||||
className="ml-auto text-muted-foreground hover:text-destructive"
|
||||
onClick={() => startTransition(() => deleteTemplate(t.id))}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<form onSubmit={onAdd} className="flex flex-wrap items-end gap-3 border-t pt-3">
|
||||
<form onSubmit={submit} className="mt-4 space-y-3 border-t pt-3">
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="space-y-1">
|
||||
<Label>添加方式</Label>
|
||||
<select value={mode} onChange={(e) => setMode(e.target.value as typeof mode)} className="h-9 rounded-md border border-input bg-background px-2 text-sm">
|
||||
<option value="weekly">每周{["日", "一", "二", "三", "四", "五", "六"][dowOf(selected)]}</option>
|
||||
<option value="date">仅 {selected}</option>
|
||||
<option value="week">本周({mondayOf(selected)} 起)</option>
|
||||
<option value="range">日期区间</option>
|
||||
</select>
|
||||
</div>
|
||||
{mode === "range" && (
|
||||
<>
|
||||
<div className="space-y-1">
|
||||
<Label>从</Label>
|
||||
<Input type="date" value={rangeStart} onChange={(e) => setRangeStart(e.target.value)} className="h-9" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>到</Label>
|
||||
<Input type="date" value={rangeEnd} onChange={(e) => setRangeEnd(e.target.value)} className="h-9" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="space-y-1">
|
||||
<Label>科目</Label>
|
||||
<select
|
||||
value={subject}
|
||||
onChange={(e) => setSubject(e.target.value as Subject)}
|
||||
className="h-9 rounded-md border border-input bg-background px-2 text-sm"
|
||||
>
|
||||
<select value={subject} onChange={(e) => setSubject(e.target.value as Subject)} className="h-9 rounded-md border border-input bg-background px-2 text-sm">
|
||||
{SUBJECTS.map((s) => (
|
||||
<option key={s.key} value={s.key}>
|
||||
{s.label}
|
||||
@@ -125,43 +182,23 @@ function KidTemplateCard({
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>星期</Label>
|
||||
<select
|
||||
value={dow}
|
||||
onChange={(e) => setDow(Number(e.target.value))}
|
||||
className="h-9 rounded-md border border-input bg-background px-2 text-sm"
|
||||
>
|
||||
{WEEK_ORDER.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{DOW_LABELS[d]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-40 flex-1 space-y-1">
|
||||
<Label>任务内容</Label>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="如:看书 30 分钟"
|
||||
maxLength={100}
|
||||
/>
|
||||
<Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="如:看书 30 分钟" maxLength={100} />
|
||||
</div>
|
||||
<div className="flex h-9 items-center gap-2">
|
||||
<Checkbox
|
||||
id={`photo-${kid.id}`}
|
||||
checked={requiresPhoto}
|
||||
onCheckedChange={(v) => setRequiresPhoto(v === true)}
|
||||
/>
|
||||
<Label htmlFor={`photo-${kid.id}`}>需拍照凭证</Label>
|
||||
<Checkbox id="tpl-photo" checked={photo} onCheckedChange={(v) => setPhoto(v === true)} />
|
||||
<Label htmlFor="tpl-photo">需拍照</Label>
|
||||
</div>
|
||||
<Button type="submit" disabled={pending || title.trim() === ""}>
|
||||
添加
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
{error && <p className="text-sm font-medium text-destructive">{error}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { getSessionUser } from "@/lib/auth";
|
||||
import { gradeAnswers, type AnswerValue } from "@/lib/grammar";
|
||||
import { buildWeeklyQuestions, currentWeekKey, getWeeklyRecord } from "@/lib/weekly";
|
||||
import { recordWrong } from "@/lib/wrongbook";
|
||||
import { db } from "@/db";
|
||||
import { taskInstances, weeklyTest } from "@/db/schema";
|
||||
import { todayStr } from "@/lib/dates";
|
||||
|
||||
export type WeeklyResult =
|
||||
| { score: number; passed: boolean; correct: number; total: number; detail: boolean[] }
|
||||
| { error: string };
|
||||
|
||||
// 提交每周能力检测:判分、记录、错题入库、达标关联当日英语打卡
|
||||
export async function takeWeekly(answers: AnswerValue[]): Promise<WeeklyResult> {
|
||||
const user = await getSessionUser();
|
||||
if (!user || user.role !== "child") return { error: "会话无效,请重新激活设备" };
|
||||
const wk = currentWeekKey();
|
||||
const existing = await getWeeklyRecord(user.id, wk);
|
||||
if (existing) return { error: "本周已完成检测,下周再来。" };
|
||||
|
||||
const questions = await buildWeeklyQuestions(user.id, wk);
|
||||
if (questions.length === 0) return { error: "暂无可组卷的题目,先学几课吧。" };
|
||||
|
||||
const g = gradeAnswers(questions, answers);
|
||||
questions.forEach((q, i) => {
|
||||
if (!g.detail[i]) void recordWrong(user.id, "weekly", wk, `每周检测 ${wk}`, q, answers[i]);
|
||||
});
|
||||
|
||||
await db
|
||||
.insert(weeklyTest)
|
||||
.values({
|
||||
childUserId: user.id,
|
||||
weekKey: wk,
|
||||
score: g.score,
|
||||
correct: g.correct,
|
||||
total: g.total,
|
||||
passed: g.passed,
|
||||
questions: JSON.stringify(questions),
|
||||
})
|
||||
.onDuplicateKeyUpdate({ set: { score: g.score, correct: g.correct, total: g.total, passed: g.passed } });
|
||||
|
||||
// 达标关联当日英语打卡
|
||||
if (g.passed) {
|
||||
const today = todayStr();
|
||||
const title = `英语周检测 · ${wk}`;
|
||||
const [ex] = await db
|
||||
.select({ id: taskInstances.id, status: taskInstances.status })
|
||||
.from(taskInstances)
|
||||
.where(and(eq(taskInstances.childUserId, user.id), eq(taskInstances.date, today), eq(taskInstances.title, title)))
|
||||
.limit(1);
|
||||
if (ex) {
|
||||
if (ex.status !== "done")
|
||||
await db.update(taskInstances).set({ status: "done", doneAt: sql`CURRENT_TIMESTAMP` }).where(eq(taskInstances.id, ex.id));
|
||||
} else {
|
||||
await db.insert(taskInstances).values({
|
||||
childUserId: user.id,
|
||||
date: today,
|
||||
title,
|
||||
subject: "english",
|
||||
status: "done",
|
||||
doneAt: new Date(),
|
||||
sortOrder: 98,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath("/weekly");
|
||||
revalidatePath("/kid");
|
||||
revalidatePath("/parent");
|
||||
revalidatePath("/wrongbook");
|
||||
return g;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { BackgroundBlobs } from "@/components/background-blobs";
|
||||
import { getSessionUser } from "@/lib/auth";
|
||||
import { buildWeeklyQuestions, currentWeekKey, getWeeklyRecord } from "@/lib/weekly";
|
||||
import { QuizBlock } from "@/app/learn/quiz-block";
|
||||
import { takeWeekly } from "./actions";
|
||||
|
||||
export default async function WeeklyPage() {
|
||||
const user = await getSessionUser();
|
||||
if (!user) redirect("/join");
|
||||
if (user.role !== "child") redirect("/parent");
|
||||
|
||||
const wk = currentWeekKey();
|
||||
const record = await getWeeklyRecord(user.id, wk);
|
||||
const questions = record ? [] : await buildWeeklyQuestions(user.id, wk);
|
||||
|
||||
return (
|
||||
<main className="relative mx-auto max-w-2xl space-y-5 p-4 pb-12">
|
||||
<BackgroundBlobs />
|
||||
<header className="flex items-center justify-between">
|
||||
<Link href="/kid" className="text-sm font-medium text-indigo-600">
|
||||
← 返回
|
||||
</Link>
|
||||
<h1 className="text-xl font-extrabold text-slate-900">每周能力检测</h1>
|
||||
<span className="text-xs text-muted-foreground">{wk}</span>
|
||||
</header>
|
||||
<p className="rounded-lg border-l-4 border-indigo-400 bg-indigo-50 px-3 py-2 text-sm text-indigo-800">
|
||||
从你已点亮的知识点里抽 10 题,判断这周的掌握情况;达标自动计入今日英语打卡,错题进错题本。
|
||||
</p>
|
||||
|
||||
{record ? (
|
||||
<div
|
||||
className={
|
||||
record.passed
|
||||
? "rounded-2xl bg-gradient-to-r from-emerald-500 to-emerald-600 p-6 text-center text-white shadow-btn"
|
||||
: "rounded-2xl bg-gradient-to-r from-rose-500 to-rose-600 p-6 text-center text-white shadow-btn"
|
||||
}
|
||||
>
|
||||
<p className="text-4xl font-extrabold">{record.score} 分</p>
|
||||
<p className="mt-1 text-sm opacity-90">
|
||||
答对 {record.correct} / {record.total} · {record.passed ? "本周掌握良好 🎉" : "看看错题本,下周再战"}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<QuizBlock pointId="" questions={questions} submitter={takeWeekly} />
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getSessionUser } from "@/lib/auth";
|
||||
import { setMastered } from "@/lib/wrongbook";
|
||||
|
||||
export async function toggleMastered(id: number, mastered: boolean): Promise<void> {
|
||||
const user = await getSessionUser();
|
||||
if (!user || user.role !== "child") return;
|
||||
await setMastered(id, user.id, mastered);
|
||||
revalidatePath("/wrongbook");
|
||||
revalidatePath("/parent");
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { BackgroundBlobs } from "@/components/background-blobs";
|
||||
import { getSessionUser } from "@/lib/auth";
|
||||
import { listWrong } from "@/lib/wrongbook";
|
||||
import type { QuizQ } from "@/lib/quiz-parse";
|
||||
import { WrongRow } from "./wrong-row";
|
||||
|
||||
export default async function WrongBookPage() {
|
||||
const user = await getSessionUser();
|
||||
if (!user) redirect("/join");
|
||||
if (user.role !== "child") redirect("/parent");
|
||||
|
||||
const rows = await listWrong(user.id);
|
||||
const open = rows.filter((r) => !r.mastered).length;
|
||||
|
||||
return (
|
||||
<main className="relative mx-auto max-w-2xl space-y-5 p-4 pb-12">
|
||||
<BackgroundBlobs />
|
||||
<header className="flex items-center justify-between">
|
||||
<Link href="/kid" className="text-sm font-medium text-indigo-600">
|
||||
← 返回
|
||||
</Link>
|
||||
<h1 className="text-xl font-extrabold text-slate-900">我的错题本</h1>
|
||||
<span className="text-xs text-muted-foreground">待掌握 {open} 题</span>
|
||||
</header>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="rounded-2xl border border-slate-100 bg-white p-8 text-center shadow-soft">
|
||||
<p className="text-3xl">🎉</p>
|
||||
<p className="mt-2 font-bold text-slate-900">还没有错题,继续保持!</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((r) => {
|
||||
let q: QuizQ;
|
||||
try {
|
||||
q = JSON.parse(r.question) as QuizQ;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<WrongRow
|
||||
key={r.id}
|
||||
id={r.id}
|
||||
sourceTitle={r.sourceTitle}
|
||||
q={q}
|
||||
userAnswer={r.userAnswer}
|
||||
correctAnswer={r.correctAnswer}
|
||||
mastered={r.mastered}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { CheckCircle2, RotateCcw } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { QuizQ } from "@/lib/quiz-parse";
|
||||
import { toggleMastered } from "./actions";
|
||||
|
||||
export function WrongRow({
|
||||
id,
|
||||
sourceTitle,
|
||||
q,
|
||||
userAnswer,
|
||||
correctAnswer,
|
||||
mastered,
|
||||
}: {
|
||||
id: number;
|
||||
sourceTitle: string | null;
|
||||
q: QuizQ;
|
||||
userAnswer: string | null;
|
||||
correctAnswer: string | null;
|
||||
mastered: boolean;
|
||||
}) {
|
||||
const [pending, startTransition] = useTransition();
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-xl border bg-white p-4 shadow-soft transition-colors",
|
||||
mastered ? "border-emerald-200 opacity-70" : "border-rose-200",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<p className="font-medium text-slate-900">{q.stem}</p>
|
||||
<span className="shrink-0 rounded-full bg-slate-100 px-2 py-0.5 text-xs text-muted-foreground">
|
||||
{sourceTitle ?? "检测"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 space-y-1 text-sm">
|
||||
<p className="text-rose-600">你的答案:{userAnswer ?? "未作答"}</p>
|
||||
<p className="text-emerald-700">正确答案:{correctAnswer ?? ""}</p>
|
||||
</div>
|
||||
<p className="mt-2 rounded-lg bg-indigo-50 px-3 py-2 text-sm text-indigo-800">💡 {q.explain}</p>
|
||||
<div className="mt-3">
|
||||
<Button
|
||||
variant={mastered ? "outline" : "secondary"}
|
||||
size="sm"
|
||||
disabled={pending}
|
||||
onClick={() => startTransition(() => toggleMastered(id, !mastered))}
|
||||
>
|
||||
{mastered ? (
|
||||
<>
|
||||
<RotateCcw className="size-4" /> 改为未掌握
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2 className="size-4" /> 已掌握
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+45
-1
@@ -87,10 +87,14 @@ export const taskTemplates = mysqlTable(
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
// 0=周日,1=周一……6=周六(与 JS Date.getDay 一致)
|
||||
dow: int("dow").notNull(),
|
||||
dow: int("dow").notNull().default(0),
|
||||
title: varchar("title", { length: 100 }).notNull(),
|
||||
subject: mysqlEnum("subject", SUBJECT_VALUES).notNull().default("other"),
|
||||
requiresPhoto: boolean("requires_photo").notNull().default(false),
|
||||
// 模板生效方式:weekly=每周某weekday / date=某一天 / range=日期区间 / week=某一周
|
||||
mode: varchar("mode", { length: 10 }).notNull().default("weekly"),
|
||||
dateStart: date("date_start", { mode: "string" }),
|
||||
dateEnd: date("date_end", { mode: "string" }),
|
||||
sortOrder: int("sort_order").notNull().default(0),
|
||||
createdAt: datetime("created_at").notNull().default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
@@ -156,6 +160,46 @@ export const grammarPoints = mysqlTable(
|
||||
(t) => [uniqueIndex("uq_grammar_point_id").on(t.pointId)],
|
||||
);
|
||||
|
||||
// ===== 错题本:所有检测的错题,带详细讲解,可标记掌握 =====
|
||||
export const wrongBook = mysqlTable(
|
||||
"wrong_book",
|
||||
{
|
||||
id: bigint("id", { mode: "number" }).primaryKey().autoincrement(),
|
||||
childUserId: bigint("child_user_id", { mode: "number" })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
sourceType: varchar("source_type", { length: 10 }).notNull(), // lesson / weekly
|
||||
sourceId: varchar("source_id", { length: 60 }).notNull(), // pointId 或 weekKey
|
||||
sourceTitle: varchar("source_title", { length: 200 }),
|
||||
question: text("question").notNull(), // 题目 JSON(含讲解)
|
||||
userAnswer: text("user_answer"),
|
||||
correctAnswer: text("correct_answer"),
|
||||
mastered: boolean("mastered").notNull().default(false),
|
||||
createdAt: datetime("created_at").notNull().default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: datetime("updated_at").notNull().default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(t) => [index("idx_wrong_child").on(t.childUserId, t.mastered)],
|
||||
);
|
||||
|
||||
// ===== 每周能力检测记录 =====
|
||||
export const weeklyTest = mysqlTable(
|
||||
"weekly_test",
|
||||
{
|
||||
id: bigint("id", { mode: "number" }).primaryKey().autoincrement(),
|
||||
childUserId: bigint("child_user_id", { mode: "number" })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
weekKey: varchar("week_key", { length: 12 }).notNull(), // 2026-W32
|
||||
score: int("score"),
|
||||
correct: int("correct"),
|
||||
total: int("total"),
|
||||
passed: boolean("passed").notNull().default(false),
|
||||
questions: text("questions"), // 组卷 JSON,供回看
|
||||
takenAt: datetime("taken_at").notNull().default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(t) => [uniqueIndex("uq_weekly_child_week").on(t.childUserId, t.weekKey)],
|
||||
);
|
||||
|
||||
// ===== 英语语法学习进度(按知识点记录,达标即通过,不锁顺序)=====
|
||||
export const grammarProgress = mysqlTable(
|
||||
"grammar_progress",
|
||||
|
||||
+26
-3
@@ -13,12 +13,35 @@ export function dowOf(dateStr: string): number {
|
||||
|
||||
// 今天往前推 n 天的日期字符串
|
||||
export function daysAgo(n: number): string {
|
||||
const now = new Date();
|
||||
// 先定位上海时区的今天零点,再回退 n 天
|
||||
const today = new Date(
|
||||
new Date().toLocaleDateString("en-US", { timeZone: "Asia/Shanghai" }),
|
||||
);
|
||||
today.setDate(today.getDate() - n);
|
||||
void now;
|
||||
return today.toLocaleDateString("en-CA");
|
||||
}
|
||||
|
||||
function parse(dateStr: string): Date {
|
||||
const [y, m, d] = dateStr.split("-").map(Number);
|
||||
return new Date(Date.UTC(y, m - 1, d));
|
||||
}
|
||||
const fmt = (d: Date) => d.toISOString().slice(0, 10);
|
||||
|
||||
// 日期加减 n 天
|
||||
export function addDays(dateStr: string, n: number): string {
|
||||
const d = parse(dateStr);
|
||||
d.setUTCDate(d.getUTCDate() + n);
|
||||
return fmt(d);
|
||||
}
|
||||
|
||||
// 该日期所在周的周一(用于"某一周"与周键)
|
||||
export function mondayOf(dateStr: string): string {
|
||||
const dow = dowOf(dateStr); // 0=周日..6=周六
|
||||
const offset = (dow + 6) % 7; // 距周一的天数
|
||||
return addDays(dateStr, -offset);
|
||||
}
|
||||
|
||||
// 周键:用该周周一的日期字符串,唯一且直观
|
||||
export function weekKey(dateStr: string): string {
|
||||
return mondayOf(dateStr);
|
||||
}
|
||||
|
||||
|
||||
+17
-3
@@ -2,9 +2,22 @@
|
||||
import { and, asc, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { photos, taskInstances, taskTemplates } from "@/db/schema";
|
||||
import { dowOf } from "@/lib/dates";
|
||||
import { dowOf, mondayOf } from "@/lib/dates";
|
||||
import { viewUrl } from "@/lib/oss";
|
||||
|
||||
// 模板是否覆盖某一天(weekly/date/range/week 四种生效方式)
|
||||
function coversDate(
|
||||
t: { mode: string; dow: number; dateStart: string | null; dateEnd: string | null },
|
||||
date: string,
|
||||
): boolean {
|
||||
if (t.mode === "weekly") return t.dow === dowOf(date);
|
||||
if (t.mode === "date") return t.dateStart === date;
|
||||
if (t.mode === "range")
|
||||
return !!t.dateStart && !!t.dateEnd && date >= t.dateStart && date <= t.dateEnd;
|
||||
if (t.mode === "week") return !!t.dateStart && mondayOf(t.dateStart) === mondayOf(date);
|
||||
return false;
|
||||
}
|
||||
|
||||
export type TaskView = {
|
||||
id: number;
|
||||
title: string;
|
||||
@@ -25,11 +38,12 @@ export async function ensureDay(childId: number, date: string) {
|
||||
.limit(1);
|
||||
if (existing.length > 0) return;
|
||||
|
||||
const templates = await tx
|
||||
const all = await tx
|
||||
.select()
|
||||
.from(taskTemplates)
|
||||
.where(and(eq(taskTemplates.childUserId, childId), eq(taskTemplates.dow, dowOf(date))))
|
||||
.where(eq(taskTemplates.childUserId, childId))
|
||||
.orderBy(asc(taskTemplates.sortOrder));
|
||||
const templates = all.filter((t) => coversDate(t, date));
|
||||
|
||||
if (templates.length > 0) {
|
||||
await tx.insert(taskInstances).values(
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { grammarPoints, grammarProgress, weeklyTest } from "@/db/schema";
|
||||
import { extractQuiz, type QuizQ } from "@/lib/quiz-parse";
|
||||
import { todayStr, weekKey } from "@/lib/dates";
|
||||
|
||||
export const currentWeekKey = () => weekKey(todayStr());
|
||||
|
||||
// 确定性随机:同 (seed) 每次得到相同组卷,保证渲染与判分一致
|
||||
function hashStr(s: string): number {
|
||||
let h = 5381;
|
||||
for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
|
||||
return h >>> 0;
|
||||
}
|
||||
function mulberry32(a: number) {
|
||||
return () => {
|
||||
a |= 0;
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
function seededSample<T>(arr: T[], seed: string, n: number): T[] {
|
||||
const rnd = mulberry32(hashStr(seed));
|
||||
const pool = [...arr];
|
||||
for (let i = pool.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rnd() * (i + 1));
|
||||
[pool[i], pool[j]] = [pool[j], pool[i]];
|
||||
}
|
||||
return pool.slice(0, n);
|
||||
}
|
||||
|
||||
// 从已点亮知识点组卷(不足则补入门题),每周固定 10 题
|
||||
export async function buildWeeklyQuestions(childId: number, wk: string): Promise<QuizQ[]> {
|
||||
const lit = await db
|
||||
.select({ pointId: grammarProgress.pointId })
|
||||
.from(grammarProgress)
|
||||
.where(and(eq(grammarProgress.childUserId, childId), eq(grammarProgress.passed, true)));
|
||||
const litIds = new Set(lit.map((r) => r.pointId));
|
||||
|
||||
const all = await db.select().from(grammarPoints);
|
||||
let pool: QuizQ[] = [];
|
||||
for (const p of all) {
|
||||
if (litIds.has(p.pointId)) pool.push(...extractQuiz(p.md));
|
||||
}
|
||||
if (pool.length < 5) {
|
||||
for (const p of all) if (p.level === "starter") pool.push(...extractQuiz(p.md));
|
||||
}
|
||||
return seededSample(pool, `${childId}:${wk}`, 10);
|
||||
}
|
||||
|
||||
export async function getWeeklyRecord(childId: number, wk: string) {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(weeklyTest)
|
||||
.where(and(eq(weeklyTest.childUserId, childId), eq(weeklyTest.weekKey, wk)))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { and, eq, desc } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { wrongBook } from "@/db/schema";
|
||||
import type { QuizQ } from "@/lib/quiz-parse";
|
||||
import type { AnswerValue } from "@/lib/grammar";
|
||||
|
||||
// 各类题型的"用户作答"与"标准答案"可读文本
|
||||
export function answerText(q: QuizQ, a: AnswerValue | null | undefined): string {
|
||||
if (a == null) return "未作答";
|
||||
if (q.type === "fill") return String(a);
|
||||
if (q.type === "order") return Array.isArray(a) ? a.join(" ") : String(a);
|
||||
if (q.type === "match") return Array.isArray(a) ? (a as string[]).join("、") : String(a);
|
||||
const opts = q.type === "judge" ? ["对", "错"] : q.options ?? [];
|
||||
return opts[Number(a)] ?? String(a);
|
||||
}
|
||||
export function correctText(q: QuizQ): string {
|
||||
if (q.type === "fill") return (q.answers ?? []).join(" / ");
|
||||
if (q.type === "order") return (q.answer as string[]).join(" ");
|
||||
if (q.type === "match") return (q.pairs ?? []).map((p) => `${p[0]}→${p[1]}`).join("、");
|
||||
const opts = q.type === "judge" ? ["对", "错"] : q.options ?? [];
|
||||
return opts[q.answer as number] ?? "";
|
||||
}
|
||||
|
||||
// 错题入库(同一孩子同一来源同一题干去重)
|
||||
export async function recordWrong(
|
||||
childId: number,
|
||||
sourceType: "lesson" | "weekly",
|
||||
sourceId: string,
|
||||
sourceTitle: string,
|
||||
q: QuizQ,
|
||||
user: AnswerValue | null | undefined,
|
||||
) {
|
||||
const rows = await db
|
||||
.select({ question: wrongBook.question })
|
||||
.from(wrongBook)
|
||||
.where(and(eq(wrongBook.childUserId, childId), eq(wrongBook.sourceId, sourceId)));
|
||||
const dup = rows.some((r) => {
|
||||
try {
|
||||
return (JSON.parse(r.question) as QuizQ).stem === q.stem;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
if (dup) return;
|
||||
await db.insert(wrongBook).values({
|
||||
childUserId: childId,
|
||||
sourceType,
|
||||
sourceId,
|
||||
sourceTitle,
|
||||
question: JSON.stringify(q),
|
||||
userAnswer: answerText(q, user),
|
||||
correctAnswer: correctText(q),
|
||||
});
|
||||
}
|
||||
|
||||
export async function listWrong(childId: number) {
|
||||
return db.select().from(wrongBook).where(eq(wrongBook.childUserId, childId)).orderBy(desc(wrongBook.createdAt));
|
||||
}
|
||||
|
||||
export async function setMastered(id: number, childId: number, mastered: boolean) {
|
||||
await db
|
||||
.update(wrongBook)
|
||||
.set({ mastered, updatedAt: new Date() })
|
||||
.where(and(eq(wrongBook.id, id), eq(wrongBook.childUserId, childId)));
|
||||
}
|
||||
Reference in New Issue
Block a user