From 92f045d6567a1f041b6d5ed4d0e3bbae0195b870 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 16 Sep 2026 19:45:21 +0000 Subject: [PATCH 1/3] Add seminar duplicate-lesson texts migration with real timestamp Same texts as PR #191's migration, filename/class timestamped with actual Date.now() instead of a rounded placeholder. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01WER1oSuN8tCQTNRU73Mi89 --- ...-UpdateYemotTextsSeminarDuplicateLesson.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 server/src/migrations/1789587905258-UpdateYemotTextsSeminarDuplicateLesson.ts diff --git a/server/src/migrations/1789587905258-UpdateYemotTextsSeminarDuplicateLesson.ts b/server/src/migrations/1789587905258-UpdateYemotTextsSeminarDuplicateLesson.ts new file mode 100644 index 00000000..569d036d --- /dev/null +++ b/server/src/migrations/1789587905258-UpdateYemotTextsSeminarDuplicateLesson.ts @@ -0,0 +1,28 @@ +import { MigrationInterface, QueryRunner } from "typeorm" + +export class UpdateYemotTextsSeminarDuplicateLesson1789587905258 implements MigrationInterface { + + public async up(queryRunner: QueryRunner): Promise { + const texts = [ + { name: 'SEMINAR.DUPLICATE_LESSON_PROMPT', text: 'השיעור כבר תוקף. הקישי 1 להוספת שיעור נוסף, 2 למחיקת הקודם' }, + { name: 'SEMINAR.DUPLICATE_LESSON_DELETED', text: 'הדיווח הקודם נמחק' }, + ]; + + for (const text of texts) { + await queryRunner.query( + 'INSERT INTO `texts` (`user_id`, `name`, `description`, `value`) VALUES (?, ?, ?, ?)', + [0, text.name, text.text, text.text], + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + 'DELETE FROM `texts` WHERE `user_id` = 0 AND `name` IN (?, ?)', + [ + 'SEMINAR.DUPLICATE_LESSON_PROMPT', + 'SEMINAR.DUPLICATE_LESSON_DELETED', + ], + ); + } +} From 0b76b6a72169ab93d4c90f5ebae1742830bd31ac Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 16 Sep 2026 20:20:31 +0000 Subject: [PATCH 2/3] Bring in seminar duplicate-lesson guard logic and tests from PR #191 Adds the duplicate-lesson-punch handling in processSeminarAttendanceCall (ask 1=add another, 2=delete previous, with cascade cleanup of now-unused ReportGroupSession/ReportGroup rows) plus its test coverage, alongside the previously added texts migration with a real timestamp. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01WER1oSuN8tCQTNRU73Mi89 --- server/src/yemot-handler.service.test.ts | 130 ++++++++++++++++++++++- server/src/yemot-handler.service.ts | 48 +++++++++ 2 files changed, 177 insertions(+), 1 deletion(-) diff --git a/server/src/yemot-handler.service.test.ts b/server/src/yemot-handler.service.test.ts index 42d883a1..9b08358e 100644 --- a/server/src/yemot-handler.service.test.ts +++ b/server/src/yemot-handler.service.test.ts @@ -1,4 +1,4 @@ -import { YemotScenarioBuilder, YemotScenarioRunner, useFakeDateOnly } from '@shared/utils/yemot/testing'; +import { MockCall, MockExitError, YemotScenarioBuilder, YemotScenarioRunner, createRealDataSource, useFakeDateOnly } from '@shared/utils/yemot/testing'; import { getCurrentHebrewYear } from '@shared/utils/entity/year.util'; import { YemotHandlerService } from './yemot-handler.service'; @@ -281,10 +281,14 @@ describe('YemotHandlerService — react-admin-nestjs', () => { { userId: 0, name: 'SEMINAR.KLASS_CONFIRMED', description: '', value: 'Confirmed klass {klassName}' }, { userId: 0, name: 'SEMINAR.TEACHER_CODE_PROMPT', description: '', value: 'Enter teacher code' }, { userId: 0, name: 'SEMINAR.INVALID_TEACHER_CODE', description: '', value: 'Invalid teacher code, try again' }, + { userId: 0, name: 'SEMINAR.DUPLICATE_LESSON_PROMPT', description: '', value: 'Lesson already reported. Press 1 to add another lesson, 2 to delete the previous' }, + { userId: 0, name: 'SEMINAR.DUPLICATE_LESSON_DELETED', description: '', value: 'Previous report deleted' }, ]; const allTexts = [...baseTexts, ...seminarTexts]; const TEACHER_CODE_PROMPT = /enter teacher code/i; + const DUPLICATE_LESSON_PROMPT = /already reported.*1.*2/i; + const DUPLICATE_LESSON_DELETED = /previous report deleted/i; const teacher = { id: 1, userId: 1, tz: '900000001', name: 'Teacher One', number: '1' }; const roster = () => [ @@ -570,6 +574,130 @@ describe('YemotHandlerService — react-admin-nestjs', () => { } }); + it('duplicate lesson exists — answering 1 keeps the previous report and saves new rows', async () => { + jest.setSystemTime(israelTimeAt(7, 0)); + const year = getCurrentHebrewYear(); + const klass = { id: 285, userId: 1, key: 21, name: 'Klass Twenty One', year }; + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const builder = seminarBuilder('Seminar duplicate lesson add', klass) + .seed('LessonSchedule', [ + { + userId: 1, + year, + teacherReferenceId: teacher.id, + klassReferenceId: 285, + lessonReferenceId: 700, + scheduleDate: today, + startTime: '07:00', + }, + ]) + .seed('AttReport', [ + { id: 901, userId: 1, studentReferenceId: 101, klassReferenceId: 285, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 0 }, + { id: 902, userId: 1, studentReferenceId: 102, klassReferenceId: 285, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 0 }, + { id: 903, userId: 1, studentReferenceId: 103, klassReferenceId: 285, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 0 }, + ]); + startsSeminarCall(builder, '21', '1'); + ask(builder, DUPLICATE_LESSON_PROMPT, '1'); + finishAbsentStudentEntry(builder); + const scenario = builder.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).toBe(700); + expect(report.absCount).toBe(0); + } + }); + + it('duplicate lesson exists — answering 2 deletes all prior rows (and their unused report session/group) and saves fresh rows', async () => { + jest.setSystemTime(israelTimeAt(7, 0)); + const year = getCurrentHebrewYear(); + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const ds = await createRealDataSource(); + try { + const repo = (entityName: string) => ds.getRepository(entityName); + await repo('User').save({ ...baseUser, permissions: { seminarAttendanceYemot: true } }); + await repo('Text').save(allTexts); + await repo('Teacher').save(teacher); + await repo('Klass').save({ id: 286, userId: 1, key: 22, name: 'Klass Twenty Two', year }); + await repo('Student').save(roster()); + await repo('StudentKlass').save(studentKlasses(286, year)); + await repo('LessonSchedule').save([ + { + userId: 1, + year, + teacherReferenceId: teacher.id, + klassReferenceId: 286, + lessonReferenceId: 700, + scheduleDate: today, + startTime: '07:00', + }, + ]); + await repo('ReportGroup').save([ + { id: 800, userId: 1, name: 'prior group', topic: 'prior', teacherReferenceId: teacher.id, klassReferenceId: 286, year }, + { id: 801, userId: 1, name: 'fully deleted group', topic: 'prior', teacherReferenceId: teacher.id, klassReferenceId: 286, year }, + ]); + await repo('ReportGroupSession').save([ + { id: 900, userId: 1, reportGroupId: 800, sessionDate: today, startTime: '07:30' }, + { id: 901, userId: 1, reportGroupId: 800, sessionDate: today, startTime: '08:00' }, + { id: 902, userId: 1, reportGroupId: 801, sessionDate: today, startTime: '08:30' }, + ]); + await repo('AttReport').save([ + { id: 910, userId: 1, studentReferenceId: 101, klassReferenceId: 286, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 1, reportGroupSessionId: 900 }, + { id: 911, userId: 1, studentReferenceId: 102, klassReferenceId: 286, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 0, reportGroupSessionId: 900 }, + { id: 912, userId: 1, studentReferenceId: 103, klassReferenceId: 286, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 0, reportGroupSessionId: 900 }, + { id: 913, userId: 1, studentReferenceId: 102, klassReferenceId: 286, teacherReferenceId: 1, lessonReferenceId: 701, reportDate: today, absCount: 0, reportGroupSessionId: 901 }, + { id: 914, userId: 1, studentReferenceId: 101, klassReferenceId: 286, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 0, reportGroupSessionId: 902 }, + ]); + + const call = new MockCall({ ApiDID: '099999999', ApiPhone: '0501234567', ApiCallId: 'test-call-2' }); + call.setInputs(['22', '1', '2', '0']); + const tracker = { + logConversationStep: jest.fn().mockResolvedValue(undefined), + initializeCall: jest.fn().mockResolvedValue(undefined), + finalizeCall: jest.fn().mockResolvedValue(undefined), + markCallError: jest.fn().mockResolvedValue(undefined), + }; + const handler = new YemotHandlerService(ds as any, call as any, tracker as any); + await handler.processCall().catch((e) => { + if (!(e instanceof MockExitError)) throw e; + }); + + expect(call.getMessages().flat().map((m) => m.data)).toEqual( + expect.arrayContaining([expect.stringMatching(DUPLICATE_LESSON_DELETED)]), + ); + + // Prior rows for the lesson (ids 910-912, one per student) are gone; only the + // fresh report plus the unrelated row for lesson 701 remain. + const reports = await repo('AttReport').find(); + expect(reports).toHaveLength(4); + const freshRows = reports.filter((r: any) => r.lessonReferenceId === 700); + expect(freshRows.map((r: any) => r.studentReferenceId).sort()).toEqual([101, 102, 103]); + for (const report of freshRows) { + expect(report.absCount).toBe(0); + expect(report.reportGroupSessionId).toBeFalsy(); + } + expect(reports.some((r: any) => r.id === 913)).toBe(true); + + // Sessions 900 and 902 had no remaining references and were deleted, along + // with group 801 (no sessions left); session 901 is still referenced by row + // 913, so its group 800 is kept. + const sessions = await repo('ReportGroupSession').find(); + expect(sessions.map((s: any) => s.id)).toEqual([901]); + const groups = await repo('ReportGroup').find(); + expect(groups.map((g: any) => g.id)).toEqual([800]); + } finally { + await ds.destroy(); + } + }); + it('schedule matches teacher but not the resolved klass — lessonReferenceId stays unset', 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 3f33d2ac..0ef108e4 100644 --- a/server/src/yemot-handler.service.ts +++ b/server/src/yemot-handler.service.ts @@ -123,11 +123,59 @@ export class YemotHandlerService extends BaseYemotHandlerService { return; } + if (lessonReferenceId) { + await this.handleLessonDuplicate(teacher, klass, lessonReferenceId); + } + const absentStudentReferenceIds = await this.collectAbsentStudentIds(); await this.saveSeminarAttendance(teacher, klass, roster, absentStudentReferenceIds, lessonReferenceId); await this.hangupWithMessageByKey('SYSTEM.REPORT_SUCCESS'); } + private async handleLessonDuplicate(teacher: Teacher, klass: Klass, lessonReferenceId: number): Promise { + const reportDate = this.getIsraelDateString(new Date()) as unknown as Date; + const existing = await this.dataSource.getRepository(AttReport).findOneBy({ + userId: this.user.id, + klassReferenceId: klass.id, + teacherReferenceId: teacher.id, + lessonReferenceId, + reportDate, + }); + if (!existing) return; + + const choice = await this.askForInputByKey('SEMINAR.DUPLICATE_LESSON_PROMPT', undefined, { + min_digits: 1, + max_digits: 1, + digits_allowed: ['1', '2'], + }); + if (choice !== '2') return; + + await this.dataSource.transaction(async (manager) => { + const attReportRepo = manager.getRepository(AttReport); + const duplicateWhere = { + userId: this.user.id, + klassReferenceId: klass.id, + teacherReferenceId: teacher.id, + lessonReferenceId, + reportDate, + }; + const priorRows = await attReportRepo.find({ where: duplicateWhere }); + await attReportRepo.delete(duplicateWhere); + + const sessionIds = [...new Set(priorRows.map((row) => row.reportGroupSessionId).filter((id) => id != null))]; + for (const reportGroupSessionId of sessionIds) { + if (await attReportRepo.findOneBy({ reportGroupSessionId })) continue; + const session = await manager.getRepository(ReportGroupSession).findOneBy({ id: reportGroupSessionId }); + if (!session) continue; + await manager.getRepository(ReportGroupSession).delete(session.id); + if (!(await manager.getRepository(ReportGroupSession).findOneBy({ reportGroupId: session.reportGroupId }))) { + await manager.getRepository(ReportGroup).delete(session.reportGroupId); + } + } + }); + await this.sendMessageByKey('SEMINAR.DUPLICATE_LESSON_DELETED'); + } + private async getScheduleForTeacherNow(teacher: Teacher): Promise { const todayDateOnly = this.getIsraelDateString(new Date()); const schedules = await this.dataSource.getRepository(LessonSchedule).find({ From 6a2087af6d602887b86cca2b7a1878a9ac0c9cab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 17 Sep 2026 05:15:39 +0000 Subject: [PATCH 3/3] Ask duplicate-lesson question early, defer actual delete to save time Strip the ReportGroup/ReportGroupSession cascade cleanup on "delete previous": it never checked Grade rows also FK-referencing ReportGroupSession (ON DELETE NO ACTION), so it could throw and abort the whole transaction. Orphaned group/session rows are harmless, so just stop touching them and only delete the duplicate AttReport rows. Also move the duplicate check right after the lesson is resolved (before the roster fetch), so the caller is asked as soon as possible, while the actual delete now happens atomically inside saveSeminarAttendance's transaction, right before the fresh rows are inserted. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01WER1oSuN8tCQTNRU73Mi89 --- server/src/yemot-handler.service.test.ts | 16 +++---- server/src/yemot-handler.service.ts | 58 ++++++++++-------------- 2 files changed, 32 insertions(+), 42 deletions(-) diff --git a/server/src/yemot-handler.service.test.ts b/server/src/yemot-handler.service.test.ts index 9b08358e..822f034a 100644 --- a/server/src/yemot-handler.service.test.ts +++ b/server/src/yemot-handler.service.test.ts @@ -614,7 +614,7 @@ describe('YemotHandlerService — react-admin-nestjs', () => { } }); - it('duplicate lesson exists — answering 2 deletes all prior rows (and their unused report session/group) and saves fresh rows', async () => { + it('duplicate lesson exists — answering 2 deletes all prior rows for that lesson and saves fresh rows', async () => { jest.setSystemTime(israelTimeAt(7, 0)); const year = getCurrentHebrewYear(); const today = new Date(); @@ -674,8 +674,9 @@ describe('YemotHandlerService — react-admin-nestjs', () => { expect.arrayContaining([expect.stringMatching(DUPLICATE_LESSON_DELETED)]), ); - // Prior rows for the lesson (ids 910-912, one per student) are gone; only the - // fresh report plus the unrelated row for lesson 701 remain. + // Prior rows for the lesson (910-912, 914 — every row matching user+klass+teacher+ + // lesson+date, regardless of student) are gone; only the fresh report plus the + // unrelated row for lesson 701 remain. const reports = await repo('AttReport').find(); expect(reports).toHaveLength(4); const freshRows = reports.filter((r: any) => r.lessonReferenceId === 700); @@ -686,13 +687,12 @@ describe('YemotHandlerService — react-admin-nestjs', () => { } expect(reports.some((r: any) => r.id === 913)).toBe(true); - // Sessions 900 and 902 had no remaining references and were deleted, along - // with group 801 (no sessions left); session 901 is still referenced by row - // 913, so its group 800 is kept. + // Report groups/sessions are left untouched — deleting a duplicate report only + // removes AttReport rows, it never cascades into ReportGroup/ReportGroupSession. const sessions = await repo('ReportGroupSession').find(); - expect(sessions.map((s: any) => s.id)).toEqual([901]); + expect(sessions.map((s: any) => s.id).sort()).toEqual([900, 901, 902]); const groups = await repo('ReportGroup').find(); - expect(groups.map((g: any) => g.id)).toEqual([800]); + expect(groups.map((g: any) => g.id).sort()).toEqual([800, 801]); } finally { await ds.destroy(); } diff --git a/server/src/yemot-handler.service.ts b/server/src/yemot-handler.service.ts index 0ef108e4..5810ae4d 100644 --- a/server/src/yemot-handler.service.ts +++ b/server/src/yemot-handler.service.ts @@ -117,22 +117,25 @@ export class YemotHandlerService extends BaseYemotHandlerService { const schedule = await this.getScheduleForTeacherNow(teacher); const lessonReferenceId = schedule?.klassReferenceId === klass.id ? schedule.lessonReferenceId : undefined; + const shouldDeletePreviousLesson = lessonReferenceId + ? await this.askDuplicateLessonChoice(teacher, klass, lessonReferenceId) + : false; + const roster = await this.getKlassRoster(klass.id); if (roster.length === 0) { await this.hangupWithMessageByKey('SEMINAR.NO_STUDENTS_IN_KLASS'); return; } - if (lessonReferenceId) { - await this.handleLessonDuplicate(teacher, klass, lessonReferenceId); - } - const absentStudentReferenceIds = await this.collectAbsentStudentIds(); - await this.saveSeminarAttendance(teacher, klass, roster, absentStudentReferenceIds, lessonReferenceId); + await this.saveSeminarAttendance(teacher, klass, roster, absentStudentReferenceIds, lessonReferenceId, shouldDeletePreviousLesson); + if (shouldDeletePreviousLesson) { + await this.sendMessageByKey('SEMINAR.DUPLICATE_LESSON_DELETED'); + } await this.hangupWithMessageByKey('SYSTEM.REPORT_SUCCESS'); } - private async handleLessonDuplicate(teacher: Teacher, klass: Klass, lessonReferenceId: number): Promise { + private async askDuplicateLessonChoice(teacher: Teacher, klass: Klass, lessonReferenceId: number): Promise { const reportDate = this.getIsraelDateString(new Date()) as unknown as Date; const existing = await this.dataSource.getRepository(AttReport).findOneBy({ userId: this.user.id, @@ -141,39 +144,14 @@ export class YemotHandlerService extends BaseYemotHandlerService { lessonReferenceId, reportDate, }); - if (!existing) return; + if (!existing) return false; const choice = await this.askForInputByKey('SEMINAR.DUPLICATE_LESSON_PROMPT', undefined, { min_digits: 1, max_digits: 1, digits_allowed: ['1', '2'], }); - if (choice !== '2') return; - - await this.dataSource.transaction(async (manager) => { - const attReportRepo = manager.getRepository(AttReport); - const duplicateWhere = { - userId: this.user.id, - klassReferenceId: klass.id, - teacherReferenceId: teacher.id, - lessonReferenceId, - reportDate, - }; - const priorRows = await attReportRepo.find({ where: duplicateWhere }); - await attReportRepo.delete(duplicateWhere); - - const sessionIds = [...new Set(priorRows.map((row) => row.reportGroupSessionId).filter((id) => id != null))]; - for (const reportGroupSessionId of sessionIds) { - if (await attReportRepo.findOneBy({ reportGroupSessionId })) continue; - const session = await manager.getRepository(ReportGroupSession).findOneBy({ id: reportGroupSessionId }); - if (!session) continue; - await manager.getRepository(ReportGroupSession).delete(session.id); - if (!(await manager.getRepository(ReportGroupSession).findOneBy({ reportGroupId: session.reportGroupId }))) { - await manager.getRepository(ReportGroup).delete(session.reportGroupId); - } - } - }); - await this.sendMessageByKey('SEMINAR.DUPLICATE_LESSON_DELETED'); + return choice === '2'; } private async getScheduleForTeacherNow(teacher: Teacher): Promise { @@ -288,12 +266,25 @@ export class YemotHandlerService extends BaseYemotHandlerService { roster: StudentKlass[], absentStudentReferenceIds: Set, lessonReferenceId?: number, + shouldDeletePreviousLesson?: boolean, ): Promise { const now = new Date(); const reportDate = this.getIsraelDateString(now) as unknown as Date; const callTime = now.toLocaleTimeString('en-GB', { timeZone: 'Asia/Jerusalem', hour12: false }); await this.dataSource.transaction(async (manager) => { + const attReportRepo = manager.getRepository(AttReport); + + if (shouldDeletePreviousLesson) { + await attReportRepo.delete({ + userId: this.user.id, + klassReferenceId: klass.id, + teacherReferenceId: teacher.id, + lessonReferenceId, + reportDate, + }); + } + let reportGroupSessionId: number | undefined; if (hasPermission(this.user, 'lessonSignature')) { @@ -316,7 +307,6 @@ export class YemotHandlerService extends BaseYemotHandlerService { reportGroupSessionId = reportGroupSession.id; } - const attReportRepo = manager.getRepository(AttReport); const rows = roster.map((studentKlass) => attReportRepo.create({ userId: this.user.id,