Author SHA1 Message Date
nessar 221edfa5ba Merge branch 'feature/ui-ux-results' into feature/ui-ux-refresh (#353, #354, #355)
# Conflicts:
#	src/app/components/user-input/user-input.html
2026-11-13 19:03:22 +01:00
nessarandClaude Fable 5.2 8be156bff4 feat(ui): keep the configuration panel in view on wide screens (#355)
At the two-column breakpoint the panel is sticky and scrolls internally, and
the indicative wait with the Calculate button stays pinned at its bottom. The
panel is registered as a CDK scrollable so that dragging a rule still
auto-scrolls it. Single-column layouts are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 19:02:28 +01:00
nessar 95e36e8a4e Merge branch 'feature/ui-ux-empty-start' into feature/ui-ux-refresh (#356) 2026-11-13 18:59:26 +01:00
nessarandClaude Opus 5.5 55144aaf37 feat(balances): start from an empty leave-balance list instead of random defaults (#356)
An absent or unreadable saved list now starts empty; no quantity is
generated. With no leave balance and no declared non-working day there
is nothing to plan: no calculation starts on load, Calculate is disabled
with the reason exposed through aria-describedby, and the results panel
shows the planning horizon's calendar with an invitation. Declared days
alone still calculate, so earned-leave chains keep working.

ADR 0012 records the decision and supersedes the random defaults of
ADR 0005. Tests now state their balances explicitly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:58:31 +01:00
nessarandClaude Fable 5.2 6660e7e6bb feat(ui): show the calendar directly under the plan summary (#354)
Move the time-window, if-then and declared time-off period blocks into one
closed "applied rules detail" disclosure next to the placement explanation,
so the legend and the first row of months sit under the summary figures.
Put the status and the calculation date on the heading line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 18:49:07 +01:00
nessarandClaude Fable 5.2 7ebc87be33 feat(ui): polish product name, statistics and calculation date (#353)
Show the product name VacOptimizer in the header, round plan statistics to one
decimal in the active locale, lay the statistics tiles out in two columns when
the dialog is wide enough, and attach the calculation date to the results
heading and status instead of a free paragraph.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 18:41:55 +01:00
24 changed files with 661 additions and 346 deletions

No files matched your search

+3 -2
View File
@@ -186,7 +186,7 @@ The `/benchmark` route and planner core are lazy-loaded, so the normal applicati
The header opens one Settings dialog for planning dates, System / Light / Dark theme selection, English / French / German / Spanish language selection, and ISO week numbers. Changes apply and save on selection; closing the dialog retains them. System follows device appearance changes.
Saved balances, including an empty list, are restored before the initial calculation. When no readable saved list exists, CP, RTT, and Other start with random quantities from 10 through 20. These defaults remain unsaved until the first balance edit; subsequent edits save the entire list with identities, order, quantities, types, and calendar dates. Invalid saved balance data is cleared without removing unrelated settings or rules.
Saved balances, including an empty list, are restored before the initial calculation. When no readable saved list exists, the list starts empty and stays unsaved until the first balance edit; every balance edit saves the entire list with identities, order, quantities, types, and calendar dates. Invalid saved balance data is cleared without removing unrelated settings or rules. An empty list shows an invitation to add a balance. With no leave balance and no declared non-working day, nothing is calculated and Calculate is disabled; the results panel shows the planning horizon's calendar with its weekends and public holidays.
## Repository layout
@@ -322,6 +322,7 @@ Run `bun scripts/ci-policy.test.mjs` and `bun scripts/ci-image.test.mjs` locally
- [ADR 0002](docs/adr/0002-personal-client-side-planner-for-now.md) records the original client-side scope, superseded by ADR 0011.
- [ADR 0003](docs/adr/0003-constraint-first-lexicographic-planning.md) records the constraint-first planner architecture.
- [ADR 0004](docs/adr/0004-stable-explanation-original-trace-counterfactual.md) separates the outcome, stable explanation and displayed-placement hypothetical analysis.
- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration and random fallback behavior.
- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration; its random fallback is superseded by ADR 0012.
- [ADR 0006](docs/adr/0006-user-selected-horizons-and-cancellable-calculations.md) records fixed saved horizons, cancellation, duration estimation, and the removal of the automatic deadline.
- [ADR 0011](docs/adr/0011-server-side-planning-for-every-device.md) records server-side planning for every device with a local fallback.
- [ADR 0012](docs/adr/0012-empty-leave-balances-on-first-visit.md) starts from an empty leave-balance list instead of random balances.
@@ -1,3 +1,5 @@
# Restore Saved Planning Inputs Before Generating Random Defaults
[ADR 0012](0012-empty-leave-balances-on-first-visit.md) supersedes the random initial balances below: an absent or unreadable saved list now starts empty. Restoring saved inputs, deleting unreadable data first and saving the whole list on every balance edit are unchanged.
VacOptimizer restores a single locally saved leave-balance list, including an intentionally empty list, with its quantities, leave types, availability dates, and expiry dates; planning rules retain their existing local persistence. Random initial balances are generated when the saved balance list is absent or unreadable: unreadable balance data is deleted first, and the generated list remains unsaved until the first balance edit, after which every balance edit automatically saves the entire current list. Restoring valid saved inputs before initialization prevents random defaults from overwriting user data and keeps a single dataset within the client-side scope of ADR 0002.
@@ -0,0 +1,11 @@
---
status: accepted
---
# Empty Leave Balances on a First Visit
Accepted on 2026-11-13 for [issue #356](https://gitea.nessar.fr/nessar/vac-optimizer/issues/356). This supersedes the random initial balances of [ADR 0005](0005-saved-planning-inputs-before-random-defaults.md); restoring the saved list, including an intentionally empty one, deleting unreadable data first and saving the whole list on every balance edit are unchanged.
A first-time visitor saw a plan calculated on three random balances of 10 to 20 days that they never entered. When the saved leave-balance list is absent or unreadable, VacOptimizer now starts from an empty list, and no quantity is ever generated. The configuration panel then invites the user to add a first leave balance.
With no leave balance and no declared non-working day there is nothing to plan: no calculation starts when the page opens, Calculate is disabled with the reason given to assistive technologies, as for an invalid planning horizon, and the results panel shows the planning horizon's calendar, with its weekends and public holidays, and an invitation instead of plan figures. Declared non-working days alone still start a calculation, because they can earn leave that the plan then places ([ADR 0007](0007-declared-days-and-reported-balances.md)). A plan already on screen stays until the next calculation, as after any other edit.
+1 -1
View File
@@ -82,4 +82,4 @@ Use behavior-level tests that assert returned planning facts and user-visible fi
- Domain definitions are maintained in [CONTEXT.md](../CONTEXT.md). Relevant architectural constraints are [server-side planning for every device](adr/0011-server-side-planning-for-every-device.md), which superseded the [personal client-side planner](adr/0002-personal-client-side-planner-for-now.md), [separate calculation outcome and trace](adr/0004-stable-explanation-original-trace-counterfactual.md), [selected horizons and cancellation](adr/0006-user-selected-horizons-and-cancellable-calculations.md), and [declared days and reported balances](adr/0007-declared-days-and-reported-balances.md).
- **Current integration gaps:** The inspected outcome exposes placements, periods, remaining balances, and several quality metrics, but no dedicated gross earned-leave summary or fixed calculation date. Remaining balances omit fully consumed entitlements. Declared-day support is in progress in the working tree: declarations are carried with outcomes, while the inspected period and work-sequence calculations still use placements alone. Coordinate with #13's finalized semantics before relying on those values; avoid a second conflicting calendar model in the popup.
- **Proposed empty-value convention, not explicitly confirmed:** Counts show 0 when there are no qualifying items. An average with no samples, or longest time-off period length when no periods exist, shows "—". The existing longest work-sequence length remains 0 when there are no work sequences. Empty samples should remain distinguishable from a measured zero in the underlying data.
- **Remaining presentation choices:** Exact decimal precision for averages, metric layout, and whether eligible rules with zero earnings receive breakdown rows were not decided. These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation.
- **Remaining presentation choices:** Metric layout and whether eligible rules with zero earnings receive breakdown rows were not decided. Statistics show at most one decimal in the active locale (#353). These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation.
+93 -95
View File
@@ -110,108 +110,106 @@ describe('Application Settings', () => {
await createApp(startJob);
}
it('keeps random starting balances unsaved through calculation and restores the first edited list', async () => {
it.each([
['absent', null],
['unreadable', '{'],
])(
'starts with nothing to plan when saved balances are %s, then calculates once a balance is added',
async (_, saved) => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
vi.spyOn(console, 'warn').mockImplementation(() => {});
if (saved === null) localStorage.removeItem('leaveBalances');
else localStorage.setItem('leaveBalances', saved);
await revisitApp(true, startInProcessJob);
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('app-day-input')).toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('unrelated.entry')).toBe('keep this value');
expect(root.querySelector('#leave-balances-empty')?.textContent).toContain(
'No leave balance yet',
);
const button = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(button.disabled).toBe(true);
expect(button.getAttribute('aria-describedby')).toBe('leave-balances-empty');
expect(root.querySelector('.duration-estimate')).toBeNull();
expect(calculate).not.toHaveBeenCalled();
expect(root.querySelector('.planning-status')?.textContent).toContain(
'Add your leave balances',
);
expect(root.querySelector('.plan-summary')).toBeNull();
expect(root.querySelector('.statistics-button')).toBeNull();
// The default planning horizon still shows its weekends and public holidays.
expect(root.querySelectorAll('app-calendar-month')).toHaveLength(13);
expect(
root.querySelector('button[data-date="2026-11-11"]')?.getAttribute('aria-label'),
).toContain('Public Holiday');
expect(
root.querySelector('button[data-date="2026-10-10"]')?.getAttribute('aria-label'),
).toContain('Weekend');
root.querySelector<HTMLButtonElement>('.add-day-button')!.click();
fixture.detectChanges();
await fixture.whenStable();
const added = localStorage.getItem('leaveBalances');
expect(JSON.parse(added!)).toMatchObject([
{
type: 'cp',
numberOfDays: 1,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
]);
expect(root.querySelector('#leave-balances-empty')).toBeNull();
expect(root.querySelector('.planning-status')).toBeNull();
expect(calculate).not.toHaveBeenCalled();
expect(button.disabled).toBe(false);
button.click();
await fixture.whenStable();
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toMatchObject([
{ type: 'cp', quantity: 1 },
]);
await expect.poll(() => root.querySelector('.plan-summary')).not.toBeNull();
await revisitApp(true);
expect(fixture.nativeElement.querySelectorAll('app-day-input')).toHaveLength(1);
expect(calculate).toHaveBeenCalledOnce();
expect(localStorage.getItem('leaveBalances')).toBe(added);
},
);
it('restores a saved empty list without calculating, and calculates declared days on their own', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
const random = vi
.spyOn(Math, 'random')
.mockReturnValueOnce(0)
.mockReturnValueOnce(0.5)
.mockReturnValue(1 - Number.EPSILON);
localStorage.removeItem('leaveBalances');
await revisitApp(true);
const root = fixture.nativeElement as HTMLElement;
expect(
Array.from(root.querySelectorAll<HTMLInputElement>('app-day-input input')).map(
(input) => input.value,
),
).toEqual([
'10',
'04/10/2026',
'04/10/2027',
'15',
'04/10/2026',
'04/10/2027',
'20',
'04/10/2026',
'04/10/2027',
]);
const types = await loader.getAllHarnesses(
MatSelectHarness.with({ selector: 'app-day-input mat-select' }),
);
expect(await Promise.all(types.map((type) => type.getValueText()))).toEqual([
'Paid Leave',
'RTT',
'Other',
]);
expect(calculate).toHaveBeenCalledOnce();
const initialRequest = calculate.mock.calls[0][0];
expect(initialRequest.balances.map((balance) => balance.quantity)).toEqual([10, 15, 20]);
expect(calculatePlanningInternal(initialRequest).kind).toBe('Plan');
await expect.poll(() => root.querySelector('.planning-status')).not.toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
root.querySelector<HTMLButtonElement>('.calculate-button')!.click();
await fixture.whenStable();
expect(calculate).toHaveBeenCalledTimes(2);
expect(calculate.mock.calls[1][0].balances).toEqual(initialRequest.balances);
await expect.poll(() => root.querySelector('.planning-status')).not.toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
const quantity = root.querySelector<HTMLInputElement>(
'app-day-input input[type="number"]',
)!;
quantity.value = '7';
quantity.dispatchEvent(new Event('input'));
await fixture.whenStable();
const saved = localStorage.getItem('leaveBalances');
expect(JSON.parse(saved!)).toMatchObject([
{ type: 'cp', numberOfDays: 7, availableDate: '2026-10-04', expiryDate: '2027-10-04' },
{
type: 'rtt',
numberOfDays: 15,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
{
type: 'other',
numberOfDays: 20,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
]);
random.mockReturnValue(0);
await revisitApp(true);
expect(
Array.from(
fixture.nativeElement.querySelectorAll('app-day-input input[type="number"]'),
(input) => (input as HTMLInputElement).value,
),
).toEqual(['7', '15', '20']);
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toEqual(
initialRequest.balances.map((balance, index) =>
index === 0 ? { ...balance, quantity: 7 } : balance,
),
);
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
it('calculates with a saved empty balance list without generating replacement rows', async () => {
localStorage.setItem('leaveBalances', '[]');
const random = vi.spyOn(Math, 'random');
await revisitApp(true);
expect(fixture.nativeElement.querySelector('app-day-input')).toBeNull();
let root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('app-day-input')).toBeNull();
expect(root.querySelector('#leave-balances-empty')).not.toBeNull();
expect(root.querySelector<HTMLButtonElement>('.calculate-button')!.disabled).toBe(true);
expect(calculate).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBe('[]');
localStorage.setItem(
'declaredNonWorkingDays',
JSON.stringify([{ date: '2026-10-06', type: 'cp' }]),
);
await revisitApp(true, startInProcessJob);
root = fixture.nativeElement as HTMLElement;
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toEqual([]);
expect(calculatePlanningInternal(calculate.mock.calls[0][0]).kind).toBe('Plan');
await expect
.poll(() => fixture.nativeElement.querySelector('.planning-status'))
.not.toBeNull();
expect(random).not.toHaveBeenCalled();
expect(calculate.mock.calls[0][0].declaredDays).toEqual([
{ date: '2026-10-06', type: 'cp' },
]);
await expect.poll(() => root.querySelector('.plan-summary')).not.toBeNull();
expect(root.querySelector('.planning-status.info')).toBeNull();
expect(root.querySelector('#leave-balances-empty')).not.toBeNull();
const button = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(button.disabled).toBe(false);
expect(button.getAttribute('aria-describedby')).toBe('planning-duration-estimate');
expect(localStorage.getItem('leaveBalances')).toBe('[]');
});
+5 -1
View File
@@ -22,7 +22,11 @@
</header>
<main class="planner-layout">
<section class="configuration-panel" aria-labelledby="leave-settings-title">
<section
class="configuration-panel"
cdkScrollable
aria-labelledby="leave-settings-title"
>
<app-user-input></app-user-input>
</section>
<section class="results-panel" aria-labelledby="planning-results-title">
+12 -2
View File
@@ -82,7 +82,8 @@ app-calendar-year {
}
.configuration-panel {
padding: 1.25rem;
--panel-padding: 1.25rem;
padding: var(--panel-padding);
background: var(--ui-card-bg);
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-lg);
@@ -106,6 +107,15 @@ app-calendar-year {
.planner-layout {
grid-template-columns: clamp(26rem, 34%, 40rem) minmax(0, 1fr);
}
// Stays in view while the results scroll, and scrolls inside when taller than the screen.
// The 9rem leaves room for the header, which scrolls away, so that the panel fits on first load.
.configuration-panel {
position: sticky;
top: 1rem;
max-height: calc(100dvh - 9rem);
overflow-y: auto;
}
}
@media (max-width: 35rem) {
@@ -118,6 +128,6 @@ app-calendar-year {
}
.configuration-panel {
padding: 1rem;
--panel-padding: 1rem;
}
}
+14 -1
View File
@@ -1,5 +1,6 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ScrollDispatcher } from '@angular/cdk/scrolling';
import { App } from './app';
import { TranslationService } from './services/translation-service';
@@ -26,7 +27,19 @@ describe('App', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('vac-optimizer');
expect(compiled.querySelector('h1')?.textContent).toContain('VacOptimizer');
});
it('registers the scrolling configuration panel so that dragging a rule can auto-scroll it', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const panel = fixture.nativeElement.querySelector('.configuration-panel') as HTMLElement;
const scrollables = TestBed.inject(ScrollDispatcher).getAncestorScrollContainers(
panel.querySelector('app-rules-panel')!,
);
expect(scrollables.map((scrollable) => scrollable.getElementRef().nativeElement)).toEqual([
panel,
]);
});
it('keeps the document language in sync with the selected language', () => {
+11 -2
View File
@@ -6,6 +6,7 @@ import {
inject,
signal,
} from '@angular/core';
import { CdkScrollable } from '@angular/cdk/scrolling';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { provideNativeDateAdapter } from '@angular/material/core';
import { UserInput } from './components/user-input/user-input';
@@ -24,7 +25,15 @@ function isBenchmarkUrl(url: string): boolean {
@Component({
selector: 'app-root',
imports: [MatDatepickerModule, UserInput, CalendarYear, MatButton, MatIcon, RouterOutlet],
imports: [
CdkScrollable,
MatDatepickerModule,
UserInput,
CalendarYear,
MatButton,
MatIcon,
RouterOutlet,
],
templateUrl: './app.html',
styleUrl: './app.scss',
providers: [provideNativeDateAdapter()],
@@ -36,7 +45,7 @@ export class App {
private readonly document = inject(DOCUMENT);
private readonly translations = inject(TranslationService);
protected readonly tr = this.translations.tr;
protected readonly title = signal('vac-optimizer');
protected readonly title = signal('VacOptimizer');
protected readonly showPlanner = signal(
!isBenchmarkUrl(typeof window !== 'undefined' ? window.location.pathname : this.router.url),
);
@@ -264,8 +264,22 @@ function activateWithKeyboard(element: HTMLElement, key: 'Enter' | ' ' = 'Enter'
const presets = createOptimizationPresetRules();
// The page calculates on load only when there is something to plan.
const savedBalances = JSON.stringify([
{
id: 'cp',
type: 'cp',
numberOfDays: 2,
availableDate: '2024-01-01',
expiryDate: '2024-12-31',
},
]);
describe('CalendarYear planning outcome boundary', () => {
beforeEach(() => localStorage.clear());
beforeEach(() => {
localStorage.clear();
localStorage.setItem('leaveBalances', savedBalances);
});
afterEach(() => {
localStorage.clear();
vi.useRealTimers();
@@ -528,7 +542,7 @@ describe('CalendarYear planning outcome boundary', () => {
const expectedStatistics = [
['New leave days', String(placements)],
['Non-working days gained (calendar days)', '4'],
['Average work sequence (working days)', '3.333'],
['Average work sequence (working days)', '3.3'],
['Longest work sequence (working days)', '6'],
['Average time-off period (calendar days)', '2.5'],
['Longest time-off period (calendar days)', '4'],
@@ -1046,7 +1060,7 @@ describe('CalendarYear planning outcome boundary', () => {
expect(dialog.textContent).toContain(holidayLabel);
expect(
Array.from(dialog.querySelectorAll('dd'), (value) => value.textContent?.trim()),
).toEqual(['2', '4', '3,333', '6', '2,5', '4', '0', '0']);
).toEqual(['2', '4', '3,3', '6', '2,5', '4', '0', '0']);
}
expect(dialog.textContent).toContain('Statistiques du planning');
expect(dialog.querySelector('dt')?.textContent).toContain('Nouveaux jours de congé posés');
@@ -1172,7 +1186,6 @@ describe('CalendarYear planning outcome boundary', () => {
(value) => (artifacts = value),
);
if (outcome.kind !== 'Plan') throw new Error(`Expected Plan, got ${outcome.kind}`);
localStorage.setItem('leaveBalances', '[]');
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
await TestBed.configureTestingModule({
imports: [CalendarYear],
@@ -1336,7 +1349,6 @@ describe('CalendarYear planning outcome boundary', () => {
(value) => (artifacts = value),
);
if (outcome.kind !== 'Plan') throw new Error('Expected a plan.');
localStorage.setItem('leaveBalances', '[]');
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
await TestBed.configureTestingModule({
imports: [CalendarYear],
@@ -1637,7 +1649,6 @@ describe('CalendarYear planning outcome boundary', () => {
it('keeps the preceding calendar until a submitted snapshot returns and ignores later edits', async () => {
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
localStorage.setItem('leaveBalances', '[]');
await TestBed.configureTestingModule({
imports: [CalendarYear, UserInput],
providers: [provideZonelessChangeDetection()],
@@ -2588,6 +2599,116 @@ describe('CalendarYear planning outcome boundary', () => {
expect(summaryValues).toEqual(['2', '4', '6']);
});
it('attaches the calculation date to the results heading and status', async () => {
const { calendar, creation } = calendarFor({ ...plan, calculationDate: '2024-05-01' });
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
spyOnCreation().mockImplementation(creation);
TestBed.inject(TranslationService).setLanguage('en');
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const meta = fixture.nativeElement.querySelector('.results-heading .calculation-date');
expect(meta?.textContent?.replace(/\s+/g, ' ').trim()).toBe(
`Calculation date : ${fixture.componentInstance['displayDate']('2024-05-01')}`,
);
expect(meta.previousElementSibling.classList).toContain('planning-status');
});
it.each([true, false])(
'groups the applied rules in one closed disclosure between the summary and the calendar (rules: %s)',
async (withRules) => {
const applied: PlanOutcome = {
...plan,
timeWindowContributions: [
{
ruleId: 'window',
label: 'Window rule',
requested: 2,
declaredDays: [{ date: '2024-05-02', type: 'cp' }],
placementDates: ['2024-05-03'],
},
],
ifThenContributions: [
{
ruleId: 'bridge',
label: 'Bridge rule',
occurrence: '2024-05-08',
requested: 1,
declaredDays: [],
placementDates: ['2024-05-06'],
},
],
timeOffPeriods: [
{
start: '2024-05-02',
end: '2024-05-05',
duration: 4,
placementDates: ['2024-05-03'],
declaredDates: ['2024-05-02'],
nonWorkingDates: ['2024-05-04', '2024-05-05'],
nonWorkingDayGain: 2,
},
],
};
const { calendar, creation } = calendarFor(withRules ? applied : plan, explanation);
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
spyOnCreation().mockImplementation(creation);
const translation = TestBed.inject(TranslationService);
translation.setLanguage('en');
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const details = root.querySelector<HTMLDetailsElement>(
'.plan-insights > .applied-rules',
);
if (!withRules) {
expect(details).toBeNull();
expect(root.querySelector('.declared-rule, .declared-period')).toBeNull();
return;
}
expect(details!.open).toBe(false);
const summary = details!.querySelector<HTMLElement>('summary')!;
expect(summary.textContent?.replace(/\s+/g, ' ')).toContain('Applied rules detail');
expect(summary.textContent?.replace(/\s+/g, ' ')).toContain('Entries : 3');
expect(root.querySelectorAll('.declared-rule, .declared-period')).toHaveLength(3);
expect(
root.querySelectorAll(
'.applied-rules .declared-rule, .applied-rules .declared-period',
),
).toHaveLength(3);
const follows = (earlier: Element, later: Element) =>
Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING);
expect(follows(root.querySelector('.plan-summary')!, details!)).toBe(true);
expect(follows(root.querySelector('.plan-details')!, details!)).toBe(true);
expect(follows(details!, root.querySelector('.calendar-legend')!)).toBe(true);
expect(follows(details!, root.querySelector('.month-grid')!)).toBe(true);
for (const [language, copy] of Object.entries(translationsMap)) {
translation.setLanguage(language);
fixture.detectChanges();
expect(summary.textContent).toContain(copy.planning.appliedRules.title);
expect(summary.textContent).toContain(copy.planning.appliedRules.entries);
}
activateWithKeyboard(summary);
expect(details!.open).toBe(true);
},
);
it('shows muted, disabled context dates in an adjacent year', async () => {
if (explanation.kind !== 'PlanExplanation') throw new Error('Expected plan explanation');
const boundaryPlan: PlanOutcome = {
@@ -3233,6 +3354,9 @@ describe('CalendarYear planning outcome boundary', () => {
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.conflict-explanation').closest('details'),
).toBeNull();
expect(fixture.nativeElement.querySelector('.conflict-explanation').textContent).toContain(
'Required spring leave',
);
@@ -70,6 +70,16 @@
<mat-icon aria-hidden="true">check_circle</mat-icon>
{{ outcomeLabel(planningOutcome()!) }}
</p>
} @else if (!isLoading() && nothingToPlan()) {
<p class="planning-status info">
<mat-icon aria-hidden="true">info</mat-icon>
{{ tr().planning.invitation }}
</p>
}
@if (displayedPlan()?.calculationDate; as calculationDate) {
<p class="calculation-date">
{{ tr().planning.calculationDate }} : {{ displayDate(calculationDate) }}
</p>
}
</div>
@if (displayedPlan()) {
@@ -153,87 +163,6 @@
<dd>{{ plan.metrics.longestWorkSequence }}</dd>
</div>
</dl>
@for (contribution of plan.timeWindowContributions ?? []; track contribution.ruleId) {
<section class="outcome-explanation declared-rule">
<h3>{{ contribution.label }}</h3>
<p>
{{ contribution.declaredDays.length }} {{ tr().bookedDays.booked }} +
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
<strong
>{{
contribution.declaredDays.length + contribution.placementDates.length
}}
/ {{ contribution.requested }}</strong
>
</p>
<p>
@for (day of contribution.declaredDays; track day.date) {
<span>{{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }} </span>
}
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
@if (plan.calculationDate) {
<p>{{ tr().planning.calculationDate }} : {{ displayDate(plan.calculationDate) }}</p>
}
@for (
contribution of plan.ifThenContributions ?? [];
track contribution.ruleId + contribution.occurrence
) {
<section class="outcome-explanation declared-rule">
<h3>{{ contribution.label }} · {{ displayDate(contribution.occurrence) }}</h3>
<p>
{{ contribution.declaredDays.length }} {{ tr().bookedDays.booked }} +
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
<strong>{{ contribution.requested }} / {{ contribution.requested }}</strong>
</p>
@for (day of contribution.declaredDays; track day.date) {
<span>{{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }} </span>
}
@if (contribution.declaredDays.length) {
<p>{{ tr().bookedDays.fixed }}</p>
}
@if (contribution.earnedEntitlement; as earned) {
<p>
{{
earned.added
? tr().planning.futureEntitlement
: tr().planning.includedEntitlement
}}
: {{ earned.quantity }} {{ tr().dayTypes[earned.type] }}
</p>
<p>
{{ tr().planning.details.available }}
{{ displayDate(earned.availableFrom) }} ·
{{ tr().planning.details.expires }} {{ displayDate(earned.expiryDate) }}
</p>
}
</section>
}
@for (period of plan.timeOffPeriods; track period.start) {
@if (period.declaredDates?.length) {
<section class="outcome-explanation declared-period">
<h3>
{{ tr().planning.explanation.breakTitle }} ·
{{ displayDate(period.start) }} – {{ displayDate(period.end) }}
</h3>
<p>
{{ period.declaredDates!.length }} {{ tr().bookedDays.booked }} +
{{ period.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} +
{{ period.nonWorkingDates.length }}
{{ tr().planning.explanation.freeDays }} =
<strong
>{{ period.duration }} {{ tr().planning.explanation.daysOff }}</strong
>
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
}
}
<div class="plan-insights">
@@ -516,6 +445,122 @@
{{ tr().planning.explanationError }} {{ reasonLabel(explanationError()!) }}
</p>
}
@if (displayedPlan(); as plan) {
@if (appliedRuleCount(); as count) {
<details class="applied-rules">
<summary>
<mat-icon aria-hidden="true">rule</mat-icon>
<span
>{{ tr().planning.appliedRules.title
}}<small
>{{ tr().planning.appliedRules.entries }} : {{ count }}</small
></span
>
<mat-icon class="disclosure-chevron" aria-hidden="true"
>expand_more</mat-icon
>
</summary>
<div class="applied-rules-content">
@for (
contribution of plan.timeWindowContributions ?? [];
track contribution.ruleId
) {
<section class="outcome-explanation declared-rule">
<h3>{{ contribution.label }}</h3>
<p>
{{ contribution.declaredDays.length }}
{{ tr().bookedDays.booked }} +
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
<strong
>{{
contribution.declaredDays.length +
contribution.placementDates.length
}}
/ {{ contribution.requested }}</strong
>
</p>
<p>
@for (day of contribution.declaredDays; track day.date) {
<span
>{{ displayDate(day.date) }} ·
{{ tr().dayTypes[day.type] }}
</span>
}
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
@for (
contribution of plan.ifThenContributions ?? [];
track contribution.ruleId + contribution.occurrence
) {
<section class="outcome-explanation declared-rule">
<h3>
{{ contribution.label }} ·
{{ displayDate(contribution.occurrence) }}
</h3>
<p>
{{ contribution.declaredDays.length }}
{{ tr().bookedDays.booked }} +
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
<strong
>{{ contribution.requested }} /
{{ contribution.requested }}</strong
>
</p>
@for (day of contribution.declaredDays; track day.date) {
<span
>{{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }}
</span>
}
@if (contribution.declaredDays.length) {
<p>{{ tr().bookedDays.fixed }}</p>
}
@if (contribution.earnedEntitlement; as earned) {
<p>
{{
earned.added
? tr().planning.futureEntitlement
: tr().planning.includedEntitlement
}}
: {{ earned.quantity }} {{ tr().dayTypes[earned.type] }}
</p>
<p>
{{ tr().planning.details.available }}
{{ displayDate(earned.availableFrom) }} ·
{{ tr().planning.details.expires }}
{{ displayDate(earned.expiryDate) }}
</p>
}
</section>
}
@for (period of declaredPeriods(); track period.start) {
<section class="outcome-explanation declared-period">
<h3>
{{ tr().planning.explanation.breakTitle }} ·
{{ displayDate(period.start) }} – {{ displayDate(period.end) }}
</h3>
<p>
{{ period.declaredDates!.length }}
{{ tr().bookedDays.booked }} +
{{ period.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} +
{{ period.nonWorkingDates.length }}
{{ tr().planning.explanation.freeDays }} =
<strong
>{{ period.duration }}
{{ tr().planning.explanation.daysOff }}</strong
>
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
</div>
</details>
}
}
</div>
<p class="calendar-help">
@@ -31,8 +31,14 @@ code {
padding-block: 0.25rem 0.5rem;
}
.results-heading {
display: grid;
gap: 0.75rem;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
}
.calculation-date {
color: var(--ui-text-secondary);
font-size: 0.8125rem;
}
.planning-status {
display: flex;
@@ -59,6 +65,10 @@ code {
background: var(--ui-error-bg);
color: var(--ui-error-text);
}
&.info {
background: var(--mat-sys-primary-container);
color: var(--mat-sys-on-primary-container);
}
}
.plan-summary {
@@ -154,12 +164,24 @@ code {
}
}
.applied-rules-content {
display: grid;
gap: 0.75rem;
padding: 1rem;
}
.statistics-content {
display: grid;
gap: 1rem;
}
.statistics-summary {
grid-template-columns: minmax(0, 1fr);
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
div {
padding: 0.875rem 1rem;
}
dd {
font-size: 1.75rem;
}
}
.earned-leave-breakdown {
display: grid;
@@ -109,6 +109,7 @@ export class CalendarYear {
protected readonly liveMessage = signal('');
protected readonly planningHorizon = this.calculations.displayedHorizon;
protected readonly declarationEntry = this.userInput.declarationEntrySignal;
protected readonly nothingToPlan = this.userInput.nothingToPlan;
private readonly monthGrid = viewChild<ElementRef<HTMLElement>>('monthGrid');
private readonly declarationDrag = signal<{
pointerId: number;
@@ -132,11 +133,15 @@ export class CalendarYear {
}
return { dates, type: this.userInput.declaredTypeSignal() };
});
/** Without a calculation to display, the calendar shows the current inputs, as during declaration entry. */
private readonly showsInputs = computed(
() => this.declarationEntry() || !this.planningHorizon(),
);
protected readonly calendarHorizon = computed(() =>
this.declarationEntry() ? this.settings.planningHorizon() : this.planningHorizon(),
this.showsInputs() ? this.settings.planningHorizon() : this.planningHorizon(),
);
protected readonly calendarDeclaredDays = computed<Readonly<Record<string, LeaveType>>>(() => {
const days = this.declarationEntry()
const days = this.showsInputs()
? this.userInput.declaredDaysSignal()
: (this.calculations.accepted()?.declaredDays ?? []);
return Object.fromEntries(days.map(({ date, type }) => [date, type]));
@@ -154,6 +159,19 @@ export class CalendarYear {
}
protected readonly displayedPlan = this.calculations.displayedPlan;
protected readonly declaredPeriods = computed(() =>
(this.displayedPlan()?.timeOffPeriods ?? []).filter(
({ declaredDates }) => declaredDates?.length,
),
);
protected readonly appliedRuleCount = computed(() => {
const plan = this.displayedPlan();
return (
(plan?.timeWindowContributions?.length ?? 0) +
(plan?.ifThenContributions?.length ?? 0) +
this.declaredPeriods().length
);
});
protected readonly weekendConnectedHolidays = computed(() => {
const isWeekend = (date: string) => {
const day = new Date(`${date}T00:00:00Z`).getUTCDay();
@@ -210,7 +228,7 @@ export class CalendarYear {
protected readonly calendarProjection = computed(() => {
const horizon = this.calendarHorizon();
if (!horizon) return undefined;
if (this.declarationEntry())
if (this.showsInputs())
return this.calendarService.project(
{ placements: [], horizon, declaredDays: this.userInput.declaredDaysSignal() },
{ fixedMonths: true },
@@ -318,7 +336,7 @@ export class CalendarYear {
),
);
});
this.calculations.start();
if (!this.nothingToPlan()) this.calculations.start();
}
protected cancelCalculation(): void {
@@ -328,7 +346,9 @@ export class CalendarYear {
}
protected formatStatistic(value: number | null): string {
return value === null ? '—' : value.toLocaleString(this.translationService.locale());
return value === null
? '—'
: value.toLocaleString(this.translationService.locale(), { maximumFractionDigits: 1 });
}
protected openStatistics(): void {
+31 -19
View File
@@ -62,6 +62,12 @@
</fieldset>
<div class="listOfDays">
@if (!daysOff.length) {
<p id="leave-balances-empty" class="empty-balances">
<mat-icon aria-hidden="true">event_available</mat-icon>
{{ tr().userInput.emptyBalances }}
</p>
}
@for (day of daysOff; track day.id) {
<div class="day-input-wrapper" animate.enter="day-enter" animate.leave="day-leave">
<app-day-input
@@ -123,25 +129,31 @@
<app-rules-panel></app-rules-panel>
@if (duration.estimate()) {
<p id="planning-duration-estimate" class="duration-estimate">{{ durationLabel() }}</p>
}
<button
mat-flat-button
class="calculate-button"
color="primary"
type="button"
[disabled]="!!calendarSettings.planningHorizonError()"
[attr.aria-describedby]="
calendarSettings.planningHorizonError()
? 'planning-dates-error'
: 'planning-duration-estimate'
"
(click)="triggerComputation()"
>
<mat-icon aria-hidden="true">auto_awesome</mat-icon>
{{ tr().userInput.calculate }}
</button>
<div class="calculate-bar">
@if (duration.estimate() && !nothingToPlan()) {
<p id="planning-duration-estimate" class="duration-estimate">{{ durationLabel() }}</p>
}
<button
mat-flat-button
class="calculate-button"
color="primary"
type="button"
[disabled]="!!calendarSettings.planningHorizonError() || nothingToPlan()"
[attr.aria-describedby]="
calendarSettings.planningHorizonError()
? nothingToPlan()
? 'planning-dates-error leave-balances-empty'
: 'planning-dates-error'
: nothingToPlan()
? 'leave-balances-empty'
: 'planning-duration-estimate'
"
(click)="triggerComputation()"
>
<mat-icon aria-hidden="true">auto_awesome</mat-icon>
{{ tr().userInput.calculate }}
</button>
</div>
@if (hasRemainingDays()) {
<mat-card class="warning-card" [class.is-informational]="!hasAtRiskDays()">
@@ -72,6 +72,25 @@
gap: 0.75rem;
}
.empty-balances {
display: flex;
align-items: flex-start;
gap: 0.75rem;
grid-column: 1 / -1;
margin: 0;
padding: 1rem;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
background: var(--ui-panel-bg);
font-size: 0.875rem;
line-height: 1.5;
mat-icon {
flex-shrink: 0;
color: var(--mat-sys-primary);
}
}
.declaration-controls {
display: grid;
container: declaration-controls / inline-size;
@@ -184,6 +203,10 @@ form {
min-height: 3rem;
}
.calculate-bar {
display: contents;
}
.duration-estimate {
grid-column: 1 / -1;
margin: 0 0 -0.5rem;
@@ -306,4 +329,26 @@ form {
.jump-to-plan {
display: none;
}
// The configuration panel scrolls here: keep Calculate and its indicative wait in view.
// A flex column instead of the grid, so that the sticky bar spans the whole content.
.user-input {
display: flex;
flex-direction: column;
align-items: stretch;
}
.calculate-bar {
display: grid;
gap: 0.5rem;
position: sticky;
bottom: calc(-1 * var(--panel-padding));
z-index: 1;
margin-inline: calc(-1 * var(--panel-padding));
padding: 0.75rem var(--panel-padding);
background: var(--ui-card-bg);
border-block-start: 1px solid var(--ui-border);
}
.duration-estimate {
margin: 0;
}
}
@@ -23,6 +23,16 @@ import { TranslationService } from '../../services/translation-service';
const presets = createOptimizationPresetRules();
const savedBalances = JSON.stringify(
(['cp', 'rtt', 'other'] as const).map((type, index) => ({
id: `00000000-0000-4000-8000-00000000000${index + 1}`,
type,
numberOfDays: 15,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
})),
);
describe('UserInput', () => {
let component: UserInput;
let fixture: ComponentFixture<UserInput>;
@@ -35,12 +45,8 @@ describe('UserInput', () => {
localStorage.setItem('app.language', '"en"');
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
vi.spyOn(Math, 'random').mockReturnValue(0.5);
vi.spyOn(crypto, 'randomUUID')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000001')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000002')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000003')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000004');
localStorage.setItem('leaveBalances', savedBalances);
vi.spyOn(crypto, 'randomUUID').mockReturnValueOnce('00000000-0000-4000-8000-000000000004');
await createInput();
});
@@ -221,6 +227,11 @@ describe('UserInput', () => {
root.querySelector('#planning-duration-estimate')?.textContent?.trim();
expect(estimateText()).toMatch(/Approximate wait: \d+–\d+ (s|min)/);
expect(calculate.getAttribute('aria-describedby')).toBe('planning-duration-estimate');
// One bar, so that the wide layout pins the wait and the action together.
expect(calculate.parentElement?.classList).toContain('calculate-bar');
expect(root.querySelector('#planning-duration-estimate')?.parentElement).toBe(
calculate.parentElement,
);
const initial = estimateText();
TestBed.inject(CalendarSettingsService).setPlanningDates('2026-10-04', '2029-10-03');
fixture.detectChanges();
@@ -394,28 +405,42 @@ describe('UserInput', () => {
it.each([
['absent', null],
['unreadable', '{'],
])('renders unsaved random defaults when balance data is %s', async (_, saved) => {
])('shows the empty state and disables Calculate when balance data is %s', async (_, saved) => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
if (saved !== null) localStorage.setItem('leaveBalances', saved);
if (saved === null) localStorage.removeItem('leaveBalances');
else localStorage.setItem('leaveBalances', saved);
await revisit();
const root = fixture.nativeElement as HTMLElement;
expect(
Array.from(root.querySelectorAll<HTMLInputElement>('app-day-input input')).map(
(input) => input.value,
),
).toEqual([
'15',
'04/10/2026',
'04/10/2027',
'15',
'04/10/2026',
'04/10/2027',
'15',
'04/10/2026',
'04/10/2027',
]);
expect(root.querySelector('app-day-input')).toBeNull();
expect(root.querySelector('#leave-balances-empty')?.textContent).toContain(
'No leave balance yet',
);
const calculate = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(calculate.disabled).toBe(true);
expect(calculate.getAttribute('aria-describedby')).toBe('leave-balances-empty');
expect(root.querySelector('#planning-duration-estimate')).toBeNull();
component.triggerComputation();
expect(createCalculation).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('app.language')).toBe('"en"');
root.querySelector<HTMLButtonElement>('.add-day-button')!.click();
fixture.detectChanges();
expect(root.querySelectorAll('app-day-input')).toHaveLength(1);
expect(root.querySelector('#leave-balances-empty')).toBeNull();
expect(calculate.disabled).toBe(false);
expect(calculate.getAttribute('aria-describedby')).toBe('planning-duration-estimate');
});
it('explains both reasons when the planning dates are invalid and there is nothing to plan', async () => {
localStorage.setItem('leaveBalances', '[]');
await revisit();
editInput('input[name="lastPlanningDate"]', '');
const calculate = fixture.nativeElement.querySelector('.calculate-button');
expect(calculate.disabled).toBe(true);
expect(calculate.getAttribute('aria-describedby')).toBe(
'planning-dates-error leave-balances-empty',
);
});
it('restores the complete edited list on a fresh visit', async () => {
@@ -431,8 +456,8 @@ describe('UserInput', () => {
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
it('saves the complete ordered balance list on the first quantity edit', () => {
expect(localStorage.getItem('leaveBalances')).toBeNull();
it('saves the complete ordered balance list on a quantity edit', () => {
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
editInput('app-day-input input[type="number"]', '7');
expect(JSON.parse(localStorage.getItem('leaveBalances')!)).toEqual([
@@ -460,7 +485,7 @@ describe('UserInput', () => {
]);
});
it('saves a leave-type selection as the first balance edit', async () => {
it('saves a leave-type selection as a balance edit', async () => {
const loader = TestbedHarnessEnvironment.loader(fixture);
const type = await loader.getHarness(
MatSelectHarness.with({ selector: 'app-day-input mat-select' }),
@@ -492,7 +517,7 @@ describe('UserInput', () => {
]);
});
it('saves adding a balance as the first edit and keeps saving subsequent edits', () => {
it('saves adding a balance and keeps saving subsequent edits', () => {
fixture.nativeElement.querySelector('.add-day-button').click();
fixture.detectChanges();
@@ -515,7 +540,7 @@ describe('UserInput', () => {
expect(JSON.parse(localStorage.getItem('leaveBalances')!)[0].numberOfDays).toBe(9);
});
it('saves removing a balance as the first edit and retains an entry after the final deletion', () => {
it('saves removing a balance and retains an empty list after the final deletion', () => {
fixture.nativeElement.querySelectorAll('.delete-button')[2].click();
fixture.detectChanges();
expect(JSON.parse(localStorage.getItem('leaveBalances')!)).toMatchObject([
@@ -530,15 +555,16 @@ describe('UserInput', () => {
fixture.detectChanges();
expect(userInputService.vacationNumberSignal()).toEqual([]);
expect(localStorage.getItem('leaveBalances')).toBe('[]');
expect(fixture.nativeElement.querySelector('#leave-balances-empty')).not.toBeNull();
expect(fixture.nativeElement.querySelector('.calculate-button').disabled).toBe(true);
});
it('keeps untouched random balances unsaved through settings, rule changes, and calculation', async () => {
it('does not rewrite restored balances through settings, rule changes, and calculation', async () => {
const initialBalances = userInputService.vacationNumberSignal();
expect(localStorage.getItem('leaveBalances')).toBeNull();
const write = vi.spyOn(Storage.prototype, 'setItem');
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
const dialogRef = TestBed.inject(MatDialog).open(UserSettings);
const dialog = await loader.getHarness(MatDialogHarness);
expect(localStorage.getItem('leaveBalances')).toBeNull();
const [theme, language] = await dialog.getAllHarnesses(MatSelectHarness);
await selectOption(theme, 'Dark');
@@ -560,7 +586,8 @@ describe('UserInput', () => {
expect(createCalculation).toHaveBeenCalledTimes(1);
expect(userInputService.vacationNumberSignal()).toEqual(initialBalances);
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(write.mock.calls.some(([key]) => key === 'leaveBalances')).toBe(false);
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
});
it('preserves unrelated stored preferences, rules, and other values when editing balances', () => {
@@ -589,7 +616,7 @@ describe('UserInput', () => {
editInput('app-day-input input[type="number"]', '7');
expect(userInputService.vacationNumberSignal()[0].numberOfDays).toBe(7);
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
write.mockRestore();
editInput('app-day-input input[type="number"]', '8');
+2 -1
View File
@@ -42,6 +42,7 @@ export class UserInput {
private userInputService: UserInputService = inject(UserInputService);
protected readonly declarationEntry = this.userInputService.declarationEntrySignal;
protected readonly declaredType = this.userInputService.declaredTypeSignal;
protected readonly nothingToPlan = this.userInputService.nothingToPlan;
protected readonly declaredTypes: readonly LeaveType[] = ['cp', 'rtt', 'other'];
protected readonly calendarSettings = inject(CalendarSettingsService);
protected readonly duration = inject(PlanningDurationService);
@@ -174,7 +175,7 @@ export class UserInput {
}
public triggerComputation() {
if (this.calendarSettings.planningHorizonError()) return;
if (this.calendarSettings.planningHorizonError() || this.nothingToPlan()) return;
this.calculations.start();
}
}
+3
View File
@@ -37,6 +37,7 @@ export interface AppTranslations {
title: string;
description: string;
addVacationDay: string;
emptyBalances: string;
calculate: string;
durationEstimate: string;
durationUnits: { seconds: string; minutes: string };
@@ -233,9 +234,11 @@ export interface AppTranslations {
unavailable: Record<string, string | undefined>;
};
title: string;
invitation: string;
calendarHelp: string;
explanationHelp: string;
technicalDetails: string;
appliedRules: { title: string; entries: string };
compareDates: string;
stopComparing: string;
daysPlaced: string;
+32 -58
View File
@@ -135,21 +135,23 @@ describe('UserInputService', () => {
expect(warn).toHaveBeenCalled();
});
it('should initialize with vacation days array', () => {
const vacations = service.vacationNumberSignal();
expect(Array.isArray(vacations)).toBe(true);
expect(vacations.length).toBeGreaterThan(0);
it('starts a first visit from an empty, unsaved balance list without drawing quantities', () => {
const random = vi.spyOn(Math, 'random');
expect(new UserInputService().vacationNumberSignal()).toEqual([]);
expect(random).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBeNull();
});
it('should have vacation days with valid properties', () => {
const vacations = service.vacationNumberSignal();
vacations.forEach((day) => {
expect(day.id).toBeDefined();
expect(day.type).toBeDefined();
expect(day.numberOfDays).toBeGreaterThanOrEqual(10);
expect(day.numberOfDays).toBeLessThanOrEqual(20);
expect(day.expiryDate).toBeInstanceOf(Date);
});
it('has nothing to plan only without a leave balance and without a declared non-working day', () => {
expect(service.nothingToPlan()).toBe(true);
service.toggleDeclaredDay('2024-01-02', 'cp');
expect(service.nothingToPlan()).toBe(false);
service.toggleDeclaredDay('2024-01-02', 'cp');
expect(service.nothingToPlan()).toBe(true);
service.updateBalances(() => [service.createVacationDay()]);
expect(service.nothingToPlan()).toBe(false);
localStorage.setItem('leaveBalances', '[]');
expect(new UserInputService().nothingToPlan()).toBe(true);
});
it('restores the saved balance order, identities, quantities, types, and calendar dates', () => {
@@ -240,32 +242,23 @@ describe('UserInputService', () => {
'mixed supported and unsupported records',
JSON.stringify([savedBalance, { ...savedBalance, type: 'any' }]),
],
])(
'deletes only unreadable balance data (%s) before using unsaved random defaults',
(_, saved) => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(Math, 'random').mockReturnValue(0.5);
const unrelated = {
'theme.preference': '"dark"',
'app.language': '"fr"',
'calendarSettings.showWeekNumbers': 'true',
vacationRules: '[]',
'unrelated.entry': 'keep this value',
};
for (const [key, value] of Object.entries(unrelated)) localStorage.setItem(key, value);
localStorage.setItem('leaveBalances', saved);
])('deletes only unreadable balance data (%s) and starts from an empty list', (_, saved) => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
const unrelated = {
'theme.preference': '"dark"',
'app.language': '"fr"',
'calendarSettings.showWeekNumbers': 'true',
vacationRules: '[]',
'unrelated.entry': 'keep this value',
};
for (const [key, value] of Object.entries(unrelated)) localStorage.setItem(key, value);
localStorage.setItem('leaveBalances', saved);
const balances = new UserInputService().vacationNumberSignal();
expect(balances.map((balance) => [balance.type, balance.numberOfDays])).toEqual([
[SelectableDayType.CP, 15],
[SelectableDayType.RTT, 15],
[SelectableDayType.OTHER, 15],
]);
expect(localStorage.getItem('leaveBalances')).toBeNull();
for (const [key, value] of Object.entries(unrelated))
expect(localStorage.getItem(key)).toBe(value);
},
);
expect(new UserInputService().vacationNumberSignal()).toEqual([]);
expect(localStorage.getItem('leaveBalances')).toBeNull();
for (const [key, value] of Object.entries(unrelated))
expect(localStorage.getItem(key)).toBe(value);
});
it('keeps saved data intact when browser storage temporarily cannot be read', () => {
const saved = JSON.stringify([savedBalance]);
@@ -275,30 +268,11 @@ describe('UserInputService', () => {
throw new DOMException('Storage is unavailable', 'SecurityError');
});
expect(new UserInputService().vacationNumberSignal()).toHaveLength(3);
expect(new UserInputService().vacationNumberSignal()).toEqual([]);
read.mockRestore();
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
it.each([
[0, 10],
[1 - Number.EPSILON, 20],
])('starts every balance at %s random draw with %s days', (draw, expected) => {
vi.spyOn(Math, 'random').mockReturnValue(draw);
const initialBalances = new UserInputService().vacationNumberSignal();
expect(initialBalances.map((balance) => balance.numberOfDays)).toEqual([
expected,
expected,
expected,
]);
expect(initialBalances.map((balance) => balance.type)).toEqual([
SelectableDayType.CP,
SelectableDayType.RTT,
SelectableDayType.OTHER,
]);
expect(localStorage.getItem('leaveBalances')).toBeNull();
});
it('should update vacation number signal', () => {
const newVacations: LeaveBalance[] = [
{
+6 -36
View File
@@ -1,4 +1,4 @@
import { Injectable, signal } from '@angular/core';
import { computed, Injectable, signal } from '@angular/core';
import { SelectableDayType } from './calendar-service';
import dayjs from 'dayjs';
import {
@@ -118,45 +118,13 @@ export class UserInputService {
try {
localStorage.removeItem('leaveBalances');
} catch {
// Keep the random fallback usable when browser storage is unavailable.
// Keep the empty list usable when browser storage is unavailable.
}
}
}
return undefined;
}
private getRandomNumber(): number {
return Math.floor(Math.random() * 11) + 10;
}
private getInitialValues(): LeaveBalance[] {
const availableDate = new Date();
return [
{
id: crypto.randomUUID(),
type: SelectableDayType.CP,
numberOfDays: this.getRandomNumber(),
availableDate,
// today + 365 days
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
{
id: crypto.randomUUID(),
type: SelectableDayType.RTT,
numberOfDays: this.getRandomNumber(),
availableDate: new Date(availableDate),
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
{
id: crypto.randomUUID(),
type: SelectableDayType.OTHER,
numberOfDays: this.getRandomNumber(),
availableDate: new Date(availableDate),
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
];
}
public createVacationDay(): LeaveBalance {
return {
id: crypto.randomUUID(),
@@ -167,8 +135,10 @@ export class UserInputService {
};
}
readonly vacationNumberSignal = signal<LeaveBalance[]>(
this.getSavedValues() ?? this.getInitialValues(),
readonly vacationNumberSignal = signal<LeaveBalance[]>(this.getSavedValues() ?? []);
/** No leave balance and no declared non-working day: nothing is calculated until one is added. */
readonly nothingToPlan = computed(
() => !this.vacationNumberSignal().length && !this.declaredDays().length,
);
public updateBalances(updater: (balances: LeaveBalance[]) => LeaveBalance[]): void {
this.vacationNumberSignal.update(updater);
+6
View File
@@ -19,6 +19,7 @@
"title": "Urlaub konfigurieren",
"description": "Wählen Sie den Planungszeitraum und fügen Sie jedes Urlaubskonto und seinen Gültigkeitszeitraum hinzu.",
"addVacationDay": "Urlaubskonto hinzufügen",
"emptyBalances": "Noch kein Urlaubskonto. Fügen Sie jedes Ihrer Urlaubskonten mit Urlaubsart, Anzahl der Tage und Gültigkeitszeitraum hinzu.",
"calculate": "Plan berechnen",
"durationEstimate": "Ungefähre Wartezeit: {range} {unit}",
"durationUnits": {
@@ -191,6 +192,7 @@
"futureEntitlement": "Erzeugter künftiger Anspruch",
"includedEntitlement": "Anspruch bereits in den gemeldeten Guthaben enthalten",
"title": "Ihr optimiertes Jahr",
"invitation": "Fügen Sie Ihre Urlaubskonten hinzu und berechnen Sie dann den Plan, um ihn hier zu sehen.",
"daysPlaced": "Eingeplante Urlaubstage",
"daysGained": "Gewonnene arbeitsfreie Tage",
"longestWorkSequence": "Längste Arbeitsphase",
@@ -296,6 +298,10 @@
"calendarHelp": "Wählen Sie einen Urlaubstag, um seinen Beitrag zum Plan zu sehen.",
"explanationHelp": "Sehen Sie Ihre Auszeit und den Beitrag jedes Tages.",
"technicalDetails": "Berechnungsdetails",
"appliedRules": {
"title": "Details zu angewendeten Regeln",
"entries": "Einträge"
},
"compareDates": "Andere Termine vergleichen",
"stopComparing": "Datumsvergleich schließen",
"explanation": {
+6
View File
@@ -19,6 +19,7 @@
"title": "Configure your leave",
"description": "Choose a planning period, then add each leave balance and its validity period.",
"addVacationDay": "Add leave balance",
"emptyBalances": "No leave balance yet. Add each of your balances with its leave type, number of days and validity period.",
"calculate": "Calculate plan",
"durationEstimate": "Approximate wait: {range} {unit}",
"durationUnits": {
@@ -191,6 +192,7 @@
"futureEntitlement": "Future entitlement generated",
"includedEntitlement": "Entitlement already included in reported balances",
"title": "Your optimized year",
"invitation": "Add your leave balances, then calculate the plan to see it here.",
"daysPlaced": "Leave days placed",
"daysGained": "Non-working days gained",
"longestWorkSequence": "Longest work sequence",
@@ -296,6 +298,10 @@
"calendarHelp": "Select a leave day to see its contribution to your plan.",
"explanationHelp": "See the break you get and what each day changes.",
"technicalDetails": "Calculation details",
"appliedRules": {
"title": "Applied rules detail",
"entries": "Entries"
},
"compareDates": "Compare other dates",
"stopComparing": "Close date comparison",
"explanation": {
+6
View File
@@ -19,6 +19,7 @@
"title": "Configura tus vacaciones",
"description": "Elige el período de planificación y añade cada saldo de vacaciones y su periodo de validez.",
"addVacationDay": "Añadir saldo de vacaciones",
"emptyBalances": "Todavía no hay ningún saldo de vacaciones. Añade cada uno de tus saldos con su tipo de permiso, su número de días y su periodo de validez.",
"calculate": "Calcular plan",
"durationEstimate": "Espera aproximada: {range} {unit}",
"durationUnits": {
@@ -191,6 +192,7 @@
"futureEntitlement": "Derecho futuro generado",
"includedEntitlement": "Derecho ya incluido en los saldos declarados",
"title": "Tu año optimizado",
"invitation": "Añade tus saldos de vacaciones y calcula el plan para verlo aquí.",
"daysPlaced": "Días de vacaciones asignados",
"daysGained": "Días no laborables ganados",
"longestWorkSequence": "Período de trabajo más largo",
@@ -296,6 +298,10 @@
"calendarHelp": "Selecciona un día de permiso para ver su aportación al plan.",
"explanationHelp": "Consulta tu descanso y qué cambia con cada día.",
"technicalDetails": "Detalles del cálculo",
"appliedRules": {
"title": "Detalle de las reglas aplicadas",
"entries": "Elementos"
},
"compareDates": "Comparar otras fechas",
"stopComparing": "Cerrar comparación",
"explanation": {
+6
View File
@@ -19,6 +19,7 @@
"title": "Configurez vos congés",
"description": "Choisissez la période à planifier, puis ajoutez chaque solde de congés et sa période de validité.",
"addVacationDay": "Ajouter un solde de congés",
"emptyBalances": "Aucun solde de congés pour l’instant. Ajoutez chacun de vos soldes avec son type de congé, son nombre de jours et sa période de validité.",
"calculate": "Calculer le planning",
"durationEstimate": "Attente indicative : {range} {unit}",
"durationUnits": {
@@ -191,6 +192,7 @@
"futureEntitlement": "Droit futur généré",
"includedEntitlement": "Droit déjà inclus dans les soldes reportés",
"title": "Votre année optimisée",
"invitation": "Ajoutez vos soldes de congés puis calculez le planning pour l’afficher ici.",
"daysPlaced": "Jours de congé placés",
"daysGained": "Jours non travaillés gagnés",
"longestWorkSequence": "Plus longue période travaillée",
@@ -296,6 +298,10 @@
"calendarHelp": "Sélectionnez un jour de congé pour voir son apport au planning.",
"explanationHelp": "Découvrez votre pause et ce que chaque jour change.",
"technicalDetails": "Détails du calcul",
"appliedRules": {
"title": "Détail des règles appliquées",
"entries": "Éléments"
},
"compareDates": "Comparer d’autres dates",
"stopComparing": "Fermer la comparaison",
"explanation": {