feat(ui): refresh the planner interface #361

Merged
nessar merged 12 commits from feature/planner-ui-refresh into develop 2026-11-14 16:42:38 +01:00
13 changed files with 631 additions and 122 deletions
Showing only changes of commit 897bdefd25 - Show all commits

No files matched your search

@@ -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<HTMLDetailsElement>('.criterion-help')?.open).toBe(false);
@@ -361,7 +361,10 @@
@for (change of placementChanges(); track change.id) {
<tr [class.decisive-row]="change.id === decisiveObjective">
<th scope="row">
{{ change.label }}<small>{{ change.help }}</small>
{{ change.label }}
@if (change.help) {
<small>{{ change.help }}</small>
}
@if (change.id === decisiveObjective) {
<span class="decisive-label">{{
tr().planning.details.firstDifference
@@ -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 {
@@ -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 <strong>samedi</strong>, poser <strong>2 jours de congés payés</strong> au mieux autour et gagner <strong>1 jour de type Autre</strong>.',
expect.stringMatching(
/^Poser <strong>5 jours de congé de tout type<\/strong> entre le <strong>20\/12\/\d{4}<\/strong> et le <strong>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 <strong>Saturday</strong>, take <strong>2 days of paid leave</strong> around it where it helps most and earn <strong>1 day of Other leave</strong>.',
);
translations.setLanguage('de');
expect(summaries()[1]).toBe(
'Wenn ein Feiertag auf einen <strong>Samstag</strong> fällt, <strong>2 Tage bezahlten Urlaub</strong> bestmöglich rund um den Feiertag nehmen und <strong>1 Tag der Art „Andere“</strong> 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 <strong>samedi</strong>, poser <strong>1 jour de congés payés</strong> 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 =
+33 -35
View File
@@ -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));
}
}
@@ -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');
});
});
+122 -10
View File
@@ -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<OptimizationCondition[][]>(
(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(
+59 -12
View File
@@ -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'];
+21 -7
View File
@@ -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<OptimizationMeasure, string>;
aggregations: Record<OptimizationAggregation, string>;
directions: Record<OptimizationDirection, string>;
plain: {
goals: Record<OptimizationDirection, string>;
count: string;
elements: Record<OptimizationElements, string>;
quantities: Record<OptimizationMeasure, Record<'sum' | 'maximum', string>>;
scopes: Record<OptimizationCondition, string>;
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<SelectableDayType, string>;
summaryPlacement: Record<PlacementStrategy, string>;
editRule: string;
deleteRule: string;
addRule: string;
@@ -228,7 +246,7 @@ export interface AppTranslations {
sameDate: string;
moveHelp: string;
comparisonUnavailable: string;
objectives: Record<string, { label: string; help: string }>;
objectives: Record<string, { label: string; help?: string }>;
preferenceHelp: Record<string, string | undefined>;
stages: Record<string, string>;
unavailable: Record<string, string | undefined>;
@@ -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
+74 -7
View File
@@ -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 <strong>{day}</strong> fällt, <strong>{placeDays}</strong> {placement} nehmen{earned}.",
"ifThenEarned": " und <strong>{earnedDays}</strong> erwerben",
"timeWindowTemplate": "<strong>{placeDays}</strong> zwischen dem <strong>{startDate}</strong> und dem <strong>{endDate}</strong> 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": {
+74 -7
View File
@@ -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 <strong>{day}</strong>, place <strong>{placeDays}</strong> day(s) <strong>{placeType}</strong> <strong>{placement}</strong> and get <strong>{rewardDays}</strong> day(s) <strong>{rewardType}</strong> as a bonus.",
"timeWindowTemplate": "Place <strong>{placeDays}</strong> day(s) <strong>{placeType}</strong> between <strong>{startDate}</strong> and <strong>{endDate}</strong>.",
"ifThenTemplate": "If a public holiday falls on a <strong>{day}</strong>, take <strong>{placeDays}</strong> {placement}{earned}.",
"ifThenEarned": " and earn <strong>{earnedDays}</strong>",
"timeWindowTemplate": "Take <strong>{placeDays}</strong> between <strong>{startDate}</strong> and <strong>{endDate}</strong>.",
"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": {
+74 -7
View File
@@ -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 <strong>{day}</strong>, colocar <strong>{placeDays}</strong> día(s) <strong>{placeType}</strong> <strong>{placement}</strong> y obtener <strong>{rewardDays}</strong> día(s) <strong>{rewardType}</strong> de bonificación.",
"timeWindowTemplate": "Colocar <strong>{placeDays}</strong> día(s) <strong>{placeType}</strong> entre el <strong>{startDate}</strong> y el <strong>{endDate}</strong>.",
"ifThenTemplate": "Si un festivo cae en <strong>{day}</strong>, tomar <strong>{placeDays}</strong> {placement}{earned}.",
"ifThenEarned": " y ganar <strong>{earnedDays}</strong>",
"timeWindowTemplate": "Tomar <strong>{placeDays}</strong> entre el <strong>{startDate}</strong> y el <strong>{endDate}</strong>.",
"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": {
+74 -7
View File
@@ -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 <strong>{day}</strong>, placer <strong>{placeDays}</strong> jour(s) <strong>{placeType}</strong> <strong>{placement}</strong> et obtenir <strong>{rewardDays}</strong> jour(s) <strong>{rewardType}</strong> en bonus.",
"timeWindowTemplate": "Placer <strong>{placeDays}</strong> jour(s) <strong>{placeType}</strong> entre le <strong>{startDate}</strong> et le <strong>{endDate}</strong>.",
"ifThenTemplate": "Si un jour férié tombe un <strong>{day}</strong>, poser <strong>{placeDays}</strong> {placement}{earned}.",
"ifThenEarned": " et gagner <strong>{earnedDays}</strong>",
"timeWindowTemplate": "Poser <strong>{placeDays}</strong> entre le <strong>{startDate}</strong> et le <strong>{endDate}</strong>.",
"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": {