From f1ce562229be0544139174f62ba2b00692d5f1e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 7 Jul 2026 07:27:17 +0000 Subject: [PATCH 1/3] Add lesson schedule Excel upload with Yemot auto-detect Admins can upload a daily teacher lesson-schedule Excel file into a new LessonSchedule entity (natural-key resolved against Klass/Lesson/Teacher, same pattern as Lesson/AttReport). Re-uploading a date replaces its rows. The seminar attendance Yemot call flow now looks up the calling teacher's current lesson from that schedule (nearest start time to now) instead of always asking for a klass number by keypad, and records the resolved lesson on the saved AttReport rows. Falls back to the existing manual klass-entry flow when no schedule match is found. The new resource is gated behind a new lessonSchedule app permission. --- client/src/App.jsx | 11 ++ .../components/LessonScheduleImportButton.jsx | 91 ++++++++++ client/src/domainTranslations.js | 16 ++ client/src/entities/lesson-schedule.jsx | 123 +++++++++++++ client/src/roadmapFeatures.js | 1 + client/src/utils/appPermissions.js | 5 + .../src/db/entities/LessonSchedule.entity.ts | 171 ++++++++++++++++++ server/src/entities.module.ts | 3 + .../entity-modules/lesson-schedule.config.ts | 40 ++++ .../1783407769935-AddLessonSchedule.ts | 43 +++++ server/src/yemot-handler.service.test.ts | 72 ++++++++ server/src/yemot-handler.service.ts | 53 +++++- 12 files changed, 627 insertions(+), 2 deletions(-) create mode 100644 client/src/components/LessonScheduleImportButton.jsx create mode 100644 client/src/entities/lesson-schedule.jsx create mode 100644 server/src/db/entities/LessonSchedule.entity.ts create mode 100644 server/src/entity-modules/lesson-schedule.config.ts create mode 100644 server/src/migrations/1783407769935-AddLessonSchedule.ts diff --git a/client/src/App.jsx b/client/src/App.jsx index 680ab58a..c501f7c4 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -26,6 +26,7 @@ import klass from 'src/entities/klass'; import klassType from 'src/entities/klass-type'; import knownAbsence from 'src/entities/known-absence'; import lesson from 'src/entities/lesson'; +import lessonSchedule from 'src/entities/lesson-schedule'; import studentKlass from 'src/entities/student-klass'; import student from 'src/entities/student'; import teacher from 'src/entities/teacher'; @@ -59,6 +60,7 @@ import { isTeacherView, isTransportation, isAbsenceType, + isLessonSchedule, isStudentView, isStudentAttendanceByKlass, } from 'src/utils/appPermissions'; @@ -70,6 +72,7 @@ import ApprovedAbsencesUpload from 'src/components/ApprovedAbsencesUpload'; import BadgeIcon from '@mui/icons-material/Badge'; import SupervisedUserCircleIcon from '@mui/icons-material/SupervisedUserCircle'; import SchoolIcon from '@mui/icons-material/School'; +import EventNoteIcon from '@mui/icons-material/EventNote'; import PortraitIcon from '@mui/icons-material/Portrait'; import WorkspacesIcon from '@mui/icons-material/Workspaces'; import GroupWorkIcon from '@mui/icons-material/GroupWork'; @@ -157,6 +160,14 @@ const App = () => ( + {isLessonSchedule(permissions) && ( + + )} } /> {isStudentAttendanceByKlass(permissions) && ( diff --git a/client/src/components/LessonScheduleImportButton.jsx b/client/src/components/LessonScheduleImportButton.jsx new file mode 100644 index 00000000..50786577 --- /dev/null +++ b/client/src/components/LessonScheduleImportButton.jsx @@ -0,0 +1,91 @@ +import { useCallback, useState } from 'react'; +import { TextField, useDataProvider } from 'react-admin'; +import { ImportButton } from '@shared/components/import/ImportButton'; +import { PreviewListWithSavingDialog } from '@shared/components/import/PreviewListWithSavingDialog'; +import { useSavableData } from '@shared/components/import/util'; +import { CommonDatagrid } from '@shared/components/crudContainers/CommonList'; + +const RESOURCE = 'lesson_schedule'; + +const fields = ['organizationalYear', 'startTime', 'klassId', 'scheduleDate', 'lessonGroupCode', 'teacherId']; + +const PreviewDatagrid = ({ children, ...props }) => ( + + {children} + + + + + + + + +); + +// The excel column "מספר שעור + קבוצה" combines two values (e.g. "7771109-02") +// that map to two separate entity fields, so it must be split before saving. +const splitLessonGroupCode = (row) => { + const { lessonGroupCode, teacherId, ...rest } = row; + const match = /^(\d+)-(\d+)$/.exec(String(lessonGroupCode ?? '').trim()); + return { + ...rest, + lessonId: match ? Number(match[1]) : undefined, + groupNumber: match ? Number(match[2]) : undefined, + teacherId: teacherId != null && teacherId !== '' ? String(teacherId) : undefined, + }; +}; + +// This file is uploaded daily, so re-importing a date should replace that +// date's rows rather than duplicate them. Deletion runs only once the admin +// confirms the save (not at parse/preview time) to avoid data loss on cancel. +const useReplaceDatesPreSaveHook = () => { + const dataProvider = useDataProvider(); + return useCallback( + async (data) => { + const scheduleDates = [...new Set(data.map((row) => row.scheduleDate).filter(Boolean))]; + const idsToDelete = []; + for (const scheduleDate of scheduleDates) { + const { data: existing } = await dataProvider.getList(RESOURCE, { + filter: { scheduleDate }, + pagination: { page: 1, perPage: 10000 }, + sort: { field: 'id', order: 'ASC' }, + }); + idsToDelete.push(...existing.map((item) => item.id)); + } + if (idsToDelete.length) { + await dataProvider.deleteMany(RESOURCE, { ids: idsToDelete }); + } + }, + [dataProvider], + ); +}; + +export const LessonScheduleImportButton = () => { + const [uploadedData, setUploadedData] = useState(null); + const [fileName, setFileName] = useState(null); + const preSaveHook = useReplaceDatesPreSaveHook(); + const { data, saveData } = useSavableData(RESOURCE, fileName, uploadedData, undefined, undefined, preSaveHook); + + const handleDataParse = useCallback(({ name, data: parsedData }) => { + setUploadedData(parsedData.map(splitLessonGroupCode)); + setFileName(name); + }, []); + + const handlePreviewCancel = useCallback(() => { + setUploadedData(null); + setFileName(null); + }, []); + + return ( + <> + + + + ); +}; diff --git a/client/src/domainTranslations.js b/client/src/domainTranslations.js index 5752df1d..0f332073 100644 --- a/client/src/domainTranslations.js +++ b/client/src/domainTranslations.js @@ -164,6 +164,22 @@ export default { order: 'סדר', }, }, + lesson_schedule: { + name: 'מערכת שעות |||| מערכת שעות', + fields: { + ...generalResourceFieldsTranslation, + organizationalYear: 'שנה אירגונית', + startTime: 'משעה', + scheduleDate: 'תאריך', + klassId: 'התמחות', + klassReferenceId: 'התמחות', + lessonId: 'שיעור', + lessonReferenceId: 'שיעור', + groupNumber: 'קבוצה', + teacherId: 'מורה', + teacherReferenceId: 'מורה', + }, + }, student_klass: { name: 'רשומת שיוך תלמידות לכיתות |||| שיוך תלמידות לכיתות', fields: { diff --git a/client/src/entities/lesson-schedule.jsx b/client/src/entities/lesson-schedule.jsx new file mode 100644 index 00000000..796d4d22 --- /dev/null +++ b/client/src/entities/lesson-schedule.jsx @@ -0,0 +1,123 @@ +import { + DateField, + DateInput, + DateTimeInput, + NumberInput, + ReferenceField, + required, + TextField, + TextInput, +} from 'react-admin'; +import { CommonDatagrid } from '@shared/components/crudContainers/CommonList'; +import { CommonRepresentation } from '@shared/components/CommonRepresentation'; +import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity'; +import { + CommonReferenceInputFilter, + filterByUserId, + filterByUserIdAndYear, +} from '@shared/components/fields/CommonReferenceInputFilter'; +import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput'; +import { defaultYearFilter } from '@shared/utils/yearFilter'; +import { CommonYearField, CommonYearInput, CommonYearInputFilter } from '@shared/components/fields/CommonYear'; +import { CommonTimeInput } from '@shared/components/fields/CommonTimeInput'; +import { commonAdminFilters } from '@shared/components/fields/PermissionFilter'; +import { LessonScheduleImportButton } from 'src/components/LessonScheduleImportButton'; + +const filters = [ + ...commonAdminFilters, + , + , + , + , +]; + +const filterDefaultValues = { + ...defaultYearFilter, +}; + +const Datagrid = ({ isAdmin, children, ...props }) => { + return ( + + {children} + {isAdmin && } + {isAdmin && } + + + + + + + + + {isAdmin && } + {isAdmin && } + + ); +}; + +const Inputs = ({ isCreate, isAdmin }) => { + return ( + <> + {!isCreate && isAdmin && } + {isAdmin && } + + + + + + + + + {!isCreate && isAdmin && } + {!isCreate && isAdmin && } + + ); +}; + +const Representation = CommonRepresentation; + +const additionalListActions = []; + +const entity = { + Datagrid, + Inputs, + Representation, + filters, + filterDefaultValues, + additionalListActions, +}; + +export default getResourceComponents(entity); diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js index ba09f9fd..aea29bc7 100644 --- a/client/src/roadmapFeatures.js +++ b/client/src/roadmapFeatures.js @@ -21,6 +21,7 @@ export default [ { html: 'הוספת סינון לפי ציון נמוך מ בתעודה', status: 'בוצע', statusColor: 'success' }, { html: 'הוספת אפשרות לדיווח נוכחות סמינר בטלפון', status: 'בוצע', statusColor: 'success' }, { html: 'הוספת אפשרות לעדכון מספר טלפון בהגדרות', status: 'בוצע', statusColor: 'success' }, + { html: 'העלאת קובץ אקסל של מערכת שעות וזיהוי אוטומטי של השיעור בדיווח נוכחות בטלפון', status: 'בוצע', statusColor: 'success' }, // { html: 'הגדרת תקופת זמן לפי תאריכים', status: 'בקרוב', statusColor: 'warning' }, // { html: 'הגדרת תקופת זמן לפי יום בשבוע', status: 'בוצע', statusColor: 'success' }, diff --git a/client/src/utils/appPermissions.js b/client/src/utils/appPermissions.js index 0904d411..00c7f290 100644 --- a/client/src/utils/appPermissions.js +++ b/client/src/utils/appPermissions.js @@ -15,6 +15,7 @@ export const appPermissions = { studentView: 'studentView', studentAttendanceByKlass: 'studentAttendanceByKlass', seminarAttendanceYemot: 'seminarAttendanceYemot', + lessonSchedule: 'lessonSchedule', }; export const isScannerUpload = (permissions) => hasPermissionLogic(permissions, appPermissions.scannerUpload); @@ -66,3 +67,7 @@ export const useIsStudentAttendanceByKlass = () => useHasPermission(appPermissio export const isSeminarAttendanceYemot = (permissions) => hasPermissionLogic(permissions, appPermissions.seminarAttendanceYemot); export const useIsSeminarAttendanceYemot = () => useHasPermission(appPermissions.seminarAttendanceYemot); + +export const isLessonSchedule = (permissions) => + isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.lessonSchedule); +export const useIsLessonSchedule = () => useHasPermission(appPermissions.lessonSchedule); diff --git a/server/src/db/entities/LessonSchedule.entity.ts b/server/src/db/entities/LessonSchedule.entity.ts new file mode 100644 index 00000000..50303541 --- /dev/null +++ b/server/src/db/entities/LessonSchedule.entity.ts @@ -0,0 +1,171 @@ +import { + BeforeInsert, + BeforeUpdate, + Column, + DataSource, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; +import { IHasUserId } from '@shared/base-entity/interface'; +import { Klass } from './Klass.entity'; +import { Lesson } from './Lesson.entity'; +import { Teacher } from './Teacher.entity'; +import { User } from './User.entity'; +import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util'; +import { IsOptional, ValidateIf } from 'class-validator'; +import { CrudValidationGroups } from '@dataui/crud'; +import { IsNotEmpty, IsNumber, MaxLength, IsDate } from '@shared/utils/validation/class-validator-he'; +import { fillDefaultYearValue } from '@shared/utils/entity/year.util'; +import { cleanDateFields, cleanTimeFields } from '@shared/utils/entity/deafultValues.util'; +import { DateType, NumberType, StringType } from '@shared/utils/entity/class-transformer'; +import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util'; + +@Index('lesson_schedules_users_idx', ['userId'], {}) +@Index('lesson_schedules_teacher_date_idx', ['userId', 'teacherReferenceId', 'scheduleDate'], {}) +@Index('lesson_schedules_date_idx', ['userId', 'scheduleDate'], {}) +@Entity('lesson_schedules') +export class LessonSchedule implements IHasUserId { + @BeforeInsert() + @BeforeUpdate() + async fillFields() { + fillDefaultYearValue(this); + cleanDateFields(this, ['scheduleDate']); + cleanTimeFields(this, ['startTime']); + + let dataSource: DataSource; + try { + dataSource = await getDataSource([Teacher, Klass, Lesson, User]); + + this.teacherReferenceId = await findOneAndAssignReferenceId( + dataSource, + Teacher, + { tz: this.teacherId }, + this.userId, + this.teacherReferenceId, + this.teacherId, + ); + this.klassReferenceId = await findOneAndAssignReferenceId( + dataSource, + Klass, + { year: this.year, key: this.klassId }, + this.userId, + this.klassReferenceId, + this.klassId, + ); + this.lessonReferenceId = await findOneAndAssignReferenceId( + dataSource, + Lesson, + { year: this.year, key: this.lessonId }, + this.userId, + this.lessonReferenceId, + this.lessonId, + ); + } finally { + dataSource?.destroy(); + } + } + + @PrimaryGeneratedColumn({ type: 'int', name: 'id' }) + id: number; + + @Column('int', { name: 'user_id' }) + userId: number; + + @Column({ nullable: true }) + year: number; + + @IsOptional({ always: true }) + @StringType + @MaxLength(10, { always: true }) + @Column('varchar', { name: 'organizational_year', length: 10, nullable: true }) + organizationalYear: string | null; + + @IsOptional({ always: true }) + @StringType + @Column('time', { name: 'start_time', nullable: true }) + startTime: string | null; + + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @DateType + @IsDate({ always: true }) + @Column('date', { name: 'schedule_date' }) + scheduleDate: Date; + + @ValidateIf((lessonSchedule: LessonSchedule) => !Boolean(lessonSchedule.klassReferenceId), { always: true }) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Column('int', { name: 'klass_id', nullable: true }) + klassId: number | null; + + @ValidateIf( + (lessonSchedule: LessonSchedule) => !Boolean(lessonSchedule.klassId) && Boolean(lessonSchedule.klassReferenceId), + { always: true }, + ) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @Column({ nullable: true }) + @Index('lesson_schedules_klass_reference_id_idx') + klassReferenceId: number; + + @ValidateIf((lessonSchedule: LessonSchedule) => !Boolean(lessonSchedule.lessonReferenceId), { always: true }) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Column('int', { name: 'lesson_id', nullable: true }) + lessonId: number | null; + + @ValidateIf( + (lessonSchedule: LessonSchedule) => + !Boolean(lessonSchedule.lessonId) && Boolean(lessonSchedule.lessonReferenceId), + { always: true }, + ) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @Column({ nullable: true }) + @Index('lesson_schedules_lesson_reference_id_idx') + lessonReferenceId: number; + + @IsOptional({ always: true }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Column('int', { name: 'group_number', nullable: true }) + groupNumber: number | null; + + @ValidateIf((lessonSchedule: LessonSchedule) => !Boolean(lessonSchedule.teacherReferenceId), { always: true }) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @Column('varchar', { name: 'teacher_id', length: 10, nullable: true }) + teacherId: string; + + @ValidateIf( + (lessonSchedule: LessonSchedule) => + !Boolean(lessonSchedule.teacherId) && Boolean(lessonSchedule.teacherReferenceId), + { always: true }, + ) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @Column({ nullable: true }) + @Index('lesson_schedules_teacher_reference_id_idx') + teacherReferenceId: number; + + @CreatedAtColumn() + createdAt: Date; + + @UpdatedAtColumn() + updatedAt: Date; + + @ManyToOne(() => Teacher, { createForeignKeyConstraints: false }) + @JoinColumn({ name: 'teacherReferenceId' }) + teacher: Teacher; + + @ManyToOne(() => Klass, { createForeignKeyConstraints: false }) + @JoinColumn({ name: 'klassReferenceId' }) + klass: Klass; + + @ManyToOne(() => Lesson, { createForeignKeyConstraints: false }) + @JoinColumn({ name: 'lessonReferenceId' }) + lesson: Lesson; +} diff --git a/server/src/entities.module.ts b/server/src/entities.module.ts index 421452d2..18e447ca 100644 --- a/server/src/entities.module.ts +++ b/server/src/entities.module.ts @@ -7,6 +7,7 @@ import klassConfig from './entity-modules/klass.config'; import klassTypeConfig from './entity-modules/klass-type.config'; import knownAbsenceConfig from './entity-modules/known-absence.config'; import lessonConfig from './entity-modules/lesson.config'; +import lessonScheduleConfig from './entity-modules/lesson-schedule.config'; import studentKlassConfig from './entity-modules/student-klass.config'; import studentConfig from './entity-modules/student.config'; import teacherConfig from './entity-modules/teacher.config'; @@ -49,6 +50,7 @@ registerEntityNameMap({ klass_type: 'שיוך כיתות', known_absence: 'חיסורים מאושרים', lesson: 'שיעורים', + lesson_schedule: 'מערכת שעות מורות', student_klass: 'שיוך תלמידות לכיתות', student: 'תלמידות', teacher: 'מורות', @@ -65,6 +67,7 @@ registerEntityNameMap({ BaseEntityModule.register(klassTypeConfig), BaseEntityModule.register(knownAbsenceConfig), BaseEntityModule.register(lessonConfig), + BaseEntityModule.register(lessonScheduleConfig), BaseEntityModule.register(studentKlassConfig), BaseEntityModule.register(studentConfig), BaseEntityModule.register(teacherConfig), diff --git a/server/src/entity-modules/lesson-schedule.config.ts b/server/src/entity-modules/lesson-schedule.config.ts new file mode 100644 index 00000000..d652c0be --- /dev/null +++ b/server/src/entity-modules/lesson-schedule.config.ts @@ -0,0 +1,40 @@ +import { CrudRequest } from '@dataui/crud'; +import { BaseEntityModuleOptions } from '@shared/base-entity/interface'; +import { IHeader } from '@shared/utils/exporter/types'; +import { LessonSchedule } from 'src/db/entities/LessonSchedule.entity'; + +function getConfig(): BaseEntityModuleOptions { + return { + entity: LessonSchedule, + query: { + join: { + teacher: { eager: false }, + klass: { eager: false }, + lesson: { eager: false }, + }, + }, + exporter: { + processReqForExport(req: CrudRequest, innerFunc) { + req.options.query.join = { + teacher: { eager: true }, + klass: { eager: true }, + lesson: { eager: true }, + }; + return innerFunc(req); + }, + getExportHeaders(): IHeader[] { + return [ + { value: 'teacher.name', label: 'מורה' }, + { value: 'klass.name', label: 'התמחות' }, + { value: 'lesson.name', label: 'שיעור' }, + { value: 'groupNumber', label: 'קבוצה' }, + { value: 'scheduleDate', label: 'תאריך' }, + { value: 'startTime', label: 'משעה' }, + { value: 'organizationalYear', label: 'שנה אירגונית' }, + ]; + }, + }, + }; +} + +export default getConfig(); diff --git a/server/src/migrations/1783407769935-AddLessonSchedule.ts b/server/src/migrations/1783407769935-AddLessonSchedule.ts new file mode 100644 index 00000000..7ab0c205 --- /dev/null +++ b/server/src/migrations/1783407769935-AddLessonSchedule.ts @@ -0,0 +1,43 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class AddLessonSchedule1783407769935 implements MigrationInterface { + name = 'AddLessonSchedule1783407769935' + + public async up(queryRunner: QueryRunner): Promise { + const dbName = queryRunner.connection.options.database; + await queryRunner.query(` + CREATE TABLE \`lesson_schedules\` ( + \`id\` int NOT NULL AUTO_INCREMENT, + \`user_id\` int NOT NULL, + \`year\` int NULL, + \`organizational_year\` varchar(10) NULL, + \`start_time\` time NULL, + \`schedule_date\` date NOT NULL, + \`klass_id\` int NULL, + \`klassReferenceId\` int NULL, + \`lesson_id\` int NULL, + \`lessonReferenceId\` int NULL, + \`group_number\` int NULL, + \`teacher_id\` varchar(10) NULL, + \`teacherReferenceId\` int NULL, + \`created_at\` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + \`updated_at\` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + INDEX \`lesson_schedules_users_idx\` (\`user_id\`), + INDEX \`lesson_schedules_teacher_date_idx\` (\`user_id\`, \`teacherReferenceId\`, \`schedule_date\`), + INDEX \`lesson_schedules_date_idx\` (\`user_id\`, \`schedule_date\`), + INDEX \`lesson_schedules_klass_reference_id_idx\` (\`klassReferenceId\`), + INDEX \`lesson_schedules_lesson_reference_id_idx\` (\`lessonReferenceId\`), + INDEX \`lesson_schedules_teacher_reference_id_idx\` (\`teacherReferenceId\`), + PRIMARY KEY (\`id\`) + ) ENGINE = InnoDB + `); + } + + public async down(queryRunner: QueryRunner): Promise { + const dbName = queryRunner.connection.options.database; + await queryRunner.query(` + DROP TABLE \`lesson_schedules\` + `); + } + +} diff --git a/server/src/yemot-handler.service.test.ts b/server/src/yemot-handler.service.test.ts index 3ae3b8bc..d3a16cc7 100644 --- a/server/src/yemot-handler.service.test.ts +++ b/server/src/yemot-handler.service.test.ts @@ -435,6 +435,78 @@ describe('YemotHandlerService — react-admin-nestjs', () => { expect(result.hungup).toBe(true); }); + it('schedule match found — auto-detects lesson/klass, skips manual klass prompt, sets lessonReferenceId', async () => { + jest.setSystemTime(israelTimeAt(7, 0)); + const year = getCurrentHebrewYear(); + const klass = { id: 260, userId: 1, key: 13, name: 'Klass Thirteen', year }; + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const scenario = new YemotScenarioBuilder('Seminar auto-detected schedule') + .seed('User', [seminarUser({ seminarAttendanceYemot: true })]) + .seed('Teacher', [teacher]) + .seed('Klass', [klass]) + .seed('LessonSchedule', [ + { + userId: 1, + year, + teacherReferenceId: teacher.id, + klassReferenceId: 260, + lessonReferenceId: 700, + scheduleDate: today, + startTime: '07:00', + }, + ]) + .seed('Student', roster()) + .seed('StudentKlass', studentKlasses(260, year)) + .seed('Text', allTexts) + .seed('AttReport', []) + .systemAsks(/enter absent student number/i) + .userResponds('0') + .systemHangsUp(/success/i) + .build(); + + const result = await runner.run(scenario); + expect(result.passed).toBe(true); + expect(result.hungup).toBe(true); + + expect(result.saved['AttReport']).toHaveLength(3); + for (const report of result.saved['AttReport']) { + expect(report.klassReferenceId).toBe(260); + expect(report.lessonReferenceId).toBe(700); + } + }); + + it('no schedule for teacher today — falls back to manual klass entry with no lessonReferenceId', async () => { + jest.setSystemTime(israelTimeAt(7, 0)); + const year = getCurrentHebrewYear(); + const klass = { id: 270, userId: 1, key: 14, name: 'Klass Fourteen', year }; + + const scenario = new YemotScenarioBuilder('Seminar no schedule fallback') + .seed('User', [seminarUser({ seminarAttendanceYemot: true })]) + .seed('Teacher', [teacher]) + .seed('Klass', [klass]) + .seed('Student', roster()) + .seed('StudentKlass', studentKlasses(270, year)) + .seed('Text', allTexts) + .seed('AttReport', []) + .systemAsks(/enter klass number/i) + .userResponds('14') + .systemAsks(/enter absent student number/i) + .userResponds('0') + .systemHangsUp(/success/i) + .build(); + + const result = await runner.run(scenario); + expect(result.passed).toBe(true); + expect(result.hungup).toBe(true); + + expect(result.saved['AttReport']).toHaveLength(3); + for (const report of result.saved['AttReport']) { + expect(report.lessonReferenceId).toBeFalsy(); + } + }); + it('no students in klass — hangup with SEMINAR.NO_STUDENTS_IN_KLASS', async () => { jest.setSystemTime(israelTimeAt(7, 0)); const year = getCurrentHebrewYear(); diff --git a/server/src/yemot-handler.service.ts b/server/src/yemot-handler.service.ts index 2a4accec..dd61c07e 100644 --- a/server/src/yemot-handler.service.ts +++ b/server/src/yemot-handler.service.ts @@ -11,7 +11,10 @@ import { Klass } from './db/entities/Klass.entity'; import { AttReport } from './db/entities/AttReport.entity'; import { ReportGroup } from './db/entities/ReportGroup.entity'; import { ReportGroupSession } from './db/entities/ReportGroupSession.entity'; +import { LessonSchedule } from './db/entities/LessonSchedule.entity'; import { Between } from 'typeorm'; + +const SCHEDULE_MATCH_TOLERANCE_MINUTES = 90; /** * Yemot Handler Service for processing incoming Yemot calls * Currently returns a maintenance mode message @@ -56,7 +59,16 @@ export class YemotHandlerService extends BaseYemotHandlerService { const teacher = await this.getTeacherByPhone(); if (!teacher) return; - const klass = await this.getKlassByInput(); + const schedule = await this.getScheduleForTeacherNow(teacher); + let klass: Klass; + let lessonReferenceId: number | undefined; + if (schedule) { + klass = await this.dataSource.getRepository(Klass).findOneBy({ id: schedule.klassReferenceId }); + lessonReferenceId = schedule.lessonReferenceId; + } + if (!klass) { + klass = await this.getKlassByInput(); + } const alreadyReported = await this.hasReportedTodayForKlass(klass.id); if (alreadyReported) { @@ -71,10 +83,45 @@ export class YemotHandlerService extends BaseYemotHandlerService { } const absentStudentReferenceIds = await this.collectAbsentStudentIds(); - await this.saveSeminarAttendance(teacher, klass, roster, absentStudentReferenceIds); + await this.saveSeminarAttendance(teacher, klass, roster, absentStudentReferenceIds, lessonReferenceId); await this.hangupWithMessageByKey('SYSTEM.REPORT_SUCCESS'); } + private async getScheduleForTeacherNow(teacher: Teacher): Promise { + const todayDateOnly = this.getIsraelDateString(new Date()); + const schedules = await this.dataSource.getRepository(LessonSchedule).find({ + where: { + userId: this.user.id, + teacherReferenceId: teacher.id, + scheduleDate: todayDateOnly as unknown as Date, + }, + }); + if (schedules.length === 0) return null; + + const nowMinutes = this.getIsraelMinutesSinceMidnight(new Date()); + let closest: LessonSchedule | null = null; + let closestDiff = Infinity; + for (const schedule of schedules) { + if (!schedule.startTime) continue; + const diff = Math.abs(this.timeStringToMinutes(schedule.startTime) - nowMinutes); + if (diff < closestDiff) { + closestDiff = diff; + closest = schedule; + } + } + return closestDiff <= SCHEDULE_MATCH_TOLERANCE_MINUTES ? closest : null; + } + + private getIsraelMinutesSinceMidnight(date: Date): number { + const timeString = date.toLocaleTimeString('en-GB', { timeZone: 'Asia/Jerusalem', hour12: false }); + return this.timeStringToMinutes(timeString); + } + + private timeStringToMinutes(time: string): number { + const [hours, minutes] = time.split(':').map(Number); + return hours * 60 + minutes; + } + private async getTeacherByPhone(): Promise { const teacher = await this.dataSource.getRepository(Teacher).findOne({ where: [ @@ -155,6 +202,7 @@ export class YemotHandlerService extends BaseYemotHandlerService { klass: Klass, roster: StudentKlass[], absentStudentReferenceIds: Set, + lessonReferenceId?: number, ): Promise { const now = new Date(); const reportDate = this.getIsraelDateString(now) as unknown as Date; @@ -190,6 +238,7 @@ export class YemotHandlerService extends BaseYemotHandlerService { studentReferenceId: studentKlass.studentReferenceId, teacherReferenceId: teacher.id, klassReferenceId: klass.id, + lessonReferenceId, reportGroupSessionId, reportDate, absCount: absentStudentReferenceIds.has(studentKlass.studentReferenceId) ? 1 : 0, From 92251b9abcb51d89ae65486fa79b36a399719a00 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 7 Jul 2026 07:54:29 +0000 Subject: [PATCH 2/3] Drop hardcoded labels in lesson-schedule.jsx, rely on domainTranslations Field/filter labels are already defined under the lesson_schedule resource in domainTranslations.js, so explicit label props were redundant. --- client/src/entities/lesson-schedule.jsx | 27 ++++++++++--------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/client/src/entities/lesson-schedule.jsx b/client/src/entities/lesson-schedule.jsx index 796d4d22..edd62266 100644 --- a/client/src/entities/lesson-schedule.jsx +++ b/client/src/entities/lesson-schedule.jsx @@ -33,13 +33,11 @@ const filters = [ />, , , @@ -56,13 +54,13 @@ const Datagrid = ({ isAdmin, children, ...props }) => { {children} {isAdmin && } {isAdmin && } - - - - - - - + + + + + + + {isAdmin && } {isAdmin && } @@ -75,28 +73,25 @@ const Inputs = ({ isCreate, isAdmin }) => { <> {!isCreate && isAdmin && } {isAdmin && } - - - + + + - + From ba2f9881cba88044f5e8e036ab1a312ab2e0c079 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 7 Jul 2026 08:02:54 +0000 Subject: [PATCH 3/3] Explicitly initialize klass to null in processSeminarAttendanceCall Addresses review comment: relying on implicit undefined made the fallback-to-manual-entry control flow less explicit. --- server/src/yemot-handler.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/yemot-handler.service.ts b/server/src/yemot-handler.service.ts index dd61c07e..ff4eb19f 100644 --- a/server/src/yemot-handler.service.ts +++ b/server/src/yemot-handler.service.ts @@ -60,7 +60,7 @@ export class YemotHandlerService extends BaseYemotHandlerService { if (!teacher) return; const schedule = await this.getScheduleForTeacherNow(teacher); - let klass: Klass; + let klass: Klass = null; let lessonReferenceId: number | undefined; if (schedule) { klass = await this.dataSource.getRepository(Klass).findOneBy({ id: schedule.klassReferenceId });