From 679a494fae7a9dd7558473a733c5b5d91ebeb09c Mon Sep 17 00:00:00 2001 From: Nessar Date: Fri, 13 Nov 2026 18:58:31 +0100 Subject: [PATCH 01/12] 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 --- README.md | 5 +- ...-planning-inputs-before-random-defaults.md | 2 + ...012-empty-leave-balances-on-first-visit.md | 11 + src/app/app-settings.spec.ts | 188 +++++++++--------- .../calendar-year-planning.spec.ts | 19 +- .../calendar-year/calendar-year.html | 5 + .../calendar-year/calendar-year.scss | 4 + .../components/calendar-year/calendar-year.ts | 13 +- src/app/components/user-input/user-input.html | 18 +- src/app/components/user-input/user-input.scss | 19 ++ .../components/user-input/user-input.spec.ts | 88 +++++--- src/app/components/user-input/user-input.ts | 3 +- src/app/services/translation-service.ts | 2 + src/app/services/user-input-service.spec.ts | 90 +++------ src/app/services/user-input-service.ts | 42 +--- src/i18n/de.json | 2 + src/i18n/en.json | 2 + src/i18n/es.json | 2 + src/i18n/fr.json | 2 + 19 files changed, 280 insertions(+), 237 deletions(-) create mode 100644 docs/adr/0012-empty-leave-balances-on-first-visit.md diff --git a/README.md b/README.md index 9cf9abf..741d485 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/adr/0005-saved-planning-inputs-before-random-defaults.md b/docs/adr/0005-saved-planning-inputs-before-random-defaults.md index ec4c70f..a37aaeb 100644 --- a/docs/adr/0005-saved-planning-inputs-before-random-defaults.md +++ b/docs/adr/0005-saved-planning-inputs-before-random-defaults.md @@ -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. diff --git a/docs/adr/0012-empty-leave-balances-on-first-visit.md b/docs/adr/0012-empty-leave-balances-on-first-visit.md new file mode 100644 index 0000000..dd211c1 --- /dev/null +++ b/docs/adr/0012-empty-leave-balances-on-first-visit.md @@ -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. diff --git a/src/app/app-settings.spec.ts b/src/app/app-settings.spec.ts index 55e4a81..7323d44 100644 --- a/src/app/app-settings.spec.ts +++ b/src/app/app-settings.spec.ts @@ -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('.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('.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('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('.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( - '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('.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('.calculate-button')!; + expect(button.disabled).toBe(false); + expect(button.getAttribute('aria-describedby')).toBe('planning-duration-estimate'); expect(localStorage.getItem('leaveBalances')).toBe('[]'); }); diff --git a/src/app/components/calendar-year/calendar-year-planning.spec.ts b/src/app/components/calendar-year/calendar-year-planning.spec.ts index 0f299fd..54b7de2 100644 --- a/src/app/components/calendar-year/calendar-year-planning.spec.ts +++ b/src/app/components/calendar-year/calendar-year-planning.spec.ts @@ -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(); @@ -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()], diff --git a/src/app/components/calendar-year/calendar-year.html b/src/app/components/calendar-year/calendar-year.html index ae891ca..d8f7723 100644 --- a/src/app/components/calendar-year/calendar-year.html +++ b/src/app/components/calendar-year/calendar-year.html @@ -70,6 +70,11 @@ {{ outcomeLabel(planningOutcome()!) }}

