Skip to main content
Tutoring lives in the Contacts satellite at /{wsId}/users/tutoring. It turns two existing signals — attendance deficits and flagged group feedback — into scheduled make-up sessions, then tracks attendance and exports the result for payroll.

Surfaces

  • Schedule lists every session for a date-range preset (upcoming, today, tomorrow, next 7 days, this month, past, all) and can be narrowed by status, group, learner, teacher, and reason. Filters drive both the table and the export. Forward-looking presets request sortOrder=asc so the nearest session is first; past and all keep the API default of newest-first.
  • Needs support is the queue of learners with an absence deficit within the configured recent attendance window (ABSENT_RECOVERY), a require_attention feedback (WEAK_SUPPORT), or both. An optional Count absences from date (absenceCountFromDate, workspace-local YYYY-MM-DD) narrows that window further: the queue counts only absences on or after the later of the rolling lookback start and that date. It lets a centre that adopted the app mid-term ignore absences from before it started tracking make-ups. Older absences and sessions are not changed or deleted; they are only left out of make-up suggestions. Unset (the default for every existing policy) keeps the rolling window alone. Linked make-up content pairs sessions with absences over its own fixed 90-day horizon (TUTORING_LINK_HORIZON_DAYS), not the queue window, so shortening the lookback never strips notes from a make-up booked earlier. The count-from date still applies: a make-up never pairs with an absence before it. An absence older than both is left unpaired, and its make-up shows no linked notes rather than another absence’s notes (queue/route.count-from.test.ts, tutoring-absence-cutoff.test.ts, linked-content.test.ts). Scheduling from a queue row fills the learner, group, reason, and suggested times for the missing sessions. Staff choose the tutoring teacher separately. A pending recovery session reserves one absence, so staff do not schedule the same make-up twice. Feedback already linked to a pending support session does not create another scheduling suggestion. It can still appear as an office-review-only row when its lesson content has remained unchanged for the configured interval. An absence marked in any class appears in the queue as soon as it is saved, however many absences the workspace has. The queue pages its attendance, session and feedback reads past the PostgREST row cap rather than reading one capped page (queue/route.max-rows.test.ts). After a completed support session, still-flagged feedback returns for reassessment after the configured interval. Older unscheduled feedback shows a parent follow-up prompt. If flagged feedback keeps the same content across the configured review interval, the queue shows an office-review alert and count. The alert compares consecutive feedback entries for that learner and group; edits made in place to an existing entry have no separate timestamp.
  • Settings stores a workspace tutoring policy with standard and English center presets. Each section starts as a read-only summary; Edit section opens only that section with Save and Cancel. Cancel discards the section draft, and other sections stay read-only while it is open. Saving merges only that section’s fields into the latest loaded policy, preserving refreshed values in other sections. Applying a preset replaces the draft except workspace-specific fields (campuses, tutor groups, group shifts, and the count-absences-from date). Save, Cancel, and editor inputs are disabled during a pending save; a failed save retains the draft for retry. Operators can adjust session length, lead time, support session count, absence lookback, the count-absences-from date (a real date no later than tomorrow in UTC; it can be cleared, and an invalid stored date reads as unset without resetting the rest of the policy), reassessment and follow-up intervals, scheduling horizon, class-time exceptions, named shifts, scoped group-name or group-tag exclusion rules, needs-tutoring groups, the unchanged-content review interval, group-to-campus labels, and the parent message template. Only members with manage_workspace_settings can save it. The English center preset excludes kindergarten group names containing DDT, Mẫu giáo, or Kindergarten from all tutoring (see Where class exclusions apply). Existing policies using the earlier unmodified DDT preset inherit these rules; custom rules remain as saved. Staff can add other naming patterns used by their workspace. Rule scope (all, make-up, or weak support), name match type, and text are editable; an interval of 0 disables office-review alerts. Older saved English center policies inherit these defaults until staff customize them.
  • Headline counts run as bounded count: exact queries, so they stay correct on workspaces with more sessions than one page. The schedule loads first; counts then load behind it. The support queue is requested when its tab is opened, and the client reuses recent results for two minutes.

Read lesson content

Every member allowed to view tutoring sessions (view_user_groups) can select its lesson-content preview in the Contacts schedule to read the full text. The dialog preserves line breaks and scrolls long notes. It is read-only and uses only the content already returned by the authorized session list. Changing the displayed session closes the old dialog. Blank content has no preview control. Editing remains a separate manager action requiring update_user_groups_scores; viewing does not save content, mark attendance, send a message or change the linked-content rules. The existing page and API workspace/group authorization still apply. Regression coverage: tutoring-session-content.test.tsx exercises a viewer without edit permission, manager edit availability, literal text and session replacement. Row actions mark a session done, no-show, cancelled, or back to pending, and generate the parent-facing message for the session. Staff can edit each session’s lesson content after creation, so teaching notes from the separate content sheet can be kept with the attendance record. Managers can permanently delete a pending or cancelled session after an in-app confirmation. Completed and no-show sessions stay intact for attendance and payroll history. The live queue remains on the retained Next.js route. The Rust migration target has shared golden fixtures for tag exclusions, the kindergarten name defaults, and current learner membership filtering. Run node --test scripts/tutoring-queue-parity.test.mjs for the TypeScript helpers and the focused workspaces_tutoring_queue Rust library tests for the same fixtures. This coverage does not establish full route parity: support-group candidates and tutor-group exclusions still need separate acceptance before a route promotion.

Who the support queue lists

The support queue lists a learner only under the classes they belong to now: a non-teacher row in workspace_user_groups_users for an unarchived learner. A learner who moved class, or was removed from one, no longer appears under the former class; their absences, flagged feedback and earlier sessions stay recorded and are not deleted. Pending make-ups for a class the learner left are not carried to the new class, because each make-up belongs to the missed class’s lessons. This applies to every workspace and has no setting. Exclusion rules in Settings → weak support read either the class name (the default) or the class’s group tags. A class format such as kindergarten, DDT or IELTS is not a class field, so staff who tag classes by format add a Class tag rule for each excluded format. Tags are read only when a tag rule exists. The English center preset still ships its name rules, with no tag rules.

Where class exclusions apply

