feat: add student supervision automation

This commit is contained in:
Codex
2026-06-30 17:07:51 +08:00
parent 7473c7a6d7
commit 0204c934d8
14 changed files with 803 additions and 16 deletions

View File

@@ -14,7 +14,7 @@ const ROLE_PERMISSION_DEFAULTS: Record<string, string[]> = {
tenant_owner: ['*'],
tenant_admin: ['*'],
tenant_operator: ['dashboard:read', 'content:*', 'marketing:*', 'badges:*', 'notifications:read', 'codes:read', 'coupons:read', 'referral:read', 'commission:read', 'crm:read'],
teacher: ['content:*', 'classes:read', 'students:read', 'students:notes:*', 'students:followups:*'],
teacher: ['content:*', 'classes:read', 'students:read', 'students:notes:*', 'students:followups:*', 'students:supervision:*'],
sales: ['codes:*', 'coupons:read', 'coupons:write', 'referral:*', 'commission:self'],
agent: ['codes:read', 'coupons:read', 'referral:self', 'commission:self'],
student: [],
@@ -136,6 +136,8 @@ export function tenantPermissionCatalog() {
{ key: 'students:notes:write', label: '学生备注管理' },
{ key: 'students:followups:read', label: '学生跟进任务查看' },
{ key: 'students:followups:write', label: '学生跟进任务管理' },
{ key: 'students:supervision:read', label: '学习督导预览' },
{ key: 'students:supervision:write', label: '学习督导生成' },
{ key: 'members:read', label: '成员查看' },
{ key: 'members:write', label: '成员管理' },
{ key: 'roles:read', label: '角色模板查看' },

View File

@@ -25,12 +25,23 @@ const FOLLOWUP_REPORT_RANGES: Record<string, number> = { '7d': 7, '30d': 30, '90
const MAX_BULK_STUDENTS = 200;
const MAX_BULK_CLASS_ASSIGNMENTS = 500;
const MAX_BULK_CRM_PUSH = 100;
const MAX_SUPERVISION_GENERATE = 100;
const CRM_ASSIGNABLE_ROLES = ['tenant_owner', 'tenant_admin', 'tenant_operator', 'teacher', 'sales', 'agent'];
const STUDENT_AVATAR_FIELD_KEYS = ['avatarUrl', 'avatar_url', 'avatar', 'headimgurl', 'headImgUrl', 'figureurl', 'figureurl_qq_1', 'figureurl_qq_2'];
const STUDENT_PRIMARY_ROLE_FIELD_KEYS = ['primaryRole', 'primary_role'];
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const DATE_KEY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const SUPERVISION_RULE_DEFAULTS = {
windowDays: 14,
inactivityDays: 7,
minAnswers: 10,
lowAccuracyThreshold: 0.6,
wrongQuestionThreshold: 5,
vocabularyDueThreshold: 20,
staleSessionDays: 3,
};
const shanghaiDateFormatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
@@ -94,11 +105,21 @@ function intValue(value: unknown, fallback: number) {
return Number.isFinite(numberValue) ? Math.trunc(numberValue) : fallback;
}
function boundedIntValue(value: unknown, fallback: number, min: number, max: number) {
const parsed = intValue(value, fallback);
return Math.max(min, Math.min(max, parsed));
}
function numberValue(value: unknown, fallback = 0) {
const parsed = Number(value ?? fallback);
return Number.isFinite(parsed) ? parsed : fallback;
}
function boundedNumberValue(value: unknown, fallback: number, min: number, max: number) {
const parsed = numberValue(value, fallback);
return Math.max(min, Math.min(max, parsed));
}
function ratio(numerator: number, denominator: number) {
if (denominator <= 0) return 0;
return Number((numerator / denominator).toFixed(4));
@@ -181,6 +202,10 @@ function isValidShanghaiDateKey(dateKey: string) {
return Number.isFinite(date.getTime()) && shanghaiDateKey(date) === dateKey;
}
function shanghaiTodayKey() {
return shanghaiDateKey(new Date());
}
function daysBetweenInclusive(startDate: string, endDate: string) {
const start = Date.parse(`${startDate}T00:00:00+08:00`);
const end = Date.parse(`${endDate}T00:00:00+08:00`);
@@ -221,6 +246,48 @@ function parseFollowupReportRange(timeRangeValue: string, startDateValue: string
};
}
interface SupervisionRuleConfig {
windowDays: number;
inactivityDays: number;
minAnswers: number;
lowAccuracyThreshold: number;
wrongQuestionThreshold: number;
vocabularyDueThreshold: number;
staleSessionDays: number;
}
function parseSupervisionRules(value: unknown): SupervisionRuleConfig {
const raw = objectValue(value);
return {
windowDays: boundedIntValue(raw.windowDays, SUPERVISION_RULE_DEFAULTS.windowDays, 3, 90),
inactivityDays: boundedIntValue(raw.inactivityDays, SUPERVISION_RULE_DEFAULTS.inactivityDays, 1, 90),
minAnswers: boundedIntValue(raw.minAnswers, SUPERVISION_RULE_DEFAULTS.minAnswers, 1, 500),
lowAccuracyThreshold: boundedNumberValue(raw.lowAccuracyThreshold, SUPERVISION_RULE_DEFAULTS.lowAccuracyThreshold, 0.1, 0.95),
wrongQuestionThreshold: boundedIntValue(raw.wrongQuestionThreshold, SUPERVISION_RULE_DEFAULTS.wrongQuestionThreshold, 1, 200),
vocabularyDueThreshold: boundedIntValue(raw.vocabularyDueThreshold, SUPERVISION_RULE_DEFAULTS.vocabularyDueThreshold, 1, 1000),
staleSessionDays: boundedIntValue(raw.staleSessionDays, SUPERVISION_RULE_DEFAULTS.staleSessionDays, 1, 30),
};
}
function supervisionBatchKey(value: unknown) {
const candidate = nullableString(value);
if (!candidate) return `manual:${shanghaiTodayKey()}`;
return candidate.length <= 120 ? candidate : createHash('sha256').update(candidate).digest('hex');
}
function defaultSupervisionDueAt() {
const date = new Date();
date.setDate(date.getDate() + 1);
date.setHours(18, 0, 0, 0);
return date.toISOString();
}
function supervisionPriority(score: number) {
if (score >= 90) return 'urgent';
if (score >= 60) return 'high';
return 'normal';
}
function classCodeValue(value: unknown) {
const code = nullableString(value);
if (!code) return null;
@@ -350,6 +417,295 @@ async function ensureStudentInScope(auth: TenantAdminAuth, studentUserId: string
}
}
async function loadStudentSupervisionCandidates(auth: TenantAdminAuth, input: {
rules: SupervisionRuleConfig;
classId: string | null;
assignedToUserId: string | null;
studentUserIds?: string[];
limit: number;
}) {
const scopedIds = await scopedClassIds(auth);
const params: unknown[] = [auth.tenantId, input.rules.windowDays, input.rules.staleSessionDays];
const filters = [
'tm.tenant_id = $1',
`tm.role = 'student'`,
`tm.status = 'active'`,
];
if (input.classId) {
params.push(input.classId);
filters.push(`exists (
select 1 from public.tenant_class_members scoped_cm
where scoped_cm.tenant_id = tm.tenant_id
and scoped_cm.user_id = tm.user_id
and scoped_cm.class_id = $${params.length}::uuid
and scoped_cm.member_type = 'student'
and scoped_cm.status = 'active'
)`);
}
if (scopedIds) {
params.push(scopedIds);
filters.push(`exists (
select 1 from public.tenant_class_members scoped_cm
where scoped_cm.tenant_id = tm.tenant_id
and scoped_cm.user_id = tm.user_id
and scoped_cm.class_id = any($${params.length}::uuid[])
and scoped_cm.member_type = 'student'
and scoped_cm.status = 'active'
)`);
}
if (input.studentUserIds?.length) {
params.push(input.studentUserIds);
filters.push(`tm.user_id = any($${params.length}::uuid[])`);
}
params.push(input.limit);
const rows = await query<Record<string, unknown>>(
`
with student_scope as (
select tm.tenant_id, tm.user_id, tm.created_at
from public.tenant_memberships tm
where ${filters.join(' and ')}
),
class_agg as (
select tcm.tenant_id, tcm.user_id,
min(tcm.class_id::text) as "defaultClassId",
jsonb_agg(
jsonb_build_object('classId', tc.id, 'className', tc.name, 'classCode', tc.code)
order by tc.sort_order asc, tc.created_at desc
) filter (where tcm.status = 'active') as classes
from public.tenant_class_members tcm
join public.tenant_classes tc on tc.tenant_id = tcm.tenant_id and tc.id = tcm.class_id
join student_scope ss on ss.tenant_id = tcm.tenant_id and ss.user_id = tcm.user_id
where tcm.member_type = 'student'
and tcm.status = 'active'
group by tcm.tenant_id, tcm.user_id
),
answers as (
select ar.tenant_id, ar.user_id,
count(*) filter (where ar.answered_at >= now() - ($2::int * interval '1 day'))::int as "answerCount",
count(*) filter (where ar.answered_at >= now() - ($2::int * interval '1 day') and ar.is_correct is true)::int as "correctCount",
count(*) filter (where ar.answered_at >= now() - ($2::int * interval '1 day') and ar.is_correct is false)::int as "wrongAnswerCount",
max(ar.answered_at) as "latestAnsweredAt"
from public.answer_records ar
join student_scope ss on ss.tenant_id = ar.tenant_id and ss.user_id = ar.user_id
group by ar.tenant_id, ar.user_id
),
wrongs as (
select wq.tenant_id, wq.user_id,
count(*) filter (where wq.resolved_at is null)::int as "unresolvedWrongQuestions",
coalesce(sum(wq.wrong_count) filter (where wq.resolved_at is null), 0)::int as "wrongQuestionAttempts",
max(wq.last_wrong_at) filter (where wq.resolved_at is null) as "latestWrongAt"
from public.wrong_questions wq
join student_scope ss on ss.tenant_id = wq.tenant_id and ss.user_id = wq.user_id
group by wq.tenant_id, wq.user_id
),
sessions as (
select ps.tenant_id, ps.user_id,
count(*) filter (
where ps.finished_at is null
and ps.started_at <= now() - ($3::int * interval '1 day')
and (ps.expires_at is null or ps.expires_at > now())
)::int as "staleActiveSessions",
max(ps.started_at) as "latestSessionAt"
from public.practice_sessions ps
join student_scope ss on ss.tenant_id = ps.tenant_id and ss.user_id = ps.user_id
group by ps.tenant_id, ps.user_id
),
reports as (
select pr.tenant_id, pr.user_id,
max(pr.submitted_at) as "latestReportAt",
min(pr.accuracy) filter (where pr.submitted_at >= now() - ($2::int * interval '1 day')) as "lowestReportAccuracy",
max(pr.score) filter (where pr.submitted_at >= now() - ($2::int * interval '1 day')) as "bestReportScore"
from public.practice_session_reports pr
join student_scope ss on ss.tenant_id = pr.tenant_id and ss.user_id = pr.user_id
group by pr.tenant_id, pr.user_id
),
vocab as (
select uwp.tenant_id, uwp.user_id,
count(*) filter (
where uwp.status in ('new', 'learning', 'reviewing')
and (uwp.next_review_date is null or uwp.next_review_date <= now())
)::int as "dueVocabularyWords",
count(*) filter (where uwp.status = 'mastered')::int as "masteredVocabularyWords",
max(uwp.last_review_date) as "latestVocabularyReviewAt"
from public.user_word_progress uwp
join student_scope ss on ss.tenant_id = uwp.tenant_id and ss.user_id = uwp.user_id
group by uwp.tenant_id, uwp.user_id
)
select ss.user_id as "studentUserId",
u.username, u.name, u.email::text as email,
case when ${canSeeStudentPhone(auth) ? 'true' : 'false'} then u.phone else null end as "studentPhone",
sp.region_id as "regionId", r.name as "regionName",
sp.selected_school_id as "selectedSchoolId", school.name as "selectedSchoolName",
sp.selected_major_id as "selectedMajorId", major.name as "selectedMajorName",
coalesce(sp.mastered_words_count, 0)::int as "profileMasteredWords",
coalesce(ca."defaultClassId", null) as "defaultClassId",
coalesce(ca.classes, '[]'::jsonb) as classes,
coalesce(a."answerCount", 0)::int as "answerCount",
coalesce(a."correctCount", 0)::int as "correctCount",
coalesce(a."wrongAnswerCount", 0)::int as "wrongAnswerCount",
a."latestAnsweredAt",
coalesce(w."unresolvedWrongQuestions", 0)::int as "unresolvedWrongQuestions",
coalesce(w."wrongQuestionAttempts", 0)::int as "wrongQuestionAttempts",
w."latestWrongAt",
coalesce(s."staleActiveSessions", 0)::int as "staleActiveSessions",
s."latestSessionAt",
rep."latestReportAt",
rep."lowestReportAccuracy",
rep."bestReportScore",
coalesce(v."dueVocabularyWords", 0)::int as "dueVocabularyWords",
coalesce(v."masteredVocabularyWords", 0)::int as "masteredVocabularyWords",
v."latestVocabularyReviewAt"
from student_scope ss
join public.platform_users u on u.id = ss.user_id
left join public.student_profiles sp on sp.tenant_id = ss.tenant_id and sp.user_id = ss.user_id
left join public.regions r on r.tenant_id = ss.tenant_id and r.id = sp.region_id
left join public.schools school on school.tenant_id = ss.tenant_id and school.id = sp.selected_school_id
left join public.majors major on major.tenant_id = ss.tenant_id and major.id = sp.selected_major_id
left join class_agg ca on ca.tenant_id = ss.tenant_id and ca.user_id = ss.user_id
left join answers a on a.tenant_id = ss.tenant_id and a.user_id = ss.user_id
left join wrongs w on w.tenant_id = ss.tenant_id and w.user_id = ss.user_id
left join sessions s on s.tenant_id = ss.tenant_id and s.user_id = ss.user_id
left join reports rep on rep.tenant_id = ss.tenant_id and rep.user_id = ss.user_id
left join vocab v on v.tenant_id = ss.tenant_id and v.user_id = ss.user_id
order by coalesce(a."latestAnsweredAt", s."latestSessionAt", v."latestVocabularyReviewAt", ss.created_at) asc nulls first
limit $${params.length}
`,
params,
);
return rows.map(row => buildSupervisionCandidate(row, input.rules, {
assignedToUserId: input.assignedToUserId,
classId: input.classId,
})).filter(Boolean) as Record<string, unknown>[];
}
function buildSupervisionCandidate(
row: Record<string, unknown>,
rules: SupervisionRuleConfig,
options: { assignedToUserId: string | null; classId: string | null },
) {
const answerCount = intValue(row.answerCount, 0);
const correctCount = intValue(row.correctCount, 0);
const unresolvedWrongQuestions = intValue(row.unresolvedWrongQuestions, 0);
const staleActiveSessions = intValue(row.staleActiveSessions, 0);
const dueVocabularyWords = intValue(row.dueVocabularyWords, 0);
const latestStudyAt = latestIso([
row.latestAnsweredAt,
row.latestSessionAt,
row.latestVocabularyReviewAt,
row.latestReportAt,
]);
const inactiveDays = latestStudyAt ? Math.floor((Date.now() - new Date(latestStudyAt).getTime()) / 86_400_000) : null;
const accuracy = answerCount > 0 ? correctCount / answerCount : null;
const reasons: Array<Record<string, unknown>> = [];
let riskScore = 0;
if (inactiveDays === null || inactiveDays >= rules.inactivityDays) {
const score = inactiveDays === null ? 35 : Math.min(55, inactiveDays * 5);
riskScore += score;
reasons.push({
code: 'inactive',
label: inactiveDays === null ? '未产生学习记录' : `${inactiveDays} 天未学习`,
severity: inactiveDays === null || inactiveDays >= rules.inactivityDays * 2 ? 'high' : 'medium',
value: inactiveDays,
threshold: rules.inactivityDays,
});
}
if (unresolvedWrongQuestions >= rules.wrongQuestionThreshold) {
riskScore += Math.min(45, unresolvedWrongQuestions * 4);
reasons.push({
code: 'wrong_backlog',
label: `未解决错题 ${unresolvedWrongQuestions}`,
severity: unresolvedWrongQuestions >= rules.wrongQuestionThreshold * 2 ? 'high' : 'medium',
value: unresolvedWrongQuestions,
threshold: rules.wrongQuestionThreshold,
});
}
if (answerCount >= rules.minAnswers && accuracy !== null && accuracy < rules.lowAccuracyThreshold) {
riskScore += Math.round((rules.lowAccuracyThreshold - accuracy) * 100);
reasons.push({
code: 'low_accuracy',
label: `${rules.windowDays} 天正确率 ${Math.round(accuracy * 100)}%`,
severity: accuracy < rules.lowAccuracyThreshold * 0.75 ? 'high' : 'medium',
value: Number(accuracy.toFixed(4)),
threshold: rules.lowAccuracyThreshold,
});
}
if (dueVocabularyWords >= rules.vocabularyDueThreshold) {
riskScore += Math.min(35, Math.ceil(dueVocabularyWords / Math.max(1, rules.vocabularyDueThreshold)) * 10);
reasons.push({
code: 'vocabulary_due',
label: `待复习单词 ${dueVocabularyWords}`,
severity: dueVocabularyWords >= rules.vocabularyDueThreshold * 2 ? 'high' : 'medium',
value: dueVocabularyWords,
threshold: rules.vocabularyDueThreshold,
});
}
if (staleActiveSessions > 0) {
riskScore += Math.min(25, staleActiveSessions * 10);
reasons.push({
code: 'stale_session',
label: `存在 ${staleActiveSessions} 个未完成练习`,
severity: 'medium',
value: staleActiveSessions,
threshold: 1,
});
}
if (!reasons.length) return null;
const priority = supervisionPriority(riskScore);
const studentName = nullableString(row.name) || nullableString(row.username) || nullableString(row.studentPhone) || String(row.studentUserId);
const primaryReason = String(reasons[0]?.label || '学习状态需要跟进');
const classId = options.classId || nullableString(row.defaultClassId);
return {
studentUserId: row.studentUserId,
studentName,
studentPhone: row.studentPhone,
assignedToUserId: options.assignedToUserId,
classId,
classes: row.classes,
title: `学习督导:${primaryReason}`,
description: reasons.map(item => item.label).join(''),
followupType: 'learning',
priority,
riskScore: Math.min(100, Math.round(riskScore)),
reasons,
evidence: {
windowDays: rules.windowDays,
answerCount,
correctCount,
wrongAnswerCount: intValue(row.wrongAnswerCount, 0),
accuracy: accuracy === null ? null : Number(accuracy.toFixed(4)),
latestStudyAt,
inactiveDays,
unresolvedWrongQuestions,
wrongQuestionAttempts: intValue(row.wrongQuestionAttempts, 0),
staleActiveSessions,
dueVocabularyWords,
masteredVocabularyWords: intValue(row.masteredVocabularyWords, 0),
latestWrongAt: row.latestWrongAt || null,
latestReportAt: row.latestReportAt || null,
lowestReportAccuracy: row.lowestReportAccuracy === null || row.lowestReportAccuracy === undefined ? null : numberValue(row.lowestReportAccuracy, 0),
bestReportScore: row.bestReportScore === null || row.bestReportScore === undefined ? null : numberValue(row.bestReportScore, 0),
latestVocabularyReviewAt: row.latestVocabularyReviewAt || null,
},
};
}
function latestIso(values: unknown[]) {
const timestamps = values
.map(value => (typeof value === 'string' || value instanceof Date ? new Date(value).getTime() : NaN))
.filter(Number.isFinite);
if (!timestamps.length) return null;
return new Date(Math.max(...timestamps)).toISOString();
}
async function ensureUserTenantMembership(
client: pg.PoolClient,
tenantId: string,
@@ -1765,6 +2121,177 @@ export async function tenantStudentFollowupReportRoute(ctx: RequestContext) {
};
}
export async function tenantStudentSupervisionPreviewRoute(ctx: RequestContext) {
const auth = await requireTenantAdmin(ctx);
requireTenantPermission(auth, 'students:read');
requireTenantPermission(auth, 'students:supervision:read');
const limit = intParam(ctx, 'limit', 20, 100);
const classId = stringParam(ctx, 'classId') || null;
const assignedToUserId = stringParam(ctx, 'assignedToUserId') || null;
if (classId) await ensureReadableClass(auth, classId);
if (assignedToUserId) {
await query(
`
select 1
from public.tenant_memberships
where tenant_id = $1 and user_id = $2::uuid and status = 'active'
and role = any($3::text[])
limit 1
`,
[auth.tenantId, assignedToUserId, CRM_ASSIGNABLE_ROLES],
).then(rows => {
if (!rows[0]) throw new HttpError(400, 'User is not an active tenant member', 'ASSIGNEE_NOT_FOUND');
});
}
const rules = parseSupervisionRules({
windowDays: stringParam(ctx, 'windowDays'),
inactivityDays: stringParam(ctx, 'inactivityDays'),
minAnswers: stringParam(ctx, 'minAnswers'),
lowAccuracyThreshold: stringParam(ctx, 'lowAccuracyThreshold'),
wrongQuestionThreshold: stringParam(ctx, 'wrongQuestionThreshold'),
vocabularyDueThreshold: stringParam(ctx, 'vocabularyDueThreshold'),
staleSessionDays: stringParam(ctx, 'staleSessionDays'),
});
const candidates = await loadStudentSupervisionCandidates(auth, { rules, classId, assignedToUserId, limit });
return {
item: {
rules,
filters: {
classId,
assignedToUserId,
scoped: (await scopedClassIds(auth)) !== null,
},
totalCandidates: candidates.length,
candidates,
},
};
}
export async function generateTenantStudentSupervisionRoute(ctx: RequestContext) {
const auth = await requireTenantAdmin(ctx);
requireTenantPermission(auth, 'students:read');
requireTenantPermission(auth, 'students:supervision:write');
const body = await readJsonBody(ctx);
const limit = boundedIntValue(body.limit, 20, 1, MAX_SUPERVISION_GENERATE);
const classId = nullableString(body.classId);
const assignedToUserId = nullableString(body.assignedToUserId);
const dueAt = optionalTimestampString(body.dueAt, 'dueAt') || defaultSupervisionDueAt();
const batchKey = supervisionBatchKey(body.batchKey);
const rules = parseSupervisionRules(body.rules);
const onlyStudentUserIds = Array.isArray(body.studentUserIds)
? strictUuidArrayValue(body.studentUserIds, 'studentUserIds', MAX_SUPERVISION_GENERATE)
: [];
if (classId) await ensureReadableClass(auth, classId);
const result = await transaction(async client => {
await ensureUserTenantMembership(client, auth.tenantId, assignedToUserId, CRM_ASSIGNABLE_ROLES, 'ASSIGNEE_NOT_FOUND');
let candidates = await loadStudentSupervisionCandidates(auth, {
rules,
classId,
assignedToUserId,
studentUserIds: onlyStudentUserIds,
limit: Math.max(limit, onlyStudentUserIds.length || 0) || limit,
});
candidates = candidates.slice(0, limit);
const items: unknown[] = [];
const errors: unknown[] = [];
for (let index = 0; index < candidates.length; index += 1) {
const candidate = candidates[index];
const studentUserId = String(candidate.studentUserId || '');
try {
await ensureStudentInScope(auth, studentUserId);
const candidateClassId = nullableString(candidate.classId);
if (candidateClassId) await ensureTenantClass(client, auth.tenantId, candidateClassId);
const idempotencyKey = `student_supervision:${batchKey}:${studentUserId}`;
const metadata = {
...objectValue(body.metadata),
autoSupervision: {
idempotencyKey,
batchKey,
generatedAt: new Date().toISOString(),
rules,
riskScore: candidate.riskScore,
reasons: candidate.reasons,
evidence: candidate.evidence,
},
};
const followup = await client.query<Record<string, unknown>>(
`
insert into public.tenant_student_followups (
tenant_id, student_user_id, assigned_to_user_id, class_id,
title, description, followup_type, priority, status, due_at,
metadata, created_by, updated_by
)
values (
$1, $2::uuid, $3::uuid, $4::uuid,
$5, $6, 'learning', $7, 'open', $8::timestamptz,
$9::jsonb, $10, $10
)
on conflict (tenant_id, (metadata->'autoSupervision'->>'idempotencyKey'))
where metadata->'autoSupervision'->>'idempotencyKey' is not null
do update set assigned_to_user_id = coalesce(excluded.assigned_to_user_id, public.tenant_student_followups.assigned_to_user_id),
class_id = coalesce(excluded.class_id, public.tenant_student_followups.class_id),
title = excluded.title,
description = excluded.description,
priority = excluded.priority,
due_at = excluded.due_at,
metadata = public.tenant_student_followups.metadata || excluded.metadata,
updated_by = excluded.updated_by,
updated_at = now()
returning id, student_user_id as "studentUserId",
assigned_to_user_id as "assignedToUserId", class_id as "classId",
title, description, followup_type as "followupType", priority, status,
due_at as "dueAt", metadata, created_at as "createdAt", updated_at as "updatedAt"
`,
[
auth.tenantId,
studentUserId,
assignedToUserId,
candidateClassId,
candidate.title,
candidate.description,
candidate.priority,
dueAt,
JSON.stringify(metadata),
auth.userId,
],
);
items.push({ index, studentUserId, followupId: followup.rows[0].id, item: followup.rows[0] });
} catch (error) {
errors.push({
index,
studentUserId,
code: error instanceof HttpError ? error.code : 'STUDENT_SUPERVISION_ITEM_FAILED',
message: error instanceof Error ? error.message : 'Student supervision item failed',
});
}
}
await recordAudit(client, auth, 'tenant.students.supervision_generated', 'tenant_student_followups', null, {
batchKey,
classId,
assignedToUserId,
total: candidates.length,
successCount: items.length,
errorCount: errors.length,
rules,
});
return {
batchKey,
total: candidates.length,
successCount: items.length,
errorCount: errors.length,
items,
errors,
};
});
return result;
}
export async function upsertTenantStudentFollowupRoute(ctx: RequestContext) {
const auth = await requireTenantAdmin(ctx);
requireTenantPermission(auth, 'students:followups:write');

View File

@@ -6,9 +6,11 @@ import {
removeTenantClassMemberRoute,
tenantClassesRoute,
tenantClassMembersRoute,
generateTenantStudentSupervisionRoute,
tenantStudentFollowupsRoute,
tenantStudentFollowupReportRoute,
tenantStudentNotesRoute,
tenantStudentSupervisionPreviewRoute,
tenantStudentsRoute,
tenantTeachersRoute,
pushTenantStudentsToCrmRoute,
@@ -105,6 +107,8 @@ export const tenantAdminRoutes: RouteDefinition[] = [
['GET', '/api/tenant-admin/students/followups', tenantStudentFollowupsRoute],
['GET', '/api/tenant-admin/students/followups/report', tenantStudentFollowupReportRoute],
['PUT', '/api/tenant-admin/students/followups', upsertTenantStudentFollowupRoute],
['GET', '/api/tenant-admin/students/supervision/preview', tenantStudentSupervisionPreviewRoute],
['POST', '/api/tenant-admin/students/supervision/generate', generateTenantStudentSupervisionRoute],
['GET', '/api/tenant-admin/teachers', tenantTeachersRoute],
['GET', '/api/tenant-admin/overview', tenantOverviewRoute],
['GET', '/api/tenant-admin/dashboard', tenantDashboardRoute],

View File

@@ -4,6 +4,7 @@ import { Button, Input, Text, Textarea, View } from '@tarojs/components';
import {
bulkAssignTenantClassMembers,
bulkUpsertTenantStudents,
generateTenantStudentSupervision,
loadTenantClasses,
loadTenantStudentFollowups,
loadTenantStudentFollowupReport,
@@ -11,6 +12,7 @@ import {
loadTenantStudents,
loadTenantTeachers,
loadTenantMembers,
previewTenantStudentSupervision,
pushTenantStudentsToCrm,
updateTenantStudentStatus,
upsertTenantStudent,
@@ -24,6 +26,7 @@ import {
type TenantStudentNoteItem,
type TenantStudentCrmPushInput,
type TenantStudentFollowupReport,
type TenantStudentSupervisionCandidate,
type TenantTeacherItem,
type TenantMemberItem,
} from '@/services/tenantAdmin';
@@ -35,6 +38,15 @@ const followupTypes = ['learning', 'service', 'sales', 'renewal', 'risk', 'custo
const followupPriorities = ['low', 'normal', 'high', 'urgent'];
const followupStatuses = ['open', 'in_progress', 'done', 'cancelled'];
const crmAssignableRoles = ['tenant_owner', 'tenant_admin', 'tenant_operator', 'teacher', 'sales', 'agent'];
const defaultSupervisionRules = {
windowDays: 14,
inactivityDays: 7,
minAnswers: 10,
lowAccuracyThreshold: 0.6,
wrongQuestionThreshold: 5,
vocabularyDueThreshold: 20,
staleSessionDays: 3,
};
function emptyStudentForm(): TenantStudentInput {
return {
@@ -124,7 +136,10 @@ export default function TenantStudentsPage() {
const [bulkResult, setBulkResult] = useState<BulkOperationResult | null>(null);
const [assignResult, setAssignResult] = useState<BulkOperationResult | null>(null);
const [crmPushResult, setCrmPushResult] = useState<BulkOperationResult | null>(null);
const [supervisionResult, setSupervisionResult] = useState<BulkOperationResult | null>(null);
const [followupReport, setFollowupReport] = useState<TenantStudentFollowupReport['item'] | null>(null);
const [supervisionCandidates, setSupervisionCandidates] = useState<TenantStudentSupervisionCandidate[]>([]);
const [supervisionRules, setSupervisionRules] = useState(defaultSupervisionRules);
const [scoped, setScoped] = useState(false);
const [busy, setBusy] = useState('');
const [error, setError] = useState('');
@@ -332,6 +347,50 @@ export default function TenantStudentsPage() {
}
}
async function previewSupervision() {
setBusy('supervisionPreview');
setError('');
try {
const payload = await previewTenantStudentSupervision({
...supervisionRules,
classId: selectedClassId || undefined,
limit: 20,
});
setSupervisionCandidates(payload.item?.candidates || []);
Taro.showToast({ title: '督导候选已刷新', icon: 'success' });
} catch (nextError) {
setError(nextError instanceof Error ? nextError.message : '学习督导预览失败');
} finally {
setBusy('');
}
}
async function generateSupervision() {
if (!supervisionCandidates.length) {
Taro.showToast({ title: '请先预览候选', icon: 'none' });
return;
}
setBusy('supervisionGenerate');
setError('');
try {
const result = await generateTenantStudentSupervision({
rules: supervisionRules,
classId: selectedClassId || null,
studentUserIds: supervisionCandidates.map(item => item.studentUserId),
batchKey: `taro-supervision-${new Date().toISOString().slice(0, 10)}-${selectedClassId || 'all'}`,
limit: supervisionCandidates.length,
metadata: { source: 'taro-tenant-admin' },
});
setSupervisionResult(result);
Taro.showToast({ title: '督导任务已生成', icon: result.errorCount ? 'none' : 'success' });
reload();
} catch (nextError) {
setError(nextError instanceof Error ? nextError.message : '学习督导生成失败');
} finally {
setBusy('');
}
}
async function saveNote() {
if (!selectedStudent) {
Taro.showToast({ title: '请选择学生', icon: 'none' });
@@ -575,6 +634,32 @@ export default function TenantStudentsPage() {
))}
</View>
<View className='admin-section'>
<Text className='admin-section-title'></Text>
<View className='admin-form-grid'>
<Input className='admin-input' placeholder='观察天数' value={String(supervisionRules.windowDays)} onInput={event => setSupervisionRules(prev => ({ ...prev, windowDays: Number(event.detail.value || prev.windowDays) }))} />
<Input className='admin-input' placeholder='未学习天数' value={String(supervisionRules.inactivityDays)} onInput={event => setSupervisionRules(prev => ({ ...prev, inactivityDays: Number(event.detail.value || prev.inactivityDays) }))} />
<Input className='admin-input' placeholder='最低答题数' value={String(supervisionRules.minAnswers)} onInput={event => setSupervisionRules(prev => ({ ...prev, minAnswers: Number(event.detail.value || prev.minAnswers) }))} />
<Input className='admin-input' placeholder='低正确率阈值' value={String(supervisionRules.lowAccuracyThreshold)} onInput={event => setSupervisionRules(prev => ({ ...prev, lowAccuracyThreshold: Number(event.detail.value || prev.lowAccuracyThreshold) }))} />
<Input className='admin-input' placeholder='错题阈值' value={String(supervisionRules.wrongQuestionThreshold)} onInput={event => setSupervisionRules(prev => ({ ...prev, wrongQuestionThreshold: Number(event.detail.value || prev.wrongQuestionThreshold) }))} />
<Input className='admin-input' placeholder='待复习单词阈值' value={String(supervisionRules.vocabularyDueThreshold)} onInput={event => setSupervisionRules(prev => ({ ...prev, vocabularyDueThreshold: Number(event.detail.value || prev.vocabularyDueThreshold) }))} />
</View>
<View className='admin-actions compact'>
<Button className='admin-button primary' loading={busy === 'supervisionPreview'} onClick={previewSupervision}></Button>
<Button className='admin-button' loading={busy === 'supervisionGenerate'} onClick={generateSupervision}></Button>
{supervisionResult ? <Text className='admin-row-meta'>{resultSummary(supervisionResult)}</Text> : null}
</View>
<View className='admin-list'>
{supervisionCandidates.slice(0, 6).map(item => (
<View className='admin-row' key={item.studentUserId}>
<Text className='admin-row-main'>{item.studentName || item.studentUserId} · {String(item.riskScore || 0)}</Text>
<Text className='admin-row-meta'>{item.priority || 'normal'} · {item.description || '学习状态需要跟进'}</Text>
</View>
))}
</View>
{!supervisionCandidates.length ? <Text className='admin-row-meta'></Text> : null}
</View>
<View className='admin-section'>
<Text className='admin-section-title'>CRM </Text>
<View className='admin-form-grid'>

View File

@@ -174,6 +174,40 @@ export interface TenantStudentFollowupReport {
};
}
export interface TenantStudentSupervisionRules {
windowDays?: number;
inactivityDays?: number;
minAnswers?: number;
lowAccuracyThreshold?: number;
wrongQuestionThreshold?: number;
vocabularyDueThreshold?: number;
staleSessionDays?: number;
}
export interface TenantStudentSupervisionCandidate {
studentUserId: string;
studentName?: string | null;
studentPhone?: string | null;
assignedToUserId?: string | null;
classId?: string | null;
title?: string;
description?: string;
followupType?: string;
priority?: string;
riskScore?: number;
reasons?: Record<string, unknown>[];
evidence?: Record<string, unknown>;
}
export interface TenantStudentSupervisionPreview {
item?: {
rules?: TenantStudentSupervisionRules;
filters?: Record<string, unknown>;
totalCandidates?: number;
candidates?: TenantStudentSupervisionCandidate[];
};
}
export interface ImportJobItem {
id: string;
importType?: string;
@@ -1113,6 +1147,32 @@ export async function loadTenantStudentFollowupReport(query: {
});
}
export async function previewTenantStudentSupervision(query: TenantStudentSupervisionRules & {
classId?: string;
assignedToUserId?: string;
limit?: number;
} = {}) {
return apiRequest<TenantStudentSupervisionPreview>('/api/tenant-admin/students/supervision/preview', {
query: { ...query, limit: query.limit || 20 },
});
}
export async function generateTenantStudentSupervision(input: {
rules?: TenantStudentSupervisionRules;
classId?: string | null;
assignedToUserId?: string | null;
studentUserIds?: string[];
dueAt?: string | null;
batchKey?: string;
limit?: number;
metadata?: Record<string, unknown>;
}) {
return apiRequest<BulkOperationResult>('/api/tenant-admin/students/supervision/generate', {
method: 'POST',
body: input,
});
}
export async function upsertTenantStudentFollowup(input: {
id?: string;
studentUserId: string;