From 10799c04778ec9bfef22edc1fdfdad4ca19bd456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Molakvo=C3=A6?= <14975046+skjnldsv@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:34:43 +0100 Subject: [PATCH] feat(replacement): offer teammates first and warn when they are away MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The replacement picker was empty until two letters were typed, and nothing said when the chosen colleague was away themselves. Before anything is typed, the picker now offers the colleagues chosen before, then the teammates of the person whose absence it is: who shares their manager, the manager and their direct reports, employees only. Typing still searches the whole company. GET /api/employees/teammates answers for the caller, or for any employee when HR asks. Once a replacement and both dates are set, the dialog asks GET /api/employees/{uid}/away whether that colleague has leave pending, escalated, approved or awaiting withdrawal on any of those days, and shows a warning without the type or the days. It answers HR, the colleague's teammates, or everyone while the shared team calendar is on, and null otherwise. Saving is never blocked. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: John Molakvoæ <14975046+skjnldsv@users.noreply.github.com> --- SPECIFICATION.md | 24 +- appinfo/routes.php | 2 + lib/Controller/EmployeeController.php | 22 ++ lib/Service/CoverageService.php | 62 +++++ src/components/RequestDialog.vue | 91 ++++++- src/services/api.ts | 5 + src/utils/people.spec.ts | 33 ++- src/utils/people.ts | 26 ++ tests/Integration/AccessMatrixTest.php | 2 + tests/Integration/EmployeeJsonTest.php | 3 +- tests/Integration/EmployeeListTest.php | 3 +- tests/Integration/RegionReminderTest.php | 3 +- tests/Integration/ReplacementPickerTest.php | 230 ++++++++++++++++++ .../Controller/EmployeeControllerTest.php | 1 + 14 files changed, 488 insertions(+), 19 deletions(-) create mode 100644 tests/Integration/ReplacementPickerTest.php diff --git a/SPECIFICATION.md b/SPECIFICATION.md index 55ca6ce7..e3d53e30 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -450,8 +450,22 @@ HR** on an employee's behalf (§5.6) — employees don't self-record it. 3. **Replacement (mandatory for `requires_replacement` types).** For annual, unpaid and special leave the employee **must** nominate a **replacement** — a colleague who covers for them. The UI is a **user picker over the whole organisation** - (`NcSelect` + core autocomplete), excluding the employee themselves. Submit is blocked - until one is chosen. Sick leave (HR-recorded) needs none. + (`NcSelect` + `GET /api/employees/search`), excluding the employee themselves. Submit + is blocked until one is chosen. Sick leave (HR-recorded) needs none. + + Before anything is typed the picker offers the **teammates** of the person whose + absence it is (`GET /api/employees/teammates`): the colleagues chosen as replacement + before come first, then who shares their manager, the manager, and their direct + reports, by name. Employees only, never the person themselves, nobody twice. + Anybody may ask for their own teammates, HR for any employee's (HR mode). + Once a replacement and both dates are set, the dialog asks whether that colleague + has leave pending, escalated, approved or awaiting withdrawal on any of those days + (`GET /api/employees/{uid}/away`, debounced like the coverage note) and if so warns + "*{name} is off on some of these days.*" without saying which days or what leave. + It answers only who may see that colleague's absences anyway: HR, their teammates + as above, or every employee while the shared team calendar is on (§10). Anybody + else gets `{away: null}` and no warning. It is a warning only: saving is never + blocked by it. **The requirement is on the employee, not on the record.** It exists because somebody arranging their own leave knows who can cover and is asked to sort it out before @@ -1448,6 +1462,12 @@ the SPA). All list endpoints paginate and accept filters. **Coverage & calendar** - `GET /api/coverage?from&to&scope=team|company` — overlaps + conflict count (§8). +- `GET /api/employees/teammates?uid`: the replacement picker's suggestions (§5.1): + `[{uid, displayName}]`. `uid` defaults to the caller; only HR may name somebody else. +- `GET /api/employees/{uid}/away?from&to`: `{away: bool|null}`, whether that employee + has leave in force or asked for on any day of the range, at most 366 days (§5.1). + Employees and HR only; `null` unless the caller is HR, a teammate, or the shared + team calendar is on. - `GET /api/calendar?from&to&scope` — events for the in-app calendar/timeline, and the public holidays of the people in them (`holidays`, by uid). diff --git a/appinfo/routes.php b/appinfo/routes.php index 8bbcb7a7..dab74bb6 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -31,6 +31,8 @@ ['name' => 'employee#remind', 'url' => '/api/employees/remind', 'verb' => 'POST'], ['name' => 'employee#index', 'url' => '/api/employees', 'verb' => 'GET'], ['name' => 'employee#search', 'url' => '/api/employees/search', 'verb' => 'GET'], + ['name' => 'employee#teammates', 'url' => '/api/employees/teammates', 'verb' => 'GET'], + ['name' => 'employee#away', 'url' => '/api/employees/{uid}/away', 'verb' => 'GET'], ['name' => 'employee#exportJson', 'url' => '/api/employees/json', 'verb' => 'GET'], ['name' => 'employee#importJson', 'url' => '/api/employees/json', 'verb' => 'POST'], ['name' => 'employee#groups', 'url' => '/api/groups', 'verb' => 'GET'], diff --git a/lib/Controller/EmployeeController.php b/lib/Controller/EmployeeController.php index 934b18b1..b1042331 100644 --- a/lib/Controller/EmployeeController.php +++ b/lib/Controller/EmployeeController.php @@ -8,6 +8,7 @@ namespace OCA\Absence\Controller; +use OCA\Absence\Service\CoverageService; use OCA\Absence\Service\EmployeeDirectory; use OCA\Absence\Service\EmployeeJsonService; use OCA\Absence\Service\EmployeeListService; @@ -42,6 +43,7 @@ public function __construct( private PermissionService $permission, private LoggerInterface $logger, private IL10N $l, + private CoverageService $coverage, ) { parent::__construct($appName, $request); } @@ -177,6 +179,26 @@ public function search(string $search = '', int $limit = 20): DataResponse { }); } + /** + * The teammates the replacement picker offers before anything is typed + * (§5.1), the caller's own unless HR asks for an employee's. + */ + #[NoAdminRequired] + #[UserRateLimit(limit: 60, period: 60)] + public function teammates(?string $uid = null): DataResponse { + return $this->handle(fn (): array => $this->coverage->getTeammates((string)$this->userId, $uid ?? (string)$this->userId)); + } + + /** + * Whether a colleague is off on any of the given days, for the warning + * under the replacement picker (§5.1). Null when the caller may not know. + */ + #[NoAdminRequired] + #[UserRateLimit(limit: 60, period: 60)] + public function away(string $uid, string $from, string $to): DataResponse { + return $this->handle(fn (): array => ['away' => $this->coverage->isAway((string)$this->userId, $uid, $from, $to)]); + } + /** * The signed-in user, when they match what was typed and may hold leave. * diff --git a/lib/Service/CoverageService.php b/lib/Service/CoverageService.php index 125b9416..f8dfdf97 100644 --- a/lib/Service/CoverageService.php +++ b/lib/Service/CoverageService.php @@ -11,6 +11,8 @@ use OCA\Absence\Db\LeaveRequest; use OCA\Absence\Db\LeaveRequestMapper; use OCA\Absence\Db\LeaveTypeMapper; +use OCA\Absence\Exception\ForbiddenException; +use OCA\Absence\Exception\ValidationException; use OCP\IL10N; use OCP\IUserManager; @@ -22,6 +24,8 @@ class CoverageService { public const SCOPE_TEAM = 'team'; public const SCOPE_COMPANY = 'company'; + /** The longest range the away check answers for: the longest request (§5.1). */ + private const MAX_AWAY_SPAN_DAYS = 366; /** The statuses that put somebody on the timeline: booked or still asked for */ private const OFF_STATUSES = [LeaveRequest::STATUS_APPROVED, LeaveRequest::STATUS_PENDING, LeaveRequest::STATUS_ESCALATED, LeaveRequest::STATUS_WITHDRAWAL_PENDING]; @@ -205,6 +209,64 @@ public function othersOffFor(array $requests): array { return $result; } + /** + * The colleagues the replacement picker offers before anything is typed + * (§5.1): who shares the person's manager, the manager, and the person's + * direct reports. Employees only, never the person themselves. Anybody may + * ask for their own, HR for anybody's. + * + * @return list + * @throws ForbiddenException + */ + public function getTeammates(string $actorUid, string $uid): array { + if ($uid !== $actorUid) { + $this->permission->assertHr($actorUid); + } elseif (!$this->permission->isEmployeeOrHr($actorUid)) { + throw new ForbiddenException($this->l->t('Only employees and HR can see this.')); + } + return array_map(fn (string $other): array => ['uid' => $other, 'displayName' => $this->displayName($other)], $this->teammateUids($uid)); + } + + /** + * Who shares the person's manager, the manager, and the person's direct + * reports: employees only, never the person themselves. + * + * @return list + */ + private function teammateUids(string $uid): array { + $managerUid = $this->managerResolver->getManagerUid($uid); + $uids = array_unique([ + ...$this->managerResolver->getPeers($uid), + ...($managerUid !== null ? [$managerUid] : []), + ...$this->managerResolver->getDirectReports($uid), + ]); + return $this->employees->filter(array_values(array_filter($uids, static fn (string $other): bool => $other !== $uid))); + } + + /** + * Whether an employee has leave in force or asked for on any day of a + * range, for the warning under the replacement picker. Says nothing about + * the type or the days. Null, no answer, unless the caller may see that + * person's absences anyway: HR, their teammates, or everyone while the + * shared team calendar shows all absences. + * + * @throws ForbiddenException + * @throws ValidationException + */ + public function isAway(string $actorUid, string $uid, string $from, string $to): ?bool { + if (!$this->permission->isEmployeeOrHr($actorUid)) { + throw new ForbiddenException($this->l->t('Only employees and HR can see this.')); + } + if (!$this->employees->isEmployee($uid)) { + throw new ValidationException($this->l->t('Unknown employee.')); + } + [$from, $to] = $this->assertValidRange($from, $to, self::MAX_AWAY_SPAN_DAYS); + if (!$this->permission->isHr($actorUid) && !$this->config->isCalDavSharedEnabled() && !in_array($uid, $this->teammateUids($actorUid), true)) { + return null; + } + return $this->requestMapper->findForEmployeesInRange([$uid], $from, $to, LeaveRequest::ACTIVE_STATUSES) !== []; + } + /** * The team relevant to a request: the manager's direct reports, or (no manager) * the employee's peers. diff --git a/src/components/RequestDialog.vue b/src/components/RequestDialog.vue index 61f7f6bd..5ea3f75f 100644 --- a/src/components/RequestDialog.vue +++ b/src/components/RequestDialog.vue @@ -202,6 +202,9 @@