The same exclusion rules apply on every tutoring screen that lists or suggests classes and learners for new tutoring, not only in the support queue. Matching ignores letter case and Vietnamese diacritics, in both the rule and the class name or tag: text is decomposed, accent marks are dropped and đ/Đ reads as d. A contains rule for DDT therefore also matches Starters ddt 2, ĐĐT and Đdt, and Mẫu giáo matches Mau giao. Exact, prefix and suffix rules compare the same folded text. A single-word contains value matches only as its own token: no letter may touch it on either side, while digits, spaces and punctuation count as borders. DDT therefore matches DDT, DDT1, DDT-A, Lớp DDT 2 and ĐĐT, but not GDĐT (the education-department abbreviation), KĐĐT or ADĐT, so a class such as Ôn thi Sở GDĐT stays eligible. A value with a space, such as Mẫu giáo, keeps plain substring matching. Class tag rules apply on the same screens: when the policy has a tag rule, Contacts loads the workspace class tags so the class picker, suggestions and queue filter hide a class excluded only by its tag. Make-up sessions read rules scoped to all or make-up; weak-support sessions read all or weak support; custom sessions read only all rules. Tutor groups count as excluded everywhere, as before. A learner in both an excluded and an ordinary class is skipped only under the excluded class: they still appear in the queue, the class picker and the suggestions under the ordinary class. Booked history is not affected. Sessions already booked in an excluded class stay in the schedule, the filters, the exports and payroll, and staff can still edit, mark, reschedule or delete them. Exclusion only stops new sessions. A custom policy without a DDT rule does not exclude DDT classes; the rules come only from the workspace policy, which staff with manage_workspace_settings edit in Settings → weak support. Regression coverage: packages/internal-api/src/tutoring-group-rules.test.ts, tutoring-suggestion.test.ts, tutoring-shift-assignment.test.ts, apps/web/src/lib/tutoring/group-exclusion.test.ts, tutoring/sessions/route.test.ts, tutoring/queue/route.test.ts, and the Contacts tutoring-create-card.exclusions.test.tsx and tutoring-suggestion-apply.test.ts. Needs-tutoring groups (Settings → weak support, empty by default) list learners who need tutoring without an absence or flagged feedback. Every current learner member of such a group appears as weak support under each of their current, unarchived classes, other than tutor and needs-tutoring groups. A learner with no other class appears under the needs-tutoring group itself. A class leaves the queue once a weak-support session is pending there, and returns only after the reassessment interval following a completed weak-support session, as with flagged feedback. Exclusion rules still apply. Rows come from group membership, so they carry no source feedback. They are marked “In a needs-tutoring group”. End tutoring is offered on them only to clear flagged feedback the row also carries; staff take a learner off the list by removing them from the group. Filtering the queue by a group reads only that group and the needs-tutoring groups, plus, when filtering by a needs-tutoring group, its members’ other classes. With no needs-tutoring group configured, the queue behaves exactly as before. The detailed and payroll exports page every session read and order it by date, start time and id. Sessions sharing one teacher slot therefore never skip or repeat across the 1,000-row PostgREST page. Group and person names are read in chunks of at most 100 ids. A read stops with an error after 200 pages instead of looping. Regression coverage: queue/route.membership.test.ts, export/route.test.ts, and packages/internal-api/src/tutoring-group-rules.test.ts.

Weekly repeats in the session draft

In Contacts tutoring creation, Repeat weekly adds the next occurrence of every selected weekday and start time after the latest dated session in the draft. Saturday plus Sunday repeats both days; a Saturday–Sunday–Monday pattern also stays intact across the calendar week boundary. Each occurrence keeps its own teacher, duration and local start time. When a weekday/time appears in several weeks, its latest row supplies those details. Clicking again adds one more occurrence of each pattern, without copying earlier weeks again. The rule applies to all tutoring reasons and workspaces, with no preset-specific exception. It uses the selected civil date and local time. For a GMT+7 center, the basis is Asia/Ho_Chi_Minh, including 22:30 and 00:30 sessions. Tutoring stores session_date as a SQL date and start_time as a time, rather than deriving weekdays from a UTC timestamp or the browser timezone. An imported UTC instant must first be interpreted in the center timezone. Repeat changes only the unsaved draft; the existing create action submits the explicit sessions[] array. Rows without a date do not seed repeats. The button is disabled if no dated rows exist or the entire repeated pattern would exceed the existing 50-session request limit; it never silently drops weekdays to fit. Existing server conflict and permission checks still apply. Regression coverage: tutoring-repeat.test.tsx drives the real draft editor for weekend, three-day, four-day and seven-day patterns, week/year boundaries, GMT+7 midnight conversion, repeated clicks, distinct timeframes and the request limit.

Enablement

Tutoring is gated by the ENABLE_TUTORING workspace config: The API enforces the same table: resolveTutoringRouteAccess (apps/web/src/lib/tutoring/route-access.ts) reads ENABLE_TUTORING from workspace_configs (the source the Contacts page reads, not a workspace secret) and, when the module is off, every tutoring route (sessions, queue, policy, teachers, export, mark, message preview, weak-support end) answers 404 like an unknown workspace, before any tutoring data is read. A missing value follows the UI default (on for shared workspaces, off for personal ones), the value is trimmed and case-insensitive, and an unreadable toggle fails closed. The Teach and Learn to-do lists (teach/todo, tulearn/todo) read the same toggle through @tuturuuu/education-core/todo/tutoring-module: with kind=tutoring they return an empty list while the module is off, so session content is not served there either. Coverage: module-gate.test.ts, module-gate-routes.test.ts (which also asserts every tutoring route handler goes through resolveTutoringRouteAccess), and todo/service.test.ts. In the UI, a disabled workspace renders an enable screen rather than a 404. Members with manage_workspace_settings get an Enable tutoring button that writes ENABLE_TUTORING=true through PUT /api/v1/workspaces/{wsId}/settings/ENABLE_TUTORING; everyone else is told to ask an admin. Reading the toggle only needs view_user_groups. Tutoring shares this gate with the other Contacts modules — see Contacts module availability for the full set of toggles and states.
The page previously called notFound() for personal workspaces, so the sidebar link 404’d even though the tutoring APIs normalize personal into a real workspace id. Personal workspaces now opt in explicitly instead.

Permissions

  • view_user_groups — open tutoring and read sessions, the queue, and exports.
  • update_user_groups_scores — schedule, edit, and delete eligible sessions, mark attendance, and generate parent messages.
  • manage_workspace_settings — enable or disable the module and edit tutoring rules.
Three non-404 states replace the old blanket 404 so an operator can tell the cases apart:

Scheduling rules

One create request can carry up to 50 slots. Overlaps are rejected twice: in the form (the offending rows are highlighted before submit) and again in POST /api/v1/workspaces/{wsId}/tutoring/sessions against both the other incoming slots and the sessions already stored. A teacher conflict needs the same teacher on both slots; a learner conflict needs only the same learner. The class managers are displayed as Homeroom teacher for context. The Tutoring teacher is chosen separately for every slot from a paginated, searchable catalog of verified teacher memberships in the same center (workspace), restricted to configured tutor groups by default when present. Changing the learner’s class does not erase a selected tutoring teacher. Students and people without a teacher role are not teacher options; the create and edit APIs enforce the same workspace eligibility boundary. See teacher assignment for the API boundary. For an absence, staff enter the missed class date and select Suggest all sessions. The form scans the selected group’s upcoming scheduled classes and proposes one slot for each missing session. This naturally handles a Monday-to-Wednesday, Saturday-to-Sunday, or Sunday-to-Saturday pattern. For weak-support feedback, the English center preset proposes one 45-minute session before the next class (Sessions for weak support defaults to 1). A higher count places that many consecutive sessions before one class. The template’s Follow up after (days) (Nhắc lại sau) defaults to 3; the standard preset keeps 7. A saved English center template that still holds the earlier defaults (2 sessions, 7 days) reads each as the new default (1 session, 3 days). Values staff edited in Timing and follow-up are kept: that edit saves the policy as custom. Scheduling from the support queue loads these suggestions before opening the form. Staff still review the teacher, date, and time before creating any session. If too few scheduled classes are available, the found slots are applied, the remaining slots stay blank for manual scheduling, and the form reports how many were filled. When the group calendar has upcoming classes but none match a shift rule, the form says so instead of reporting an empty calendar.

