diff --git a/server/src/__tests__/app.module.spec.ts b/server/src/__tests__/app.module.spec.ts index 49f70f96..02657096 100644 --- a/server/src/__tests__/app.module.spec.ts +++ b/server/src/__tests__/app.module.spec.ts @@ -8,7 +8,7 @@ import { TypeOrmModule } from '@nestjs/typeorm'; import { RequestContextModule } from 'nestjs-request-context'; import { LoggerModule } from 'nestjs-pino'; import { AuthModule } from '@shared/auth/auth.module'; -import { YemotModule } from '@shared/utils/yemot/yemot.module'; +import { YemotModule } from '@shared/utils/yemot/v2/yemot.module'; import { MailSendModule } from '@shared/utils/mail/mail-send.module'; import { EntitiesModule } from '../entities.module'; import { getPinoConfig } from '@shared/config/pino.config'; diff --git a/server/src/app.module.ts b/server/src/app.module.ts index 14d5526c..93354ed5 100644 --- a/server/src/app.module.ts +++ b/server/src/app.module.ts @@ -8,10 +8,8 @@ import { RequestContextModule } from 'nestjs-request-context'; import { LoggerModule } from 'nestjs-pino'; import { typeOrmModuleConfig } from '@shared/config/typeorm.config'; import { AuthModule } from '@shared/auth/auth.module'; -import { YemotModule } from '@shared/utils/yemot/yemot.module'; -// import { yemotProcessorProvider } from 'src/yemot.processor'; -import yemotChain from './yemot/yemot.chain'; -import { YemotRequestImpl } from './yemot/yemot.request.impl'; +import { YemotModule } from '@shared/utils/yemot/v2/yemot.module'; +import { YemotHandlerService } from './yemot-handler.service'; import { MailSendModule } from '@shared/utils/mail/mail-send.module'; import { EntitiesModule } from './entities.module'; import { getPinoConfig } from '@shared/config/pino.config'; @@ -30,7 +28,7 @@ import { UserInitializationService } from './user-initialization.service'; imports: [UserInitModule], userInitServiceType: UserInitializationService, }), - YemotModule.register(yemotChain, YemotRequestImpl), + YemotModule.register(YemotHandlerService), ], controllers: [AppController], providers: [ diff --git a/server/src/main.ts b/server/src/main.ts index 320e8803..25d56272 100644 --- a/server/src/main.ts +++ b/server/src/main.ts @@ -5,6 +5,7 @@ import * as bodyParser from 'body-parser'; import * as cookieParser from 'cookie-parser'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { Logger, LoggerErrorInterceptor } from 'nestjs-pino'; +import { YemotRouterService } from '@shared/utils/yemot/v2/yemot-router.service'; async function bootstrap() { const app = await NestFactory.create(AppModule); @@ -38,6 +39,9 @@ async function bootstrap() { app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); app.use(cookieParser()); + const yemotRouterSvc = app.get(YemotRouterService); + app.use('/yemot/handle-call', yemotRouterSvc.getRouter()); + await app.listen(3000); } bootstrap(); diff --git a/server/src/yemot-handler.service.ts b/server/src/yemot-handler.service.ts new file mode 100644 index 00000000..a5f838fb --- /dev/null +++ b/server/src/yemot-handler.service.ts @@ -0,0 +1,16 @@ +import { Injectable } from '@nestjs/common'; +import { BaseYemotHandlerService } from '@shared/utils/yemot/v2/yemot-router.service'; + +/** + * Yemot Handler Service for processing incoming Yemot calls + * Currently returns a maintenance mode message + */ +@Injectable() +export class YemotHandlerService extends BaseYemotHandlerService { + override async processCall(): Promise { + this.logger.log(`Processing call with ID: ${this.call.callId} from phone: ${this.call.phone}`); + + // Return maintenance mode message + this.hangupWithMessage('המערכת במצב תחזוקה, אנא נסה שוב מאוחר יותר'); + } +} diff --git a/server/src/yemot/__tests__/attReport.chain.spec.ts b/server/src/yemot/__tests__/attReport.chain.spec.ts deleted file mode 100644 index 6c2bcd5e..00000000 --- a/server/src/yemot/__tests__/attReport.chain.spec.ts +++ /dev/null @@ -1,443 +0,0 @@ -import getReportChain, { IReportProperty } from "../attReport.chain"; -import { YemotRequest, YemotResponse, YemotResponseMock } from "@shared/utils/yemot/yemot.interface"; -import util from "@shared/utils/yemot/yemot.util"; - -describe("attReport chain", () => { - let req: YemotRequest; - let res: YemotResponse; - let next: jest.Mock; - let chain: ReturnType; - const getExistingReports = jest.fn().mockResolvedValue([]); - const properties: IReportProperty[] = [ - { - name: 'absCount', - message: 'absCount', - field: 'abs_count', - validate(req: YemotRequest) { - return req.params.absCount >= 0 && req.params.absCount <= req.params.howManyLessons; - } - } - ] - - beforeEach(() => { - req = { - params: { - userId: "user123", - klass: { data: { id: "klass123" } }, - lesson: { data: { id: "lesson123" } }, - isCurrentMonth: "1", - }, - getUser: jest.fn(), - } as unknown as YemotRequest; - - res = new YemotResponseMock(); - jest.spyOn(res, 'send'); - - next = jest.fn(); - - chain = getReportChain(getExistingReports, 'att', properties); - }); - - describe("GetSheetNameHandler", () => { - beforeEach(() => { - chain.handlers.length = 1; - }); - - it("should call next if sheetName is already defined", () => { - req.params.sheetName = "someSheetName"; - - chain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalled(); - expect(res.send).not.toHaveBeenCalled(); - expect(req.params.sheetName).toEqual("someSheetName"); - }); - - it("should ask if current month if isCurrentMonth is not defined", async () => { - req.params.isCurrentMonth = undefined; - - chain.handleRequest(req, res, next); - - const response = await res.getResponse(); - expect(response).toEqual(util.read_v2("askIsCurrentMonth", "isCurrentMonth")); - expect(next).not.toHaveBeenCalled(); - }); - - it("should set sheetName to current month if isCurrentMonth is '1'", () => { - chain.handleRequest(req, res, next); - - expect(res.send).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - expect(req.params.sheetName).toEqual(expect.any(String)); - }); - - it("should ask for current month if isCurrentMonth is not '1'", async () => { - req.params.isCurrentMonth = "0"; - - chain.handleRequest(req, res, next); - - const response = await res.getResponse(); - expect(response).toEqual(util.read_v2("askForCurrentMonth", "currentMonth")); - expect(next).not.toHaveBeenCalled(); - }); - - it("should set sheetName to requested month if currentMonth is defined", () => { - req.params.currentMonth = "3"; - - chain.handleRequest(req, res, next); - - expect(res.send).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - expect(req.params.sheetName).toEqual(expect.any(String)); - }); - - it("should call next if sheetName is not defined", async () => { - req.params.sheetName = undefined; - req.params.isCurrentMonth = '2'; - req.params.currentMonth = '3'; - - chain.handleRequest(req, res, next); - - const response = await res.getResponse(); - expect(response).toEqual(""); - expect(next).toHaveBeenCalled(); - }); - }); - - - describe('GetExistingReportsHandler', () => { - beforeEach(() => { - req.params.sheetName = 'someSheetName'; - chain.handlers.length = 2; - getExistingReports.mockClear(); - }); - - it('should call getExistingReports if existingReports param is not defined', async () => { - await chain.handleRequest(req, res, next); - - expect(getExistingReports).toHaveBeenCalledWith(req, req.params.klass.data.id, req.params.lesson.data.id, req.params.sheetName); - expect(next).toHaveBeenCalled(); - expect(req.params.existingReports).toEqual(expect.any(Array)); - }); - - it('should not call getExistingReports if existingReports param is already defined', async () => { - req.params.existingReports = []; - - await chain.handleRequest(req, res, next); - - expect(getExistingReports).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - }); - }); - - describe('CheckExistingReportsHandler', () => { - beforeEach(() => { - req.params.sheetName = 'someSheetName'; - req.params.existingReports = [{ studentReferenceId: '123' }, { studentReferenceId: '456' }]; - chain.handlers.length = 3; - }); - - it('should ask if skip existing reports if existingReports has items and isSkipExistingReports is not defined', async () => { - await chain.handleRequest(req, res, next); - - const response = await res.getResponse(); - expect(response).toEqual(util.read_v2("askIfSkipExistingReports", "isSkipExistingReports")); - expect(next).not.toHaveBeenCalled(); - }); - - it('should not ask if skip existing reports if existingReports is empty', async () => { - req.params.existingReports = []; - - await chain.handleRequest(req, res, next); - - expect(res.send).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - }); - - it('should not ask if skip existing reports if isSkipExistingReports is already defined', async () => { - req.params.isSkipExistingReports = true; - - await chain.handleRequest(req, res, next); - - expect(res.send).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - }); - - it('should create idsToSkip set if isSkipExistingReports is "1"', async () => { - req.params.isSkipExistingReports = '1'; - - await chain.handleRequest(req, res, next); - - expect(req.params.idsToSkip).toEqual(['123', '456']); - expect(next).toHaveBeenCalled(); - }); - - it('should create an empty idsToSkip set if isSkipExistingReports is not "1"', async () => { - req.params.isSkipExistingReports = '0'; - - await chain.handleRequest(req, res, next); - - expect(req.params.idsToSkip).toEqual([]); - expect(next).toHaveBeenCalled(); - }); - }); - - describe('CheckHowManyLessonsHandler', () => { - beforeEach(() => { - req.params.sheetName = 'someSheetName'; - req.params.existingReports = []; - chain.handlers.length = 4; - }); - - it("call next if reportType is 'grade'", async () => { - const chain = getReportChain(getExistingReports, 'grade', properties); - chain.handlers.length = 4; - - await chain.handleRequest(req, res, next); - - expect(res.send).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - }); - - - it('should ask for how many lessons if howManyLessons param is not defined', async () => { - await chain.handleRequest(req, res, next); - - const response = await res.getResponse(); - expect(response).toEqual(util.read_v2("howManyLessons", "howManyLessons")); - expect(next).not.toHaveBeenCalled(); - }); - - it('should ask for how many lessons if howManyLessons param is "0"', async () => { - req.params.howManyLessons = '0'; - - await chain.handleRequest(req, res, next); - - const response = await res.getResponse(); - expect(response).toEqual(util.send( - util.id_list_message_v2("tryAgain"), - util.read_v2("howManyLessons", "howManyLessons") - )); - expect(next).not.toHaveBeenCalled(); - }); - - it('should call next if howManyLessons is defined', async () => { - req.params.howManyLessons = '10'; - - await chain.handleRequest(req, res, next); - - expect(res.send).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - }); - }); - - describe('should load student list', () => { - beforeEach(() => { - req.params.sheetName = 'someSheetName'; - req.params.existingReports = []; - req.params.howManyLessons = 2; - req.params.baseReport = { - userId: req.params.userId, - teacherReferenceId: 'teacher1', - klassReferenceId: req.params.klass.data.id, - lessonReferenceId: req.params.lesson.data.id, - reportDate: new Date(), - }; - chain.handlers.length = 5; - next.mockClear(); - }); - - it('should not load student list if already defined', async () => { - // Arrange - req.params.students = [{ tz: '111111111' }, { tz: '222222222' }]; - - // Act - await chain.handleRequest(req, res, next); - - // Assert - expect(res.send).not.toHaveBeenCalled(); - expect(req.params.students).toEqual([{ tz: '111111111' }, { tz: '222222222' }]); - expect(next).toHaveBeenCalled(); - }); - - it('should load student list if not defined and idsToSkip is empty set', async () => { - // Arrange - req.params.students = undefined; - req.params.idsToSkip = []; - req.getStudentsByKlassId = jest.fn().mockResolvedValue([{ tz: '111111111' }, { tz: '222222222' }]); - - // Act - await chain.handleRequest(req, res, next); - - // Assert - expect(res.send).not.toHaveBeenCalled(); - expect(req.getStudentsByKlassId).toHaveBeenCalledWith(req.params.baseReport.klassReferenceId); - expect(req.params.students).toEqual([{ tz: '111111111' }, { tz: '222222222' }]); - expect(next).toHaveBeenCalled(); - }); - - it('should load student list if not defined and idsToSkip is filled set', async () => { - // Arrange - req.params.students = undefined; - req.params.idsToSkip = ['333333333']; - req.getStudentsByKlassId = jest.fn().mockResolvedValue([{ id: '111111111' }, { id: '222222222' }, { id: '333333333' }]); - - // Act - await chain.handleRequest(req, res, next); - - // Assert - expect(res.send).not.toHaveBeenCalled(); - expect(req.getStudentsByKlassId).toHaveBeenCalledWith(req.params.baseReport.klassReferenceId); - expect(req.params.students).toEqual([{ id: '111111111' }, { id: '222222222' }]); - expect(next).toHaveBeenCalled(); - }); - }); - - describe('should iterate students', () => { - beforeEach(() => { - req.params.sheetName = 'someSheetName'; - req.params.existingReports = []; - req.params.howManyLessons = 2; - req.params.baseReport = { - userId: req.params.userId, - teacherReferenceId: 'teacher1', - klassReferenceId: req.params.klass.data.id, - lessonReferenceId: req.params.lesson.data.id, - reportDate: new Date(), - }; - req.params.students = [{ tz: '111111111' }, { tz: '222222222' }, { tz: '333333333' }]; - chain.handlers.length = 6; - req.saveReport = jest.fn(); - req.deleteExistingReports = jest.fn(); - next.mockClear(); - }); - - it('when there are more students to iterate, should set the current student and call the studentChain', async () => { - await chain.handleRequest(req, res, next); - - expect(req.params.studentIndex).toBe(0); - expect(req.params.student).toEqual(req.params.students[0]); - expect(req.params.existing).toEqual([]); - expect(next).toHaveBeenCalledTimes(0); - const response = await res.getResponse(); - expect(response).toEqual(util.send( - util.id_list_message_v2("nextStudent"), - util.read_v2("absCount", "absCount") - )); - }); - - it('when there are no more students to iterate, should call the next handler', async () => { - req.params.studentIndex = 3; - - await chain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalledTimes(1); - }); - - it('when shouldNotAsk is returning true value, should not ask for absCount', async () => { - properties[0].shouldNotAsk = () => Promise.resolve(true); - - await chain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalledTimes(1); - const response = await res.getResponse(); - expect(response).toEqual(util.id_list_message_v2("nextStudent")); - delete properties[0].shouldNotAsk; - }); - - it('when there is an absCount, should validate its value', async () => { - req.params.absCount = -1; - - await chain.handleRequest(req, res, next); - - expect(req.params.absCountValidation).toBeUndefined(); - expect(next).toHaveBeenCalledTimes(0); - const response = await res.getResponse(); - expect(response).toEqual(util.send( - util.id_list_message_v2('tryAgain'), - util.read_v2("absCount", "absCount") - )); - }); - - it('when there is a large absCount, should ask again', async () => { - req.params.absCount = 3; - - await chain.handleRequest(req, res, next); - - expect(req.params.absCountValidation).toBeUndefined(); - expect(next).toHaveBeenCalledTimes(0); - const response = await res.getResponse(); - expect(response).toEqual(util.send( - util.id_list_message_v2('tryAgain'), - util.read_v2("absCount", "absCount") - )); - }); - - it('when opened a side menu, should ask for direction', async () => { - req.params.absCount = '*'; - - await chain.handleRequest(req, res, next); - - expect(req.params.absCountValidation).toBeUndefined(); - expect(next).toHaveBeenCalledTimes(0); - const response = await res.getResponse(); - expect(response).toEqual(util.read_v2("sideMenu", "sideMenu")); - }); - - it('when opened a side menu with a direction, should ask for absCount', async () => { - req.params.absCount = '*'; - req.params.sideMenu = '4'; - - await chain.handleRequest(req, res, next); - - expect(req.params.absCountValidation).toBeUndefined(); - expect(req.params.sideMenu).toBeUndefined(); - expect(next).toHaveBeenCalledTimes(0); - }); - - it('when opened a side menu with a direction, should go to next student', async () => { - req.params.absCount = '*6'; - - await chain.handleRequest(req, res, next); - - expect(req.params.studentIndex).toEqual(1); - expect(next).toHaveBeenCalledTimes(0); - const response = await res.getResponse(); - expect(response).toEqual(util.send( - util.id_list_message_v2("nextStudent"), - util.read_v2("absCount", "absCount") - )); - }); - - it('when opened a side menu with a direction, should go to prev student', async () => { - req.params.absCount = '*4'; - - await chain.handleRequest(req, res, next); - - expect(req.params.studentIndex).toEqual(0); - expect(next).toHaveBeenCalledTimes(0); - const response = await res.getResponse(); - expect(response).toEqual(util.send( - util.id_list_message_v2("nextStudent"), - util.read_v2("absCount", "absCount") - )); - }); - - it('when there is a valid absCount, should save and go to next student', async () => { - req.params.absCount = 1; - req.params.studentIndex = 0; - - await chain.handleRequest(req, res, next); - - console.log(req.params) - expect(req.params.studentIndex).toEqual(1); - expect(req.saveReport).toHaveBeenCalled(); - expect(next).toHaveBeenCalledTimes(0); - const response = await res.getResponse(); - expect(response).toEqual(util.send( - util.id_list_message_v2("nextStudent"), - util.read_v2("absCount", "absCount") - )); - }); - }); -}); diff --git a/server/src/yemot/__tests__/reportType.chain.spec.ts b/server/src/yemot/__tests__/reportType.chain.spec.ts deleted file mode 100644 index d70dbc06..00000000 --- a/server/src/yemot/__tests__/reportType.chain.spec.ts +++ /dev/null @@ -1,55 +0,0 @@ -import getReportChain from '../attReport.chain'; -import { YemotRequest, YemotResponse, YemotResponseMock } from "@shared/utils/yemot/yemot.interface"; -import getReportTypeChain from '../reportType.chain'; -import util from '@shared/utils/yemot/yemot.util'; - -async function getExistingReports(req: YemotRequest, klassId: string, lessonId: string, sheetName: string) { - return []; -} -const attReportChain = getReportChain(getExistingReports, 'att', []); -const gradeReportChain = getReportChain(getExistingReports, 'grade', []); -const reportTypeChain = getReportTypeChain(attReportChain, gradeReportChain); - -describe('reportChain', () => { - let req: YemotRequest; - let res: YemotResponse; - const next = jest.fn(); - beforeEach(() => { - req = { params: {} } as YemotRequest; - res = new YemotResponseMock(); - next.mockClear(); - }); - - it('should return askForReportType if reportType is undefined', async () => { - await reportTypeChain.handleRequest(req, res, next); - - const response = await res.getResponse(); - expect(response).toEqual(util.read_v2('getReportType', 'reportType')); - expect(next).not.toHaveBeenCalled(); - }); - - it('should use attReportChain if reportType is 1', async () => { - req.params.reportType = '1'; - const attReportChainMock = jest.spyOn(attReportChain, 'handleRequest'); - await reportTypeChain.handleRequest(req, res, next); - - expect(attReportChainMock).toHaveBeenCalled(); - expect(next).not.toHaveBeenCalled(); - }); - - it('should use gradeReportChain if reportType is 2', async () => { - req.params.reportType = '2'; - const gradeReportChainMock = jest.spyOn(gradeReportChain, 'handleRequest'); - await reportTypeChain.handleRequest(req, res, next); - - expect(gradeReportChainMock).toHaveBeenCalled(); - expect(next).not.toHaveBeenCalled(); - }); - - it('should go on if reportType is 3', async () => { - req.params.reportType = '3'; - await reportTypeChain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalled(); - }); -}); diff --git a/server/src/yemot/__tests__/resourceWithConfirmation.chain.spec.ts b/server/src/yemot/__tests__/resourceWithConfirmation.chain.spec.ts deleted file mode 100644 index c96cb8df..00000000 --- a/server/src/yemot/__tests__/resourceWithConfirmation.chain.spec.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { pascalCase } from "change-case"; -import getResourceConfirmationChain from "../resourceWithConfirmation.chain"; - -const resource = 'lesson'; -const chain = getResourceConfirmationChain(resource, req => req.getLessonFromLessonId(req.params[resource + 'Id'])); - -describe('lesson chain of responsibility', () => { - let req; - let res; - let next; - const defaultLesson = { - id: 'history101', - name: 'History 101' - }; - - beforeEach(() => { - // Reset req and res objects before each test - req = { - params: { - [resource]: { - data: undefined, - dataToConfirm: undefined, - }, - [resource + 'Id']: undefined, - [resource + 'Confirm']: undefined, - }, - getLessonFromLessonId: jest.fn().mockResolvedValue(defaultLesson), - }; - res = { - continueMock: false, - send: jest.fn(async (msg: string) => { - switch (msg) { - case `type${pascalCase(resource)}Id`: - req.params[resource + 'Id'] = defaultLesson.id; - break; - case `confirm${pascalCase(resource)}`: - req.params[resource + 'Confirm'] = '1'; - break; - } - if (res.continueMock) { - await chain.handleRequest(req, res, next); - } - }), - getText: jest.fn(key => key), - clear: jest.fn(), - }; - next = jest.fn(() => Promise.resolve()); - }); - - test('req.params[resource] is undefined, should set resource', async () =>{ - delete req.params[resource]; - - await chain.handleRequest(req, res, next); - - expect(next).not.toHaveBeenCalled(); - expect(res.send).toHaveBeenCalledWith(`type${pascalCase(resource)}Id`, resource + 'Id'); - expect(req.params[resource]).toBeDefined(); - }); - - test('lesson is defined, should early exit chain', async () => { - req.params[resource].data = defaultLesson; - - await chain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalled(); - }); - - test('lesson is confirmed, should set lesson and exit chain', async () => { - req.params[resource + 'Id'] = defaultLesson.id; - req.params[resource].dataToConfirm = defaultLesson; - req.params[resource + 'Confirm'] = '1'; - - await chain.handleRequest(req, res, next); - - expect(res.send).not.toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); - expect(req.params[resource].data).toEqual(defaultLesson); - }); - - test('lesson ID is not defined, should ask for lesson ID', async () => { - await chain.handleRequest(req, res, next); - - expect(next).not.toHaveBeenCalled(); - expect(res.send).toHaveBeenCalledWith(`type${pascalCase(resource)}Id`, resource + 'Id'); - }); - - test('lesson is found, should ask for confirmation', async () => { - req.params[resource + 'Id'] = defaultLesson.id; - - await chain.handleRequest(req, res, next); - - expect(req.params[resource].dataToConfirm).toEqual(defaultLesson); - expect(next).not.toHaveBeenCalled(); - expect(req.getLessonFromLessonId).toHaveBeenCalledWith(defaultLesson.id); - expect(res.send).toHaveBeenCalledWith(`confirm${pascalCase(resource)}`, resource + 'Confirm'); - }); - - test('req has lessonId, lesson exists but is not confirmed, user enters a new lessonId which also exists and is confirmed', async () => { - req.params[resource + 'Id'] = 'math101'; - req.params[resource].dataToConfirm = { - id: 'math101', - name: 'Mathematics 101' - }; - req.params[resource + 'Confirm'] = '0'; - res.continueMock = true; - - await chain.handleRequest(req, res, next); - - expect(res.send).toBeCalledTimes(2); - expect(res.send).toHaveBeenNthCalledWith(1, `type${pascalCase(resource)}Id`, resource + 'Id'); - expect(req.getLessonFromLessonId).toHaveBeenCalledWith(defaultLesson.id); - expect(req.params[resource].dataToConfirm).toEqual(undefined); - expect(res.send).toHaveBeenNthCalledWith(2, `confirm${pascalCase(resource)}`, resource + 'Confirm'); - expect(next).toHaveBeenCalled(); - expect(req.params[resource].data).toEqual(defaultLesson); - }); - - test('lesson is not found, should ask for lesson ID again', async () => { - req.params[resource + 'Id'] = '123'; - req.getLessonFromLessonId = jest.fn().mockReturnValueOnce(null); - - await chain.handleRequest(req, res, next); - - expect(req.params[resource].dataToConfirm).toBeFalsy(); - expect(next).not.toHaveBeenCalled(); - expect(req.getLessonFromLessonId).toHaveBeenCalledWith('123'); - expect(res.send).toHaveBeenCalledWith(`type${pascalCase(resource)}Id`, resource + 'Id'); - }); -}); \ No newline at end of file diff --git a/server/src/yemot/__tests__/teacherByPhone.chain.spec.ts b/server/src/yemot/__tests__/teacherByPhone.chain.spec.ts deleted file mode 100644 index f054e4f1..00000000 --- a/server/src/yemot/__tests__/teacherByPhone.chain.spec.ts +++ /dev/null @@ -1,56 +0,0 @@ -import teacherByPhoneChain from "../teacherByPhone.chain"; - -const chain = teacherByPhoneChain; - -describe('teacher chain of responsibility', () => { - let req; - let res; - let next; - const defaultTeacher = { - id: 'history101', - name: 'History 101' - }; - - beforeEach(() => { - // Reset req and res objects before each test - req = { - params: { - phone: undefined, - teacher: undefined, - }, - getTeacherByPhone: jest.fn().mockResolvedValue(defaultTeacher), - }; - res = { - send: jest.fn(() => Promise.resolve()), - getText: jest.fn(key => key), - hangup: jest.fn().mockReturnValue('hangup'), - }; - next = jest.fn(() => Promise.resolve()); - }); - - test('teacher is defined, should early exit chain', async () => { - req.params.teacher = defaultTeacher; - - await chain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalled(); - }); - - test('teacher is not defined and no teahcer found, should return error message', async () => { - req.getTeacherByPhone = jest.fn().mockReturnValue(null); - - await chain.handleRequest(req, res, next); - - expect(next).not.toHaveBeenCalled(); - expect(res.send).toBeCalledWith('phoneIsNotRecognizedInTheSystem'); - expect(res.send).toBeCalledWith('hangup'); - }); - - test('teacher is not defined & fetched by phone, should end chain', async () => { - await chain.handleRequest(req, res, next); - - expect(next).toHaveBeenCalled(); - expect(req.getTeacherByPhone).toHaveBeenCalled(); - expect(req.params.teacher).toEqual(defaultTeacher); - }); -}); \ No newline at end of file diff --git a/server/src/yemot/__tests__/yemotRequestImp.spec.ts b/server/src/yemot/__tests__/yemotRequestImp.spec.ts deleted file mode 100644 index 9b6bebd1..00000000 --- a/server/src/yemot/__tests__/yemotRequestImp.spec.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { User } from "@shared/entities/User.entity"; -import { YemotCall } from "@shared/entities/YemotCall.entity"; -import { getCurrentHebrewYear } from "@shared/utils/entity/year.util"; -import { getMockDataSource, MockYemotRequest } from "@shared/utils/yemot/__tests__/yemot.interface.spec"; -import { YemotRequest } from "@shared/utils/yemot/yemot.interface"; -import { AttReport } from "src/db/entities/AttReport.entity"; -import { Grade } from "src/db/entities/Grade.entity"; -import { DataSource, In } from "typeorm"; -import { YemotRequestImpl } from "../yemot.request.impl"; - -describe('YemotRequest', () => { - let dataSource: DataSource; - let yemotRequest: YemotRequestImpl; - let activeCall: YemotCall; - - beforeEach(() => { - dataSource = getMockDataSource(); - activeCall = new YemotCall(); - activeCall.userId = 1; - yemotRequest = new YemotRequestImpl(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"]); - }); - - it('should get lesson by lesson id', async () => { - const lessonId = 1; - const lesson = { id: 1 }; - - jest.spyOn(dataSource.getRepository(YemotCall), 'findOneBy').mockResolvedValue(lesson as YemotCall); - - const result = await yemotRequest.getLessonFromLessonId(lessonId); - expect(result).toEqual(lesson); - }); - - it('should get klass by klass id', async () => { - const klassId = 1; - const klass = { id: 1 }; - - const mock = jest.spyOn(dataSource.getRepository(YemotCall), 'findOneBy').mockResolvedValue(klass as YemotCall); - - const result = await yemotRequest.getKlassByKlassId(null, klassId); - expect(result).toEqual(klass); - expect(mock).toHaveBeenCalledWith({ id: klassId }); - }); - - it('should get klass by key', async () => { - const klassKey = 1; - const klass = { id: 1 }; - - const mock = jest.spyOn(dataSource.getRepository(YemotCall), 'findOneBy').mockResolvedValue(klass as YemotCall); - - const result = await yemotRequest.getKlassByKlassId(klassKey, null); - expect(result).toEqual(klass); - expect(mock).toHaveBeenCalledWith({ key: klassKey, userId: 1, year: getCurrentHebrewYear() }); - }); - - it('should get teacher by phone', async () => { - const phone = '1234567890'; - const teacher = { id: 1 }; - - jest.spyOn(dataSource.getRepository(YemotCall), 'findOne').mockResolvedValue(teacher as YemotCall); - - const result = await yemotRequest.getTeacherByPhone(phone); - expect(result).toEqual(teacher); - }); - - it('should get students by klass id', async () => { - const klassId = 1; - const students = [{ id: 1 }, { id: 2 }]; - - jest.spyOn(dataSource.getRepository(YemotCall), 'find').mockResolvedValue(students.map(student => ({ student })) as any[] as YemotCall[]); - - const result = await yemotRequest.getStudentsByKlassId(klassId); - expect(result).toEqual(students); - }); - - it('should save report', async () => { - const reportData = { id: 1 }; - const type = 'att'; - - jest.spyOn(yemotRequest, 'getExistingAttReports').mockResolvedValue([]); - jest.spyOn(yemotRequest, 'getExistingGradeReports').mockResolvedValue([]); - jest.spyOn(dataSource.getRepository(AttReport), 'create').mockResolvedValue(reportData as never); - - const result = await yemotRequest.saveReport(reportData as AttReport, type); - expect(result).toEqual(reportData); - - expect(dataSource.getRepository).toHaveBeenCalledWith(AttReport); - }); - - it('should get existing att reports', async () => { - jest.spyOn(dataSource.getRepository(AttReport), 'findBy').mockResolvedValue([]); - - const result = await yemotRequest.getExistingAttReports(null, null, null); - expect(result).toEqual([]); - }); - - it('should get existing grade reports', async () => { - jest.spyOn(dataSource.getRepository(Grade), 'findBy').mockResolvedValue([]); - - const result = await yemotRequest.getExistingGradeReports(null, null, null); - expect(result).toEqual([]); - }); - - it('should delete existing reports', async () => { - const existingReports = [{ id: 1 }, { id: 2 }]; - - const attMock = jest.spyOn(dataSource.getRepository(AttReport), 'delete').mockResolvedValue(null); - const gradeMock = jest.spyOn(dataSource.getRepository(Grade), 'delete').mockResolvedValue(null); - - const result = await yemotRequest.deleteExistingReports(existingReports as (AttReport | Grade)[], 'att'); - expect(result).toEqual(undefined); - expect(attMock).toHaveBeenCalledWith({ id: In([1, 2]) }); - - const result2 = await yemotRequest.deleteExistingReports(existingReports as (AttReport | Grade)[], 'grade'); - expect(result2).toEqual(undefined); - expect(gradeMock).toHaveBeenCalledWith({ id: In([1, 2]) }); - }); -}); - diff --git a/server/src/yemot/attReport.chain.ts b/server/src/yemot/attReport.chain.ts deleted file mode 100644 index 6720137e..00000000 --- a/server/src/yemot/attReport.chain.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { User } from "@shared/entities/User.entity"; -import { Chain, HandlerBase } from "@shared/utils/yemot/chain.interface"; -import { ReportType, YemotRequest, YemotResponse } from "@shared/utils/yemot/yemot.interface"; -import { AttReport } from "src/db/entities/AttReport.entity"; -import { Grade } from "src/db/entities/Grade.entity"; - -type GetExistingReportsFunction = (req: YemotRequest, klassId: string, lessonId: string, sheetName: string) => - Promise>; - -export interface IReportProperty { - name: string; - message: string; - field: string; - validate(req: YemotRequest): boolean; - shouldNotAsk?(req: YemotRequest): Promise; -} - -class GetSheetNameHandler extends HandlerBase { - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.sheetName !== undefined) { - return next(); - } else if (req.params.isCurrentMonth === undefined) { - const currentMonth = this.getMonthName(new Date().getMonth() + 1); - return res.send(res.getText('askIsCurrentMonth', currentMonth), 'isCurrentMonth'); - } else if (req.params.isCurrentMonth === '1') { - req.params.sheetName = this.getMonthName(new Date().getMonth() + 1); - return next(); - } else if (req.params.currentMonth === undefined) { - return res.send(res.getText('askForCurrentMonth'), 'currentMonth'); - } else { - req.params.sheetName = this.getMonthName(Number(req.params.currentMonth)); - return next(); - } - } - - getMonthName(number: number) { - const date = new Date(2009, number - 1, 1); // 2009-11-10 - const month = date.toLocaleString('he', { month: 'long' }); - return month; - } -} - -class GetExistingReportsHandler extends HandlerBase { - constructor(private getExistingReports: GetExistingReportsFunction) { - super(); - } - - async handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.existingReports === undefined) { - req.params.existingReports = await this.getExistingReports(req, req.params.klass.data.id, req.params.lesson.data.id, req.params.sheetName); - } - return next(); - } -} - -class CheckExistingReportsHandler extends HandlerBase { - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.existingReports.length > 0) { - if (req.params.isSkipExistingReports === undefined) { - return res.send(res.getText('askIfSkipExistingReports'), 'isSkipExistingReports'); - } else if (req.params.idsToSkip === undefined) { - if (req.params.isSkipExistingReports === '1') { - req.params.idsToSkip = [...new Set(req.params.existingReports.map(item => item.studentReferenceId))]; - } - } - } - req.params.idsToSkip ??= []; - return next(); - } -} - -class CheckHowManyLessonsHandler extends HandlerBase { - constructor(private reportType: ReportType) { - super(); - } - - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (this.reportType === 'grade') { - return next(); - } - if (req.params.howManyLessons === undefined) { - return res.send(res.getText('howManyLessons'), 'howManyLessons'); - } else if (req.params.howManyLessons === '0') { - res.send(res.getText('tryAgain')); - return res.send(res.getText('howManyLessons'), 'howManyLessons'); - } - return next(); - } -} - -class LoadStudentListHandler extends HandlerBase { - async handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.students === undefined) { - const studentList = await req.getStudentsByKlassId(req.params.baseReport.klassReferenceId); - req.params.students = studentList.filter(item => !req.params.idsToSkip.includes(item.id)); - } - return next(); - } -} - -class GetParamsDataHandler extends HandlerBase { - constructor(private properties: IReportProperty[]) { - super(); - } - - async shouldAsk(property: IReportProperty, req: YemotRequest) { - if (!property.shouldNotAsk) { - return true; - } - return property.shouldNotAsk(req).then(result => !result); - } - - async handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - req.params.propertyIndex ??= 0; - while (req.params.propertyIndex < this.properties.length) { - const prop = this.properties[req.params.propertyIndex]; - const shouldAsk = await this.shouldAsk(prop, req); - if (shouldAsk) { - if (req.params[prop.name] === undefined) { - return res.send(res.getText(prop.message), prop.name); - } else if (!req.params[prop.name + 'Validated']) { - if (this.isSideMenu(req.params[prop.name], req, res)) { - if (res.messages.length) { - return; - } - return next(true); - } - req.params[prop.name + 'Validated'] = prop.validate(req); - if (!req.params[prop.name + 'Validated']) { - res.clear(); - res.send(res.getText('tryAgain')); - return res.send(res.getText(prop.message), prop.name); - } - } - } - req.params.propertyIndex++; - } - return next(); - } - - isSideMenu(value: string, req: YemotRequest, res: YemotResponse) { - if (req.params.sideMenu !== undefined) { - value = '*' + req.params.sideMenu; - req.params.sideMenu = undefined; - } - if (value === '*') { - res.clear(); - res.send(res.getText('sideMenu'), 'sideMenu'); - } else if (value === '*4') { - res.clear(); - req.params.studentIndex--; - req.params.studentIndex = Math.max(0, req.params.studentIndex); - } else if (value === '*6') { - res.clear(); - req.params.studentIndex++; - } else { - return false; - } - return true; - } -} -class SaveAndGoToNextStudent extends HandlerBase { - constructor(private properties: IReportProperty[], private reportType: ReportType, private beforeSave?: (report: AttReport | Grade, user: User) => void) { - super(); - } - - async handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - await req.deleteExistingReports(req.params.existing, this.reportType); - const report: AttReport | Grade = { - ...req.params.baseReport, - studentTz: req.params.student.tz, - comments: '', - sheetName: req.params.sheetName, - }; - if (this.reportType === 'att') { - report.howManyLessons = Number(req.params.howManyLessons); - } - for (const prop of this.properties) { - report[prop.field] = req.params[prop.name]; - } - - const user = await req.getUser(); - this.beforeSave?.(report, user); - await req.saveReport(report, this.reportType); - - req.params.studentIndex++; - clearStudentData(req, this.properties); - return next(); - } -} -function clearStudentData(req: YemotRequest, properties: IReportProperty[]) { - delete req.params.student; - delete req.params.existing; - delete req.params.propertyIndex; - for (const prop of properties) { - delete req.params[prop.name]; - delete req.params[prop.name + 'Validated']; - } -} - -class IterateStudentsHandler extends HandlerBase { - studentChain: Chain; - - constructor(private properties: IReportProperty[], private reportType: ReportType, beforeSave?: (report: AttReport | Grade, user: User) => void) { - super(); - this.studentChain = new Chain('iterate students', [ - new GetParamsDataHandler(properties), - new SaveAndGoToNextStudent(properties, this.reportType, beforeSave), - ]); - } - - async handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - req.params.studentIndex ??= 0; - if (req.params.studentIndex < req.params.students.length) { - res.clear(); - req.params.student ??= req.params.students[req.params.studentIndex]; - req.params.existing ??= req.params.existingReports.filter(item => item.studentReferenceId === req.params.student.id); - - res.send(res.getText('nextStudent', req.params.student.name)); - return this.studentChain.handleRequest(req, res, () => { - clearStudentData(req, this.properties); - - return this.handleRequest(req, res, next); - }); - } - return next(); - } -} - - -export default function getReportChain(getExistingReports: GetExistingReportsFunction, reportType: ReportType, properties: IReportProperty[], beforeSave?: (report: AttReport | Grade, user: User) => void) { - return new Chain('get report chain', [ - new GetSheetNameHandler(), - new GetExistingReportsHandler(getExistingReports), - new CheckExistingReportsHandler(), - new CheckHowManyLessonsHandler(reportType), - new LoadStudentListHandler(), - new IterateStudentsHandler(properties, reportType, beforeSave), - ]); -} diff --git a/server/src/yemot/reportType.chain.ts b/server/src/yemot/reportType.chain.ts deleted file mode 100644 index 383b8177..00000000 --- a/server/src/yemot/reportType.chain.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { Chain, HandlerBase, IHandler } from "@shared/utils/yemot/chain.interface"; -import { YemotRequest, YemotResponse } from "@shared/utils/yemot/yemot.interface"; - -class CheckIfReportTypeDefinedHandler extends HandlerBase { - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.reportType !== undefined) { - return next(); - } else { - return res.send(res.getText('getReportType'), 'reportType'); - } - } -} - -class UseAttReportChainHandler extends HandlerBase { - constructor(private attReportChain: IHandler) { - super(); - } - - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.reportType === '1') { - return this.attReportChain.handleRequest(req, res, next); - } - return next(); - } -} - -class UseGradeReportChainHandler extends HandlerBase { - constructor(private gradeReportChain: IHandler) { - super(); - } - - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.reportType === '2') { - return this.gradeReportChain.handleRequest(req, res, next); - } - return next(); - } -} - -export default function getReportTypeChain(attReportChain: Chain, gradeReportChain: Chain) { - return new Chain('get report type chain', [ - new CheckIfReportTypeDefinedHandler(), - new UseAttReportChainHandler(attReportChain), - new UseGradeReportChainHandler(gradeReportChain), - ]); -} diff --git a/server/src/yemot/resourceWithConfirmation.chain.ts b/server/src/yemot/resourceWithConfirmation.chain.ts deleted file mode 100644 index d9af3364..00000000 --- a/server/src/yemot/resourceWithConfirmation.chain.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { pascalCase } from "change-case"; -import { Chain, HandlerBase } from "@shared/utils/yemot/chain.interface"; -import { YemotRequest, YemotResponse } from "@shared/utils/yemot/yemot.interface"; - -class CheckIfResourceDefinedHandler extends HandlerBase { - constructor(private resource: string) { super(); } - - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (!req.params[this.resource]) { - req.params[this.resource] = {}; - } - if (req.params[this.resource].data !== undefined) { - // Exit the chain early if resource is already defined - res.clear(); - return next(true); - } else { - return next(); - } - } -} - -class AskForResourceIdHandler extends HandlerBase { - constructor(private resource: string) { super(); } - - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params[this.resource + 'Id'] === undefined) { - delete req.params[this.resource].dataToConfirm; - return res.send(res.getText(`type${pascalCase(this.resource)}Id`), this.resource + 'Id'); - } - res.clear(); - return next(); - } -} - -class GetResourceFromResourceIdHandler extends HandlerBase { - constructor(private resource: string, private getResource: (req: YemotRequest) => Promise) { super(); } - - async handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params[this.resource].dataToConfirm === undefined) { - const resource = await this.getResource(req); - req.params[this.resource].dataToConfirm = resource; - } - return next(); - } -} - -class AskForResourceConfirmHandler extends HandlerBase { - constructor(private resource: string) { super(); } - - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params[this.resource + 'Confirm'] === undefined) { - if (req.params[this.resource].dataToConfirm) { - delete req.params[this.resource].data; - return res.send(res.getText(`confirm${pascalCase(this.resource)}`, req.params[this.resource].dataToConfirm.name), this.resource + 'Confirm'); - } else { - // If resource is null, ask for resource ID again - delete req.params[this.resource + 'Id']; - delete req.params[this.resource].dataToConfirm; - res.send(res.getText('tryAgain')); - return res.send(res.getText(`type${pascalCase(this.resource)}Id`), this.resource + 'Id'); - } - } - return next(); - } -} - -class ConfirmResourceHandler extends HandlerBase { - constructor(private resource: string) { super(); } - - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params[this.resource + 'Confirm'] === '1') { - // Set the resource and exit the chain if confirmed - req.params[this.resource].data = req.params[this.resource].dataToConfirm; - delete req.params[this.resource].dataToConfirm; - return next(); - } else { - // If not confirmed, ask for resource ID again - delete req.params[this.resource + 'Id']; - delete req.params[this.resource].dataToConfirm; - delete req.params[this.resource + 'Confirm']; - return res.send(res.getText(`type${pascalCase(this.resource)}Id`), this.resource + 'Id'); - } - } -} - -// Create the chain with the appropriate handlers -export default function getResourceConfirmationChain(resource: string, getResource: (req: YemotRequest) => Promise) { - return new Chain('resource with confirmation', [ - new CheckIfResourceDefinedHandler(resource), - new AskForResourceIdHandler(resource), - new GetResourceFromResourceIdHandler(resource, getResource), - new AskForResourceConfirmHandler(resource), - new ConfirmResourceHandler(resource), - ]); -} diff --git a/server/src/yemot/teacherByPhone.chain.ts b/server/src/yemot/teacherByPhone.chain.ts deleted file mode 100644 index ae4202d8..00000000 --- a/server/src/yemot/teacherByPhone.chain.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Chain, HandlerBase } from "@shared/utils/yemot/chain.interface"; -import { YemotRequest, YemotResponse } from "@shared/utils/yemot/yemot.interface"; - -class CheckIfTeacherDefinedHandler extends HandlerBase { - handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - if (req.params.teacher !== undefined) { - // Exit the chain early if teacher is already defined - return next(true); - } else { - return next(); - } - } -} - -class GetTeacherFromPhoneHandler extends HandlerBase { - async handleRequest(req: YemotRequest, res: YemotResponse, next: Function) { - const teacher = await req.getTeacherByPhone(req.params.ApiPhone); - if (teacher) { - req.params.teacher = teacher; - res.send(res.getText('welcomeForTeacher', teacher.name)) - return next(); - } else { - res.send(res.getText('phoneIsNotRecognizedInTheSystem')); - res.send(res.hangup()); - } - } -} - -// Create the chain with the appropriate handlers -export default new Chain('teacher by phone', [ - new CheckIfTeacherDefinedHandler(), - new GetTeacherFromPhoneHandler(), -]); diff --git a/server/src/yemot/yemot.chain.ts b/server/src/yemot/yemot.chain.ts deleted file mode 100644 index 05369ef6..00000000 --- a/server/src/yemot/yemot.chain.ts +++ /dev/null @@ -1,105 +0,0 @@ -import getReportChain, { IReportProperty } from "./attReport.chain"; -import { Chain, Handler } from "@shared/utils/yemot/chain.interface"; -import getReportTypeChain from "./reportType.chain"; -import getResourceConfirmationChain from "./resourceWithConfirmation.chain"; -import teacherByPhoneChain from "./teacherByPhone.chain"; -import { YemotRequest } from "@shared/utils/yemot/yemot.interface"; -import { calcAttLateCount } from "src/entity-modules/att-report.config"; - - -function getLessonFromLessonId(req: YemotRequest) { - return req.getLessonFromLessonId(req.params.lessonId); -}; -const lessonChain = getResourceConfirmationChain('lesson', getLessonFromLessonId); - - -const klassFromLessonHandler = new Handler(async (req, res, next) => { - if (req.params.klass?.data === undefined) { - if (req.params.lesson.data.klassReferenceIds?.length === 1) { - const klass = await req.getKlassByKlassId(req.params.klassId, req.params.lesson.data.klassReferenceIds[0]); - req.params.klass = { - id: klass.key, - data: klass, - }; - } - } - return next(); -}); -function getKlassFromKlassId(req: YemotRequest) { - return req.getKlassByKlassId(req.params.klassId); -}; -const klassChain = getResourceConfirmationChain('klass', getKlassFromKlassId); - - -const createBaseReportHandler = new Handler(async (req, res, next) => { - if (req.params.baseReport === undefined) { - req.params.baseReport = { - userId: req.getUserId(), - teacherReferenceId: req.params.teacher.id, - klassReferenceId: req.params.klass.data.id, - lessonReferenceId: req.params.lesson.data.id, - reportDate: new Date().toISOString().slice(0, 10), - }; - } - return next(); -}); - - -const notifySuccessAndEndHandler = new Handler(async (req, res, next) => { - return res.send(res.getText('dataWasSavedSuccessfully')); -}); - - -async function getExistingAttReports(req: YemotRequest, klassId: string, lessonId: string, sheetName: string) { - return req.getExistingAttReports(klassId, lessonId, sheetName); -} -const attProperties: IReportProperty[] = [ - { - name: 'absCount', - message: 'absCount', - field: 'absCount', - validate(req: YemotRequest) { - return Number(req.params.absCount) >= 0 && Number(req.params.absCount) <= Number(req.params.howManyLessons); - } - }, - { - name: 'lateCount', - message: 'lateCount', - field: 'lateCount', - validate(req: YemotRequest) { - return Number(req.params.lateCount) >= 0 && Number(req.params.lateCount) <= Number(req.params.howManyLessons); - }, - shouldNotAsk(req: YemotRequest) { - return req.getUserPermissions().then(permissions => !permissions?.inLessonReport?.withLate); - } - } -] -const attReportChain = getReportChain(getExistingAttReports, 'att', attProperties, calcAttLateCount); -async function getExistingGradeReports(req: YemotRequest, klassId: string, lessonId: string, sheetName: string) { - return req.getExistingGradeReports(klassId, lessonId, sheetName); -} -const gradeProperties: IReportProperty[] = [ - { - name: 'grade', - message: 'grade', - field: 'grade', - validate(req: YemotRequest) { - return req.params.grade > 0 && req.params.grade <= 1000; - } - } -] -const gradeReportChain = getReportChain(getExistingGradeReports, 'grade', gradeProperties); - -const reportTypeChain = getReportTypeChain(attReportChain, gradeReportChain); - - -// todo: add exeption handler and res.send('dataWasNotSaved'); -export default new Chain('yemot chain', [ - teacherByPhoneChain, - lessonChain, - klassFromLessonHandler, - klassChain, - createBaseReportHandler, - reportTypeChain, - notifySuccessAndEndHandler, -]); diff --git a/server/src/yemot/yemot.request.impl.ts b/server/src/yemot/yemot.request.impl.ts deleted file mode 100644 index 926d73cd..00000000 --- a/server/src/yemot/yemot.request.impl.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { YemotCall } from "@shared/entities/YemotCall.entity"; -import { Between, DataSource, In } from "typeorm"; -import { YemotRequest, ReportType } from "../../shared/utils/yemot/yemot.interface"; -import { Lesson } from "../db/entities/Lesson.entity"; -import { Klass } from "../db/entities/Klass.entity"; -import { Teacher } from "../db/entities/Teacher.entity"; -import { StudentKlass } from "../db/entities/StudentKlass.entity"; -import { AttReport } from "../db/entities/AttReport.entity"; -import { Grade } from "../db/entities/Grade.entity"; -import { getCurrentHebrewYear } from "../../shared/utils/entity/year.util"; - -export class YemotRequestImpl extends YemotRequest { - constructor( - activeCall: YemotCall, - dataSource: DataSource, - ) { - super(activeCall, dataSource); - } - - async getLessonFromLessonId(lessonId: number) { - return this.dataSource.getRepository(Lesson).findOneBy({ - userId: this.getUserId(), - key: lessonId, - year: getCurrentHebrewYear(), - }); - } - - async getKlassByKlassId(klassKey: number, klassId?: number) { - if (!!klassId) { - return this.dataSource.getRepository(Klass).findOneBy({ - id: klassId, - }); - } - return this.dataSource.getRepository(Klass).findOneBy({ - userId: this.getUserId(), - key: klassKey, - year: getCurrentHebrewYear(), - }); - } - - async getTeacherByPhone(phone: string) { - return this.dataSource.getRepository(Teacher).findOne({ - where: [ - { userId: this.getUserId(), phone }, - { userId: this.getUserId(), phone2: phone }, - ] - }); - } - - async getStudentsByKlassId(klassId: number) { - const res = await this.dataSource.getRepository(StudentKlass).find({ - where: { - userId: this.getUserId(), - klassReferenceId: klassId, - year: getCurrentHebrewYear(), - }, - relations: { - student: true, - }, - order: { - student: { - name: 'ASC', - } - } - }); - - return res.map(item => item.student).filter(Boolean); - } - - async saveReport(reportData: AttReport | Grade, type: ReportType) { - const reportEntity = type === 'att' ? AttReport : Grade; - const reportRepo = this.dataSource.getRepository(reportEntity); - - const report = reportRepo.create(reportData) - await reportRepo.save(report); - - return report; - } - - getExistingAttReports(klassId: string, lessonId: string, sheetName: string): Promise { - return this.dataSource.getRepository(AttReport).findBy({ - userId: this.getUserId(), - sheetName, - lessonReferenceId: Number(lessonId), - klassReferenceId: Number(klassId), - year: getCurrentHebrewYear(), - }) - } - - getExistingGradeReports(klassId: string, lessonId: string, sheetName: string): Promise { - return this.dataSource.getRepository(Grade).findBy({ - userId: this.getUserId(), - lessonReferenceId: Number(lessonId), - klassReferenceId: Number(klassId), - year: getCurrentHebrewYear(), - reportDate: Between(new Date(Date.now() - 2 * 7 * 24 * 60 * 60 * 1000), new Date()) - }) - } - - async deleteExistingReports(existingReports: (AttReport | Grade)[], type: ReportType) { - if (existingReports.length) { - const entity = type === 'att' ? AttReport : Grade; - await this.dataSource.getRepository(entity) - .delete({ - id: In(existingReports.map(item => item.id)) - }); - } - } -} \ No newline at end of file