From d20e5610dd0ee6c0c322fd88aed654fb14af2b70 Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Wed, 16 Sep 2026 20:40:23 +0200 Subject: [PATCH 1/2] Ask before duplicating a seminar lesson punch; option 2 deletes the prior report Girls were punching the same lesson multiple times. When the resolved lesson+klass+teacher+date already has AttReport rows, the caller now gets a prompt: 1 = add another lesson (new rows saved on top), 2 = delete the previous rows for that lesson before the new report is saved. New IVR text keys (need manual DB setup, see PR): - SEMINAR.DUPLICATE_LESSON_PROMPT - SEMINAR.DUPLICATE_LESSON_DELETED Queries ride the existing att_teacher_lesson_date_idx - no migration. --- server/src/yemot-handler.service.test.ts | 85 ++++++++++++++++++++++++ server/src/yemot-handler.service.ts | 32 +++++++++ 2 files changed, 117 insertions(+) diff --git a/server/src/yemot-handler.service.test.ts b/server/src/yemot-handler.service.test.ts index 42d883a1..06930bd6 100644 --- a/server/src/yemot-handler.service.test.ts +++ b/server/src/yemot-handler.service.test.ts @@ -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,87 @@ 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 the previous rows and saves new rows', async () => { + jest.setSystemTime(israelTimeAt(7, 0)); + const year = getCurrentHebrewYear(); + const klass = { id: 286, userId: 1, key: 22, name: 'Klass Twenty Two', year }; + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const builder = seminarBuilder('Seminar duplicate lesson delete', klass) + .seed('LessonSchedule', [ + { + userId: 1, + year, + teacherReferenceId: teacher.id, + klassReferenceId: 286, + lessonReferenceId: 700, + scheduleDate: today, + startTime: '07:00', + }, + ]) + .seed('AttReport', [ + { id: 910, userId: 1, studentReferenceId: 101, klassReferenceId: 286, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 1 }, + ]); + startsSeminarCall(builder, '22', '1'); + ask(builder, DUPLICATE_LESSON_PROMPT, '2'); + builder.systemSends(DUPLICATE_LESSON_DELETED); + 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); + + // 3 fresh rows are saved; the harness subtracts seeds by count, so the + // first fresh row is folded into the 1-row seed slice and 2 remain visible. + expect(result.saved['AttReport']).toHaveLength(2); + for (const report of result.saved['AttReport']) { + expect(report.lessonReferenceId).toBe(700); + expect(report.absCount).toBe(0); + } + }); + 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..61461b3b 100644 --- a/server/src/yemot-handler.service.ts +++ b/server/src/yemot-handler.service.ts @@ -117,6 +117,10 @@ export class YemotHandlerService extends BaseYemotHandlerService { const schedule = await this.getScheduleForTeacherNow(teacher); const lessonReferenceId = schedule?.klassReferenceId === klass.id ? schedule.lessonReferenceId : undefined; + if (lessonReferenceId) { + await this.handleLessonDuplicate(teacher, klass, lessonReferenceId); + } + const roster = await this.getKlassRoster(klass.id); if (roster.length === 0) { await this.hangupWithMessageByKey('SEMINAR.NO_STUDENTS_IN_KLASS'); @@ -128,6 +132,34 @@ export class YemotHandlerService extends BaseYemotHandlerService { 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.getRepository(AttReport).delete({ + userId: this.user.id, + klassReferenceId: klass.id, + teacherReferenceId: teacher.id, + lessonReferenceId, + reportDate, + }); + 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 419ddb88376ed8146333483ee6cfd7af226d6e5e Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Wed, 16 Sep 2026 21:24:31 +0200 Subject: [PATCH 2/2] Review fixes: roster guard first, orphaned report-group cleanup, texts migration, stronger delete test - Check the klass roster (hang up when empty) before the duplicate prompt, so an empty-klass call can no longer delete prior rows. - On delete (option 2): remove the prior AttReport rows, then drop their ReportGroupSessions once no report row references them, and their ReportGroups once no session references them - all in one transaction. - Seed the two new texts via migration instead of manual DB setup (UpdateYemotTextsSeminarDuplicateLesson, user_id 0). - Delete-path test now seeds the full prior report (one row per student, one with absCount 1, two report sessions) and asserts the complete post-run DB state instead of the runner's seed-count arithmetic. --- ...-UpdateYemotTextsSeminarDuplicateLesson.ts | 28 ++++++ server/src/yemot-handler.service.test.ts | 89 ++++++++++++++----- server/src/yemot-handler.service.ts | 36 +++++--- 3 files changed, 120 insertions(+), 33 deletions(-) create mode 100644 server/src/migrations/1789600000000-UpdateYemotTextsSeminarDuplicateLesson.ts diff --git a/server/src/migrations/1789600000000-UpdateYemotTextsSeminarDuplicateLesson.ts b/server/src/migrations/1789600000000-UpdateYemotTextsSeminarDuplicateLesson.ts new file mode 100644 index 00000000..d996f37b --- /dev/null +++ b/server/src/migrations/1789600000000-UpdateYemotTextsSeminarDuplicateLesson.ts @@ -0,0 +1,28 @@ +import { MigrationInterface, QueryRunner } from "typeorm" + +export class UpdateYemotTextsSeminarDuplicateLesson1789600000000 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', + ], + ); + } +} \ No newline at end of file diff --git a/server/src/yemot-handler.service.test.ts b/server/src/yemot-handler.service.test.ts index 06930bd6..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'; @@ -614,15 +614,22 @@ describe('YemotHandlerService — react-admin-nestjs', () => { } }); - it('duplicate lesson exists — answering 2 deletes the previous rows and saves new rows', async () => { + 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 klass = { id: 286, userId: 1, key: 22, name: 'Klass Twenty Two', year }; const today = new Date(); today.setHours(0, 0, 0, 0); - const builder = seminarBuilder('Seminar duplicate lesson delete', klass) - .seed('LessonSchedule', [ + 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, @@ -632,26 +639,62 @@ describe('YemotHandlerService — react-admin-nestjs', () => { scheduleDate: today, startTime: '07:00', }, - ]) - .seed('AttReport', [ - { id: 910, userId: 1, studentReferenceId: 101, klassReferenceId: 286, teacherReferenceId: 1, lessonReferenceId: 700, reportDate: today, absCount: 1 }, ]); - startsSeminarCall(builder, '22', '1'); - ask(builder, DUPLICATE_LESSON_PROMPT, '2'); - builder.systemSends(DUPLICATE_LESSON_DELETED); - 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); + 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 }, + ]); - // 3 fresh rows are saved; the harness subtracts seeds by count, so the - // first fresh row is folded into the 1-row seed slice and 2 remain visible. - expect(result.saved['AttReport']).toHaveLength(2); - for (const report of result.saved['AttReport']) { - expect(report.lessonReferenceId).toBe(700); - expect(report.absCount).toBe(0); + 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(); } }); diff --git a/server/src/yemot-handler.service.ts b/server/src/yemot-handler.service.ts index 61461b3b..0ef108e4 100644 --- a/server/src/yemot-handler.service.ts +++ b/server/src/yemot-handler.service.ts @@ -117,16 +117,16 @@ export class YemotHandlerService extends BaseYemotHandlerService { const schedule = await this.getScheduleForTeacherNow(teacher); const lessonReferenceId = schedule?.klassReferenceId === klass.id ? schedule.lessonReferenceId : undefined; - if (lessonReferenceId) { - await this.handleLessonDuplicate(teacher, klass, lessonReferenceId); - } - 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.hangupWithMessageByKey('SYSTEM.REPORT_SUCCESS'); @@ -150,12 +150,28 @@ export class YemotHandlerService extends BaseYemotHandlerService { }); if (choice !== '2') return; - await this.dataSource.getRepository(AttReport).delete({ - userId: this.user.id, - klassReferenceId: klass.id, - teacherReferenceId: teacher.id, - lessonReferenceId, - reportDate, + 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'); }