Shift rules and group shifts

Each workspace configures its own shift rules under Settings → Special class times: a class window (start, optional end) and class days, the tutoring start time, tutoring days, and length (45 minutes by default). Tutoring days may be a subset of class days. Rules without an assignment match a class by weekday and exact local start time. Settings → Group shifts assigns a class group to a named shift. An assigned group uses that shift’s tutoring time and tutoring days for every class on its calendar, whatever clock time the calendar stores. This covers class dates imported from the legacy session list, which were stored at a 07:00 Asia/Ho_Chi_Minh placeholder that matches no shift. When an assigned group has no scheduled classes in the look-ahead window, suggestions use the shift’s days in the workspace default time zone (Asia/Ho_Chi_Minh). These implied classes are never stored, and staff still review every slot. Assignments to a renamed or deleted shift match nothing. They do not invalidate the policy. Applying a preset keeps campus and group shift assignments. The standard preset places a 45-minute session immediately before class. The learning-centre preset includes the eight named weekday and weekend shifts from the center’s schedule. The Monday/Wednesday/Friday 18:00 class uses Wednesday and Friday 17:15–18:00 only: Monday is skipped, even when it is the next scheduled class. The Tuesday/Thursday class uses 17:15–18:00. The weekend 08:00–09:30 class uses 09:30–10:30 after class, an intentional 60-minute exception to the usual 45 minutes. The weekend 19:00 class (Shift 8) uses 18:15–19:00. Other weekend shifts keep the table below. An untouched saved seven-shift preset gains Shift 8 when read. Untouched older learning-centre preset shift rules adopt these corrections when read; staff-edited rules and the standard/custom policies keep their saved behavior, including generic before-class fallback. The canonical learning-centre preset never falls back to an unlisted class day or time. The preset is a template: applying it fills these rules into the workspace’s own policy, which the owner can then edit. It contains no learner or group data. Untouched saved preset rules gain the display-only class window and class days when read. Regression coverage: tutoring-policy.test.ts, tutoring-suggestion.test.ts, tutoring-shift-assignment.test.ts, the Contacts tutoring-suggestion-apply.test.ts (partial and unmatched results), and the Contacts tutoring-policy-card.test.tsx, tutoring-teacher-picker.test.tsx, and tutoring-create-card.test.tsx mounted section/teacher controls. tutoring-policy-save.test.tsx covers refreshed-section isolation and pending/failed saves. The schedule displays a matching shift name alongside the actual date and time. Staff can rename, add, or change each rule. Suggestions need an existing group schedule; they never create sessions or send parent messages automatically. The parent message is a draft that staff copy after reviewing it. Campus labels are configured per class group; a clear CS1, CS2, Cơ sở 1, or Cơ sở 2 marker in the group name is inferred when no override exists. The existing generic Lớp học group tag does not identify a campus. Ambiguous groups show no campus on the schedule and Chưa xác định in the parent draft until staff set an override. The learning-centre template uses the resolved label in the parent draft. Each workspace keeps its own campus list (campusOptions in the same TUTORING_POLICY config, default empty). Labels are trimmed, blank entries are dropped, duplicates are removed, and a label longer than 80 characters fails validation. Policies saved before the list existed read as an empty list with every other field unchanged, and saving the Campuses section keeps all other policy fields. The class-to-campus editor offers the list plus any label already mapped to a class, so earlier free-text mappings stay selectable and are never dropped; staff can still type a new label. Topic announcements offer the same choices as a Place picker (see User Management). No campus names are built in or seeded; each center enters its own. Coverage: tutoring-campus-options.test.ts, the policy route.test.ts, and tutoring-policy-save.test.tsx. Payroll exports count completed teaching time. When scheduling from Needs support, the draft’s content follows the content-to-teach rule. Staff can review and edit any draft before saving; content is never invented from a class title or an unrelated lesson.

Content to teach follows the reason

Decision (applies to every row of Needs support in Contacts → Tutoring; always on, no setting):
  • Kèm nghỉ (absent make-up) teaches what the class covered on the day the learner was absent: the class session’s notes for that date, then the class’s posts (bài viết) created that day. When both exist the draft labels them “Lesson notes” and “Class posts”. Posts have no date field of their own, so a post belongs to the missed date it was created on, in the class’s time zone (the class session’s own zone, falling back to Asia/Ho_Chi_Minh when the group has no session in range). Rejected posts are skipped, and only the post’s title and content are read, not its internal notes. Post text is included only for viewers who may read group posts (view_user_groups_posts).
  • Kèm yếu (weak support) teaches what the homeroom teacher (GVCN) wrote when moving the learner into support: the flagged feedback a support session was first opened from. Later flagged notes do not replace it; with no session yet tied to a flagged note, the latest one is used. Scheduling and reassessment still follow the latest flagged feedback, so queue membership is unchanged.
  • Both reasons put both texts in one draft under the headings “Kèm nghỉ” and “Kèm yếu” (English: “Absent make-up” and “Weak support”), so the homeroom teacher’s note is never dropped.
  • The queue table shows the same content per row. The server derives the notes for the visible page in the queue response (missed_lesson_content, missed_post_content, their per-date splits missed_lesson_by_date and missed_post_by_date, missing_lesson_dates, content_feedback_id), so the list does not fetch per row.
  • A missed date with neither session notes nor a post shows the inline hint “No lesson notes recorded for ” in the queue and the draft, instead of an empty field.
  • A make-up draft that is only session notes still follows the class notes while pending (linked content). A draft that includes a post, or a homeroom note, is saved as written.
Existing sessions are not rewritten; only new drafts use this rule.

Each created session has its own content

Decision (Contacts → Tutoring create form, POST .../tutoring/sessions; always on, no setting):
  • With more than one session the create form shows a Content field inside every session card. With one session it keeps the single Content field.
  • A learner who missed several classes gets one session per missed date, and session i drafts missed date i (oldest first): that day’s class notes and posts, in the same YYYY-MM-DD: ... form as before. Two missed dates and two sessions give each session its own date.
  • Kèm yếu repeats the homeroom teacher’s note in every session. A row with both reasons pairs each session’s own missed-day text with that note, under the same two headings.
  • A session beyond the missed dates drafts no class notes. Content stays editable per session; a new weekly or blank slot starts with the form-level content, never a copy of the previous session’s text.
  • The API accepts an optional content on each sessions[] entry (same 10,000-character limit) and falls back to the payload content when a slot omits it, so existing callers are unchanged. An explicit empty string is kept, so a blank make-up session still follows its class’s notes (linked content) per row. The form saves untouched notes empty only while a slot still follows the missed date it was drafted for. The server gives each blank session, in date and time order, the oldest uncovered absence on or before its date, and skips a session dated before that absence. The form runs the same rule and saves a slot empty only when it would receive the date it shows; slots that share a date and time, or that a removed, reordered or early slot would shift, save the text as shown. Pending reservations already on the student can shift the pairing too; the guard covers it as far as the form can know.

