From affd1c1e9d6dec2ac52755e5f9985d713af9421b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Molakvo=C3=A6?= <14975046+skjnldsv@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:44:46 +0100 Subject: [PATCH 1/2] fix(notifications): a withdrawal goes to the manager first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Withdrawing approved leave notified the manager and the whole HR team at once, although the manager is the one expected to decide. It now goes to the manager like a new request, when they can decide it and are not away today; otherwise to HR, never to the employee themselves. A withdrawal the manager leaves unanswered for the escalation window is handed to HR once by the daily reminder job. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: John Molakvoæ <14975046+skjnldsv@users.noreply.github.com> --- SPECIFICATION.md | 3 +- lib/BackgroundJob/ReminderJob.php | 43 +++++++++++++++++++ lib/ConfigLexicon.php | 3 ++ lib/Db/LeaveRequestMapper.php | 16 +++++++ lib/Service/RequestService.php | 20 ++++++++- tests/Unit/BackgroundJob/ReminderJobTest.php | 44 +++++++++++++++++++- tests/Unit/ConfigLexiconTest.php | 1 + tests/Unit/Service/RequestServiceTest.php | 23 ++++++++++ 8 files changed, 148 insertions(+), 5 deletions(-) diff --git a/SPECIFICATION.md b/SPECIFICATION.md index fe51f1d..5b19978 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -1316,7 +1316,8 @@ All four channels are required. - **Nextcloud notifications:** implement `OCP\Notification\INotifier`. Events: new request (→ manager), decision made (→ employee), escalation (→ HR), - reminder (→ manager), withdrawal request (→ manager/HR), **comment added** + reminder (→ manager), withdrawal request (→ the manager who can decide it and is not away today, else + HR; one the manager leaves unanswered for the escalation window reaches HR once), **comment added** (→ the employee and their manager, plus HR once the request has been escalated; never back to the comment's own author), **replacement assigned** (→ replacement, on approval) and **replacement cancelled** (→ replacement, when diff --git a/lib/BackgroundJob/ReminderJob.php b/lib/BackgroundJob/ReminderJob.php index e2a1d06..d612f34 100644 --- a/lib/BackgroundJob/ReminderJob.php +++ b/lib/BackgroundJob/ReminderJob.php @@ -60,6 +60,11 @@ protected function run($argument): void { $this->logger->error('Absence: carry-over reminder failed', ['app' => 'absence', 'exception' => $e]); } + try { + $this->handOverWithdrawals(); + } catch (\Throwable $e) { + $this->logger->error('Absence: withdrawal hand-over failed', ['app' => 'absence', 'exception' => $e]); + } $window = max(1, $this->config->getEscalationWindowDays()); $lead = max(0, $this->config->getReminderLeadDays()); $reminderThreshold = max(1, $window - $lead); @@ -110,4 +115,42 @@ protected function run($argument): void { } } } + + /** + * A withdrawal goes to the manager first (§5.3). One the manager left + * unanswered for the escalation window is handed to HR, once: the band of + * withdrawals that crossed the window since the last run, like the reminders. + * Withdrawals that went to HR straight away (no manager, a manager who cannot + * decide it or was away that day) are not handed over again. + */ + private function handOverWithdrawals(): void { + $today = $this->clock->serverNow()->setTime(0, 0); + if ((int)$today->format('N') > 5) { + return; + } + $before = $this->subtractWorkingDays($today, max(1, $this->config->getEscalationWindowDays())); + $last = $this->appConfig->getValueInt(ConfigService::APP_ID, ConfigLexicon::KEY_WITHDRAWAL_CUTOFF); + if ($last >= $before->getTimestamp()) { + return; + } + $after = $last === 0 + ? $this->subtractWorkingDays($before, 1) + : max($before->setTimestamp($last), $before->modify('-' . self::MAX_CATCH_UP_DAYS . ' days')); + $withdrawals = $this->requestMapper->findWithdrawalsPendingBetween($after, $before); + $this->appConfig->setValueInt(ConfigService::APP_ID, ConfigLexicon::KEY_WITHDRAWAL_CUTOFF, $before->getTimestamp()); + foreach ($withdrawals as $request) { + $managerUid = $this->managerResolver->getManagerUid($request->getEmployeeUid()); + $day = \DateTimeImmutable::createFromInterface($request->getUpdatedAt() ?? $today)->setTimezone($today->getTimezone())->format('Y-m-d'); + if ($managerUid === null + || !$this->permission->canDecide($managerUid, $request) + || $this->requestMapper->hasApprovedAbsenceCovering($managerUid, $day, $day)) { + continue; + } + try { + $this->notifications->notifyWithdrawal($request, array_values(array_diff($this->permission->getHrUids(), [$request->getEmployeeUid()]))); + } catch (\Throwable $e) { + $this->logger->error('Absence: failed to hand a withdrawal to HR', ['app' => 'absence', 'request' => $request->getId(), 'exception' => $e]); + } + } + } } diff --git a/lib/ConfigLexicon.php b/lib/ConfigLexicon.php index a511d4f..e1084b5 100644 --- a/lib/ConfigLexicon.php +++ b/lib/ConfigLexicon.php @@ -47,6 +47,7 @@ class ConfigLexicon implements ILexicon { // Internal state. 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_CARRYOVER_REMINDER_YEAR = 'carryover_reminder_year'; // The holiday region code each person sets for themselves (§7.2). @@ -104,6 +105,8 @@ public function getAppConfigs(): array { 'Internal marker: last year already processed by the rollover job', lazy: true), new Entry(self::KEY_REMINDER_CUTOFF, ValueType::INT, 0, '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_CARRYOVER_REMINDER_YEAR, ValueType::INT, 0, 'Internal marker: last year whose carry-over expiry reminder was sent', lazy: true), ]; diff --git a/lib/Db/LeaveRequestMapper.php b/lib/Db/LeaveRequestMapper.php index 89b0a72..db17070 100644 --- a/lib/Db/LeaveRequestMapper.php +++ b/lib/Db/LeaveRequestMapper.php @@ -340,6 +340,22 @@ public function findPendingCreatedBetween(\DateTimeInterface $after, \DateTimeIn return $this->findEntities($qb); } + /** + * Withdrawals still awaiting a decision, asked for in [$after, $before): the + * request was last changed when the employee withdrew it. + * + * @return LeaveRequest[] + */ + public function findWithdrawalsPendingBetween(\DateTimeInterface $after, \DateTimeInterface $before): array { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('status', $qb->createNamedParameter(LeaveRequest::STATUS_WITHDRAWAL_PENDING))) + ->andWhere($qb->expr()->lt('updated_at', $qb->createNamedParameter($this->asStoredTimestamp($before), IQueryBuilder::PARAM_STR))) + ->andWhere($qb->expr()->gte('updated_at', $qb->createNamedParameter($this->asStoredTimestamp($after), IQueryBuilder::PARAM_STR))); + return $this->findEntities($qb); + } + /** * Requests for a set of employees overlapping a range, restricted to statuses. * Used for coverage / who's-off calendar. diff --git a/lib/Service/RequestService.php b/lib/Service/RequestService.php index a492df0..ca8cab3 100644 --- a/lib/Service/RequestService.php +++ b/lib/Service/RequestService.php @@ -1165,8 +1165,8 @@ public function cancel(string $actorUid, int $id): LeaveRequest { $request->setUpdatedAt($this->clock->now()); return $this->requestMapper->update($request); }, $this->db)); - $recipients = array_filter([$this->managerResolver->getManagerUid($request->getEmployeeUid()), ...$this->permission->getHrUids()]); - $this->notifications->notifyWithdrawal($request, array_values($recipients)); + $recipients = $this->withdrawalDeciders($request); + $this->notifications->notifyWithdrawal($request, $recipients); $this->activity->publish(ActivityPublisher::SUBJECT_WITHDRAWAL, $this->activityParams($request), [$request->getEmployeeUid(), ...$recipients], $request); $this->audit('withdrawal_requested', $request, ['actor' => $actorUid]); return $request; @@ -1652,6 +1652,22 @@ private function normaliseDate(string $date): string { return $date; } + /** + * Who is asked to decide a withdrawal (§5.3): the manager, like for a new + * request, when they can decide it and are not away today; otherwise HR, + * never the employee themselves. An unanswered one reaches HR later + * ({@see \OCA\Absence\BackgroundJob\ReminderJob}). + * + * @return list + */ + public function withdrawalDeciders(LeaveRequest $request): array { + $managerUid = $this->managerResolver->getManagerUid($request->getEmployeeUid()); + if ($managerUid !== null && $this->permission->canDecide($managerUid, $request) && !$this->managerCurrentlyAway($managerUid)) { + return [$managerUid]; + } + return array_values(array_diff($this->permission->getHrUids(), [$request->getEmployeeUid()])); + } + /** * Whether the assigned manager is on approved leave today (§5.4a) — on the * server's calendar, like every company-wide decision. diff --git a/tests/Unit/BackgroundJob/ReminderJobTest.php b/tests/Unit/BackgroundJob/ReminderJobTest.php index 46f481c..fc9bdd2 100644 --- a/tests/Unit/BackgroundJob/ReminderJobTest.php +++ b/tests/Unit/BackgroundJob/ReminderJobTest.php @@ -9,6 +9,7 @@ namespace OCA\Absence\Tests\Unit\BackgroundJob; use OCA\Absence\BackgroundJob\ReminderJob; +use OCA\Absence\ConfigLexicon; use OCA\Absence\Db\LeaveRequest; use OCA\Absence\Db\LeaveRequestMapper; use OCA\Absence\Service\CarryOverReminderService; @@ -31,12 +32,18 @@ class ReminderJobTest extends TestCase { private ReminderJob $job; private \DateTimeImmutable $now; + /** @var array */ + private array $otherCutoffs = []; private int $storedCutoff = 0; /** @var LeaveRequest[] */ private array $pending = []; /** @var int[] ids of the reminded requests, in order */ private array $reminded = []; private CarryOverReminderService&MockObject $carryOverReminder; + /** @var list withdrawals awaiting a decision */ + private array $withdrawals = []; + /** @var list}> withdrawals handed over, with whom to */ + private array $handedOver = []; /** @var int[] ids of the requests the manager may not decide */ private array $undecidable = []; @@ -54,7 +61,17 @@ protected function setUp(): void { )), ); + $mapper->method('findWithdrawalsPendingBetween')->willReturnCallback( + fn (\DateTimeInterface $after, \DateTimeInterface $before): array => array_values(array_filter( + $this->withdrawals, + static fn (LeaveRequest $request): bool => $request->getUpdatedAt() >= $after && $request->getUpdatedAt() < $before, + )), + ); + $notifications = $this->createMock(NotificationService::class); + $notifications->method('notifyWithdrawal')->willReturnCallback(function (LeaveRequest $request, array $to): void { + $this->handedOver[] = [$request->getId(), $to]; + }); $notifications->method('notifyReminder')->willReturnCallback(function (LeaveRequest $request): void { $this->reminded[] = $request->getId(); }); @@ -64,9 +81,14 @@ protected function setUp(): void { $config->method('getReminderLeadDays')->willReturn(1); $appConfig = $this->createMock(IAppConfig::class); - $appConfig->method('getValueInt')->willReturnCallback(fn (): int => $this->storedCutoff); + // The reminder cut-off; the withdrawal hand-over keeps its own + $appConfig->method('getValueInt')->willReturnCallback(fn (string $app, string $key): int => $key === ConfigLexicon::KEY_REMINDER_CUTOFF ? $this->storedCutoff : ($this->otherCutoffs[$key] ?? 0)); $appConfig->method('setValueInt')->willReturnCallback(function (string $app, string $key, int $value): bool { - $this->storedCutoff = $value; + if ($key === ConfigLexicon::KEY_REMINDER_CUTOFF) { + $this->storedCutoff = $value; + } else { + $this->otherCutoffs[$key] = $value; + } return true; }); @@ -74,6 +96,7 @@ protected function setUp(): void { $managers->method('getManagerUid')->willReturn('itest-manager'); $permission = $this->createMock(PermissionService::class); + $permission->method('getHrUids')->willReturn(['itest-hr', 'itest-employee']); $permission->method('canDecide')->willReturnCallback( fn (string $uid, LeaveRequest $request): bool => !in_array($request->getId(), $this->undecidable, true), ); @@ -193,6 +216,23 @@ private function pendingSince(int $id, string $day): void { $this->pending[] = $request; } + public function testAnUnansweredWithdrawalIsHandedToHrOnce(): void { + $withdrawal = new LeaveRequest(); + $withdrawal->setId(9); + $withdrawal->setEmployeeUid('itest-employee'); + $withdrawal->setStatus(LeaveRequest::STATUS_WITHDRAWAL_PENDING); + $withdrawal->setUpdatedAt(new \DateTime('2026-03-05 10:00:00', new \DateTimeZone('UTC'))); + $this->withdrawals = [$withdrawal]; + + // The window is three working days: not yet on Monday, on Tuesday, not again after + $this->runOn('2026-03-09'); + self::assertSame([], $this->handedOver); + $this->runOn('2026-03-10'); + $this->runOn('2026-03-11'); + + self::assertSame([[9, ['itest-hr']]], $this->handedOver); + } + private function runOn(string $day): void { $this->now = new \DateTimeImmutable($day . ' 03:00:00', 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 8fad6b8..b22550c 100644 --- a/tests/Unit/ConfigLexiconTest.php +++ b/tests/Unit/ConfigLexiconTest.php @@ -56,6 +56,7 @@ public function testDeclaresAllAdminAndInternalKeys(): void { ConfigLexicon::KEY_MAX_CONCURRENT, ConfigLexicon::KEY_NOTICE_PERIOD, ConfigLexicon::KEY_REMINDER_CUTOFF, + ConfigLexicon::KEY_WITHDRAWAL_CUTOFF, ConfigLexicon::KEY_REMINDER_LEAD, ConfigLexicon::KEY_SHARED_VISIBILITY, ]; diff --git a/tests/Unit/Service/RequestServiceTest.php b/tests/Unit/Service/RequestServiceTest.php index de624b4..becdf55 100644 --- a/tests/Unit/Service/RequestServiceTest.php +++ b/tests/Unit/Service/RequestServiceTest.php @@ -47,6 +47,7 @@ use OCP\IUserManager; use OCP\Lock\ILockingProvider; use OCP\Log\Audit\CriticalActionPerformedEvent; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -1541,6 +1542,28 @@ public function testCancellingARequestApprovedInTheMeantimeIsAConflict(): void { $this->service->cancel('emp', 5); } + /** + * @return iterable}> + */ + public static function withdrawalDeciderCases(): iterable { + yield 'the manager, who can decide and is here' => ['mgr', true, false, ['mgr']]; + yield 'HR without a manager' => [null, true, false, ['hr1', 'hr2']]; + yield 'HR when the manager cannot decide it' => ['mgr', false, false, ['hr1', 'hr2']]; + yield 'HR while the manager is away' => ['mgr', true, true, ['hr1', 'hr2']]; + } + + /** @param list $expected */ + #[DataProvider('withdrawalDeciderCases')] + public function testAWithdrawalGoesToTheManagerFirst(?string $manager, bool $canDecide, bool $away, array $expected): void { + $request = $this->pendingOwnRequest(); + $this->managerResolver->method('getManagerUid')->willReturn($manager); + $this->permission->method('canDecide')->willReturn($canDecide); + $this->permission->method('getHrUids')->willReturn(['hr1', 'emp', 'hr2']); + $this->requestMapper->method('hasApprovedAbsenceCovering')->willReturn($away); + + self::assertSame($expected, $this->service->withdrawalDeciders($request)); + } + public function testAskingToWithdrawLeaveCancelledInTheMeantimeIsAConflict(): void { $request = $this->pendingOwnRequest(); $request->setStatus(LeaveRequest::STATUS_APPROVED); From 1f9025d2227b2531b8c9000466ec3b44efd91317 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Molakvo=C3=A6?= <14975046+skjnldsv@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:49:41 +0100 Subject: [PATCH 2/2] test: a withdrawal reaches the new manager only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: John Molakvoæ <14975046+skjnldsv@users.noreply.github.com> --- tests/Integration/ManagerChangeTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Integration/ManagerChangeTest.php b/tests/Integration/ManagerChangeTest.php index eb2685b..bd535e6 100644 --- a/tests/Integration/ManagerChangeTest.php +++ b/tests/Integration/ManagerChangeTest.php @@ -148,7 +148,8 @@ public function testCommentsAndWithdrawalsAreSentToTheNewManager(): void { $service->cancel(self::EMPLOYEE, $approved->getId()); self::assertSame([self::CURRENT], $this->recipients(NotificationService::SUBJECT_COMMENT, $pending)); - self::assertEqualsCanonicalizing([self::CURRENT, self::HR], $this->recipients(NotificationService::SUBJECT_WITHDRAWAL, $approved)); + // The withdrawal goes to the manager first, HR only if they do not answer + self::assertSame([self::CURRENT], $this->recipients(NotificationService::SUBJECT_WITHDRAWAL, $approved)); } public function testAnEditedRequestIsSentToTheNewManager(): void {