From e8c4d1b61882aaf0a19d0e3527d0943e2e16c136 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 20:53:11 +0000 Subject: [PATCH 1/2] refactor(yemot): remove unused v1 chain-based Yemot flow No consumer wires the v1 YemotModule/YemotService/Chain; every app uses v2 (BaseYemotHandlerService via base-app.module). Keep FormatString in yemot.interface.ts since react-admin-nestjs imports it from that path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WhKqWQTBUpM1iambUHayry --- utils/yemot/__tests__/chain.interface.spec.ts | 98 ---- utils/yemot/__tests__/yemot.interface.spec.ts | 174 +------ utils/yemot/__tests__/yemot.service.spec.ts | 435 ------------------ utils/yemot/chain.interface.ts | 46 -- utils/yemot/yemot.exception.ts | 16 - utils/yemot/yemot.interface.ts | 137 ------ utils/yemot/yemot.module.ts | 41 -- utils/yemot/yemot.service.ts | 138 ------ utils/yemot/yemot.util.ts | 96 ---- 9 files changed, 1 insertion(+), 1180 deletions(-) delete mode 100644 utils/yemot/__tests__/chain.interface.spec.ts delete mode 100644 utils/yemot/__tests__/yemot.service.spec.ts delete mode 100644 utils/yemot/chain.interface.ts delete mode 100644 utils/yemot/yemot.exception.ts delete mode 100644 utils/yemot/yemot.module.ts delete mode 100644 utils/yemot/yemot.service.ts delete mode 100644 utils/yemot/yemot.util.ts diff --git a/utils/yemot/__tests__/chain.interface.spec.ts b/utils/yemot/__tests__/chain.interface.spec.ts deleted file mode 100644 index bb34d66..0000000 --- a/utils/yemot/__tests__/chain.interface.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { Chain, Handler, HandlerBase, IHandler } from "../chain.interface"; -import { YemotRequest, YemotResponse } from "../yemot.interface"; -import { MockYemotRequest } from "./yemot.interface.spec"; - -const req = new MockYemotRequest({} as any, {} as any); -const res = new YemotResponse(); - -describe('Chain', () => { - - // Given a Chain instance with one handler, when calling handleRequest with a YemotRequest and YemotResponse, then the handler should be called and callback should be called - it('should call handler and callback', (done) => { - const chain = new Chain(); - const handler: IHandler = { - handleRequest: jest.fn().mockImplementation((req, res, callback) => { - callback(true); - }) - }; - chain.addHandler(handler); - - chain.handleRequest(req, res, () => { - expect(handler.handleRequest).toHaveBeenCalledTimes(1); - done(); - }); - }); - - // Given a Chain instance with multiple handlers, when calling handleRequest with a YemotRequest and YemotResponse, then each handler should be called in order and callback should be called - it('should call each handler in order and callback', (done) => { - const chain = new Chain(); - const handler1: IHandler = { - handleRequest: jest.fn().mockImplementation((req, res, callback) => { - callback(false); - }) - }; - const handler2: IHandler = { - handleRequest: jest.fn().mockImplementation((req, res, callback) => { - callback(true); - }) - }; - chain.addHandler(handler1); - chain.addHandler(handler2); - - chain.handleRequest(req, res, () => { - expect(handler1.handleRequest).toHaveBeenCalledTimes(1); - expect(handler2.handleRequest).toHaveBeenCalledTimes(1); - done(); - }); - }); - - // Given a Chain instance with no handlers, when calling handleRequest with a YemotRequest and YemotResponse, then callback should be called - it('should call callback when no handlers', (done) => { - const chain = new Chain(); - - chain.handleRequest(req, res, () => { - done(); - }); - }); - - // Given a Chain instance with a handler that throws an error, when calling handleRequest with a YemotRequest and YemotResponse, then the error should be propagated and callback should not be called - it('should propagate error when handler throws an error', (done) => { - const chain = new Chain(); - const handler: IHandler = { - handleRequest: jest.fn().mockImplementation((req, res, callback) => { - throw new Error('Handler error'); - }) - }; - chain.addHandler(handler); - - expect(() => { - return chain.handleRequest(req, res, () => { - done.fail('Callback should not be called'); - }); - }).rejects.toThrowError('Handler error'); - - expect(handler.handleRequest).toHaveBeenCalledTimes(1); - done(); - }); - - it('should call callback when no handlers', (done) => { - class MockHandler extends HandlerBase { } - - const handler = new MockHandler(); - const chain = new Chain(); - chain.addHandler(handler); - const next = jest.fn(); - - chain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalledTimes(1); - done(); - }); - - it('should use handler class', (done) => { - const handle = jest.fn(); - const handler = new Handler(handle); - expect(handler.handleRequest).toBe(handle); - done(); - }); -}); diff --git a/utils/yemot/__tests__/yemot.interface.spec.ts b/utils/yemot/__tests__/yemot.interface.spec.ts index ede582a..8972224 100644 --- a/utils/yemot/__tests__/yemot.interface.spec.ts +++ b/utils/yemot/__tests__/yemot.interface.spec.ts @@ -1,39 +1,4 @@ -import { DataSource, getRepository } from "typeorm"; -import { FormatString, YEMOT_HANGUP_STEP, YemotProcessor, YemotRequest, YemotResponse } from "../yemot.interface"; -import { YemotCall, YemotParams } from "@shared/entities/YemotCall.entity"; -import { TextByUser } from "@shared/view-entities/TextByUser.entity"; -import { User } from "@shared/entities/User.entity"; -import util from "../yemot.util"; - -export class MockYemotRequest extends YemotRequest { - constructor(activeCall: any, dataSource: any) { - super(activeCall, dataSource); - } - getLessonFromLessonId(lessonId: number) { - return {} as any; - } - getKlassByKlassId(klassKey: number, klassId?: number) { - return {} as any; - } - getTeacherByPhone(phone: string) { - return {} as any; - } - getStudentsByKlassId(klassId: number) { - return [] as any; - } - saveReport(reportData: any, type: any) { - return {} as any; - } - async getExistingAttReports(klassId: string, lessonId: string, sheetName: string): Promise { - return []; - } - async getExistingGradeReports(klassId: string, lessonId: string, sheetName: string): Promise { - return []; - } - deleteExistingReports(existingReports: any[], type: any) { - return {} as any; - } -} +import { FormatString } from "../yemot.interface"; describe('FormatString', () => { it('should replace placeholders with values', () => { @@ -46,140 +11,3 @@ describe('FormatString', () => { expect(result).toBe("Hello World!"); }); }); - -export const getMockDataSource = () => ({ - getRepository: jest.fn().mockReturnValue({ - findOne: jest.fn(), - findOneByOrFail: jest.fn(), - findOneBy: jest.fn(), - find: jest.fn(), - findBy: jest.fn(), - create: jest.fn(), - save: jest.fn(), - delete: jest.fn(), - }) -} as unknown as DataSource); - -class MockYemotProcessor extends YemotProcessor { - processCall(activeCall: YemotCall, body: YemotParams): Promise { - throw new Error("Method not implemented."); - } - - getTextPublic(userId: number, textKey: string, ...args): Promise { - return this.getText(userId, textKey, ...args); - } -} - -describe('YemotProcessor', () => { - let dataSource: DataSource; - let yemotProcessor: MockYemotProcessor; - - beforeEach(() => { - dataSource = getMockDataSource(); - yemotProcessor = new MockYemotProcessor(dataSource); - }); - - it('should return formatted text for a given user and text key', async () => { - const userId = 1; - const textKey = "greeting"; - const args = ["John"]; - const textValue = "Hello {0}"; - - // Mock the database call - jest.spyOn(dataSource.getRepository(TextByUser), 'findOne').mockResolvedValue({ value: textValue } as TextByUser); - - const result = await yemotProcessor.getTextPublic(userId, textKey, ...args); - expect(result).toBe("Hello John"); - }); - - it('should handle cases where textKey does not exist', async () => { - const userId = 1; - const textKey = "nonexistent"; - - // Mock the database call - jest.spyOn(dataSource.getRepository(TextByUser), 'findOne').mockResolvedValue(null); - - const result = await yemotProcessor.getTextPublic(userId, textKey); - expect(result).toBe(textKey); - }); -}); - -describe('YemotRequest', () => { - let dataSource: DataSource; - let yemotRequest: YemotRequest; - let activeCall: YemotCall; - - beforeEach(() => { - dataSource = getMockDataSource(); - activeCall = new YemotCall(); - activeCall.userId = 1; - yemotRequest = new MockYemotRequest(activeCall, dataSource); - }); - - it('should return the correct userId from the active call', () => { - const result = yemotRequest.getUserId(); - expect(result).toBe(1); - }); - - it('should return user permissions for the given userId', async () => { - const user = { id: 1, permissions: ["READ", "WRITE"] }; - - // Mock the database call - jest.spyOn(yemotRequest, 'getUser').mockResolvedValue(user as User); - - const result = await yemotRequest.getUserPermissions(); - expect(result).toEqual(["READ", "WRITE"]); - }); -}); - -describe('YemotResponse', () => { - let dataSource: DataSource; - let yemotResponse: YemotResponse; - - beforeEach(() => { - dataSource = getMockDataSource(); - yemotResponse = new YemotResponse(dataSource, 1); - }); - - it('should return the correct formatted text for a given text key', async () => { - const textKey = "greeting"; - const args = ["John"]; - const textValue = "Hello {0}"; - - // Mock the database call - jest.spyOn(dataSource.getRepository(TextByUser), 'findOne').mockResolvedValue({ value: textValue } as TextByUser); - - const result = await yemotResponse.getText(textKey, ...args); - expect(result).toBe("Hello John"); - }); - - it('should return the correct hangup step', () => { - const result = yemotResponse.hangup(); - expect(result).toBe(YEMOT_HANGUP_STEP); - }); - - it('should clear all messages', () => { - yemotResponse.send("Test message"); - yemotResponse.clear(); - expect(yemotResponse.messages.length).toBe(0); - }); - - it('should correctly send a message with given parameters and options', () => { - yemotResponse.send("Test message", "param1", { option: "value" }); - expect(yemotResponse.messages.length).toBe(1); - expect(yemotResponse.messages[0]).toEqual({ text: "Test message", param: "param1", options: { option: "value" } }); - }); - - it('should correctly send a message with given parameters', async () => { - yemotResponse.send(yemotResponse.hangup()); - expect(yemotResponse.messages.length).toBe(1); - const response = await yemotResponse.getResponse(); - expect(response).toBe(util.send(util.hangup())); - }); - - it('should get the key for the text if not found', async () => { - jest.spyOn(dataSource.getRepository(TextByUser), 'findOne').mockResolvedValue(null); - const result = await yemotResponse.getText("test"); - expect(result).toBe("test"); - }); -}); diff --git a/utils/yemot/__tests__/yemot.service.spec.ts b/utils/yemot/__tests__/yemot.service.spec.ts deleted file mode 100644 index ca3a150..0000000 --- a/utils/yemot/__tests__/yemot.service.spec.ts +++ /dev/null @@ -1,435 +0,0 @@ -// Generated by CodiumAI - -import { YemotParams } from "@shared/entities/YemotCall.entity"; -import { YemotService } from "../yemot.service"; -import yemotUtil from "../yemot.util"; -import { MockYemotRequest } from "./yemot.interface.spec"; - -describe('YemotService', () => { - let mockRepo: any; - let mockUserRepo: any; - let mockDataSource: any; - let mockYemotChain: any; - let body: YemotParams; - - beforeEach(() => { - mockRepo = { - findOne: jest.fn().mockResolvedValue({ - isOpen: true, - history: [], - data: body, - currentStep: 'placeholder', - }), - create: jest.fn().mockResolvedValue({}), - save: jest.fn().mockResolvedValue({}), - }; - mockUserRepo = { - findOneBy: jest.fn().mockResolvedValue({}), - }; - mockDataSource = {}; - mockYemotChain = { - handleRequest: jest.fn().mockImplementation((req, res, next) => next()), - }; - body = { - ApiCallId: "754b9ce7c434ea952f2ed99671c274fee143165a", - ApiYFCallId: "9da82d44-c071-4c61-877b-1680d75968e6", - ApiDID: "035586526", - ApiRealDID: "035586526", - ApiPhone: "0527609942", - ApiExtension: "", - ApiTime: "1669485562", - reportDateType: "2", - reportDate: "10112022", - reportDateConfirm: "1", - questionAnswer: "1", - howManyLessons: "2", - howManyWatchOrIndividual: "1", - howManyTeachedOrInterfering: "0", - wasKamal: "0", - howManyDiscussingLessons: "1", - } as any as YemotParams; - }); - - // handle a call with valid body - it('should handle a call with valid body', async () => { - // Mock dependencies - - const mockRepo = { - findOne: jest.fn().mockResolvedValue(null), - create: jest.fn().mockReturnValue({}), - save: jest.fn().mockResolvedValue({}), - } as any; - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Define test data - - // Invoke the method under test - await yemotService.handleCall(body); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: body.ApiCallId, - }, - }); - expect(mockRepo.create).toHaveBeenCalledWith({ - user: expect.any(Object), - apiCallId: body.ApiCallId, - phone: body.ApiPhone, - isOpen: true, - history: [], - data: body, - currentStep: 'placeholder', - }); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).toHaveBeenCalled(); - }); - - // handle a call with existing active call - it('should handle a call with existing active call', async () => { - // Mock dependencies - const mockRepo = { - findOne: jest.fn().mockResolvedValue({}), - create: jest.fn().mockReturnValue({}), - save: jest.fn().mockResolvedValue({}), - } as any; - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Define test data - - // Invoke the method under test - await yemotService.handleCall(body); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: body.ApiCallId, - }, - }); - expect(mockRepo.create).not.toHaveBeenCalled(); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).toHaveBeenCalled(); - }); - - // should handle a call with a hangup signal - it('should handle a call with a hangup signal', async () => { - // Mock dependencies - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Define test data - - // Invoke the method under test - await yemotService.handleCall({ ...body, hangup: 'true' }); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: body.ApiCallId, - }, - }); - expect(mockRepo.create).not.toHaveBeenCalled(); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).not.toHaveBeenCalled(); - }); - - // should handle call with duplicate values - it('should handle call with duplicate values', async () => { - // Mock dependencies - mockRepo = { - findOne: jest.fn().mockResolvedValue(null), - create: jest.fn().mockReturnValue({}), - save: jest.fn().mockResolvedValue({}), - } as any; - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Define test data - body = { - ApiCallId: "754b9ce7c434ea952f2ed99671c274fee143165a", - ApiYFCallId: "9da82d44-c071-4c61-877b-1680d75968e6", - ApiDID: "035586526", - ApiRealDID: "035586526", - ApiPhone: "0527609942", - ApiExtension: "", - ApiTime: "1669485562", - reportDateType: ["2", "1"], - reportDate: "10112022", - reportDateConfirm: "1", - questionAnswer: "1", - howManyLessons: "2", - howManyWatchOrIndividual: "1", - howManyTeachedOrInterfering: "0", - wasKamal: "0", - howManyDiscussingLessons: "1", - } as any as YemotParams; - - // Invoke the method under test - await yemotService.handleCall(body); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: body.ApiCallId, - }, - }); - expect(mockRepo.create).toHaveBeenCalledWith({ - user: expect.any(Object), - apiCallId: body.ApiCallId, - phone: body.ApiPhone, - isOpen: true, - history: [], - data: body, - currentStep: 'placeholder', - }); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).toHaveBeenCalled(); - }); - - // should handle call with empty body - it('should handle call with empty body', async () => { - // Mock dependencies - mockRepo = { - findOne: jest.fn().mockResolvedValue(null), - create: jest.fn().mockReturnValue({}), - save: jest.fn().mockResolvedValue({}), - } as any; - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Define test data - - // Invoke the method under test - await expect(yemotService.handleCall({} as YemotParams)).resolves.toEqual(yemotUtil.send( - yemotUtil.id_list_message_v2('שגיאה'), - yemotUtil.hangup(), - )); - }); - - // handle a call with valid body and no active call - it('should handle a call with valid body and no active call', async () => { - // Mock dependencies - mockRepo.findOne.mockResolvedValue(null); - mockRepo.create.mockReturnValue({}); - mockRepo.save.mockResolvedValue({}); - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Invoke the method under test - await yemotService.handleCall(body); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: body.ApiCallId, - }, - }); - expect(mockRepo.create).toHaveBeenCalledWith({ - user: expect.any(Object), - apiCallId: body.ApiCallId, - phone: body.ApiPhone, - isOpen: true, - history: [], - data: body, - currentStep: 'placeholder', - }); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).toHaveBeenCalled(); - }); - - // handle a call with existing active call - it('should handle a call with existing active call', async () => { - // Mock dependencies - mockRepo.findOne.mockResolvedValue({}); - mockRepo.create.mockReturnValue({}); - mockRepo.save.mockResolvedValue({}); - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Invoke the method under test - await yemotService.handleCall(body); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: body.ApiCallId, - }, - }); - expect(mockRepo.create).not.toHaveBeenCalled(); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).toHaveBeenCalled(); - }); - - // handle a call with a hangup signal - it('should handle a call with a hangup signal', async () => { - // Mock dependencies - mockRepo.findOne.mockResolvedValue({ - isOpen: true, - history: [], - data: body, - currentStep: 'placeholder', - }); - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Invoke the method under test - await yemotService.handleCall({ ...body, hangup: 'true' }); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: body.ApiCallId, - }, - }); - expect(mockRepo.create).not.toHaveBeenCalled(); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).not.toHaveBeenCalled(); - }); - - // handle call with duplicate values - it('should handle call with duplicate values', async () => { - // Mock dependencies - mockRepo.findOne.mockResolvedValue(null); - mockRepo.create.mockReturnValue({}); - mockRepo.save.mockResolvedValue({}); - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Define test data with duplicate values - const duplicateBody = { - ...body, - reportDateType: ["2", "1"] as any, - }; - - // Invoke the method under test - await yemotService.handleCall(duplicateBody); - - // Assertions - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { - apiCallId: duplicateBody.ApiCallId, - }, - }); - expect(mockRepo.create).toHaveBeenCalledWith({ - user: expect.any(Object), - apiCallId: duplicateBody.ApiCallId, - phone: duplicateBody.ApiPhone, - isOpen: true, - history: [], - data: duplicateBody, - currentStep: 'placeholder', - }); - expect(mockRepo.save).toHaveBeenCalledWith(expect.any(Object)); - expect(mockYemotChain.handleRequest).toHaveBeenCalled(); - }); - - // handle call with empty body - it('should handle call with empty body', async () => { - // Mock dependencies - mockRepo.findOne.mockResolvedValue(null); - mockRepo.create.mockReturnValue({}); - mockRepo.save.mockResolvedValue({}); - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Invoke the method under test - await expect(yemotService.handleCall({} as YemotParams)).resolves.toEqual(yemotUtil.send( - yemotUtil.id_list_message_v2('שגיאה'), - yemotUtil.hangup(), - )); - }); - - // handle call when user is not found - it('should handle call when user is not found', async () => { - // Mock dependencies - mockRepo.findOne.mockResolvedValue(null); - mockUserRepo.findOneBy.mockResolvedValue(null); - - // Create instance of YemotService with mocked dependencies - const yemotService = new YemotService( - mockRepo, - mockUserRepo, - mockDataSource, - mockYemotChain, - MockYemotRequest, - ); - - // Invoke the method under test - await expect(yemotService.handleCall(body)).resolves.toEqual(yemotUtil.send( - yemotUtil.id_list_message_v2('מספר הטלפון עדיין לא חובר למשתמש באתר יומנט'), - yemotUtil.hangup(), - )); - }); -}); diff --git a/utils/yemot/chain.interface.ts b/utils/yemot/chain.interface.ts deleted file mode 100644 index 67b606b..0000000 --- a/utils/yemot/chain.interface.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { YemotRequest, YemotResponse } from "./yemot.interface"; - -export interface IHandler { - handleRequest: (req: YemotRequest, res: YemotResponse, callback: Function) => Promise; -} - -export class Chain implements IHandler { - constructor(private name = 'unknown', public handlers: IHandler[] = []) { } - - async handleRequest(req: YemotRequest, res: YemotResponse, callback: Function) { - let index = 0; - const next = async () => { - if (index < this.handlers.length) { - const handler = this.handlers[index]; - index++; - return handler.handleRequest(req, res, (handled: Boolean) => { - if (handled) { - return callback(); - } else { - return next(); - } - }); - } else { - return callback(); - } - }; - return next(); - } - - addHandler(handler: IHandler) { - this.handlers.push(handler); - } -} - -export abstract class HandlerBase implements IHandler { - handleRequest(req: YemotRequest, res: YemotResponse, callback: Function): any { - return callback(); - }; -} - -export class Handler extends HandlerBase { - constructor(handleRequest: IHandler['handleRequest']) { - super(); - this.handleRequest = handleRequest; - } -} \ No newline at end of file diff --git a/utils/yemot/yemot.exception.ts b/utils/yemot/yemot.exception.ts deleted file mode 100644 index f82257f..0000000 --- a/utils/yemot/yemot.exception.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { YemotCall } from "@shared/entities/YemotCall.entity"; - -export class UnexpectedHangupException extends Error { - isUnexpectedHangupException = true; - constructor(call: YemotCall) { - super(`Unexpected hangup ${call.id}, user: ${call.userId}`); - } -} - -export class UserNotFoundException extends Error { - isUserNotFoundException = true; - responseMessage = 'מספר הטלפון עדיין לא חובר למשתמש באתר יומנט'; - constructor(phoneNumber: string) { - super(`User not found for phone number ${phoneNumber}`); - } -} diff --git a/utils/yemot/yemot.interface.ts b/utils/yemot/yemot.interface.ts index 16457b2..c68adf4 100644 --- a/utils/yemot/yemot.interface.ts +++ b/utils/yemot/yemot.interface.ts @@ -1,140 +1,3 @@ -import { YemotCall, YemotParams } from "@shared/entities/YemotCall.entity"; -import { DataSource } from "typeorm"; -import util from "./yemot.util"; -import { TextByUser, getTextByUserCacheId } from "@shared/view-entities/TextByUser.entity"; -import { cacheTTL } from "@shared/config/database.config"; -import { User } from "@shared/entities/User.entity"; - -export const YEMOT_PROCCESSOR_PROVIDER = 'yemot_processor_provider'; -export const YEMOT_CHAIN = 'yemot_chain'; -export const YEMOT_REQUEST = 'yemot_request'; -export const YEMOT_HANGUP_STEP = 'hangup'; -export const YEMOT_NOT_IMPL_STEP = 'error-not-impl-step'; - -export type YemotRequestConstructor = new (activeCall: YemotCall, dataSource: DataSource) => YemotRequest; - export function FormatString(str: string, val: string[]) { return str.replace(/{([\d]*)}/g, (_, index) => val[index]); } - -export abstract class YemotProcessor { - constructor(protected dataSource: DataSource) { } - - steps: { [key: string]: string }; - params: { [key: string]: string }; - - protected async getText(userId: number, textKey: string, ...args): Promise { - const text = await this.dataSource.getRepository(TextByUser).findOne({ - where: { userId, name: textKey }, - cache: { id: getTextByUserCacheId(userId, textKey), milliseconds: cacheTTL }, - }) - const textValue = text?.value || textKey - return FormatString(textValue, args); - } - - abstract processCall(activeCall: YemotCall, body: YemotParams): Promise; -} - -export type YemotProcessorProvider = (dataSource: DataSource) => YemotProcessor; - -export abstract class YemotRequest { - constructor( - protected activeCall: YemotCall, - public dataSource: DataSource, - ) { - this.params = this.activeCall.data || {}; - } - - params: any; - - getUserId() { - return this.activeCall.userId; - } - - async getUser() { - return this.activeCall.user ?? this.dataSource.getRepository(User).findOneOrFail({ where: { id: this.activeCall.userId } }); - } - - async getUserPermissions() { - const user = await this.getUser(); - return user.permissions; - } - - abstract getLessonFromLessonId(lessonId: number): Promise; - abstract getKlassByKlassId(klassKey: number, klassId?: number): Promise; - abstract getTeacherByPhone(phone: string): Promise; - abstract getStudentsByKlassId(klassId: number): Promise; - abstract saveReport(reportData: any, type: ReportType): Promise; - abstract getExistingAttReports(klassId: string, lessonId: string, sheetName: string): Promise; - abstract getExistingGradeReports(klassId: string, lessonId: string, sheetName: string): Promise; - abstract deleteExistingReports(existingReports: any[], type: ReportType): Promise; -} - -export type ReportType = 'att' | 'grade'; -type PromiseOrSelf = T | Promise; - -interface MessageItem { - text: PromiseOrSelf; - param: string; - options: any; -} - -const invalidCharsRegex = /[\.\-'"&]/g; - -export class YemotResponse { - constructor( - private dataSource?: DataSource, - private userId?: number - ) { } - - messages: MessageItem[] = []; - - async getText(textKey: string, ...args) { - const text = await this.dataSource.getRepository(TextByUser).findOne({ - where: { - userId: this.userId, - name: textKey - }, - cache: { id: getTextByUserCacheId(this.userId, textKey), milliseconds: cacheTTL }, - }) - const textValue = text?.value || textKey - return FormatString(textValue, args)?.replace(invalidCharsRegex, ''); - } - - hangup() { - return YEMOT_HANGUP_STEP; - } - - clear() { - this.messages.length = 0; - } - - send(text: PromiseOrSelf, param: string = null, options: any = {}) { - this.messages.push({ text, param, options }); - } - - async getResponse(): Promise { - const userMessages = []; - for (const message of this.messages) { - if (typeof message.text !== 'string') { - message.text = await message.text; - } - - if (message.param) { - userMessages.push(util.read_v2(message.text, message.param, message.options)) - } else if (message.text === YEMOT_HANGUP_STEP) { - userMessages.push(util.hangup()); - } else { - userMessages.push(util.id_list_message_v2(message.text)); - } - } - console.log('userMessages:', userMessages) - return util.send(...userMessages); - } -}; - -export class YemotResponseMock extends YemotResponse { - async getText(textKey: string, ...args) { - return textKey; - } -} \ No newline at end of file diff --git a/utils/yemot/yemot.module.ts b/utils/yemot/yemot.module.ts deleted file mode 100644 index 2c6585c..0000000 --- a/utils/yemot/yemot.module.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { YemotCall } from "../../entities/YemotCall.entity"; -import { Controller, Post, Body, Module, DynamicModule } from "@nestjs/common"; -import { TypeOrmModule } from "@nestjs/typeorm"; -import { YemotService } from "./yemot.service"; -import { YEMOT_CHAIN, YemotRequestConstructor, YEMOT_REQUEST } from "./yemot.interface"; -import { User } from "@shared/entities/User.entity"; -import { Chain } from "@shared/utils/yemot/chain.interface"; - -// todo: @UseGuards(JwtAuthGuard) -@Controller('yemot') -export class YemotController { - constructor(public service: YemotService) { } - - @Post('handle-call') - async handleCall(@Body() body) { - return this.service.handleCall(body) - } -} - -@Module({}) -export class YemotModule { - static register(chain: Chain, yemotRequest: YemotRequestConstructor): DynamicModule { - return { - module: YemotModule, - imports: [TypeOrmModule.forFeature([YemotCall, User])], - providers: [ - { - provide: YEMOT_CHAIN, - useValue: chain, - }, - { - provide: YEMOT_REQUEST, - useValue: yemotRequest, - }, - YemotService, - ], - exports: [YemotService], - controllers: [YemotController], - } - } -} diff --git a/utils/yemot/yemot.service.ts b/utils/yemot/yemot.service.ts deleted file mode 100644 index 3ca8dc5..0000000 --- a/utils/yemot/yemot.service.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { Injectable, Inject, Logger } from "@nestjs/common"; -import { InjectDataSource, InjectRepository } from "@nestjs/typeorm"; -import { YemotCall, YemotParams } from "@shared/entities/YemotCall.entity"; -import { DataSource, Repository } from "typeorm"; -import { User } from "../../entities/User.entity"; -import { Chain } from "./chain.interface"; -import { YemotProcessor, YemotRequest, YemotResponse, YEMOT_CHAIN, YEMOT_HANGUP_STEP, YEMOT_REQUEST, YemotRequestConstructor } from "./yemot.interface"; -import { UnexpectedHangupException, UserNotFoundException } from "./yemot.exception"; -import yemotUtil from "./yemot.util"; - -@Injectable() -export class YemotService { - yemotProccessor: YemotProcessor; - activeCalls: Map = new Map(); - private readonly logger = new Logger(YemotService.name); - - constructor( - @InjectRepository(YemotCall) private repo: Repository, - @InjectRepository(User) private userRepo: Repository, - @InjectDataSource() private dataSource: DataSource, - @Inject(YEMOT_CHAIN) private yemotChain: Chain, - @Inject(YEMOT_REQUEST) private yemotRequest: YemotRequestConstructor, - ) { - } - - async handleCall(body: YemotParams) { - this.logger.log('start handleCall', body); - let activeCall: YemotCall; - try { - this.cleanBodyDuplicateValues(body); - activeCall = await this.getActiveCall(body); - if (body.hangup) { - if (activeCall.isOpen) { - throw new UnexpectedHangupException(activeCall); - } else { - this.closeCall(activeCall, body); - } - } else { - const { req, res } = this.getHandlerObjects(activeCall, body); - await this.yemotChain.handleRequest(req, res, () => { - // nothing here, I guess - }) - const response = await res.getResponse(); - this.saveStep(activeCall, body, response); - return response; - } - } - catch (e) { - let errorResponse = e.responseMessage ?? 'שגיאה'; - this.logger.log(`an error has occured in yemot_call: ${e.message}`); - this.logger.log(`stack: ${e.stack}`); - if (activeCall) { - activeCall.isOpen = false; - activeCall.hasError = true; - activeCall.errorMessage = e.message; - this.repo.save(activeCall); - } - return yemotUtil.send( - yemotUtil.id_list_message_v2(errorResponse), - yemotUtil.hangup(), - ); - } - finally { - this.logger.log('end handleCall', body); - } - } - - getHandlerObjects(activeCall: YemotCall, body: YemotParams) { - const req: YemotRequest = new this.yemotRequest(activeCall, this.dataSource); - const res: YemotResponse = new YemotResponse(this.dataSource, activeCall.userId); - return { req, res }; - } - - private cleanBodyDuplicateValues(body: YemotParams) { - for (const key in body) { - const value = body[key]; - if (Array.isArray(value)) { - body[key] = value[value.length - 1]; - } - } - } - - private async getActiveCall(body: YemotParams) { - let call: YemotCall; - if (this.activeCalls.has(body.ApiCallId)) { - call = this.activeCalls.get(body.ApiCallId); - } else { - call = await this.repo.findOne({ - where: { - apiCallId: body.ApiCallId - } - }); - } - if (call) { - this.activeCalls.set(body.ApiCallId, call); - call.data = { ...call.data, ...body }; - return call; - } - const userFilter = { - phoneNumber: body.ApiDID - }; - const user = await this.userRepo.findOneBy(userFilter); - if (!user) { - throw new UserNotFoundException(body.ApiDID); - } - return this.repo.create({ - user, - apiCallId: body.ApiCallId, - phone: body.ApiPhone, - isOpen: true, - history: [], - data: body, - currentStep: 'placeholder' - }) - } - - private saveStep(activeCall: YemotCall, body: YemotParams, response: string) { - activeCall.history.push({ - params: body, - response, - time: new Date(), - }) - if (response.includes(YEMOT_HANGUP_STEP)) { - activeCall.isOpen = false; - } - setTimeout(() => this.repo.save(activeCall)); - } - - private async closeCall(activeCall: YemotCall, body: YemotParams) { - activeCall.history.push({ - params: body, - response: YEMOT_HANGUP_STEP, - time: new Date(), - }) - await this.repo.save(activeCall); - this.activeCalls.delete(body.ApiCallId); - } -} \ No newline at end of file diff --git a/utils/yemot/yemot.util.ts b/utils/yemot/yemot.util.ts deleted file mode 100644 index 6f4af6b..0000000 --- a/utils/yemot/yemot.util.ts +++ /dev/null @@ -1,96 +0,0 @@ -const util = { - send(...params) { - const messages = Array.prototype.filter.call(arguments, item => item); - const response = Array.prototype.join.call(messages, '&'); - - return response; - }, - - read(message, param, mode = 'tap', options = {}) { - return `read=${getMessage(message)}=${getReadDef(param, mode, options)}`; - }, - go_to_folder(folder) { - return `go_to_folder=/${folder}`; - }, - id_list_message(message) { - return `id_list_message=${getMessage(message)}.`; - }, - routing_yemot(route) { - return `routing_yemot=${route}`; - }, - hangup() { - return `go_to_folder=hangup`; - }, - - id_list_message_v2(text) { - return util.id_list_message({ type: 'text', text }); - }, - read_v2(text, param, options = {}) { - return util.read({ type: 'text', text }, param, 'tap', options); - } -} - -export default util; - -const messageType = { - "file": "f", - "text": "t", - "speech": "s", - "digits": "d", - "number": "n", - "alpha": "a" -}; - -function getMessage(message) { - if (Array.isArray(message)) - return message.map(getMessage).join('.'); - - return `${messageType[message.type]}-${message.text}`; -} - -function getReadDef(param, mode, options) { - let res = [param]; - switch (mode) { - case 'tap': - res.push(options.use_previous_if_exists ? "yes" : "no"); - res.push(options.max || "*"); - res.push(options.min || "1"); - res.push(options.sec_wait || 7); - res.push(options.play_ok_mode || "No"); - res.push(options.block_asterisk ? "yes" : "no"); - res.push(options.block_zero ? "yes" : "no"); - res.push(options.replace_char || ""); - res.push(options.digits_allowed ? options.digits_allowed.join(".") : ""); // [1, 14] - res.push(options.amount_attempts || ""); - res.push(options.read_none ? "Ok" : "no"); - res.push(options.read_none_var || ""); - break; - - case "record": - res.push(options.use_previous_if_exists ? "yes" : "no"); - res.push("record"); - res.push(options.path || ""); - res.push(options.file_name || ""); - res.push(options.record_ok === false ? "no" : "yes"); - res.push(options.record_hangup ? "yes" : "no"); - res.push(options.record_attach ? "yes" : "no"); - res.push(options.lenght_min || ""); - res.push(options.lenght_max || ""); - break; - - case "voice": - res.push(options.use_previous_if_exists ? "yes" : "no"); - res.push("voice"); - res.push(options.lang || ""); - res.push(options.allow_typing ? "yes" : "no"); - res.push(options.max_typing_digits || ""); - res.push(options.record_engine ? "record" : ""); - res.push(options.lenght_min || ""); - res.push(options.lenght_max || ""); - break; - - default: - break; - } - return res.join(','); -} From c95f8eb06a229bd323405b474b6071adabbd7138 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 11 Oct 2026 20:34:59 +0000 Subject: [PATCH 2/2] docs: record v1 Yemot removal in CONSUMER_CHANGES.md Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WhKqWQTBUpM1iambUHayry --- CONSUMER_CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONSUMER_CHANGES.md b/CONSUMER_CHANGES.md index af379d1..515d979 100644 --- a/CONSUMER_CHANGES.md +++ b/CONSUMER_CHANGES.md @@ -11,3 +11,4 @@ submodule bump — each needs a matching change in the consuming app. | `8ffe995` | `handle-email` webhook now guarded by `MailWebhookGuard` (checks `X-Webhook-Secret` header against `MAIL_WEBHOOK_SECRET`); Yemot gets a second, per-user-token-secured mount at `/yemot/handle-call/:secret` alongside the existing open one | Set `MAIL_WEBHOOK_SECRET` in `server/.env` and have n8n send that value as `X-Webhook-Secret` on its request to `handle-email` (no-op / stays open until this is set). No env var needed for Yemot — the per-user token is generated automatically and shown on the client's Tutorial page once `nra-client`'s matching change lands; users need to update their `ext.ini` to the new URL (old one keeps working during migration) | all 5 apps | | `28a61f5` | `TestAppHelper` now wires `cookie-parser` itself; `utils/testing/e2e/test-utils.ts` adds `registerAndAuthenticate()` (register a test user + guarded Authentication-cookie extraction) and `asList()` (normalizes a CRUD list response that may be a plain array or `{ data: [...] }`) | Not required to keep working (purely additive), but each app's `server/test/*-crud.e2e-spec.ts` should swap its hand-rolled `Test.createTestingModule`/cookie-parser/cookie-regex/teardown boilerplate for `createTestApp()` + `registerAndAuthenticate()` + `asList()` to drop the duplication | react-admin-nestjs, event-management-nra, teacher-report-nra, student-report-nra, dnd-management-nra | | `e876588` | Async job queue + scheduler (`JobsModule` in `BaseNraAppModule`, `Job`/`Schedule` entities) | Add `@nestjs/schedule` and `cron-parser` to `server/package.json`; add a migration creating the `jobs` and `schedules` tables; to actually process jobs on an instance, set `WORKER_ENABLED=true` (optionally `JOB_POLL_MS`, `JOB_WORKER_BATCH`) | all 5 apps, form-call | +| `e8c4d1b` | Removed unused v1 Yemot flow (`utils/yemot/yemot.module.ts`, `yemot.service.ts`, `chain.interface.ts`, `yemot.util.ts`, `yemot.exception.ts`; `yemot.interface.ts` now exports only `FormatString`). All apps already use v2 (`BaseYemotHandlerService`) | Confirm `server/src` imports none of the removed files (`grep -rn "utils/yemot/" server/src` — only `v2/`, `testing` and `FormatString` from `yemot.interface` may remain). Copy `.github/skills/yemot-integration/SKILL.md` from `multi-repo-codespace` so the skill points at v2 only | react-admin-nestjs |