Parent message fields

The parent message is a per-workspace template. Besides student, reason, date, time, duration, group, teacher and campus, it supports: Parents often assume a learner attends only the tutoring slot and goes home, so the learning-centre default template also states the official class time:
That is the code default only. A workspace that already saved a template keeps it until staff edit it in the policy card, which lists the available fields. The preview route (message-preview) computes the fields when it renders and stores the draft. Regression coverage: tutoring-message-values.test.ts (time range, weekdays, same-day, next and no class time, time zones), tutoring-policy.test.ts (renderer), message-preview/route.test.ts (class session filters, error fallback, template values), session-create-helpers.test.ts (per-slot content and fallback), tutoring-content.test.ts (per-session split), use-tutoring-create.test.ts (stored sessions), queue/route.test.ts (absent with and without notes, posts by date and permission, both reasons, triggering versus latest feedback), tutoring-queue-content.test.tsx and the prefill cases in tutoring-handoff.test.tsx.

Weak-support content comes from the homeroom teacher

Decision (applies to WEAK_SUPPORT tutoring in Contacts; the restriction is off by default):
  • The text the homeroom teacher (GVCN) enters when flagging feedback as Requires Attention is the learner’s tutoring content (Nội dung kèm). The feedback dialogs say so while the flag is on. The support queue labels the column Tutoring content and prefills it into weak-support drafts.
  • Only class managers set tutoring content is an optional policy switch (restrictWeakContentEditors, default off, in the weak-support section of Settings). When on, creating, editing or deleting flagged feedback, or ending weak support, also needs the existing update_user_groups class-management permission, on top of the usual update_user_groups_scores. Unflagged feedback is unaffected. No role is added. Groups’ homeroom teachers are expected to hold that permission through their workspace role. The check runs on the server for every feedback write path: the Contacts feedback API (apps/contacts/src/lib/user-feedbacks.ts, used by both its workspace and group-member feedback routes) and the web feedback and tutoring routes.
  • Sessions are weak-support content too. A tutoring session counts as weak content when its reasonType is WEAK_SUPPORT or it has a sourceFeedbackId (it came from a flagged feedback). With the policy on, POST /tutoring/sessions for such a session, PUT /tutoring/sessions/{id} that changes its content, reasonDetail or reasonType (or turns a session into weak support), and DELETE /tutoring/sessions/{id} also need update_user_groups and otherwise answer 403 with TUTORING_CONTENT_RESTRICTED. The Contacts UI shows a specific “only class managers can change weak-support content” message for that code instead of the generic failure toast. A content edit is applied only while the session still has the reason and source feedback the check read; if they changed in between, the write answers 409. A queue row that has both an absence and flagged feedback creates an ABSENT_RECOVERY session with a sourceFeedbackId. Because of that sourceFeedbackId it counts as weak content and is restricted like a WEAK_SUPPORT session. Plain ABSENT_RECOVERY content (no sourceFeedbackId), and attendance or schedule changes on weak-support sessions, are unaffected.
  • End tutoring (Thoát kèm) is an explicit queue action for weak-support and office-review rows, confirmed in an in-app dialog. It calls POST /api/v1/workspaces/{wsId}/tutoring/weak-support/end, which clears the attention flag on that learner’s feedback for that class. The feedback text stays as history, and sessions already scheduled remain for staff to complete or cancel. Flagging the learner again puts them back on the list.
Group-member feedback uses the authorized workspace for both the learner and class. Teachers retain feedback history after a learner leaves the class; current class membership is not required. This matches Contacts. The usual view/edit permissions and weak-content policy still apply. The web group-member feedback route.test.ts covers scoping, former-member history and weak-content denial. Regression coverage: weak-content-access.test.ts, sessions/weak-content.test.ts, weak-support/end/route.test.ts, the Contacts route cases in users/feedbacks/route.test.ts (Contacts), the weak-support policy cases in users/feedbacks/route.test.ts, and tutoring-policy.test.ts.

Make-up content follows the missed lesson’s notes

Decision (applies to ABSENT_RECOVERY sessions in Contacts → Tutoring; default on, no setting):
  • While a make-up session is pending, its content follows the lesson notes recorded for the missed class session. Notes a teacher adds or edits after scheduling appear in the schedule automatically. The schedule marks such sessions with “Follows the missed lesson notes”.
  • When the session is marked done (row action or session edit), the notes as they stand are stored on the session and are frozen. Later edits to the class notes no longer change it.
  • A tutor’s manual edit of the content stores their own text and stops the updates for that session; a completion never overwrites it. Clearing the content of a pending session links it to the notes again.
  • No-show and cancelled sessions keep whatever content they have.
  • Which missed class: each make-up session follows exactly one missed class. Within a learner’s class, absences in the last 90 days (on or after the count-from date, when set; the queue lookback does not apply) and that learner’s pending or done make-up sessions are paired in date order. The oldest absence not yet covered goes to the earliest session dated on or after it. Sessions dated before every open absence follow no class and show no notes. Deleting or rescheduling a session, or editing attendance, can re-pair later pending sessions; completed sessions keep their stored notes.
  • Content narrows to one date: the scheduling draft lists notes for every missed date in the queue row (YYYY-MM-DD: notes, one line each). Once the session is saved linked, it shows only its own paired date’s notes, so a learner with two absences sees one date on each of their two sessions.
  • Completion stays fast: storing the notes waits at most three seconds. If the lookup fails or times out, the session is still completed. The response carries warning: "LINKED_CONTENT_NOT_STORED", and the schedule shows a non-blocking warning so staff can check the content. A slow write may still land after the timeout, but only while the content is empty.
Implementation: no schema change. A linked session is one whose stored content is blank (empty or whitespace only), so the create form saves an unchanged drafted note as empty. The sessions list derives the content at read time, pairing each session with its missed class through the queue’s legacy absence credit matching, and reads that class session’s notes. Completion writes the notes only while the stored content is still the blank value it read (a compare-and-set, so a concurrent staff edit wins). Completing through the session edit with no content, or with blank content, still stores the notes; only real text sent with the completion counts as a manual edit. If the lookup fails, the list shows the stored content and completion still succeeds. Regression coverage: linked-content.test.ts (notes filled after scheduling, frozen after completion, manual edit kept, lookup failure, whitespace-only content, bounded wait, pairing order), sessions/[id]/route.test.ts (completion with absent, empty or blank content, and the completion warning) and use-tutoring-create.test.ts.

