学习闭环增强:错题本+每周能力检测+学习概览日历+模板日历+课程管理
- 错题本:所有检测错题自动入库,带详细讲解,可标记掌握,孩子端可查 - 每周能力检测:从已学知识点确定性组卷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
@@ -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>
|
||||
<form action={logout}>
|
||||
<Button type="submit" variant="outline" size="sm">
|
||||
退出登录
|
||||
</Button>
|
||||
</form>
|
||||
</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>
|
||||
</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 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="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}
|
||||
</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-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",
|
||||
)}
|
||||
>
|
||||
<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>
|
||||
<span className="shrink-0 font-medium 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>
|
||||
)}
|
||||
{!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>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</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>
|
||||
</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} />;
|
||||
}
|
||||
|
||||
+155
-118
@@ -3,165 +3,202 @@
|
||||
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]}
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
onClick={() => setSelected(d)}
|
||||
className={cn(
|
||||
"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>
|
||||
<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}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 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>}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`删除 ${item.title}`}
|
||||
className="ml-1 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => startTransition(() => deleteTemplate(item.id))}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<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">{t.title}</span>
|
||||
<span className="text-xs text-muted-foreground">({modeLabel[t.mode] ?? t.mode})</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`删除 ${t.title}`}
|
||||
className="ml-auto text-muted-foreground hover:text-destructive"
|
||||
onClick={() => startTransition(() => deleteTemplate(t.id))}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<form onSubmit={onAdd} className="flex flex-wrap items-end gap-3 border-t pt-3">
|
||||
<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"
|
||||
>
|
||||
{SUBJECTS.map((s) => (
|
||||
<option key={s.key} value={s.key}>
|
||||
{s.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<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">
|
||||
{SUBJECTS.map((s) => (
|
||||
<option key={s.key} value={s.key}>
|
||||
{s.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</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 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} />
|
||||
</div>
|
||||
<div className="flex h-9 items-center gap-2">
|
||||
<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>
|
||||
</div>
|
||||
<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}
|
||||
/>
|
||||
</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>
|
||||
</div>
|
||||
<Button type="submit" disabled={pending || title.trim() === ""}>
|
||||
添加
|
||||
</Button>
|
||||
{error && <p className="text-sm font-medium text-destructive">{error}</p>}
|
||||
</form>
|
||||
{error && <p className="text-sm font-medium text-destructive">{error}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user