diff --git a/README.md b/README.md index 9cf9abf..3ef42ad 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 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 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 ec4c70f..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,3 +1,5 @@ # Restore Saved Planning Inputs Before Generating Random Defaults +[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/0013-empty-leave-balances-on-first-visit.md b/docs/adr/0013-empty-leave-balances-on-first-visit.md new file mode 100644 index 0000000..dd211c1 --- /dev/null +++ b/docs/adr/0013-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/docs/statistics.md b/docs/statistics.md index 89c45ca..577b1cc 100644 --- a/docs/statistics.md +++ b/docs/statistics.md @@ -82,4 +82,4 @@ Use behavior-level tests that assert returned planning facts and user-visible fi - Domain definitions are maintained in [CONTEXT.md](../CONTEXT.md). Relevant architectural constraints are [server-side planning for every device](adr/0011-server-side-planning-for-every-device.md), which superseded the [personal client-side planner](adr/0002-personal-client-side-planner-for-now.md), [separate calculation outcome and trace](adr/0004-stable-explanation-original-trace-counterfactual.md), [selected horizons and cancellation](adr/0006-user-selected-horizons-and-cancellable-calculations.md), and [declared days and reported balances](adr/0007-declared-days-and-reported-balances.md). - **Current integration gaps:** The inspected outcome exposes placements, periods, remaining balances, and several quality metrics, but no dedicated gross earned-leave summary or fixed calculation date. Remaining balances omit fully consumed entitlements. Declared-day support is in progress in the working tree: declarations are carried with outcomes, while the inspected period and work-sequence calculations still use placements alone. Coordinate with #13's finalized semantics before relying on those values; avoid a second conflicting calendar model in the popup. - **Proposed empty-value convention, not explicitly confirmed:** Counts show 0 when there are no qualifying items. An average with no samples, or longest time-off period length when no periods exist, shows "—". The existing longest work-sequence length remains 0 when there are no work sequences. Empty samples should remain distinguishable from a measured zero in the underlying data. -- **Remaining presentation choices:** Exact decimal precision for averages, metric layout, and whether eligible rules with zero earnings receive breakdown rows were not decided. These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation. +- **Remaining presentation choices:** Metric layout and whether eligible rules with zero earnings receive breakdown rows were not decided. Statistics show at most one decimal in the active locale (#353). These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation. 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/app.html b/src/app/app.html index cfc03ed..58cbd05 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -1,6 +1,8 @@ @if (showPlanner()) {
- +
@@ -21,13 +23,43 @@
-
-
+
+
+
+ @if (declarationEntry() && view() === 'plan') { + + } +
+
+ + +
+ +
+
} diff --git a/src/app/app.scss b/src/app/app.scss index ed9d694..667daa0 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); @@ -102,10 +103,91 @@ 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 { + position: sticky; + top: 1rem; + max-height: calc(100dvh - 9rem); + overflow-y: auto; + } } @media (max-width: 35rem) { @@ -118,6 +200,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 936669f..a29ce45 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -1,6 +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', () => { @@ -12,7 +15,8 @@ describe('App', () => { }); afterEach(() => { - localStorage.removeItem('app.language'); + vi.restoreAllMocks(); + localStorage.clear(); document.documentElement.lang = 'en'; }); @@ -26,7 +30,19 @@ describe('App', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; - expect(compiled.querySelector('h1')?.textContent).toContain('vac-optimizer'); + expect(compiled.querySelector('h1')?.textContent).toContain('VacOptimizer'); + }); + + it('registers the scrolling configuration panel so that dragging a rule can auto-scroll it', () => { + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + const panel = fixture.nativeElement.querySelector('.configuration-panel') as HTMLElement; + const scrollables = TestBed.inject(ScrollDispatcher).getAncestorScrollContainers( + panel.querySelector('app-rules-panel')!, + ); + expect(scrollables.map((scrollable) => scrollable.getElementRef().nativeElement)).toEqual([ + panel, + ]); }); it('keeps the document language in sync with the selected language', () => { @@ -47,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 58a08da..0ce80df 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,22 +1,34 @@ 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'; 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'; @@ -24,7 +36,17 @@ function isBenchmarkUrl(url: string): boolean { @Component({ selector: 'app-root', - imports: [MatDatepickerModule, UserInput, CalendarYear, MatButton, MatIcon, RouterOutlet], + imports: [ + CdkScrollable, + MatDatepickerModule, + UserInput, + CalendarYear, + CalculateButton, + DeclarationControls, + MatButton, + MatIcon, + RouterOutlet, + ], templateUrl: './app.html', styleUrl: './app.scss', providers: [provideNativeDateAdapter()], @@ -35,8 +57,20 @@ 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('vac-optimizer'); + protected readonly title = signal('VacOptimizer'); protected readonly showPlanner = signal( !isBenchmarkUrl(typeof window !== 'undefined' ? window.location.pathname : this.router.url), ); @@ -48,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-planning.spec.ts b/src/app/components/calendar-year/calendar-year-planning.spec.ts index 0f299fd..5992500 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', @@ -264,8 +265,22 @@ function activateWithKeyboard(element: HTMLElement, key: 'Enter' | ' ' = 'Enter' const presets = createOptimizationPresetRules(); +// The page calculates on load only when there is something to plan. +const savedBalances = JSON.stringify([ + { + id: 'cp', + type: 'cp', + numberOfDays: 2, + availableDate: '2024-01-01', + expiryDate: '2024-12-31', + }, +]); + describe('CalendarYear planning outcome boundary', () => { - beforeEach(() => localStorage.clear()); + beforeEach(() => { + localStorage.clear(); + localStorage.setItem('leaveBalances', savedBalances); + }); afterEach(() => { localStorage.clear(); vi.useRealTimers(); @@ -528,7 +543,7 @@ describe('CalendarYear planning outcome boundary', () => { const expectedStatistics = [ ['New leave days', String(placements)], ['Non-working days gained (calendar days)', '4'], - ['Average work sequence (working days)', '3.333'], + ['Average work sequence (working days)', '3.3'], ['Longest work sequence (working days)', '6'], ['Average time-off period (calendar days)', '2.5'], ['Longest time-off period (calendar days)', '4'], @@ -1046,7 +1061,7 @@ describe('CalendarYear planning outcome boundary', () => { expect(dialog.textContent).toContain(holidayLabel); expect( Array.from(dialog.querySelectorAll('dd'), (value) => value.textContent?.trim()), - ).toEqual(['2', '4', '3,333', '6', '2,5', '4', '0', '0']); + ).toEqual(['2', '4', '3,3', '6', '2,5', '4', '0', '0']); } expect(dialog.textContent).toContain('Statistiques du planning'); expect(dialog.querySelector('dt')?.textContent).toContain('Nouveaux jours de congé posés'); @@ -1172,7 +1187,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 +1350,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 +1650,6 @@ describe('CalendarYear planning outcome boundary', () => { it('keeps the preceding calendar until a submitted snapshot returns and ignores later edits', async () => { localStorage.setItem('vacationRules', '{"version":1,"rules":[]}'); - localStorage.setItem('leaveBalances', '[]'); await TestBed.configureTestingModule({ imports: [CalendarYear, UserInput], providers: [provideZonelessChangeDetection()], @@ -2588,6 +2600,271 @@ describe('CalendarYear planning outcome boundary', () => { expect(summaryValues).toEqual(['2', '4', '6']); }); + it('attaches the calculation date to the results heading and status', async () => { + const { calendar, creation } = calendarFor({ ...plan, calculationDate: '2024-05-01' }); + await TestBed.configureTestingModule({ + imports: [CalendarYear], + providers: [ + provideZonelessChangeDetection(), + { provide: CalendarService, useValue: calendar }, + ], + }).compileComponents(); + spyOnCreation().mockImplementation(creation); + TestBed.inject(TranslationService).setLanguage('en'); + const fixture = TestBed.createComponent(CalendarYear); + fixture.detectChanges(); + await fixture.whenStable(); + fixture.detectChanges(); + const meta = fixture.nativeElement.querySelector('.results-heading .calculation-date'); + expect(meta?.textContent?.replace(/\s+/g, ' ').trim()).toBe( + `Calculation date : ${fixture.componentInstance['displayDate']('2024-05-01')}`, + ); + expect(meta.previousElementSibling.classList).toContain('planning-status'); + }); + + it.each([true, false])( + 'groups the applied rules in one closed disclosure between the summary and the calendar (rules: %s)', + async (withRules) => { + const applied: PlanOutcome = { + ...plan, + timeWindowContributions: [ + { + ruleId: 'window', + label: 'Window rule', + requested: 2, + declaredDays: [{ date: '2024-05-02', type: 'cp' }], + placementDates: ['2024-05-03'], + }, + ], + ifThenContributions: [ + { + ruleId: 'bridge', + label: 'Bridge rule', + occurrence: '2024-05-08', + requested: 1, + declaredDays: [], + placementDates: ['2024-05-06'], + }, + ], + timeOffPeriods: [ + { + start: '2024-05-02', + end: '2024-05-05', + duration: 4, + placementDates: ['2024-05-03'], + declaredDates: ['2024-05-02'], + nonWorkingDates: ['2024-05-04', '2024-05-05'], + nonWorkingDayGain: 2, + }, + ], + }; + const { calendar, creation } = calendarFor(withRules ? applied : plan, explanation); + await TestBed.configureTestingModule({ + imports: [CalendarYear], + providers: [ + provideZonelessChangeDetection(), + { provide: CalendarService, useValue: calendar }, + ], + }).compileComponents(); + spyOnCreation().mockImplementation(creation); + const translation = TestBed.inject(TranslationService); + translation.setLanguage('en'); + const fixture = TestBed.createComponent(CalendarYear); + fixture.detectChanges(); + await fixture.whenStable(); + await new Promise((resolve) => setTimeout(resolve, 0)); + fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + const details = root.querySelector( + '.plan-insights > .applied-rules', + ); + if (!withRules) { + expect(details).toBeNull(); + expect(root.querySelector('.declared-rule, .declared-period')).toBeNull(); + return; + } + expect(details!.open).toBe(false); + const summary = details!.querySelector('summary')!; + expect(summary.textContent?.replace(/\s+/g, ' ')).toContain('Applied rules detail'); + expect(summary.textContent?.replace(/\s+/g, ' ')).toContain('Entries : 3'); + expect(root.querySelectorAll('.declared-rule, .declared-period')).toHaveLength(3); + expect( + root.querySelectorAll( + '.applied-rules .declared-rule, .applied-rules .declared-period', + ), + ).toHaveLength(3); + const follows = (earlier: Element, later: Element) => + Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING); + expect(follows(root.querySelector('.plan-summary')!, details!)).toBe(true); + expect(follows(root.querySelector('.plan-details')!, details!)).toBe(true); + expect(follows(details!, root.querySelector('.calendar-legend')!)).toBe(true); + expect(follows(details!, root.querySelector('.month-grid')!)).toBe(true); + for (const [language, copy] of Object.entries(translationsMap)) { + translation.setLanguage(language); + fixture.detectChanges(); + expect(summary.textContent).toContain(copy.planning.appliedRules.title); + expect(summary.textContent).toContain(copy.planning.appliedRules.entries); + } + activateWithKeyboard(summary); + expect(details!.open).toBe(true); + }, + ); + + 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 = { @@ -3110,6 +3387,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' }, ], }; @@ -3119,6 +3397,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' }, ], }; @@ -3155,6 +3434,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], @@ -3184,7 +3470,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 — 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( 'Preference: Spring break', ); @@ -3202,7 +3495,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); @@ -3233,6 +3529,9 @@ describe('CalendarYear planning outcome boundary', () => { await fixture.whenStable(); await new Promise((resolve) => setTimeout(resolve, 0)); fixture.detectChanges(); + expect( + fixture.nativeElement.querySelector('.conflict-explanation').closest('details'), + ).toBeNull(); expect(fixture.nativeElement.querySelector('.conflict-explanation').textContent).toContain( 'Required spring leave', ); diff --git a/src/app/components/calendar-year/calendar-year.html b/src/app/components/calendar-year/calendar-year.html index ae891ca..dde31e7 100644 --- a/src/app/components/calendar-year/calendar-year.html +++ b/src/app/components/calendar-year/calendar-year.html @@ -70,6 +70,16 @@ {{ outcomeLabel(planningOutcome()!) }}

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

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

+ } + @if (displayedPlan()?.calculationDate; as calculationDate) { +

+ {{ tr().planning.calculationDate }} : {{ displayDate(calculationDate) }} +

} @if (displayedPlan()) { @@ -153,87 +163,6 @@
{{ plan.metrics.longestWorkSequence }}
- @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 }}