Homeroom teachers hear when tutoring is completed

Decision (applies to every tutoring reason; always on, no setting):
  • When a tutoring session is marked done (row action or session edit), the class’s homeroom teachers (GVCN) get an in-app notification. These are group members with role TEACHER whose workspace user is linked to a platform account. Teachers without a linked account are skipped. The person who completed the session is not notified of their own action.
  • The notice is sent after the completion is saved and never blocks or fails it. Errors are logged, and a notice slower than three seconds is abandoned.
  • At most one notice per session and recipient. Retries, and re-completing a session after reopening it, do not send another.
  • It uses the existing create_notification path with type system_announcement, code tutoring_session_completed and entity tutoring_session, so recipients’ notification preferences for system announcements apply. Apps render the code in the viewer’s language; the stored English text names the learner, class and date.
Limitation: without a receipts table, de-duplication checks for an existing notification before sending. Two completions of the same session at the same instant can both send. A unique receipt (the planned tutoring notification migration) would make it exact. Regression coverage: completion-notification.test.ts and sessions/[id]/mark/route.test.ts. Policies are validated at GET/PUT /api/v1/workspaces/{wsId}/tutoring/policy and stored under TUTORING_POLICY with bounded TUTORING_POLICY_PART_* rows in workspace_configs. The table enforces a 1,000-character limit per value, so the policy API writes all chunks in one upsert and readers reconstruct the validated policy. Unset or malformed values safely use the standard preset. Existing workspaces need no migration.

Follow-up notifications

Status: database foundation only. No job, route, or screen sends these yet; the completion notice and the daily content check ship in later changes. These rules are configurable and apply to any workspace that enables them.
  • Recipients. A class’s homeroom teachers (GVCN) are its workspace_user_groups_users members with role TEACHER; every one of them is notified, never just one. Each is reached through its workspace_user_linked_users account. A teacher without a linked account is skipped and reported, not replaced by someone else.
  • Office. The office is every workspace member who holds admin (administrators, including the creator) or approve_reports (supervisors), checked with has_workspace_permission. No office role, recipient list, or column exists; grant or revoke those permissions to change who is notified.
  • Weak-support content alert. After the configured review period (default 14 days) with no homeroom-teacher action, all homeroom teachers of the class and the office are notified together, in one step. There is no separate reminder or later escalation. Each unchanged period alerts each recipient once.
  • Review clock. Any homeroom-teacher action resets the clock: keeping the content, changing it, or completing/exiting support (thoát kèm). A change is a new require_attention feedback row; exiting clears require_attention, which ends the clock. Keeping content writes private.tutoring_weak_support_reviews.last_reviewed_at. The clock starts at the later of that value and the latest require_attention feedback for the student in the class.
  • Completion notice. When the tutor marks a session done (Hoàn thành), every homeroom teacher of the class is notified once per session. They then update the content or exit support, and that action resets the review clock.
  • Tutor comment. Sessions have an optional tutor_comment (up to 2,000 characters, stored as null when empty) that the completion notice shows.
  • Channels. Notifications are in-app and email, created with create_notification using the types tutoring_weak_content_review_due and tutoring_session_completed. Email uses the existing notification mail path and recipients’ notification preferences; there is no new provider.
  • Idempotency. private.tutoring_notification_receipts records one row per recipient and alert cycle or session, claimed before notifying. Reruns, repeated marks, and deleted notifications never send twice; delivery is at most once per recipient. Both private tables are service-role only, with RLS enabled and no client policies.
  • Residual risk (accepted for v1). user_feedbacks is writable by any workspace member over the Data API. A member who adds a new require_attention feedback for the student restarts the clock and so postpones the office alert by up to one review period. Each postponement leaves a visible feedback row, and the alert fires one period after the last one, so it cannot be suppressed without repeated inserts. Only the service role can write last_reviewed_at.
Regression coverage: apps/database/supabase/tests/tutoring-follow-up-notification-foundation.sql. Rollback: apps/database/rollbacks/20261026191000_tutoring_follow_up_notification_foundation.rollback.sql.

Absence follow-up and automation settings

Status: database foundation only, off for every workspace. No job, route, or screen uses it yet; the scheduled follow-up, the settings card, and the archived-absences view ship in later changes. These rules are configurable and apply to any workspace that enables them.
  • Off by default. private.tutoring_automation_settings holds one row per workspace. A missing row, or a row with the defaults, keeps every rule off. Turning a rule on stamps its enablement time, so absences older than that time minus the absence lookback are never reminded about. The stamp changes only when the rule switches on; it cannot be preset or backdated. Defaults: remind 3 days after the absence, archive 3 days after the reminder, and flag 2 consecutive incomplete lessons (for the later lesson-completion report).
  • One reminder, then archive. An absence with no make-up is reminded about once, ever. If it is still not made up after the archive delay, the scheduled job archives it. The job never archives an absence it has not reminded about.
  • Archive hides the queue row only. It does not archive the learner and never deletes attendance, sessions, or the follow-up. Staff can restore an archived absence. A restored absence is held: the job will not archive it again, but staff can. Staff can also archive an absence manually. The state machine (reminded, archived, restored) is enforced in the database for every writer, and follow-ups cannot be hard-deleted. Reminder, archive and restore times are always the database’s now(); a caller cannot supply or backdate them.
  • Audit. Every effective transition and settings change writes one row to private.tutoring_automation_events, with the staff actor or null for the scheduled job. No-op writes and upserts that change nothing write no event. The settings actor comes from the tutoring_automation.actor_user_id setting, never a stored updated_by. Required for the settings route: all writes go through a service-role-only private.tutoring_automation_settings_save(...) that checks the actor is a member of that workspace and sets the setting with is_local = true; direct table writes are then revoked. Until then, a session-level value could leave a stale or unvalidated actor. The audit is append-only: no role can update or truncate it, and the service role cannot delete it.
  • Actors. Routes take the staff actor from the authenticated session and never pass null for a user request; null is reserved for the scheduled job. A staff actor must be a workspace MEMBER (not a guest) holding update_user_groups_scores.
  • Attendance link. A follow-up may link the attendance row of the same class, learner and date only.
  • Notifications. The types tutoring_absence_makeup_reminder and tutoring_lesson_incomplete_report use the existing create_notification path. private.tutoring_notification_receipts gains the kinds absence_reminder (one per follow-up and recipient) and lesson_report (one per workspace, local date, and recipient), so reruns never notify twice.
  • Access. All three tables are service-role only, with RLS enabled and no client policies. private.tutoring_absence_followup_apply is the single service-role entry point; scheduled actions are refused while the workspace setting is off, and staff actions require current workspace membership.
