From 374cba462aa2ed5f49005c47e0f2dd7230d5933d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 19 Aug 2026 20:04:21 +0000 Subject: [PATCH 1/4] Add attendance-cleanup-sweep: recurring per-lesson attendance cleanup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Self-service, recurring attendance cleanup requested by a paying client: for a chosen lesson and a klass/track to preserve, every student NOT in that track has att_reports deleted for that lesson across the last N occurrences of a chosen weekday, run automatically every Motzei Shabbat. - AttendanceCleanupRule entity: friendly CRUD (lesson/klass reference dropdowns, day-of-week select, weeks-back, active). Stores lessonId/klassId as Lesson.key/Klass.key (stable across years), not a fixed referenceId, so a rule doesn't go stale when a new school year's Lesson/Klass rows get created with fresh ids. - attendance-cleanup-sweep job handler: re-resolves lessonId/klassId against each target date's own academic year at run time, then deletes att_reports for that lesson+date where klass != preserved klass. Skips (rather than over-deletes) a date it can't resolve. - "Run now" bulk button on the rule list enqueues the same handler scoped to the selected rule ids, via the job queue infra (buzz-code/nra-server#29..38) already merged into this app (#141). - One weekly Schedule row (jobType: attendance-cleanup-sweep, empty payload) is a one-time manual setup — the sweep itself reads every active rule for that job's user, so new rules need no further setup. - Migration for attendance_cleanup_rules (validated against real MySQL). - Unit tests: date-window computation, handler (scoping, deletion, skip-on-unresolved), doAction routing. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011dEYULADLgGNfZ4nv6gz8s --- client/src/App.jsx | 10 ++ client/src/domainTranslations.js | 15 ++ .../src/entities/attendance-cleanup-rule.jsx | 95 +++++++++++ client/src/roadmapFeatures.js | 1 + server/src/app.module.ts | 2 + .../entities/AttendanceCleanupRule.entity.ts | 149 ++++++++++++++++++ server/src/entities.module.ts | 2 + .../attendance-cleanup-rule.config.spec.ts | 58 +++++++ .../attendance-cleanup-rule.config.ts | 47 ++++++ .../attendance-cleanup-sweep.handler.spec.ts | 101 ++++++++++++ .../jobs/attendance-cleanup-sweep.handler.ts | 105 ++++++++++++ ...00000000-addAttendanceCleanupRulesTable.ts | 31 ++++ 12 files changed, 616 insertions(+) create mode 100644 client/src/entities/attendance-cleanup-rule.jsx create mode 100644 server/src/db/entities/AttendanceCleanupRule.entity.ts create mode 100644 server/src/entity-modules/__tests__/attendance-cleanup-rule.config.spec.ts create mode 100644 server/src/entity-modules/attendance-cleanup-rule.config.ts create mode 100644 server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts create mode 100644 server/src/jobs/attendance-cleanup-sweep.handler.ts create mode 100644 server/src/migrations/1787200000000-addAttendanceCleanupRulesTable.ts 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/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..21dccdc0 --- /dev/null +++ b/server/src/db/entities/AttendanceCleanupRule.entity.ts @@ -0,0 +1,149 @@ +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 { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util'; +import { IsOptional, ValidateIf } 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: for `lessonId` (a Lesson.key, not a + * one-year Lesson.id), on `dayOfWeek`, delete att_reports for every klass + * EXCEPT `klassId` (the klass/track to preserve), 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 — a rule + * is meant to keep working across academic years. lessonReferenceId and + * klassReferenceId below are resolved for display/at save time only; the + * sweep re-resolves lessonId/klassId against the target date's own academic + * year at run time, so the rule doesn't go stale when a new year's + * Lesson/Klass 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.lessonReferenceId = await findOneAndAssignReferenceId( + dataSource, + Lesson, + { key: this.lessonId }, + this.userId, + this.lessonReferenceId, + this.lessonId, + ); + this.klassReferenceId = await findOneAndAssignReferenceId( + dataSource, + Klass, + { key: this.klassId }, + 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; + + /** Lesson.key — resolved to that year's Lesson at sweep time, not fixed at creation. */ + @ValidateIf((rule: AttendanceCleanupRule) => !Boolean(rule.lessonReferenceId), { always: true }) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Column('int', { name: 'lesson_id' }) + lessonId: number; + + @ValidateIf( + (rule: AttendanceCleanupRule) => !Boolean(rule.lessonId) && Boolean(rule.lessonReferenceId), + { always: true }, + ) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @Column({ nullable: true }) + lessonReferenceId: number; + + /** Klass.key of the track/class to PRESERVE — every other klass gets cleaned. */ + @ValidateIf((rule: AttendanceCleanupRule) => !Boolean(rule.klassReferenceId), { always: true }) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + @NumberType + @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) + @Column('int', { name: 'klass_id' }) + klassId: number; + + @ValidateIf( + (rule: AttendanceCleanupRule) => !Boolean(rule.klassId) && Boolean(rule.klassReferenceId), + { always: true }, + ) + @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) + @Column({ nullable: true }) + klassReferenceId: 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-sweep.handler.spec.ts b/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts new file mode 100644 index 00000000..31e17bad --- /dev/null +++ b/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts @@ -0,0 +1,101 @@ +import { In, Not } from 'typeorm'; +import { AttendanceCleanupSweepHandler, getTargetDates } from '../attendance-cleanup-sweep.handler'; +import { Job } from '@shared/entities/Job.entity'; + +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() }, + 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 every klass except the preserved one, across weeksBack dates', 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 }) }, + 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.AttReport.delete).toHaveBeenCalledTimes(2); // weeksBack: 2 + const [firstCallArgs] = dataSource.repos.AttReport.delete.mock.calls[0]; + expect(firstCallArgs).toMatchObject({ userId: 1, lessonReferenceId: 105 }); + expect(firstCallArgs.klassReferenceId).toEqual(Not(103)); + 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('דולג'); + }); +}); 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..8695dec5 --- /dev/null +++ b/server/src/jobs/attendance-cleanup-sweep.handler.ts @@ -0,0 +1,105 @@ +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 { 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 klass OTHER than the + * one being preserved. + * + * 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 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 result = await this.dataSource.getRepository(AttReport).delete({ + userId: job.userId, + lessonReferenceId: lesson.id, + reportDate: date, + klassReferenceId: Not(preserveKlass.id), + }); + 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. + */ +export function getTargetDates(dayOfWeek: number, weeksBack: number, now: Date = new Date()): 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; +} 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\``); + } + +} From 65f3189dbf5c1ae9023e2eb01561e8bb25a5016d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 08:28:04 +0000 Subject: [PATCH 2/4] Fix exclusion source, timezone, weeksBack bounds; surface job result MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three review fixes on the attendance-cleanup-sweep feature: - Correctness: exclusion was checking att_reports.klassReferenceId (the report/session's own klass, the same for every row in it) instead of actual student-klass membership. Now looks up student_klasses for the preserved klass and excludes by studentReferenceId membership. Also flipped AttendanceCleanupRule.fillFields from key->id resolution (which the form never triggers, since it submits the picked referenceId directly) to id->key: the picked lessonReferenceId/ klassReferenceId now correctly resolves down to the stable Lesson.key/Klass.key the sweep needs for cross-year lookups. Without this fix lessonId/klassId would have stayed null forever. - Timezone: getTargetDates defaulted to `new Date()` in the server process's own timezone (commonly UTC in prod), which could misdate every target date by a day. Added getIsraelToday() (Intl.DateTimeFormat pinned to Asia/Jerusalem) as the default anchor instead. - Client weeksBack input had no min/max, so a value outside the server's Min(1)/Max(52) validation would round-trip as a 400. Added matching min/max/step plus minValue/maxValue validators. - Bump client/shared for buzz-code/nra-client#42: the shared Job monitor didn't show `result` at all, so there was no way to see a completed sweep's summary (e.g. "נמחקו 14 רשומות נוכחות") without querying the API directly. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011dEYULADLgGNfZ4nv6gz8s --- client/shared | 2 +- .../src/entities/attendance-cleanup-rule.jsx | 12 ++- .../entities/AttendanceCleanupRule.entity.ts | 90 +++++++++---------- .../AttendanceCleanupRule.entity.spec.ts | 62 +++++++++++++ .../attendance-cleanup-sweep.handler.spec.ts | 48 +++++++++- .../jobs/attendance-cleanup-sweep.handler.ts | 50 ++++++++--- 6 files changed, 198 insertions(+), 66 deletions(-) create mode 100644 server/src/db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts 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/entities/attendance-cleanup-rule.jsx b/client/src/entities/attendance-cleanup-rule.jsx index 71b635d2..6deadc9e 100644 --- a/client/src/entities/attendance-cleanup-rule.jsx +++ b/client/src/entities/attendance-cleanup-rule.jsx @@ -3,6 +3,8 @@ import { BooleanInput, DateField, FunctionField, + maxValue, + minValue, NumberField, NumberInput, ReferenceField, @@ -79,7 +81,15 @@ const Inputs = ({ isCreate, isAdmin }) => { helperText="הכיתה/מסלול שישמר - הנוכחות תימחק לכל שאר הכיתות" /> - + ); diff --git a/server/src/db/entities/AttendanceCleanupRule.entity.ts b/server/src/db/entities/AttendanceCleanupRule.entity.ts index 21dccdc0..fcf978cc 100644 --- a/server/src/db/entities/AttendanceCleanupRule.entity.ts +++ b/server/src/db/entities/AttendanceCleanupRule.entity.ts @@ -11,8 +11,8 @@ import { } from 'typeorm'; import { IHasUserId } from '@shared/base-entity/interface'; import { BooleanIntColumn } from '@shared/utils/entity/column-types.util'; -import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util'; -import { IsOptional, ValidateIf } from 'class-validator'; +import { 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'; @@ -22,18 +22,21 @@ import { Klass } from './Klass.entity'; import { User } from './User.entity'; /** - * A recurring attendance-cleanup rule: for `lessonId` (a Lesson.key, not a - * one-year Lesson.id), on `dayOfWeek`, delete att_reports for every klass - * EXCEPT `klassId` (the klass/track to preserve), for each of the last - * `weeksBack` occurrences of that weekday. Consumed weekly by the - * attendance-cleanup-sweep job handler. + * 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 — a rule - * is meant to keep working across academic years. lessonReferenceId and - * klassReferenceId below are resolved for display/at save time only; the - * sweep re-resolves lessonId/klassId against the target date's own academic - * year at run time, so the rule doesn't go stale when a new year's - * Lesson/Klass rows get created with fresh ids. + * 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') @@ -45,22 +48,18 @@ export class AttendanceCleanupRule implements IHasUserId { try { dataSource = await getDataSource([Lesson, Klass, User]); - this.lessonReferenceId = await findOneAndAssignReferenceId( - dataSource, - Lesson, - { key: this.lessonId }, - this.userId, - this.lessonReferenceId, - this.lessonId, - ); - this.klassReferenceId = await findOneAndAssignReferenceId( - dataSource, - Klass, - { key: this.klassId }, - this.userId, - this.klassReferenceId, - this.klassId, - ); + if (this.lessonReferenceId) { + const lesson = await dataSource + .getRepository(Lesson) + .findOne({ where: { id: this.lessonReferenceId, userId: this.userId } }); + this.lessonId = lesson?.key ?? this.lessonId; + } + if (this.klassReferenceId) { + const klass = await dataSource + .getRepository(Klass) + .findOne({ where: { id: this.klassReferenceId, userId: this.userId } }); + this.klassId = klass?.key ?? this.klassId; + } } finally { dataSource?.destroy(); } @@ -78,40 +77,31 @@ export class AttendanceCleanupRule implements IHasUserId { @Column('varchar', { name: 'name', length: 255, nullable: true }) name: string | null; - /** Lesson.key — resolved to that year's Lesson at sweep time, not fixed at creation. */ - @ValidateIf((rule: AttendanceCleanupRule) => !Boolean(rule.lessonReferenceId), { always: true }) @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' }) + @Column('int', { name: 'lesson_id', nullable: true }) lessonId: number; - @ValidateIf( - (rule: AttendanceCleanupRule) => !Boolean(rule.lessonId) && Boolean(rule.lessonReferenceId), - { always: true }, - ) + /** 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 }) - lessonReferenceId: number; + klassReferenceId: number; - /** Klass.key of the track/class to PRESERVE — every other klass gets cleaned. */ - @ValidateIf((rule: AttendanceCleanupRule) => !Boolean(rule.klassReferenceId), { always: true }) - @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) - @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) + /** Klass.key, derived from klassReferenceId in fillFields — not user-editable. */ + @IsOptional({ always: true }) @NumberType @IsNumber({ maxDecimalPlaces: 0 }, { always: true }) - @Column('int', { name: 'klass_id' }) + @Column('int', { name: 'klass_id', nullable: true }) klassId: number; - @ValidateIf( - (rule: AttendanceCleanupRule) => !Boolean(rule.klassId) && Boolean(rule.klassReferenceId), - { always: true }, - ) - @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) - @Column({ nullable: true }) - klassReferenceId: number; - /** 0=Sunday .. 6=Saturday (JS Date.getDay() convention). */ @IsNotEmpty({ groups: [CrudValidationGroups.CREATE] }) @IsOptional({ groups: [CrudValidationGroups.UPDATE] }) diff --git a/server/src/db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts b/server/src/db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts new file mode 100644 index 00000000..7712f817 --- /dev/null +++ b/server/src/db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts @@ -0,0 +1,62 @@ +const mockDestroy = jest.fn(); +const mockGetRepository = jest.fn(); + +jest.mock('@shared/utils/entity/foreignKey.util', () => ({ + getDataSource: jest.fn().mockResolvedValue({ + getRepository: (...args: any[]) => mockGetRepository(...args), + destroy: mockDestroy, + }), +})); + +import { AttendanceCleanupRule } from '../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 index 31e17bad..2025a45e 100644 --- a/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts +++ b/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts @@ -1,7 +1,22 @@ import { In, Not } from 'typeorm'; -import { AttendanceCleanupSweepHandler, getTargetDates } from '../attendance-cleanup-sweep.handler'; +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) @@ -31,6 +46,7 @@ describe('AttendanceCleanupSweepHandler', () => { 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, }; @@ -57,7 +73,7 @@ describe('AttendanceCleanupSweepHandler', () => { }); }); - it('deletes att_reports for every klass except the preserved one, across weeksBack dates', async () => { + it('deletes att_reports for students NOT recorded as members of the preserved klass', async () => { const dataSource = makeDataSource({ AttendanceCleanupRule: { find: jest.fn().mockResolvedValue([ @@ -66,16 +82,22 @@ describe('AttendanceCleanupSweepHandler', () => { }, 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.klassReferenceId).toEqual(Not(103)); + expect(firstCallArgs.studentReferenceId).toEqual(Not(In([201, 202]))); expect(result.totalDeleted).toBe(14); // 7 + 7 expect(result.rulesProcessed).toBe(1); }); @@ -98,4 +120,24 @@ describe('AttendanceCleanupSweepHandler', () => { 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 index 8695dec5..2edfdc49 100644 --- a/server/src/jobs/attendance-cleanup-sweep.handler.ts +++ b/server/src/jobs/attendance-cleanup-sweep.handler.ts @@ -7,19 +7,25 @@ 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 klass OTHER than the - * one being preserved. + * 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 rows get created with fresh ids. + * school year's Lesson/Klass/StudentKlass rows get created with fresh ids. */ @Injectable() export class AttendanceCleanupSweepHandler implements JobHandler { @@ -56,7 +62,19 @@ export class AttendanceCleanupSweepHandler implements JobHandler { .findOne({ where: { userId: job.userId, key: rule.klassId, year } }); if (!lesson || !preserveKlass) { - skipped.push(date.toISOString().slice(0, 10)); + 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; } @@ -64,18 +82,14 @@ export class AttendanceCleanupSweepHandler implements JobHandler { userId: job.userId, lessonReferenceId: lesson.id, reportDate: date, - klassReferenceId: Not(preserveKlass.id), + 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}`, - ); + perRule.push(skipped.length ? `${label}: נמחקו ${ruleDeleted} (דולג על ${skipped.join(', ')})` : `${label}: נמחקו ${ruleDeleted}`); } this.logger.log(`attendance-cleanup-sweep: ${rules.length} rules, ${totalDeleted} att_reports deleted`); @@ -92,8 +106,13 @@ export class AttendanceCleanupSweepHandler implements JobHandler { /** * 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 = new Date()): 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); @@ -103,3 +122,12 @@ export function getTargetDates(dayOfWeek: number, weeksBack: number, now: Date = } 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); +} From 115aa96aa5e02119bab300917ab02ed873007463 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 08:37:09 +0000 Subject: [PATCH 3/4] Move AttendanceCleanupRule entity spec out of src/db/entities/ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit real-data-source.ts globs every .ts under src/db/** as an entity module (join(serverRoot, 'src/db/**/*.{js,ts}')) — no other entity in this repo has a colocated spec, so this was never exercised before. With the spec under src/db/entities/__tests__/, TypeORM's real DataSource.initialize() (used by shared/utils/yemot/testing) required the spec file as an entity, executing its top-level describe/it calls outside Jest's own run and breaking 4 unrelated suites with "Tests cannot be nested". Moved to src/jobs/__tests__/, alongside the rest of this feature's tests, which isn't part of that glob. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011dEYULADLgGNfZ4nv6gz8s --- .../__tests__/attendance-cleanup-rule.entity.spec.ts} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename server/src/{db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts => jobs/__tests__/attendance-cleanup-rule.entity.spec.ts} (95%) diff --git a/server/src/db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts b/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts similarity index 95% rename from server/src/db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts rename to server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts index 7712f817..9702d753 100644 --- a/server/src/db/entities/__tests__/AttendanceCleanupRule.entity.spec.ts +++ b/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts @@ -8,7 +8,7 @@ jest.mock('@shared/utils/entity/foreignKey.util', () => ({ }), })); -import { AttendanceCleanupRule } from '../AttendanceCleanupRule.entity'; +import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity'; describe('AttendanceCleanupRule.fillFields', () => { beforeEach(() => { From 538dfa32d21046e9ee82b2ac10664148e2e1f92b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 08:45:37 +0000 Subject: [PATCH 4/4] Use shared findOneAndAssignKey for the id->key resolution Bump server/shared for buzz-code/nra-server#39 and replace AttendanceCleanupRule's inline id->key lookups with the new shared helper, mirroring the existing key->id convention used everywhere else in this codebase. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011dEYULADLgGNfZ4nv6gz8s --- server/shared | 2 +- .../db/entities/AttendanceCleanupRule.entity.ts | 16 +++------------- .../attendance-cleanup-rule.entity.spec.ts | 4 ++++ 3 files changed, 8 insertions(+), 14 deletions(-) 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/db/entities/AttendanceCleanupRule.entity.ts b/server/src/db/entities/AttendanceCleanupRule.entity.ts index fcf978cc..e9f6dc33 100644 --- a/server/src/db/entities/AttendanceCleanupRule.entity.ts +++ b/server/src/db/entities/AttendanceCleanupRule.entity.ts @@ -11,7 +11,7 @@ import { } from 'typeorm'; import { IHasUserId } from '@shared/base-entity/interface'; import { BooleanIntColumn } from '@shared/utils/entity/column-types.util'; -import { getDataSource } from '@shared/utils/entity/foreignKey.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'; @@ -48,18 +48,8 @@ export class AttendanceCleanupRule implements IHasUserId { try { dataSource = await getDataSource([Lesson, Klass, User]); - if (this.lessonReferenceId) { - const lesson = await dataSource - .getRepository(Lesson) - .findOne({ where: { id: this.lessonReferenceId, userId: this.userId } }); - this.lessonId = lesson?.key ?? this.lessonId; - } - if (this.klassReferenceId) { - const klass = await dataSource - .getRepository(Klass) - .findOne({ where: { id: this.klassReferenceId, userId: this.userId } }); - this.klassId = klass?.key ?? this.klassId; - } + 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(); } diff --git a/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts b/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts index 9702d753..1bc06022 100644 --- a/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts +++ b/server/src/jobs/__tests__/attendance-cleanup-rule.entity.spec.ts @@ -1,7 +1,11 @@ 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,