+ } @else if (!isLoading() && nothingToPlan()) { +

+ + {{ tr().planning.invitation }} +

} @if (displayedPlan()) { diff --git a/src/app/components/calendar-year/calendar-year.scss b/src/app/components/calendar-year/calendar-year.scss index 2f076cf..2b65f33 100644 --- a/src/app/components/calendar-year/calendar-year.scss +++ b/src/app/components/calendar-year/calendar-year.scss @@ -59,6 +59,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 { diff --git a/src/app/components/calendar-year/calendar-year.ts b/src/app/components/calendar-year/calendar-year.ts index aa60851..f4ba599 100644 --- a/src/app/components/calendar-year/calendar-year.ts +++ b/src/app/components/calendar-year/calendar-year.ts @@ -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>('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>>(() => { - const days = this.declarationEntry() + const days = this.showsInputs() ? this.userInput.declaredDaysSignal() : (this.calculations.accepted()?.declaredDays ?? []); return Object.fromEntries(days.map(({ date, type }) => [date, type])); @@ -210,7 +215,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 +323,7 @@ export class CalendarYear { ), ); }); - this.calculations.start(); + if (!this.nothingToPlan()) this.calculations.start(); } protected cancelCalculation(): void { diff --git a/src/app/components/user-input/user-input.html b/src/app/components/user-input/user-input.html index abbd8b2..2425fe1 100644 --- a/src/app/components/user-input/user-input.html +++ b/src/app/components/user-input/user-input.html @@ -62,6 +62,12 @@
+ @if (!daysOff.length) { +

+ + {{ tr().userInput.emptyBalances }} +

+ } @for (day of daysOff; track day.id) {
- @if (duration.estimate()) { + @if (duration.estimate() && !nothingToPlan()) {

{{ durationLabel() }}

}
@if (displayedPlan()) {
- @for (contribution of plan.timeWindowContributions ?? []; track contribution.ruleId) { -
-

{{ contribution.label }}

-

- {{ contribution.declaredDays.length }} {{ tr().bookedDays.booked }} + - {{ contribution.placementDates.length }} - {{ tr().planning.explanation.leaveDays }} = - {{ - contribution.declaredDays.length + contribution.placementDates.length - }} - / {{ contribution.requested }} -

-

- @for (day of contribution.declaredDays; track day.date) { - {{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }} - } -

-

{{ tr().bookedDays.fixed }}

-
- } - @for ( - contribution of plan.ifThenContributions ?? []; - track contribution.ruleId + contribution.occurrence - ) { -
-

{{ contribution.label }} · {{ displayDate(contribution.occurrence) }}

-

- {{ contribution.declaredDays.length }} {{ tr().bookedDays.booked }} + - {{ contribution.placementDates.length }} - {{ tr().planning.explanation.leaveDays }} = - {{ contribution.requested }} / {{ contribution.requested }} -

- @for (day of contribution.declaredDays; track day.date) { - {{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }} - } - @if (contribution.declaredDays.length) { -

{{ tr().bookedDays.fixed }}

- } - @if (contribution.earnedEntitlement; as earned) { -

- {{ - earned.added - ? tr().planning.futureEntitlement - : tr().planning.includedEntitlement - }} - : {{ earned.quantity }} {{ tr().dayTypes[earned.type] }} -

-

- {{ tr().planning.details.available }} - {{ displayDate(earned.availableFrom) }} · - {{ tr().planning.details.expires }} {{ displayDate(earned.expiryDate) }} -

- } -
- } - @for (period of plan.timeOffPeriods; track period.start) { - @if (period.declaredDates?.length) { -
-

- {{ tr().planning.explanation.breakTitle }} · - {{ displayDate(period.start) }} – {{ displayDate(period.end) }} -

-

- {{ period.declaredDates!.length }} {{ tr().bookedDays.booked }} + - {{ period.placementDates.length }} - {{ tr().planning.explanation.leaveDays }} + - {{ period.nonWorkingDates.length }} - {{ tr().planning.explanation.freeDays }} = - {{ period.duration }} {{ tr().planning.explanation.daysOff }} -

-

{{ tr().bookedDays.fixed }}

-
- } - } }
@@ -523,6 +445,122 @@ {{ tr().planning.explanationError }} {{ reasonLabel(explanationError()!) }}

} + @if (displayedPlan(); as plan) { + @if (appliedRuleCount(); as count) { +
+ + + {{ tr().planning.appliedRules.title + }}{{ tr().planning.appliedRules.entries }} : {{ count }} + + +
+ @for ( + contribution of plan.timeWindowContributions ?? []; + track contribution.ruleId + ) { +
+

{{ contribution.label }}

+

+ {{ contribution.declaredDays.length }} + {{ tr().bookedDays.booked }} + + {{ contribution.placementDates.length }} + {{ tr().planning.explanation.leaveDays }} = + {{ + contribution.declaredDays.length + + contribution.placementDates.length + }} + / {{ contribution.requested }} +

+

+ @for (day of contribution.declaredDays; track day.date) { + {{ displayDate(day.date) }} · + {{ tr().dayTypes[day.type] }} + + } +

+

{{ tr().bookedDays.fixed }}

+
+ } + @for ( + contribution of plan.ifThenContributions ?? []; + track contribution.ruleId + contribution.occurrence + ) { +
+

+ {{ contribution.label }} · + {{ displayDate(contribution.occurrence) }} +

+

+ {{ contribution.declaredDays.length }} + {{ tr().bookedDays.booked }} + + {{ contribution.placementDates.length }} + {{ tr().planning.explanation.leaveDays }} = + {{ contribution.requested }} / + {{ contribution.requested }} +

+ @for (day of contribution.declaredDays; track day.date) { + {{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }} + + } + @if (contribution.declaredDays.length) { +

{{ tr().bookedDays.fixed }}

+ } + @if (contribution.earnedEntitlement; as earned) { +

+ {{ + earned.added + ? tr().planning.futureEntitlement + : tr().planning.includedEntitlement + }} + : {{ earned.quantity }} {{ tr().dayTypes[earned.type] }} +

+

+ {{ tr().planning.details.available }} + {{ displayDate(earned.availableFrom) }} · + {{ tr().planning.details.expires }} + {{ displayDate(earned.expiryDate) }} +

+ } +
+ } + @for (period of declaredPeriods(); track period.start) { +
+

+ {{ tr().planning.explanation.breakTitle }} · + {{ displayDate(period.start) }} – {{ displayDate(period.end) }} +

+

+ {{ period.declaredDates!.length }} + {{ tr().bookedDays.booked }} + + {{ period.placementDates.length }} + {{ tr().planning.explanation.leaveDays }} + + {{ period.nonWorkingDates.length }} + {{ tr().planning.explanation.freeDays }} = + {{ period.duration }} + {{ tr().planning.explanation.daysOff }} +

+

{{ tr().bookedDays.fixed }}

+
+ } +
+
+ } + }

diff --git a/src/app/components/calendar-year/calendar-year.scss b/src/app/components/calendar-year/calendar-year.scss index f18293e..9b7fcbe 100644 --- a/src/app/components/calendar-year/calendar-year.scss +++ b/src/app/components/calendar-year/calendar-year.scss @@ -31,8 +31,10 @@ 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); @@ -162,6 +164,12 @@ code { } } +.applied-rules-content { + display: grid; + gap: 0.75rem; + padding: 1rem; +} + .statistics-content { display: grid; gap: 1rem; diff --git a/src/app/components/calendar-year/calendar-year.ts b/src/app/components/calendar-year/calendar-year.ts index 0b50946..48faeb8 100644 --- a/src/app/components/calendar-year/calendar-year.ts +++ b/src/app/components/calendar-year/calendar-year.ts @@ -159,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(); diff --git a/src/app/services/translation-service.ts b/src/app/services/translation-service.ts index d455fa9..b4c9594 100644 --- a/src/app/services/translation-service.ts +++ b/src/app/services/translation-service.ts @@ -238,6 +238,7 @@ export interface AppTranslations { calendarHelp: string; explanationHelp: string; technicalDetails: string; + appliedRules: { title: string; entries: string }; compareDates: string; stopComparing: string; daysPlaced: string; diff --git a/src/i18n/de.json b/src/i18n/de.json index 78a06a3..d524de7 100644 --- a/src/i18n/de.json +++ b/src/i18n/de.json @@ -298,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": { diff --git a/src/i18n/en.json b/src/i18n/en.json index 0bf4e3f..4390468 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -298,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": { diff --git a/src/i18n/es.json b/src/i18n/es.json index 72338ed..db6d202 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -298,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": { diff --git a/src/i18n/fr.json b/src/i18n/fr.json index 180122f..ebdf7b0 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -298,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": { -- 2.54.0 From 0561a2f9d16c65c74a6390e4f7f9aa6949a874f4 Mon Sep 17 00:00:00 2001 From: Nessar Date: Fri, 13 Nov 2026 19:02:28 +0100 Subject: [PATCH 04/12] 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 --- src/app/app.html | 6 ++- src/app/app.scss | 14 +++++- src/app/app.spec.ts | 13 +++++ src/app/app.ts | 11 ++++- src/app/components/user-input/user-input.html | 48 ++++++++++--------- src/app/components/user-input/user-input.scss | 26 ++++++++++ .../components/user-input/user-input.spec.ts | 5 ++ 7 files changed, 96 insertions(+), 27 deletions(-) diff --git a/src/app/app.html b/src/app/app.html index cfc03ed..0877f36 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -22,7 +22,11 @@

-
+
diff --git a/src/app/app.scss b/src/app/app.scss index ed9d694..cdc20e9 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -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; } } diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index b001ef3..89e07c2 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -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'; @@ -29,6 +30,18 @@ describe('App', () => { 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', () => { TestBed.createComponent(App); TestBed.inject(TranslationService).setLanguage('fr'); diff --git a/src/app/app.ts b/src/app/app.ts index b5ee1a2..f5e3c75 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -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()], diff --git a/src/app/components/user-input/user-input.html b/src/app/components/user-input/user-input.html index 2425fe1..3c61068 100644 --- a/src/app/components/user-input/user-input.html +++ b/src/app/components/user-input/user-input.html @@ -129,29 +129,31 @@ - @if (duration.estimate() && !nothingToPlan()) { -

{{ durationLabel() }}

- } - +
+ @if (duration.estimate() && !nothingToPlan()) { +

{{ durationLabel() }}

+ } + +
@if (hasRemainingDays()) { diff --git a/src/app/components/user-input/user-input.scss b/src/app/components/user-input/user-input.scss index d3271f7..34d4a32 100644 --- a/src/app/components/user-input/user-input.scss +++ b/src/app/components/user-input/user-input.scss @@ -203,6 +203,10 @@ form { min-height: 3rem; } +.calculate-bar { + display: contents; +} + .duration-estimate { grid-column: 1 / -1; margin: 0 0 -0.5rem; @@ -325,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; + } } diff --git a/src/app/components/user-input/user-input.spec.ts b/src/app/components/user-input/user-input.spec.ts index 2d632b0..75e47ba 100644 --- a/src/app/components/user-input/user-input.spec.ts +++ b/src/app/components/user-input/user-input.spec.ts @@ -227,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(); -- 2.54.0 From 897bdefd252eedc650d984689856fbfde06ef863 Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 10:56:42 +0100 Subject: [PATCH 05/12] feat(rules): describe planning rules in plain language (#357) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Optimization rules now read as a goal ("Réduire la plus longue séquence de travail") built from per-measure phrases, element nouns and condition qualifiers, so every valid composition gets a sentence. The technical composition stays in the calculation details and the audit data. The placement impact table drops the generic help repeated on every optimization row. If-then and imposed-period summaries use real plurals, leave-type phrases and the earned-leave wording of CONTEXT.md; the German templates, which never filled their placeholders, are rewritten. Co-Authored-By: Claude Opus 5.5 --- .../calendar-year-planning.spec.ts | 24 +++- .../calendar-year/calendar-year.html | 5 +- .../planning-criteria/planning-criteria.ts | 18 ++- .../rules-panel/rules-panel.spec.ts | 48 ++++++- src/app/components/rules-panel/rules-panel.ts | 68 +++++---- .../work-sequence-rule-editor.spec.ts | 35 +++-- src/app/services/planner-labels.spec.ts | 132 ++++++++++++++++-- src/app/services/planner-labels.ts | 71 ++++++++-- src/app/services/translation-service.ts | 28 +++- src/i18n/de.json | 81 ++++++++++- src/i18n/en.json | 81 ++++++++++- src/i18n/es.json | 81 ++++++++++- src/i18n/fr.json | 81 ++++++++++- 13 files changed, 631 insertions(+), 122 deletions(-) diff --git a/src/app/components/calendar-year/calendar-year-planning.spec.ts b/src/app/components/calendar-year/calendar-year-planning.spec.ts index 5d081da..a599e7d 100644 --- a/src/app/components/calendar-year/calendar-year-planning.spec.ts +++ b/src/app/components/calendar-year/calendar-year-planning.spec.ts @@ -35,6 +35,7 @@ import { PlanningDurationService } from '../../services/planning-duration.servic import { PlanningCalculationService } from '../../services/planning-calculation.service'; import { DateRange } from '@angular/material/datepicker'; import { translationsMap } from '../../i18n-registry'; +import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives'; const invalid: InvalidInputOutcome = { kind: 'InvalidInput', @@ -3231,6 +3232,7 @@ describe('CalendarYear planning outcome boundary', () => { { id: 'preference:spring', direction: 'maximize', value: 1 }, { id: 'non-working-day-gain', direction: 'maximize', value: 0 }, { id: 'longest-work-sequence', direction: 'minimize', value: 12 }, + { id: 'optimization:gain', direction: 'maximize', value: 1 }, { id: 'placement-date', direction: 'minimize', value: 'removed' }, ], }; @@ -3240,6 +3242,7 @@ describe('CalendarYear planning outcome boundary', () => { { id: 'preference:spring', direction: 'maximize', value: 2 }, { id: 'non-working-day-gain', direction: 'maximize', value: 4 }, { id: 'longest-work-sequence', direction: 'minimize', value: 6 }, + { id: 'optimization:gain', direction: 'maximize', value: 3 }, { id: 'placement-date', direction: 'minimize', value: '2024-05-03' }, ], }; @@ -3276,6 +3279,13 @@ describe('CalendarYear planning outcome boundary', () => { placeDays: 2, placeType: 'cp', }, + { + id: 'gain', + name: 'Gain', + type: 'optimization', + force: 'preference', + configuration: OPTIMIZATION_PRESETS.nonWorkingDayGain, + }, ]; await TestBed.configureTestingModule({ imports: [CalendarYear], @@ -3305,7 +3315,14 @@ describe('CalendarYear planning outcome boundary', () => { Array.from(element.querySelectorAll('.day-impact td'), (node) => node.textContent?.trim(), ), - ).toEqual(['1', '0', '1', '2', '0', '4', '12', '6']); + ).toEqual(['1', '0', '1', '2', '0', '4', '12', '6', '1', '3']); + const gainRow = Array.from(element.querySelectorAll('.day-impact tbody th')).find((row) => + row.textContent?.includes('Gain — '), + )!; + expect(gainRow.textContent?.trim()).toBe( + 'Gain — Increase weekend days and public holidays within time-off periods', + ); + expect(gainRow.querySelector('small')).toBeNull(); expect(element.querySelector('.day-impact')?.textContent).toContain( 'Preference: Spring break', ); @@ -3323,7 +3340,10 @@ describe('CalendarYear planning outcome boundary', () => { expect(details.querySelector('.balance-ledger')?.textContent).toContain( 'Unused days in the final plan', ); - expect(details.querySelectorAll('.criteria-table tbody tr')).toHaveLength(4); + expect(details.querySelectorAll('.criteria-table tbody tr')).toHaveLength(5); + expect(details.querySelector('.criteria-table')?.textContent).toContain( + 'Maximize Sum: Non-working-day gain (calendar days) — Time-off periods.', + ); expect(details.querySelector('.criteria-detail')?.textContent).not.toContain('2024-05-03'); expect(details.querySelector('.tie-breaks')?.textContent).toContain('Earlier dates first'); expect(details.querySelector('.criterion-help')?.open).toBe(false); diff --git a/src/app/components/calendar-year/calendar-year.html b/src/app/components/calendar-year/calendar-year.html index d65fc3a..9ebd22a 100644 --- a/src/app/components/calendar-year/calendar-year.html +++ b/src/app/components/calendar-year/calendar-year.html @@ -361,7 +361,10 @@ @for (change of placementChanges(); track change.id) { - {{ change.label }}{{ change.help }} + {{ change.label }} + @if (change.help) { + {{ change.help }} + } @if (change.id === decisiveObjective) { {{ tr().planning.details.firstDifference diff --git a/src/app/components/planning-criteria/planning-criteria.ts b/src/app/components/planning-criteria/planning-criteria.ts index 83b32d2..bffa258 100644 --- a/src/app/components/planning-criteria/planning-criteria.ts +++ b/src/app/components/planning-criteria/planning-criteria.ts @@ -30,13 +30,17 @@ export class PlanningCriteria { } protected objectiveRows(before: PlanningObjectiveVector, after: PlanningObjectiveVector) { - return after.objectives.map((objective) => ({ - ...objective, - label: labels.objectiveLabel(this.tr(), this.snapshot(), objective), - help: labels.objectiveCopy(this.tr(), this.snapshot(), objective.id)?.help, - before: before.objectives.find((item) => item.id === objective.id)?.value, - numeric: typeof objective.value === 'number', - })); + return after.objectives.map((objective) => { + const copy = labels.objectiveCopy(this.tr(), this.snapshot(), objective.id); + return { + ...objective, + label: labels.objectiveLabel(this.tr(), this.snapshot(), objective), + // The calculation details keep an optimization rule's technical composition. + help: copy?.technical ?? copy?.help, + before: before.objectives.find((item) => item.id === objective.id)?.value, + numeric: typeof objective.value === 'number', + }; + }); } protected hasTieBreaks(vector: PlanningObjectiveVector): boolean { diff --git a/src/app/components/rules-panel/rules-panel.spec.ts b/src/app/components/rules-panel/rules-panel.spec.ts index ca98a71..e7c0b80 100644 --- a/src/app/components/rules-panel/rules-panel.spec.ts +++ b/src/app/components/rules-panel/rules-panel.spec.ts @@ -41,6 +41,50 @@ describe('RulesPanel', () => { expect(component.rules.length).toBe(8); }); + it('describes the supplied rules in plain words in every language', () => { + const summaries = () => component.rules.map((rule) => component.getRuleSummary(rule)); + expect(summaries()).toEqual([ + 'Réduire les jours non posés expirant pendant la période planifiée.', + 'Si un jour férié tombe un samedi, poser 2 jours de congés payés au mieux autour et gagner 1 jour de type Autre.', + expect.stringMatching( + /^Poser 5 jours de congé de tout type<\/strong> entre le 20\/12\/\d{4}<\/strong> et le 03\/01\/\d{4}<\/strong>\.$/, + ), + 'Augmenter la valeur des semaines avec un jour férié prises en entier, plus forte pour un férié en milieu de semaine.', + 'Augmenter les jours de week-end et fériés compris dans les périodes de repos.', + 'Réduire la plus longue séquence de travail.', + 'Réduire les jours qui manquent aux séquences de travail entre deux périodes de repos pour atteindre 5 jours ouvrés.', + 'Réduire le nombre de jours posés en plus sur des soldes expirant après la période planifiée.', + ]); + const translations = TestBed.inject(TranslationService); + for (const language of translations.availableLanguages) { + translations.setLanguage(language); + for (const summary of summaries()) expect(summary).not.toMatch(/[{}]|\(s\)/); + } + translations.setLanguage('en'); + expect(summaries()[1]).toBe( + 'If a public holiday falls on a Saturday, take 2 days of paid leave around it where it helps most and earn 1 day of Other leave.', + ); + translations.setLanguage('de'); + expect(summaries()[1]).toBe( + 'Wenn ein Feiertag auf einen Samstag fällt, 2 Tage bezahlten Urlaub bestmöglich rund um den Feiertag nehmen und 1 Tag der Art „Andere“ erwerben.', + ); + }); + + it('leaves out zero earned days and counts a single day in the singular', () => { + const samediMalin = component.rules[1]; + if (samediMalin.type !== RuleType.IF_THEN) throw new Error('Expected an IF_THEN rule'); + expect( + component.getRuleSummary({ + ...samediMalin, + placeDays: 1, + rewardDays: 0, + placement: 'before', + }), + ).toBe( + 'Si un jour férié tombe un samedi, poser 1 jour de congés payés juste avant.', + ); + }); + it('should start adding new If-Then rule', () => { component.startAddNew(RuleType.IF_THEN); @@ -134,7 +178,9 @@ describe('RulesPanel', () => { force: 'preference', configuration: OPTIMIZATION_PRESETS.unplacedAtRisk, }); - expect(component.getRuleSummary(rule)).toContain('Quantité non placée'); + expect(component.getRuleSummary(rule)).toBe( + 'Réduire les jours non posés expirant pendant la période planifiée.', + ); const announce = vi.spyOn(TestBed.inject(LiveAnnouncer), 'announce').mockResolvedValue(); const buttons = fixture.nativeElement.querySelectorAll('.rule-item'); const moveUp: HTMLButtonElement = diff --git a/src/app/components/rules-panel/rules-panel.ts b/src/app/components/rules-panel/rules-panel.ts index 5889ad2..55bf2ff 100644 --- a/src/app/components/rules-panel/rules-panel.ts +++ b/src/app/components/rules-panel/rules-panel.ts @@ -28,6 +28,7 @@ import { MatDatepickerModule } from '@angular/material/datepicker'; import { FormsModule } from '@angular/forms'; import { NgTemplateOutlet } from '@angular/common'; import { LiveAnnouncer } from '@angular/cdk/a11y'; +import * as labels from '../../services/planner-labels'; import { OPTIMIZATION_CATALOG, OPTIMIZATION_PRESETS, @@ -315,41 +316,38 @@ export class RulesPanel { public getRuleSummary(rule: VacationRule): string { const tr = this.tr(); - if (rule.type === RuleType.OPTIMIZATION) - return this.translationService.optimizationSummary(rule.configuration); - if (rule.type === RuleType.IF_THEN) { - const ifThen = rule as IfThenRule; - const dayLabel = this.daysOfWeek.find((d) => d.value === ifThen.dayOfWeek)?.label ?? ''; - const placeTypeLabel = this.getDayTypeLabel(ifThen.placeType); - const placementLabel = ( - this.placementOptions.find((p) => p.value === ifThen.placement)?.label ?? '' - ) - .trim() - .toLowerCase(); - const rewardTypeLabel = this.getDayTypeLabel(ifThen.rewardType); - - return tr.rules.ifThenTemplate - .replace('{day}', dayLabel) - .replace('{placeDays}', String(ifThen.placeDays)) - .replace('{placeType}', placeTypeLabel) - .replace('{placement}', placementLabel) - .replace('{rewardDays}', String(ifThen.rewardDays)) - .replace('{rewardType}', rewardTypeLabel); - } else { - const timeWindow = rule as TimeWindowRule; - const placeTypeLabel = this.getDayTypeLabel(timeWindow.placeType); - const startDateStr = new Date(timeWindow.startDate).toLocaleDateString( - this.translationService.locale(), - ); - const endDateStr = new Date(timeWindow.endDate).toLocaleDateString( - this.translationService.locale(), - ); - - return tr.rules.timeWindowTemplate - .replace('{placeDays}', String(timeWindow.placeDays)) - .replace('{placeType}', placeTypeLabel) - .replace('{startDate}', startDateStr) - .replace('{endDate}', endDateStr); + if (rule.type === RuleType.OPTIMIZATION) { + const goal = labels.optimizationGoal(tr, rule.configuration); + return goal ? `${goal}.` : tr.rules.optimization.invalidConfiguration; } + const locale = this.translationService.locale(); + const days = (count: number, type: SelectableDayType) => + labels + .plural(tr, tr.rules.dayCount, count) + .replace('{type}', tr.rules.summaryTypes[type]); + if (rule.type === RuleType.IF_THEN) { + // 1 January 2023 is a Sunday, the day numbered 0; Intl gives each language its own casing. + const day = new Intl.DateTimeFormat(locale, { + weekday: 'long', + timeZone: 'UTC', + }).format(Date.UTC(2023, 0, 1 + rule.dayOfWeek)); + return tr.rules.ifThenTemplate + .replace('{day}', day) + .replace('{placeDays}', days(rule.placeDays, rule.placeType)) + .replace('{placement}', tr.rules.summaryPlacement[rule.placement]) + .replace( + '{earned}', + rule.rewardDays > 0 + ? tr.rules.ifThenEarned.replace( + '{earnedDays}', + days(rule.rewardDays, rule.rewardType), + ) + : '', + ); + } + return tr.rules.timeWindowTemplate + .replace('{placeDays}', days(rule.placeDays, rule.placeType)) + .replace('{startDate}', new Date(rule.startDate).toLocaleDateString(locale)) + .replace('{endDate}', new Date(rule.endDate).toLocaleDateString(locale)); } } diff --git a/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts b/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts index f7de01e..5340784 100644 --- a/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts +++ b/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts @@ -7,6 +7,7 @@ import { RuleService, RuleType } from '../../services/rule-service'; import { TranslationService } from '../../services/translation-service'; import { calculatePlanningInternal } from '../../services/leave-planner.core'; import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives'; +import { optimizationSummary } from '../../services/planner-labels'; import { RulesPanel } from './rules-panel'; describe('work-sequence rule editor and reload', () => { @@ -77,8 +78,8 @@ describe('work-sequence rule editor and reload', () => { await fixture.whenStable(); const rule = component.rules[0]; expect(rule).toMatchObject({ configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit }); - expect(component.getRuleSummary(rule)).toContain( - 'Déficit des séquences de travail (jours ouvrés)', + expect(component.getRuleSummary(rule)).toBe( + 'Réduire les jours qui manquent aux séquences de travail entre deux périodes de repos pour atteindre 5 jours ouvrés.', ); const request = { horizon: { start: '2024-01-08', end: '2024-01-13' }, @@ -95,7 +96,7 @@ describe('work-sequence rule editor and reload', () => { component.saveEdit(); await fixture.whenStable(); expect(component.getRuleSummary(component.rules[0])).toContain( - 'seuil de préférence : 3 jours ouvrés', + 'pour atteindre 3 jours ouvrés', ); expect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({ kind: 'Plan', @@ -152,21 +153,17 @@ describe('work-sequence rule editor and reload', () => { }); it('distinguishes aggregation units from the working-day threshold', () => { - const translations = TestBed.inject(TranslationService); - expect( - translations.optimizationSummary(OPTIMIZATION_PRESETS.longestWorkSequence), - ).toContain('Longueur des séquences de travail (jours ouvrés)'); - expect( - translations.optimizationSummary({ - ...OPTIMIZATION_PRESETS.shortSequenceDeficit, - aggregation: 'count', - }), - ).toContain('Déficit des séquences de travail (Nombre)'); - expect( - translations.optimizationSummary({ - ...OPTIMIZATION_PRESETS.shortSequenceDeficit, - aggregation: 'count', - }), - ).toContain('seuil de préférence : 5 jours ouvrés'); + const tr = TestBed.inject(TranslationService).tr(); + expect(optimizationSummary(tr, OPTIMIZATION_PRESETS.longestWorkSequence)).toContain( + 'Longueur des séquences de travail (jours ouvrés)', + ); + const count = { + ...OPTIMIZATION_PRESETS.shortSequenceDeficit, + aggregation: 'count' as const, + }; + expect(optimizationSummary(tr, count)).toContain( + 'Déficit des séquences de travail (Nombre)', + ); + expect(optimizationSummary(tr, count)).toContain('seuil de préférence : 5 jours ouvrés'); }); }); diff --git a/src/app/services/planner-labels.spec.ts b/src/app/services/planner-labels.spec.ts index 9444870..e054f3e 100644 --- a/src/app/services/planner-labels.spec.ts +++ b/src/app/services/planner-labels.spec.ts @@ -14,8 +14,10 @@ import { numericChanges, objectiveCopy, objectiveLabel, + optimizationGoal, optimizationSummary, outcomeLabel, + plural, progressStageLabel, reasonLabel, ruleLabel, @@ -24,7 +26,12 @@ import { validationReasonLabel, type RuleSource, } from './planner-labels'; -import { OPTIMIZATION_PRESETS } from './planning-objectives'; +import { + OPTIMIZATION_CATALOG, + OPTIMIZATION_PRESETS, + type OptimizationCondition, + type OptimizationConfiguration, +} from './planning-objectives'; import type { AppTranslations } from './translation-service'; const en = translationsMap['en']; @@ -205,15 +212,15 @@ describe('planning stage label', () => { expect(stageLabel(en, source, 'preference:spring')).toBe('Preference: Spring break'); }); - it('names an optimization stage after its rule and its summary', () => { + it('names an optimization stage after its rule and its goal', () => { expect(stageLabel(en, source, 'optimization:gain')).toBe( - `More days off: ${optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain)}`, + 'More days off — Increase weekend days and public holidays within time-off periods', ); }); it('shows the rule identifier when the rule is not in the snapshot', () => { expect(stageLabel(en, source, 'preference:ghost')).toBe('Preference: ghost'); - expect(stageLabel(en, source, 'optimization:ghost')).toBe('ghost: '); + expect(stageLabel(en, source, 'optimization:ghost')).toBe('ghost'); expect(stageLabel(en, null, 'preference:spring')).toBe('Preference: spring'); }); @@ -292,15 +299,15 @@ describe('objective copy', () => { ); }); - it('names an optimization after its rule and its configuration', () => { + it('names an optimization after its rule and its goal, keeping its composition technical', () => { expect(objectiveCopy(en, source, 'optimization:gain')).toEqual({ - label: `More days off: ${optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain)}`, - help: objectives['optimization'].help, + label: 'More days off — Increase weekend days and public holidays within time-off periods', + technical: optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain), }); }); it('names an optimization whose rule is unknown by its identifier alone', () => { - expect(objectiveCopy(en, source, 'optimization:ghost')?.label).toBe('ghost: '); + expect(objectiveCopy(en, source, 'optimization:ghost')).toEqual({ label: 'ghost' }); }); it('has no copy for an unknown objective', () => { @@ -328,7 +335,7 @@ describe('objective label', () => { }); describe('numeric changes', () => { - it('lists only numeric objectives whose value differs, with their label and help', () => { + it('lists only numeric objectives whose value differs, with help only where it is specific', () => { const vector = ( gain: number, tieBreak: string, @@ -344,16 +351,121 @@ describe('numeric changes', () => { { id: 'optimization:gain', label: objectiveLabel(en, source, { id: 'optimization:gain' }), - help: objectiveCopy(en, source, 'optimization:gain')?.help, + help: undefined, before: 1, after: 3, }, ]); + expect(numericChanges(en, source, vector(1, 'a', 2), vector(1, 'b', 3))).toEqual([ + { + id: 'preference:spring', + label: 'Preference: Spring break', + help: en.planning.explanation.preferenceHelp['time_window'], + before: 2, + after: 3, + }, + ]); expect(numericChanges(en, source, undefined, vector(3, 'b', 2))).toEqual([]); expect(numericChanges(en, source, vector(1, 'a', 2), undefined)).toEqual([]); }); }); +describe('optimization goal', () => { + const subsets = (conditions: readonly OptimizationCondition[]) => + conditions.reduce( + (found, condition) => [...found, ...found.map((subset) => [...subset, condition])], + [[]], + ); + const compositions = OPTIMIZATION_CATALOG.flatMap((row) => + subsets(row.conditions).flatMap((conditions) => + row.aggregations.flatMap((aggregation) => + (['minimize', 'maximize'] as const).map( + (direction) => + ({ + elements: row.elements, + measure: row.measure, + conditions, + aggregation, + direction, + ...(row.measure === 'work-sequence-deficit' + ? { thresholdDays: 3 } + : {}), + }) as OptimizationConfiguration, + ), + ), + ), + ); + + it('words the supplied rules in plain French', () => { + const goals = Object.fromEntries( + Object.entries(OPTIMIZATION_PRESETS).map(([key, configuration]) => [ + key, + optimizationGoal(fr, configuration), + ]), + ); + expect(goals).toEqual({ + unplacedAtRisk: 'Réduire les jours non posés expirant pendant la période planifiée', + holidayWeekValue: + 'Augmenter la valeur des semaines avec un jour férié prises en entier, plus forte pour un férié en milieu de semaine', + nonWorkingDayGain: + 'Augmenter les jours de week-end et fériés compris dans les périodes de repos', + longestWorkSequence: 'Réduire la plus longue séquence de travail', + shortSequenceDeficit: + 'Réduire les jours qui manquent aux séquences de travail entre deux périodes de repos pour atteindre 5 jours ouvrés', + supportingPlacements: + 'Réduire le nombre de jours posés en plus sur des soldes expirant après la période planifiée', + }); + }); + + it.each(Object.keys(translationsMap))( + 'words every valid composition without engine terms in %s', + (language) => { + const tr = translationsMap[language]; + const rules = tr.rules.optimization; + expect(compositions).toHaveLength(90); + for (const configuration of compositions) { + const goal = optimizationGoal(tr, configuration); + expect(goal).toMatch(/^\p{Lu}[^{}]+$/u); + expect(goal).not.toContain(rules.directions[configuration.direction]); + expect(goal).not.toContain(' — '); + for (const condition of configuration.conditions) + if (condition !== 'non-empty' || configuration.aggregation === 'count') + expect(goal).toContain(rules.plain.scopes[condition]); + if ( + configuration.measure === 'work-sequence-deficit' && + configuration.aggregation !== 'count' + ) + expect(goal).toContain(plural(tr, rules.plain.workingDays, 3)); + } + }, + ); + + it('leaves out an empty-sequence condition that cannot change a sum or a maximum', () => { + const length = { + ...OPTIMIZATION_PRESETS.longestWorkSequence, + conditions: ['non-empty'] as const, + }; + expect(optimizationGoal(fr, length)).toBe('Réduire la plus longue séquence de travail'); + expect(optimizationGoal(fr, { ...length, aggregation: 'count' })).toBe( + 'Réduire le nombre de séquences de travail d’au moins un jour ouvré', + ); + }); + + it('puts the threshold in the singular or plural of the language', () => { + const deficit = { ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 1 }; + expect(optimizationGoal(fr, deficit)).toContain('pour atteindre 1 jour ouvré'); + expect(optimizationGoal(en, deficit)).toContain('to reach 1 working day'); + expect(optimizationGoal(en, { ...deficit, thresholdDays: 2 })).toContain( + 'to reach 2 working days', + ); + }); + + it('has no goal for an invalid configuration', () => { + const invalid = { ...OPTIMIZATION_PRESETS.nonWorkingDayGain, elements: 'leave-balances' }; + expect(optimizationGoal(en, invalid as never)).toBeUndefined(); + }); +}); + describe('optimization summary', () => { it('describes a valid configuration in the language it is given', () => { expect(optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain)).not.toBe( diff --git a/src/app/services/planner-labels.ts b/src/app/services/planner-labels.ts index 14769e5..97c60bc 100644 --- a/src/app/services/planner-labels.ts +++ b/src/app/services/planner-labels.ts @@ -8,9 +8,10 @@ import type { import { optimizationUnit, validateOptimizationConfiguration, + type OptimizationCondition, type OptimizationConfiguration, } from './planning-objectives'; -import type { AppTranslations } from './translation-service'; +import type { AppTranslations, PluralForms } from './translation-service'; // Turns planner results into the sentences the page shows. Pure: no Angular, only translations and data. @@ -79,6 +80,13 @@ export function ruleLabel(source: RuleSource, ruleId: string): string { return source?.rules.find(({ id }) => id === ruleId)?.name ?? source?.labels[ruleId] ?? ruleId; } +/** The form of a translation that suits a count in the translation's language. */ +export function plural(tr: AppTranslations, forms: PluralForms, count: number): string { + const form = new Intl.PluralRules(tr.locale).select(count) === 'one' ? forms.one : forms.other; + return form.replace('{count}', String(count)); +} + +/** The technical composition of an optimization rule, kept for the calculation details. */ export function optimizationSummary(tr: AppTranslations, configuration: OptimizationConfiguration) { const rules = tr.rules.optimization; if (!validateOptimizationConfiguration(configuration).valid) return rules.invalidConfiguration; @@ -100,25 +108,64 @@ export function optimizationSummary(tr: AppTranslations, configuration: Optimiza .replace('{conditions}', conditions.length ? ` (${conditions.join(', ')})` : ''); } -/** The label and help of a planning objective; a rule's objective is named after its rule. */ -export function objectiveCopy(tr: AppTranslations, source: RuleSource, id: string) { +/** What an optimization rule aims for, in everyday words; undefined for an invalid configuration. */ +export function optimizationGoal( + tr: AppTranslations, + configuration: OptimizationConfiguration, +): string | undefined { + if (!validateOptimizationConfiguration(configuration).valid) return undefined; + const plain = tr.rules.optimization.plain; + const { aggregation, conditions } = configuration; + // Qualifiers follow the key order of the translation. An empty work sequence adds nothing to a + // sum or a maximum, so leaving it out only changes a count. + const scope = (Object.keys(plain.scopes) as OptimizationCondition[]) + .filter( + (condition) => + conditions.includes(condition) && + (condition !== 'non-empty' || aggregation === 'count'), + ) + .map((condition) => plain.scopes[condition]) + .join(''); + const quantity = + aggregation === 'count' + ? plain.count.replace('{elements}', plain.elements[configuration.elements]) + : plain.quantities[configuration.measure][aggregation]; + return plain.goals[configuration.direction].replace( + '{quantity}', + quantity + .replace('{scope}', scope) + .replace( + '{threshold}', + configuration.measure === 'work-sequence-deficit' + ? plural(tr, plain.workingDays, configuration.thresholdDays) + : '', + ), + ); +} + +/** + * The label and help of a planning objective; a rule's objective is named after its rule. An + * optimization rule's objective also carries its technical composition for the calculation details. + */ +export function objectiveCopy( + tr: AppTranslations, + source: RuleSource, + id: string, +): { label: string; help?: string; technical?: string } { const objectives = tr.planning.explanation.objectives; const reference = ruleOfIdentifier(id); if (!reference) return objectives[id]; const rule = source?.rules.find((candidate) => candidate.id === reference.ruleId); const name = ruleLabel(source, reference.ruleId); if (reference.kind === 'optimization') { - const copy = objectives['optimization']; + const configuration = rule && 'configuration' in rule ? rule.configuration : undefined; + const goal = configuration && optimizationGoal(tr, configuration); + if (!configuration || !goal) return { label: name }; return { - ...copy, - label: copy.label + label: objectives['optimization'].label .replace('{rule}', name) - .replace( - '{summary}', - rule && 'configuration' in rule - ? optimizationSummary(tr, rule.configuration) - : '', - ), + .replace('{summary}', goal), + technical: optimizationSummary(tr, configuration), }; } const copy = objectives['preference']; diff --git a/src/app/services/translation-service.ts b/src/app/services/translation-service.ts index b4c9594..842b832 100644 --- a/src/app/services/translation-service.ts +++ b/src/app/services/translation-service.ts @@ -6,9 +6,9 @@ import type { RemainingBalance, } from './leave-planner.service'; import { addPlanningDays } from './planning-date'; -import { optimizationSummary } from './planner-labels'; +import type { SelectableDayType } from './calendar-service'; +import type { PlacementStrategy } from './rule-service'; import { - type OptimizationConfiguration, type OptimizationElements, type OptimizationCondition, type OptimizationMeasure, @@ -16,6 +16,12 @@ import { type OptimizationDirection, } from './planning-objectives'; +/** A text for one item and a text for several, each with a {count} placeholder. */ +export interface PluralForms { + one: string; + other: string; +} + export interface AppTranslations { locale: string; bookedDays: { @@ -104,6 +110,14 @@ export interface AppTranslations { measures: Record; aggregations: Record; directions: Record; + plain: { + goals: Record; + count: string; + elements: Record; + quantities: Record>; + scopes: Record; + workingDays: PluralForms; + }; }; title: string; subtitle: string; @@ -114,7 +128,11 @@ export interface AppTranslations { ruleMoved: string; priorityInfo: string; ifThenTemplate: string; + ifThenEarned: string; timeWindowTemplate: string; + dayCount: PluralForms; + summaryTypes: Record; + summaryPlacement: Record; editRule: string; deleteRule: string; addRule: string; @@ -228,7 +246,7 @@ export interface AppTranslations { sameDate: string; moveHelp: string; comparisonUnavailable: string; - objectives: Record; + objectives: Record; preferenceHelp: Record; stages: Record; unavailable: Record; @@ -381,10 +399,6 @@ export class TranslationService { } } - public optimizationSummary(configuration: OptimizationConfiguration): string { - return optimizationSummary(this.tr(), configuration); - } - public getLanguageName(langCode: string): string { try { // Using native Intl.DisplayNames to get name of language in its own language diff --git a/src/i18n/de.json b/src/i18n/de.json index d524de7..b644b4c 100644 --- a/src/i18n/de.json +++ b/src/i18n/de.json @@ -85,8 +85,25 @@ "dragRule": "Zum Verschieben ziehen", "ruleMoved": "{name}: Position {position} von {count}.", "priorityInfo": "Die obersten Regeln haben Vorrang. Mit dem Griff oder den Pfeiltasten umsortieren.", - "ifThenTemplate": "Wenn {type} dann {placement}", - "timeWindowTemplate": "Zeitfenster {startDate} bis {endDate}", + "ifThenTemplate": "Wenn ein Feiertag auf einen {day} fällt, {placeDays} {placement} nehmen{earned}.", + "ifThenEarned": " und {earnedDays} erwerben", + "timeWindowTemplate": "{placeDays} zwischen dem {startDate} und dem {endDate} nehmen.", + "dayCount": { + "one": "{count} Tag {type}", + "other": "{count} Tage {type}" + }, + "summaryTypes": { + "cp": "bezahlten Urlaub", + "rtt": "RTT", + "other": "der Art „Andere“", + "any": "beliebiger Art" + }, + "summaryPlacement": { + "before": "direkt davor", + "after": "direkt danach", + "around": "auf beiden Seiten", + "auto": "bestmöglich rund um den Feiertag" + }, "editRule": "Regel bearbeiten", "deleteRule": "Regel löschen", "addRule": "Regel hinzufügen", @@ -96,7 +113,7 @@ "days": "Tage", "type": "Typ", "position": "Position", - "getBonus": "Bonus erhalten", + "getBonus": "erwerben", "force": "Regelverbindlichkeit", "obligation": "Verpflichtung", "preference": "Präferenz", @@ -168,6 +185,57 @@ "directions": { "minimize": "Minimieren", "maximize": "Maximieren" + }, + "plain": { + "goals": { + "minimize": "{quantity} verringern", + "maximize": "{quantity} erhöhen" + }, + "count": "Anzahl der {elements}{scope}", + "elements": { + "leave-balances": "Urlaubsguthaben", + "public-holiday-weeks": "Feiertagswochen", + "time-off-periods": "Auszeiten", + "work-sequences": "Arbeitsphasen", + "leave-placements": "genommenen Urlaubstage" + }, + "quantities": { + "unplaced-quantity": { + "sum": "Ungenutzte Urlaubstage{scope}", + "maximum": "Höchste Zahl ungenutzter Tage auf einem Guthaben{scope}" + }, + "public-holiday-week-value": { + "sum": "Wert der Feiertagswochen{scope} (Feiertage mitten in der Woche zählen mehr)", + "maximum": "Wert der besten Feiertagswoche{scope} (Feiertage mitten in der Woche zählen mehr)" + }, + "non-working-day-gain": { + "sum": "Wochenend- und Feiertage in den Auszeiten", + "maximum": "Wochenend- und Feiertage in der Auszeit mit den meisten davon" + }, + "work-sequence-length": { + "sum": "Summe der Arbeitstage in Arbeitsphasen{scope}", + "maximum": "Länge der längsten Arbeitsphase{scope}" + }, + "work-sequence-deficit": { + "sum": "Fehlende Tage von Arbeitsphasen{scope} bis zur Mindestlänge von {threshold}", + "maximum": "Höchste Zahl fehlender Tage einer Arbeitsphase{scope} bis zur Mindestlänge von {threshold}" + }, + "placement-count": { + "sum": "Anzahl der genommenen Urlaubstage{scope}", + "maximum": "Vorhandensein mindestens eines genommenen Urlaubstags{scope}" + } + }, + "scopes": { + "at-risk": " mit Verfall im Planungszeitraum", + "complete": " ohne Arbeitstag", + "supporting": " als Ergänzung aus Guthaben mit Verfall nach dem Planungszeitraum", + "non-empty": " mit mindestens einem Arbeitstag", + "internal": " zwischen zwei Auszeiten" + }, + "workingDays": { + "one": "{count} Arbeitstag", + "other": "{count} Arbeitstagen" + } } } }, @@ -273,8 +341,8 @@ "rule-window": "Eine Zeitfenster-Regel braucht ein Startdatum, das nicht nach dem Enddatum liegt.", "rule-weekday": "Eine Wenn-Dann-Regel braucht einen gültigen Wochentag.", "rule-mode": "Eine Wenn-Dann-Regel hat eine nicht unterstützte Platzierung.", - "earned-quantity": "Eine Wenn-Dann-Regel braucht eine nicht negative ganze Zahl an Bonustagen.", - "earned-type": "Eine Wenn-Dann-Regel braucht CP, RTT oder Andere als Bonusart.", + "earned-quantity": "Eine Wenn-Dann-Regel braucht eine nicht negative ganze Zahl erworbener Tage.", + "earned-type": "Eine Wenn-Dann-Regel braucht CP, RTT oder Andere als Art der erworbenen Tage.", "invalid-optimization-configuration": "Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.", "unsupported-optimization-configuration": "Diese Regel kombiniert unvereinbare Planungselemente und Messgrößen.", "horizon": "Der Planungszeitraum ist erforderlich.", @@ -370,8 +438,7 @@ "help": "Letztes Kriterium, wenn alle anderen Kriterien gleich sind." }, "optimization": { - "label": "{rule}: {summary}", - "help": "Diese Optimierungspräferenz bewertet ihre gespeicherte Konfiguration. Aktive Präferenzen werden in der angezeigten Reihenfolge verglichen; frühere haben Vorrang." + "label": "{rule} — {summary}" } }, "stages": { diff --git a/src/i18n/en.json b/src/i18n/en.json index 4390468..6cda3ad 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -85,8 +85,25 @@ "dragRule": "Drag to reorder", "ruleMoved": "{name}: position {position} of {count}.", "priorityInfo": "Rules at the top have higher priority. Reorder with the handle or arrow buttons.", - "ifThenTemplate": "If a holiday falls on a {day}, place {placeDays} day(s) {placeType} {placement} and get {rewardDays} day(s) {rewardType} as a bonus.", - "timeWindowTemplate": "Place {placeDays} day(s) {placeType} between {startDate} and {endDate}.", + "ifThenTemplate": "If a public holiday falls on a {day}, take {placeDays} {placement}{earned}.", + "ifThenEarned": " and earn {earnedDays}", + "timeWindowTemplate": "Take {placeDays} between {startDate} and {endDate}.", + "dayCount": { + "one": "{count} day {type}", + "other": "{count} days {type}" + }, + "summaryTypes": { + "cp": "of paid leave", + "rtt": "of RTT", + "other": "of Other leave", + "any": "of any leave type" + }, + "summaryPlacement": { + "before": "right before it", + "after": "right after it", + "around": "on both sides of it", + "auto": "around it where it helps most" + }, "editRule": "Edit rule", "deleteRule": "Delete rule", "addRule": "Add a rule", @@ -96,7 +113,7 @@ "days": "Days", "type": "Type", "position": "Position", - "getBonus": "Get as bonus", + "getBonus": "Earn", "force": "Rule force", "obligation": "Obligation", "preference": "Preference", @@ -168,6 +185,57 @@ "directions": { "minimize": "Minimize", "maximize": "Maximize" + }, + "plain": { + "goals": { + "minimize": "Reduce {quantity}", + "maximize": "Increase {quantity}" + }, + "count": "the number of {elements}{scope}", + "elements": { + "leave-balances": "leave balances", + "public-holiday-weeks": "public-holiday weeks", + "time-off-periods": "time-off periods", + "work-sequences": "work sequences", + "leave-placements": "leave days taken" + }, + "quantities": { + "unplaced-quantity": { + "sum": "unused leave days{scope}", + "maximum": "the largest number of unused days left on one balance{scope}" + }, + "public-holiday-week-value": { + "sum": "the value of public-holiday weeks{scope}, higher for a midweek holiday", + "maximum": "the value of the best public-holiday week{scope}, higher for a midweek holiday" + }, + "non-working-day-gain": { + "sum": "weekend days and public holidays within time-off periods", + "maximum": "weekend days and public holidays in the time-off period with the most of them" + }, + "work-sequence-length": { + "sum": "the total working days in work sequences{scope}", + "maximum": "the longest work sequence{scope}" + }, + "work-sequence-deficit": { + "sum": "the days missing from work sequences{scope} to reach {threshold}", + "maximum": "the largest number of days missing from one work sequence{scope} to reach {threshold}" + }, + "placement-count": { + "sum": "the number of leave days taken{scope}", + "maximum": "the presence of at least one leave day taken{scope}" + } + }, + "scopes": { + "at-risk": " expiring within the planning period", + "complete": " taken off entirely", + "supporting": " as extras from balances expiring after the planning period", + "non-empty": " of at least one working day", + "internal": " between two time-off periods" + }, + "workingDays": { + "one": "{count} working day", + "other": "{count} working days" + } } } }, @@ -273,8 +341,8 @@ "rule-window": "An imposed period needs a start date on or before its end date.", "rule-weekday": "An \"If ... Then\" rule needs a valid weekday.", "rule-mode": "An \"If ... Then\" rule has an unsupported placement.", - "earned-quantity": "An \"If ... Then\" rule needs a non-negative whole number of bonus days.", - "earned-type": "An \"If ... Then\" rule needs CP, RTT, or Other as its bonus type.", + "earned-quantity": "An \"If ... Then\" rule needs a non-negative whole number of earned days.", + "earned-type": "An \"If ... Then\" rule needs CP, RTT, or Other as the type of its earned days.", "invalid-optimization-configuration": "Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.", "unsupported-optimization-configuration": "This rule uses an unsupported combination of planning elements and measures.", "horizon": "The planning period is required.", @@ -370,8 +438,7 @@ "help": "Final tie-breaker when all other criteria are equal." }, "optimization": { - "label": "{rule}: {summary}", - "help": "This optimization preference evaluates its saved configuration. Active preferences follow the displayed order; earlier preferences win before later ones." + "label": "{rule} — {summary}" } }, "stages": { diff --git a/src/i18n/es.json b/src/i18n/es.json index db6d202..cb4d666 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -85,8 +85,25 @@ "dragRule": "Arrastrar para reordenar", "ruleMoved": "{name}: posición {position} de {count}.", "priorityInfo": "Las reglas de arriba tienen prioridad. Reordénalas con el tirador o las flechas.", - "ifThenTemplate": "Si un día festivo cae en {day}, colocar {placeDays} día(s) {placeType} {placement} y obtener {rewardDays} día(s) {rewardType} de bonificación.", - "timeWindowTemplate": "Colocar {placeDays} día(s) {placeType} entre el {startDate} y el {endDate}.", + "ifThenTemplate": "Si un festivo cae en {day}, tomar {placeDays} {placement}{earned}.", + "ifThenEarned": " y ganar {earnedDays}", + "timeWindowTemplate": "Tomar {placeDays} entre el {startDate} y el {endDate}.", + "dayCount": { + "one": "{count} día {type}", + "other": "{count} días {type}" + }, + "summaryTypes": { + "cp": "de vacaciones pagadas", + "rtt": "de RTT", + "other": "de tipo Otro", + "any": "de cualquier tipo" + }, + "summaryPlacement": { + "before": "justo antes", + "after": "justo después", + "around": "a ambos lados", + "auto": "alrededor donde más convenga" + }, "editRule": "Editar regla", "deleteRule": "Eliminar regla", "addRule": "Añadir una regla", @@ -96,7 +113,7 @@ "days": "Días", "type": "Tipo", "position": "Posición", - "getBonus": "Obtener en bonificación", + "getBonus": "Ganar", "force": "Fuerza de la regla", "obligation": "Obligación", "preference": "Preferencia", @@ -168,6 +185,57 @@ "directions": { "minimize": "Minimizar", "maximize": "Maximizar" + }, + "plain": { + "goals": { + "minimize": "Reducir {quantity}", + "maximize": "Aumentar {quantity}" + }, + "count": "el número de {elements}{scope}", + "elements": { + "leave-balances": "saldos de vacaciones", + "public-holiday-weeks": "semanas con festivo", + "time-off-periods": "períodos de descanso", + "work-sequences": "secuencias de trabajo", + "leave-placements": "días de permiso tomados" + }, + "quantities": { + "unplaced-quantity": { + "sum": "los días sin usar{scope}", + "maximum": "el mayor número de días sin usar de un mismo saldo{scope}" + }, + "public-holiday-week-value": { + "sum": "el valor de las semanas con festivo{scope}, mayor si el festivo cae a mitad de semana", + "maximum": "el valor de la mejor semana con festivo{scope}, mayor si el festivo cae a mitad de semana" + }, + "non-working-day-gain": { + "sum": "los días de fin de semana y festivos incluidos en los períodos de descanso", + "maximum": "los días de fin de semana y festivos del período de descanso que más tiene" + }, + "work-sequence-length": { + "sum": "el total de días trabajados en las secuencias de trabajo{scope}", + "maximum": "la secuencia de trabajo más larga{scope}" + }, + "work-sequence-deficit": { + "sum": "los días que les faltan a las secuencias de trabajo{scope} para llegar a {threshold}", + "maximum": "el mayor número de días que le faltan a una secuencia de trabajo{scope} para llegar a {threshold}" + }, + "placement-count": { + "sum": "el número de días de permiso tomados{scope}", + "maximum": "la presencia de al menos un día de permiso tomado{scope}" + } + }, + "scopes": { + "at-risk": " con vencimiento dentro del período de planificación", + "complete": " sin ningún día trabajado", + "supporting": " como extra de saldos con vencimiento posterior al período de planificación", + "non-empty": " de al menos un día laborable", + "internal": " entre dos períodos de descanso" + }, + "workingDays": { + "one": "{count} día laborable", + "other": "{count} días laborables" + } } } }, @@ -273,8 +341,8 @@ "rule-window": "Un período impuesto necesita una fecha de inicio que no sea posterior a la de fin.", "rule-weekday": "Una regla «Si … Entonces» necesita un día de la semana válido.", "rule-mode": "Una regla «Si … Entonces» tiene una colocación no admitida.", - "earned-quantity": "Una regla «Si … Entonces» necesita un número entero de días de bonificación no negativo.", - "earned-type": "Una regla «Si … Entonces» necesita Vacaciones pagadas, RTT u Otro como tipo de bonificación.", + "earned-quantity": "Una regla «Si … Entonces» necesita un número entero no negativo de días ganados.", + "earned-type": "Una regla «Si … Entonces» necesita Vacaciones pagadas, RTT u Otro como tipo de los días ganados.", "invalid-optimization-configuration": "Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.", "unsupported-optimization-configuration": "Esta regla combina elementos del plan y medidas incompatibles.", "horizon": "El período de planificación es obligatorio.", @@ -370,8 +438,7 @@ "help": "Último desempate cuando los demás criterios son iguales." }, "optimization": { - "label": "{rule}: {summary}", - "help": "Esta preferencia de optimización evalúa su configuración guardada. Las preferencias activas siguen el orden mostrado; las anteriores tienen prioridad." + "label": "{rule} — {summary}" } }, "stages": { diff --git a/src/i18n/fr.json b/src/i18n/fr.json index ebdf7b0..ef4f40e 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -85,8 +85,25 @@ "dragRule": "Glisser pour réordonner", "ruleMoved": "{name} : position {position} sur {count}.", "priorityInfo": "Les règles du haut sont prioritaires. Réorganisez-les avec la poignée ou les flèches.", - "ifThenTemplate": "Si un jour férié tombe un {day}, placer {placeDays} jour(s) {placeType} {placement} et obtenir {rewardDays} jour(s) {rewardType} en bonus.", - "timeWindowTemplate": "Placer {placeDays} jour(s) {placeType} entre le {startDate} et le {endDate}.", + "ifThenTemplate": "Si un jour férié tombe un {day}, poser {placeDays} {placement}{earned}.", + "ifThenEarned": " et gagner {earnedDays}", + "timeWindowTemplate": "Poser {placeDays} entre le {startDate} et le {endDate}.", + "dayCount": { + "one": "{count} jour {type}", + "other": "{count} jours {type}" + }, + "summaryTypes": { + "cp": "de congés payés", + "rtt": "de RTT", + "other": "de type Autre", + "any": "de congé de tout type" + }, + "summaryPlacement": { + "before": "juste avant", + "after": "juste après", + "around": "de part et d’autre", + "auto": "au mieux autour" + }, "editRule": "Modifier la règle", "deleteRule": "Supprimer la règle", "addRule": "Ajouter une règle", @@ -96,7 +113,7 @@ "days": "Jours", "type": "Type", "position": "Position", - "getBonus": "Obtenir en bonus", + "getBonus": "Gagner", "force": "Force de la règle", "obligation": "Obligation", "preference": "Préférence", @@ -168,6 +185,57 @@ "directions": { "minimize": "Minimiser", "maximize": "Maximiser" + }, + "plain": { + "goals": { + "minimize": "Réduire {quantity}", + "maximize": "Augmenter {quantity}" + }, + "count": "le nombre de {elements}{scope}", + "elements": { + "leave-balances": "soldes de congés", + "public-holiday-weeks": "semaines avec un jour férié", + "time-off-periods": "périodes de repos", + "work-sequences": "séquences de travail", + "leave-placements": "jours posés" + }, + "quantities": { + "unplaced-quantity": { + "sum": "les jours non posés{scope}", + "maximum": "le plus grand nombre de jours non posés d’un même solde{scope}" + }, + "public-holiday-week-value": { + "sum": "la valeur des semaines avec un jour férié{scope}, plus forte pour un férié en milieu de semaine", + "maximum": "la valeur de la meilleure des semaines avec un jour férié{scope}, plus forte pour un férié en milieu de semaine" + }, + "non-working-day-gain": { + "sum": "les jours de week-end et fériés compris dans les périodes de repos", + "maximum": "les jours de week-end et fériés de la période de repos qui en compte le plus" + }, + "work-sequence-length": { + "sum": "le total des jours travaillés dans les séquences de travail{scope}", + "maximum": "la plus longue séquence de travail{scope}" + }, + "work-sequence-deficit": { + "sum": "les jours qui manquent aux séquences de travail{scope} pour atteindre {threshold}", + "maximum": "le plus grand nombre de jours qui manquent à une séquence de travail{scope} pour atteindre {threshold}" + }, + "placement-count": { + "sum": "le nombre de jours posés{scope}", + "maximum": "la présence d’au moins un jour posé{scope}" + } + }, + "scopes": { + "at-risk": " expirant pendant la période planifiée", + "complete": " prises en entier", + "supporting": " en plus sur des soldes expirant après la période planifiée", + "non-empty": " d’au moins un jour ouvré", + "internal": " entre deux périodes de repos" + }, + "workingDays": { + "one": "{count} jour ouvré", + "other": "{count} jours ouvrés" + } } } }, @@ -273,8 +341,8 @@ "rule-window": "Une période imposée doit avoir une date de début qui ne dépasse pas sa date de fin.", "rule-weekday": "Une règle « Si … Alors » doit avoir un jour de la semaine valide.", "rule-mode": "Une règle « Si … Alors » a un placement non pris en charge.", - "earned-quantity": "Une règle « Si … Alors » doit avoir un nombre entier de jours bonus positif ou nul.", - "earned-type": "Une règle « Si … Alors » doit avoir CP, RTT ou Autre comme type de bonus.", + "earned-quantity": "Une règle « Si … Alors » doit avoir un nombre entier de jours gagnés positif ou nul.", + "earned-type": "Une règle « Si … Alors » doit avoir CP, RTT ou Autre comme type des jours gagnés.", "invalid-optimization-configuration": "Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.", "unsupported-optimization-configuration": "Cette règle combine des éléments du planning et des mesures incompatibles.", "horizon": "La période à planifier est obligatoire.", @@ -370,8 +438,7 @@ "help": "Dernier départage lorsque tous les autres critères sont égaux." }, "optimization": { - "label": "{rule}: {summary}", - "help": "Cette préférence d’optimisation évalue sa configuration enregistrée. Les préférences actives suivent l’ordre affiché ; les premières passent avant les suivantes." + "label": "{rule} — {summary}" } }, "stages": { -- 2.54.0 From b165245aa0e415c22841f2f09a9344a557d60bea Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 11:02:56 +0100 Subject: [PATCH 06/12] feat(plan): list the time-off periods of the plan (#358) Add a third disclosure above the calendar, closed by default, listing every time-off period that contains a leave placement or a declared non-working day: its date range in the active locale, the leave days per leave type, the declared days and its duration in days off. Choosing a period scrolls its first leave or declared day into view (honouring prefers-reduced-motion) and focuses it. The three disclosures share one row on a wide screen; their summaries drop the decorative icon when narrow so that the calendar stays above the fold. Co-Authored-By: Claude Sonnet 5.5 --- .../calendar-year-planning.spec.ts | 155 ++++++++++++++++++ .../calendar-year/calendar-year.html | 17 ++ .../calendar-year/calendar-year.scss | 18 +- .../components/calendar-year/calendar-year.ts | 17 ++ .../time-off-periods/time-off-periods.html | 31 ++++ .../time-off-periods/time-off-periods.scss | 99 +++++++++++ .../time-off-periods/time-off-periods.spec.ts | 132 +++++++++++++++ .../time-off-periods/time-off-periods.ts | 72 ++++++++ src/app/services/translation-service.ts | 1 + src/i18n/de.json | 5 + src/i18n/en.json | 5 + src/i18n/es.json | 5 + src/i18n/fr.json | 5 + 13 files changed, 561 insertions(+), 1 deletion(-) create mode 100644 src/app/components/time-off-periods/time-off-periods.html create mode 100644 src/app/components/time-off-periods/time-off-periods.scss create mode 100644 src/app/components/time-off-periods/time-off-periods.spec.ts create mode 100644 src/app/components/time-off-periods/time-off-periods.ts diff --git a/src/app/components/calendar-year/calendar-year-planning.spec.ts b/src/app/components/calendar-year/calendar-year-planning.spec.ts index a599e7d..8ab196b 100644 --- a/src/app/components/calendar-year/calendar-year-planning.spec.ts +++ b/src/app/components/calendar-year/calendar-year-planning.spec.ts @@ -2710,6 +2710,161 @@ describe('CalendarYear planning outcome boundary', () => { }, ); + describe('time-off period list', () => { + const periods: PlanOutcome = { + ...plan, + timeOffPeriods: [ + { + start: '2024-05-04', + end: '2024-05-08', + duration: 5, + placementDates: ['2024-05-06'], + nonWorkingDates: ['2024-05-04', '2024-05-05', '2024-05-07', '2024-05-08'], + nonWorkingDayGain: 4, + }, + // Plain weekend: no leave placement and no declared day, so not listed. + { + start: '2024-05-11', + end: '2024-05-12', + duration: 2, + placementDates: [], + nonWorkingDates: ['2024-05-11', '2024-05-12'], + nonWorkingDayGain: 2, + }, + { + start: '2024-05-02', + end: '2024-05-03', + duration: 2, + placementDates: ['2024-05-03'], + declaredDates: ['2024-05-02'], + nonWorkingDates: [], + nonWorkingDayGain: 0, + }, + ], + }; + + async function show(outcome: PlanningOutcome, explained?: PlanningExplanation) { + const { calendar, creation } = calendarFor(outcome, explained); + 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(); + await new Promise((resolve) => setTimeout(resolve, 0)); + fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + return { + fixture, + root, + details: root.querySelector( + '.plan-insights > .time-off-periods', + ), + }; + } + + it('lists the periods with leave in a closed disclosure among the others', async () => { + const { fixture, root, details } = await show(periods, explanation); + expect(details!.open).toBe(false); + const summary = details!.querySelector('summary')!.textContent?.replace(/\s+/g, ' '); + expect(summary).toContain('Your time-off periods'); + expect(summary).toContain('Periods : 2'); + const translation = TestBed.inject(TranslationService); + for (const [language, copy] of Object.entries(translationsMap)) { + translation.setLanguage(language); + fixture.detectChanges(); + const shown = details!.querySelector('summary')!.textContent; + expect(shown).toContain(copy.planning.timeOffPeriods.title); + expect(shown).toContain(copy.planning.timeOffPeriods.count); + expect(details!.querySelector('.help')!.textContent).toBe( + copy.planning.timeOffPeriods.help, + ); + } + expect( + [...details!.querySelectorAll('li > button')].map( + (b) => b.dataset['start'], + ), + ).toEqual(['2024-05-02', '2024-05-04']); + 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('.month-grid')!)).toBe(true); + }); + + it.each([ + ['without any period', plan], + [ + 'without a period with leave', + { ...periods, timeOffPeriods: [periods.timeOffPeriods[1]] }, + ], + ['without a plan', { kind: 'InvalidInput', reasons: [] } as PlanningOutcome], + ])('is absent %s', async (_label, outcome) => { + const { root, details } = await show(outcome); + expect(details).toBeNull(); + expect(root.querySelector('app-time-off-periods')).toBeNull(); + }); + + it('follows the partial plan of an interrupted calculation', async () => { + const { details } = await show({ + kind: 'PlanningIncomplete', + incumbent: periods, + completedStages: [], + reasons: [{ code: 'user-cancelled', message: 'Cancelled' }], + }); + expect(details!.querySelectorAll('li > button')).toHaveLength(2); + }); + + describe.each([ + [false, 'smooth'], + [true, 'auto'], + ])('choosing a period (reduced motion: %s)', (reduced, behavior) => { + const scrollIntoView = vi.fn(); + beforeEach(() => { + scrollIntoView.mockClear(); + Element.prototype.scrollIntoView = scrollIntoView; + const base = window.matchMedia('(prefers-reduced-motion: reduce)'); + vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({ + ...base, + matches: reduced, + media: query, + })); + }); + afterEach(() => { + vi.restoreAllMocks(); + delete (Element.prototype as Partial).scrollIntoView; + }); + + it('scrolls to its first leave day and focuses it', async () => { + const { fixture, details } = await show(periods, explanation); + // A keyboard user opens the disclosure, then activates the second period. + activateWithKeyboard(details!.querySelector('summary')!); + const [, second] = details!.querySelectorAll('li > button'); + activateWithKeyboard(second); + fixture.detectChanges(); + const day = fixture.nativeElement.querySelector('button[data-date="2024-05-06"]'); + expect(document.activeElement).toBe(day); + expect(scrollIntoView).toHaveBeenCalledOnce(); + expect(scrollIntoView.mock.contexts[0]).toBe(day); + expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior }); + }); + + it('prefers a declared day when it comes first', async () => { + const { fixture, details } = await show(periods, explanation); + activateWithKeyboard(details!.querySelector('li > button')!); + expect(document.activeElement).toBe( + fixture.nativeElement.querySelector('button[data-date="2024-05-02"]'), + ); + }); + }); + }); + it('shows muted, disabled context dates in an adjacent year', async () => { if (explanation.kind !== 'PlanExplanation') throw new Error('Expected plan explanation'); const boundaryPlan: PlanOutcome = { diff --git a/src/app/components/calendar-year/calendar-year.html b/src/app/components/calendar-year/calendar-year.html index 9ebd22a..dde31e7 100644 --- a/src/app/components/calendar-year/calendar-year.html +++ b/src/app/components/calendar-year/calendar-year.html @@ -563,6 +563,23 @@ } + @if (timeOffPeriodCount(); as count) { +
+ + + {{ tr().planning.timeOffPeriods.title + }}{{ tr().planning.timeOffPeriods.count }} : {{ count }} + + + +
+ } } diff --git a/src/app/components/calendar-year/calendar-year.scss b/src/app/components/calendar-year/calendar-year.scss index 9b7fcbe..78b011e 100644 --- a/src/app/components/calendar-year/calendar-year.scss +++ b/src/app/components/calendar-year/calendar-year.scss @@ -110,10 +110,12 @@ code { .plan-insights { display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); + // Closed disclosures share a row (three on a wide screen); an open one takes the full row. + grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr)); align-items: start; gap: 0.75rem; > details { + container-type: inline-size; min-width: 0; border: 1px solid var(--ui-border); border-radius: var(--ui-radius-md); @@ -151,6 +153,20 @@ code { font-weight: 400; } } + // Three disclosures share a wide row: drop the decorative icon to keep the row as low as two. + @container (max-width: 20rem) { + > summary { + gap: 0.5rem; + padding: 0.625rem 0.875rem; + min-height: 0; + > mat-icon:first-child { + display: none; + } + small { + margin-top: 0.125rem; + } + } + } &[open] { grid-column: 1 / -1; > summary { diff --git a/src/app/components/calendar-year/calendar-year.ts b/src/app/components/calendar-year/calendar-year.ts index 48faeb8..ebc7dc6 100644 --- a/src/app/components/calendar-year/calendar-year.ts +++ b/src/app/components/calendar-year/calendar-year.ts @@ -27,6 +27,7 @@ import { import { CalendarMonth, DeclarationPreview } from '../calendar-month/calendar-month'; import { DateComparison } from '../date-comparison/date-comparison'; import { PlanningCriteria } from '../planning-criteria/planning-criteria'; +import { TimeOffPeriods, timeOffPeriodRows } from '../time-off-periods/time-off-periods'; import { addPlanningDays } from '../../services/planning-date'; import { isWorkingPlanningDate } from '../../services/declared-non-working-days'; import { CalendarService, SelectedDates } from '../../services/calendar-service'; @@ -58,6 +59,7 @@ type PlacementExplanation = PlanExplanation['placements'][number]; CalendarMonth, DateComparison, PlanningCriteria, + TimeOffPeriods, MatCardContent, MatProgressSpinner, MatIcon, @@ -172,6 +174,10 @@ export class CalendarYear { this.declaredPeriods().length ); }); + protected readonly timeOffPeriodCount = computed(() => { + const plan = this.displayedPlan(); + return plan ? timeOffPeriodRows(plan).length : 0; + }); protected readonly weekendConnectedHolidays = computed(() => { const isWeekend = (date: string) => { const day = new Date(`${date}T00:00:00Z`).getUTCDay(); @@ -571,6 +577,17 @@ export class CalendarYear { } } + /** Brings a date of the calendar into view and moves focus to its day button. */ + protected showDate(date: string): void { + const day = this.monthGrid()?.nativeElement.querySelector( + `[data-date="${date}"]`, + ); + if (!day) return; + const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches; + day.scrollIntoView({ block: 'center', behavior: reduced ? 'auto' : 'smooth' }); + day.focus({ preventScroll: true }); + } + protected selectCalendarDate(date: string): void { if (this.declarationEntry()) { const horizon = this.calendarHorizon(); diff --git a/src/app/components/time-off-periods/time-off-periods.html b/src/app/components/time-off-periods/time-off-periods.html new file mode 100644 index 0000000..249fe1e --- /dev/null +++ b/src/app/components/time-off-periods/time-off-periods.html @@ -0,0 +1,31 @@ +

{{ tr().planning.timeOffPeriods.help }}

+
    + @for (row of rows(); track row.start) { +
  • + +
  • + } +
diff --git a/src/app/components/time-off-periods/time-off-periods.scss b/src/app/components/time-off-periods/time-off-periods.scss new file mode 100644 index 0000000..82cdc21 --- /dev/null +++ b/src/app/components/time-off-periods/time-off-periods.scss @@ -0,0 +1,99 @@ +:host { + display: block; + min-width: 0; +} + +.help { + margin: 0; + padding: 0.75rem 1rem 0; + color: var(--ui-text-secondary); + font-size: 0.875rem; +} + +// A long plan scrolls here instead of pushing the calendar down. +.periods { + max-height: min(22rem, 60dvh); + margin: 0; + padding: 0.5rem; + overflow-y: auto; + list-style: none; +} + +li + li { + border-top: 1px solid var(--ui-border); +} + +button { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.375rem 1rem; + width: 100%; + min-height: 2.75rem; + padding: 0.5rem 0.75rem; + border: 0; + border-radius: var(--ui-radius-sm); + background: transparent; + color: inherit; + font: inherit; + text-align: start; + cursor: pointer; + transition: background-color 150ms ease; + &:hover { + background: var(--ui-panel-bg); + } +} + +.range { + flex: 1 1 11rem; + font-weight: 600; + font-variant-numeric: tabular-nums; +} +.counts { + display: flex; + flex-wrap: wrap; + gap: 0.375rem 0.75rem; + font-size: 0.8125rem; +} +.count { + display: inline-flex; + align-items: center; + gap: 0.375rem; + color: var(--ui-text-secondary); + strong { + color: var(--mat-sys-on-surface); + font-variant-numeric: tabular-nums; + } +} +.duration { + flex: 0 0 auto; + min-width: 9rem; + color: var(--ui-text-secondary); + font-size: 0.8125rem; + text-align: end; + strong { + color: var(--mat-sys-on-surface); + font-size: 1rem; + font-variant-numeric: tabular-nums; + } +} + +.swatch { + flex-shrink: 0; + width: 1rem; + height: 1rem; + border-radius: 0.25rem; + &.cp { + background: var(--cp-bg); + } + &.rtt { + background: var(--rtt-bg); + } + &.other { + background: var(--other-bg); + } + &.declared { + background-image: var(--declared-day-pattern); + border: 1px solid var(--ui-border); + } +} diff --git a/src/app/components/time-off-periods/time-off-periods.spec.ts b/src/app/components/time-off-periods/time-off-periods.spec.ts new file mode 100644 index 0000000..a18b9af --- /dev/null +++ b/src/app/components/time-off-periods/time-off-periods.spec.ts @@ -0,0 +1,132 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import type { LeavePlacement, PlanOutcome } from '../../services/leave-planner.service'; +import { TranslationService } from '../../services/translation-service'; +import { TimeOffPeriods, timeOffPeriodRows } from './time-off-periods'; + +const placement = (date: string, type: LeavePlacement['type']): LeavePlacement => ({ + date, + balanceId: type, + type, + ruleIds: [], + supporting: false, +}); + +// Deliberately out of order, with a plain public-holiday weekend between the two listed periods. +const plan: Pick = { + placements: [ + placement('2024-05-06', 'rtt'), + placement('2024-05-07', 'cp'), + placement('2024-05-03', 'cp'), + placement('2024-05-08', 'cp'), + ], + timeOffPeriods: [ + { + start: '2024-05-04', + end: '2024-05-12', + duration: 9, + placementDates: ['2024-05-06', '2024-05-07', '2024-05-08'], + nonWorkingDates: ['2024-05-04', '2024-05-05', '2024-05-09', '2024-05-10'], + nonWorkingDayGain: 4, + }, + { + start: '2024-05-25', + end: '2024-05-26', + duration: 2, + placementDates: [], + nonWorkingDates: ['2024-05-25', '2024-05-26'], + nonWorkingDayGain: 2, + }, + { + start: '2024-05-01', + end: '2024-05-05', + duration: 5, + placementDates: ['2024-05-03'], + declaredDates: ['2024-05-02'], + nonWorkingDates: ['2024-05-01', '2024-05-04', '2024-05-05'], + nonWorkingDayGain: 3, + }, + ], +}; + +describe('timeOffPeriodRows', () => { + it('lists chronologically the periods with leave or a declared day, with their leave by type', () => { + expect(timeOffPeriodRows(plan)).toEqual([ + { + start: '2024-05-01', + end: '2024-05-05', + duration: 5, + leave: [{ type: 'cp', days: 1 }], + declared: 1, + firstDate: '2024-05-02', + }, + { + start: '2024-05-04', + end: '2024-05-12', + duration: 9, + leave: [ + { type: 'cp', days: 2 }, + { type: 'rtt', days: 1 }, + ], + declared: 0, + firstDate: '2024-05-06', + }, + ]); + }); + + it('lists nothing for a plan without leave', () => { + expect( + timeOffPeriodRows({ placements: [], timeOffPeriods: [plan.timeOffPeriods[1]] }), + ).toEqual([]); + }); +}); + +describe('TimeOffPeriods', () => { + async function render(language: string) { + await TestBed.configureTestingModule({ + imports: [TimeOffPeriods], + providers: [provideZonelessChangeDetection()], + }).compileComponents(); + TestBed.inject(TranslationService).setLanguage(language); + const fixture = TestBed.createComponent(TimeOffPeriods); + fixture.componentRef.setInput('plan', plan); + fixture.detectChanges(); + return { fixture, root: fixture.nativeElement as HTMLElement }; + } + const text = (element: Element) => element.textContent?.replace(/\s+/g, ' ').trim(); + + it('shows the range, the leave days per type, the declared days and the duration of each period', async () => { + const { root } = await render('en'); + const buttons = [...root.querySelectorAll('li > button')]; + expect(buttons.map((button) => button.dataset['start'])).toEqual([ + '2024-05-01', + '2024-05-04', + ]); + const range = (start: string, end: string) => + new Intl.DateTimeFormat(TestBed.inject(TranslationService).locale(), { + dateStyle: 'medium', + timeZone: 'UTC', + }).formatRange(new Date(start), new Date(end)); + expect(text(buttons[0])).toBe( + `${range('2024-05-01', '2024-05-05')} Paid Leave : 1 Already booked : 1 5 days off in a row`, + ); + expect(text(buttons[1])).toBe( + `${range('2024-05-04', '2024-05-12')} Paid Leave : 2 RTT : 1 9 days off in a row`, + ); + expect(buttons[1].querySelector('.swatch.rtt')).not.toBeNull(); + }); + + it('shows dates in the active locale', async () => { + const { root } = await render('de'); + expect(root.querySelector('.range')?.textContent).toContain('01.–05.05.2024'); + }); + + it('chooses the first leave placement or declared day of a period', async () => { + const { fixture, root } = await render('en'); + const chosen: string[] = []; + fixture.componentInstance.dateChosen.subscribe((date) => chosen.push(date)); + for (const button of root.querySelectorAll('li > button')) + button.click(); + expect(chosen).toEqual(['2024-05-02', '2024-05-06']); + }); +}); diff --git a/src/app/components/time-off-periods/time-off-periods.ts b/src/app/components/time-off-periods/time-off-periods.ts new file mode 100644 index 0000000..2e56f5b --- /dev/null +++ b/src/app/components/time-off-periods/time-off-periods.ts @@ -0,0 +1,72 @@ +import { ChangeDetectionStrategy, Component, computed, inject, input, output } from '@angular/core'; +import type { LeaveType, PlanOutcome, TimeOffPeriod } from '../../services/leave-planner.service'; +import { TranslationService } from '../../services/translation-service'; + +const LEAVE_TYPES: readonly LeaveType[] = ['cp', 'rtt', 'other']; + +export interface TimeOffPeriodRow extends Pick { + /** Leave days to place in the period, by leave type; types without a day are left out. */ + leave: readonly { type: LeaveType; days: number }[]; + declared: number; + /** The first leave placement or declared non-working day of the period. */ + firstDate: string; +} + +/** The periods of a plan worth reading dates from, in chronological order: those with leave or a declared day. */ +export function timeOffPeriodRows( + plan: Pick, +): TimeOffPeriodRow[] { + const typeOf = new Map(plan.placements.map(({ date, type }) => [date, type])); + return plan.timeOffPeriods + .filter( + ({ placementDates, declaredDates }) => placementDates.length || declaredDates?.length, + ) + .map(({ start, end, duration, placementDates, declaredDates = [] }) => ({ + start, + end, + duration, + leave: LEAVE_TYPES.map((type) => ({ + type, + days: placementDates.filter((date) => typeOf.get(date) === type).length, + })).filter(({ days }) => days), + declared: declaredDates.length, + firstDate: [...placementDates, ...declaredDates].sort()[0], + })) + .sort((a, b) => a.start.localeCompare(b.start)); +} + +/** The time-off periods of a plan, each a button that asks for its first leave day to be shown. */ +@Component({ + selector: 'app-time-off-periods', + templateUrl: './time-off-periods.html', + styleUrl: './time-off-periods.scss', + // A button's name is read from its content: keep the spaces between its parts. + preserveWhitespaces: true, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class TimeOffPeriods { + readonly plan = input.required>(); + /** The first leave placement or declared day of the chosen period. */ + readonly dateChosen = output(); + private readonly translationService = inject(TranslationService); + protected readonly rows = computed(() => timeOffPeriodRows(this.plan())); + private readonly dateFormat = computed( + () => + new Intl.DateTimeFormat(this.translationService.locale(), { + dateStyle: 'medium', + timeZone: 'UTC', + }), + ); + + get tr() { + return this.translationService.tr; + } + + protected range({ start, end }: TimeOffPeriodRow): string { + return this.dateFormat().formatRange(new Date(start), new Date(end)); + } + + protected typeLabel(type: LeaveType): string { + return this.translationService.getDayTypeLabel(type); + } +} diff --git a/src/app/services/translation-service.ts b/src/app/services/translation-service.ts index 842b832..756ba08 100644 --- a/src/app/services/translation-service.ts +++ b/src/app/services/translation-service.ts @@ -257,6 +257,7 @@ export interface AppTranslations { explanationHelp: string; technicalDetails: string; appliedRules: { title: string; entries: string }; + timeOffPeriods: { title: string; count: string; help: string }; compareDates: string; stopComparing: string; daysPlaced: string; diff --git a/src/i18n/de.json b/src/i18n/de.json index b644b4c..f142ae4 100644 --- a/src/i18n/de.json +++ b/src/i18n/de.json @@ -370,6 +370,11 @@ "title": "Details zu angewendeten Regeln", "entries": "Einträge" }, + "timeOffPeriods": { + "title": "Ihre freien Zeiträume", + "count": "Zeiträume", + "help": "Die zu nehmenden Tage, Zeitraum für Zeitraum. Wählen Sie einen aus, um ihn im Kalender anzuzeigen." + }, "compareDates": "Andere Termine vergleichen", "stopComparing": "Datumsvergleich schließen", "explanation": { diff --git a/src/i18n/en.json b/src/i18n/en.json index 6cda3ad..8da0e1d 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -370,6 +370,11 @@ "title": "Applied rules detail", "entries": "Entries" }, + "timeOffPeriods": { + "title": "Your time-off periods", + "count": "Periods", + "help": "The days to take, period by period. Choose one to show it in the calendar." + }, "compareDates": "Compare other dates", "stopComparing": "Close date comparison", "explanation": { diff --git a/src/i18n/es.json b/src/i18n/es.json index cb4d666..7a41519 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -370,6 +370,11 @@ "title": "Detalle de las reglas aplicadas", "entries": "Elementos" }, + "timeOffPeriods": { + "title": "Tus periodos de descanso", + "count": "Periodos", + "help": "Los días que pedir, periodo a periodo. Elige uno para verlo en el calendario." + }, "compareDates": "Comparar otras fechas", "stopComparing": "Cerrar comparación", "explanation": { diff --git a/src/i18n/fr.json b/src/i18n/fr.json index ef4f40e..7a61753 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -370,6 +370,11 @@ "title": "Détail des règles appliquées", "entries": "Éléments" }, + "timeOffPeriods": { + "title": "Vos périodes de repos", + "count": "Périodes", + "help": "Les jours à poser, période par période. Choisissez-en une pour l’afficher dans le calendrier." + }, "compareDates": "Comparer d’autres dates", "stopComparing": "Fermer la comparaison", "explanation": { -- 2.54.0 From 5148274d4d40afaa78c4aa3fc3be5739bf63f404 Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 11:16:30 +0100 Subject: [PATCH 07/12] refactor(rules): edit planning rules in a dialog with one shared form (#360) Adding or editing a planning rule now opens a Material dialog instead of swapping the list item for an in-place form. One RuleDialog component serves both, for every rule kind, so the duplicated add/edit template and the state that only existed for in-place editing (editing class, cdkDragDisabled, the hidden add buttons) are gone. The list only displays, enables, reorders and deletes rules, and no longer changes layout while a rule is edited. The form markup, validation and saved rule shape are moved unchanged; the dialog returns the rule and the panel hands it to the rule service. The rule editor tests now drive the real dialog. Co-Authored-By: Claude Sonnet 5.5 --- .../rules-panel/calendar-rule-editor.spec.ts | 52 +- .../components/rules-panel/rule-dialog.html | 216 ++++++++ .../components/rules-panel/rule-dialog.scss | 55 ++ .../rules-panel/rule-dialog.spec.ts | 237 ++++++++ src/app/components/rules-panel/rule-dialog.ts | 225 ++++++++ .../components/rules-panel/rules-panel.html | 522 ++---------------- .../components/rules-panel/rules-panel.scss | 63 +-- .../rules-panel/rules-panel.spec.ts | 114 ++-- src/app/components/rules-panel/rules-panel.ts | 239 +------- .../work-sequence-rule-editor.spec.ts | 76 +-- src/testing/rule-dialog.ts | 64 +++ 11 files changed, 970 insertions(+), 893 deletions(-) create mode 100644 src/app/components/rules-panel/rule-dialog.html create mode 100644 src/app/components/rules-panel/rule-dialog.scss create mode 100644 src/app/components/rules-panel/rule-dialog.spec.ts create mode 100644 src/app/components/rules-panel/rule-dialog.ts create mode 100644 src/testing/rule-dialog.ts diff --git a/src/app/components/rules-panel/calendar-rule-editor.spec.ts b/src/app/components/rules-panel/calendar-rule-editor.spec.ts index 6f51a29..d0e7e96 100644 --- a/src/app/components/rules-panel/calendar-rule-editor.spec.ts +++ b/src/app/components/rules-panel/calendar-rule-editor.spec.ts @@ -10,6 +10,13 @@ import { type OptimizationConfiguration, } from '../../services/planning-objectives'; import { calculatePlanningInternal } from '../../services/leave-planner.core'; +import { + chooseInDialog, + clickDialogButton, + dialogField, + ruleDialog, + typeInDialog, +} from '../../../testing/rule-dialog'; describe('calendar rule editing and persistence', () => { let fixture: ComponentFixture; @@ -40,28 +47,15 @@ describe('calendar rule editing and persistence', () => { }); afterEach(() => localStorage.clear()); + const closed = () => expect.poll(() => ruleDialog()).toBeNull(); + async function select(label: string, value: string) { - const fields: HTMLElement[] = Array.from( - fixture.nativeElement.querySelectorAll('mat-form-field'), - ); - const field = fields.find( - (candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label, - ); - const control = field?.querySelector('mat-select'); - if (!control) throw new Error(`Missing labelled control: ${label}`); + const control = dialogField(label).querySelector('mat-select')!; const labels = (control.getAttribute('aria-labelledby') ?? '') .split(/\s+/) .map((id) => document.getElementById(id)?.textContent?.trim()); expect(labels).toContain(label); - control.click(); - await fixture.whenStable(); - const option = Array.from(document.querySelectorAll('mat-option')).find( - (candidate) => candidate.textContent?.trim() === value, - ); - if (!option) throw new Error(`Missing translated option: ${value}`); - option.click(); - document.querySelector('.cdk-overlay-backdrop')?.click(); - await fixture.whenStable(); + await chooseInDialog(fixture, label, value); fixture.detectChanges(); } @@ -72,10 +66,7 @@ describe('calendar rule editing and persistence', () => { ); buttons.find((button) => button.textContent?.includes(tr.optimization.newRule))!.click(); await fixture.whenStable(); - const nameInput: HTMLInputElement = - fixture.nativeElement.querySelector('.rule-editor input'); - nameInput.value = name; - nameInput.dispatchEvent(new Event('input', { bubbles: true })); + await typeInDialog(fixture, tr.ruleName, name); await select( tr.optimization.elementsLabel, tr.optimization.elements[configuration.elements], @@ -90,11 +81,8 @@ describe('calendar rule editing and persistence', () => { tr.optimization.directionLabel, tr.optimization.directions[configuration.direction], ); - const actions: HTMLButtonElement[] = Array.from( - fixture.nativeElement.querySelectorAll('.editor-actions button'), - ); - actions.find((button) => button.textContent?.trim() === tr.add)!.click(); - await fixture.whenStable(); + await clickDialogButton(fixture, tr.add); + await closed(); fixture.detectChanges(); } @@ -154,8 +142,8 @@ describe('calendar rule editing and persistence', () => { translations.tr().rules.optimization.aggregationLabel, translations.tr().rules.optimization.aggregations.count, ); - fixture.componentInstance.saveEdit(); - await fixture.whenStable(); + await clickDialogButton(fixture, translations.tr().rules.save); + await closed(); await expect .poll( () => @@ -201,11 +189,9 @@ describe('calendar rule editing and persistence', () => { fixture.componentInstance.startEdit(service.rules[0], new Event('click')); await fixture.whenStable(); - const input: HTMLInputElement = fixture.nativeElement.querySelector('.rule-editor input'); - input.value = 'Mes jours conservés'; - input.dispatchEvent(new Event('input', { bubbles: true })); - fixture.componentInstance.saveEdit(); - await fixture.whenStable(); + await typeInDialog(fixture, translations.tr().rules.ruleName, 'Mes jours conservés'); + await clickDialogButton(fixture, translations.tr().rules.save); + await closed(); const toggle: HTMLButtonElement = fixture.nativeElement .querySelector('.rule-item') .querySelector('button[role="switch"]'); diff --git a/src/app/components/rules-panel/rule-dialog.html b/src/app/components/rules-panel/rule-dialog.html new file mode 100644 index 0000000..9f9ec3b --- /dev/null +++ b/src/app/components/rules-panel/rule-dialog.html @@ -0,0 +1,216 @@ +

{{ isNew ? tr().rules.addRule : tr().rules.editRule }}

+ +
+ + {{ tr().rules.ruleName }} + + + + {{ tr().rules.force }} + + @for (option of forceOptions; track option.value) { + {{ option.label() }} + } + + + + @if ($any(editBuffer).type === RuleType.IF_THEN) { +
+ + {{ tr().rules.holidayFalls }} + + @for (day of daysOfWeek; track day.value) { + {{ day.label }} + } + + +
+ +
+ {{ tr().rules.place }} + + {{ tr().rules.days }} + + + + + {{ tr().rules.type }} + + @for (type of placeDayTypes; track type) { + {{ getDayTypeLabel(type) }} + } + + + + + {{ tr().rules.position }} + + @for (opt of placementOptions; track opt.value) { + {{ opt.label }} + } + + +
+ +
+ {{ tr().rules.getBonus }} + + {{ tr().rules.days }} + + + + + {{ tr().rules.type }} + + @for (type of rewardDayTypes; track type) { + {{ getDayTypeLabel(type) }} + } + + +
+ } @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) { + @if (optimizationConfiguration; as configuration) { +
+ + {{ tr().rules.optimization.elementsLabel }} + + @for (elements of optimizationElements; track elements) { + {{ + tr().rules.optimization.elements[elements] + }} + } + + + + {{ tr().rules.optimization.measureLabel }} + + @for (row of optimizationMeasures; track row.measure) { + {{ + tr().rules.optimization.measures[row.measure] + }} + } + + +
+ @if (optimizationConditions.length) { + + {{ tr().rules.optimization.conditionsLabel }} + + @for (condition of optimizationConditions; track condition) { + {{ + tr().rules.optimization.conditions[condition] + }} + } + + + } +
+ + {{ tr().rules.optimization.aggregationLabel }} + + @for (aggregation of optimizationAggregations; track aggregation) { + {{ + tr().rules.optimization.aggregations[aggregation] + }} + } + + + + {{ tr().rules.optimization.directionLabel }} + + @for (direction of optimizationDirections; track direction) { + {{ + tr().rules.optimization.directions[direction] + }} + } + + + @if (configuration.measure === 'work-sequence-deficit') { + + {{ tr().rules.optimization.thresholdLabel }} + + + } +
+ } + } @else { +
+ + {{ tr().rules.startDate }} + + + + + + + {{ tr().rules.endDate }} + + + + +
+ +
+ {{ tr().rules.place }} + + {{ tr().rules.days }} + + + + + {{ tr().rules.type }} + + @for (type of placeDayTypes; track type) { + {{ getDayTypeLabel(type) }} + } + + +
+ } +
+
+@if (validationError()) { +

{{ validationError() }}

+} + + + + diff --git a/src/app/components/rules-panel/rule-dialog.scss b/src/app/components/rules-panel/rule-dialog.scss new file mode 100644 index 0000000..6cea44d --- /dev/null +++ b/src/app/components/rules-panel/rule-dialog.scss @@ -0,0 +1,55 @@ +:host { + display: block; +} + +.rule-editor { + display: flex; + flex-direction: column; + gap: 16px; + // Room for the floating label of the first field, which the scrolling content would clip. + padding-top: 0.5rem; + + .editor-row { + display: flex; + flex-wrap: wrap; + gap: 16px; + align-items: center; + + .action-text { + flex-basis: 100%; + font-weight: 500; + } + + mat-form-field { + flex: 1 1 11rem; + min-width: 0; + max-width: 100%; + } + + .small-input { + flex: 0 1 6.25rem; + } + + // Its label is long: take a row of its own once the others leave no room for it. + .wide-label { + flex-basis: 16rem; + } + } + + mat-form-field ::ng-deep .mat-mdc-form-field-subscript-wrapper { + display: none; + } + + .full-width { + width: 100%; + min-width: 0; + } +} + +[role='alert'] { + margin: 1rem 1.5rem 0; + padding: 0.75rem; + border-radius: var(--ui-radius-sm, 0.5rem); + color: var(--ui-error-text); + background: var(--ui-error-bg); +} diff --git a/src/app/components/rules-panel/rule-dialog.spec.ts b/src/app/components/rules-panel/rule-dialog.spec.ts new file mode 100644 index 0000000..1cd5969 --- /dev/null +++ b/src/app/components/rules-panel/rule-dialog.spec.ts @@ -0,0 +1,237 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { By } from '@angular/platform-browser'; +import { MatExpansionPanel } from '@angular/material/expansion'; +import { RulesPanel } from './rules-panel'; +import { RuleService, RuleType } from '../../services/rule-service'; +import { TranslationService } from '../../services/translation-service'; +import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives'; +import { vi } from '../../../testing/vitest-compat'; +import { + chooseInDialog, + clickDialogButton, + dialogButton, + dialogField, + ruleDialog, + typeInDialog, +} from '../../../testing/rule-dialog'; + +describe('rule dialog', () => { + let fixture: ComponentFixture; + let component: RulesPanel; + + const addButton = (index: number) => + fixture.nativeElement.querySelectorAll('.add-buttons button')[index] as HTMLButtonElement; + const editButton = (index: number) => + fixture.nativeElement + .querySelectorAll('.rule-item') + [index].querySelector('[aria-label="Modifier la règle"]') as HTMLButtonElement; + const nameInput = () => dialogField('Nom de la règle').querySelector('input')!; + const title = () => ruleDialog()!.querySelector('h2')!.textContent!.trim(); + const closed = () => expect.poll(() => ruleDialog()).toBeNull(); + + beforeEach(async () => { + localStorage.clear(); + vi.setSystemTime(new Date('2024-01-01T12:00:00Z')); + await TestBed.configureTestingModule({ + imports: [RulesPanel], + providers: [provideZonelessChangeDetection(), RuleService], + }).compileComponents(); + TestBed.inject(TranslationService).setLanguage('fr'); + fixture = TestBed.createComponent(RulesPanel); + component = fixture.componentInstance; + fixture.detectChanges(); + fixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open(); + await fixture.whenStable(); + }); + afterEach(() => { + localStorage.clear(); + vi.useRealTimers(); + }); + + it.each([ + [0, 'Nouvelle Règle'], + [1, 'Nouvelle Période'], + [2, 'Prévention des pertes'], + ])('opens one dialog to add a rule of kind %i with its defaults', async (index, name) => { + addButton(index).focus(); + addButton(index).click(); + await fixture.whenStable(); + + expect(document.querySelectorAll('mat-dialog-container')).toHaveLength(1); + expect(title()).toBe('Ajouter une règle'); + expect(nameInput().value).toBe(name); + await expect.poll(() => ruleDialog()!.contains(document.activeElement)).toBe(true); + expect(dialogButton('Ajouter')).toBeTruthy(); + expect(ruleDialog()!.querySelector('[role="alert"]')).toBeNull(); + }); + + it.each([ + [1, 'Samedi Malin', 'Jour férié tombe un'], + [2, 'Vacances de Noël', 'Date de début'], + [5, 'Séquence de travail maximale', 'Éléments du planning'], + ])( + 'opens the same dialog to edit rule %i, filled with the saved rule', + async (index, name, field) => { + editButton(index).focus(); + editButton(index).click(); + await fixture.whenStable(); + + expect(title()).toBe('Modifier la règle'); + expect(nameInput().value).toBe(name); + expect(dialogField(field)).toBeTruthy(); + expect(dialogButton('Enregistrer')).toBeTruthy(); + }, + ); + + it('keeps the list as it is while a rule is being added or edited', async () => { + const list = () => fixture.nativeElement.querySelector('.rules-list').innerHTML; + const before = list(); + editButton(1).click(); + await fixture.whenStable(); + nameInput().value = 'Pas encore enregistrée'; + nameInput().dispatchEvent(new Event('input', { bubbles: true })); + await fixture.whenStable(); + expect(list()).toBe(before); + expect(fixture.nativeElement.querySelector('.rule-editor')).toBeNull(); + expect(fixture.nativeElement.querySelector('.add-buttons').classList).not.toContain( + 'hidden', + ); + }); + + it('adds a rule once Add is chosen and returns focus to the add button', async () => { + const count = component.rules.length; + addButton(0).focus(); + addButton(0).click(); + await fixture.whenStable(); + await typeInDialog(fixture, 'Nom de la règle', 'Ma règle'); + await chooseInDialog(fixture, 'Force de la règle', 'Obligation'); + await chooseInDialog(fixture, 'Jour férié tombe un', 'Vendredi'); + await clickDialogButton(fixture, 'Ajouter'); + await closed(); + + expect(component.rules).toHaveLength(count + 1); + expect(component.rules.at(-1)).toEqual({ + name: 'Ma règle', + type: RuleType.IF_THEN, + force: 'obligation', + dayOfWeek: 5, + placeDays: 2, + placeType: 'cp', + placement: 'auto', + rewardDays: 1, + rewardType: 'other', + id: expect.any(String), + enabled: true, + }); + expect(document.activeElement).toBe(addButton(0)); + }); + + it('adds an imposed period with the dates it was given', async () => { + addButton(1).click(); + await fixture.whenStable(); + await typeInDialog(fixture, 'Date de début', '21/12/2024'); + await typeInDialog(fixture, 'Date de fin', '31/12/2024'); + await typeInDialog(fixture, 'Jours', '4'); + await clickDialogButton(fixture, 'Ajouter'); + await closed(); + + const rule = component.rules.at(-1)!; + if (rule.type !== RuleType.TIME_WINDOW) throw new Error('Expected a time window'); + expect(rule).toMatchObject({ name: 'Nouvelle Période', force: 'preference', placeDays: 4 }); + expect(new Date(rule.startDate)).toEqual(new Date(2024, 11, 21)); + expect(new Date(rule.endDate)).toEqual(new Date(2024, 11, 31)); + }); + + it('replaces the saved rule with the edited one and returns focus to the edit button', async () => { + const ifThen = component.rules[1]; + const optimization = component.rules[5]; + editButton(1).focus(); + editButton(1).click(); + await fixture.whenStable(); + await typeInDialog(fixture, 'Nom de la règle', 'Samedi modifié'); + await chooseInDialog(fixture, 'Position', 'Avant'); + await clickDialogButton(fixture, 'Enregistrer'); + await closed(); + expect(component.rules[1]).toEqual({ + ...ifThen, + name: 'Samedi modifié', + placement: 'before', + }); + expect(document.activeElement).toBe(editButton(1)); + + editButton(5).click(); + await fixture.whenStable(); + await chooseInDialog(fixture, 'Direction', 'Maximiser'); + await clickDialogButton(fixture, 'Enregistrer'); + await closed(); + expect(component.rules[5]).toEqual({ + ...optimization, + configuration: { ...OPTIMIZATION_PRESETS.longestWorkSequence, direction: 'maximize' }, + }); + expect(component.rules).toHaveLength(8); + }); + + it.each(['Annuler', 'Escape'])( + '%s closes the dialog without saving and returns focus to the control that opened it', + async (way) => { + const before = structuredClone(component.rules); + editButton(2).focus(); + editButton(2).click(); + await fixture.whenStable(); + await typeInDialog(fixture, 'Nom de la règle', 'Ne pas enregistrer'); + if (way === 'Escape') { + ruleDialog()!.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'Escape', + code: 'Escape', + keyCode: 27, + bubbles: true, + }), + ); + await fixture.whenStable(); + } else await clickDialogButton(fixture, way); + await closed(); + expect(component.rules).toEqual(before); + expect(document.activeElement).toBe(editButton(2)); + + addButton(2).focus(); + addButton(2).click(); + await fixture.whenStable(); + await clickDialogButton(fixture, way === 'Escape' ? 'Annuler' : way); + await closed(); + expect(component.rules).toEqual(before); + expect(document.activeElement).toBe(addButton(2)); + }, + ); + + it('keeps the dialog open and shows the error beside the form until the rule is valid', async () => { + addButton(0).click(); + await fixture.whenStable(); + await typeInDialog(fixture, 'Nom de la règle', ' '); + await clickDialogButton(fixture, 'Ajouter'); + expect(ruleDialog()).not.toBeNull(); + expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain( + 'Saisissez un nom de règle.', + ); + expect(component.rules).toHaveLength(8); + + await typeInDialog(fixture, 'Nom de la règle', 'Règle valide'); + await clickDialogButton(fixture, 'Ajouter'); + await closed(); + expect(component.rules.at(-1)!.name).toBe('Règle valide'); + }); + + it('shows the optimization error without changing the saved rule', async () => { + editButton(6).click(); + await fixture.whenStable(); + await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '0'); + await clickDialogButton(fixture, 'Enregistrer'); + expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain( + 'seuil entier positif', + ); + expect(component.rules[6]).toMatchObject({ + configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit, + }); + }); +}); diff --git a/src/app/components/rules-panel/rule-dialog.ts b/src/app/components/rules-panel/rule-dialog.ts new file mode 100644 index 0000000..ce7b6ca --- /dev/null +++ b/src/app/components/rules-panel/rule-dialog.ts @@ -0,0 +1,225 @@ +import { ChangeDetectionStrategy, Component, effect, inject, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { DateAdapter } from '@angular/material/core'; +import { MatDatepickerModule } from '@angular/material/datepicker'; +import { + MAT_DIALOG_DATA, + MatDialogActions, + MatDialogClose, + MatDialogContent, + MatDialogRef, + MatDialogTitle, +} from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { SelectableDayType } from '../../services/calendar-service'; +import { + IfThenRule, + OptimizationRule, + PlacementStrategy, + RuleType, + TimeWindowRule, + VacationRule, +} from '../../services/rule-service'; +import { + OPTIMIZATION_CATALOG, + OPTIMIZATION_PRESETS, + validateOptimizationConfiguration, + type OptimizationElements, + type OptimizationMeasure, +} from '../../services/planning-objectives'; +import { TranslationService } from '../../services/translation-service'; +import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter'; + +/** The rule to edit, or the kind of rule to create. */ +export type RuleDialogData = { rule: VacationRule } | { type: RuleType }; + +/** Adds or edits one planning rule; closes with the saved rule, or with nothing when cancelled. */ +@Component({ + selector: 'app-rule-dialog', + imports: [ + MatButtonModule, + MatDatepickerModule, + MatDialogActions, + MatDialogClose, + MatDialogContent, + MatDialogTitle, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + FormsModule, + ], + templateUrl: './rule-dialog.html', + styleUrl: './rule-dialog.scss', + changeDetection: ChangeDetectionStrategy.OnPush, + providers: DAY_FIRST_DATE_PROVIDERS, +}) +export class RuleDialog { + private readonly data = inject(MAT_DIALOG_DATA); + private readonly dialogRef = inject>(MatDialogRef); + protected readonly translationService = inject(TranslationService); + private readonly dateAdapter = inject(DateAdapter); + + get tr() { + return this.translationService.tr; + } + + constructor() { + effect(() => { + this.dateAdapter.setLocale(this.translationService.locale()); + }); + } + + protected readonly RuleType = RuleType; + protected readonly isNew = !('rule' in this.data); + protected readonly placeDayTypes = Object.values(SelectableDayType); + protected readonly rewardDayTypes = Object.values(SelectableDayType).filter( + (t) => t !== SelectableDayType.ANY, + ); + protected get forceOptions() { + const preference = { + value: 'preference' as const, + label: () => this.tr().rules.preference, + }; + return this.editBuffer.type === RuleType.OPTIMIZATION + ? [preference] + : [ + { value: 'obligation' as const, label: () => this.tr().rules.obligation }, + preference, + ]; + } + protected readonly optimizationElements = [ + ...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)), + ]; + protected get optimizationConfiguration() { + return this.editBuffer.type === RuleType.OPTIMIZATION + ? this.editBuffer.configuration + : undefined; + } + protected get optimizationMeasures() { + return OPTIMIZATION_CATALOG.filter( + (row) => row.elements === this.optimizationConfiguration?.elements, + ); + } + protected get optimizationConditions() { + return ( + this.optimizationMeasures.find( + (row) => row.measure === this.optimizationConfiguration?.measure, + )?.conditions ?? [] + ); + } + protected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const; + protected readonly optimizationDirections = ['minimize', 'maximize'] as const; + protected validationError = signal(''); + + public changeOptimizationElements(elements: OptimizationElements) { + this.changeOptimizationMeasure( + OPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure, + ); + } + + public changeOptimizationMeasure(measure: OptimizationMeasure) { + if (this.editBuffer.type !== RuleType.OPTIMIZATION) return; + const row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!; + const previous = this.editBuffer.configuration; + const conditions: readonly string[] = row.conditions; + this.editBuffer.configuration = { + elements: row.elements, + conditions: + previous?.conditions.filter((condition) => conditions.includes(condition)) ?? [], + aggregation: previous?.aggregation ?? 'sum', + direction: previous?.direction ?? 'minimize', + ...(measure === 'work-sequence-deficit' + ? { + measure, + thresholdDays: previous?.measure === measure ? previous.thresholdDays : 5, + } + : { measure }), + }; + } + + protected get daysOfWeek() { + const tr = this.tr(); + return [ + { value: 1, label: tr.rules.daysOfWeek[1] }, + { value: 2, label: tr.rules.daysOfWeek[2] }, + { value: 3, label: tr.rules.daysOfWeek[3] }, + { value: 4, label: tr.rules.daysOfWeek[4] }, + { value: 5, label: tr.rules.daysOfWeek[5] }, + { value: 6, label: tr.rules.daysOfWeek[6] }, + { value: 0, label: tr.rules.daysOfWeek[0] }, + ]; + } + + protected get placementOptions(): { value: PlacementStrategy; label: string }[] { + const tr = this.tr(); + return [ + { value: 'before', label: tr.rules.placement.before }, + { value: 'after', label: tr.rules.placement.after }, + { value: 'around', label: tr.rules.placement.around }, + { value: 'auto', label: tr.rules.placement.auto }, + ]; + } + + protected editBuffer: Partial = + 'rule' in this.data ? structuredClone(this.data.rule) : this.newRule(this.data.type); + + private newRule(type: RuleType): Partial { + if (type === RuleType.IF_THEN) { + return { + name: this.tr().rules.defaultNewRuleName, + type: RuleType.IF_THEN, + force: 'preference', + dayOfWeek: 6, + placeDays: 2, + placeType: SelectableDayType.CP, + placement: 'auto', + rewardDays: 1, + rewardType: SelectableDayType.OTHER, + } as Partial; + } + if (type === RuleType.OPTIMIZATION) { + return { + name: this.tr().rules.optimization.defaultName, + type, + force: 'preference', + configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk), + } satisfies Partial; + } + return { + name: this.tr().rules.defaultNewPeriodName, + type: RuleType.TIME_WINDOW, + force: 'preference', + startDate: new Date(), + endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000), + placeDays: 5, + placeType: SelectableDayType.CP, + } as Partial; + } + + protected getDayTypeLabel(type: string | undefined | null): string { + if (!type) return ''; + return this.translationService.getDayTypeLabel(type); + } + + protected save() { + if (!this.editBuffer.name?.trim()) { + this.validationError.set(this.tr().rules.optimization.nameRequired); + return; + } + if (this.editBuffer.type === RuleType.OPTIMIZATION) { + if (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) { + this.validationError.set(this.tr().rules.optimization.invalidConfiguration); + return; + } + this.editBuffer.force = 'preference'; + } + this.dialogRef.close( + (this.isNew + ? { ...this.editBuffer, id: crypto.randomUUID(), enabled: true } + : this.editBuffer) as VacationRule, + ); + } +} diff --git a/src/app/components/rules-panel/rules-panel.html b/src/app/components/rules-panel/rules-panel.html index 7a76faa..6f1a6c5 100644 --- a/src/app/components/rules-panel/rules-panel.html +++ b/src/app/components/rules-panel/rules-panel.html @@ -20,401 +20,75 @@ cdkDrag cdkDragLockAxis="y" [cdkDragStartDelay]="{ touch: 180, mouse: 0 }" - [cdkDragDisabled]="editingRuleId() === rule.id" - [class.editing]="editingRuleId() === rule.id" > - @if (editingRuleId() !== rule.id) { -
-
- - - {{ i + 1 }}. - {{ rule.name }} - +
+
+ -
- + {{ i + 1 }}. {{ rule.name }} - {{ - rule.force === 'obligation' - ? tr().rules.obligation - : tr().rules.preference - }} - - -
-
- - - - -
+
- } @else { -
-

{{ tr().rules.editRule }}

- - - {{ tr().rules.ruleName }} - - - - {{ tr().rules.force }} - - @for (option of forceOptions; track option.value) { - {{ - option.label() - }} - } - - - - @if ($any(editBuffer).type === RuleType.IF_THEN) { -
- - {{ tr().rules.holidayFalls }} - - @for (day of daysOfWeek; track day.value) { - {{ - day.label - }} - } - - -
- -
- {{ tr().rules.place }} - - {{ tr().rules.days }} - - - - - {{ tr().rules.type }} - - @for (type of placeDayTypes; track type) { - {{ - getDayTypeLabel(type) - }} - } - - - - - {{ tr().rules.position }} - - @for (opt of placementOptions; track opt.value) { - {{ - opt.label - }} - } - - -
- -
- {{ tr().rules.getBonus }} - - {{ tr().rules.days }} - - - - - {{ tr().rules.type }} - - @for (type of rewardDayTypes; track type) { - {{ - getDayTypeLabel(type) - }} - } - - -
- } @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) { - - } @else { -
- - {{ tr().rules.startDate }} - - - - - - - {{ tr().rules.endDate }} - - - - -
- -
- {{ tr().rules.place }} - - {{ tr().rules.days }} - - - - - {{ tr().rules.type }} - - @for (type of placeDayTypes; track type) { - {{ - getDayTypeLabel(type) - }} - } - - -
- } - - @if (validationError()) { -

{{ validationError() }}

- } -
- - -
+
+ + {{ + rule.force === 'obligation' + ? tr().rules.obligation + : tr().rules.preference + }} + +
- } -
- } - - @if (isAddingNew()) { -
-
-

{{ tr().rules.addRule }}

- - - {{ tr().rules.ruleName }} - - - - {{ tr().rules.force }} - - @for (option of forceOptions; track option.value) { - {{ option.label() }} - } - - - - @if (newRuleType() === RuleType.IF_THEN) { -
- - {{ tr().rules.holidayFalls }} - - @for (day of daysOfWeek; track day.value) { - {{ day.label }} - } - - -
- -
- {{ tr().rules.place }} - - {{ tr().rules.days }} - - - - - {{ tr().rules.type }} - - @for (type of placeDayTypes; track type) { - {{ - getDayTypeLabel(type) - }} - } - - - - - {{ tr().rules.position }} - - @for (opt of placementOptions; track opt.value) { - {{ opt.label }} - } - - -
- -
- {{ tr().rules.getBonus }} - - {{ tr().rules.days }} - - - - - {{ tr().rules.type }} - - @for (type of rewardDayTypes; track type) { - {{ - getDayTypeLabel(type) - }} - } - - -
- } @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) { - - } @else { -
- - {{ tr().rules.startDate }} - - - - - - - {{ tr().rules.endDate }} - - - - -
- -
- {{ tr().rules.place }} - - {{ tr().rules.days }} - - - - - {{ tr().rules.type }} - - @for (type of placeDayTypes; track type) { - {{ - getDayTypeLabel(type) - }} - } - - -
- } - - @if (validationError()) { -

{{ validationError() }}

- } -
- - + + +
} -
+
@@ -427,83 +101,3 @@
- - - @if (optimizationConfiguration; as configuration) { -
- - {{ tr().rules.optimization.elementsLabel }} - - @for (elements of optimizationElements; track elements) { - {{ - tr().rules.optimization.elements[elements] - }} - } - - - - {{ tr().rules.optimization.measureLabel }} - - @for (row of optimizationMeasures; track row.measure) { - {{ - tr().rules.optimization.measures[row.measure] - }} - } - - -
- @if (optimizationConditions.length) { - - {{ tr().rules.optimization.conditionsLabel }} - - @for (condition of optimizationConditions; track condition) { - {{ - tr().rules.optimization.conditions[condition] - }} - } - - - } -
- - {{ tr().rules.optimization.aggregationLabel }} - - @for (aggregation of optimizationAggregations; track aggregation) { - {{ - tr().rules.optimization.aggregations[aggregation] - }} - } - - - - {{ tr().rules.optimization.directionLabel }} - - @for (direction of optimizationDirections; track direction) { - {{ - tr().rules.optimization.directions[direction] - }} - } - - - @if (configuration.measure === 'work-sequence-deficit') { - - {{ tr().rules.optimization.thresholdLabel }} - - - } -
- } -
diff --git a/src/app/components/rules-panel/rules-panel.scss b/src/app/components/rules-panel/rules-panel.scss index eb050c1..ac82f2d 100644 --- a/src/app/components/rules-panel/rules-panel.scss +++ b/src/app/components/rules-panel/rules-panel.scss @@ -71,13 +71,9 @@ background: var(--ui-panel-bg); color: var(--mat-sys-on-surface); - &:hover:not(.editing) { + &:hover { border-color: var(--mat-sys-outline, #777680); } - - &.editing { - border: 1px solid var(--mat-sys-primary, #005cbb); - } } .cdk-drag-preview { @@ -213,59 +209,6 @@ } } -.rule-editor { - padding: clamp(0.75rem, 3cqi, 1.25rem); - display: flex; - flex-direction: column; - gap: 16px; - background: var(--mat-sys-surface-container-high, #e9e9ee); - border-radius: var(--ui-radius-sm, 0.5rem); - - h4 { - margin: 0; - font-size: 1.1rem; - font-weight: 500; - } - - .editor-row { - display: flex; - flex-wrap: wrap; - gap: 16px; - align-items: center; - - .action-text { - flex-basis: 100%; - font-weight: 500; - } - - mat-form-field { - flex: 1 1 11rem; - min-width: 0; - max-width: 100%; - ::ng-deep .mat-mdc-form-field-subscript-wrapper { - display: none; - } - } - - .small-input { - flex: 0 1 6.25rem; - } - } - - .full-width { - width: 100%; - min-width: 0; - } - - .editor-actions { - display: flex; - flex-wrap: wrap; - justify-content: flex-end; - gap: 12px; - margin-top: 8px; - } -} - .add-buttons { display: flex; flex-wrap: wrap; @@ -273,10 +216,6 @@ gap: 8px; margin-top: 8px; - &.hidden { - display: none; - } - button { border-radius: var(--ui-radius-sm); min-height: 2.75rem; diff --git a/src/app/components/rules-panel/rules-panel.spec.ts b/src/app/components/rules-panel/rules-panel.spec.ts index e7c0b80..a1ef66b 100644 --- a/src/app/components/rules-panel/rules-panel.spec.ts +++ b/src/app/components/rules-panel/rules-panel.spec.ts @@ -9,10 +9,18 @@ import { LiveAnnouncer } from '@angular/cdk/a11y'; import { vi } from '../../../testing/vitest-compat'; import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives'; import { MatExpansionPanel } from '@angular/material/expansion'; +import { + chooseInDialog, + clickDialogButton, + dialogField, + ruleDialog, + typeInDialog, +} from '../../../testing/rule-dialog'; describe('RulesPanel', () => { let component: RulesPanel; let fixture: ComponentFixture; + const closed = () => expect.poll(() => ruleDialog()).toBeNull(); beforeEach(async () => { // Clear localStorage before testing @@ -85,57 +93,6 @@ describe('RulesPanel', () => { ); }); - it('should start adding new If-Then rule', () => { - component.startAddNew(RuleType.IF_THEN); - - expect(component['isAddingNew']()).toBe(true); - expect(component['newRuleType']()).toBe(RuleType.IF_THEN); - expect(component['editBuffer'].type).toBe(RuleType.IF_THEN); - expect(component['editBuffer'].name).toBe('Nouvelle Règle'); - }); - - it('should start adding new Time Window rule', () => { - component.startAddNew(RuleType.TIME_WINDOW); - - expect(component['isAddingNew']()).toBe(true); - expect(component['newRuleType']()).toBe(RuleType.TIME_WINDOW); - expect(component['editBuffer'].type).toBe(RuleType.TIME_WINDOW); - expect(component['editBuffer'].name).toBe('Nouvelle Période'); - }); - - it('should cancel edit', () => { - component.startAddNew(RuleType.IF_THEN); - component.cancelEdit(); - - expect(component['isAddingNew']()).toBe(false); - expect(component['editingRuleId']()).toBeNull(); - expect(Object.keys(component['editBuffer']).length).toBe(0); - }); - - it('should save a new rule', () => { - const initialCount = component.rules.length; - - component.startAddNew(RuleType.IF_THEN); - component['editBuffer'].name = 'Custom Test Rule'; - component.saveEdit(); - - expect(component.rules.length).toBe(initialCount + 1); - expect(component.rules.some((r) => r.name === 'Custom Test Rule')).toBe(true); - }); - - it('should update an existing rule', () => { - const targetRule = component.rules[0]; - - // Create a mock event with stopPropagation - const mockEvent = { stopPropagation: () => {} } as Event; - - component.startEdit(targetRule, mockEvent); - component['editBuffer'].name = 'Updated Name'; - component.saveEdit(); - - expect(component.rules.find((r) => r.id === targetRule.id)?.name).toBe('Updated Name'); - }); - it('should delete a rule', () => { const targetId = component.rules[0].id; const initialCount = component.rules.length; @@ -165,11 +122,20 @@ describe('RulesPanel', () => { it('creates, edits and moves an optimization using the keyboard controls with preference-only mode', async () => { fixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open(); component.startAddNew(RuleType.OPTIMIZATION); - fixture.detectChanges(); - expect(component['forceOptions'].map((option) => option.value)).toEqual(['preference']); - expect(fixture.nativeElement.textContent).toContain('Éléments du planning'); - component['editBuffer'].name = 'Mes pertes'; - component.saveEdit(); + await fixture.whenStable(); + dialogField('Force de la règle').querySelector('mat-select')!.click(); + await fixture.whenStable(); + expect( + Array.from(document.querySelectorAll('mat-option')).map((option) => + option.textContent?.trim(), + ), + ).toEqual(['Préférence']); + document.querySelector('.cdk-overlay-transparent-backdrop')!.click(); + await fixture.whenStable(); + expect(ruleDialog()!.textContent).toContain('Éléments du planning'); + await typeInDialog(fixture, 'Nom de la règle', 'Mes pertes'); + await clickDialogButton(fixture, 'Ajouter'); + await closed(); await fixture.whenStable(); const rule = component.rules.at(-1)!; expect(rule).toMatchObject({ @@ -192,8 +158,10 @@ describe('RulesPanel', () => { expect(document.activeElement).toBe(moveUp); expect(announce).toHaveBeenCalledWith('Mes pertes : position 8 sur 9.'); component.startEdit(rule, new Event('click')); - component['editBuffer'].name = 'Pertes modifiées'; - component.saveEdit(); + await fixture.whenStable(); + await typeInDialog(fixture, 'Nom de la règle', 'Pertes modifiées'); + await clickDialogButton(fixture, 'Enregistrer'); + await closed(); expect(component.rules[7].name).toBe('Pertes modifiées'); component.toggleRule(rule.id); expect(component.rules[7].enabled).toBe(false); @@ -201,25 +169,31 @@ describe('RulesPanel', () => { expect(component.rules.some((candidate) => candidate.id === rule.id)).toBe(false); }); - it('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', () => { + it('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', async () => { component.startAddNew(RuleType.OPTIMIZATION); - component.saveEdit(); + await fixture.whenStable(); + await clickDialogButton(fixture, 'Ajouter'); + await closed(); const rule = component.rules.at(-1)!; component.startEdit(rule, new Event('click')); - const configuration = component['optimizationConfiguration']!; - configuration.conditions = []; - component.cancelEdit(); + await fixture.whenStable(); + await chooseInDialog( + fixture, + 'Conditions (toutes doivent être vérifiées)', + 'À risque d’expiration', + ); + await clickDialogButton(fixture, 'Annuler'); + await closed(); expect(component.rules.at(-1)).toMatchObject({ configuration: OPTIMIZATION_PRESETS.unplacedAtRisk, }); component.startEdit(rule, new Event('click')); - component.changeOptimizationMeasure('work-sequence-deficit'); - const invalid = component['optimizationConfiguration']; - if (invalid?.measure !== 'work-sequence-deficit') throw new Error('Expected deficit'); - invalid.thresholdDays = 0; - component.saveEdit(); - fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('[role="alert"]').textContent).toContain( + await fixture.whenStable(); + await chooseInDialog(fixture, 'Éléments du planning', 'Séquences de travail'); + await chooseInDialog(fixture, 'Mesure', 'Déficit des séquences de travail'); + await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '0'); + await clickDialogButton(fixture, 'Enregistrer'); + expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain( 'seuil entier positif', ); expect(component.rules.at(-1)).toMatchObject({ diff --git a/src/app/components/rules-panel/rules-panel.ts b/src/app/components/rules-panel/rules-panel.ts index 55bf2ff..49a03c5 100644 --- a/src/app/components/rules-panel/rules-panel.ts +++ b/src/app/components/rules-panel/rules-panel.ts @@ -1,44 +1,15 @@ -import { - Component, - ChangeDetectionStrategy, - ChangeDetectorRef, - inject, - signal, - effect, -} from '@angular/core'; -import { - RuleService, - RuleType, - IfThenRule, - TimeWindowRule, - OptimizationRule, - VacationRule, - PlacementStrategy, -} from '../../services/rule-service'; +import { Component, ChangeDetectionStrategy, ChangeDetectorRef, inject } from '@angular/core'; +import { RuleService, RuleType, VacationRule } from '../../services/rule-service'; import { SelectableDayType } from '../../services/calendar-service'; import { TranslationService } from '../../services/translation-service'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule } from '@angular/material/button'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatInputModule } from '@angular/material/input'; -import { MatSelectModule } from '@angular/material/select'; -import { MatDatepickerModule } from '@angular/material/datepicker'; -import { FormsModule } from '@angular/forms'; -import { NgTemplateOutlet } from '@angular/common'; +import { MatDialog } from '@angular/material/dialog'; import { LiveAnnouncer } from '@angular/cdk/a11y'; import * as labels from '../../services/planner-labels'; -import { - OPTIMIZATION_CATALOG, - OPTIMIZATION_PRESETS, - validateOptimizationConfiguration, - type OptimizationElements, - type OptimizationMeasure, -} from '../../services/planning-objectives'; - -import { DateAdapter } from '@angular/material/core'; -import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter'; +import { RuleDialog, type RuleDialogData } from './rule-dialog'; import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/drag-drop'; @Component({ @@ -48,12 +19,6 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d MatIconModule, MatButtonModule, MatSlideToggleModule, - MatFormFieldModule, - MatInputModule, - MatSelectModule, - MatDatepickerModule, - FormsModule, - NgTemplateOutlet, CdkDropList, CdkDrag, CdkDragHandle, @@ -61,12 +26,11 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d templateUrl: './rules-panel.html', styleUrl: './rules-panel.scss', changeDetection: ChangeDetectionStrategy.OnPush, - providers: DAY_FIRST_DATE_PROVIDERS, }) export class RulesPanel { public ruleService = inject(RuleService); protected readonly translationService = inject(TranslationService); - private readonly dateAdapter = inject(DateAdapter); + private readonly dialog = inject(MatDialog); private readonly liveAnnouncer = inject(LiveAnnouncer); private readonly changeDetector = inject(ChangeDetectorRef); @@ -74,109 +38,7 @@ export class RulesPanel { return this.translationService.tr; } - constructor() { - effect(() => { - this.dateAdapter.setLocale(this.translationService.locale()); - }); - } - protected readonly RuleType = RuleType; - protected readonly placeDayTypes = Object.values(SelectableDayType); - protected readonly rewardDayTypes = Object.values(SelectableDayType).filter( - (t) => t !== SelectableDayType.ANY, - ); - protected get forceOptions() { - const preference = { - value: 'preference' as const, - label: () => this.tr().rules.preference, - }; - return this.editBuffer.type === RuleType.OPTIMIZATION - ? [preference] - : [ - { value: 'obligation' as const, label: () => this.tr().rules.obligation }, - preference, - ]; - } - protected readonly optimizationElements = [ - ...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)), - ]; - protected get optimizationConfiguration() { - return this.editBuffer.type === RuleType.OPTIMIZATION - ? this.editBuffer.configuration - : undefined; - } - protected get optimizationMeasures() { - return OPTIMIZATION_CATALOG.filter( - (row) => row.elements === this.optimizationConfiguration?.elements, - ); - } - protected get optimizationConditions() { - return ( - this.optimizationMeasures.find( - (row) => row.measure === this.optimizationConfiguration?.measure, - )?.conditions ?? [] - ); - } - protected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const; - protected readonly optimizationDirections = ['minimize', 'maximize'] as const; - protected validationError = signal(''); - - public changeOptimizationElements(elements: OptimizationElements) { - this.changeOptimizationMeasure( - OPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure, - ); - } - - public changeOptimizationMeasure(measure: OptimizationMeasure) { - if (this.editBuffer.type !== RuleType.OPTIMIZATION) return; - const row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!; - const previous = this.editBuffer.configuration; - const conditions: readonly string[] = row.conditions; - this.editBuffer.configuration = { - elements: row.elements, - conditions: - previous?.conditions.filter((condition) => conditions.includes(condition)) ?? [], - aggregation: previous?.aggregation ?? 'sum', - direction: previous?.direction ?? 'minimize', - ...(measure === 'work-sequence-deficit' - ? { - measure, - thresholdDays: previous?.measure === measure ? previous.thresholdDays : 5, - } - : { measure }), - }; - } - - protected get daysOfWeek() { - const tr = this.tr(); - return [ - { value: 1, label: tr.rules.daysOfWeek[1] }, - { value: 2, label: tr.rules.daysOfWeek[2] }, - { value: 3, label: tr.rules.daysOfWeek[3] }, - { value: 4, label: tr.rules.daysOfWeek[4] }, - { value: 5, label: tr.rules.daysOfWeek[5] }, - { value: 6, label: tr.rules.daysOfWeek[6] }, - { value: 0, label: tr.rules.daysOfWeek[0] }, - ]; - } - - protected get placementOptions(): { value: PlacementStrategy; label: string }[] { - const tr = this.tr(); - return [ - { value: 'before', label: tr.rules.placement.before }, - { value: 'after', label: tr.rules.placement.after }, - { value: 'around', label: tr.rules.placement.around }, - { value: 'auto', label: tr.rules.placement.auto }, - ]; - } - - protected editingRuleId = signal(null); - protected isAddingNew = signal(false); - - protected newRuleType = signal(RuleType.IF_THEN); - - protected editBuffer: Partial = {}; - public get rules() { return this.ruleService.rules; } @@ -229,41 +91,27 @@ export class RulesPanel { public startEdit(rule: VacationRule, event: Event) { event.stopPropagation(); - this.editingRuleId.set(rule.id); - this.isAddingNew.set(false); - this.editBuffer = structuredClone(rule); - this.validationError.set(''); + this.openRuleDialog({ rule }); } - public cancelEdit() { - this.editingRuleId.set(null); - this.isAddingNew.set(false); - this.editBuffer = {}; - this.validationError.set(''); + public startAddNew(type: RuleType) { + this.openRuleDialog({ type }); } - public saveEdit() { - if (!this.editBuffer.name?.trim()) { - this.validationError.set(this.tr().rules.optimization.nameRequired); - return; - } - if (this.editBuffer.type === RuleType.OPTIMIZATION) { - if (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) { - this.validationError.set(this.tr().rules.optimization.invalidConfiguration); - return; - } - this.editBuffer.force = 'preference'; - } - if (this.editBuffer.id) { - this.ruleService.updateRule(this.editBuffer as VacationRule); - } else { - this.ruleService.addRule({ - ...this.editBuffer, - id: crypto.randomUUID(), - enabled: true, - } as VacationRule); - } - this.cancelEdit(); + private openRuleDialog(data: RuleDialogData) { + this.dialog + .open(RuleDialog, { + data, + width: '40rem', + maxWidth: 'calc(100vw - 2rem)', + maxHeight: 'calc(100dvh - 2rem)', + }) + .afterClosed() + .subscribe((rule) => { + if (!rule) return; + if ('rule' in data) this.ruleService.updateRule(rule); + else this.ruleService.addRule(rule); + }); } public deleteRule(id: string, event: Event) { @@ -271,49 +119,6 @@ export class RulesPanel { this.ruleService.deleteRule(id); } - public startAddNew(type: RuleType) { - this.isAddingNew.set(true); - this.editingRuleId.set(null); - this.newRuleType.set(type); - this.validationError.set(''); - - if (type === RuleType.IF_THEN) { - this.editBuffer = { - name: this.tr().rules.defaultNewRuleName, - type: RuleType.IF_THEN, - force: 'preference', - dayOfWeek: 6, - placeDays: 2, - placeType: SelectableDayType.CP, - placement: 'auto', - rewardDays: 1, - rewardType: SelectableDayType.OTHER, - } as Partial; - } else if (type === RuleType.OPTIMIZATION) { - this.editBuffer = { - name: this.tr().rules.optimization.defaultName, - type, - force: 'preference', - configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk), - } satisfies Partial; - } else { - this.editBuffer = { - name: this.tr().rules.defaultNewPeriodName, - type: RuleType.TIME_WINDOW, - force: 'preference', - startDate: new Date(), - endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000), - placeDays: 5, - placeType: SelectableDayType.CP, - } as Partial; - } - } - - protected getDayTypeLabel(type: string | undefined | null): string { - if (!type) return ''; - return this.translationService.getDayTypeLabel(type); - } - public getRuleSummary(rule: VacationRule): string { const tr = this.tr(); if (rule.type === RuleType.OPTIMIZATION) { diff --git a/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts b/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts index 5340784..179d807 100644 --- a/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts +++ b/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts @@ -8,38 +8,23 @@ import { TranslationService } from '../../services/translation-service'; import { calculatePlanningInternal } from '../../services/leave-planner.core'; import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives'; import { optimizationSummary } from '../../services/planner-labels'; +import { + chooseInDialog, + clickDialogButton, + dialogField, + ruleDialog, + typeInDialog, +} from '../../../testing/rule-dialog'; import { RulesPanel } from './rules-panel'; describe('work-sequence rule editor and reload', () => { let fixture: ComponentFixture; let component: RulesPanel; - async function choose(label: string, text: string) { - const fields: HTMLElement[] = Array.from( - fixture.nativeElement.querySelectorAll('mat-form-field'), - ); - const select = fields - .find((field) => field.querySelector('mat-label')?.textContent?.trim() === label) - ?.querySelector('mat-select'); - if (!select) throw new Error(`Missing select ${label}`); - select.click(); - await fixture.whenStable(); - const option = Array.from(document.querySelectorAll('mat-option')).find( - (candidate) => candidate.textContent?.trim() === text, - ); - if (!option) throw new Error(`Missing option ${text}`); - option.click(); - await fixture.whenStable(); - document.querySelector('.cdk-overlay-backdrop')?.click(); - await fixture.whenStable(); - } - - async function setInput(selector: string, value: string) { - const input: HTMLInputElement = fixture.nativeElement.querySelector(selector); - input.value = value; - input.dispatchEvent(new Event('input')); - await fixture.whenStable(); - } + const closed = () => expect.poll(() => ruleDialog()).toBeNull(); + const choose = (label: string, text: string) => chooseInDialog(fixture, label, text); + const threshold = () => + dialogField('Seuil de préférence en jours ouvrés').querySelector('input')!; beforeEach(async () => { localStorage.clear(); @@ -63,19 +48,16 @@ describe('work-sequence rule editor and reload', () => { it('creates threshold five, edits it to three, and restores its effect, order and activation after reload', async () => { component.startAddNew(RuleType.OPTIMIZATION); await fixture.whenStable(); - await setInput('input:not([type="number"])', 'Mes reprises'); + await typeInDialog(fixture, 'Nom de la règle', 'Mes reprises'); await choose('Éléments du planning', 'Séquences de travail'); await choose('Mesure', 'Déficit des séquences de travail'); await choose('Conditions (toutes doivent être vérifiées)', 'Internes'); await choose('Conditions (toutes doivent être vérifiées)', 'Non vides'); - const threshold: HTMLInputElement = - fixture.nativeElement.querySelector('input[type="number"]'); - expect(threshold.value).toBe('5'); - expect(threshold.min).toBe('1'); - expect(threshold.step).toBe('1'); - expect(fixture.nativeElement.textContent).toContain('Seuil de préférence en jours ouvrés'); - component.saveEdit(); - await fixture.whenStable(); + expect(threshold().value).toBe('5'); + expect(threshold().min).toBe('1'); + expect(threshold().step).toBe('1'); + await clickDialogButton(fixture, 'Ajouter'); + await closed(); const rule = component.rules[0]; expect(rule).toMatchObject({ configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit }); expect(component.getRuleSummary(rule)).toBe( @@ -92,9 +74,9 @@ describe('work-sequence rule editor and reload', () => { }); component.startEdit(rule, new Event('click')); await fixture.whenStable(); - await setInput('input[type="number"]', '3'); - component.saveEdit(); - await fixture.whenStable(); + await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '3'); + await clickDialogButton(fixture, 'Enregistrer'); + await closed(); expect(component.getRuleSummary(component.rules[0])).toContain( 'pour atteindre 3 jours ouvrés', ); @@ -105,11 +87,11 @@ describe('work-sequence rule editor and reload', () => { component.startAddNew(RuleType.OPTIMIZATION); await fixture.whenStable(); - await setInput('input:not([type="number"])', 'Ma séquence maximale'); + await typeInDialog(fixture, 'Nom de la règle', 'Ma séquence maximale'); await choose('Éléments du planning', 'Séquences de travail'); await choose('Agrégation', 'Maximum'); - component.saveEdit(); - await fixture.whenStable(); + await clickDialogButton(fixture, 'Ajouter'); + await closed(); const maximum = component.rules[1]; expect(maximum).toMatchObject({ configuration: OPTIMIZATION_PRESETS.longestWorkSequence }); component.toggleRule(maximum.id); @@ -140,16 +122,16 @@ describe('work-sequence rule editor and reload', () => { it('keeps the saved threshold and shows an accessible error for fractional input', async () => { component.startAddNew(RuleType.OPTIMIZATION); - component.changeOptimizationMeasure('work-sequence-deficit'); - await fixture.whenStable(); - await setInput('input[type="number"]', '1.5'); - component.saveEdit(); await fixture.whenStable(); + await choose('Éléments du planning', 'Séquences de travail'); + await choose('Mesure', 'Déficit des séquences de travail'); + await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '1.5'); + await clickDialogButton(fixture, 'Ajouter'); expect(component.rules).toEqual([]); - expect(fixture.nativeElement.querySelector('[role="alert"]').textContent).toContain( + expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain( 'seuil entier positif', ); - expect(fixture.nativeElement.querySelector('input[type="number"]').value).toBe('1.5'); + expect(threshold().value).toBe('1.5'); }); it('distinguishes aggregation units from the working-day threshold', () => { diff --git a/src/testing/rule-dialog.ts b/src/testing/rule-dialog.ts new file mode 100644 index 0000000..f30d66c --- /dev/null +++ b/src/testing/rule-dialog.ts @@ -0,0 +1,64 @@ +import type { ComponentFixture } from '@angular/core/testing'; + +/** Drives the rule dialog, which Material renders in an overlay outside the panel's fixture. */ +export const ruleDialog = () => document.querySelector('mat-dialog-container'); + +function openDialog(): HTMLElement { + const dialog = ruleDialog(); + if (!dialog) throw new Error('The rule dialog is not open'); + return dialog; +} + +export function dialogField(label: string, index = 0): HTMLElement { + const field = Array.from(openDialog().querySelectorAll('mat-form-field')).filter( + (candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label, + )[index]; + if (!field) throw new Error(`Missing labelled control: ${label}`); + return field; +} + +export function dialogButton(text: string): HTMLButtonElement { + const button = Array.from(openDialog().querySelectorAll('button')).find( + (candidate) => candidate.textContent?.trim() === text, + ); + if (!button) throw new Error(`Missing dialog button: ${text}`); + return button; +} + +export async function typeInDialog( + fixture: ComponentFixture, + label: string, + value: string, + index = 0, +) { + const input = dialogField(label, index).querySelector('input')!; + input.value = value; + input.dispatchEvent(new Event('input', { bubbles: true })); + await fixture.whenStable(); +} + +export async function chooseInDialog( + fixture: ComponentFixture, + label: string, + text: string, + index = 0, +) { + const control = dialogField(label, index).querySelector('mat-select'); + if (!control) throw new Error(`Missing select: ${label}`); + control.click(); + await fixture.whenStable(); + const option = Array.from(document.querySelectorAll('mat-option')).find( + (candidate) => candidate.textContent?.trim() === text, + ); + if (!option) throw new Error(`Missing option: ${text}`); + option.click(); + await fixture.whenStable(); + // A multiple select stays open; its transparent backdrop is not the dialog's own. + document.querySelector('.cdk-overlay-transparent-backdrop')?.click(); + await fixture.whenStable(); +} + +export async function clickDialogButton(fixture: ComponentFixture, text: string) { + dialogButton(text).click(); + await fixture.whenStable(); +} -- 2.54.0 From bde65fc90ef791d4ac36d183c94ae115783a00c2 Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 15:16:59 +0100 Subject: [PATCH 08/12] feat(rules): word the supplied optimization rules by their intent (#357) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The six supplied optimization compositions now say what the planner does for the person ("Raccourcir la plus longue période travaillée d'affilée") instead of naming the measure it moves. A rule matches when its elements, measure, aggregation, direction and conditions equal a supplied rule; the deficit threshold stays a placeholder, so a custom threshold keeps the intent. Other compositions keep their generic sentence, and the public-holiday-week phrases now explain their points per holiday. Co-Authored-By: Claude Opus 5.5 --- .../calendar-year-planning.spec.ts | 2 +- .../rules-panel/rules-panel.spec.ts | 14 +++--- .../work-sequence-rule-editor.spec.ts | 4 +- src/app/services/planner-labels.spec.ts | 48 ++++++++++++++----- src/app/services/planner-labels.ts | 38 +++++++++++---- src/app/services/translation-service.ts | 2 + src/i18n/de.json | 12 ++++- src/i18n/en.json | 12 ++++- src/i18n/es.json | 12 ++++- src/i18n/fr.json | 12 ++++- 10 files changed, 117 insertions(+), 39 deletions(-) diff --git a/src/app/components/calendar-year/calendar-year-planning.spec.ts b/src/app/components/calendar-year/calendar-year-planning.spec.ts index 8ab196b..e0258a8 100644 --- a/src/app/components/calendar-year/calendar-year-planning.spec.ts +++ b/src/app/components/calendar-year/calendar-year-planning.spec.ts @@ -3475,7 +3475,7 @@ describe('CalendarYear planning outcome boundary', () => { row.textContent?.includes('Gain — '), )!; expect(gainRow.textContent?.trim()).toBe( - 'Gain — Increase weekend days and public holidays within time-off periods', + 'Gain — Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave', ); expect(gainRow.querySelector('small')).toBeNull(); expect(element.querySelector('.day-impact')?.textContent).toContain( diff --git a/src/app/components/rules-panel/rules-panel.spec.ts b/src/app/components/rules-panel/rules-panel.spec.ts index a1ef66b..9ca629e 100644 --- a/src/app/components/rules-panel/rules-panel.spec.ts +++ b/src/app/components/rules-panel/rules-panel.spec.ts @@ -52,16 +52,16 @@ describe('RulesPanel', () => { it('describes the supplied rules in plain words in every language', () => { const summaries = () => component.rules.map((rule) => component.getRuleSummary(rule)); expect(summaries()).toEqual([ - 'Réduire les jours non posés expirant pendant la période planifiée.', + 'Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre.', 'Si un jour férié tombe un samedi, poser 2 jours de congés payés au mieux autour et gagner 1 jour de type Autre.', expect.stringMatching( /^Poser 5 jours de congé de tout type<\/strong> entre le 20\/12\/\d{4}<\/strong> et le 03\/01\/\d{4}<\/strong>\.$/, ), - 'Augmenter la valeur des semaines avec un jour férié prises en entier, plus forte pour un férié en milieu de semaine.', - 'Augmenter les jours de week-end et fériés compris dans les périodes de repos.', - 'Réduire la plus longue séquence de travail.', - 'Réduire les jours qui manquent aux séquences de travail entre deux périodes de repos pour atteindre 5 jours ouvrés.', - 'Réduire le nombre de jours posés en plus sur des soldes expirant après la période planifiée.', + 'Prendre la semaine entière quand elle contient un jour férié, en priorité si le férié tombe en milieu de semaine.', + 'Coller les congés aux week-ends et aux jours fériés, pour allonger les périodes de repos avec des jours qui ne coûtent aucun congé.', + 'Raccourcir la plus longue période travaillée d’affilée.', + 'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos.', + 'Garder pour plus tard les jours qui n’expirent pas pendant la période planifiée : en poser le moins possible.', ]); const translations = TestBed.inject(TranslationService); for (const language of translations.availableLanguages) { @@ -145,7 +145,7 @@ describe('RulesPanel', () => { configuration: OPTIMIZATION_PRESETS.unplacedAtRisk, }); expect(component.getRuleSummary(rule)).toBe( - 'Réduire les jours non posés expirant pendant la période planifiée.', + 'Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre.', ); const announce = vi.spyOn(TestBed.inject(LiveAnnouncer), 'announce').mockResolvedValue(); const buttons = fixture.nativeElement.querySelectorAll('.rule-item'); diff --git a/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts b/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts index 179d807..e6275ec 100644 --- a/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts +++ b/src/app/components/rules-panel/work-sequence-rule-editor.spec.ts @@ -61,7 +61,7 @@ describe('work-sequence rule editor and reload', () => { const rule = component.rules[0]; expect(rule).toMatchObject({ configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit }); expect(component.getRuleSummary(rule)).toBe( - 'Réduire les jours qui manquent aux séquences de travail entre deux périodes de repos pour atteindre 5 jours ouvrés.', + 'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos.', ); const request = { horizon: { start: '2024-01-08', end: '2024-01-13' }, @@ -78,7 +78,7 @@ describe('work-sequence rule editor and reload', () => { await clickDialogButton(fixture, 'Enregistrer'); await closed(); expect(component.getRuleSummary(component.rules[0])).toContain( - 'pour atteindre 3 jours ouvrés', + 'pour moins de 3 jours ouvrés', ); expect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({ kind: 'Plan', diff --git a/src/app/services/planner-labels.spec.ts b/src/app/services/planner-labels.spec.ts index e054f3e..866c1d6 100644 --- a/src/app/services/planner-labels.spec.ts +++ b/src/app/services/planner-labels.spec.ts @@ -214,7 +214,7 @@ describe('planning stage label', () => { it('names an optimization stage after its rule and its goal', () => { expect(stageLabel(en, source, 'optimization:gain')).toBe( - 'More days off — Increase weekend days and public holidays within time-off periods', + 'More days off — Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave', ); }); @@ -301,7 +301,7 @@ describe('objective copy', () => { it('names an optimization after its rule and its goal, keeping its composition technical', () => { expect(objectiveCopy(en, source, 'optimization:gain')).toEqual({ - label: 'More days off — Increase weekend days and public holidays within time-off periods', + label: 'More days off — Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave', technical: optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain), }); }); @@ -396,7 +396,7 @@ describe('optimization goal', () => { ), ); - it('words the supplied rules in plain French', () => { + it('says in French what the supplied rules do for the person', () => { const goals = Object.fromEntries( Object.entries(OPTIMIZATION_PRESETS).map(([key, configuration]) => [ key, @@ -404,28 +404,51 @@ describe('optimization goal', () => { ]), ); expect(goals).toEqual({ - unplacedAtRisk: 'Réduire les jours non posés expirant pendant la période planifiée', + unplacedAtRisk: + 'Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre', holidayWeekValue: - 'Augmenter la valeur des semaines avec un jour férié prises en entier, plus forte pour un férié en milieu de semaine', + 'Prendre la semaine entière quand elle contient un jour férié, en priorité si le férié tombe en milieu de semaine', nonWorkingDayGain: - 'Augmenter les jours de week-end et fériés compris dans les périodes de repos', - longestWorkSequence: 'Réduire la plus longue séquence de travail', + 'Coller les congés aux week-ends et aux jours fériés, pour allonger les périodes de repos avec des jours qui ne coûtent aucun congé', + longestWorkSequence: 'Raccourcir la plus longue période travaillée d’affilée', shortSequenceDeficit: - 'Réduire les jours qui manquent aux séquences de travail entre deux périodes de repos pour atteindre 5 jours ouvrés', + 'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos', supportingPlacements: - 'Réduire le nombre de jours posés en plus sur des soldes expirant après la période planifiée', + 'Garder pour plus tard les jours qui n’expirent pas pendant la période planifiée : en poser le moins possible', }); }); + it('keeps the intent of a supplied rule with another threshold, and only for its composition', () => { + const deficit = OPTIMIZATION_PRESETS.shortSequenceDeficit; + expect(optimizationGoal(fr, { ...deficit, thresholdDays: 3 })).toBe( + 'Éviter de reprendre le travail pour moins de 3 jours ouvrés entre deux périodes de repos', + ); + expect(optimizationGoal(fr, { ...deficit, aggregation: 'maximum' })).toBe( + 'Réduire le plus grand nombre de jours qui manquent à une séquence de travail entre deux périodes de repos pour atteindre 5 jours ouvrés', + ); + expect( + optimizationGoal(fr, { ...OPTIMIZATION_PRESETS.unplacedAtRisk, conditions: [] }), + ).toBe('Réduire les jours non posés'); + }); + it.each(Object.keys(translationsMap))( 'words every valid composition without engine terms in %s', (language) => { const tr = translationsMap[language]; const rules = tr.rules.optimization; expect(compositions).toHaveLength(90); + const intents = Object.values(rules.plain.intents).map((intent) => + intent.replace('{threshold}', plural(tr, rules.plain.workingDays, 3)), + ); + let supplied = 0; for (const configuration of compositions) { const goal = optimizationGoal(tr, configuration); expect(goal).toMatch(/^\p{Lu}[^{}]+$/u); + // The supplied compositions are worded by intent rather than by their parts. + if (intents.includes(goal!)) { + supplied++; + continue; + } expect(goal).not.toContain(rules.directions[configuration.direction]); expect(goal).not.toContain(' — '); for (const condition of configuration.conditions) @@ -437,6 +460,7 @@ describe('optimization goal', () => { ) expect(goal).toContain(plural(tr, rules.plain.workingDays, 3)); } + expect(supplied).toBe(Object.keys(OPTIMIZATION_PRESETS).length); }, ); @@ -453,10 +477,10 @@ describe('optimization goal', () => { it('puts the threshold in the singular or plural of the language', () => { const deficit = { ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 1 }; - expect(optimizationGoal(fr, deficit)).toContain('pour atteindre 1 jour ouvré'); - expect(optimizationGoal(en, deficit)).toContain('to reach 1 working day'); + expect(optimizationGoal(fr, deficit)).toContain('pour moins de 1 jour ouvré'); + expect(optimizationGoal(en, deficit)).toContain('for fewer than 1 working day'); expect(optimizationGoal(en, { ...deficit, thresholdDays: 2 })).toContain( - 'to reach 2 working days', + 'for fewer than 2 working days', ); }); diff --git a/src/app/services/planner-labels.ts b/src/app/services/planner-labels.ts index 97c60bc..c539680 100644 --- a/src/app/services/planner-labels.ts +++ b/src/app/services/planner-labels.ts @@ -6,6 +6,7 @@ import type { PlanningSnapshot, } from './leave-planner.service'; import { + OPTIMIZATION_PRESETS, optimizationUnit, validateOptimizationConfiguration, type OptimizationCondition, @@ -108,13 +109,39 @@ export function optimizationSummary(tr: AppTranslations, configuration: Optimiza .replace('{conditions}', conditions.length ? ` (${conditions.join(', ')})` : ''); } -/** What an optimization rule aims for, in everyday words; undefined for an invalid configuration. */ +/** The supplied rule whose composition a configuration repeats, whatever its threshold. */ +function presetOf(configuration: OptimizationConfiguration) { + return (Object.keys(OPTIMIZATION_PRESETS) as (keyof typeof OPTIMIZATION_PRESETS)[]).find( + (key) => { + const preset: OptimizationConfiguration = OPTIMIZATION_PRESETS[key]; + return ( + preset.elements === configuration.elements && + preset.measure === configuration.measure && + preset.aggregation === configuration.aggregation && + preset.direction === configuration.direction && + preset.conditions.length === configuration.conditions.length && + preset.conditions.every((condition) => configuration.conditions.includes(condition)) + ); + }, + ); +} + +/** + * What an optimization rule aims for, in everyday words; undefined for an invalid configuration. + * The supplied compositions say what the planner does for the person; others describe their measure. + */ export function optimizationGoal( tr: AppTranslations, configuration: OptimizationConfiguration, ): string | undefined { if (!validateOptimizationConfiguration(configuration).valid) return undefined; const plain = tr.rules.optimization.plain; + const threshold = + configuration.measure === 'work-sequence-deficit' + ? plural(tr, plain.workingDays, configuration.thresholdDays) + : ''; + const preset = presetOf(configuration); + if (preset) return plain.intents[preset].replace('{threshold}', threshold); const { aggregation, conditions } = configuration; // Qualifiers follow the key order of the translation. An empty work sequence adds nothing to a // sum or a maximum, so leaving it out only changes a count. @@ -132,14 +159,7 @@ export function optimizationGoal( : plain.quantities[configuration.measure][aggregation]; return plain.goals[configuration.direction].replace( '{quantity}', - quantity - .replace('{scope}', scope) - .replace( - '{threshold}', - configuration.measure === 'work-sequence-deficit' - ? plural(tr, plain.workingDays, configuration.thresholdDays) - : '', - ), + quantity.replace('{scope}', scope).replace('{threshold}', threshold), ); } diff --git a/src/app/services/translation-service.ts b/src/app/services/translation-service.ts index 756ba08..178cbeb 100644 --- a/src/app/services/translation-service.ts +++ b/src/app/services/translation-service.ts @@ -9,6 +9,7 @@ import { addPlanningDays } from './planning-date'; import type { SelectableDayType } from './calendar-service'; import type { PlacementStrategy } from './rule-service'; import { + type OPTIMIZATION_PRESETS, type OptimizationElements, type OptimizationCondition, type OptimizationMeasure, @@ -112,6 +113,7 @@ export interface AppTranslations { directions: Record; plain: { goals: Record; + intents: Record; count: string; elements: Record; quantities: Record>; diff --git a/src/i18n/de.json b/src/i18n/de.json index f142ae4..c131178 100644 --- a/src/i18n/de.json +++ b/src/i18n/de.json @@ -191,6 +191,14 @@ "minimize": "{quantity} verringern", "maximize": "{quantity} erhöhen" }, + "intents": { + "unplacedAtRisk": "Tage, die im Planungszeitraum verfallen, zuerst einplanen, damit keiner verloren geht", + "holidayWeekValue": "Die ganze Woche freinehmen, wenn sie einen Feiertag enthält, vor allem wenn der Feiertag mitten in der Woche liegt", + "nonWorkingDayGain": "Urlaub an Wochenenden und Feiertage anschließen, um Auszeiten mit Tagen zu verlängern, die keinen Urlaub kosten", + "longestWorkSequence": "Die längste Arbeitsphase am Stück verkürzen", + "shortSequenceDeficit": "Kurze Arbeitsphasen mit weniger als {threshold} zwischen zwei Auszeiten vermeiden", + "supportingPlacements": "Tage, die nicht im Planungszeitraum verfallen, für später aufheben: möglichst wenige davon nehmen" + }, "count": "Anzahl der {elements}{scope}", "elements": { "leave-balances": "Urlaubsguthaben", @@ -205,8 +213,8 @@ "maximum": "Höchste Zahl ungenutzter Tage auf einem Guthaben{scope}" }, "public-holiday-week-value": { - "sum": "Wert der Feiertagswochen{scope} (Feiertage mitten in der Woche zählen mehr)", - "maximum": "Wert der besten Feiertagswoche{scope} (Feiertage mitten in der Woche zählen mehr)" + "sum": "Punkte der Feiertagswochen{scope} (je Feiertag 1 am Montag oder Freitag bis 3 am Mittwoch)", + "maximum": "Punkte der besten Feiertagswoche{scope} (je Feiertag 1 am Montag oder Freitag bis 3 am Mittwoch)" }, "non-working-day-gain": { "sum": "Wochenend- und Feiertage in den Auszeiten", diff --git a/src/i18n/en.json b/src/i18n/en.json index 8da0e1d..72a9f45 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -191,6 +191,14 @@ "minimize": "Reduce {quantity}", "maximize": "Increase {quantity}" }, + "intents": { + "unplacedAtRisk": "Use the days that expire within the planning period first, so that none are lost", + "holidayWeekValue": "Take the whole week off when it contains a public holiday, especially when the holiday falls midweek", + "nonWorkingDayGain": "Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave", + "longestWorkSequence": "Shorten the longest stretch of consecutive working days", + "shortSequenceDeficit": "Avoid going back to work for fewer than {threshold} between two time-off periods", + "supportingPlacements": "Keep the days that do not expire within the planning period for later: use as few of them as possible" + }, "count": "the number of {elements}{scope}", "elements": { "leave-balances": "leave balances", @@ -205,8 +213,8 @@ "maximum": "the largest number of unused days left on one balance{scope}" }, "public-holiday-week-value": { - "sum": "the value of public-holiday weeks{scope}, higher for a midweek holiday", - "maximum": "the value of the best public-holiday week{scope}, higher for a midweek holiday" + "sum": "the points of public-holiday weeks{scope}, each holiday scoring from 1 (Monday, Friday) to 3 (Wednesday)", + "maximum": "the points of the best public-holiday week{scope}, each holiday scoring from 1 (Monday, Friday) to 3 (Wednesday)" }, "non-working-day-gain": { "sum": "weekend days and public holidays within time-off periods", diff --git a/src/i18n/es.json b/src/i18n/es.json index 7a41519..84e9723 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -191,6 +191,14 @@ "minimize": "Reducir {quantity}", "maximize": "Aumentar {quantity}" }, + "intents": { + "unplacedAtRisk": "Usar primero los días que vencen durante el período de planificación, para no perderlos", + "holidayWeekValue": "Tomar la semana entera cuando incluye un festivo, sobre todo si el festivo cae a mitad de semana", + "nonWorkingDayGain": "Pegar las vacaciones a los fines de semana y festivos, para alargar los períodos de descanso con días que no gastan vacaciones", + "longestWorkSequence": "Acortar el tramo más largo de días trabajados seguidos", + "shortSequenceDeficit": "Evitar volver al trabajo durante menos de {threshold} entre dos períodos de descanso", + "supportingPlacements": "Guardar para más adelante los días que no vencen durante el período de planificación: usar el menor número posible de ellos" + }, "count": "el número de {elements}{scope}", "elements": { "leave-balances": "saldos de vacaciones", @@ -205,8 +213,8 @@ "maximum": "el mayor número de días sin usar de un mismo saldo{scope}" }, "public-holiday-week-value": { - "sum": "el valor de las semanas con festivo{scope}, mayor si el festivo cae a mitad de semana", - "maximum": "el valor de la mejor semana con festivo{scope}, mayor si el festivo cae a mitad de semana" + "sum": "los puntos de las semanas con festivo{scope}, de 1 por festivo en lunes o viernes a 3 en miércoles", + "maximum": "los puntos de la mejor semana con festivo{scope}, de 1 por festivo en lunes o viernes a 3 en miércoles" }, "non-working-day-gain": { "sum": "los días de fin de semana y festivos incluidos en los períodos de descanso", diff --git a/src/i18n/fr.json b/src/i18n/fr.json index 7a61753..29c04f9 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -191,6 +191,14 @@ "minimize": "Réduire {quantity}", "maximize": "Augmenter {quantity}" }, + "intents": { + "unplacedAtRisk": "Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre", + "holidayWeekValue": "Prendre la semaine entière quand elle contient un jour férié, en priorité si le férié tombe en milieu de semaine", + "nonWorkingDayGain": "Coller les congés aux week-ends et aux jours fériés, pour allonger les périodes de repos avec des jours qui ne coûtent aucun congé", + "longestWorkSequence": "Raccourcir la plus longue période travaillée d’affilée", + "shortSequenceDeficit": "Éviter de reprendre le travail pour moins de {threshold} entre deux périodes de repos", + "supportingPlacements": "Garder pour plus tard les jours qui n’expirent pas pendant la période planifiée : en poser le moins possible" + }, "count": "le nombre de {elements}{scope}", "elements": { "leave-balances": "soldes de congés", @@ -205,8 +213,8 @@ "maximum": "le plus grand nombre de jours non posés d’un même solde{scope}" }, "public-holiday-week-value": { - "sum": "la valeur des semaines avec un jour férié{scope}, plus forte pour un férié en milieu de semaine", - "maximum": "la valeur de la meilleure des semaines avec un jour férié{scope}, plus forte pour un férié en milieu de semaine" + "sum": "les points des semaines avec un jour férié{scope}, chaque férié valant de 1 point (lundi, vendredi) à 3 points (mercredi)", + "maximum": "les points de la meilleure des semaines avec un jour férié{scope}, chaque férié valant de 1 point (lundi, vendredi) à 3 points (mercredi)" }, "non-working-day-gain": { "sum": "les jours de week-end et fériés compris dans les périodes de repos", -- 2.54.0 From aa3ef003414e6e866c93c3c6e6f68143e29782e5 Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 15:17:10 +0100 Subject: [PATCH 09/12] feat(ui): switch between configuration and plan from a bottom bar on narrow viewports (#359) Below 75rem only the chosen view is displayed, and a bar fixed to the bottom of the viewport offers the configuration / plan switch and Calculate. The page opens on the plan unless there is nothing to plan. Calculate in the bar shows the plan and focuses its heading. Declared non-working days are entered on the plan's calendar with the type and erase choices in the bar. The skip link now shows the plan, and the "go to your plan" link in the configuration is removed. Calculate and the declaration controls become shared components, so that the panel and the bar use the same markup and rules. The bar's measured height reserves space at the end of the page and as scroll padding, so that it never covers content or a focused element. The two-column layout is unchanged. Co-Authored-By: Claude Opus 5.5 --- src/app/app.html | 32 ++++- src/app/app.scss | 72 +++++++++++ src/app/app.spec.ts | 114 +++++++++++++++++- src/app/app.ts | 74 ++++++++++++ .../calculate-button/calculate-button.html | 20 +++ .../calculate-button/calculate-button.scss | 11 ++ .../calculate-button/calculate-button.ts | 32 +++++ .../components/calendar-year/calendar-year.ts | 7 +- .../declaration-controls.html | 40 ++++++ .../declaration-controls.scss | 80 ++++++++++++ .../declaration-controls.ts | 24 ++++ src/app/components/user-input/user-input.html | 69 +---------- src/app/components/user-input/user-input.scss | 114 +----------------- .../components/user-input/user-input.spec.ts | 18 ++- src/app/components/user-input/user-input.ts | 13 +- src/app/services/translation-service.ts | 3 + src/i18n/de.json | 5 +- src/i18n/en.json | 5 +- src/i18n/es.json | 5 +- src/i18n/fr.json | 5 +- src/styles.scss | 2 + 21 files changed, 544 insertions(+), 201 deletions(-) create mode 100644 src/app/components/calculate-button/calculate-button.html create mode 100644 src/app/components/calculate-button/calculate-button.scss create mode 100644 src/app/components/calculate-button/calculate-button.ts create mode 100644 src/app/components/declaration-controls/declaration-controls.html create mode 100644 src/app/components/declaration-controls/declaration-controls.scss create mode 100644 src/app/components/declaration-controls/declaration-controls.ts diff --git a/src/app/app.html b/src/app/app.html index 0877f36..58cbd05 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -1,6 +1,8 @@ @if (showPlanner()) {
- +
@@ -21,7 +23,7 @@
-
+
+
+ @if (declarationEntry() && view() === 'plan') { + + } +
+
+ + +
+ +
+
} diff --git a/src/app/app.scss b/src/app/app.scss index cdc20e9..667daa0 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -103,11 +103,83 @@ app-calendar-year { } } +// Below 75rem, only the chosen view is displayed; the bar at the bottom switches it and calculates. +@media (width < 75rem) { + .app-shell { + padding-block-end: var(--action-bar-height, 0px); + } + + .planner-layout[data-view='plan'] .configuration-panel, + .planner-layout[data-view='configuration'] .results-panel { + display: none; + } +} + +.action-bar { + position: fixed; + inset: auto 0 0; + z-index: 2; + display: grid; + gap: 0.5rem; + padding: 0.5rem var(--workspace-gutter) calc(0.5rem + env(safe-area-inset-bottom, 0px)); + background: var(--ui-card-bg); + border-block-start: 1px solid var(--ui-border); + box-shadow: 0 -0.25rem 1rem rgb(0 0 0 / 8%); +} + +.action-bar-row { + display: flex; + align-items: stretch; + gap: 0.5rem; + + app-calculate-button { + flex: 1; + min-width: 0; + } +} + +.view-switch { + display: flex; + flex-shrink: 0; + gap: 0.25rem; + padding: 0.25rem; + border: 1px solid var(--ui-border); + border-radius: var(--ui-radius-sm); + background: var(--ui-panel-bg); + + button { + display: grid; + justify-items: center; + align-content: center; + min-width: 4.5rem; + min-height: 2.75rem; + padding: 0.125rem 0.5rem; + border: 0; + border-radius: 0.375rem; + background: transparent; + color: var(--ui-text-secondary); + font: inherit; + font-size: 0.75rem; + font-weight: 600; + line-height: 1.25; + cursor: pointer; + + &[aria-pressed='true'] { + background: var(--mat-sys-primary-container); + color: var(--mat-sys-on-primary-container); + } + } +} + @media (min-width: 75rem) { .planner-layout { grid-template-columns: clamp(26rem, 34%, 40rem) minmax(0, 1fr); } + .action-bar { + display: none; + } + // 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 { diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index 89e07c2..a29ce45 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -1,7 +1,9 @@ import { provideZonelessChangeDetection } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { ScrollDispatcher } from '@angular/cdk/scrolling'; +import { vi } from '../testing/vitest-compat'; import { App } from './app'; +import { PlanningCalculationService } from './services/planning-calculation.service'; import { TranslationService } from './services/translation-service'; describe('App', () => { @@ -13,7 +15,8 @@ describe('App', () => { }); afterEach(() => { - localStorage.removeItem('app.language'); + vi.restoreAllMocks(); + localStorage.clear(); document.documentElement.lang = 'en'; }); @@ -60,4 +63,113 @@ describe('App', () => { history.replaceState({}, '', originalPath); } }); + + describe('narrow layout views', () => { + const balance = { + id: 'b1', + type: 'cp', + numberOfDays: 3, + availableDate: '2026-01-01', + expiryDate: '2026-12-31', + }; + + async function render(balances: unknown[]) { + localStorage.setItem('leaveBalances', JSON.stringify(balances)); + const calculate = vi + .spyOn(TestBed.inject(PlanningCalculationService), 'createPlanningCalculation') + .mockImplementation(() => ({ outcome: new Promise(() => undefined) }) as never); + vi.spyOn(window, 'scrollTo').mockImplementation(() => undefined); + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + await fixture.whenStable(); + const root = fixture.nativeElement as HTMLElement; + const view = () => root.querySelector('.planner-layout')?.getAttribute('data-view'); + const bar = root.querySelector('.action-bar')!; + const [configuration, plan] = + bar.querySelectorAll('.view-switch button'); + const settle = async () => { + fixture.detectChanges(); + await fixture.whenStable(); + }; + return { root, view, bar, configuration, plan, calculate, settle }; + } + + it('opens on the configuration when there is nothing to plan, and on the plan being calculated otherwise', async () => { + const empty = await render([]); + expect(empty.view()).toBe('configuration'); + expect(empty.configuration.getAttribute('aria-pressed')).toBe('true'); + expect(empty.plan.getAttribute('aria-pressed')).toBe('false'); + expect(empty.calculate).not.toHaveBeenCalled(); + expect(empty.bar.querySelector('.calculate-button')!.disabled).toBe( + true, + ); + TestBed.resetTestingModule(); + await TestBed.configureTestingModule({ + imports: [App], + providers: [provideZonelessChangeDetection()], + }).compileComponents(); + const planned = await render([balance]); + expect(planned.view()).toBe('plan'); + expect(planned.calculate).toHaveBeenCalledOnce(); + }); + + it('switches views from the bar, and its Calculate shows the plan from its heading', async () => { + const { root, view, bar, configuration, plan, calculate, settle } = await render([ + balance, + ]); + configuration.click(); + await settle(); + expect(view()).toBe('configuration'); + expect(plan.getAttribute('aria-pressed')).toBe('false'); + expect(window.scrollTo).toHaveBeenCalledWith(0, 0); + const barCalculate = bar.querySelector('.calculate-button')!; + expect(barCalculate.getAttribute('aria-describedby')).toBe( + 'planning-duration-estimate', + ); + barCalculate.focus(); + barCalculate.click(); + await settle(); + expect(calculate).toHaveBeenCalledTimes(2); + expect(view()).toBe('plan'); + expect(plan.getAttribute('aria-pressed')).toBe('true'); + expect(document.activeElement).toBe(root.querySelector('#planning-results-title')); + }); + + it('shows the plan and its heading from the skip link', async () => { + const { root, view, configuration, settle } = await render([balance]); + configuration.click(); + await settle(); + root.querySelector('.skip-link')!.click(); + await settle(); + expect(view()).toBe('plan'); + expect(document.activeElement).toBe(root.querySelector('#planning-results-title')); + expect(root.querySelector('.jump-to-plan')).toBeNull(); + }); + + it('enters declared days on the plan with the type choices in the bar, then keeps focus in the bar', async () => { + const { root, view, bar, configuration, plan, settle } = await render([balance]); + configuration.click(); + await settle(); + expect(bar.querySelector('app-declaration-controls')).toBeNull(); + root.querySelector( + '.configuration-panel .declaration-entry-toggle', + )!.click(); + await settle(); + expect(view()).toBe('plan'); + const controls = bar.querySelector('app-declaration-controls')!; + expect( + [ + ...controls.querySelectorAll('[data-declared-type], [data-declaration-erase]'), + ].map((button) => button.textContent?.trim()), + ).toEqual(['check CP', 'check RTT', 'check Other', 'backspace Erase']); + const finish = controls.querySelector('.declaration-entry-toggle')!; + expect(finish.getAttribute('aria-pressed')).toBe('true'); + finish.focus(); + finish.click(); + await settle(); + expect(bar.querySelector('app-declaration-controls')).toBeNull(); + expect(view()).toBe('plan'); + expect(document.activeElement).toBe(plan); + }); + }); }); diff --git a/src/app/app.ts b/src/app/app.ts index f5e3c75..0ce80df 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,10 +1,15 @@ import { + afterNextRender, ChangeDetectionStrategy, Component, DOCUMENT, effect, + ElementRef, inject, + Injector, + linkedSignal, signal, + viewChild, } from '@angular/core'; import { CdkScrollable } from '@angular/cdk/scrolling'; import { MatDatepickerModule } from '@angular/material/datepicker'; @@ -12,12 +17,18 @@ import { provideNativeDateAdapter } from '@angular/material/core'; import { UserInput } from './components/user-input/user-input'; import { CalendarYear } from './components/calendar-year/calendar-year'; import { UserSettings } from './components/user-settings/user-settings'; +import { CalculateButton } from './components/calculate-button/calculate-button'; +import { DeclarationControls } from './components/declaration-controls/declaration-controls'; import { MatButton } from '@angular/material/button'; import { MatDialog } from '@angular/material/dialog'; import { MatIcon } from '@angular/material/icon'; import { NavigationEnd, Router, RouterOutlet } from '@angular/router'; import { TranslationService } from './services/translation-service'; import { ThemeService } from './services/theme-service'; +import { UserInputService } from './services/user-input-service'; + +/** Below 75rem, only one of the configuration and the plan is displayed. */ +type PlannerView = 'configuration' | 'plan'; function isBenchmarkUrl(url: string): boolean { return url.split(/[?#]/, 1)[0].replace(/\/+$/, '') === '/benchmark'; @@ -30,6 +41,8 @@ function isBenchmarkUrl(url: string): boolean { MatDatepickerModule, UserInput, CalendarYear, + CalculateButton, + DeclarationControls, MatButton, MatIcon, RouterOutlet, @@ -44,6 +57,18 @@ export class App { private readonly dialog = inject(MatDialog); private readonly document = inject(DOCUMENT); private readonly translations = inject(TranslationService); + private readonly injector = inject(Injector); + private readonly userInput = inject(UserInputService); + private readonly actionBar = viewChild>('actionBar'); + protected readonly declarationEntry = this.userInput.declarationEntrySignal; + /** The plan unless there is nothing to plan yet; declared days are entered on the plan's calendar. */ + protected readonly view = linkedSignal({ + source: this.declarationEntry, + computation: (entry, previous) => + entry + ? 'plan' + : (previous?.value ?? (this.userInput.nothingToPlan() ? 'configuration' : 'plan')), + }); protected readonly tr = this.translations.tr; protected readonly title = signal('VacOptimizer'); protected readonly showPlanner = signal( @@ -57,6 +82,55 @@ export class App { if (event instanceof NavigationEnd) this.showPlanner.set(!isBenchmarkUrl(event.urlAfterRedirects)); }); + effect((onCleanup) => { + const bar = this.actionBar()?.nativeElement; + if (!bar || typeof ResizeObserver === 'undefined') return; + // The fixed bar must not hide the end of the page or a focused element: see styles.scss. + const observer = new ResizeObserver(() => + this.document.documentElement.style.setProperty( + '--action-bar-height', + `${bar.offsetHeight}px`, + ), + ); + observer.observe(bar, { box: 'border-box' }); + onCleanup(() => { + observer.disconnect(); + this.document.documentElement.style.removeProperty('--action-bar-height'); + }); + }); + effect(() => { + this.view(); + this.declarationEntry(); + const focused = this.document.activeElement; + if (!(focused instanceof HTMLElement) || focused === this.document.body) return; + // A control that hides its own panel, or the bar's copy of the declaration controls, loses focus: + // move it to the bar's current choice instead of the start of the page. + afterNextRender( + () => { + const active = this.document.activeElement; + if (focused.isConnected && focused.checkVisibility?.() !== false) return; + if (active !== focused && active !== this.document.body) return; + this.actionBar() + ?.nativeElement.querySelector('[aria-pressed="true"]') + ?.focus(); + }, + { injector: this.injector }, + ); + }); + } + + protected show(view: PlannerView): void { + if (view === this.view()) return; + this.view.set(view); + this.document.defaultView?.scrollTo?.(0, 0); + } + + /** After Calculate in the bar, or the skip link: the plan, with its loading state and Cancel, from its heading. */ + protected showPlanHeading(): void { + this.view.set('plan'); + afterNextRender(() => this.document.getElementById('planning-results-title')?.focus(), { + injector: this.injector, + }); } protected openSettings(): void { diff --git a/src/app/components/calculate-button/calculate-button.html b/src/app/components/calculate-button/calculate-button.html new file mode 100644 index 0000000..dee6c93 --- /dev/null +++ b/src/app/components/calculate-button/calculate-button.html @@ -0,0 +1,20 @@ + diff --git a/src/app/components/calculate-button/calculate-button.scss b/src/app/components/calculate-button/calculate-button.scss new file mode 100644 index 0000000..344ad23 --- /dev/null +++ b/src/app/components/calculate-button/calculate-button.scss @@ -0,0 +1,11 @@ +// A grid, so that the button is laid out as a block, as it was as a direct child of its bar. +:host { + display: grid; +} + +.calculate-button { + width: 100%; + min-height: 3.25rem; + border-radius: var(--ui-radius-sm); + font-weight: 600; +} diff --git a/src/app/components/calculate-button/calculate-button.ts b/src/app/components/calculate-button/calculate-button.ts new file mode 100644 index 0000000..cfe849a --- /dev/null +++ b/src/app/components/calculate-button/calculate-button.ts @@ -0,0 +1,32 @@ +import { ChangeDetectionStrategy, Component, inject, output } from '@angular/core'; +import { MatButton } from '@angular/material/button'; +import { MatIcon } from '@angular/material/icon'; +import { CalendarSettingsService } from '../../services/calendar-settings-service'; +import { PlanningCalculationService } from '../../services/planning-calculation.service'; +import { TranslationService } from '../../services/translation-service'; +import { UserInputService } from '../../services/user-input-service'; + +/** + * Calculate, disabled and described by the reason while there is nothing valid to plan. + * The descriptions are the configuration panel's messages, referenced by id even where that panel is hidden. + */ +@Component({ + selector: 'app-calculate-button', + imports: [MatButton, MatIcon], + templateUrl: './calculate-button.html', + styleUrl: './calculate-button.scss', + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class CalculateButton { + protected readonly calendarSettings = inject(CalendarSettingsService); + protected readonly nothingToPlan = inject(UserInputService).nothingToPlan; + private readonly calculations = inject(PlanningCalculationService); + protected readonly tr = inject(TranslationService).tr; + readonly started = output(); + + calculate(): void { + if (this.calendarSettings.planningHorizonError() || this.nothingToPlan()) return; + this.calculations.start(); + this.started.emit(); + } +} diff --git a/src/app/components/calendar-year/calendar-year.ts b/src/app/components/calendar-year/calendar-year.ts index ebc7dc6..bb3240d 100644 --- a/src/app/components/calendar-year/calendar-year.ts +++ b/src/app/components/calendar-year/calendar-year.ts @@ -496,8 +496,11 @@ export class CalendarYear { this.declarationScrollFrame = undefined; const pointer = this.declarationPointer; if (!pointer || !this.declarationDrag()) return; - const direction = - pointer.clientY < 48 ? -1 : pointer.clientY > window.innerHeight - 48 ? 1 : 0; + // The document's scroll padding is the part of the viewport covered by the app's bottom bar. + const bottom = + window.innerHeight - + (parseFloat(getComputedStyle(document.documentElement).scrollPaddingBottom) || 0); + const direction = pointer.clientY < 48 ? -1 : pointer.clientY > bottom - 48 ? 1 : 0; if (!direction || pointer.clientX < 0 || pointer.clientX > window.innerWidth) return; const before = window.scrollY; window.scrollBy(0, direction * (lastFrame ? Math.min(now - lastFrame, 32) : 16) * 0.5); diff --git a/src/app/components/declaration-controls/declaration-controls.html b/src/app/components/declaration-controls/declaration-controls.html new file mode 100644 index 0000000..f021ff8 --- /dev/null +++ b/src/app/components/declaration-controls/declaration-controls.html @@ -0,0 +1,40 @@ + +@if (declarationEntry()) { +
+ @for (type of declaredTypes; track type) { + + } + +
+} diff --git a/src/app/components/declaration-controls/declaration-controls.scss b/src/app/components/declaration-controls/declaration-controls.scss new file mode 100644 index 0000000..ec77d35 --- /dev/null +++ b/src/app/components/declaration-controls/declaration-controls.scss @@ -0,0 +1,80 @@ +:host { + display: grid; + container: declaration-controls / inline-size; + grid-column: 1 / -1; + border: 1px solid var(--ui-border); + border-radius: var(--ui-radius-sm); + background: var(--ui-panel-bg); + + &.is-active { + border-color: var(--mat-sys-primary); + } +} + +.declaration-entry-toggle { + justify-content: flex-start; + width: 100%; + height: auto; + min-height: 3.25rem; + padding: 0.75rem 1rem; + border-radius: calc(var(--ui-radius-sm) - 1px); + text-align: start; + line-height: 1.5; + transition: + background-color 150ms ease-out, + color 150ms ease-out; + + &[aria-pressed='true'] { + background: var(--mat-sys-primary-container); + color: var(--mat-sys-on-primary-container); + } +} + +.declaration-types { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 0.5rem; + padding: 0.75rem; + + button { + min-height: 2.75rem; + height: auto; + padding: 0.5rem; + border-radius: calc(var(--ui-radius-sm) - 1px); + background-color: var(--ui-card-bg); + color: var(--number-color); + line-height: 1.5; + + &[data-declared-type='cp'] { + background-color: var(--cp-bg); + } + &[data-declared-type='rtt'] { + background-color: var(--rtt-bg); + } + &[data-declared-type='other'] { + background-color: var(--other-bg); + } + &[aria-pressed='true'] { + border-color: currentColor; + box-shadow: inset 0 0 0 1px currentColor; + } + &[data-declared-type][aria-pressed='true'] { + background-image: var(--declared-day-pattern); + } + &[aria-pressed='false'] .declaration-type-check { + visibility: hidden; + } + } +} + +@container declaration-controls (min-width: 18rem) { + .declaration-types { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@container declaration-controls (min-width: 34rem) { + .declaration-types { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } +} diff --git a/src/app/components/declaration-controls/declaration-controls.ts b/src/app/components/declaration-controls/declaration-controls.ts new file mode 100644 index 0000000..f07eb87 --- /dev/null +++ b/src/app/components/declaration-controls/declaration-controls.ts @@ -0,0 +1,24 @@ +import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; +import { MatButton } from '@angular/material/button'; +import { MatIcon } from '@angular/material/icon'; +import type { LeaveType } from '../../services/leave-planner.service'; +import { TranslationService } from '../../services/translation-service'; +import { UserInputService } from '../../services/user-input-service'; + +/** Starts and ends declared non-working day entry, and chooses the type a calendar tap applies. */ +@Component({ + selector: 'app-declaration-controls', + imports: [MatButton, MatIcon], + templateUrl: './declaration-controls.html', + styleUrl: './declaration-controls.scss', + changeDetection: ChangeDetectionStrategy.OnPush, + host: { '[class.is-active]': 'declarationEntry()' }, +}) +export class DeclarationControls { + private readonly userInput = inject(UserInputService); + protected readonly declarationEntry = this.userInput.declarationEntrySignal; + protected readonly declaredType = this.userInput.declaredTypeSignal; + protected readonly declaredTypes: readonly LeaveType[] = ['cp', 'rtt', 'other']; + protected readonly translationService = inject(TranslationService); + protected readonly tr = this.translationService.tr; +} diff --git a/src/app/components/user-input/user-input.html b/src/app/components/user-input/user-input.html index 3c61068..05a4955 100644 --- a/src/app/components/user-input/user-input.html +++ b/src/app/components/user-input/user-input.html @@ -2,9 +2,6 @@

{{ tr().userInput.title }}

{{ tr().userInput.description }}

- {{ tr().app.skipToPlan }}
@@ -81,50 +78,7 @@ {{ tr().userInput.addVacationDay }} -
- - @if (declarationEntry()) { -
- @for (type of declaredTypes; track type) { - - } - -
- } -
+
@@ -133,26 +87,7 @@ @if (duration.estimate() && !nothingToPlan()) {

{{ durationLabel() }}

} - +
@if (hasRemainingDays()) { diff --git a/src/app/components/user-input/user-input.scss b/src/app/components/user-input/user-input.scss index 34d4a32..0683caa 100644 --- a/src/app/components/user-input/user-input.scss +++ b/src/app/components/user-input/user-input.scss @@ -91,75 +91,6 @@ } } -.declaration-controls { - display: grid; - container: declaration-controls / inline-size; - grid-column: 1 / -1; - border: 1px solid var(--ui-border); - border-radius: var(--ui-radius-sm); - background: var(--ui-panel-bg); - - &.is-active { - border-color: var(--mat-sys-primary); - } -} - -.declaration-entry-toggle { - justify-content: flex-start; - width: 100%; - height: auto; - min-height: 3.25rem; - padding: 0.75rem 1rem; - border-radius: calc(var(--ui-radius-sm) - 1px); - text-align: start; - line-height: 1.5; - transition: - background-color 150ms ease-out, - color 150ms ease-out; - - &[aria-pressed='true'] { - background: var(--mat-sys-primary-container); - color: var(--mat-sys-on-primary-container); - } -} - -.declaration-types { - display: grid; - grid-template-columns: minmax(0, 1fr); - gap: 0.5rem; - padding: 0.75rem; - - button { - min-height: 2.75rem; - height: auto; - padding: 0.5rem; - border-radius: calc(var(--ui-radius-sm) - 1px); - background-color: var(--ui-card-bg); - color: var(--number-color); - line-height: 1.5; - - &[data-declared-type='cp'] { - background-color: var(--cp-bg); - } - &[data-declared-type='rtt'] { - background-color: var(--rtt-bg); - } - &[data-declared-type='other'] { - background-color: var(--other-bg); - } - &[aria-pressed='true'] { - border-color: currentColor; - box-shadow: inset 0 0 0 1px currentColor; - } - &[data-declared-type][aria-pressed='true'] { - background-image: var(--declared-day-pattern); - } - &[aria-pressed='false'] .declaration-type-check { - visibility: hidden; - } - } -} - .day-input-wrapper { animation: slide-fade-in 200ms ease-out; @@ -197,19 +128,18 @@ form { flex-direction: column; } -.add-day-button, -.calculate-button { +.add-day-button { width: 100%; min-height: 3rem; } +// Below 75rem, Calculate is in the app's bottom bar instead. .calculate-bar { - display: contents; + display: none; } .duration-estimate { - grid-column: 1 / -1; - margin: 0 0 -0.5rem; + margin: 0; color: var(--ui-text-secondary); font-size: 0.875rem; line-height: 1.5; @@ -223,12 +153,6 @@ form { border-radius: var(--ui-radius-sm); } -.calculate-button { - min-height: 3.25rem; - border-radius: var(--ui-radius-sm); - font-weight: 600; -} - .warning-card { background: var(--ui-warning-bg, #fff4d6); color: var(--ui-warning-text, #4f3800); @@ -275,18 +199,6 @@ form { max-width: 100%; } -@container declaration-controls (min-width: 18rem) { - .declaration-types { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } -} - -@container declaration-controls (min-width: 34rem) { - .declaration-types { - grid-template-columns: repeat(4, minmax(0, 1fr)); - } -} - @container user-input (min-width: 40rem) { .planning-dates { grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -306,7 +218,6 @@ form { column-gap: 1.5rem; } .section-heading, - .calculate-button, .warning-card { grid-column: 1 / -1; } @@ -315,21 +226,7 @@ form { } } -.jump-to-plan { - display: inline-flex; - align-items: center; - gap: 0.5rem; - width: fit-content; - min-height: 2.75rem; - color: var(--mat-sys-primary); - font-size: 0.875rem; - text-underline-offset: 0.25em; -} @media (min-width: 75rem) { - .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 { @@ -348,7 +245,4 @@ form { background: var(--ui-card-bg); border-block-start: 1px solid var(--ui-border); } - .duration-estimate { - margin: 0; - } } diff --git a/src/app/components/user-input/user-input.spec.ts b/src/app/components/user-input/user-input.spec.ts index 75e47ba..386f0cd 100644 --- a/src/app/components/user-input/user-input.spec.ts +++ b/src/app/components/user-input/user-input.spec.ts @@ -10,6 +10,8 @@ import { MatSlideToggleHarness } from '@angular/material/slide-toggle/testing'; import { type MockInstance, vi } from '../../../testing/vitest-compat'; import { createInProcessCalculation } from '../../../testing/planning-jobs'; import { UserInput } from './user-input'; +import { CalculateButton } from '../calculate-button/calculate-button'; +import { By } from '@angular/platform-browser'; import { UserInputService } from '../../services/user-input-service'; import { PlanningCalculationService } from '../../services/planning-calculation.service'; import { UserSettings } from '../user-settings/user-settings'; @@ -68,6 +70,11 @@ describe('UserInput', () => { await fixture.whenStable(); } + /** Calculate's own guard, as if the disabled button were activated anyway. */ + function calculateDirectly(): void { + fixture.debugElement.query(By.directive(CalculateButton)).componentInstance.calculate(); + } + async function revisit(): Promise { fixture.destroy(); TestBed.resetTestingModule(); @@ -228,10 +235,9 @@ describe('UserInput', () => { 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 bar = root.querySelector('.calculate-bar'); + expect(bar?.contains(calculate)).toBe(true); + expect(root.querySelector('#planning-duration-estimate')?.parentElement).toBe(bar); const initial = estimateText(); TestBed.inject(CalendarSettingsService).setPlanningDates('2026-10-04', '2029-10-03'); fixture.detectChanges(); @@ -283,7 +289,7 @@ describe('UserInput', () => { expect(root.querySelector('#planning-dates-error')?.textContent).toContain('on or after'); expect(calculate.getAttribute('aria-describedby')).toBe('planning-dates-error'); calculate.click(); - component.triggerComputation(); + calculateDirectly(); expect(createCalculation).not.toHaveBeenCalled(); editInput('input[name="planningStart"]', '29/02/2024'); expect(calculate.disabled).toBe(false); @@ -419,7 +425,7 @@ describe('UserInput', () => { expect(calculate.disabled).toBe(true); expect(calculate.getAttribute('aria-describedby')).toBe('leave-balances-empty'); expect(root.querySelector('#planning-duration-estimate')).toBeNull(); - component.triggerComputation(); + calculateDirectly(); expect(createCalculation).not.toHaveBeenCalled(); expect(localStorage.getItem('leaveBalances')).toBeNull(); expect(localStorage.getItem('app.language')).toBe('"en"'); diff --git a/src/app/components/user-input/user-input.ts b/src/app/components/user-input/user-input.ts index f47d27e..af44a96 100644 --- a/src/app/components/user-input/user-input.ts +++ b/src/app/components/user-input/user-input.ts @@ -11,13 +11,14 @@ 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 type { LeaveType } from '../../services/leave-planner.service'; import { TranslationService } from '../../services/translation-service'; import { CalendarSettingsService } from '../../services/calendar-settings-service'; import { PlanningCalculationService } from '../../services/planning-calculation.service'; import { PlanningDurationService } from '../../services/planning-duration.service'; import { addPlanningDays, isPlanningDate } from '../../services/planning-date'; import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter'; +import { DeclarationControls } from '../declaration-controls/declaration-controls'; +import { CalculateButton } from '../calculate-button/calculate-button'; @Component({ selector: 'app-user-input', @@ -32,6 +33,8 @@ import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter'; MatIcon, MatButtonModule, DayInput, + DeclarationControls, + CalculateButton, ], templateUrl: './user-input.html', styleUrl: './user-input.scss', @@ -40,10 +43,7 @@ import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter'; }) 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); private readonly calculations = inject(PlanningCalculationService); @@ -173,9 +173,4 @@ export class UserInput { days.map((day, i) => (i === index ? updatedDay : day)), ); } - - public triggerComputation() { - if (this.calendarSettings.planningHorizonError() || this.nothingToPlan()) return; - this.calculations.start(); - } } diff --git a/src/app/services/translation-service.ts b/src/app/services/translation-service.ts index 178cbeb..7d615ce 100644 --- a/src/app/services/translation-service.ts +++ b/src/app/services/translation-service.ts @@ -39,6 +39,9 @@ export interface AppTranslations { title: string; description: string; skipToPlan: string; + view: string; + configuration: string; + plan: string; }; userInput: { title: string; diff --git a/src/i18n/de.json b/src/i18n/de.json index c131178..ddddcb8 100644 --- a/src/i18n/de.json +++ b/src/i18n/de.json @@ -13,7 +13,10 @@ "app": { "title": "vac-optimizer", "description": "Mehr Raum für freie Zeit.", - "skipToPlan": "Zum Urlaubsplan" + "skipToPlan": "Zum Urlaubsplan", + "view": "Ansicht", + "configuration": "Eingaben", + "plan": "Plan" }, "userInput": { "title": "Urlaub konfigurieren", diff --git a/src/i18n/en.json b/src/i18n/en.json index 72a9f45..a91b319 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -13,7 +13,10 @@ "app": { "title": "vac-optimizer", "description": "Make more room for time off.", - "skipToPlan": "Skip to your plan" + "skipToPlan": "Skip to your plan", + "view": "View", + "configuration": "Setup", + "plan": "Plan" }, "userInput": { "title": "Configure your leave", diff --git a/src/i18n/es.json b/src/i18n/es.json index 84e9723..3a688c9 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -13,7 +13,10 @@ "app": { "title": "vac-optimizer", "description": "Más espacio para descansar.", - "skipToPlan": "Ir a tu plan" + "skipToPlan": "Ir a tu plan", + "view": "Vista", + "configuration": "Configurar", + "plan": "Plan" }, "userInput": { "title": "Configura tus vacaciones", diff --git a/src/i18n/fr.json b/src/i18n/fr.json index 29c04f9..0b8e3ef 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -13,7 +13,10 @@ "app": { "title": "vac-optimizer", "description": "Faites plus de place aux vacances.", - "skipToPlan": "Aller à votre planning" + "skipToPlan": "Aller à votre planning", + "view": "Affichage", + "configuration": "Réglages", + "plan": "Planning" }, "userInput": { "title": "Configurez vos congés", diff --git a/src/styles.scss b/src/styles.scss index 98cec15..a63437a 100644 --- a/src/styles.scss +++ b/src/styles.scss @@ -107,6 +107,8 @@ html { html { scrollbar-gutter: stable; + // Keeps elements focused or scrolled to above the app's bottom bar, measured in app.ts. + scroll-padding-bottom: var(--action-bar-height, 0px); } body { -- 2.54.0 From 1e30812bb458efd09f902b21cc3483cd941df3af Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 15:41:26 +0100 Subject: [PATCH 10/12] fix(rules): reword the default rule summaries as what the planner does (#357) The maintainer could not understand several default rule summaries. Each default optimization rule now states the action and its benefit, in the four languages, and the automatic placement of an if-then rule reads "au meilleur moment autour de ce jour". Co-Authored-By: Claude Fable 5.2 --- .../calendar-year/calendar-year-planning.spec.ts | 2 +- .../components/rules-panel/rules-panel.spec.ts | 14 +++++++------- src/app/services/planner-labels.spec.ts | 15 ++++++++------- src/i18n/de.json | 10 +++++----- src/i18n/en.json | 10 +++++----- src/i18n/es.json | 10 +++++----- src/i18n/fr.json | 12 ++++++------ 7 files changed, 37 insertions(+), 36 deletions(-) diff --git a/src/app/components/calendar-year/calendar-year-planning.spec.ts b/src/app/components/calendar-year/calendar-year-planning.spec.ts index e0258a8..5992500 100644 --- a/src/app/components/calendar-year/calendar-year-planning.spec.ts +++ b/src/app/components/calendar-year/calendar-year-planning.spec.ts @@ -3475,7 +3475,7 @@ describe('CalendarYear planning outcome boundary', () => { row.textContent?.includes('Gain — '), )!; expect(gainRow.textContent?.trim()).toBe( - 'Gain — Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave', + 'Gain — Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave', ); expect(gainRow.querySelector('small')).toBeNull(); expect(element.querySelector('.day-impact')?.textContent).toContain( diff --git a/src/app/components/rules-panel/rules-panel.spec.ts b/src/app/components/rules-panel/rules-panel.spec.ts index 9ca629e..3e65dc5 100644 --- a/src/app/components/rules-panel/rules-panel.spec.ts +++ b/src/app/components/rules-panel/rules-panel.spec.ts @@ -52,16 +52,16 @@ describe('RulesPanel', () => { it('describes the supplied rules in plain words in every language', () => { const summaries = () => component.rules.map((rule) => component.getRuleSummary(rule)); expect(summaries()).toEqual([ - 'Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre.', - 'Si un jour férié tombe un samedi, poser 2 jours de congés payés au mieux autour et gagner 1 jour de type Autre.', + 'Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible.', + 'Si un jour férié tombe un samedi, poser 2 jours de congés payés au meilleur moment autour de ce jour et gagner 1 jour de type Autre.', expect.stringMatching( /^Poser 5 jours de congé de tout type<\/strong> entre le 20\/12\/\d{4}<\/strong> et le 03\/01\/\d{4}<\/strong>\.$/, ), - 'Prendre la semaine entière quand elle contient un jour férié, en priorité si le férié tombe en milieu de semaine.', - 'Coller les congés aux week-ends et aux jours fériés, pour allonger les périodes de repos avec des jours qui ne coûtent aucun congé.', - 'Raccourcir la plus longue période travaillée d’affilée.', + 'Prendre la semaine entière quand elle contient un jour férié, surtout s’il tombe en milieu de semaine.', + 'Coller les congés aux week-ends et aux jours fériés, pour gagner un maximum de jours de repos sans les poser.', + 'Répartir les congés pour raccourcir la plus longue période de travail sans congé.', 'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos.', - 'Garder pour plus tard les jours qui n’expirent pas pendant la période planifiée : en poser le moins possible.', + 'Poser le moins possible de jours qui n’expirent qu’après la période planifiée, afin de les garder pour plus tard.', ]); const translations = TestBed.inject(TranslationService); for (const language of translations.availableLanguages) { @@ -145,7 +145,7 @@ describe('RulesPanel', () => { configuration: OPTIMIZATION_PRESETS.unplacedAtRisk, }); expect(component.getRuleSummary(rule)).toBe( - 'Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre.', + 'Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible.', ); const announce = vi.spyOn(TestBed.inject(LiveAnnouncer), 'announce').mockResolvedValue(); const buttons = fixture.nativeElement.querySelectorAll('.rule-item'); diff --git a/src/app/services/planner-labels.spec.ts b/src/app/services/planner-labels.spec.ts index 866c1d6..25fe342 100644 --- a/src/app/services/planner-labels.spec.ts +++ b/src/app/services/planner-labels.spec.ts @@ -214,7 +214,7 @@ describe('planning stage label', () => { it('names an optimization stage after its rule and its goal', () => { expect(stageLabel(en, source, 'optimization:gain')).toBe( - 'More days off — Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave', + 'More days off — Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave', ); }); @@ -301,7 +301,7 @@ describe('objective copy', () => { it('names an optimization after its rule and its goal, keeping its composition technical', () => { expect(objectiveCopy(en, source, 'optimization:gain')).toEqual({ - label: 'More days off — Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave', + label: 'More days off — Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave', technical: optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain), }); }); @@ -405,16 +405,17 @@ describe('optimization goal', () => { ); expect(goals).toEqual({ unplacedAtRisk: - 'Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre', + 'Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible', holidayWeekValue: - 'Prendre la semaine entière quand elle contient un jour férié, en priorité si le férié tombe en milieu de semaine', + 'Prendre la semaine entière quand elle contient un jour férié, surtout s’il tombe en milieu de semaine', nonWorkingDayGain: - 'Coller les congés aux week-ends et aux jours fériés, pour allonger les périodes de repos avec des jours qui ne coûtent aucun congé', - longestWorkSequence: 'Raccourcir la plus longue période travaillée d’affilée', + 'Coller les congés aux week-ends et aux jours fériés, pour gagner un maximum de jours de repos sans les poser', + longestWorkSequence: + 'Répartir les congés pour raccourcir la plus longue période de travail sans congé', shortSequenceDeficit: 'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos', supportingPlacements: - 'Garder pour plus tard les jours qui n’expirent pas pendant la période planifiée : en poser le moins possible', + 'Poser le moins possible de jours qui n’expirent qu’après la période planifiée, afin de les garder pour plus tard', }); }); diff --git a/src/i18n/de.json b/src/i18n/de.json index ddddcb8..8066b1c 100644 --- a/src/i18n/de.json +++ b/src/i18n/de.json @@ -195,12 +195,12 @@ "maximize": "{quantity} erhöhen" }, "intents": { - "unplacedAtRisk": "Tage, die im Planungszeitraum verfallen, zuerst einplanen, damit keiner verloren geht", - "holidayWeekValue": "Die ganze Woche freinehmen, wenn sie einen Feiertag enthält, vor allem wenn der Feiertag mitten in der Woche liegt", - "nonWorkingDayGain": "Urlaub an Wochenenden und Feiertage anschließen, um Auszeiten mit Tagen zu verlängern, die keinen Urlaub kosten", - "longestWorkSequence": "Die längste Arbeitsphase am Stück verkürzen", + "unplacedAtRisk": "Tage einplanen, die im Planungszeitraum verfallen, damit möglichst wenige verloren gehen", + "holidayWeekValue": "Die ganze Woche freinehmen, wenn sie einen Feiertag enthält, vor allem wenn er mitten in der Woche liegt", + "nonWorkingDayGain": "Urlaub an Wochenenden und Feiertage anschließen, um möglichst viele freie Tage zu gewinnen, ohne dafür Urlaub zu nehmen", + "longestWorkSequence": "Urlaub so verteilen, dass die längste Arbeitsphase ohne Urlaub kürzer wird", "shortSequenceDeficit": "Kurze Arbeitsphasen mit weniger als {threshold} zwischen zwei Auszeiten vermeiden", - "supportingPlacements": "Tage, die nicht im Planungszeitraum verfallen, für später aufheben: möglichst wenige davon nehmen" + "supportingPlacements": "Möglichst wenige Tage nehmen, die erst nach dem Planungszeitraum verfallen, um sie für später aufzuheben" }, "count": "Anzahl der {elements}{scope}", "elements": { diff --git a/src/i18n/en.json b/src/i18n/en.json index a91b319..f27b5a6 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -195,12 +195,12 @@ "maximize": "Increase {quantity}" }, "intents": { - "unplacedAtRisk": "Use the days that expire within the planning period first, so that none are lost", - "holidayWeekValue": "Take the whole week off when it contains a public holiday, especially when the holiday falls midweek", - "nonWorkingDayGain": "Attach leave to weekends and public holidays, to lengthen time-off periods with days that cost no leave", - "longestWorkSequence": "Shorten the longest stretch of consecutive working days", + "unplacedAtRisk": "Take the days that expire within the planning period, to lose as few as possible", + "holidayWeekValue": "Take the whole week off when it contains a public holiday, especially if the holiday falls midweek", + "nonWorkingDayGain": "Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave", + "longestWorkSequence": "Spread leave out to shorten the longest stretch of work without leave", "shortSequenceDeficit": "Avoid going back to work for fewer than {threshold} between two time-off periods", - "supportingPlacements": "Keep the days that do not expire within the planning period for later: use as few of them as possible" + "supportingPlacements": "Take as few as possible of the days that only expire after the planning period, to keep them for later" }, "count": "the number of {elements}{scope}", "elements": { diff --git a/src/i18n/es.json b/src/i18n/es.json index 3a688c9..ec91c79 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -195,12 +195,12 @@ "maximize": "Aumentar {quantity}" }, "intents": { - "unplacedAtRisk": "Usar primero los días que vencen durante el período de planificación, para no perderlos", - "holidayWeekValue": "Tomar la semana entera cuando incluye un festivo, sobre todo si el festivo cae a mitad de semana", - "nonWorkingDayGain": "Pegar las vacaciones a los fines de semana y festivos, para alargar los períodos de descanso con días que no gastan vacaciones", - "longestWorkSequence": "Acortar el tramo más largo de días trabajados seguidos", + "unplacedAtRisk": "Tomar los días que vencen durante el período de planificación, para perder el menor número posible", + "holidayWeekValue": "Tomar la semana entera cuando incluye un festivo, sobre todo si cae a mitad de semana", + "nonWorkingDayGain": "Pegar las vacaciones a los fines de semana y festivos, para ganar el máximo de días libres sin tomarlos como vacaciones", + "longestWorkSequence": "Repartir las vacaciones para acortar el tramo más largo de trabajo sin vacaciones", "shortSequenceDeficit": "Evitar volver al trabajo durante menos de {threshold} entre dos períodos de descanso", - "supportingPlacements": "Guardar para más adelante los días que no vencen durante el período de planificación: usar el menor número posible de ellos" + "supportingPlacements": "Tomar el menor número posible de días que solo vencen después del período de planificación, para guardarlos para más adelante" }, "count": "el número de {elements}{scope}", "elements": { diff --git a/src/i18n/fr.json b/src/i18n/fr.json index 0b8e3ef..1d8ffae 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -105,7 +105,7 @@ "before": "juste avant", "after": "juste après", "around": "de part et d’autre", - "auto": "au mieux autour" + "auto": "au meilleur moment autour de ce jour" }, "editRule": "Modifier la règle", "deleteRule": "Supprimer la règle", @@ -195,12 +195,12 @@ "maximize": "Augmenter {quantity}" }, "intents": { - "unplacedAtRisk": "Poser en priorité les jours qui expirent pendant la période planifiée, pour ne pas les perdre", - "holidayWeekValue": "Prendre la semaine entière quand elle contient un jour férié, en priorité si le férié tombe en milieu de semaine", - "nonWorkingDayGain": "Coller les congés aux week-ends et aux jours fériés, pour allonger les périodes de repos avec des jours qui ne coûtent aucun congé", - "longestWorkSequence": "Raccourcir la plus longue période travaillée d’affilée", + "unplacedAtRisk": "Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible", + "holidayWeekValue": "Prendre la semaine entière quand elle contient un jour férié, surtout s’il tombe en milieu de semaine", + "nonWorkingDayGain": "Coller les congés aux week-ends et aux jours fériés, pour gagner un maximum de jours de repos sans les poser", + "longestWorkSequence": "Répartir les congés pour raccourcir la plus longue période de travail sans congé", "shortSequenceDeficit": "Éviter de reprendre le travail pour moins de {threshold} entre deux périodes de repos", - "supportingPlacements": "Garder pour plus tard les jours qui n’expirent pas pendant la période planifiée : en poser le moins possible" + "supportingPlacements": "Poser le moins possible de jours qui n’expirent qu’après la période planifiée, afin de les garder pour plus tard" }, "count": "le nombre de {elements}{scope}", "elements": { -- 2.54.0 From 556fa3fe379823647a71c91641d7292861af92d1 Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 15:44:35 +0100 Subject: [PATCH 11/12] docs(adr): renumber the empty leave balances decision to ADR 0013 (#356) develop already records ADR 0012 for obligation solutions. Co-Authored-By: Claude Fable 5.2 --- README.md | 4 ++-- docs/adr/0005-saved-planning-inputs-before-random-defaults.md | 2 +- ...t-visit.md => 0013-empty-leave-balances-on-first-visit.md} | 0 3 files changed, 3 insertions(+), 3 deletions(-) rename docs/adr/{0012-empty-leave-balances-on-first-visit.md => 0013-empty-leave-balances-on-first-visit.md} (100%) diff --git a/README.md b/README.md index 741d485..3ef42ad 100644 --- a/README.md +++ b/README.md @@ -322,7 +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; its random fallback is superseded by ADR 0012. +- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration; its random fallback is superseded by ADR 0013. - [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. +- [ADR 0013](docs/adr/0013-empty-leave-balances-on-first-visit.md) starts from an empty leave-balance list instead of random balances. diff --git a/docs/adr/0005-saved-planning-inputs-before-random-defaults.md b/docs/adr/0005-saved-planning-inputs-before-random-defaults.md index a37aaeb..8f62d6e 100644 --- a/docs/adr/0005-saved-planning-inputs-before-random-defaults.md +++ b/docs/adr/0005-saved-planning-inputs-before-random-defaults.md @@ -1,5 +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. +[ADR 0013](0013-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. diff --git a/docs/adr/0012-empty-leave-balances-on-first-visit.md b/docs/adr/0013-empty-leave-balances-on-first-visit.md similarity index 100% rename from docs/adr/0012-empty-leave-balances-on-first-visit.md rename to docs/adr/0013-empty-leave-balances-on-first-visit.md -- 2.54.0 From 57521cc28b0f8bfd03585fceceb2d600bf8b1456 Mon Sep 17 00:00:00 2001 From: Nessar Date: Sat, 14 Nov 2026 16:07:03 +0100 Subject: [PATCH 12/12] test(date-comparison): wait for the dialog's initial focus before the retry focus check The retry test recorded document.activeElement right after clicking Retry and expected the arriving result not to move focus. MatDialog defaults to delayFocusTrap, so autoFocus 'first-heading' moves focus to the title only after the 150 ms opening animation timer and the next render. The test usually finished just before that timer fired, so it compared body with body. Under load the timer fired while job(2) was being polled, and the final detectChanges ran the pending afterNextRender. Focus then moved from body to #counterfactual-title and the assertion failed, even though the result had not moved focus. Wait for the title to receive focus, as the first test does, before taking the snapshot. The assertion now checks that the result leaves the dialog's settled focus on the title. Co-Authored-By: Claude Opus 5.5 --- src/app/components/date-comparison/date-comparison.spec.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/app/components/date-comparison/date-comparison.spec.ts b/src/app/components/date-comparison/date-comparison.spec.ts index 57e3efb..6dc1cb9 100644 --- a/src/app/components/date-comparison/date-comparison.spec.ts +++ b/src/app/components/date-comparison/date-comparison.spec.ts @@ -447,6 +447,10 @@ describe('DateComparison', () => { fixture.detectChanges(); expect(document.querySelector('.comparison-loading')).not.toBeNull(); expect(comparison.failed()).toBe(false); + // The dialog focuses its title only after its opening animation; let that settle first. + await vi.waitFor(() => + expect(document.activeElement).toBe(document.getElementById('counterfactual-title')), + ); const focusedBeforeResult = document.activeElement; (await job(2)).emit({ type: 'counterfactual-result', -- 2.54.0