Delays are settings, and recipients are resolved by the later job. Regression coverage: apps/database/supabase/tests/tutoring-automation-foundation.sql and tutoring-automation-hardening.sql. Rollback: run 20261030051010_tutoring_automation_notifications.rollback.sql, then 20261030051000_tutoring_automation_foundation.rollback.sql, and prove it with apps/database/verification/tutoring-automation-foundation-rollback-roundtrip.sql. The rollback keeps both notification types, because a CHECK constraint is re-checked on every update and removing them would make existing notifications of those types fail mark-read.

Exports

Detailed (per session) and payroll (per teacher, completed sessions and total minutes) exports are available as CSV and XLSX. Exports use the active filters, including the date range, and are generated server-side in pages of 1,000 rows. Both formats require a start and end date in order, at most 366 days inclusive. Today, Tomorrow, Next 7 days, This month and Last month use the preset’s exact calendar bounds for the schedule and export. No manual custom dates are needed for these bounded presets. Upcoming, Past and All remain open-ended and keep the four export formats disabled. Choose date range switches to Custom and fills an editable range: today through 30 days later for Upcoming or All; the previous 30 days through yesterday for Past. Dates follow the viewer’s local calendar, matching the schedule presets. Choosing a range does not download anything or change other filters. Staff can adjust the dates before selecting CSV or XLSX. An invalid or over-limit custom range stays disabled and is not silently replaced. Export permissions and the server’s 366-day cap still apply. Regression coverage: tutoring-filters.test.ts and tutoring-export-range.test.tsx.

Troubleshooting

Confirm the caller resolves a workspace profile at all. A missing workspace_user_linked_users row now renders the Unavailable screen; a still-hard 404 means WorkspaceWrapper could not resolve the workspace itself, which points at the app session rather than at tutoring.

The queue is empty but learners are behind

The queue reads absence deficits and user_feedbacks.require_attention. Check that group attendance is being recorded and that feedback is flagged.

The schedule or queue stays empty after loading

An API failure now shows a retry button instead of an empty table. Check the workspace permission, then retry. If the same tutoring API works on the central web domain but returns 404 Not found through Contacts, check that the central route accepts the verified Contacts app session forwarded by the satellite proxy. Schedule and queue loading show table-shaped placeholders while data is in flight.

A session cannot be created

The create button stays disabled until the group, learner, and every slot (date, time, 1–480 minutes, teacher) are complete and no two slots overlap. It also stays disabled for a class the workspace excludes from tutoring; the form says so. To arrange tutoring there, change the exclusion rules in Settings → weak support. See Where class exclusions apply.

Tutoring teacher assignment

In Contacts, a tutoring teacher is selected separately from the student’s homeroom teacher. By default, both session creation and editing accept any workspace user with an actual TEACHER membership in a group belonging to the same verified workspace. A teacher need not manage the student’s selected class. Student membership in that class, staff management permission, and scheduling conflict checks still apply. Users without a teacher role and teachers belonging only to another workspace remain ineligible. The teacher selector uses the paginated, searchable tutoring teacher catalog, not the general people directory or the currently loaded class managers. Multiple teacher memberships produce one catalog identity. This contract applies to the live Next.js API; the teacher catalog and unported tutoring mutations remain tracked Rust migration backlog, while the existing Rust session-list GET is unchanged. Regression coverage: apps/web/src/lib/tutoring/teachers.test.ts, apps/web/src/lib/tutoring/teacher-assignment-routes.test.ts, and the tutoring teacher catalog’s colocated route.test.ts cover workspace boundaries, teacher eligibility, permission denial, error handling, pagination, and session writes.

Tutor groups

Tutors are usually students outside the class, so they have no title of their own: a tutor is a workspace user with TEACHER membership in a group that staff mark as a tutor group.
  • Scope and default. The tutorGroupIds list in the tutoring policy (Contacts, Tutoring policy, Tutor groups) is workspace-wide and defaults to empty. Policies saved before the setting existed read as no tutor groups, and every policy field round-trips on save. Presets keep the chosen groups.
  • Roles combine. The teacher catalog returns isTutor (TEACHER in any tutor group) and isClassTeacher (TEACHER in any other group). Both can be true, so a homeroom lecturer who also tutors keeps both. No role or permission is added and tutor-group teachers stay valid tutoring teachers.
  • Picker. The tutoring teacher picker shows Tutor and Teacher labels beside the name, both when both apply, and a Tutors only toggle that starts on and sends tutorsOnly=true. Switching it off explicitly sends tutorsOnly=false to show all workspace teachers. The plan always requests tutorsOnly=false so existing main-teacher sessions retain their names. When an API request omits the flag, configured tutor groups now restrict the server catalog to their TEACHER members. Main teachers outside those groups are excluded. With no configured groups, the default remains the workspace teacher catalog. An explicit tutorsOnly=false API request retains the broader catalog. Policy read failures fail closed for default and tutors-only requests; assignment permissions are unchanged. The teacher catalog route regression covers configured tutor A and main teacher B. Group names are not used for matching.
  • Queues. Tutor groups have no real students, so they are excluded from the make-up and weak-support queues by group id, in addition to the name-based exclusion rules.
  • Setup is configuration. Staff create a group such as “Giáo viên kèm”, add each tutor as TEACHER, and select it in the policy. Nothing is seeded.
Regression coverage: tutoring-policy.test.ts (parser, round trip, exclusion by id), the policy, queue and teacher catalog route.test.ts files, teachers.test.ts (tutor-only, class-only, both), and the Contacts tutoring-teacher-picker.test.tsx and tutoring-tutor-groups.test.tsx.

Queue handoff and missed-date defaults

In Contacts, scheduling an absence-recovery queue row selects the oldest supplied outstanding missed-class date in the editable form. This is a suggestion anchor, not a persisted link between an absence and a make-up session. Staff can change it; custom tutoring policy and sequential slot suggestions remain unchanged. Manual creation still starts with no missed date. Changing the learner or group clears that date so another learner’s absence is not carried into the new draft. A queue lookup belongs to its committed actor/workspace and current draft interaction. A newer queue selection, form edit, dialog open/close, scope change, or unmount invalidates the older handoff. Late results cannot overwrite a newer draft or reopen a closed dialog. Failed schedule reads retain the existing editable fallback; they do not create sessions automatically. Regression coverage: tutoring-handoff.test.tsx mounts the actual Contacts client and create card with a real QueryClient and synthetic transport responses. Its table/dialog presentation harness is bounded component evidence, not customer roster, production provider, or end-to-end dialog proof.

Archive intent when editing students

Contacts student edits preserve the stored archived intent when an existing archive-until date is loaded. An unrelated field edit or repeated open/save must not archive an explicitly active student. Selecting a temporary archive date explicitly still marks the student archived; clearing the date and switching to active retains the existing server contract that clears the archive-until value. This changes neither the temporary archive date policy nor enrollment history, and does not repair earlier customer records. Regression coverage exercises the actual student form, calendar, switch and mutation transport in form-archive.test.tsx.

Legacy absence credit matching

