Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions SPECIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ properly. Every rule and design decision is documented in the
<background-jobs>
<job>OCA\Absence\BackgroundJob\EscalationJob</job>
<job>OCA\Absence\BackgroundJob\ReminderJob</job>
<job>OCA\Absence\BackgroundJob\EscalationDigestJob</job>
<job>OCA\Absence\BackgroundJob\YearRolloverJob</job>
<job>OCA\Absence\BackgroundJob\CommentMailJob</job>
<job>OCA\Absence\BackgroundJob\EncryptAttachmentsJob</job>
Expand Down
74 changes: 74 additions & 0 deletions lib/BackgroundJob/EscalationDigestJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Absence\BackgroundJob;

use OCA\Absence\ConfigLexicon;
use OCA\Absence\Db\LeaveRequest;
use OCA\Absence\Db\LeaveRequestMapper;
use OCA\Absence\Service\ClockService;
use OCA\Absence\Service\ConfigService;
use OCA\Absence\Service\NotificationService;
use OCA\Absence\Service\PermissionService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\IAppConfig;
use Psr\Log\LoggerInterface;

/**
* Mails every HR member, once a working day in the morning, the requests that
* wait for HR (§5.4), instead of one email per escalation. The notification of
* each escalation still comes at once.
*
* Runs hourly and sends on the first run of a weekday from 07:00 server time,
* so the mail is there when the day starts whatever time cron first ran.
* Nobody is sent an empty list, nor their own requests.
*/
class EscalationDigestJob extends TimedJob {
public const SEND_FROM_HOUR = 7;

public function __construct(
ITimeFactory $time,
private ClockService $clock,
private LeaveRequestMapper $requestMapper,
private NotificationService $notifications,
private PermissionService $permission,
private IAppConfig $appConfig,
private LoggerInterface $logger,
) {
parent::__construct($time);
$this->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]);
}
}
}
}
3 changes: 3 additions & 0 deletions lib/ConfigLexicon.php
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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),
];
Expand Down
55 changes: 52 additions & 3 deletions lib/Service/NotificationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<LeaveRequest> $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]);
}
}

Expand Down Expand Up @@ -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;
Expand All @@ -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 */
Expand Down
82 changes: 82 additions & 0 deletions tests/Unit/BackgroundJob/EscalationDigestJobTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Absence\Tests\Unit\BackgroundJob;

use OCA\Absence\BackgroundJob\EscalationDigestJob;
use OCA\Absence\Db\LeaveRequest;
use OCA\Absence\Db\LeaveRequestMapper;
use OCA\Absence\Service\ClockService;
use OCA\Absence\Service\NotificationService;
use OCA\Absence\Service\PermissionService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IAppConfig;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;

class EscalationDigestJobTest extends TestCase {
private \DateTimeImmutable $now;
private string $sentDay = '';
/** @var list<LeaveRequest> */
private array $waiting = [];
/** @var list<array{string, list<int>}> */
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);
}
}
1 change: 1 addition & 0 deletions tests/Unit/ConfigLexiconTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];
Expand Down
17 changes: 15 additions & 2 deletions tests/Unit/Service/NotificationServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);

Expand Down Expand Up @@ -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 {
Expand Down
Loading