diff --git a/SPECIFICATION.md b/SPECIFICATION.md index 3e80c07..fd8524f 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -1357,6 +1357,12 @@ All four channels are required. - **Email:** via `OCP\Mail\IMailer` with templated messages (`OCP\Mail\IEMailTemplate`) for each of the above events. Respect the user's configured email + language. + - **Escalations are mailed once a day.** An escalation notifies HR at once in the + app, but sends no email of its own: `EscalationDigestJob` mails every HR member, + on the first run of a weekday from 07:00 server time, one list of the requests + that wait for HR, oldest first, without their own. Who and when only, with + "short notice" where it applies; the reasons are in the app. Nobody gets an + empty list. - **Comment e-mails are batched.** The notification of a comment goes out right away; its e-mail is queued (§3.6). Once nobody has commented on the request for 10 minutes, each recipient gets one mail with all the comments they have not been diff --git a/appinfo/info.xml b/appinfo/info.xml index 2615fb1..4c66040 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -83,6 +83,7 @@ properly. Every rule and design decision is documented in the OCA\Absence\BackgroundJob\EscalationJob OCA\Absence\BackgroundJob\ReminderJob + OCA\Absence\BackgroundJob\EscalationDigestJob OCA\Absence\BackgroundJob\YearRolloverJob OCA\Absence\BackgroundJob\CommentMailJob OCA\Absence\BackgroundJob\EncryptAttachmentsJob diff --git a/lib/BackgroundJob/EscalationDigestJob.php b/lib/BackgroundJob/EscalationDigestJob.php new file mode 100644 index 0000000..737fb3b --- /dev/null +++ b/lib/BackgroundJob/EscalationDigestJob.php @@ -0,0 +1,74 @@ +setInterval(3600); + $this->setTimeSensitivity(self::TIME_INSENSITIVE); + } + + #[\Override] + protected function run($argument): void { + // The company's day, like the reminders: there is no single reader to ask + $now = $this->clock->serverNow(); + $today = $now->format('Y-m-d'); + if ((int)$now->format('N') > 5 || (int)$now->format('G') < self::SEND_FROM_HOUR + || $this->appConfig->getValueString(ConfigService::APP_ID, ConfigLexicon::KEY_ESCALATION_DIGEST_DAY) === $today) { + return; + } + // Stored before sending: a run that dies half way must not mail the first half again + $this->appConfig->setValueString(ConfigService::APP_ID, ConfigLexicon::KEY_ESCALATION_DIGEST_DAY, $today); + $waiting = $this->requestMapper->findEscalated(); + if ($waiting === []) { + return; + } + foreach (array_unique($this->permission->getHrUids()) as $uid) { + $theirs = array_values(array_filter($waiting, static fn (LeaveRequest $request): bool => $request->getEmployeeUid() !== $uid)); + try { + $this->notifications->sendEscalationDigest($uid, $theirs); + } catch (\Throwable $e) { + $this->logger->error('Absence: failed to send the escalation digest', ['app' => 'absence', 'exception' => $e]); + } + } + } +} diff --git a/lib/ConfigLexicon.php b/lib/ConfigLexicon.php index e1084b5..b61f353 100644 --- a/lib/ConfigLexicon.php +++ b/lib/ConfigLexicon.php @@ -48,6 +48,7 @@ class ConfigLexicon implements ILexicon { public const KEY_LAST_ROLLOVER_YEAR = 'last_rollover_year'; public const KEY_REMINDER_CUTOFF = 'reminder_cutoff'; public const KEY_WITHDRAWAL_CUTOFF = 'withdrawal_cutoff'; + public const KEY_ESCALATION_DIGEST_DAY = 'escalation_digest_day'; public const KEY_CARRYOVER_REMINDER_YEAR = 'carryover_reminder_year'; // The holiday region code each person sets for themselves (§7.2). @@ -107,6 +108,8 @@ public function getAppConfigs(): array { 'Internal marker: creation time (Unix time) up to which the reminder job has reminded pending requests', lazy: true), new Entry(self::KEY_WITHDRAWAL_CUTOFF, ValueType::INT, 0, 'Internal marker: withdrawal time (Unix time) up to which the reminder job has handed unanswered withdrawals to HR', lazy: true), + new Entry(self::KEY_ESCALATION_DIGEST_DAY, ValueType::STRING, '', + 'Internal marker: last day (YYYY-MM-DD, server time) the daily digest of requests waiting for HR was sent', lazy: true), new Entry(self::KEY_CARRYOVER_REMINDER_YEAR, ValueType::INT, 0, 'Internal marker: last year whose carry-over expiry reminder was sent', lazy: true), ]; diff --git a/lib/Service/NotificationService.php b/lib/Service/NotificationService.php index e0d74be..fb24144 100644 --- a/lib/Service/NotificationService.php +++ b/lib/Service/NotificationService.php @@ -81,8 +81,55 @@ public function notifyEscalation(LeaveRequest $request, array $hrUids): void { 'requestId' => $request->getId(), ]); } + // In-app at once; the email waits for the daily digest of everything that + // waits for HR ({@see \OCA\Absence\BackgroundJob\EscalationDigestJob}), + // so a team of several HR members does not get one mail each per request. foreach ($hrUids as $uid) { - $this->send($uid, self::SUBJECT_ESCALATION, $request, true, $request->getReason(), $request->getEmployeeUid(), $notice); + $this->send($uid, self::SUBJECT_ESCALATION, $request, true, $request->getReason(), $request->getEmployeeUid(), $notice, email: false); + } + } + + /** + * One email listing the requests that wait for HR, oldest first, instead of + * one email per escalation. Who and when only, like the notification's + * subject: the reasons are in the app. + * + * @param list $requests + */ + public function sendEscalationDigest(string $recipientUid, array $requests): void { + $user = $this->userManager->get($recipientUid); + if ($requests === [] || $user === null || !$user->isEnabled()) { + return; + } + $email = $user->getEMailAddress(); + if (!$email) { + return; + } + try { + $l = $this->l10nFactory->get(ConfigService::APP_ID, $this->l10nFactory->getUserLanguage($user)); + $heading = $l->n('%n leave request waits for HR', '%n leave requests wait for HR', count($requests)); + $template = $this->mailer->createEMailTemplate('absence.escalation_digest'); + $template->setSubject($heading); + $template->addHeader(); + $template->addHeading($heading); + foreach ($requests as $request) { + $line = $this->displayName($l, $request->getEmployeeUid()) . ': ' . $request->getStartDate() . ' – ' . $request->getEndDate(); + if ($this->notice->warningFor($request) !== null) { + $line .= ' · ' . $l->t('short notice'); + } + $template->addBodyListItem($line); + } + $template->addBodyButton( + $l->t('Open Absence'), + $this->urlGenerator->linkToRouteAbsolute('absence.page.index') . '#/approvals', + ); + $template->addFooter(); + $message = $this->mailer->createMessage(); + $message->setTo([$email => $user->getDisplayName()]); + $message->useTemplate($template); + $this->mailer->send($message); + } catch (\Throwable $e) { + $this->logger->warning('Absence: email failed', ['exception' => $e]); } } @@ -207,7 +254,7 @@ public function notifyAbsenceRecorded(LeaveRequest $request, string $managerUid) * * On a confidential request (§5.7) only HR gets $note and its author, as in the app. */ - private function send(string $recipientUid, string $subject, LeaveRequest $request, bool $actionable, #[\SensitiveParameter] ?string $note = null, ?string $noteAuthorUid = null, ?array $notice = null): void { + private function send(string $recipientUid, string $subject, LeaveRequest $request, bool $actionable, #[\SensitiveParameter] ?string $note = null, ?string $noteAuthorUid = null, ?array $notice = null, bool $email = true): void { // A disabled account cannot act on any of this. if ($this->userManager->get($recipientUid)?->isEnabled() === false) { return; @@ -218,7 +265,9 @@ private function send(string $recipientUid, string $subject, LeaveRequest $reque } $note = trim((string)$note); $this->sendNotification($recipientUid, $subject, $request, $actionable, $note, $noteAuthorUid, $notice); - $this->sendEmail($recipientUid, $subject, $request, $note !== '' ? [['author' => $noteAuthorUid, 'text' => $note]] : [], $notice); + if ($email) { + $this->sendEmail($recipientUid, $subject, $request, $note !== '' ? [['author' => $noteAuthorUid, 'text' => $note]] : [], $notice); + } } /** @param ?array{days:int,noticePeriod:int} $notice */ diff --git a/tests/Unit/BackgroundJob/EscalationDigestJobTest.php b/tests/Unit/BackgroundJob/EscalationDigestJobTest.php new file mode 100644 index 0000000..c2ad004 --- /dev/null +++ b/tests/Unit/BackgroundJob/EscalationDigestJobTest.php @@ -0,0 +1,82 @@ + */ + private array $waiting = []; + /** @var list}> */ + private array $mailed = []; + private EscalationDigestJob $job; + + protected function setUp(): void { + parent::setUp(); + $clock = $this->createMock(ClockService::class); + $clock->method('serverNow')->willReturnCallback(fn (): \DateTimeImmutable => $this->now); + $mapper = $this->createMock(LeaveRequestMapper::class); + $mapper->method('findEscalated')->willReturnCallback(fn (): array => $this->waiting); + $notifications = $this->createMock(NotificationService::class); + $notifications->method('sendEscalationDigest')->willReturnCallback(function (string $uid, array $requests): void { + $this->mailed[] = [$uid, array_map(static fn (LeaveRequest $r): int => (int)$r->getId(), $requests)]; + }); + $permission = $this->createMock(PermissionService::class); + $permission->method('getHrUids')->willReturn(['hr1', 'hr2']); + $appConfig = $this->createMock(IAppConfig::class); + $appConfig->method('getValueString')->willReturnCallback(fn (): string => $this->sentDay); + $appConfig->method('setValueString')->willReturnCallback(function (string $app, string $key, string $value): bool { + $this->sentDay = $value; + return true; + }); + $this->job = new EscalationDigestJob($this->createMock(ITimeFactory::class), $clock, $mapper, $notifications, $permission, $appConfig, $this->createMock(LoggerInterface::class)); + $this->waiting = [$this->escalated(1, 'emp'), $this->escalated(2, 'hr2')]; + } + + public function testEveryHrMemberGetsOneMailAMorningWithoutTheirOwnRequests(): void { + $this->runAt('2026-12-03 06:00'); + $this->runAt('2026-12-03 07:10'); + $this->runAt('2026-12-03 08:10'); + + self::assertSame([['hr1', [1, 2]], ['hr2', [1]]], $this->mailed); + } + + public function testNothingOnTheWeekendAndNothingWhenNothingWaits(): void { + $this->runAt('2026-12-05 09:00'); + $this->waiting = []; + $this->runAt('2026-12-07 09:00'); + + self::assertSame([], $this->mailed); + } + + private function escalated(int $id, string $employee): LeaveRequest { + $request = new LeaveRequest(); + $request->setId($id); + $request->setEmployeeUid($employee); + $request->setStatus(LeaveRequest::STATUS_ESCALATED); + return $request; + } + + private function runAt(string $time): void { + $this->now = new \DateTimeImmutable($time, new \DateTimeZone('UTC')); + (new \ReflectionMethod($this->job, 'run'))->invoke($this->job, null); + } +} diff --git a/tests/Unit/ConfigLexiconTest.php b/tests/Unit/ConfigLexiconTest.php index b22550c..7f82b61 100644 --- a/tests/Unit/ConfigLexiconTest.php +++ b/tests/Unit/ConfigLexiconTest.php @@ -57,6 +57,7 @@ public function testDeclaresAllAdminAndInternalKeys(): void { ConfigLexicon::KEY_NOTICE_PERIOD, ConfigLexicon::KEY_REMINDER_CUTOFF, ConfigLexicon::KEY_WITHDRAWAL_CUTOFF, + ConfigLexicon::KEY_ESCALATION_DIGEST_DAY, ConfigLexicon::KEY_REMINDER_LEAD, ConfigLexicon::KEY_SHARED_VISIBILITY, ]; diff --git a/tests/Unit/Service/NotificationServiceTest.php b/tests/Unit/Service/NotificationServiceTest.php index 95e6a1c..e5581cc 100644 --- a/tests/Unit/Service/NotificationServiceTest.php +++ b/tests/Unit/Service/NotificationServiceTest.php @@ -536,8 +536,9 @@ public function testTheReplacementIsNotToldWhyTheEmployeeIsAway(): void { public function testAnEscalationIsNotSentToThePersonItIsAbout(): void { // An HR member cannot decide their own request, so they are not asked to. + // The email waits for the daily digest. $this->withUsers('emp', 'hr1'); - $this->mailer->expects(self::once())->method('send'); + $this->mailer->expects(self::never())->method('send'); $this->service->notifyEscalation($this->request(), ['emp', 'hr1']); @@ -618,7 +619,19 @@ public function testHrReadWhatWasWrittenOnAConfidentialRequest(): void { self::assertSame('Itest written note.', $this->pushed[0]['note']); self::assertSame('emp', $this->pushed[0]['noteAuthor']); - self::assertSame([['Itest written note.', 'Emp wrote:']], $this->emailNotes); + } + + public function testTheDigestListsWhoWaitsForHrAndWhenWithoutWhatWasWritten(): void { + $this->withUsers('emp', 'hr1'); + $request = $this->request(); + $request->setReason('Itest written note.'); + $this->mailer->expects(self::once())->method('send'); + + $this->service->sendEscalationDigest('hr1', [$request]); + + // Who and when, not the reason + self::assertSame('1 leave request waits for HR', $this->emailSubject); + self::assertSame([['Emp: 2026-02-10 – 2026-02-12', '']], $this->emailNotes); } public function testAMailThatFailsLogsATraceWithoutTheComment(): void {