The support queue matches eligible absence dates and DONE/PENDING absent-recovery session dates chronologically within the configured lookback, independently for each group/student. A reservation consumes at most one absence on or before its session date; earlier make-ups cannot consume later absences. Remaining dates are returned with the same deficit and drive the make-up handoff. This is a fallback for records without a persisted source-attendance link. It does not prove which historical absence staff intended to cover, repair prior records, or alter custom eligibility/exclusion policy. Explicit attendance-row linkage remains separate work, including multiple sessions on the same date. Web queue regressions and the Rust queue parity tests cover the chronological boundary, ordering, same-day multiplicity and group/student isolation.

Staff-reviewed draft planning

Contacts offers compact per-session date/time and eligible teacher choices alongside the existing manual editor. Choices use the workspace policy, scheduled group classes, and a complete bounded read of workspace teacher memberships and tutoring sessions within the policy horizon (including the prior date for overnight conflicts). Date/time ranking is chronological; teacher ties are stable by ID. Staff explicitly select a teacher to apply a choice. Nothing is created until the existing Create action. The planner never fills an unsupported time with an invented 18:00 fallback. Each teacher/session catalog is capped at 20 pages of 100 records. Errors, inconsistent counts, duplicate or truncated pages prevent suggestions and expose Retry. Missing teachers and schedules have distinct feedback. Configured but unmaterialized class occurrences are shown as a schedule-review exception, not confirmed classes. The displayed horizon follows the configured policy rather than a fixed four weeks. An empty window is complete: the sessions API reports totalPages: 1 for zero rows, and the reader accepts either zero or one page for an empty catalog. Before this was accepted, a workspace with no tutoring sessions in the horizon always showed the incomplete-data retry state. Choices exclude recorded learner/teacher tutoring conflicts and other slots in the current draft, with half-open intervals and overnight overlap. Cancellation records are conservatively included to match the existing creation conflict check. These are no recorded tutoring conflict choices, not confirmed teacher availability: other classes, rooms, capacity and contractual availability are not modeled. Reads are not an atomic reservation. The server rechecks at Create, but concurrent creation remains a separate unresolved frontier. Existing custom policy, consent, staff edits and actor/workspace lifetimes remain authoritative. A late read never applies choices. Regression coverage: tutoring-draft-plan.test.ts, tutoring-plan-data.test.ts, tutoring-draft-choices.test.tsx, and the actual queue handoff regression. Source tests are not customer runtime or production-data repair evidence. Original absence linkage and automatic planning/teacher notices remain outside this packet. The next teacher-hours foundation is intended to support staff-defined defaults and explicit per-teacher overrides, with the teacher override taking precedence. Those hours are not yet implemented or consulted by this first draft packet; absence of a recorded tutoring conflict must never be treated as availability consent.

Teacher-hours domain contract

The pure @tuturuuu/utils/tutoring-teacher-hours model defines staff defaults and per-teacher weekday overrides; it does not yet read or write hours, change Contacts UI, constrain Create, or send notices. Existing custom tutoring policy and staff confirmation remain unchanged. Calendar’s automatically created 07:00–23:00 defaults are not teacher-hours authority. An absent staff weekday is unknown; an explicit empty array is closed. An absent override weekday inherits the current default. Custom teacher windows replace that weekday, rather than widening it by union. Override reset retains an empty, revisioned row; future storage must atomically reject stale revisions, including absent→create→reset races. The model preserves opaque revision strings without numeric/date conversion and rejects unchanged write receipts, but does not itself prove database CAS, role admission or same-content revision advancement. Hours require an explicitly confirmed IANA timezone. Overrides cannot establish availability without that staff frame. Windows are sorted, disjoint, half-open civil times; midnight endings use 24:00. Overnight windows must be explicitly split across weekdays. Candidate inputs are in the confirmed staff frame, never silently in the browser/class timezone. Gap/fold endpoints and slots crossing DST transitions are conservatively rejected rather than assigned an offset. Unknown coverage stays unknown; any known closed portion denies coverage. Regression coverage in tutoring-teacher-hours.test.ts keeps unconfirmed teacher hours unknown and exercises Temporal compatible gap conversion as an unsuitable input, inheritance/replacement, lossless reset receipts, adjacency, midnight, weekly wrapping and DST. The actual Calendar default factory is tested separately in Calendar’s hour-settings-shared.test.ts; utils tests stay within their package source boundary. This is pure source evidence, not persisted availability or production scheduling proof. API/schema/authenticated editor, atomic revision storage, staff-default/teacher-role permissions, outside-hours exceptions and planner consumption remain separate reviewed packets.

Private teacher-hours storage foundation

The additive storage foundation keeps confirmed staff defaults and teacher weekday overrides in private tables behind service-only, scoped RPCs. It remains inert: no current API, settings UI or Create action consumes these tables. Reads never initialize defaults. Account actors require explicit workspace MEMBER status plus view_user_groups for reads or manage_workspace_settings for writes; teacher IDs are separate workspace-user identities. Current same-workspace TEACHER membership is checked and locked for override writes. This proves current admission, not a historical role remove/readd epoch. All writes lock the workspace hours anchor, default and override in that order. Default and override revisions are positive bigint values exposed only as full-precision decimal text. Absent creation requires a null revision; updates, same-content saves and resets advance the revision. Override writes also compare the captured default revision. Reset stores a revisioned empty override instead of deleting it, so old absent/create or pre-reset drafts cannot silently revive. Unknown, explicitly closed and inherited weekdays retain the pure-model contract. The SQL window validator also rejects extra untyped interval properties. Revision-only audit receipts use canonical audit.to_record_id table/key identity and explicit account actor, without copying hours content. Audit insertion and hours mutation share one transaction; an audit failure rolls the write back. A transport timeout is still an unknown receipt, not proof of rollback: future clients must refetch and review rather than blindly replay a stale revision. No cross-request idempotency or automatic provider operation is promised. tutoring-teacher-hours-contract.yaml applies the complete schema in an owned CI disposable database, runs strict pgTAP and actual two-connection create, default-change and save/reset races, then generates an exact-schema type artifact. Node wiring tests and pure model tests are source checks; only successful exact CI supplies database evidence. The foundation requires that proof before merge. Outside-hours exceptions, API/Rust migration tracking, authenticated editing, teacher-hour consumer integration and atomic tutoring reservations remain separate reviewed work. Existing tutoring policy, workspace timezone and staff Create permissions are unchanged.

Selected-absence identity foundation (unwired)

