diff --git a/client/shared b/client/shared index 4245d533..28d0c04e 160000 --- a/client/shared +++ b/client/shared @@ -1 +1 @@ -Subproject commit 4245d53311003e49b730ff6fc8b85bf92f89626a +Subproject commit 28d0c04ea3ddff92ea0f91a424d7fa90ae15abd2 diff --git a/client/src/App.jsx b/client/src/App.jsx index 91ae7974..55c94553 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -48,6 +48,7 @@ import attGradeEffect from './entities/att-grade-effect'; import reportGroup from './entities/report-group'; import reportGroupSession from './entities/report-group-session'; import teacherReportedToday from './entities/teacher-reported-today'; +import attendanceCleanupRule from './entities/attendance-cleanup-rule'; import Settings from 'src/settings/Settings'; import StudentAttendanceList from 'src/pivots/StudentAttendanceList'; @@ -93,6 +94,7 @@ import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettingsOutlin import DirectionsBusIcon from '@mui/icons-material/DirectionsBusOutlined'; import CelebrationIcon from '@mui/icons-material/CelebrationOutlined'; import AssignmentTurnedInIcon from '@mui/icons-material/AssignmentTurnedInOutlined'; +import CleaningServicesIcon from '@mui/icons-material/CleaningServicesOutlined'; const themeOptions = { primary: blue[700], secondary: purple[500] }; @@ -284,6 +286,14 @@ const App = () => ( options={{ menuGroup: 'settings' }} icon={CalculateIcon} /> + {isAdmin(permissions) && ( + + )} , + , +]; + +const Datagrid = ({ isAdmin, children, ...props }) => { + const additionalBulkButtons = [ + , + ]; + + return ( + + {children} + {isAdmin && } + + + + dayOfWeekChoices.find((c) => c.id === record.dayOfWeek)?.name} + /> + + + {isAdmin && } + + ); +}; + +const Inputs = ({ isCreate, isAdmin }) => { + return ( + <> + {!isCreate && isAdmin && } + {isAdmin && } + + + + + + + + ); +}; + +const entity = { + Datagrid, + Inputs, + Representation: CommonRepresentation, + filters, +}; + +export default getResourceComponents(entity); diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js index 5b250f27..aed7a00d 100644 --- a/client/src/roadmapFeatures.js +++ b/client/src/roadmapFeatures.js @@ -29,6 +29,7 @@ export default [ { html: 'הוספת דוח המציג אילו מורות דיווחו נוכחות בתאריך נבחר', status: 'בוצע', statusColor: 'success' }, { html: 'הוספת דף "צור קשר" לשליחת פנייה עם קבצים מצורפים', status: 'בוצע', statusColor: 'success' }, { html: 'תשתית משימות רקע: ייצוא נתונים אסינכרוני, תזמונים קבועים וניטור משימות', status: 'בוצע', statusColor: 'success' }, + { html: 'ניקוי אוטומטי של נוכחות שיעור נבחר, לפי כיתה/מסלול לשמירה, בכל מוצאי שבת', status: 'בוצע', statusColor: 'success' }, // { html: 'הגדרת תקופת זמן לפי תאריכים', status: 'בקרוב', statusColor: 'warning' }, // { html: 'הגדרת תקופת זמן לפי יום בשבוע', status: 'בוצע', statusColor: 'success' }, diff --git a/server/shared b/server/shared index 0c3ea446..9640e33e 160000 --- a/server/shared +++ b/server/shared @@ -1 +1 @@ -Subproject commit 0c3ea44661df6a39bee000086fcdd8544b2be2bf +Subproject commit 9640e33ef61710aa8157828fae95970f5b9fe583 diff --git a/server/src/app.module.ts b/server/src/app.module.ts index 285c3612..5bea6787 100644 --- a/server/src/app.module.ts +++ b/server/src/app.module.ts @@ -2,10 +2,12 @@ import { BaseNraAppModule } from '@shared/app/base-app.module'; import { EntitiesModule } from './entities.module'; import { UserInitModule } from './user-init.module'; import { YemotHandlerService } from './yemot-handler.service'; +import { AttendanceCleanupSweepHandler } from './jobs/attendance-cleanup-sweep.handler'; export const AppModule = BaseNraAppModule.forRoot({ entitiesModule: EntitiesModule, yemotHandlerService: YemotHandlerService, userInitModule: UserInitModule, throttlerLimit: 200, + jobHandlers: [AttendanceCleanupSweepHandler], }); diff --git a/server/src/db/entities/AttendanceCleanupRule.entity.ts b/server/src/db/entities/AttendanceCleanupRule.entity.ts new file mode 100644 index 00000000..e9f6dc33 --- /dev/null +++ b/server/src/db/entities/AttendanceCleanupRule.entity.ts @@ -0,0 +1,129 @@ +import { + BeforeInsert, + BeforeUpdate, + Column, + DataSource, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; +import { IHasUserId } from '@shared/base-entity/interface'; +import { BooleanIntColumn } from '@shared/utils/entity/column-types.util'; +import { findOneAndAssignKey, getDataSource } from '@shared/utils/entity/foreignKey.util'; +import { IsOptional } from 'class-validator'; +import { CrudValidationGroups } from '@dataui/crud'; +import { IsNotEmpty, IsNumber, MaxLength, Max, Min } from '@shared/utils/validation/class-validator-he'; +import { StringType, NumberType } from '@shared/utils/entity/class-transformer'; +import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util'; +import { Lesson } from './Lesson.entity'; +import { Klass } from './Klass.entity'; +import { User } from './User.entity'; + +/** + * A recurring attendance-cleanup rule: on `dayOfWeek`, delete att_reports for + * every student who does NOT belong to `klassId` (the klass/track to + * preserve, via student_klasses membership — NOT att_reports' own + * klassReferenceId, which is the report/session's klass and the same for + * everyone in it), for each of the last `weeksBack` occurrences of that + * weekday. Consumed weekly by the attendance-cleanup-sweep job handler. + * + * Deliberately has no `year` column, unlike Lesson/Klass/AttReport/ + * StudentKlass — a rule is meant to keep working across academic years. + * The form picks lessonReferenceId/klassReferenceId (this year's row, via a + * friendly dropdown); fillFields below resolves those DOWN to the + * underlying Lesson.key/Klass.key (stable across years) and persists the + * key, not the one-year id. The sweep re-resolves key -> that target date's + * own academic year's id at run time, so the rule doesn't go stale when a + * new year's Lesson/Klass/StudentKlass rows get created with fresh ids. + */ +@Index('attendance_cleanup_rules_users_idx', ['userId'], {}) +@Entity('attendance_cleanup_rules') +export class AttendanceCleanupRule implements IHasUserId { + @BeforeInsert() + @BeforeUpdate() + async fillFields() { + let dataSource: DataSource; + try { + dataSource = await getDataSource([Lesson, Klass, User]); + + this.lessonId = await findOneAndAssignKey(dataSource, Lesson, this.userId, this.lessonReferenceId, this.lessonId); + this.klassId = await findOneAndAssignKey(dataSource, Klass, this.userId, this.klassReferenceId, this.klassId); + } finally { + dataSource?.destroy(); + } + } + + @PrimaryGeneratedColumn({ type: 'int', name: 'id' }) + id: number; + + @Column('int', { name: 'user_id' }) + userId: number; + + @IsOptional({ always: true }) + @StringType + @MaxLength(255, { always: true }) + @Column('varchar', { name: 'name', length: 255, nullable: true }) + name: string | null; + + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @Column({ nullable: true }) + lessonReferenceId: number; + + /** Lesson.key, derived from lessonReferenceId in fillFields — not user-editable. */ + @IsOptional({ always: true }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Column('int', { name: 'lesson_id', nullable: true }) + lessonId: number; + + /** The track/class to PRESERVE (checked via student_klasses membership, not att_reports.klassReferenceId). */ + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @Column({ nullable: true }) + klassReferenceId: number; + + /** Klass.key, derived from klassReferenceId in fillFields — not user-editable. */ + @IsOptional({ always: true }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Column('int', { name: 'klass_id', nullable: true }) + klassId: number; + + /** 0=Sunday .. 6=Saturday (JS Date.getDay() convention). */ + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Min(0, { always: true }) + @Max(6, { always: true }) + @Column('int', { name: 'day_of_week' }) + dayOfWeek: number; + + @IsOptional({ always: true }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Min(1, { always: true }) + @Max(52, { always: true }) + @Column('int', { name: 'weeks_back', default: 2 }) + weeksBack: number; + + @BooleanIntColumn({ default: true }) + active: boolean; + + @CreatedAtColumn() + createdAt: Date; + + @UpdatedAtColumn() + updatedAt: Date; + + @ManyToOne(() => Lesson, { createForeignKeyConstraints: false }) + @JoinColumn({ name: 'lessonReferenceId' }) + lesson: Lesson; + + @ManyToOne(() => Klass, { createForeignKeyConstraints: false }) + @JoinColumn({ name: 'klassReferenceId' }) + klass: Klass; +} diff --git a/server/src/entities.module.ts b/server/src/entities.module.ts index 0db8837c..84d2b4b1 100644 --- a/server/src/entities.module.ts +++ b/server/src/entities.module.ts @@ -39,6 +39,7 @@ import absenceTypeConfig from './entity-modules/absenceType.config'; import uploadedFileConfig from '@shared/entities/configs/uploaded-file.config'; import phoneTemplateConfig from '@shared/entities/configs/phone-template.config'; import phoneCampaignConfig from '@shared/entities/configs/phone-campaign.config'; +import attendanceCleanupRuleConfig from './entity-modules/attendance-cleanup-rule.config'; import { Student } from './db/entities/Student.entity'; import { Teacher } from './db/entities/Teacher.entity'; import userConfig from '@shared/entities/configs/user.config'; @@ -99,6 +100,7 @@ registerEntityNameMap({ BaseEntityModule.register(phoneTemplateConfig), BaseEntityModule.register(phoneCampaignConfig), BaseEntityModule.register({ entity: TeacherReportedToday }), + BaseEntityModule.register(attendanceCleanupRuleConfig), ], }) export class EntitiesModule {} diff --git a/server/src/entity-modules/__tests__/attendance-cleanup-rule.config.spec.ts b/server/src/entity-modules/__tests__/attendance-cleanup-rule.config.spec.ts new file mode 100644 index 00000000..96b8e441 --- /dev/null +++ b/server/src/entity-modules/__tests__/attendance-cleanup-rule.config.spec.ts @@ -0,0 +1,58 @@ +import { CrudRequest } from '@dataui/crud'; +import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity'; +import attendanceCleanupRuleConfig from '../attendance-cleanup-rule.config'; + +describe('AttendanceCleanupRuleConfig', () => { + it('should have correct base configuration', () => { + expect(attendanceCleanupRuleConfig.entity).toBe(AttendanceCleanupRule); + expect(attendanceCleanupRuleConfig.query.join).toEqual( + expect.objectContaining({ + lesson: { eager: false }, + klass: { eager: false }, + }), + ); + expect(attendanceCleanupRuleConfig.service).toBeDefined(); + }); + + describe('doAction: runNow', () => { + function makeService() { + const ServiceClass = attendanceCleanupRuleConfig.service as any; + const mockRepository = { + target: AttendanceCleanupRule, + manager: { transaction: jest.fn((cb) => cb()) }, + metadata: { + columns: [{ propertyName: 'id' }, { propertyName: 'userId' }], + connection: { options: { type: 'mysql' } }, + targetName: 'AttendanceCleanupRule', + }, + } as any; + const jobService = { enqueue: jest.fn().mockResolvedValue({ id: 42 }) }; + const service = new ServiceClass(mockRepository, {} as any, jobService); + return { service, jobService }; + } + + it('enqueues an attendance-cleanup-sweep job scoped to the selected rule ids', async () => { + const { service, jobService } = makeService(); + const req = { + auth: { id: 7 }, + parsed: { extra: { action: 'runNow', ids: '1,2' } }, + } as unknown as CrudRequest; + + const message = await service.doAction(req, {}); + + expect(jobService.enqueue).toHaveBeenCalledWith(7, 'attendance-cleanup-sweep', { ruleIds: [1, 2] }); + expect(message).toContain('42'); + }); + + it('falls through to the base doAction for unknown actions', async () => { + const { service } = makeService(); + const req = { + auth: { id: 7 }, + parsed: { extra: { action: 'somethingElse' } }, + } as unknown as CrudRequest; + + const result = await service.doAction(req, {}); + expect(result).toBe('done nothing'); + }); + }); +}); diff --git a/server/src/entity-modules/attendance-cleanup-rule.config.ts b/server/src/entity-modules/attendance-cleanup-rule.config.ts new file mode 100644 index 00000000..045c9f90 --- /dev/null +++ b/server/src/entity-modules/attendance-cleanup-rule.config.ts @@ -0,0 +1,47 @@ +import { CrudRequest } from '@dataui/crud'; +import { Repository } from 'typeorm'; +import { getUserIdFromUser } from '@shared/auth/auth.util'; +import { BaseEntityService } from '@shared/base-entity/base-entity.service'; +import { BaseEntityModuleOptions, Entity, InjectEntityRepository } from '@shared/base-entity/interface'; +import { MailSendService } from '@shared/utils/mail/mail-send.service'; +import { JobService } from '@shared/utils/jobs/job.service'; +import { getAsNumberArray } from '@shared/utils/queryParam.util'; +import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity'; + +class AttendanceCleanupRuleService extends BaseEntityService { + constructor( + @InjectEntityRepository repo: Repository, + mailSendService: MailSendService, + private readonly jobService: JobService, + ) { + super(repo, mailSendService); + } + + async doAction(req: CrudRequest, body: any): Promise { + const extra = req.parsed.extra as any; + switch (extra.action) { + case 'runNow': { + const userId = getUserIdFromUser(req.auth); + const ruleIds = getAsNumberArray(extra.ids) ?? []; + const job = await this.jobService.enqueue(userId, 'attendance-cleanup-sweep', { ruleIds }); + return `נוצרה משימת ניקוי נוכחות (מזהה ${job.id})`; + } + } + return super.doAction(req, body); + } +} + +function getConfig(): BaseEntityModuleOptions { + return { + entity: AttendanceCleanupRule, + query: { + join: { + lesson: { eager: false }, + klass: { eager: false }, + }, + }, + service: AttendanceCleanupRuleService, + }; +} + +export default getConfig(); diff --git a/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts b/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts new file mode 100644 index 00000000..1bc06022 --- /dev/null +++ b/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts @@ -0,0 +1,66 @@ +const mockDestroy = jest.fn(); +const mockGetRepository = jest.fn(); + +// Only getDataSource is mocked (to avoid a real DB connection); findOneAndAssignKey +// runs for real against the mocked dataSource, so this also covers the entity's +// wiring into that shared helper (itself separately unit-tested in nra-server). +jest.mock('@shared/utils/entity/foreignKey.util', () => ({ + ...jest.requireActual('@shared/utils/entity/foreignKey.util'), + getDataSource: jest.fn().mockResolvedValue({ + getRepository: (...args: any[]) => mockGetRepository(...args), + destroy: mockDestroy, + }), +})); + +import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity'; + +describe('AttendanceCleanupRule.fillFields', () => { + beforeEach(() => { + mockGetRepository.mockReset(); + mockDestroy.mockReset(); + }); + + it('resolves lessonId/klassId (the stable key) DOWN from the picked lessonReferenceId/klassReferenceId', async () => { + mockGetRepository.mockImplementation((entity: any) => { + if (entity.name === 'Lesson') return { findOne: jest.fn().mockResolvedValue({ key: 5 }) }; + if (entity.name === 'Klass') return { findOne: jest.fn().mockResolvedValue({ key: 3 }) }; + throw new Error(`unexpected repo for ${entity?.name}`); + }); + + const rule = new AttendanceCleanupRule(); + rule.userId = 1; + rule.lessonReferenceId = 105; + rule.klassReferenceId = 103; + + await rule.fillFields(); + + expect(rule.lessonId).toBe(5); + expect(rule.klassId).toBe(3); + expect(mockDestroy).toHaveBeenCalled(); + }); + + it('leaves lessonId/klassId unset when no reference was picked', async () => { + mockGetRepository.mockImplementation(() => ({ findOne: jest.fn() })); + + const rule = new AttendanceCleanupRule(); + rule.userId = 1; + + await rule.fillFields(); + + expect(rule.lessonId).toBeUndefined(); + expect(rule.klassId).toBeUndefined(); + }); + + it('keeps the previous key when the picked reference no longer resolves', async () => { + mockGetRepository.mockImplementation(() => ({ findOne: jest.fn().mockResolvedValue(undefined) })); + + const rule = new AttendanceCleanupRule(); + rule.userId = 1; + rule.lessonReferenceId = 105; + rule.lessonId = 9; + + await rule.fillFields(); + + expect(rule.lessonId).toBe(9); + }); +}); diff --git a/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts b/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts new file mode 100644 index 00000000..2025a45e --- /dev/null +++ b/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts @@ -0,0 +1,143 @@ +import { In, Not } from 'typeorm'; +import { AttendanceCleanupSweepHandler, getIsraelToday, getTargetDates } from '../attendance-cleanup-sweep.handler'; +import { Job } from '@shared/entities/Job.entity'; + +describe('getIsraelToday', () => { + it('returns Israel calendar date regardless of the process timezone', () => { + const originalTZ = process.env.TZ; + process.env.TZ = 'UTC'; + try { + const today = getIsraelToday(); + const expected = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Jerusalem' }).format(new Date()); + const actual = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; + expect(actual).toBe(expected); + } finally { + process.env.TZ = originalTZ; + } + }); +}); + +describe('getTargetDates', () => { + it('returns today when today is the target weekday', () => { + // 2026-08-22 is a Saturday (day 6) + const now = new Date(2026, 7, 22); + const dates = getTargetDates(6, 1, now); + expect(dates).toHaveLength(1); + expect(dates[0].toISOString().slice(0, 10)).toBe('2026-08-22'); + }); + + it('walks back to the most recent occurrence of the weekday', () => { + // 2026-08-22 is Saturday; the most recent Thursday (4) before/on it is 2026-08-20 + const now = new Date(2026, 7, 22); + const dates = getTargetDates(4, 1, now); + expect(dates[0].toISOString().slice(0, 10)).toBe('2026-08-20'); + }); + + it('returns weeksBack dates, most recent first, 7 days apart', () => { + const now = new Date(2026, 7, 22); + const dates = getTargetDates(4, 3, now); + expect(dates.map((d) => d.toISOString().slice(0, 10))).toEqual(['2026-08-20', '2026-08-13', '2026-08-06']); + }); +}); + +describe('AttendanceCleanupSweepHandler', () => { + function makeDataSource(overrides: Partial> = {}) { + const repos: Record = { + AttendanceCleanupRule: { find: jest.fn().mockResolvedValue([]) }, + Lesson: { findOne: jest.fn() }, + Klass: { findOne: jest.fn() }, + StudentKlass: { find: jest.fn().mockResolvedValue([]) }, + AttReport: { delete: jest.fn().mockResolvedValue({ affected: 0 }) }, + ...overrides, + }; + return { + getRepository: (entity: any) => repos[entity.name], + repos, + } as any; + } + + it('returns zero-work summary when there are no active rules', async () => { + const dataSource = makeDataSource(); + const handler = new AttendanceCleanupSweepHandler(dataSource); + const result = await handler.handle({ userId: 1, payload: {} } as unknown as Job); + expect(result.rulesProcessed).toBe(0); + expect(result.totalDeleted).toBe(0); + }); + + it('scopes to payload.ruleIds when provided (run-now path)', async () => { + const dataSource = makeDataSource(); + const handler = new AttendanceCleanupSweepHandler(dataSource); + await handler.handle({ userId: 1, payload: { ruleIds: [5, 6] } } as unknown as Job); + expect(dataSource.repos.AttendanceCleanupRule.find).toHaveBeenCalledWith({ + where: { userId: 1, id: In([5, 6]) }, + }); + }); + + it('deletes att_reports for students NOT recorded as members of the preserved klass', async () => { + const dataSource = makeDataSource({ + AttendanceCleanupRule: { + find: jest.fn().mockResolvedValue([ + { id: 1, userId: 1, name: 'תפילה', lessonId: 5, klassId: 3, dayOfWeek: 4, weeksBack: 2, active: true }, + ]), + }, + Lesson: { findOne: jest.fn().mockResolvedValue({ id: 105 }) }, + Klass: { findOne: jest.fn().mockResolvedValue({ id: 103 }) }, + StudentKlass: { + find: jest.fn().mockResolvedValue([{ studentReferenceId: 201 }, { studentReferenceId: 202 }]), + }, + AttReport: { delete: jest.fn().mockResolvedValue({ affected: 7 }) }, + }); + const handler = new AttendanceCleanupSweepHandler(dataSource); + + const result = await handler.handle({ userId: 1, payload: {} } as unknown as Job); + + expect(dataSource.repos.StudentKlass.find).toHaveBeenCalledWith({ + where: { userId: 1, klassReferenceId: 103, year: expect.any(Number) }, + }); + expect(dataSource.repos.AttReport.delete).toHaveBeenCalledTimes(2); // weeksBack: 2 + const [firstCallArgs] = dataSource.repos.AttReport.delete.mock.calls[0]; + expect(firstCallArgs).toMatchObject({ userId: 1, lessonReferenceId: 105 }); + expect(firstCallArgs.studentReferenceId).toEqual(Not(In([201, 202]))); + expect(result.totalDeleted).toBe(14); // 7 + 7 + expect(result.rulesProcessed).toBe(1); + }); + + it('skips a date when the lesson or klass cannot be resolved for that year, without deleting', async () => { + const dataSource = makeDataSource({ + AttendanceCleanupRule: { + find: jest.fn().mockResolvedValue([ + { id: 2, userId: 1, name: null, lessonId: 5, klassId: 3, dayOfWeek: 4, weeksBack: 1, active: true }, + ]), + }, + Lesson: { findOne: jest.fn().mockResolvedValue(undefined) }, + Klass: { findOne: jest.fn().mockResolvedValue(undefined) }, + }); + const handler = new AttendanceCleanupSweepHandler(dataSource); + + const result = await handler.handle({ userId: 1, payload: {} } as unknown as Job); + + expect(dataSource.repos.AttReport.delete).not.toHaveBeenCalled(); + expect(result.totalDeleted).toBe(0); + expect(result.perRule[0]).toContain('דולג'); + }); + + it('skips a date when no student is recorded as a member of the preserved klass, rather than deleting for everyone', async () => { + const dataSource = makeDataSource({ + AttendanceCleanupRule: { + find: jest.fn().mockResolvedValue([ + { id: 3, userId: 1, name: 'x', lessonId: 5, klassId: 3, dayOfWeek: 4, weeksBack: 1, active: true }, + ]), + }, + Lesson: { findOne: jest.fn().mockResolvedValue({ id: 105 }) }, + Klass: { findOne: jest.fn().mockResolvedValue({ id: 103 }) }, + StudentKlass: { find: jest.fn().mockResolvedValue([]) }, + }); + const handler = new AttendanceCleanupSweepHandler(dataSource); + + const result = await handler.handle({ userId: 1, payload: {} } as unknown as Job); + + expect(dataSource.repos.AttReport.delete).not.toHaveBeenCalled(); + expect(result.totalDeleted).toBe(0); + expect(result.perRule[0]).toContain('דולג'); + }); +}); diff --git a/server/src/jobs/attendance-cleanup-sweep.handler.ts b/server/src/jobs/attendance-cleanup-sweep.handler.ts new file mode 100644 index 00000000..2edfdc49 --- /dev/null +++ b/server/src/jobs/attendance-cleanup-sweep.handler.ts @@ -0,0 +1,133 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { InjectDataSource } from '@nestjs/typeorm'; +import { DataSource, In, Not } from 'typeorm'; +import { Job } from '@shared/entities/Job.entity'; +import { JobHandler, JobResult } from '@shared/utils/jobs/job.types'; +import { getHebrewYearByGregorianDate } from '@shared/utils/entity/year.util'; +import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity'; +import { Lesson } from 'src/db/entities/Lesson.entity'; +import { Klass } from 'src/db/entities/Klass.entity'; +import { StudentKlass } from 'src/db/entities/StudentKlass.entity'; +import { AttReport } from 'src/db/entities/AttReport.entity'; + +/** + * For each active AttendanceCleanupRule owned by the job's user (or a + * specific subset via payload.ruleIds, for the "run now" button), and for + * each of the last `weeksBack` occurrences of `dayOfWeek`, deletes + * att_reports for that lesson+date belonging to any student who is NOT a + * member of the klass being preserved. + * + * Membership is checked via student_klasses (a student's actual track + * assignment for the year) — NOT att_reports.klassReferenceId, which is the + * klass the attendance session/report itself belongs to and is typically + * the same for every row in that report, not each student's own track. + * + * lessonId/klassId on the rule are Lesson.key/Klass.key (stable across + * years) — re-resolved against the target date's own academic year here, + * not against a fixed referenceId, so a rule keeps working after a new + * school year's Lesson/Klass/StudentKlass rows get created with fresh ids. + */ +@Injectable() +export class AttendanceCleanupSweepHandler implements JobHandler { + readonly type = 'attendance-cleanup-sweep'; + private readonly logger = new Logger(AttendanceCleanupSweepHandler.name); + + constructor(@InjectDataSource() private readonly dataSource: DataSource) {} + + async handle(job: Job): Promise { + const ruleRepo = this.dataSource.getRepository(AttendanceCleanupRule); + const ruleIds: number[] = job.payload?.ruleIds ?? []; + + const rules = await ruleRepo.find({ + where: ruleIds.length + ? { userId: job.userId, id: In(ruleIds) } + : { userId: job.userId, active: true }, + }); + + let totalDeleted = 0; + const perRule: string[] = []; + + for (const rule of rules) { + const targetDates = getTargetDates(rule.dayOfWeek, rule.weeksBack); + let ruleDeleted = 0; + const skipped: string[] = []; + + for (const date of targetDates) { + const year = getHebrewYearByGregorianDate(date); + const lesson = await this.dataSource + .getRepository(Lesson) + .findOne({ where: { userId: job.userId, key: rule.lessonId, year } }); + const preserveKlass = await this.dataSource + .getRepository(Klass) + .findOne({ where: { userId: job.userId, key: rule.klassId, year } }); + + if (!lesson || !preserveKlass) { + skipped.push(`${date.toISOString().slice(0, 10)} (שיעור/כיתה לא נמצאו לאותה שנה)`); + continue; + } + + const preservedMemberships = await this.dataSource + .getRepository(StudentKlass) + .find({ where: { userId: job.userId, klassReferenceId: preserveKlass.id, year } }); + const preservedStudentIds = preservedMemberships.map((m) => m.studentReferenceId); + + if (preservedStudentIds.length === 0) { + // No one is recorded as belonging to the preserved klass for this year - safer to + // skip than to delete for everyone, which is what an empty exclusion set would do. + skipped.push(`${date.toISOString().slice(0, 10)} (אין תלמידות משויכות לכיתה הנשמרת לאותה שנה)`); + continue; + } + + const result = await this.dataSource.getRepository(AttReport).delete({ + userId: job.userId, + lessonReferenceId: lesson.id, + reportDate: date, + studentReferenceId: Not(In(preservedStudentIds)), + }); + ruleDeleted += result.affected ?? 0; + } + + totalDeleted += ruleDeleted; + const label = rule.name || `כלל ${rule.id}`; + perRule.push(skipped.length ? `${label}: נמחקו ${ruleDeleted} (דולג על ${skipped.join(', ')})` : `${label}: נמחקו ${ruleDeleted}`); + } + + this.logger.log(`attendance-cleanup-sweep: ${rules.length} rules, ${totalDeleted} att_reports deleted`); + + return { + summary: `נמחקו ${totalDeleted} רשומות נוכחות (${rules.length} כללים)`, + rulesProcessed: rules.length, + totalDeleted, + perRule, + }; + } +} + +/** + * The last `weeksBack` occurrences of `dayOfWeek` (0=Sun..6=Sat), most + * recent first, including today if today is that weekday. + * + * `now` defaults to today's calendar date in Asia/Jerusalem, not the + * server process's own timezone (commonly UTC in production) — using the + * server's local date here could shift "today" by a day right around + * midnight in either timezone and misdate every target date. + */ +export function getTargetDates(dayOfWeek: number, weeksBack: number, now: Date = getIsraelToday()): Date[] { + const diffToMostRecent = (now.getDay() - dayOfWeek + 7) % 7; + const mostRecent = new Date(now.getFullYear(), now.getMonth(), now.getDate() - diffToMostRecent); + + const dates: Date[] = []; + for (let i = 0; i < weeksBack; i++) { + dates.push(new Date(mostRecent.getFullYear(), mostRecent.getMonth(), mostRecent.getDate() - i * 7)); + } + return dates; +} + +/** Today's calendar date in Asia/Jerusalem, as a timezone-naive local Date (midnight). */ +export function getIsraelToday(): Date { + const [y, m, d] = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Jerusalem' }) + .format(new Date()) + .split('-') + .map(Number); + return new Date(y, m - 1, d); +} diff --git a/server/src/migrations/1787200000000-addAttendanceCleanupRulesTable.ts b/server/src/migrations/1787200000000-addAttendanceCleanupRulesTable.ts new file mode 100644 index 00000000..5b8fbb5f --- /dev/null +++ b/server/src/migrations/1787200000000-addAttendanceCleanupRulesTable.ts @@ -0,0 +1,31 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class addAttendanceCleanupRulesTable1787200000000 implements MigrationInterface { + name = 'addAttendanceCleanupRulesTable1787200000000' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE IF NOT EXISTS \`attendance_cleanup_rules\` ( + \`id\` int NOT NULL AUTO_INCREMENT, + \`user_id\` int NOT NULL, + \`name\` varchar(255) NULL, + \`lesson_id\` int NOT NULL, + \`lessonReferenceId\` int NULL, + \`klass_id\` int NOT NULL, + \`klassReferenceId\` int NULL, + \`day_of_week\` int NOT NULL, + \`weeks_back\` int NOT NULL DEFAULT '2', + \`active\` tinyint NOT NULL DEFAULT '1', + \`created_at\` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + \`updated_at\` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (\`id\`), + INDEX \`attendance_cleanup_rules_users_idx\` (\`user_id\`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP TABLE IF EXISTS \`attendance_cleanup_rules\``); + } + +}