{{ replacementHint }}

+ + {{ t('absence', '{name} is off on some of these days.', { name: selectedReplacement.displayName }, undefined, { escape: false, sanitize: false }) }} +
@@ -273,7 +276,7 @@ import { formatRegionCode, makeHolidayChecker } from '../utils/holidays.ts' import { missingYears } from '../utils/holidayYears.ts' import { latestOnly } from '../utils/latest.ts' import { formatNumber } from '../utils/locale.ts' -import { namesAndMore } from '../utils/people.ts' +import { namesAndMore, replacementSuggestions } from '../utils/people.ts' import { defaultLeaveType, estimateMismatch, isStoredRange, prefilledWorkingDays } from '../utils/prefill.ts' import { offeredLeaveTypes, requestChanges, requestCreation } from '../utils/requestPayload.ts' import { restAfter, splitAtYearEnd } from '../utils/yearSplit.ts' @@ -327,8 +330,16 @@ const selectedEmployee = ref(null) const employeeOptions = ref([]) const employeeLoading = ref(false) const selectedReplacement = ref(null) -const replacementOptions = ref([]) +// The search results while at least two letters are typed, null otherwise. +const replacementResults = ref(null) const replacementLoading = ref(false) +// The absent person's teammates, offered before anything is typed (§5.1). +const teammates = ref([]) +const startTeammatesLoad = latestOnly() +// Whether the picked replacement is off during the picked dates, checked as they change. +const replacementAway = ref(false) +let awaySeq = 0 +let awayTimer: ReturnType | undefined // Who else on the team is off during the picked dates (§8), fetched as the // dates change. `coverageSeq` discards answers overtaken by a newer range. const coverage = ref(null) @@ -451,6 +462,14 @@ const replacementHint = computed(() => { : t('absence', 'Optional. A colleague who covers these duties while this employee is away, and is notified once this is recorded.') }) +/** Typed search results, else the colleagues chosen before and the teammates. */ +const replacementOptions = computed(() => replacementResults.value ?? replacementSuggestions({ + past: isOwnLeave.value ? pastReplacements() : [], + teammates: teammates.value, + selected: selectedReplacement.value, + subjectUid: subjectUid.value, +})) + // Bridge the native date pickers (Date objects) to our ISO string state. const startDate = computed({ get() { @@ -668,15 +687,22 @@ watch([startIso, endIso], () => { watch(subjectUid, () => { loadSubject() + loadTeammates() +}) + +watch([selectedReplacement, startIso, endIso], () => { + scheduleAway() }) onBeforeUnmount(() => { clearTimeout(coverageTimer) + clearTimeout(awayTimer) }) onMounted(async () => { await initFromProps() loadSubject() + loadTeammates() if (!props.hrMode && !requestsStore.balance.balances.length) { // No year on purpose: the server then answers every year, which balanceRow needs for leave booked in another year await requestsStore.loadMyBalance() @@ -712,6 +738,53 @@ async function loadCoverage() { } } +/** Debounced like the coverage note: the dates move a lot while a picker is being dragged. */ +function scheduleAway() { + replacementAway.value = false + clearTimeout(awayTimer) + awayTimer = setTimeout(() => loadAway(), 350) +} + +/** + * Check whether the picked replacement is off on any of the picked days. + */ +async function loadAway() { + const replacement = selectedReplacement.value + const seq = ++awaySeq + if (!needsReplacement.value || !replacement || !startIso.value || !endIso.value || endIso.value < startIso.value) { + return + } + try { + const { away } = await api.isAway(replacement.uid, startIso.value, endIso.value) + if (seq === awaySeq) { + replacementAway.value = away === true + } + } catch { + // Advisory only, like the coverage note: a failed check leaves the warning out. + } +} + +/** + * The teammates of the person whose absence this is: mine, or for HR the + * employee's. Only the last person picked lands. + */ +async function loadTeammates() { + const isLatest = startTeammatesLoad() + teammates.value = [] + const uid = subjectUid.value + if (!uid) { + return + } + try { + const list = await api.teammates(isOwnLeave.value ? undefined : uid) + if (isLatest()) { + teammates.value = list + } + } catch { + // Suggestions only: typing still searches the whole company. + } +} + /** * Take a number typed into the working-days field. * @@ -875,15 +948,6 @@ async function initFromProps() { selectedReplacement.value = pastReplacements()[0] || null } } - // Offer colleagues used before so the dropdown isn't empty (self-service). - if (!props.hrMode) { - replacementOptions.value = pastReplacements() - // Keep the current selection pickable even if it isn't in that list. - const selected = selectedReplacement.value - if (selected && !replacementOptions.value.some((o) => o.uid === selected.uid)) { - replacementOptions.value = [selected, ...replacementOptions.value] - } - } } // Distinct colleagues used as replacement in the user's past requests, newest first. @@ -932,15 +996,16 @@ async function onEmployeeSearch(query: string) { */ async function onReplacementSearch(query: string) { if (!query || query.length < 2) { + replacementResults.value = null return } replacementLoading.value = true try { const users = await api.searchUsers(query) // A person can't be their own replacement. - replacementOptions.value = users.filter((u) => u.uid !== subjectUid.value) + replacementResults.value = users.filter((u) => u.uid !== subjectUid.value) } catch { - replacementOptions.value = [] + replacementResults.value = [] } finally { replacementLoading.value = false } diff --git a/src/services/api.ts b/src/services/api.ts index cb4f1f1e..a496b56c 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -52,6 +52,7 @@ import type { SettingsInput, SickLeaveReport, Trends, + UserRef, } from '../types/index.ts' import axios from '@nextcloud/axios' @@ -189,6 +190,10 @@ export default { // employees (§2.2). The endpoint wraps the same collaborator search, so the // admin's user-enumeration settings still apply. searchUsers: (search: string) => get('/api/employees/search', { search }), + // The teammates the replacement picker offers before anything is typed: mine, or an employee's for HR. + teammates: (uid?: string) => get('/api/employees/teammates', uid ? { uid } : {}), + // Whether a colleague is off on any day of the range, nothing more (§5.1). + isAway: (uid: string, from: string, to: string) => get<{ away: boolean | null }>(`/api/employees/${user(uid)}/away`, { from, to }), // Group list for the HR report/export filters (HR-only endpoint). listGroups: () => get('/api/groups'), diff --git a/src/utils/people.spec.ts b/src/utils/people.spec.ts index 17da68c2..0413bd59 100644 --- a/src/utils/people.spec.ts +++ b/src/utils/people.spec.ts @@ -30,7 +30,7 @@ vi.mock('@nextcloud/l10n', () => ({ }, })) -const { namesAndMore } = await import('./people.js') +const { namesAndMore, replacementSuggestions } = await import('./people.js') describe('namesAndMore', () => { it('lists everyone when all names are known', () => { @@ -45,3 +45,34 @@ describe('namesAndMore', () => { expect(namesAndMore({ count: 3, names: ['R&D Team', 'Ann '] })).toBe('R&D Team, Ann and 1 more') }) }) + +describe('replacementSuggestions', () => { + const alice = { uid: 'alice', displayName: 'Alice Martin' } + const bob = { uid: 'bob', displayName: 'Bob Keller' } + const charlie = { uid: 'charlie', displayName: 'Charlie Dubois' } + const dave = { uid: 'dave', displayName: 'Dave Novak' } + const eve = { uid: 'eve', displayName: 'Eve Laurent' } + const uids = (list: { uid: string }[]) => list.map((person) => person.uid) + + it('offers the colleagues chosen before first, then the teammates by name', () => { + expect(uids(replacementSuggestions({ past: [dave, bob], teammates: [eve, charlie], selected: null, subjectUid: 'alice' }))) + .toEqual(['dave', 'bob', 'charlie', 'eve']) + }) + + it('lists a teammate chosen before only once, where it was chosen', () => { + expect(uids(replacementSuggestions({ past: [eve], teammates: [eve, charlie, bob], selected: null, subjectUid: 'alice' }))) + .toEqual(['eve', 'bob', 'charlie']) + }) + + it('never offers the person whose absence it is', () => { + expect(uids(replacementSuggestions({ past: [alice], teammates: [alice, bob], selected: null, subjectUid: 'alice' }))) + .toEqual(['bob']) + }) + + it('keeps the current choice pickable when nobody else lists it', () => { + expect(uids(replacementSuggestions({ past: [], teammates: [bob], selected: dave, subjectUid: 'alice' }))) + .toEqual(['dave', 'bob']) + expect(uids(replacementSuggestions({ past: [], teammates: [bob], selected: bob, subjectUid: 'alice' }))) + .toEqual(['bob']) + }) +}) diff --git a/src/utils/people.ts b/src/utils/people.ts index 57f1068f..2953778d 100644 --- a/src/utils/people.ts +++ b/src/utils/people.ts @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ +import type { UserRef } from '../types/index.ts' + import { n } from '@nextcloud/l10n' /** @@ -20,3 +22,27 @@ export function namesAndMore({ count, names }: { count: number, names: string[] } return n('absence', '{names} and {count} more', '{names} and {count} more', rest, { names: listed, count: rest }, { escape: false, sanitize: false }) } + +/** + * What the replacement picker offers before anything is typed (§5.1): the + * colleagues chosen before first, then the teammates by name. Nobody twice, + * never the person whose absence it is, and the current choice stays pickable. + * + * @param people the lists to merge + * @param people.past colleagues chosen as replacement before, newest first + * @param people.teammates the teammates of the person, in any order + * @param people.selected the replacement picked now, null for none + * @param people.subjectUid whose absence it is + */ +export function replacementSuggestions({ past, teammates, selected, subjectUid }: { past: UserRef[], teammates: UserRef[], selected: UserRef | null, subjectUid: string | null }): UserRef[] { + const byName = [...teammates].sort((a, b) => a.displayName.localeCompare(b.displayName)) + const seen = new Set(subjectUid ? [subjectUid] : []) + const list: UserRef[] = [] + for (const person of [...past, ...byName]) { + if (!seen.has(person.uid)) { + seen.add(person.uid) + list.push(person) + } + } + return selected && !seen.has(selected.uid) ? [selected, ...list] : list +} diff --git a/tests/Integration/AccessMatrixTest.php b/tests/Integration/AccessMatrixTest.php index beb2f797..0276eeaf 100644 --- a/tests/Integration/AccessMatrixTest.php +++ b/tests/Integration/AccessMatrixTest.php @@ -110,6 +110,8 @@ private static function matrix(): array { 'employee#index' => [$hr, []], 'employee#search' => [[self::COLLEAGUE, self::OWNER, self::MANAGER, self::HR], ['search' => 'itest'], 'empty'], + 'employee#teammates' => [[self::OWNER, self::HR], ['uid' => '{owner}']], + 'employee#away' => [[self::COLLEAGUE, self::OWNER, self::MANAGER, self::HR], ['uid' => '{owner}'] + $from], 'employee#exportJson' => [$hr, []], 'employee#importJson' => [$hr, ['json' => '[]', 'dryRun' => true]], 'employee#remind' => [$hr, ['dryRun' => true]], diff --git a/tests/Integration/EmployeeJsonTest.php b/tests/Integration/EmployeeJsonTest.php index e548dd9b..7a3f49f4 100644 --- a/tests/Integration/EmployeeJsonTest.php +++ b/tests/Integration/EmployeeJsonTest.php @@ -17,6 +17,7 @@ use OCA\Absence\Exception\ValidationException; use OCA\Absence\Service\BalanceService; use OCA\Absence\Service\ConfigService; +use OCA\Absence\Service\CoverageService; use OCA\Absence\Service\EmployeeDirectory; use OCA\Absence\Service\EmployeeJsonService; use OCA\Absence\Service\EmployeeListService; @@ -337,6 +338,6 @@ private function controller(string $uid): EmployeeController { return new EmployeeController('absence', Server::get(IRequest::class), $uid, Server::get(IUserManager::class), Server::get(IGroupManager::class), Server::get(ISearch::class), Server::get(EmployeeDirectory::class), Server::get(EmployeeListService::class), $this->service, Server::get(RegionReminderService::class), Server::get(PermissionService::class), - Server::get(LoggerInterface::class), Server::get(IFactory::class)->get('absence')); + Server::get(LoggerInterface::class), Server::get(IFactory::class)->get('absence'), Server::get(CoverageService::class)); } } diff --git a/tests/Integration/EmployeeListTest.php b/tests/Integration/EmployeeListTest.php index cf9c6317..9e89b48a 100644 --- a/tests/Integration/EmployeeListTest.php +++ b/tests/Integration/EmployeeListTest.php @@ -18,6 +18,7 @@ use OCA\Absence\Db\LeaveTypeMapper; use OCA\Absence\Service\BalanceService; use OCA\Absence\Service\ConfigService; +use OCA\Absence\Service\CoverageService; use OCA\Absence\Service\EmployeeDirectory; use OCA\Absence\Service\EmployeeJsonService; use OCA\Absence\Service\EmployeeListService; @@ -255,6 +256,6 @@ private function controller(string $uid): EmployeeController { return new EmployeeController('absence', Server::get(IRequest::class), $uid, Server::get(IUserManager::class), Server::get(IGroupManager::class), Server::get(ISearch::class), Server::get(EmployeeDirectory::class), Server::get(EmployeeListService::class), Server::get(EmployeeJsonService::class), Server::get(RegionReminderService::class), - Server::get(PermissionService::class), Server::get(LoggerInterface::class), Server::get(IFactory::class)->get('absence')); + Server::get(PermissionService::class), Server::get(LoggerInterface::class), Server::get(IFactory::class)->get('absence'), Server::get(CoverageService::class)); } } diff --git a/tests/Integration/RegionReminderTest.php b/tests/Integration/RegionReminderTest.php index 69b5a4b3..ddc8286d 100644 --- a/tests/Integration/RegionReminderTest.php +++ b/tests/Integration/RegionReminderTest.php @@ -14,6 +14,7 @@ use OCA\Absence\Controller\EmployeeController; use OCA\Absence\Notification\Notifier; use OCA\Absence\Service\ConfigService; +use OCA\Absence\Service\CoverageService; use OCA\Absence\Service\EmployeeDirectory; use OCA\Absence\Service\EmployeeJsonService; use OCA\Absence\Service\EmployeeListService; @@ -165,7 +166,7 @@ private function employeeController(string $uid): EmployeeController { return new EmployeeController('absence', Server::get(IRequest::class), $uid, Server::get(IUserManager::class), Server::get(IGroupManager::class), Server::get(ISearch::class), Server::get(EmployeeDirectory::class), Server::get(EmployeeListService::class), Server::get(EmployeeJsonService::class), Server::get(RegionReminderService::class), - Server::get(PermissionService::class), Server::get(LoggerInterface::class), Server::get(IFactory::class)->get('absence')); + Server::get(PermissionService::class), Server::get(LoggerInterface::class), Server::get(IFactory::class)->get('absence'), Server::get(CoverageService::class)); } private function configController(string $uid): ConfigController { diff --git a/tests/Integration/ReplacementPickerTest.php b/tests/Integration/ReplacementPickerTest.php new file mode 100644 index 00000000..c19b59e3 --- /dev/null +++ b/tests/Integration/ReplacementPickerTest.php @@ -0,0 +1,230 @@ + */ + private array $configBefore = []; + private bool $sharedCalendarBefore = false; + + protected function setUp(): void { + parent::setUp(); + $users = Server::get(IUserManager::class); + $groups = Server::get(IGroupManager::class); + $staff = $groups->createGroup(self::STAFF_GROUP); + foreach (self::USERS as $uid) { + $user = $users->createUser($uid, 'Itest-Password-' . $uid); + $user->setDisplayName(ucfirst(substr($uid, strlen(self::PREFIX)))); + if ($uid !== self::FRANK) { + $staff->addUser($user); + } + } + $groups->createGroup(self::HR_GROUP)->addUser($users->get(self::HR)); + foreach ([self::ALICE, self::BOB, self::CHARLIE, self::FRANK] as $uid) { + $users->get($uid)->setManagerUids([self::DAVE]); + } + $users->get(self::DAVE)->setManagerUids([self::ERIN]); + $users->get(self::EVE)->setManagerUids([self::ALICE]); + + $config = Server::get(ConfigService::class); + $this->configBefore = [ + ConfigLexicon::KEY_HR_GROUP => $config->getHrGroup(), + ConfigLexicon::KEY_EMPLOYEES_GROUP => $config->getEmployeesGroup(), + ]; + $this->sharedCalendarBefore = $config->isCalDavSharedEnabled(); + $appConfig = Server::get(IAppConfig::class); + $appConfig->setValueBool(ConfigService::APP_ID, ConfigLexicon::KEY_CALDAV_SHARED, false); + $appConfig->setValueString(ConfigService::APP_ID, ConfigLexicon::KEY_HR_GROUP, self::HR_GROUP); + $appConfig->setValueString(ConfigService::APP_ID, ConfigLexicon::KEY_EMPLOYEES_GROUP, self::STAFF_GROUP); + } + + protected function tearDown(): void { + $db = Server::get(IDBConnection::class); + $qb = $db->getQueryBuilder(); + $qb->delete('absence_requests') + ->where($qb->expr()->in('employee_uid', $qb->createNamedParameter(self::USERS, IQueryBuilder::PARAM_STR_ARRAY))) + ->executeStatement(); + foreach (self::USERS as $uid) { + Server::get(IUserManager::class)->get($uid)?->delete(); + } + foreach ([self::STAFF_GROUP, self::HR_GROUP] as $gid) { + Server::get(IGroupManager::class)->get($gid)?->delete(); + } + foreach ($this->configBefore as $key => $value) { + Server::get(IAppConfig::class)->setValueString(ConfigService::APP_ID, $key, $value); + } + Server::get(IAppConfig::class)->setValueBool(ConfigService::APP_ID, ConfigLexicon::KEY_CALDAV_SHARED, $this->sharedCalendarBefore); + parent::tearDown(); + } + + public function testTeammatesAreThePeersTheManagerAndTheReports(): void { + self::assertEqualsCanonicalizing([self::BOB, self::CHARLIE, self::DAVE, self::EVE], $this->uids($this->service()->getTeammates(self::ALICE, self::ALICE))); + } + + public function testAManagersTeammatesAreTheirReportsAndTheirOwnManager(): void { + // Frank reports to Dave but is no employee, so he is nobody's replacement. + self::assertEqualsCanonicalizing([self::ALICE, self::BOB, self::CHARLIE, self::ERIN], $this->uids($this->service()->getTeammates(self::DAVE, self::DAVE))); + } + + public function testTeammatesComeWithTheirName(): void { + $byUid = array_column($this->service()->getTeammates(self::EVE, self::EVE), 'displayName', 'uid'); + + self::assertSame([self::ALICE => 'Alice'], $byUid); + } + + public function testHrAsksForAnyEmployee(): void { + self::assertEqualsCanonicalizing([self::ALICE, self::BOB, self::DAVE], $this->uids($this->service()->getTeammates(self::HR, self::CHARLIE))); + } + + public function testAnEmployeeOnlyAsksForThemselves(): void { + $this->expectException(ForbiddenException::class); + $this->service()->getTeammates(self::DAVE, self::ALICE); + } + + public function testSomebodyOutsideTheEmployeesHasNoTeammatesToAskFor(): void { + $this->expectException(ForbiddenException::class); + $this->service()->getTeammates(self::FRANK, self::FRANK); + } + + public function testLeaveInForceOrAskedForIsAway(): void { + foreach ([LeaveRequest::STATUS_PENDING, LeaveRequest::STATUS_ESCALATED, LeaveRequest::STATUS_APPROVED, LeaveRequest::STATUS_WITHDRAWAL_PENDING] as $status) { + $request = $this->seed(self::BOB, $status, '2027-03-08', '2027-03-10'); + self::assertTrue($this->service()->isAway(self::ALICE, self::BOB, '2027-03-10', '2027-03-12'), $status); + Server::get(LeaveRequestMapper::class)->delete($request); + } + } + + public function testLeaveThatIsNotTakenOrOtherDaysIsNotAway(): void { + $this->seed(self::BOB, LeaveRequest::STATUS_REJECTED, '2027-03-08', '2027-03-10'); + $this->seed(self::BOB, LeaveRequest::STATUS_CANCELLED, '2027-03-08', '2027-03-10'); + $this->seed(self::BOB, LeaveRequest::STATUS_APPROVED, '2027-03-01', '2027-03-05'); + + self::assertFalse($this->service()->isAway(self::ALICE, self::BOB, '2027-03-08', '2027-03-12')); + } + + public function testHrAndTheTeamGetAnAnswer(): void { + $this->seed(self::BOB, LeaveRequest::STATUS_APPROVED, '2027-03-08', '2027-03-10'); + + self::assertTrue($this->service()->isAway(self::HR, self::BOB, '2027-03-08', '2027-03-12')); + // Dave is Bob's manager + self::assertTrue($this->service()->isAway(self::DAVE, self::BOB, '2027-03-08', '2027-03-12')); + } + + public function testSomebodyWithNoTieToThePersonGetsNoAnswer(): void { + // Eve reports to Alice: Bob is not one of her teammates. + $this->seed(self::BOB, LeaveRequest::STATUS_APPROVED, '2027-03-08', '2027-03-10'); + + self::assertNull($this->service()->isAway(self::EVE, self::BOB, '2027-03-08', '2027-03-12')); + } + + public function testEveryoneGetsAnAnswerWhileTheSharedCalendarShowsEveryone(): void { + Server::get(IAppConfig::class)->setValueBool(ConfigService::APP_ID, ConfigLexicon::KEY_CALDAV_SHARED, true); + $this->seed(self::BOB, LeaveRequest::STATUS_APPROVED, '2027-03-08', '2027-03-10'); + + self::assertTrue($this->service()->isAway(self::EVE, self::BOB, '2027-03-08', '2027-03-12')); + } + + public function testARangeOverAYearIsRefused(): void { + $this->expectException(ValidationException::class); + $this->service()->isAway(self::ALICE, self::BOB, '2027-01-01', '2028-01-03'); + } + + public function testOnlyEmployeesAndHrAskWhoIsAway(): void { + $this->expectException(ForbiddenException::class); + $this->service()->isAway(self::FRANK, self::BOB, '2027-03-08', '2027-03-12'); + } + + public function testOnlyAnEmployeeCanBeAway(): void { + $this->expectException(ValidationException::class); + $this->service()->isAway(self::HR, self::FRANK, '2027-03-08', '2027-03-12'); + } + + /** + * The resolver and the directory remember what they read for the length of + * a web request, so each test builds its own. + */ + private function service(): CoverageService { + $directory = new EmployeeDirectory(Server::get(IUserManager::class), Server::get(IGroupManager::class), Server::get(ConfigService::class), Server::get(LoggerInterface::class)); + $resolver = new ManagerResolver(Server::get(IUserManager::class), Server::get(IUserConfig::class), $directory, Server::get(LoggerInterface::class)); + $l = Server::get(IFactory::class)->get(ConfigService::APP_ID, 'en'); + return new CoverageService( + Server::get(LeaveRequestMapper::class), + Server::get(LeaveTypeMapper::class), + $resolver, + new PermissionService(Server::get(IGroupManager::class), $resolver, Server::get(ConfigService::class), Server::get(LeaveTypeMapper::class), $l, Server::get(LoggerInterface::class), $directory), + Server::get(ConfigService::class), + $directory, + Server::get(IUserManager::class), + $l, + ); + } + + /** + * @param list $people + * @return list + */ + private function uids(array $people): array { + return array_column($people, 'uid'); + } + + private function seed(string $uid, string $status, string $start, string $end): LeaveRequest { + $request = new LeaveRequest(); + $request->setEmployeeUid($uid); + $request->setTypeId(1); + $request->setStartDate($start); + $request->setEndDate($end); + $request->setWorkingDays(1.0); + $request->setStatus($status); + $request->setCreatedAt(new \DateTime()); + $request->setUpdatedAt(new \DateTime()); + return Server::get(LeaveRequestMapper::class)->insert($request); + } +} diff --git a/tests/Unit/Controller/EmployeeControllerTest.php b/tests/Unit/Controller/EmployeeControllerTest.php index 5431c393..84505792 100644 --- a/tests/Unit/Controller/EmployeeControllerTest.php +++ b/tests/Unit/Controller/EmployeeControllerTest.php @@ -49,6 +49,7 @@ protected function setUp(): void { $permission, $this->createMock(LoggerInterface::class), $this->createMock(\OCP\IL10N::class), + $this->createMock(\OCA\Absence\Service\CoverageService::class), ); }