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