The additive foundation is service-only and has no Contacts/API activation. Existing historical sessions remain unlinked and use the chronological fallback above; no migration guesses which absence an old make-up covered. The selected date in the current form is still suggestion context, not proof of saved attribution. The new contract identifies an absence by its attendance UUID, including separate class occurrences on the same date. Each linked make-up slot requires a distinct eligible source UUID. PENDING reserves one source; DONE permanently credits it. Cancel, no-show, or a pending reason change releases the reservation while retaining its original identity and history. Reactivation uses revision CAS and must reclaim the same eligible source; another reservation causes a conflict. Allowed deletion retains attribution; DONE credit cannot be released by deletion or a reason/status edit. Ordinary content and parent-message metadata edits preserve credit identity. Linked date/time/duration/teacher and creation actor/timestamp rewrites require an exact canonical permit. Direct schedule edits are rejected until a future validated PATCH operation exists, including moving a make-up before its source absence. No client is wired to these operations in this foundation packet. Correcting active source attendance to PRESENT requires an explicit staff-managed resolution. Silent correction or standalone deletion is rejected. A credited source keeps its history after explicit resolution. Existing workspace/group/student or membership teardown uses narrowly scoped FK cleanup; immutable original IDs/date remain available for retained records. Deleting an actual class occurrence releases pending reservations while preserving DONE credit and immutable occurrence snapshots. Declared teacher/creator SET NULL and parent rekey cascades may change only their live FK fields after the old parent disappears; arbitrary direct rewrites stay denied. Tenant-authorized release is possible after learner archive or enrollment departure; new reservations still require an active enrolled learner. Input-bound replay returns its original receipt before mutable learner/source checks, but only after rechecking the current actor’s permission. Revoked actors cannot replay. No generic trigger-depth or caller-writable session flag authorizes a protected write. Only a verified backend actor may call the canonical service-only operations, which also check current MEMBER membership and the existing tutoring permission. Private, ungranted permits exist only during an exact transaction/session/revision/mutation; success removes them and failure rolls them back. Linked status/reason/delete writes outside that boundary are rejected. Full historical schema replay, strict pgTAP, two-connection claim-versus-correction/replay races, and generated types must pass on the exact head before foundation merge. Fixtures and source checks are not live customer proof. Queue/API/UI integration and selected-card-to-transport regression are separate dependent packets; historical customer data is not repaired here.

Create completion ownership

Contacts captures the exact actor/workspace lifetime and draft revision before a make-up create request. Only that still-current intent may close its draft, announce success/failure, or invalidate its scoped queries. Replacing the draft or leaving and returning to an actor/workspace permanently invalidates old completion effects. A new scope remains usable while an old admitted write is pending. This does not cancel or undo a server write: current-scope success and failure remain visible, and synchronous duplicate submission is suppressed. The mounted Client/CreateCard regressions in tutoring-create-scope.test.tsx cover these boundaries with held synthetic transports; they are not customer or production-write evidence. The inert absence identity contract checks rejected linked-session mutations against the canonical-operation error and preserved schedule and attribution. Trigger permit lookups use distinct local variable names and qualified columns to avoid ambiguous SQL references before admission. Regression evidence lives in apps/database/supabase/tests/tutoring-absence-credit-contract.sql and apps/database/supabase/tests/tutoring-absence-credit-lifecycle.sql; the exact-head database contract must pass before this foundation is considered verified.

Shared tutoring slots

One teacher tutors many learners in the same session. Every workspace allows any number of learners with one teacher at the same date, start time and duration by default, whether the learners come from the same class group or from different ones. Each learner keeps a separate session row for attendance, absence recovery, lesson notes and payroll history; there is no shared-session identifier or capacity limit. Staff schedule each learner through the Contacts schedule or support queue. The create and edit APIs and draft teacher choices apply this same rule. Booking the teacher for an overlapping interval with a different start or duration still blocks the teacher. A learner cannot have overlapping bookings, including a second booking in the same slot under any group. Slots match by date, start minute and duration; seconds in a start time are ignored by both the APIs and draft teacher choices. Payroll exports count a shared slot once for its teacher: completed sessions with the same teacher, date, start minute and duration add one session and one duration, however many learners attended. For every workspace, teacher payroll công defaults to teaching time divided by 45 minutes: 45 minutes is 1 công and 90 minutes is 2 công. The active Web payroll API returns total_cong; Contacts payroll CSV and XLSX include TotalCong. Fractional công are retained without rounding, matching the existing exact-minute aggregation. Detailed learner exports and attendance remain per learner. This conversion does not calculate currency or alter pay rates. Regression coverage: payroll route tests. Rows without a teacher are counted individually. Export filters apply before this count, so a slot shared across groups appears once in each group’s payroll export, and per-group exports can add up to more than the unfiltered total. Re-exporting a past period that has shared slots gives lower totals than before this rule. The Rust export route keeps the earlier per-row count until it is ported. Existing cancellation conflict handling remains conservative. The rule is enforced in application conflict checks only; the database has no per-teacher uniqueness or exclusion constraint on tutoring sessions. It does not imply room or contractual availability. Regression coverage lives in tutoring shared.test.ts, apps/web/src/lib/tutoring/teacher-assignment-routes.test.ts, packages/internal-api/src/tutoring-draft-plan.test.ts, export/route.payroll.test.ts and the Contacts use-tutoring-create.test.ts.

Teacher công report

Contacts tutoring includes a teacher công tab with a calendar-month default, previous-month and week presets, and inclusive custom dates. Schedule filters also accept previous month and custom dates. The report and payroll downloads share calculateTutoringPayroll in internal-api. Only DONE sessions pay; 45 minutes equals one công, retaining fractions. The existing teacher/date/start minute/duration key remains unchanged: overlapping starts or different durations remain distinct, and unassigned rows remain independent. No-show and cancelled sessions pay zero. Past PENDING learner sessions are shown without pay. All-teacher payroll reports and downloads require view_payroll (including its existing admin implication). A member with only view_user_groups can read only their linked teacher row, enforced before session loading. Missing links deny access. Detailed session exports, session lists, and teacher picker lists also require view_payroll for all-teacher scope; holders of only view_user_groups receive their linked self scope. This intentionally tightens the previous staff-wide access. Every export mode and report requires both dates, with an inclusive span of at most 366 days. Open-ended schedule presets must be changed to a bounded range before export. Numbers display two decimals; spreadsheet totals retain full precision. Regression coverage: export route.payroll.test.ts, route.access.test.ts, the tutoring read-scope.routes.test.ts permission matrix, and Contacts tutoring-filters.test.ts. Parent-message previews retain the editor permission and also apply the same teacher read scope to both the session read and preview save. Editors without view_payroll can preview only their linked teacher sessions; missing links and other-teacher session IDs are denied. A concurrent reassignment cannot return a preview after a scoped save no longer matches. Regression coverage is the message-preview route test suite.

Parent message v2

The workspace config tutoring_parent_message_v2 defaults to OFF; only the string true enables it. Set it to false or remove it to restore the existing template (kill switch). Contacts parent-message previews use the optional tutoring_parent_message_centre_name workspace config as the centre, falling back to the workspace name when the override is absent or blank. Centre names are trimmed and NFC-normalized. No migration is required. The requested Vietnamese closing applies with v2 on. The official-class line appears only for a scheduled class on the tutoring day. If neither centre source is available, the entire existing template and class fallback remain unchanged, even with the flag on. With the flag off, custom templates and existing output bytes are preserved. Regression coverage: the message-preview route tests and packages/utils/src/tutoring-message-values.test.ts.