diff --git a/client/src/domainTranslations.js b/client/src/domainTranslations.js index 43c343e5..1e546d5c 100644 --- a/client/src/domainTranslations.js +++ b/client/src/domainTranslations.js @@ -452,9 +452,12 @@ export default { dayOfWeek: 'יום בשבוע', weeksBack: 'שבועות אחורה', active: 'פעיל?', + lastRunAt: 'הרצה אחרונה', + lastRunSummary: 'תוצאת הרצה אחרונה', }, actions: { runNow: 'הרץ עכשיו', + preview: 'מי תימחק? (תצוגה מקדימה)', }, }, grade_effect_by_user: { diff --git a/client/src/entities/attendance-cleanup-rule.jsx b/client/src/entities/attendance-cleanup-rule.jsx index 6deadc9e..38bc9f58 100644 --- a/client/src/entities/attendance-cleanup-rule.jsx +++ b/client/src/entities/attendance-cleanup-rule.jsx @@ -1,5 +1,7 @@ +import { useState } from 'react'; import { BooleanField, + Button, BooleanInput, DateField, FunctionField, @@ -12,14 +14,21 @@ import { SelectInput, TextField, TextInput, + useDataProvider, + useListContext, + useNotify, + useRefresh, } from 'react-admin'; +import { Dialog, DialogActions, DialogContent, DialogTitle, Typography } from '@mui/material'; +import PlayArrowIcon from '@mui/icons-material/PlayArrow'; +import VisibilityIcon from '@mui/icons-material/Visibility'; +import { handleError } from '@shared/utils/notifyUtil'; import { CommonDatagrid } from '@shared/components/crudContainers/CommonList'; import { CommonRepresentation } from '@shared/components/CommonRepresentation'; import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity'; import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput'; import { CommonReferenceInputFilter, filterByUserId } from '@shared/components/fields/CommonReferenceInputFilter'; import { commonAdminFilters } from '@shared/components/fields/PermissionFilter'; -import { BulkActionButton } from '@shared/components/crudContainers/BulkActionButton'; const dayOfWeekChoices = [ { id: 0, name: 'ראשון' }, @@ -37,9 +46,49 @@ const filters = [ , ]; +// Runs a rule action on the selected rules and shows the per-rule result in a dialog +// (a notification is too short-lived for a list of dates and student names). +const RuleResultButton = ({ label, name, icon }) => { + const dataProvider = useDataProvider(); + const { selectedIds, resource } = useListContext(); + const notify = useNotify(); + const refresh = useRefresh(); + const [result, setResult] = useState(null); + const [isLoading, setIsLoading] = useState(false); + + const handleClick = async () => { + setIsLoading(true); + try { + const response = await dataProvider.action(resource, name, { 'extra.ids': selectedIds }); + setResult(typeof response.body === 'string' ? response.body : JSON.stringify(response.body)); + refresh(); + } catch (error) { + handleError(notify)(error); + } finally { + setIsLoading(false); + } + }; + + return ( + <> + + setResult(null)} fullWidth maxWidth="md"> + {label} + + {result} + + + + + ); +}; + const Datagrid = ({ isAdmin, children, ...props }) => { const additionalBulkButtons = [ - , + } />, + } />, ]; return ( @@ -55,6 +104,8 @@ const Datagrid = ({ isAdmin, children, ...props }) => { /> + + {isAdmin && } ); diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js index 603ea138..48da429a 100644 --- a/client/src/roadmapFeatures.js +++ b/client/src/roadmapFeatures.js @@ -48,4 +48,5 @@ export default [ { html: 'דיווחים למורה וציונים למורה: סינון "יש שיעורים שלא דווחו", ומיון לפי מספר השיעורים שדווחו / שלא דווחו', status: 'בוצע', statusColor: 'success' }, { html: 'דף חדש "אפשרויות שדרוג" בהסברים נוספים: כל היכולות שאפשר להפעיל בהרשאה, עם הסבר ומחיר', status: 'בוצע', statusColor: 'success' }, { html: 'התקנה כאפליקציה: אפשר להתקין את המערכת מהדפדפן (בכרום: סמל ההתקנה בשורת הכתובת) ולפתוח אותה בחלון נפרד, עם לוגו משלה בשולחן העבודה ובשורת המשימות', status: 'בוצע', statusColor: 'success' }, + { html: 'כללי ניקוי נוכחות: הצגת ההרצה האחרונה (מתי, כמה נמחקו ומה דולג), כפתור "מי תימחק?" לתצוגה מקדימה בלי מחיקה, וסיכום מיד אחרי "הרץ עכשיו"', status: 'בוצע', statusColor: 'success' }, ].reverse(); diff --git a/server/src/db/entities/AttendanceCleanupRule.entity.ts b/server/src/db/entities/AttendanceCleanupRule.entity.ts index 77a0e81e..16d9dadf 100644 --- a/server/src/db/entities/AttendanceCleanupRule.entity.ts +++ b/server/src/db/entities/AttendanceCleanupRule.entity.ts @@ -117,6 +117,16 @@ export class AttendanceCleanupRule implements IHasUserId { @Column('boolean', { name: 'active', default: true }) active: boolean; + /** Set by the sweep after each real run - read-only for the client. */ + @IsOptional({ always: true }) + @Column('datetime', { name: 'last_run_at', nullable: true }) + lastRunAt: Date | null; + + /** What the last run did: how many att_reports it deleted and which dates it skipped, and why. */ + @IsOptional({ always: true }) + @Column('text', { name: 'last_run_summary', nullable: true }) + lastRunSummary: string | null; + @CreatedAtColumn() createdAt: Date; 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 index 3b525ddd..f8f56079 100644 --- a/server/src/entity-modules/__tests__/attendance-cleanup-rule.config.spec.ts +++ b/server/src/entity-modules/__tests__/attendance-cleanup-rule.config.spec.ts @@ -3,6 +3,11 @@ import { ADMIN_FILTER, CrudAuthFilter } from '@shared/auth/crud-auth.filter'; import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity'; import attendanceCleanupRuleConfig from '../attendance-cleanup-rule.config'; +const mockRunCleanupRules = jest.fn(); +jest.mock('src/jobs/attendance-cleanup-sweep.handler', () => ({ + runCleanupRules: (...args: any[]) => mockRunCleanupRules(...args), +})); + describe('AttendanceCleanupRuleConfig', () => { it('should have correct base configuration', () => { expect(attendanceCleanupRuleConfig.entity).toBe(AttendanceCleanupRule); @@ -34,7 +39,7 @@ describe('AttendanceCleanupRuleConfig', () => { }); }); - describe('doAction: runNow', () => { + describe('doAction: runNow / preview', () => { function makeService() { const ServiceClass = attendanceCleanupRuleConfig.service as any; const mockRepository = { @@ -46,63 +51,83 @@ describe('AttendanceCleanupRuleConfig', () => { targetName: 'AttendanceCleanupRule', }, } as any; - const jobService = { enqueue: jest.fn().mockResolvedValue({ id: 42 }) }; - const service = new ServiceClass(mockRepository, {} as any, jobService); - return { service, jobService }; + const service = new ServiceClass(mockRepository, {} as any); + service.dataSource = { name: 'ds' }; + return { service }; } - function makeReq(ids: string) { + function makeReq(ids: string, action = 'runNow') { // getManyByIds is what actually applies crudAuth's filter (via createBuilder) - it's // mocked here rather than re-testing that plumbing, which base-entity.service.spec.ts // already covers directly. const req = { auth: { id: -1, permissions: { admin: true } }, - parsed: { extra: { action: 'runNow', ids } }, + parsed: { extra: { action, ids } }, options: {}, } as unknown as CrudRequest; return req; } - it("enqueues a job scoped to the resolved rules' own userId", async () => { - const { service, jobService } = makeService(); - jest.spyOn(service, 'getManyByIds').mockResolvedValue([ + beforeEach(() => { + mockRunCleanupRules.mockReset(); + mockRunCleanupRules.mockImplementation(async (_ds, _userId, rules) => ({ + totalDeleted: rules.length, + perRule: rules.map((rule) => `כלל ${rule.id}: נמחקו 1`), + })); + }); + + it("runs the resolved rules under their own userId and returns the summary", async () => { + const { service } = makeService(); + const rules = [ { id: 1, userId: 38 }, { id: 2, userId: 38 }, - ] as any); + ]; + jest.spyOn(service, 'getManyByIds').mockResolvedValue(rules as any); const req = makeReq('1,2'); const message = await service.doAction(req, {}); expect(service.getManyByIds).toHaveBeenCalledWith(req, [1, 2]); - expect(jobService.enqueue).toHaveBeenCalledTimes(1); - expect(jobService.enqueue).toHaveBeenCalledWith(38, 'attendance-cleanup-sweep', { ruleIds: [1, 2] }); - expect(message).toContain('42'); + expect(mockRunCleanupRules).toHaveBeenCalledTimes(1); + expect(mockRunCleanupRules).toHaveBeenCalledWith(service.dataSource, 38, rules, false); + expect(message).toContain('נמחקו 2'); + expect(message).toContain('כלל 1: נמחקו 1'); }); - it('enqueues nothing when none of the selected ids resolve for this caller', async () => { - const { service, jobService } = makeService(); + it('runs nothing when none of the selected ids resolve for this caller', async () => { + const { service } = makeService(); jest.spyOn(service, 'getManyByIds').mockResolvedValue([]); const req = makeReq('99'); // e.g. owned by someone else, filtered out by crudAuth const message = await service.doAction(req, {}); - expect(jobService.enqueue).not.toHaveBeenCalled(); + expect(mockRunCleanupRules).not.toHaveBeenCalled(); expect(message).toContain('0'); }); - it('enqueues one job per distinct owner when the resolved rules span multiple users', async () => { - const { service, jobService } = makeService(); + it('runs once per distinct owner when the resolved rules span multiple users', async () => { + const { service } = makeService(); jest.spyOn(service, 'getManyByIds').mockResolvedValue([ { id: 1, userId: 38 }, { id: 2, userId: 39 }, ] as any); - const req = makeReq('1,2'); - await service.doAction(req, {}); + await service.doAction(makeReq('1,2'), {}); + + expect(mockRunCleanupRules).toHaveBeenCalledTimes(2); + expect(mockRunCleanupRules).toHaveBeenCalledWith(service.dataSource, 38, [{ id: 1, userId: 38 }], false); + expect(mockRunCleanupRules).toHaveBeenCalledWith(service.dataSource, 39, [{ id: 2, userId: 39 }], false); + }); + + it('preview runs as a dry run and says nothing was deleted', async () => { + const { service } = makeService(); + const rules = [{ id: 1, userId: 38 }]; + jest.spyOn(service, 'getManyByIds').mockResolvedValue(rules as any); + + const message = await service.doAction(makeReq('1', 'preview'), {}); - expect(jobService.enqueue).toHaveBeenCalledTimes(2); - expect(jobService.enqueue).toHaveBeenCalledWith(38, 'attendance-cleanup-sweep', { ruleIds: [1] }); - expect(jobService.enqueue).toHaveBeenCalledWith(39, 'attendance-cleanup-sweep', { ruleIds: [2] }); + expect(mockRunCleanupRules).toHaveBeenCalledWith(service.dataSource, 38, rules, true); + expect(message).toContain('לא נמחק כלום'); }); it('falls through to the base doAction for unknown actions', async () => { diff --git a/server/src/entity-modules/attendance-cleanup-rule.config.ts b/server/src/entity-modules/attendance-cleanup-rule.config.ts index 18e97a94..209e5ef8 100644 --- a/server/src/entity-modules/attendance-cleanup-rule.config.ts +++ b/server/src/entity-modules/attendance-cleanup-rule.config.ts @@ -4,15 +4,14 @@ import { CrudAuthFilter } from '@shared/auth/crud-auth.filter'; 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'; +import { runCleanupRules } from 'src/jobs/attendance-cleanup-sweep.handler'; class AttendanceCleanupRuleService extends BaseEntityService { constructor( @InjectEntityRepository repo: Repository, mailSendService: MailSendService, - private readonly jobService: JobService, ) { super(repo, mailSendService); } @@ -20,23 +19,33 @@ class AttendanceCleanupRuleService ext async doAction(req: CrudRequest, body: any): Promise { const extra = req.parsed.extra; switch (extra.action) { - case 'runNow': { + case 'runNow': + case 'preview': { const ruleIds = getAsNumberArray(extra.ids) ?? []; // getManyByIds applies crudAuth's filter (already merged into req.parsed.search // by CrudRequestInterceptor) - a non-owned id in the selection simply doesn't // come back, instead of being trusted from the request. const rules = (await this.getManyByIds(req, ruleIds)) as unknown as AttendanceCleanupRule[]; - // Admin sees everyone, so a selection can still span multiple owners - scope - // each enqueued job to its own rule subset. + const dryRun = extra.action === 'preview'; + // Admin sees everyone, so a selection can still span multiple owners - run + // each owner's rules under its own userId. const userIds = [...new Set(rules.map((rule) => rule.userId))]; - const jobs = await Promise.all( - userIds.map((userId) => - this.jobService.enqueue(userId, 'attendance-cleanup-sweep', { - ruleIds: rules.filter((rule) => rule.userId === userId).map((rule) => rule.id), - }), - ), - ); - return `נוצרו ${jobs.length} משימות ניקוי נוכחות (מזהים: ${jobs.map((job) => job.id).join(', ')})`; + let totalDeleted = 0; + const perRule: string[] = []; + for (const userId of userIds) { + const result = await runCleanupRules( + this.dataSource, + userId, + rules.filter((rule) => rule.userId === userId), + dryRun, + ); + totalDeleted += result.totalDeleted; + perRule.push(...result.perRule); + } + const header = dryRun + ? `תצוגה מקדימה, לא נמחק כלום. יימחקו ${totalDeleted} רשומות נוכחות` + : `נמחקו ${totalDeleted} רשומות נוכחות`; + return [header, ...perRule].join('\n'); } } return super.doAction(req, body); 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 2025a45e..7cd759de 100644 --- a/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts +++ b/server/src/jobs/__tests__/attendance-cleanup-sweep.handler.spec.ts @@ -1,5 +1,5 @@ import { In, Not } from 'typeorm'; -import { AttendanceCleanupSweepHandler, getIsraelToday, getTargetDates } from '../attendance-cleanup-sweep.handler'; +import { AttendanceCleanupSweepHandler, getIsraelToday, getTargetDates, runCleanupRules } from '../attendance-cleanup-sweep.handler'; import { Job } from '@shared/entities/Job.entity'; describe('getIsraelToday', () => { @@ -43,11 +43,11 @@ describe('getTargetDates', () => { describe('AttendanceCleanupSweepHandler', () => { function makeDataSource(overrides: Partial> = {}) { const repos: Record = { - AttendanceCleanupRule: { find: jest.fn().mockResolvedValue([]) }, + AttendanceCleanupRule: { find: jest.fn().mockResolvedValue([]), update: jest.fn() }, Lesson: { findOne: jest.fn() }, Klass: { findOne: jest.fn() }, StudentKlass: { find: jest.fn().mockResolvedValue([]) }, - AttReport: { delete: jest.fn().mockResolvedValue({ affected: 0 }) }, + AttReport: { delete: jest.fn().mockResolvedValue({ affected: 0 }), find: jest.fn().mockResolvedValue([]) }, ...overrides, }; return { @@ -76,6 +76,7 @@ describe('AttendanceCleanupSweepHandler', () => { it('deletes att_reports for students NOT recorded as members of the preserved klass', async () => { const dataSource = makeDataSource({ AttendanceCleanupRule: { + update: jest.fn(), find: jest.fn().mockResolvedValue([ { id: 1, userId: 1, name: 'תפילה', lessonId: 5, klassId: 3, dayOfWeek: 4, weeksBack: 2, active: true }, ]), @@ -100,11 +101,38 @@ describe('AttendanceCleanupSweepHandler', () => { expect(firstCallArgs.studentReferenceId).toEqual(Not(In([201, 202]))); expect(result.totalDeleted).toBe(14); // 7 + 7 expect(result.rulesProcessed).toBe(1); + expect(dataSource.repos.AttendanceCleanupRule.update).toHaveBeenCalledWith(1, { + lastRunAt: expect.any(Date), + lastRunSummary: 'נמחקו 14', + }); + }); + + it('dry run lists the students that would be deleted, without deleting or saving a last run', async () => { + const rule = { id: 1, userId: 1, name: 'תפילה', lessonId: 5, klassId: 3, dayOfWeek: 4, weeksBack: 1, active: true }; + const dataSource = makeDataSource({ + Lesson: { findOne: jest.fn().mockResolvedValue({ id: 105 }) }, + Klass: { findOne: jest.fn().mockResolvedValue({ id: 103 }) }, + StudentKlass: { find: jest.fn().mockResolvedValue([{ studentReferenceId: 201 }]) }, + AttReport: { + delete: jest.fn(), + find: jest.fn().mockResolvedValue([{ student: { name: 'רחל' } }, { student: null, studentTz: '123' }]), + }, + }); + + const result = await runCleanupRules(dataSource, 1, [rule as any], true); + + expect(dataSource.repos.AttReport.delete).not.toHaveBeenCalled(); + expect(dataSource.repos.AttendanceCleanupRule.update).not.toHaveBeenCalled(); + expect(dataSource.repos.AttReport.find.mock.calls[0][0].where.studentReferenceId).toEqual(Not(In([201]))); + expect(result.totalDeleted).toBe(2); + expect(result.perRule[0]).toContain('יימחקו 2'); + expect(result.perRule[0]).toContain('רחל, 123'); }); it('skips a date when the lesson or klass cannot be resolved for that year, without deleting', async () => { const dataSource = makeDataSource({ AttendanceCleanupRule: { + update: jest.fn(), find: jest.fn().mockResolvedValue([ { id: 2, userId: 1, name: null, lessonId: 5, klassId: 3, dayOfWeek: 4, weeksBack: 1, active: true }, ]), @@ -124,6 +152,7 @@ describe('AttendanceCleanupSweepHandler', () => { 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: { + update: jest.fn(), find: jest.fn().mockResolvedValue([ { id: 3, userId: 1, name: 'x', lessonId: 5, klassId: 3, dayOfWeek: 4, weeksBack: 1, active: true }, ]), diff --git a/server/src/jobs/attendance-cleanup-sweep.handler.ts b/server/src/jobs/attendance-cleanup-sweep.handler.ts index 2edfdc49..ca945b39 100644 --- a/server/src/jobs/attendance-cleanup-sweep.handler.ts +++ b/server/src/jobs/attendance-cleanup-sweep.handler.ts @@ -44,53 +44,7 @@ export class AttendanceCleanupSweepHandler implements JobHandler { : { 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}`); - } + const { totalDeleted, perRule } = await runCleanupRules(this.dataSource, job.userId, rules); this.logger.log(`attendance-cleanup-sweep: ${rules.length} rules, ${totalDeleted} att_reports deleted`); @@ -103,6 +57,100 @@ export class AttendanceCleanupSweepHandler implements JobHandler { } } +/** + * Runs the given rules (all owned by `userId`). With `dryRun`, deletes nothing and + * instead lists the students whose att_reports would be deleted on each date. + * A real run also stores its outcome on each rule (lastRunAt/lastRunSummary), so the + * client can see what the last run did. + */ +export async function runCleanupRules( + dataSource: DataSource, + userId: number, + rules: AttendanceCleanupRule[], + dryRun = false, +): Promise<{ totalDeleted: number; perRule: string[] }> { + let totalDeleted = 0; + const perRule: string[] = []; + + for (const rule of rules) { + const targetDates = getTargetDates(rule.dayOfWeek, rule.weeksBack); + let ruleDeleted = 0; + const skipped: string[] = []; + const preview: string[] = []; + + for (const date of targetDates) { + const dateLabel = formatDate(date); + const year = getHebrewYearByGregorianDate(date); + const lesson = await dataSource + .getRepository(Lesson) + .findOne({ where: { userId, key: rule.lessonId, year } }); + const preserveKlass = await dataSource + .getRepository(Klass) + .findOne({ where: { userId, key: rule.klassId, year } }); + + if (!lesson || !preserveKlass) { + skipped.push(`${dateLabel} (שיעור/כיתה לא נמצאו לאותה שנה)`); + continue; + } + + const preservedMemberships = await dataSource + .getRepository(StudentKlass) + .find({ where: { 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(`${dateLabel} (אין תלמידות משויכות לכיתה הנשמרת לאותה שנה)`); + continue; + } + + const where = { + userId, + lessonReferenceId: lesson.id, + reportDate: date, + studentReferenceId: Not(In(preservedStudentIds)), + }; + + if (dryRun) { + const reports = await dataSource.getRepository(AttReport).find({ where, relations: { student: true } }); + ruleDeleted += reports.length; + if (reports.length) { + preview.push(`${dateLabel}: ${reports.map((r) => r.student?.name ?? r.studentTz).join(', ')}`); + } + continue; + } + + const result = await dataSource.getRepository(AttReport).delete(where); + ruleDeleted += result.affected ?? 0; + } + + totalDeleted += ruleDeleted; + const label = rule.name || `כלל ${rule.id}`; + const skippedText = skipped.length ? ` (דולג על ${skipped.join(', ')})` : ''; + + if (dryRun) { + const details = preview.length ? `: ${preview.join('; ')}` : ''; + perRule.push(`${label}: יימחקו ${ruleDeleted}${details}${skippedText}`); + continue; + } + + const summary = `נמחקו ${ruleDeleted}${skippedText}`; + perRule.push(`${label}: ${summary}`); + // update() (not save()) so the entity's @BeforeUpdate key resolution doesn't run. + await dataSource.getRepository(AttendanceCleanupRule).update(rule.id, { + lastRunAt: new Date(), + lastRunSummary: summary, + }); + } + + return { totalDeleted, perRule }; +} + +function formatDate(date: Date): string { + return `${date.getDate()}.${date.getMonth() + 1}.${date.getFullYear()}`; +} + /** * The last `weeksBack` occurrences of `dayOfWeek` (0=Sun..6=Sat), most * recent first, including today if today is that weekday. diff --git a/server/src/migrations/1794780000000-addAttendanceCleanupRuleLastRun.ts b/server/src/migrations/1794780000000-addAttendanceCleanupRuleLastRun.ts new file mode 100644 index 00000000..4f43231b --- /dev/null +++ b/server/src/migrations/1794780000000-addAttendanceCleanupRuleLastRun.ts @@ -0,0 +1,22 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class addAttendanceCleanupRuleLastRun1794780000000 implements MigrationInterface { + name = 'addAttendanceCleanupRuleLastRun1794780000000' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE \`attendance_cleanup_rules\` + ADD \`last_run_at\` datetime NULL, + ADD \`last_run_summary\` text NULL + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE \`attendance_cleanup_rules\` + DROP COLUMN \`last_run_summary\`, + DROP COLUMN \`last_run_at\` + `); + } + +}