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
24 changes: 22 additions & 2 deletions SPECIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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).

Expand Down
2 changes: 2 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
22 changes: 22 additions & 0 deletions lib/Controller/EmployeeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -42,6 +43,7 @@ public function __construct(
private PermissionService $permission,
private LoggerInterface $logger,
private IL10N $l,
private CoverageService $coverage,
) {
parent::__construct($appName, $request);
}
Expand Down Expand Up @@ -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.
*
Expand Down
62 changes: 62 additions & 0 deletions lib/Service/CoverageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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];
Expand Down Expand Up @@ -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<array{uid: string, displayName: string}>
* @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<string>
*/
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.
Expand Down
91 changes: 78 additions & 13 deletions src/components/RequestDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@
<p class="dialog__hint">
{{ replacementHint }}
</p>
<NcNoteCard v-if="replacementAway && selectedReplacement" type="warning">
{{ t('absence', '{name} is off on some of these days.', { name: selectedReplacement.displayName }, undefined, { escape: false, sanitize: false }) }}
</NcNoteCard>
</div>

<div class="dialog__field">
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -327,8 +330,16 @@ const selectedEmployee = ref<UserRef | null>(null)
const employeeOptions = ref<UserRef[]>([])
const employeeLoading = ref(false)
const selectedReplacement = ref<UserRef | null>(null)
const replacementOptions = ref<UserRef[]>([])
// The search results while at least two letters are typed, null otherwise.
const replacementResults = ref<UserRef[] | null>(null)
const replacementLoading = ref(false)
// The absent person's teammates, offered before anything is typed (§5.1).
const teammates = ref<UserRef[]>([])
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<typeof setTimeout> | 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<Coverage | null>(null)
Expand Down Expand Up @@ -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<UserRef[]>(() => 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<Date | null>({
get() {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down
5 changes: 5 additions & 0 deletions src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import type {
SettingsInput,
SickLeaveReport,
Trends,
UserRef,
} from '../types/index.ts'

import axios from '@nextcloud/axios'
Expand Down Expand Up @@ -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<EmployeeSearchResult[]>('/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<UserRef[]>('/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<Group[]>('/api/groups'),
Expand Down
33 changes: 32 additions & 1 deletion src/utils/people.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand All @@ -45,3 +45,34 @@ describe('namesAndMore', () => {
expect(namesAndMore({ count: 3, names: ['R&D Team', 'Ann <Lee>'] })).toBe('R&D Team, Ann <Lee> 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'])
})
})
Loading
Loading