-
- } - @if (plan.calculationDate) { -

{{ tr().planning.calculationDate }} : {{ displayDate(plan.calculationDate) }}

- } - @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 }}

-
- } - } }
@@ -432,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 @@ -516,6 +448,139 @@ {{ 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 }}

+
+ } +
+
+ } + @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 2f076cf..78b011e 100644 --- a/src/app/components/calendar-year/calendar-year.scss +++ b/src/app/components/calendar-year/calendar-year.scss @@ -31,8 +31,14 @@ code { padding-block: 0.25rem 0.5rem; } .results-heading { - display: grid; - gap: 0.75rem; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem 1rem; +} +.calculation-date { + color: var(--ui-text-secondary); + font-size: 0.8125rem; } .planning-status { display: flex; @@ -59,6 +65,10 @@ code { background: var(--ui-error-bg); color: var(--ui-error-text); } + &.info { + background: var(--mat-sys-primary-container); + color: var(--mat-sys-on-primary-container); + } } .plan-summary { @@ -100,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); @@ -141,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 { @@ -154,12 +180,24 @@ code { } } +.applied-rules-content { + display: grid; + gap: 0.75rem; + padding: 1rem; +} + .statistics-content { display: grid; gap: 1rem; } .statistics-summary { - grid-template-columns: minmax(0, 1fr); + grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); + div { + padding: 0.875rem 1rem; + } + dd { + font-size: 1.75rem; + } } .earned-leave-breakdown { display: grid; diff --git a/src/app/components/calendar-year/calendar-year.ts b/src/app/components/calendar-year/calendar-year.ts index aa60851..bb3240d 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, @@ -109,6 +111,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 +135,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])); @@ -154,6 +161,23 @@ 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 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(); @@ -210,7 +234,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 +342,7 @@ export class CalendarYear { ), ); }); - this.calculations.start(); + if (!this.nothingToPlan()) this.calculations.start(); } protected cancelCalculation(): void { @@ -328,7 +352,9 @@ export class CalendarYear { } protected formatStatistic(value: number | null): string { - return value === null ? '—' : value.toLocaleString(this.translationService.locale()); + return value === null + ? '—' + : value.toLocaleString(this.translationService.locale(), { maximumFractionDigits: 1 }); } protected openStatistics(): void { @@ -470,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); @@ -551,6 +580,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/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', 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/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/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 ca98a71..3e65dc5 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 @@ -41,55 +49,48 @@ describe('RulesPanel', () => { expect(component.rules.length).toBe(8); }); - 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('describes the supplied rules in plain words in every language', () => { + const summaries = () => component.rules.map((rule) => component.getRuleSummary(rule)); + expect(summaries()).toEqual([ + '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é, 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.', + '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) { + 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('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('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 delete a rule', () => { @@ -121,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({ @@ -134,7 +144,9 @@ describe('RulesPanel', () => { force: 'preference', configuration: OPTIMIZATION_PRESETS.unplacedAtRisk, }); - expect(component.getRuleSummary(rule)).toContain('Quantité non placée'); + expect(component.getRuleSummary(rule)).toBe( + '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'); const moveUp: HTMLButtonElement = @@ -146,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); @@ -155,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 5889ad2..49a03c5 100644 --- a/src/app/components/rules-panel/rules-panel.ts +++ b/src/app/components/rules-panel/rules-panel.ts @@ -1,43 +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 { - 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 * as labels from '../../services/planner-labels'; +import { RuleDialog, type RuleDialogData } from './rule-dialog'; import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/drag-drop'; @Component({ @@ -47,12 +19,6 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d MatIconModule, MatButtonModule, MatSlideToggleModule, - MatFormFieldModule, - MatInputModule, - MatSelectModule, - MatDatepickerModule, - FormsModule, - NgTemplateOutlet, CdkDropList, CdkDrag, CdkDragHandle, @@ -60,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); @@ -73,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; } @@ -228,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) { @@ -270,86 +119,40 @@ 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) - 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..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 @@ -7,38 +7,24 @@ 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 { + 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(); @@ -62,23 +48,20 @@ 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)).toContain( - 'Déficit des séquences de travail (jours ouvrés)', + expect(component.getRuleSummary(rule)).toBe( + 'É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' }, @@ -91,11 +74,11 @@ 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( - 'seuil de préférence : 3 jours ouvrés', + 'pour moins de 3 jours ouvrés', ); expect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({ kind: 'Plan', @@ -104,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); @@ -139,34 +122,30 @@ 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', () => { - 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/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/components/user-input/user-input.html b/src/app/components/user-input/user-input.html index abbd8b2..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 }}
@@ -62,6 +59,12 @@
+ @if (!daysOff.length) { +

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

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

{{ 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 fa1f4ae..0683caa 100644 --- a/src/app/components/user-input/user-input.scss +++ b/src/app/components/user-input/user-input.scss @@ -72,72 +72,22 @@ gap: 0.75rem; } -.declaration-controls { - display: grid; - container: declaration-controls / inline-size; +.empty-balances { + display: flex; + align-items: flex-start; + gap: 0.75rem; grid-column: 1 / -1; + margin: 0; + padding: 1rem; border: 1px solid var(--ui-border); border-radius: var(--ui-radius-sm); background: var(--ui-panel-bg); - - &.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; + font-size: 0.875rem; 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; - } + mat-icon { + flex-shrink: 0; + color: var(--mat-sys-primary); } } @@ -178,15 +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: 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; @@ -200,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); @@ -252,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)); @@ -283,7 +218,6 @@ form { column-gap: 1.5rem; } .section-heading, - .calculate-button, .warning-card { grid-column: 1 / -1; } @@ -292,18 +226,23 @@ 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 { + 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); } } diff --git a/src/app/components/user-input/user-input.spec.ts b/src/app/components/user-input/user-input.spec.ts index f084832..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'; @@ -23,6 +25,16 @@ import { TranslationService } from '../../services/translation-service'; const presets = createOptimizationPresetRules(); +const savedBalances = JSON.stringify( + (['cp', 'rtt', 'other'] as const).map((type, index) => ({ + id: `00000000-0000-4000-8000-00000000000${index + 1}`, + type, + numberOfDays: 15, + availableDate: '2026-10-04', + expiryDate: '2027-10-04', + })), +); + describe('UserInput', () => { let component: UserInput; let fixture: ComponentFixture; @@ -35,12 +47,8 @@ describe('UserInput', () => { localStorage.setItem('app.language', '"en"'); vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 9, 4, 12)); - vi.spyOn(Math, 'random').mockReturnValue(0.5); - vi.spyOn(crypto, 'randomUUID') - .mockReturnValueOnce('00000000-0000-4000-8000-000000000001') - .mockReturnValueOnce('00000000-0000-4000-8000-000000000002') - .mockReturnValueOnce('00000000-0000-4000-8000-000000000003') - .mockReturnValueOnce('00000000-0000-4000-8000-000000000004'); + localStorage.setItem('leaveBalances', savedBalances); + vi.spyOn(crypto, 'randomUUID').mockReturnValueOnce('00000000-0000-4000-8000-000000000004'); await createInput(); }); @@ -62,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(); @@ -221,6 +234,10 @@ 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. + 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(); @@ -272,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); @@ -394,28 +411,42 @@ describe('UserInput', () => { it.each([ ['absent', null], ['unreadable', '{'], - ])('renders unsaved random defaults when balance data is %s', async (_, saved) => { + ])('shows the empty state and disables Calculate when balance data is %s', async (_, saved) => { vi.spyOn(console, 'warn').mockImplementation(() => {}); - if (saved !== null) localStorage.setItem('leaveBalances', saved); + if (saved === null) localStorage.removeItem('leaveBalances'); + else localStorage.setItem('leaveBalances', saved); await revisit(); const root = fixture.nativeElement as HTMLElement; - expect( - Array.from(root.querySelectorAll('app-day-input input')).map( - (input) => input.value, - ), - ).toEqual([ - '15', - '04/10/2026', - '04/10/2027', - '15', - '04/10/2026', - '04/10/2027', - '15', - '04/10/2026', - '04/10/2027', - ]); + expect(root.querySelector('app-day-input')).toBeNull(); + expect(root.querySelector('#leave-balances-empty')?.textContent).toContain( + 'No leave balance yet', + ); + const calculate = root.querySelector('.calculate-button')!; + expect(calculate.disabled).toBe(true); + expect(calculate.getAttribute('aria-describedby')).toBe('leave-balances-empty'); + expect(root.querySelector('#planning-duration-estimate')).toBeNull(); + calculateDirectly(); + expect(createCalculation).not.toHaveBeenCalled(); expect(localStorage.getItem('leaveBalances')).toBeNull(); expect(localStorage.getItem('app.language')).toBe('"en"'); + + root.querySelector('.add-day-button')!.click(); + fixture.detectChanges(); + expect(root.querySelectorAll('app-day-input')).toHaveLength(1); + expect(root.querySelector('#leave-balances-empty')).toBeNull(); + expect(calculate.disabled).toBe(false); + expect(calculate.getAttribute('aria-describedby')).toBe('planning-duration-estimate'); + }); + + it('explains both reasons when the planning dates are invalid and there is nothing to plan', async () => { + localStorage.setItem('leaveBalances', '[]'); + await revisit(); + editInput('input[name="lastPlanningDate"]', ''); + const calculate = fixture.nativeElement.querySelector('.calculate-button'); + expect(calculate.disabled).toBe(true); + expect(calculate.getAttribute('aria-describedby')).toBe( + 'planning-dates-error leave-balances-empty', + ); }); it('restores the complete edited list on a fresh visit', async () => { @@ -431,8 +462,8 @@ describe('UserInput', () => { expect(localStorage.getItem('leaveBalances')).toBe(saved); }); - it('saves the complete ordered balance list on the first quantity edit', () => { - expect(localStorage.getItem('leaveBalances')).toBeNull(); + it('saves the complete ordered balance list on a quantity edit', () => { + expect(localStorage.getItem('leaveBalances')).toBe(savedBalances); editInput('app-day-input input[type="number"]', '7'); expect(JSON.parse(localStorage.getItem('leaveBalances')!)).toEqual([ @@ -460,7 +491,7 @@ describe('UserInput', () => { ]); }); - it('saves a leave-type selection as the first balance edit', async () => { + it('saves a leave-type selection as a balance edit', async () => { const loader = TestbedHarnessEnvironment.loader(fixture); const type = await loader.getHarness( MatSelectHarness.with({ selector: 'app-day-input mat-select' }), @@ -492,7 +523,7 @@ describe('UserInput', () => { ]); }); - it('saves adding a balance as the first edit and keeps saving subsequent edits', () => { + it('saves adding a balance and keeps saving subsequent edits', () => { fixture.nativeElement.querySelector('.add-day-button').click(); fixture.detectChanges(); @@ -515,7 +546,7 @@ describe('UserInput', () => { expect(JSON.parse(localStorage.getItem('leaveBalances')!)[0].numberOfDays).toBe(9); }); - it('saves removing a balance as the first edit and retains an entry after the final deletion', () => { + it('saves removing a balance and retains an empty list after the final deletion', () => { fixture.nativeElement.querySelectorAll('.delete-button')[2].click(); fixture.detectChanges(); expect(JSON.parse(localStorage.getItem('leaveBalances')!)).toMatchObject([ @@ -530,15 +561,16 @@ describe('UserInput', () => { fixture.detectChanges(); expect(userInputService.vacationNumberSignal()).toEqual([]); expect(localStorage.getItem('leaveBalances')).toBe('[]'); + expect(fixture.nativeElement.querySelector('#leave-balances-empty')).not.toBeNull(); + expect(fixture.nativeElement.querySelector('.calculate-button').disabled).toBe(true); }); - it('keeps untouched random balances unsaved through settings, rule changes, and calculation', async () => { + it('does not rewrite restored balances through settings, rule changes, and calculation', async () => { const initialBalances = userInputService.vacationNumberSignal(); - expect(localStorage.getItem('leaveBalances')).toBeNull(); + const write = vi.spyOn(Storage.prototype, 'setItem'); const loader = TestbedHarnessEnvironment.documentRootLoader(fixture); const dialogRef = TestBed.inject(MatDialog).open(UserSettings); const dialog = await loader.getHarness(MatDialogHarness); - expect(localStorage.getItem('leaveBalances')).toBeNull(); const [theme, language] = await dialog.getAllHarnesses(MatSelectHarness); await selectOption(theme, 'Dark'); @@ -560,7 +592,8 @@ describe('UserInput', () => { expect(createCalculation).toHaveBeenCalledTimes(1); expect(userInputService.vacationNumberSignal()).toEqual(initialBalances); - expect(localStorage.getItem('leaveBalances')).toBeNull(); + expect(write.mock.calls.some(([key]) => key === 'leaveBalances')).toBe(false); + expect(localStorage.getItem('leaveBalances')).toBe(savedBalances); }); it('preserves unrelated stored preferences, rules, and other values when editing balances', () => { @@ -589,7 +622,7 @@ describe('UserInput', () => { editInput('app-day-input input[type="number"]', '7'); expect(userInputService.vacationNumberSignal()[0].numberOfDays).toBe(7); - expect(localStorage.getItem('leaveBalances')).toBeNull(); + expect(localStorage.getItem('leaveBalances')).toBe(savedBalances); write.mockRestore(); editInput('app-day-input input[type="number"]', '8'); diff --git a/src/app/components/user-input/user-input.ts b/src/app/components/user-input/user-input.ts index e3d56e5..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,9 +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 declaredTypes: readonly LeaveType[] = ['cp', 'rtt', 'other']; + protected readonly nothingToPlan = this.userInputService.nothingToPlan; protected readonly calendarSettings = inject(CalendarSettingsService); protected readonly duration = inject(PlanningDurationService); private readonly calculations = inject(PlanningCalculationService); @@ -172,9 +173,4 @@ export class UserInput { days.map((day, i) => (i === index ? updatedDay : day)), ); } - - public triggerComputation() { - if (this.calendarSettings.planningHorizonError()) return; - this.calculations.start(); - } } diff --git a/src/app/services/planner-labels.spec.ts b/src/app/services/planner-labels.spec.ts index 9444870..25fe342 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 — Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave', ); }); 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 — 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), }); }); 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,146 @@ 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('says in French what the supplied rules do for the person', () => { + const goals = Object.fromEntries( + Object.entries(OPTIMIZATION_PRESETS).map(([key, configuration]) => [ + key, + optimizationGoal(fr, configuration), + ]), + ); + expect(goals).toEqual({ + 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 5 jours ouvrés entre deux périodes de repos', + 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', + }); + }); + + 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) + 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)); + } + expect(supplied).toBe(Object.keys(OPTIMIZATION_PRESETS).length); + }, + ); + + 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 moins de 1 jour ouvré'); + expect(optimizationGoal(en, deficit)).toContain('for fewer than 1 working day'); + expect(optimizationGoal(en, { ...deficit, thresholdDays: 2 })).toContain( + 'for fewer than 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..c539680 100644 --- a/src/app/services/planner-labels.ts +++ b/src/app/services/planner-labels.ts @@ -6,11 +6,13 @@ import type { PlanningSnapshot, } from './leave-planner.service'; import { + OPTIMIZATION_PRESETS, 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 +81,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 +109,83 @@ 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) { +/** 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. + 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}', threshold), + ); +} + +/** + * 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 84b995f..7d615ce 100644 --- a/src/app/services/translation-service.ts +++ b/src/app/services/translation-service.ts @@ -6,9 +6,10 @@ 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 OPTIMIZATION_PRESETS, type OptimizationElements, type OptimizationCondition, type OptimizationMeasure, @@ -16,6 +17,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: { @@ -32,11 +39,15 @@ export interface AppTranslations { title: string; description: string; skipToPlan: string; + view: string; + configuration: string; + plan: string; }; userInput: { title: string; description: string; addVacationDay: string; + emptyBalances: string; calculate: string; durationEstimate: string; durationUnits: { seconds: string; minutes: string }; @@ -103,6 +114,15 @@ export interface AppTranslations { measures: Record; aggregations: Record; directions: Record; + plain: { + goals: Record; + intents: Record; + count: string; + elements: Record; + quantities: Record>; + scopes: Record; + workingDays: PluralForms; + }; }; title: string; subtitle: string; @@ -113,7 +133,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; @@ -227,15 +251,18 @@ export interface AppTranslations { sameDate: string; moveHelp: string; comparisonUnavailable: string; - objectives: Record; + objectives: Record; preferenceHelp: Record; stages: Record; unavailable: Record; }; title: string; + invitation: string; calendarHelp: string; explanationHelp: string; technicalDetails: string; + appliedRules: { title: string; entries: string }; + timeOffPeriods: { title: string; count: string; help: string }; compareDates: string; stopComparing: string; daysPlaced: string; @@ -378,10 +405,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/app/services/user-input-service.spec.ts b/src/app/services/user-input-service.spec.ts index 83151ed..d0f2eef 100644 --- a/src/app/services/user-input-service.spec.ts +++ b/src/app/services/user-input-service.spec.ts @@ -135,21 +135,23 @@ describe('UserInputService', () => { expect(warn).toHaveBeenCalled(); }); - it('should initialize with vacation days array', () => { - const vacations = service.vacationNumberSignal(); - expect(Array.isArray(vacations)).toBe(true); - expect(vacations.length).toBeGreaterThan(0); + it('starts a first visit from an empty, unsaved balance list without drawing quantities', () => { + const random = vi.spyOn(Math, 'random'); + expect(new UserInputService().vacationNumberSignal()).toEqual([]); + expect(random).not.toHaveBeenCalled(); + expect(localStorage.getItem('leaveBalances')).toBeNull(); }); - it('should have vacation days with valid properties', () => { - const vacations = service.vacationNumberSignal(); - vacations.forEach((day) => { - expect(day.id).toBeDefined(); - expect(day.type).toBeDefined(); - expect(day.numberOfDays).toBeGreaterThanOrEqual(10); - expect(day.numberOfDays).toBeLessThanOrEqual(20); - expect(day.expiryDate).toBeInstanceOf(Date); - }); + it('has nothing to plan only without a leave balance and without a declared non-working day', () => { + expect(service.nothingToPlan()).toBe(true); + service.toggleDeclaredDay('2024-01-02', 'cp'); + expect(service.nothingToPlan()).toBe(false); + service.toggleDeclaredDay('2024-01-02', 'cp'); + expect(service.nothingToPlan()).toBe(true); + service.updateBalances(() => [service.createVacationDay()]); + expect(service.nothingToPlan()).toBe(false); + localStorage.setItem('leaveBalances', '[]'); + expect(new UserInputService().nothingToPlan()).toBe(true); }); it('restores the saved balance order, identities, quantities, types, and calendar dates', () => { @@ -240,32 +242,23 @@ describe('UserInputService', () => { 'mixed supported and unsupported records', JSON.stringify([savedBalance, { ...savedBalance, type: 'any' }]), ], - ])( - 'deletes only unreadable balance data (%s) before using unsaved random defaults', - (_, saved) => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); - vi.spyOn(Math, 'random').mockReturnValue(0.5); - const unrelated = { - 'theme.preference': '"dark"', - 'app.language': '"fr"', - 'calendarSettings.showWeekNumbers': 'true', - vacationRules: '[]', - 'unrelated.entry': 'keep this value', - }; - for (const [key, value] of Object.entries(unrelated)) localStorage.setItem(key, value); - localStorage.setItem('leaveBalances', saved); + ])('deletes only unreadable balance data (%s) and starts from an empty list', (_, saved) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const unrelated = { + 'theme.preference': '"dark"', + 'app.language': '"fr"', + 'calendarSettings.showWeekNumbers': 'true', + vacationRules: '[]', + 'unrelated.entry': 'keep this value', + }; + for (const [key, value] of Object.entries(unrelated)) localStorage.setItem(key, value); + localStorage.setItem('leaveBalances', saved); - const balances = new UserInputService().vacationNumberSignal(); - expect(balances.map((balance) => [balance.type, balance.numberOfDays])).toEqual([ - [SelectableDayType.CP, 15], - [SelectableDayType.RTT, 15], - [SelectableDayType.OTHER, 15], - ]); - expect(localStorage.getItem('leaveBalances')).toBeNull(); - for (const [key, value] of Object.entries(unrelated)) - expect(localStorage.getItem(key)).toBe(value); - }, - ); + expect(new UserInputService().vacationNumberSignal()).toEqual([]); + expect(localStorage.getItem('leaveBalances')).toBeNull(); + for (const [key, value] of Object.entries(unrelated)) + expect(localStorage.getItem(key)).toBe(value); + }); it('keeps saved data intact when browser storage temporarily cannot be read', () => { const saved = JSON.stringify([savedBalance]); @@ -275,30 +268,11 @@ describe('UserInputService', () => { throw new DOMException('Storage is unavailable', 'SecurityError'); }); - expect(new UserInputService().vacationNumberSignal()).toHaveLength(3); + expect(new UserInputService().vacationNumberSignal()).toEqual([]); read.mockRestore(); expect(localStorage.getItem('leaveBalances')).toBe(saved); }); - it.each([ - [0, 10], - [1 - Number.EPSILON, 20], - ])('starts every balance at %s random draw with %s days', (draw, expected) => { - vi.spyOn(Math, 'random').mockReturnValue(draw); - const initialBalances = new UserInputService().vacationNumberSignal(); - expect(initialBalances.map((balance) => balance.numberOfDays)).toEqual([ - expected, - expected, - expected, - ]); - expect(initialBalances.map((balance) => balance.type)).toEqual([ - SelectableDayType.CP, - SelectableDayType.RTT, - SelectableDayType.OTHER, - ]); - expect(localStorage.getItem('leaveBalances')).toBeNull(); - }); - it('should update vacation number signal', () => { const newVacations: LeaveBalance[] = [ { diff --git a/src/app/services/user-input-service.ts b/src/app/services/user-input-service.ts index feec7a2..44343de 100644 --- a/src/app/services/user-input-service.ts +++ b/src/app/services/user-input-service.ts @@ -1,4 +1,4 @@ -import { Injectable, signal } from '@angular/core'; +import { computed, Injectable, signal } from '@angular/core'; import { SelectableDayType } from './calendar-service'; import dayjs from 'dayjs'; import { @@ -118,45 +118,13 @@ export class UserInputService { try { localStorage.removeItem('leaveBalances'); } catch { - // Keep the random fallback usable when browser storage is unavailable. + // Keep the empty list usable when browser storage is unavailable. } } } return undefined; } - private getRandomNumber(): number { - return Math.floor(Math.random() * 11) + 10; - } - - private getInitialValues(): LeaveBalance[] { - const availableDate = new Date(); - return [ - { - id: crypto.randomUUID(), - type: SelectableDayType.CP, - numberOfDays: this.getRandomNumber(), - availableDate, - // today + 365 days - expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)), - }, - { - id: crypto.randomUUID(), - type: SelectableDayType.RTT, - numberOfDays: this.getRandomNumber(), - availableDate: new Date(availableDate), - expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)), - }, - { - id: crypto.randomUUID(), - type: SelectableDayType.OTHER, - numberOfDays: this.getRandomNumber(), - availableDate: new Date(availableDate), - expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)), - }, - ]; - } - public createVacationDay(): LeaveBalance { return { id: crypto.randomUUID(), @@ -167,8 +135,10 @@ export class UserInputService { }; } - readonly vacationNumberSignal = signal( - this.getSavedValues() ?? this.getInitialValues(), + readonly vacationNumberSignal = signal(this.getSavedValues() ?? []); + /** No leave balance and no declared non-working day: nothing is calculated until one is added. */ + readonly nothingToPlan = computed( + () => !this.vacationNumberSignal().length && !this.declaredDays().length, ); public updateBalances(updater: (balances: LeaveBalance[]) => LeaveBalance[]): void { this.vacationNumberSignal.update(updater); diff --git a/src/i18n/de.json b/src/i18n/de.json index 8776620..8066b1c 100644 --- a/src/i18n/de.json +++ b/src/i18n/de.json @@ -13,12 +13,16 @@ "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", "description": "Wählen Sie den Planungszeitraum und fügen Sie jedes Urlaubskonto und seinen Gültigkeitszeitraum hinzu.", "addVacationDay": "Urlaubskonto hinzufügen", + "emptyBalances": "Noch kein Urlaubskonto. Fügen Sie jedes Ihrer Urlaubskonten mit Urlaubsart, Anzahl der Tage und Gültigkeitszeitraum hinzu.", "calculate": "Plan berechnen", "durationEstimate": "Ungefähre Wartezeit: {range} {unit}", "durationUnits": { @@ -84,8 +88,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", @@ -95,7 +116,7 @@ "days": "Tage", "type": "Typ", "position": "Position", - "getBonus": "Bonus erhalten", + "getBonus": "erwerben", "force": "Regelverbindlichkeit", "obligation": "Verpflichtung", "preference": "Präferenz", @@ -167,6 +188,65 @@ "directions": { "minimize": "Minimieren", "maximize": "Maximieren" + }, + "plain": { + "goals": { + "minimize": "{quantity} verringern", + "maximize": "{quantity} erhöhen" + }, + "intents": { + "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": "Möglichst wenige Tage nehmen, die erst nach dem Planungszeitraum verfallen, um sie für später aufzuheben" + }, + "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": "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", + "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" + } } } }, @@ -191,6 +271,7 @@ "futureEntitlement": "Erzeugter künftiger Anspruch", "includedEntitlement": "Anspruch bereits in den gemeldeten Guthaben enthalten", "title": "Ihr optimiertes Jahr", + "invitation": "Fügen Sie Ihre Urlaubskonten hinzu und berechnen Sie dann den Plan, um ihn hier zu sehen.", "daysPlaced": "Eingeplante Urlaubstage", "daysGained": "Gewonnene arbeitsfreie Tage", "longestWorkSequence": "Längste Arbeitsphase", @@ -271,8 +352,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.", @@ -296,6 +377,15 @@ "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" + }, + "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": { @@ -364,8 +454,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 1a91b09..f27b5a6 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -13,12 +13,16 @@ "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", "description": "Choose a planning period, then add each leave balance and its validity period.", "addVacationDay": "Add leave balance", + "emptyBalances": "No leave balance yet. Add each of your balances with its leave type, number of days and validity period.", "calculate": "Calculate plan", "durationEstimate": "Approximate wait: {range} {unit}", "durationUnits": { @@ -84,8 +88,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", @@ -95,7 +116,7 @@ "days": "Days", "type": "Type", "position": "Position", - "getBonus": "Get as bonus", + "getBonus": "Earn", "force": "Rule force", "obligation": "Obligation", "preference": "Preference", @@ -167,6 +188,65 @@ "directions": { "minimize": "Minimize", "maximize": "Maximize" + }, + "plain": { + "goals": { + "minimize": "Reduce {quantity}", + "maximize": "Increase {quantity}" + }, + "intents": { + "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": "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": { + "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 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", + "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" + } } } }, @@ -191,6 +271,7 @@ "futureEntitlement": "Future entitlement generated", "includedEntitlement": "Entitlement already included in reported balances", "title": "Your optimized year", + "invitation": "Add your leave balances, then calculate the plan to see it here.", "daysPlaced": "Leave days placed", "daysGained": "Non-working days gained", "longestWorkSequence": "Longest work sequence", @@ -271,8 +352,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.", @@ -296,6 +377,15 @@ "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" + }, + "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": { @@ -364,8 +454,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 e88a1d9..ec91c79 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -13,12 +13,16 @@ "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", "description": "Elige el período de planificación y añade cada saldo de vacaciones y su periodo de validez.", "addVacationDay": "Añadir saldo de vacaciones", + "emptyBalances": "Todavía no hay ningún saldo de vacaciones. Añade cada uno de tus saldos con su tipo de permiso, su número de días y su periodo de validez.", "calculate": "Calcular plan", "durationEstimate": "Espera aproximada: {range} {unit}", "durationUnits": { @@ -84,8 +88,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", @@ -95,7 +116,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", @@ -167,6 +188,65 @@ "directions": { "minimize": "Minimizar", "maximize": "Maximizar" + }, + "plain": { + "goals": { + "minimize": "Reducir {quantity}", + "maximize": "Aumentar {quantity}" + }, + "intents": { + "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": "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": { + "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": "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", + "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" + } } } }, @@ -191,6 +271,7 @@ "futureEntitlement": "Derecho futuro generado", "includedEntitlement": "Derecho ya incluido en los saldos declarados", "title": "Tu año optimizado", + "invitation": "Añade tus saldos de vacaciones y calcula el plan para verlo aquí.", "daysPlaced": "Días de vacaciones asignados", "daysGained": "Días no laborables ganados", "longestWorkSequence": "Período de trabajo más largo", @@ -271,8 +352,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.", @@ -296,6 +377,15 @@ "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" + }, + "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": { @@ -364,8 +454,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 839f2c1..1d8ffae 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -13,12 +13,16 @@ "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", "description": "Choisissez la période à planifier, puis ajoutez chaque solde de congés et sa période de validité.", "addVacationDay": "Ajouter un solde de congés", + "emptyBalances": "Aucun solde de congés pour l’instant. Ajoutez chacun de vos soldes avec son type de congé, son nombre de jours et sa période de validité.", "calculate": "Calculer le planning", "durationEstimate": "Attente indicative : {range} {unit}", "durationUnits": { @@ -84,8 +88,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 meilleur moment autour de ce jour" + }, "editRule": "Modifier la règle", "deleteRule": "Supprimer la règle", "addRule": "Ajouter une règle", @@ -95,7 +116,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", @@ -167,6 +188,65 @@ "directions": { "minimize": "Minimiser", "maximize": "Maximiser" + }, + "plain": { + "goals": { + "minimize": "Réduire {quantity}", + "maximize": "Augmenter {quantity}" + }, + "intents": { + "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": "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": { + "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": "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", + "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" + } } } }, @@ -191,6 +271,7 @@ "futureEntitlement": "Droit futur généré", "includedEntitlement": "Droit déjà inclus dans les soldes reportés", "title": "Votre année optimisée", + "invitation": "Ajoutez vos soldes de congés puis calculez le planning pour l’afficher ici.", "daysPlaced": "Jours de congé placés", "daysGained": "Jours non travaillés gagnés", "longestWorkSequence": "Plus longue période travaillée", @@ -271,8 +352,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.", @@ -296,6 +377,15 @@ "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" + }, + "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": { @@ -364,8 +454,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": { 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 { 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(); +}