Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions server/src/yemot-handler.service.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { MockCall, MockExitError, YemotScenarioBuilder, YemotScenarioRunner, createRealDataSource, useFakeDateOnly } from '@shared/utils/yemot/testing';
import { getCurrentHebrewYear } from '@shared/utils/entity/year.util';
import { HangupError } from 'yemot-router2';
import { YemotHandlerService } from './yemot-handler.service';

/**
Expand Down Expand Up @@ -1038,3 +1039,26 @@ describe('YemotHandlerService — react-admin-nestjs', () => {
});
});
});

describe('YemotHandlerService — seminar caller hangs up mid-call', () => {
it('logs the confirmed absent students it could not save, then rethrows the hangup', async () => {
const students: Record<string, { id: number; name: string }> = { '513': { id: 21239, name: 'A' }, '814': { id: 21376, name: 'B' } };
const dataSource = { getRepository: () => ({ findOneBy: async ({ studentNumber }) => students[studentNumber] ?? null }) };
const call = { callId: 'call-1' };
const handler: any = new YemotHandlerService(dataSource as any, call as any, {} as any);
handler.user = { id: 1 };
const inputs = ['513', '814'];
handler.askForInputByKey = jest.fn(async () => {
if (inputs.length) return inputs.shift();
throw new HangupError(call as any);
});
handler.askConfirmation = jest.fn(async () => true);
const warn = jest.spyOn(handler.logger, 'warn').mockImplementation(() => undefined);

await expect(handler.collectAbsentStudentIds({ id: 7 }, { id: 200 })).rejects.toBeInstanceOf(HangupError);

expect(warn).toHaveBeenCalledWith(
'Call call-1 hung up before finishing - not saved: klass 200, teacher 7, 2 confirmed absent student(s) [21239, 21376]',
);
});
});
54 changes: 35 additions & 19 deletions server/src/yemot-handler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { ReportGroupSession } from './db/entities/ReportGroupSession.entity';
import { LessonSchedule } from './db/entities/LessonSchedule.entity';
import { Lesson } from './db/entities/Lesson.entity';
import { Between, In, Like } from 'typeorm';
import { HangupError } from 'yemot-router2';

const SCHEDULE_MATCH_TOLERANCE_MINUTES = 90;
/**
Expand All @@ -24,9 +25,11 @@ const SCHEDULE_MATCH_TOLERANCE_MINUTES = 90;

@Injectable()
export class YemotHandlerService extends BaseYemotHandlerService {
// Stateless replay (see shared yemot-replay.ts): time-based branches read
// callStartedAt instead of new Date(), and DB writes only follow the last prompt.
static stateless = true;
// Stateless replay (see shared yemot-replay.ts) is off for now: calls are kept in
// memory between Yemot requests (single server node). The flow stays replay-safe -
// time-based branches read callStartedAt and DB writes only follow the last prompt -
// so it can be turned back on with `static stateless = true`.
static stateless = false;

override async processCall(): Promise<void> {
await this.getUserByDidPhone();
Expand Down Expand Up @@ -139,7 +142,7 @@ export class YemotHandlerService extends BaseYemotHandlerService {
return;
}

const absentStudentReferenceIds = await this.collectAbsentStudentIds();
const absentStudentReferenceIds = await this.collectAbsentStudentIds(teacher, klass);
await this.saveSeminarAttendance(teacher, klass, roster, absentStudentReferenceIds, lessonReferenceId, shouldDeletePreviousLesson);
if (shouldDeletePreviousLesson) {
await this.sendMessageByKey('SEMINAR.DUPLICATE_LESSON_DELETED');
Expand Down Expand Up @@ -268,25 +271,38 @@ export class YemotHandlerService extends BaseYemotHandlerService {
});
}

private async collectAbsentStudentIds(): Promise<Set<number>> {
private async collectAbsentStudentIds(teacher: Teacher, klass: Klass): Promise<Set<number>> {
const absentStudentReferenceIds = new Set<number>();
let input = await this.askForInputByKey('SEMINAR.ABSENT_STUDENT_PROMPT');
while (input !== '0') {
const student = await this.dataSource.getRepository(Student).findOneBy({
userId: this.user.id,
studentNumber: input,
});
if (!student) {
await this.sendMessageByKey('SEMINAR.INVALID_STUDENT_NUM');
} else {
const nameConfirmed = await this.askConfirmation('SEMINAR.CONFIRM_STUDENT_NAME', { studentName: student.name });
if (nameConfirmed) {
absentStudentReferenceIds.add(student.id);
try {
let input = await this.askForInputByKey('SEMINAR.ABSENT_STUDENT_PROMPT');
while (input !== '0') {
const student = await this.dataSource.getRepository(Student).findOneBy({
userId: this.user.id,
studentNumber: input,
});
if (!student) {
await this.sendMessageByKey('SEMINAR.INVALID_STUDENT_NUM');
} else {
await this.sendMessageByKey('SEMINAR.STUDENT_NAME_REJECTED');
const nameConfirmed = await this.askConfirmation('SEMINAR.CONFIRM_STUDENT_NAME', { studentName: student.name });
if (nameConfirmed) {
absentStudentReferenceIds.add(student.id);
} else {
await this.sendMessageByKey('SEMINAR.STUDENT_NAME_REJECTED');
}
}
input = await this.askForInputByKey('SEMINAR.ABSENT_STUDENT_PROMPT');
}
} catch (e) {
// Nothing is saved when the caller hangs up before finishing; log what was already
// confirmed so the lost report can be traced. warn, not log: info logs are muted
// while a stateless call replays its earlier steps.
if (e instanceof HangupError) {
this.logger.warn(
`Call ${this.call.callId} hung up before finishing - not saved: klass ${klass.id}, teacher ${teacher.id}, ` +
`${absentStudentReferenceIds.size} confirmed absent student(s) [${[...absentStudentReferenceIds].join(', ')}]`,
);
}
input = await this.askForInputByKey('SEMINAR.ABSENT_STUDENT_PROMPT');
throw e;
}
return absentStudentReferenceIds;
}
Expand Down
Loading