Files
vac-optimizer/src/app/components/user-input/user-input.ts
T

238 lines
7.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
Component,
computed,
effect,
inject,
signal,
ChangeDetectionStrategy,
} from '@angular/core';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { UserInputService } from '../../services/user-input-service';
import { RulesPanel } from '../rules-panel/rules-panel';
import { MatCard, MatCardContent } from '@angular/material/card';
import { MatIcon } from '@angular/material/icon';
import { DayInput } from '../userInput/day-input/day-input';
import { MatButtonModule } from '@angular/material/button';
import { VacDay } from '../../services/calendar-service';
import type { LeaveType } from '../../services/leave-planner.service';
import { TranslationService } from '../../services/translation-service';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { PlanningDurationService } from '../../services/planning-duration.service';
import { addPlanningDays } from '../../services/planning-date';
@Component({
selector: 'app-user-input',
imports: [
MatInputModule,
MatFormFieldModule,
RulesPanel,
MatCard,
MatCardContent,
MatIcon,
MatButtonModule,
DayInput,
],
templateUrl: './user-input.html',
styleUrl: './user-input.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserInput {
private userInputService: UserInputService = inject(UserInputService);
protected readonly declarationEntry = this.userInputService.declarationEntrySignal;
protected readonly declaredType = this.userInputService.declaredTypeSignal;
protected readonly declaredTypes: readonly LeaveType[] = ['cp', 'rtt', 'other'];
protected readonly calendarSettings = inject(CalendarSettingsService);
protected readonly duration = inject(PlanningDurationService);
protected readonly translationService = inject(TranslationService);
protected readonly durationLabel = computed(() => {
const estimate = this.duration.estimate();
if (!estimate) return '';
return this.tr()
.userInput.durationEstimate.replace(
'{range}',
`${estimate.minimum}–${estimate.maximum}`,
)
.replace('{unit}', this.tr().userInput.durationUnits[estimate.unit]);
});
get tr() {
return this.translationService.tr;
}
protected readonly trace = this.userInputService.planningTraceSignal;
protected readonly traceResolved = this.userInputService.traceResolvedSignal;
protected readonly historyBalanceId = signal<string | null>(null);
protected readonly historyPage = signal(0);
protected readonly remainingDays = computed(() =>
(this.userInputService.displayedPlanSignal()?.remainingBalances ?? []).reduce(
(total, balance) => total + balance.quantity,
0,
),
);
protected readonly hasAtRiskDays = computed(() =>
this.userInputService
.displayedPlanSignal()
?.remainingBalances.some((balance) => balance.classification !== 'deferred'),
);
protected remainingDaysDetails = computed(() => {
const plan = this.userInputService.displayedPlanSignal();
if (!plan) return [];
const incomplete =
this.userInputService.planningOutcomeSignal()?.kind === 'PlanningIncomplete';
const copy = this.tr().userInput;
return plan.remainingBalances.map((balance) => {
const code =
incomplete && ['preserved', 'not-established'].includes(balance.reason.code)
? 'calculation-incomplete'
: balance.reason.code;
return {
id: balance.id,
title: `${balance.quantity} ${balance.quantity > 1 ? copy.daysSuffix : copy.daySuffix} ${this.translationService.getDayTypeLabel(balance.type)}`,
reason: this.translationService.getRemainingBalanceReason(
balance,
plan,
incomplete,
),
validity: copy.remainingValidity
.replace(
'{available}',
this.translationService.formatPlanningDate(balance.availableFrom),
)
.replace(
'{expiry}',
this.translationService.formatPlanningDate(balance.expiryDate),
),
horizon: copy.remainingHorizon
.replace(
'{start}',
this.translationService.formatPlanningDate(plan.horizon.start),
)
.replace(
'{end}',
this.translationService.formatPlanningDate(
addPlanningDays(plan.horizon.end, -1),
),
),
earnedFrom: balance.sourceRuleId
? copy.remainingEarnedFrom.replace(
'{rule}',
this.ruleName(balance.sourceRuleId),
)
: '',
suggestion: copy.remainingSuggestions[code],
};
});
});
protected readonly remainingHistory = computed(() => {
const id = this.historyBalanceId();
if (!id) return [];
return (
this.trace()?.phases.flatMap((phase) =>
phase.decisions.flatMap((decision) =>
decision.candidates
.filter((candidate) => candidate.placement?.balanceId === id)
.map((candidate) => ({ candidate, phase: phase.name })),
),
) ?? []
);
});
protected readonly historyPageCount = computed(() =>
Math.ceil(this.remainingHistory().length / 20),
);
protected readonly visibleHistory = computed(() =>
this.remainingHistory()
.slice(this.historyPage() * 20, (this.historyPage() + 1) * 20)
.map(({ candidate, phase }) => ({
date: (candidate.dates ?? (candidate.date ? [candidate.date] : []))
.map((date) => this.translationService.formatPlanningDate(date))
.join(', '),
phase: this.tr().planning.explanation.stages[phase] ?? this.criterionLabel(phase),
status: this.tr().planning.traceStatuses[candidate.status],
reason: candidate.reason
? (this.tr().userInput.remainingCandidateReasons[candidate.reason.code] ??
this.tr().planning.explanation.unavailable[candidate.reason.code] ??
this.tr().userInput.remainingCandidateReasons['unknown'])
: '',
criteria: (candidate.technicalComparison ?? []).flatMap((value) => {
const label = this.criterionLabel(value.name);
return label
? [
{
text: `${label} : ${value.before} → ${value.after}`,
decisive: value.name === candidate.firstDecisiveComparator,
},
]
: [];
}),
})),
);
constructor() {
effect(() => {
this.userInputService.planningOutcomeSignal();
this.historyBalanceId.set(null);
this.historyPage.set(0);
});
}
private ruleName(id: string): string {
return (
this.userInputService.planningSnapshotSignal()?.rules.find((rule) => rule.id === id)
?.name ?? id
);
}
private criterionLabel(name: string): string | undefined {
const id = name.replace(/^protected:/, '');
const key =
id === 'obligations'
? 'obligation-validity'
: id.startsWith('preference:')
? 'preference'
: id;
return this.tr().planning.explanation.objectives[key]?.label.replace(
'{rule}',
this.ruleName(id.slice('preference:'.length)),
);
}
protected toggleRemainingHistory(id: string, event: Event): void {
const open = (event.currentTarget as HTMLDetailsElement).open;
if (open && id !== this.historyBalanceId()) {
this.historyPage.set(0);
this.historyBalanceId.set(id);
} else if (!open && id === this.historyBalanceId()) this.historyBalanceId.set(null);
}
protected hasRemainingDays = computed(() => this.remainingDays() > 0);
protected get daysOff() {
return this.userInputService.vacationNumberSignal();
}
public addDay() {
this.userInputService.updateBalances((days) => [
...days,
this.userInputService.createVacationDay(),
]);
}
public removeFromList(index: number) {
this.userInputService.updateBalances((days) => days.filter((_, i) => i !== index));
}
public updateDay(index: number, updatedDay: VacDay) {
this.userInputService.updateBalances((days) =>
days.map((day, i) => (i === index ? updatedDay : day)),
);
}
public triggerComputation() {
if (this.calendarSettings.planningHorizonError()) return;
this.userInputService.requestComputation();
}
}