Skip to content
Merged
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
3 changes: 2 additions & 1 deletion SPECIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions lib/BackgroundJob/ReminderJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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]);
}
}
}
}
3 changes: 3 additions & 0 deletions lib/ConfigLexicon.php
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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),
];
Expand Down
16 changes: 16 additions & 0 deletions lib/Db/LeaveRequestMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 18 additions & 2 deletions lib/Service/RequestService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<string>
*/
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.
Expand Down
3 changes: 2 additions & 1 deletion tests/Integration/ManagerChangeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
44 changes: 42 additions & 2 deletions tests/Unit/BackgroundJob/ReminderJobTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -31,12 +32,18 @@
class ReminderJobTest extends TestCase {
private ReminderJob $job;
private \DateTimeImmutable $now;
/** @var array<string,int> */
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<LeaveRequest> withdrawals awaiting a decision */
private array $withdrawals = [];
/** @var list<array{int, list<string>}> withdrawals handed over, with whom to */
private array $handedOver = [];
/** @var int[] ids of the requests the manager may not decide */
private array $undecidable = [];

Expand All @@ -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();
});
Expand All @@ -64,16 +81,22 @@ 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;
});

$managers = $this->createMock(ManagerResolver::class);
$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),
);
Expand Down Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions tests/Unit/ConfigLexiconTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];
Expand Down
23 changes: 23 additions & 0 deletions tests/Unit/Service/RequestServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1541,6 +1542,28 @@ public function testCancellingARequestApprovedInTheMeantimeIsAConflict(): void {
$this->service->cancel('emp', 5);
}

/**
* @return iterable<string, array{?string, bool, bool, list<string>}>
*/
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<string> $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);
Expand Down
Loading