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
11 changed files with 970 additions and 893 deletions
Showing only changes of commit 5148274d4d - Show all commits

No files matched your search

@@ -10,6 +10,13 @@ import {
type OptimizationConfiguration,
} from '../../services/planning-objectives';
import { calculatePlanningInternal } from '../../services/leave-planner.core';
import {
chooseInDialog,
clickDialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
describe('calendar rule editing and persistence', () => {
let fixture: ComponentFixture<RulesPanel>;
@@ -40,28 +47,15 @@ describe('calendar rule editing and persistence', () => {
});
afterEach(() => localStorage.clear());
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
async function select(label: string, value: string) {
const fields: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('mat-form-field'),
);
const field = fields.find(
(candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label,
);
const control = field?.querySelector<HTMLElement>('mat-select');
if (!control) throw new Error(`Missing labelled control: ${label}`);
const control = dialogField(label).querySelector<HTMLElement>('mat-select')!;
const labels = (control.getAttribute('aria-labelledby') ?? '')
.split(/\s+/)
.map((id) => document.getElementById(id)?.textContent?.trim());
expect(labels).toContain(label);
control.click();
await fixture.whenStable();
const option = Array.from(document.querySelectorAll<HTMLElement>('mat-option')).find(
(candidate) => candidate.textContent?.trim() === value,
);
if (!option) throw new Error(`Missing translated option: ${value}`);
option.click();
document.querySelector<HTMLElement>('.cdk-overlay-backdrop')?.click();
await fixture.whenStable();
await chooseInDialog(fixture, label, value);
fixture.detectChanges();
}
@@ -72,10 +66,7 @@ describe('calendar rule editing and persistence', () => {
);
buttons.find((button) => button.textContent?.includes(tr.optimization.newRule))!.click();
await fixture.whenStable();
const nameInput: HTMLInputElement =
fixture.nativeElement.querySelector('.rule-editor input');
nameInput.value = name;
nameInput.dispatchEvent(new Event('input', { bubbles: true }));
await typeInDialog(fixture, tr.ruleName, name);
await select(
tr.optimization.elementsLabel,
tr.optimization.elements[configuration.elements],
@@ -90,11 +81,8 @@ describe('calendar rule editing and persistence', () => {
tr.optimization.directionLabel,
tr.optimization.directions[configuration.direction],
);
const actions: HTMLButtonElement[] = Array.from(
fixture.nativeElement.querySelectorAll('.editor-actions button'),
);
actions.find((button) => button.textContent?.trim() === tr.add)!.click();
await fixture.whenStable();
await clickDialogButton(fixture, tr.add);
await closed();
fixture.detectChanges();
}
@@ -154,8 +142,8 @@ describe('calendar rule editing and persistence', () => {
translations.tr().rules.optimization.aggregationLabel,
translations.tr().rules.optimization.aggregations.count,
);
fixture.componentInstance.saveEdit();
await fixture.whenStable();
await clickDialogButton(fixture, translations.tr().rules.save);
await closed();
await expect
.poll(
() =>
@@ -201,11 +189,9 @@ describe('calendar rule editing and persistence', () => {
fixture.componentInstance.startEdit(service.rules[0], new Event('click'));
await fixture.whenStable();
const input: HTMLInputElement = fixture.nativeElement.querySelector('.rule-editor input');
input.value = 'Mes jours conservés';
input.dispatchEvent(new Event('input', { bubbles: true }));
fixture.componentInstance.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, translations.tr().rules.ruleName, 'Mes jours conservés');
await clickDialogButton(fixture, translations.tr().rules.save);
await closed();
const toggle: HTMLButtonElement = fixture.nativeElement
.querySelector('.rule-item')
.querySelector('button[role="switch"]');
@@ -0,0 +1,216 @@
<h2 mat-dialog-title>{{ isNew ? tr().rules.addRule : tr().rules.editRule }}</h2>
<mat-dialog-content>
<div class="rule-editor">
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.ruleName }}</mat-label>
<input matInput [(ngModel)]="$any(editBuffer).name" required />
</mat-form-field>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.force }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).force">
@for (option of forceOptions; track option.value) {
<mat-option [value]="option.value">{{ option.label() }}</mat-option>
}
</mat-select>
</mat-form-field>
@if ($any(editBuffer).type === RuleType.IF_THEN) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.holidayFalls }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).dayOfWeek">
@for (day of daysOfWeek; track day.value) {
<mat-option [value]="day.value">{{ day.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{ getDayTypeLabel(type) }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.position }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placement">
@for (opt of placementOptions; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.getBonus }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).rewardDays"
min="0"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).rewardType">
@for (type of rewardDayTypes; track type) {
<mat-option [value]="type">{{ getDayTypeLabel(type) }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {
@if (optimizationConfiguration; as configuration) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.elementsLabel }}</mat-label>
<mat-select
[ngModel]="configuration.elements"
(ngModelChange)="changeOptimizationElements($event)"
>
@for (elements of optimizationElements; track elements) {
<mat-option [value]="elements">{{
tr().rules.optimization.elements[elements]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.measureLabel }}</mat-label>
<mat-select
[ngModel]="configuration.measure"
(ngModelChange)="changeOptimizationMeasure($event)"
>
@for (row of optimizationMeasures; track row.measure) {
<mat-option [value]="row.measure">{{
tr().rules.optimization.measures[row.measure]
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
@if (optimizationConditions.length) {
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.optimization.conditionsLabel }}</mat-label>
<mat-select multiple [(ngModel)]="configuration.conditions">
@for (condition of optimizationConditions; track condition) {
<mat-option [value]="condition">{{
tr().rules.optimization.conditions[condition]
}}</mat-option>
}
</mat-select>
</mat-form-field>
}
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.aggregationLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.aggregation">
@for (aggregation of optimizationAggregations; track aggregation) {
<mat-option [value]="aggregation">{{
tr().rules.optimization.aggregations[aggregation]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.directionLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.direction">
@for (direction of optimizationDirections; track direction) {
<mat-option [value]="direction">{{
tr().rules.optimization.directions[direction]
}}</mat-option>
}
</mat-select>
</mat-form-field>
@if (configuration.measure === 'work-sequence-deficit') {
<mat-form-field class="wide-label">
<mat-label>{{ tr().rules.optimization.thresholdLabel }}</mat-label>
<input
matInput
type="number"
min="1"
step="1"
required
[(ngModel)]="configuration.thresholdDays"
/>
</mat-form-field>
}
</div>
}
} @else {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.startDate }}</mat-label>
<input
matInput
[matDatepicker]="startPicker"
[(ngModel)]="$any(editBuffer).startDate"
/>
<mat-datepicker-toggle matSuffix [for]="startPicker"></mat-datepicker-toggle>
<mat-datepicker #startPicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.endDate }}</mat-label>
<input
matInput
[matDatepicker]="endPicker"
[(ngModel)]="$any(editBuffer).endDate"
/>
<mat-datepicker-toggle matSuffix [for]="endPicker"></mat-datepicker-toggle>
<mat-datepicker #endPicker></mat-datepicker>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{ getDayTypeLabel(type) }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
}
</div>
</mat-dialog-content>
@if (validationError()) {
<p role="alert">{{ validationError() }}</p>
}
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>{{ tr().rules.cancel }}</button>
<button mat-flat-button type="button" color="primary" (click)="save()">
{{ isNew ? tr().rules.add : tr().rules.save }}
</button>
</mat-dialog-actions>
@@ -0,0 +1,55 @@
:host {
display: block;
}
.rule-editor {
display: flex;
flex-direction: column;
gap: 16px;
// Room for the floating label of the first field, which the scrolling content would clip.
padding-top: 0.5rem;
.editor-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
.action-text {
flex-basis: 100%;
font-weight: 500;
}
mat-form-field {
flex: 1 1 11rem;
min-width: 0;
max-width: 100%;
}
.small-input {
flex: 0 1 6.25rem;
}
// Its label is long: take a row of its own once the others leave no room for it.
.wide-label {
flex-basis: 16rem;
}
}
mat-form-field ::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
.full-width {
width: 100%;
min-width: 0;
}
}
[role='alert'] {
margin: 1rem 1.5rem 0;
padding: 0.75rem;
border-radius: var(--ui-radius-sm, 0.5rem);
color: var(--ui-error-text);
background: var(--ui-error-bg);
}
@@ -0,0 +1,237 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { By } from '@angular/platform-browser';
import { MatExpansionPanel } from '@angular/material/expansion';
import { RulesPanel } from './rules-panel';
import { RuleService, RuleType } from '../../services/rule-service';
import { TranslationService } from '../../services/translation-service';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
import { vi } from '../../../testing/vitest-compat';
import {
chooseInDialog,
clickDialogButton,
dialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
describe('rule dialog', () => {
let fixture: ComponentFixture<RulesPanel>;
let component: RulesPanel;
const addButton = (index: number) =>
fixture.nativeElement.querySelectorAll('.add-buttons button')[index] as HTMLButtonElement;
const editButton = (index: number) =>
fixture.nativeElement
.querySelectorAll('.rule-item')
[index].querySelector('[aria-label="Modifier la règle"]') as HTMLButtonElement;
const nameInput = () => dialogField('Nom de la règle').querySelector('input')!;
const title = () => ruleDialog()!.querySelector('h2')!.textContent!.trim();
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
beforeEach(async () => {
localStorage.clear();
vi.setSystemTime(new Date('2024-01-01T12:00:00Z'));
await TestBed.configureTestingModule({
imports: [RulesPanel],
providers: [provideZonelessChangeDetection(), RuleService],
}).compileComponents();
TestBed.inject(TranslationService).setLanguage('fr');
fixture = TestBed.createComponent(RulesPanel);
component = fixture.componentInstance;
fixture.detectChanges();
fixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();
await fixture.whenStable();
});
afterEach(() => {
localStorage.clear();
vi.useRealTimers();
});
it.each([
[0, 'Nouvelle Règle'],
[1, 'Nouvelle Période'],
[2, 'Prévention des pertes'],
])('opens one dialog to add a rule of kind %i with its defaults', async (index, name) => {
addButton(index).focus();
addButton(index).click();
await fixture.whenStable();
expect(document.querySelectorAll('mat-dialog-container')).toHaveLength(1);
expect(title()).toBe('Ajouter une règle');
expect(nameInput().value).toBe(name);
await expect.poll(() => ruleDialog()!.contains(document.activeElement)).toBe(true);
expect(dialogButton('Ajouter')).toBeTruthy();
expect(ruleDialog()!.querySelector('[role="alert"]')).toBeNull();
});
it.each([
[1, 'Samedi Malin', 'Jour férié tombe un'],
[2, 'Vacances de Noël', 'Date de début'],
[5, 'Séquence de travail maximale', 'Éléments du planning'],
])(
'opens the same dialog to edit rule %i, filled with the saved rule',
async (index, name, field) => {
editButton(index).focus();
editButton(index).click();
await fixture.whenStable();
expect(title()).toBe('Modifier la règle');
expect(nameInput().value).toBe(name);
expect(dialogField(field)).toBeTruthy();
expect(dialogButton('Enregistrer')).toBeTruthy();
},
);
it('keeps the list as it is while a rule is being added or edited', async () => {
const list = () => fixture.nativeElement.querySelector('.rules-list').innerHTML;
const before = list();
editButton(1).click();
await fixture.whenStable();
nameInput().value = 'Pas encore enregistrée';
nameInput().dispatchEvent(new Event('input', { bubbles: true }));
await fixture.whenStable();
expect(list()).toBe(before);
expect(fixture.nativeElement.querySelector('.rule-editor')).toBeNull();
expect(fixture.nativeElement.querySelector('.add-buttons').classList).not.toContain(
'hidden',
);
});
it('adds a rule once Add is chosen and returns focus to the add button', async () => {
const count = component.rules.length;
addButton(0).focus();
addButton(0).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Ma règle');
await chooseInDialog(fixture, 'Force de la règle', 'Obligation');
await chooseInDialog(fixture, 'Jour férié tombe un', 'Vendredi');
await clickDialogButton(fixture, 'Ajouter');
await closed();
expect(component.rules).toHaveLength(count + 1);
expect(component.rules.at(-1)).toEqual({
name: 'Ma règle',
type: RuleType.IF_THEN,
force: 'obligation',
dayOfWeek: 5,
placeDays: 2,
placeType: 'cp',
placement: 'auto',
rewardDays: 1,
rewardType: 'other',
id: expect.any(String),
enabled: true,
});
expect(document.activeElement).toBe(addButton(0));
});
it('adds an imposed period with the dates it was given', async () => {
addButton(1).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Date de début', '21/12/2024');
await typeInDialog(fixture, 'Date de fin', '31/12/2024');
await typeInDialog(fixture, 'Jours', '4');
await clickDialogButton(fixture, 'Ajouter');
await closed();
const rule = component.rules.at(-1)!;
if (rule.type !== RuleType.TIME_WINDOW) throw new Error('Expected a time window');
expect(rule).toMatchObject({ name: 'Nouvelle Période', force: 'preference', placeDays: 4 });
expect(new Date(rule.startDate)).toEqual(new Date(2024, 11, 21));
expect(new Date(rule.endDate)).toEqual(new Date(2024, 11, 31));
});
it('replaces the saved rule with the edited one and returns focus to the edit button', async () => {
const ifThen = component.rules[1];
const optimization = component.rules[5];
editButton(1).focus();
editButton(1).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Samedi modifié');
await chooseInDialog(fixture, 'Position', 'Avant');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.rules[1]).toEqual({
...ifThen,
name: 'Samedi modifié',
placement: 'before',
});
expect(document.activeElement).toBe(editButton(1));
editButton(5).click();
await fixture.whenStable();
await chooseInDialog(fixture, 'Direction', 'Maximiser');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.rules[5]).toEqual({
...optimization,
configuration: { ...OPTIMIZATION_PRESETS.longestWorkSequence, direction: 'maximize' },
});
expect(component.rules).toHaveLength(8);
});
it.each(['Annuler', 'Escape'])(
'%s closes the dialog without saving and returns focus to the control that opened it',
async (way) => {
const before = structuredClone(component.rules);
editButton(2).focus();
editButton(2).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Ne pas enregistrer');
if (way === 'Escape') {
ruleDialog()!.dispatchEvent(
new KeyboardEvent('keydown', {
key: 'Escape',
code: 'Escape',
keyCode: 27,
bubbles: true,
}),
);
await fixture.whenStable();
} else await clickDialogButton(fixture, way);
await closed();
expect(component.rules).toEqual(before);
expect(document.activeElement).toBe(editButton(2));
addButton(2).focus();
addButton(2).click();
await fixture.whenStable();
await clickDialogButton(fixture, way === 'Escape' ? 'Annuler' : way);
await closed();
expect(component.rules).toEqual(before);
expect(document.activeElement).toBe(addButton(2));
},
);
it('keeps the dialog open and shows the error beside the form until the rule is valid', async () => {
addButton(0).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', ' ');
await clickDialogButton(fixture, 'Ajouter');
expect(ruleDialog()).not.toBeNull();
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'Saisissez un nom de règle.',
);
expect(component.rules).toHaveLength(8);
await typeInDialog(fixture, 'Nom de la règle', 'Règle valide');
await clickDialogButton(fixture, 'Ajouter');
await closed();
expect(component.rules.at(-1)!.name).toBe('Règle valide');
});
it('shows the optimization error without changing the saved rule', async () => {
editButton(6).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '0');
await clickDialogButton(fixture, 'Enregistrer');
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'seuil entier positif',
);
expect(component.rules[6]).toMatchObject({
configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit,
});
});
});
@@ -0,0 +1,225 @@
import { ChangeDetectionStrategy, Component, effect, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { DateAdapter } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import {
MAT_DIALOG_DATA,
MatDialogActions,
MatDialogClose,
MatDialogContent,
MatDialogRef,
MatDialogTitle,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { SelectableDayType } from '../../services/calendar-service';
import {
IfThenRule,
OptimizationRule,
PlacementStrategy,
RuleType,
TimeWindowRule,
VacationRule,
} from '../../services/rule-service';
import {
OPTIMIZATION_CATALOG,
OPTIMIZATION_PRESETS,
validateOptimizationConfiguration,
type OptimizationElements,
type OptimizationMeasure,
} from '../../services/planning-objectives';
import { TranslationService } from '../../services/translation-service';
import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';
/** The rule to edit, or the kind of rule to create. */
export type RuleDialogData = { rule: VacationRule } | { type: RuleType };
/** Adds or edits one planning rule; closes with the saved rule, or with nothing when cancelled. */
@Component({
selector: 'app-rule-dialog',
imports: [
MatButtonModule,
MatDatepickerModule,
MatDialogActions,
MatDialogClose,
MatDialogContent,
MatDialogTitle,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
FormsModule,
],
templateUrl: './rule-dialog.html',
styleUrl: './rule-dialog.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: DAY_FIRST_DATE_PROVIDERS,
})
export class RuleDialog {
private readonly data = inject<RuleDialogData>(MAT_DIALOG_DATA);
private readonly dialogRef = inject<MatDialogRef<RuleDialog, VacationRule>>(MatDialogRef);
protected readonly translationService = inject(TranslationService);
private readonly dateAdapter = inject(DateAdapter);
get tr() {
return this.translationService.tr;
}
constructor() {
effect(() => {
this.dateAdapter.setLocale(this.translationService.locale());
});
}
protected readonly RuleType = RuleType;
protected readonly isNew = !('rule' in this.data);
protected readonly placeDayTypes = Object.values(SelectableDayType);
protected readonly rewardDayTypes = Object.values(SelectableDayType).filter(
(t) => t !== SelectableDayType.ANY,
);
protected get forceOptions() {
const preference = {
value: 'preference' as const,
label: () => this.tr().rules.preference,
};
return this.editBuffer.type === RuleType.OPTIMIZATION
? [preference]
: [
{ value: 'obligation' as const, label: () => this.tr().rules.obligation },
preference,
];
}
protected readonly optimizationElements = [
...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)),
];
protected get optimizationConfiguration() {
return this.editBuffer.type === RuleType.OPTIMIZATION
? this.editBuffer.configuration
: undefined;
}
protected get optimizationMeasures() {
return OPTIMIZATION_CATALOG.filter(
(row) => row.elements === this.optimizationConfiguration?.elements,
);
}
protected get optimizationConditions() {
return (
this.optimizationMeasures.find(
(row) => row.measure === this.optimizationConfiguration?.measure,
)?.conditions ?? []
);
}
protected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const;
protected readonly optimizationDirections = ['minimize', 'maximize'] as const;
protected validationError = signal('');
public changeOptimizationElements(elements: OptimizationElements) {
this.changeOptimizationMeasure(
OPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure,
);
}
public changeOptimizationMeasure(measure: OptimizationMeasure) {
if (this.editBuffer.type !== RuleType.OPTIMIZATION) return;
const row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!;
const previous = this.editBuffer.configuration;
const conditions: readonly string[] = row.conditions;
this.editBuffer.configuration = {
elements: row.elements,
conditions:
previous?.conditions.filter((condition) => conditions.includes(condition)) ?? [],
aggregation: previous?.aggregation ?? 'sum',
direction: previous?.direction ?? 'minimize',
...(measure === 'work-sequence-deficit'
? {
measure,
thresholdDays: previous?.measure === measure ? previous.thresholdDays : 5,
}
: { measure }),
};
}
protected get daysOfWeek() {
const tr = this.tr();
return [
{ value: 1, label: tr.rules.daysOfWeek[1] },
{ value: 2, label: tr.rules.daysOfWeek[2] },
{ value: 3, label: tr.rules.daysOfWeek[3] },
{ value: 4, label: tr.rules.daysOfWeek[4] },
{ value: 5, label: tr.rules.daysOfWeek[5] },
{ value: 6, label: tr.rules.daysOfWeek[6] },
{ value: 0, label: tr.rules.daysOfWeek[0] },
];
}
protected get placementOptions(): { value: PlacementStrategy; label: string }[] {
const tr = this.tr();
return [
{ value: 'before', label: tr.rules.placement.before },
{ value: 'after', label: tr.rules.placement.after },
{ value: 'around', label: tr.rules.placement.around },
{ value: 'auto', label: tr.rules.placement.auto },
];
}
protected editBuffer: Partial<VacationRule> =
'rule' in this.data ? structuredClone(this.data.rule) : this.newRule(this.data.type);
private newRule(type: RuleType): Partial<VacationRule> {
if (type === RuleType.IF_THEN) {
return {
name: this.tr().rules.defaultNewRuleName,
type: RuleType.IF_THEN,
force: 'preference',
dayOfWeek: 6,
placeDays: 2,
placeType: SelectableDayType.CP,
placement: 'auto',
rewardDays: 1,
rewardType: SelectableDayType.OTHER,
} as Partial<IfThenRule>;
}
if (type === RuleType.OPTIMIZATION) {
return {
name: this.tr().rules.optimization.defaultName,
type,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),
} satisfies Partial<OptimizationRule>;
}
return {
name: this.tr().rules.defaultNewPeriodName,
type: RuleType.TIME_WINDOW,
force: 'preference',
startDate: new Date(),
endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
placeDays: 5,
placeType: SelectableDayType.CP,
} as Partial<TimeWindowRule>;
}
protected getDayTypeLabel(type: string | undefined | null): string {
if (!type) return '';
return this.translationService.getDayTypeLabel(type);
}
protected save() {
if (!this.editBuffer.name?.trim()) {
this.validationError.set(this.tr().rules.optimization.nameRequired);
return;
}
if (this.editBuffer.type === RuleType.OPTIMIZATION) {
if (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) {
this.validationError.set(this.tr().rules.optimization.invalidConfiguration);
return;
}
this.editBuffer.force = 'preference';
}
this.dialogRef.close(
(this.isNew
? { ...this.editBuffer, id: crypto.randomUUID(), enabled: true }
: this.editBuffer) as VacationRule,
);
}
}
+58 -464
View File
@@ -20,401 +20,75 @@
cdkDrag
cdkDragLockAxis="y"
[cdkDragStartDelay]="{ touch: 180, mouse: 0 }"
[cdkDragDisabled]="editingRuleId() === rule.id"
[class.editing]="editingRuleId() === rule.id"
>
@if (editingRuleId() !== rule.id) {
<div class="rule-display">
<div class="rule-header">
<div
class="rule-drag-grip"
cdkDragHandle
[title]="tr().rules.dragRule"
aria-hidden="true"
>
<mat-icon>drag_indicator</mat-icon>
</div>
<mat-slide-toggle
[checked]="rule.enabled"
(change)="toggleRule(rule.id)"
color="primary"
>
<span class="rule-name"
><span class="rule-number">{{ i + 1 }}.</span>
{{ rule.name }}</span
>
</mat-slide-toggle>
<div class="rule-display">
<div class="rule-header">
<div
class="rule-drag-grip"
cdkDragHandle
[title]="tr().rules.dragRule"
aria-hidden="true"
>
<mat-icon>drag_indicator</mat-icon>
</div>
<div class="rule-summary">
<span
class="rule-force"
[class.obligation]="rule.force === 'obligation'"
<mat-slide-toggle
[checked]="rule.enabled"
(change)="toggleRule(rule.id)"
color="primary"
>
<span class="rule-name"
><span class="rule-number">{{ i + 1 }}.</span> {{ rule.name }}</span
>
{{
rule.force === 'obligation'
? tr().rules.obligation
: tr().rules.preference
}}
</span>
<span [innerHTML]="getRuleSummary(rule)"></span>
</div>
<div class="rule-actions">
<button
mat-icon-button
[disabled]="i === 0"
[aria-label]="tr().rules.moveRuleUp"
(click)="moveRule(i, -1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_up</mat-icon>
</button>
<button
mat-icon-button
[disabled]="i === rules.length - 1"
[aria-label]="tr().rules.moveRuleDown"
(click)="moveRule(i, 1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_down</mat-icon>
</button>
<button
mat-icon-button
[aria-label]="tr().rules.editRule"
(click)="startEdit(rule, $event)"
>
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
color="warn"
[aria-label]="tr().rules.deleteRule"
(click)="deleteRule(rule.id, $event)"
>
<mat-icon>delete</mat-icon>
</button>
</div>
</mat-slide-toggle>
</div>
} @else {
<div class="rule-editor">
<h4>{{ tr().rules.editRule }}</h4>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.ruleName }}</mat-label>
<input matInput [(ngModel)]="$any(editBuffer).name" required />
</mat-form-field>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.force }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).force">
@for (option of forceOptions; track option.value) {
<mat-option [value]="option.value">{{
option.label()
}}</mat-option>
}
</mat-select>
</mat-form-field>
@if ($any(editBuffer).type === RuleType.IF_THEN) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.holidayFalls }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).dayOfWeek">
@for (day of daysOfWeek; track day.value) {
<mat-option [value]="day.value">{{
day.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.position }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placement">
@for (opt of placementOptions; track opt.value) {
<mat-option [value]="opt.value">{{
opt.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.getBonus }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).rewardDays"
min="0"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).rewardType">
@for (type of rewardDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {
<ng-container [ngTemplateOutlet]="optimizationEditor" />
} @else {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.startDate }}</mat-label>
<input
matInput
[matDatepicker]="startPicker"
[(ngModel)]="$any(editBuffer).startDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="startPicker"
></mat-datepicker-toggle>
<mat-datepicker #startPicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.endDate }}</mat-label>
<input
matInput
[matDatepicker]="endPicker"
[(ngModel)]="$any(editBuffer).endDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="endPicker"
></mat-datepicker-toggle>
<mat-datepicker #endPicker></mat-datepicker>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
}
@if (validationError()) {
<p role="alert">{{ validationError() }}</p>
}
<div class="editor-actions">
<button mat-button (click)="cancelEdit()">
{{ tr().rules.cancel }}
</button>
<button mat-flat-button color="primary" (click)="saveEdit()">
{{ tr().rules.save }}
</button>
</div>
<div class="rule-summary">
<span class="rule-force" [class.obligation]="rule.force === 'obligation'">
{{
rule.force === 'obligation'
? tr().rules.obligation
: tr().rules.preference
}}
</span>
<span [innerHTML]="getRuleSummary(rule)"></span>
</div>
}
</div>
}
@if (isAddingNew()) {
<div class="rule-item editing">
<div class="rule-editor">
<h4>{{ tr().rules.addRule }}</h4>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.ruleName }}</mat-label>
<input matInput [(ngModel)]="$any(editBuffer).name" required />
</mat-form-field>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.force }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).force">
@for (option of forceOptions; track option.value) {
<mat-option [value]="option.value">{{ option.label() }}</mat-option>
}
</mat-select>
</mat-form-field>
@if (newRuleType() === RuleType.IF_THEN) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.holidayFalls }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).dayOfWeek">
@for (day of daysOfWeek; track day.value) {
<mat-option [value]="day.value">{{ day.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.position }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placement">
@for (opt of placementOptions; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.getBonus }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).rewardDays"
min="0"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).rewardType">
@for (type of rewardDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {
<ng-container [ngTemplateOutlet]="optimizationEditor" />
} @else {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.startDate }}</mat-label>
<input
matInput
[matDatepicker]="startPicker"
[(ngModel)]="$any(editBuffer).startDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="startPicker"
></mat-datepicker-toggle>
<mat-datepicker #startPicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.endDate }}</mat-label>
<input
matInput
[matDatepicker]="endPicker"
[(ngModel)]="$any(editBuffer).endDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="endPicker"
></mat-datepicker-toggle>
<mat-datepicker #endPicker></mat-datepicker>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
}
@if (validationError()) {
<p role="alert">{{ validationError() }}</p>
}
<div class="editor-actions">
<button mat-button (click)="cancelEdit()">{{ tr().rules.cancel }}</button>
<button mat-flat-button color="primary" (click)="saveEdit()">
{{ tr().rules.add }}
<div class="rule-actions">
<button
mat-icon-button
[disabled]="i === 0"
[aria-label]="tr().rules.moveRuleUp"
(click)="moveRule(i, -1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_up</mat-icon>
</button>
<button
mat-icon-button
[disabled]="i === rules.length - 1"
[aria-label]="tr().rules.moveRuleDown"
(click)="moveRule(i, 1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_down</mat-icon>
</button>
<button
mat-icon-button
[aria-label]="tr().rules.editRule"
(click)="startEdit(rule, $event)"
>
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
color="warn"
[aria-label]="tr().rules.deleteRule"
(click)="deleteRule(rule.id, $event)"
>
<mat-icon>delete</mat-icon>
</button>
</div>
</div>
</div>
}
<div class="add-buttons" [class.hidden]="isAddingNew() || editingRuleId()">
<div class="add-buttons">
<button mat-stroked-button (click)="startAddNew(RuleType.IF_THEN)">
<mat-icon>add</mat-icon> {{ tr().rules.newIfThenRule }}
</button>
@@ -427,83 +101,3 @@
</div>
</div>
</mat-expansion-panel>
<ng-template #optimizationEditor>
@if (optimizationConfiguration; as configuration) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.elementsLabel }}</mat-label>
<mat-select
[ngModel]="configuration.elements"
(ngModelChange)="changeOptimizationElements($event)"
>
@for (elements of optimizationElements; track elements) {
<mat-option [value]="elements">{{
tr().rules.optimization.elements[elements]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.measureLabel }}</mat-label>
<mat-select
[ngModel]="configuration.measure"
(ngModelChange)="changeOptimizationMeasure($event)"
>
@for (row of optimizationMeasures; track row.measure) {
<mat-option [value]="row.measure">{{
tr().rules.optimization.measures[row.measure]
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
@if (optimizationConditions.length) {
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.optimization.conditionsLabel }}</mat-label>
<mat-select multiple [(ngModel)]="configuration.conditions">
@for (condition of optimizationConditions; track condition) {
<mat-option [value]="condition">{{
tr().rules.optimization.conditions[condition]
}}</mat-option>
}
</mat-select>
</mat-form-field>
}
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.aggregationLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.aggregation">
@for (aggregation of optimizationAggregations; track aggregation) {
<mat-option [value]="aggregation">{{
tr().rules.optimization.aggregations[aggregation]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.directionLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.direction">
@for (direction of optimizationDirections; track direction) {
<mat-option [value]="direction">{{
tr().rules.optimization.directions[direction]
}}</mat-option>
}
</mat-select>
</mat-form-field>
@if (configuration.measure === 'work-sequence-deficit') {
<mat-form-field>
<mat-label>{{ tr().rules.optimization.thresholdLabel }}</mat-label>
<input
matInput
type="number"
min="1"
step="1"
required
[(ngModel)]="configuration.thresholdDays"
/>
</mat-form-field>
}
</div>
}
</ng-template>
@@ -71,13 +71,9 @@
background: var(--ui-panel-bg);
color: var(--mat-sys-on-surface);
&:hover:not(.editing) {
&:hover {
border-color: var(--mat-sys-outline, #777680);
}
&.editing {
border: 1px solid var(--mat-sys-primary, #005cbb);
}
}
.cdk-drag-preview {
@@ -213,59 +209,6 @@
}
}
.rule-editor {
padding: clamp(0.75rem, 3cqi, 1.25rem);
display: flex;
flex-direction: column;
gap: 16px;
background: var(--mat-sys-surface-container-high, #e9e9ee);
border-radius: var(--ui-radius-sm, 0.5rem);
h4 {
margin: 0;
font-size: 1.1rem;
font-weight: 500;
}
.editor-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
.action-text {
flex-basis: 100%;
font-weight: 500;
}
mat-form-field {
flex: 1 1 11rem;
min-width: 0;
max-width: 100%;
::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
}
.small-input {
flex: 0 1 6.25rem;
}
}
.full-width {
width: 100%;
min-width: 0;
}
.editor-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 12px;
margin-top: 8px;
}
}
.add-buttons {
display: flex;
flex-wrap: wrap;
@@ -273,10 +216,6 @@
gap: 8px;
margin-top: 8px;
&.hidden {
display: none;
}
button {
border-radius: var(--ui-radius-sm);
min-height: 2.75rem;
@@ -9,10 +9,18 @@ import { LiveAnnouncer } from '@angular/cdk/a11y';
import { vi } from '../../../testing/vitest-compat';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
import { MatExpansionPanel } from '@angular/material/expansion';
import {
chooseInDialog,
clickDialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
describe('RulesPanel', () => {
let component: RulesPanel;
let fixture: ComponentFixture<RulesPanel>;
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
beforeEach(async () => {
// Clear localStorage before testing
@@ -85,57 +93,6 @@ describe('RulesPanel', () => {
);
});
it('should start adding new If-Then rule', () => {
component.startAddNew(RuleType.IF_THEN);
expect(component['isAddingNew']()).toBe(true);
expect(component['newRuleType']()).toBe(RuleType.IF_THEN);
expect(component['editBuffer'].type).toBe(RuleType.IF_THEN);
expect(component['editBuffer'].name).toBe('Nouvelle Règle');
});
it('should start adding new Time Window rule', () => {
component.startAddNew(RuleType.TIME_WINDOW);
expect(component['isAddingNew']()).toBe(true);
expect(component['newRuleType']()).toBe(RuleType.TIME_WINDOW);
expect(component['editBuffer'].type).toBe(RuleType.TIME_WINDOW);
expect(component['editBuffer'].name).toBe('Nouvelle Période');
});
it('should cancel edit', () => {
component.startAddNew(RuleType.IF_THEN);
component.cancelEdit();
expect(component['isAddingNew']()).toBe(false);
expect(component['editingRuleId']()).toBeNull();
expect(Object.keys(component['editBuffer']).length).toBe(0);
});
it('should save a new rule', () => {
const initialCount = component.rules.length;
component.startAddNew(RuleType.IF_THEN);
component['editBuffer'].name = 'Custom Test Rule';
component.saveEdit();
expect(component.rules.length).toBe(initialCount + 1);
expect(component.rules.some((r) => r.name === 'Custom Test Rule')).toBe(true);
});
it('should update an existing rule', () => {
const targetRule = component.rules[0];
// Create a mock event with stopPropagation
const mockEvent = { stopPropagation: () => {} } as Event;
component.startEdit(targetRule, mockEvent);
component['editBuffer'].name = 'Updated Name';
component.saveEdit();
expect(component.rules.find((r) => r.id === targetRule.id)?.name).toBe('Updated Name');
});
it('should delete a rule', () => {
const targetId = component.rules[0].id;
const initialCount = component.rules.length;
@@ -165,11 +122,20 @@ describe('RulesPanel', () => {
it('creates, edits and moves an optimization using the keyboard controls with preference-only mode', async () => {
fixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();
component.startAddNew(RuleType.OPTIMIZATION);
fixture.detectChanges();
expect(component['forceOptions'].map((option) => option.value)).toEqual(['preference']);
expect(fixture.nativeElement.textContent).toContain('Éléments du planning');
component['editBuffer'].name = 'Mes pertes';
component.saveEdit();
await fixture.whenStable();
dialogField('Force de la règle').querySelector<HTMLElement>('mat-select')!.click();
await fixture.whenStable();
expect(
Array.from(document.querySelectorAll('mat-option')).map((option) =>
option.textContent?.trim(),
),
).toEqual(['Préférence']);
document.querySelector<HTMLElement>('.cdk-overlay-transparent-backdrop')!.click();
await fixture.whenStable();
expect(ruleDialog()!.textContent).toContain('Éléments du planning');
await typeInDialog(fixture, 'Nom de la règle', 'Mes pertes');
await clickDialogButton(fixture, 'Ajouter');
await closed();
await fixture.whenStable();
const rule = component.rules.at(-1)!;
expect(rule).toMatchObject({
@@ -192,8 +158,10 @@ describe('RulesPanel', () => {
expect(document.activeElement).toBe(moveUp);
expect(announce).toHaveBeenCalledWith('Mes pertes : position 8 sur 9.');
component.startEdit(rule, new Event('click'));
component['editBuffer'].name = 'Pertes modifiées';
component.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Pertes modifiées');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.rules[7].name).toBe('Pertes modifiées');
component.toggleRule(rule.id);
expect(component.rules[7].enabled).toBe(false);
@@ -201,25 +169,31 @@ describe('RulesPanel', () => {
expect(component.rules.some((candidate) => candidate.id === rule.id)).toBe(false);
});
it('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', () => {
it('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', async () => {
component.startAddNew(RuleType.OPTIMIZATION);
component.saveEdit();
await fixture.whenStable();
await clickDialogButton(fixture, 'Ajouter');
await closed();
const rule = component.rules.at(-1)!;
component.startEdit(rule, new Event('click'));
const configuration = component['optimizationConfiguration']!;
configuration.conditions = [];
component.cancelEdit();
await fixture.whenStable();
await chooseInDialog(
fixture,
'Conditions (toutes doivent être vérifiées)',
'À risque d’expiration',
);
await clickDialogButton(fixture, 'Annuler');
await closed();
expect(component.rules.at(-1)).toMatchObject({
configuration: OPTIMIZATION_PRESETS.unplacedAtRisk,
});
component.startEdit(rule, new Event('click'));
component.changeOptimizationMeasure('work-sequence-deficit');
const invalid = component['optimizationConfiguration'];
if (invalid?.measure !== 'work-sequence-deficit') throw new Error('Expected deficit');
invalid.thresholdDays = 0;
component.saveEdit();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('[role="alert"]').textContent).toContain(
await fixture.whenStable();
await chooseInDialog(fixture, 'Éléments du planning', 'Séquences de travail');
await chooseInDialog(fixture, 'Mesure', 'Déficit des séquences de travail');
await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '0');
await clickDialogButton(fixture, 'Enregistrer');
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'seuil entier positif',
);
expect(component.rules.at(-1)).toMatchObject({
+22 -217
View File
@@ -1,44 +1,15 @@
import {
Component,
ChangeDetectionStrategy,
ChangeDetectorRef,
inject,
signal,
effect,
} from '@angular/core';
import {
RuleService,
RuleType,
IfThenRule,
TimeWindowRule,
OptimizationRule,
VacationRule,
PlacementStrategy,
} from '../../services/rule-service';
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, inject } from '@angular/core';
import { RuleService, RuleType, VacationRule } from '../../services/rule-service';
import { SelectableDayType } from '../../services/calendar-service';
import { TranslationService } from '../../services/translation-service';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { FormsModule } from '@angular/forms';
import { NgTemplateOutlet } from '@angular/common';
import { MatDialog } from '@angular/material/dialog';
import { LiveAnnouncer } from '@angular/cdk/a11y';
import * as labels from '../../services/planner-labels';
import {
OPTIMIZATION_CATALOG,
OPTIMIZATION_PRESETS,
validateOptimizationConfiguration,
type OptimizationElements,
type OptimizationMeasure,
} from '../../services/planning-objectives';
import { DateAdapter } from '@angular/material/core';
import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';
import { RuleDialog, type RuleDialogData } from './rule-dialog';
import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/drag-drop';
@Component({
@@ -48,12 +19,6 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d
MatIconModule,
MatButtonModule,
MatSlideToggleModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatDatepickerModule,
FormsModule,
NgTemplateOutlet,
CdkDropList,
CdkDrag,
CdkDragHandle,
@@ -61,12 +26,11 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d
templateUrl: './rules-panel.html',
styleUrl: './rules-panel.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: DAY_FIRST_DATE_PROVIDERS,
})
export class RulesPanel {
public ruleService = inject(RuleService);
protected readonly translationService = inject(TranslationService);
private readonly dateAdapter = inject(DateAdapter);
private readonly dialog = inject(MatDialog);
private readonly liveAnnouncer = inject(LiveAnnouncer);
private readonly changeDetector = inject(ChangeDetectorRef);
@@ -74,109 +38,7 @@ export class RulesPanel {
return this.translationService.tr;
}
constructor() {
effect(() => {
this.dateAdapter.setLocale(this.translationService.locale());
});
}
protected readonly RuleType = RuleType;
protected readonly placeDayTypes = Object.values(SelectableDayType);
protected readonly rewardDayTypes = Object.values(SelectableDayType).filter(
(t) => t !== SelectableDayType.ANY,
);
protected get forceOptions() {
const preference = {
value: 'preference' as const,
label: () => this.tr().rules.preference,
};
return this.editBuffer.type === RuleType.OPTIMIZATION
? [preference]
: [
{ value: 'obligation' as const, label: () => this.tr().rules.obligation },
preference,
];
}
protected readonly optimizationElements = [
...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)),
];
protected get optimizationConfiguration() {
return this.editBuffer.type === RuleType.OPTIMIZATION
? this.editBuffer.configuration
: undefined;
}
protected get optimizationMeasures() {
return OPTIMIZATION_CATALOG.filter(
(row) => row.elements === this.optimizationConfiguration?.elements,
);
}
protected get optimizationConditions() {
return (
this.optimizationMeasures.find(
(row) => row.measure === this.optimizationConfiguration?.measure,
)?.conditions ?? []
);
}
protected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const;
protected readonly optimizationDirections = ['minimize', 'maximize'] as const;
protected validationError = signal('');
public changeOptimizationElements(elements: OptimizationElements) {
this.changeOptimizationMeasure(
OPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure,
);
}
public changeOptimizationMeasure(measure: OptimizationMeasure) {
if (this.editBuffer.type !== RuleType.OPTIMIZATION) return;
const row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!;
const previous = this.editBuffer.configuration;
const conditions: readonly string[] = row.conditions;
this.editBuffer.configuration = {
elements: row.elements,
conditions:
previous?.conditions.filter((condition) => conditions.includes(condition)) ?? [],
aggregation: previous?.aggregation ?? 'sum',
direction: previous?.direction ?? 'minimize',
...(measure === 'work-sequence-deficit'
? {
measure,
thresholdDays: previous?.measure === measure ? previous.thresholdDays : 5,
}
: { measure }),
};
}
protected get daysOfWeek() {
const tr = this.tr();
return [
{ value: 1, label: tr.rules.daysOfWeek[1] },
{ value: 2, label: tr.rules.daysOfWeek[2] },
{ value: 3, label: tr.rules.daysOfWeek[3] },
{ value: 4, label: tr.rules.daysOfWeek[4] },
{ value: 5, label: tr.rules.daysOfWeek[5] },
{ value: 6, label: tr.rules.daysOfWeek[6] },
{ value: 0, label: tr.rules.daysOfWeek[0] },
];
}
protected get placementOptions(): { value: PlacementStrategy; label: string }[] {
const tr = this.tr();
return [
{ value: 'before', label: tr.rules.placement.before },
{ value: 'after', label: tr.rules.placement.after },
{ value: 'around', label: tr.rules.placement.around },
{ value: 'auto', label: tr.rules.placement.auto },
];
}
protected editingRuleId = signal<string | null>(null);
protected isAddingNew = signal(false);
protected newRuleType = signal<RuleType>(RuleType.IF_THEN);
protected editBuffer: Partial<VacationRule> = {};
public get rules() {
return this.ruleService.rules;
}
@@ -229,41 +91,27 @@ export class RulesPanel {
public startEdit(rule: VacationRule, event: Event) {
event.stopPropagation();
this.editingRuleId.set(rule.id);
this.isAddingNew.set(false);
this.editBuffer = structuredClone(rule);
this.validationError.set('');
this.openRuleDialog({ rule });
}
public cancelEdit() {
this.editingRuleId.set(null);
this.isAddingNew.set(false);
this.editBuffer = {};
this.validationError.set('');
public startAddNew(type: RuleType) {
this.openRuleDialog({ type });
}
public saveEdit() {
if (!this.editBuffer.name?.trim()) {
this.validationError.set(this.tr().rules.optimization.nameRequired);
return;
}
if (this.editBuffer.type === RuleType.OPTIMIZATION) {
if (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) {
this.validationError.set(this.tr().rules.optimization.invalidConfiguration);
return;
}
this.editBuffer.force = 'preference';
}
if (this.editBuffer.id) {
this.ruleService.updateRule(this.editBuffer as VacationRule);
} else {
this.ruleService.addRule({
...this.editBuffer,
id: crypto.randomUUID(),
enabled: true,
} as VacationRule);
}
this.cancelEdit();
private openRuleDialog(data: RuleDialogData) {
this.dialog
.open<RuleDialog, RuleDialogData, VacationRule>(RuleDialog, {
data,
width: '40rem',
maxWidth: 'calc(100vw - 2rem)',
maxHeight: 'calc(100dvh - 2rem)',
})
.afterClosed()
.subscribe((rule) => {
if (!rule) return;
if ('rule' in data) this.ruleService.updateRule(rule);
else this.ruleService.addRule(rule);
});
}
public deleteRule(id: string, event: Event) {
@@ -271,49 +119,6 @@ export class RulesPanel {
this.ruleService.deleteRule(id);
}
public startAddNew(type: RuleType) {
this.isAddingNew.set(true);
this.editingRuleId.set(null);
this.newRuleType.set(type);
this.validationError.set('');
if (type === RuleType.IF_THEN) {
this.editBuffer = {
name: this.tr().rules.defaultNewRuleName,
type: RuleType.IF_THEN,
force: 'preference',
dayOfWeek: 6,
placeDays: 2,
placeType: SelectableDayType.CP,
placement: 'auto',
rewardDays: 1,
rewardType: SelectableDayType.OTHER,
} as Partial<IfThenRule>;
} else if (type === RuleType.OPTIMIZATION) {
this.editBuffer = {
name: this.tr().rules.optimization.defaultName,
type,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),
} satisfies Partial<OptimizationRule>;
} else {
this.editBuffer = {
name: this.tr().rules.defaultNewPeriodName,
type: RuleType.TIME_WINDOW,
force: 'preference',
startDate: new Date(),
endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
placeDays: 5,
placeType: SelectableDayType.CP,
} as Partial<TimeWindowRule>;
}
}
protected getDayTypeLabel(type: string | undefined | null): string {
if (!type) return '';
return this.translationService.getDayTypeLabel(type);
}
public getRuleSummary(rule: VacationRule): string {
const tr = this.tr();
if (rule.type === RuleType.OPTIMIZATION) {
@@ -8,38 +8,23 @@ import { TranslationService } from '../../services/translation-service';
import { calculatePlanningInternal } from '../../services/leave-planner.core';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
import { optimizationSummary } from '../../services/planner-labels';
import {
chooseInDialog,
clickDialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
import { RulesPanel } from './rules-panel';
describe('work-sequence rule editor and reload', () => {
let fixture: ComponentFixture<RulesPanel>;
let component: RulesPanel;
async function choose(label: string, text: string) {
const fields: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('mat-form-field'),
);
const select = fields
.find((field) => field.querySelector('mat-label')?.textContent?.trim() === label)
?.querySelector<HTMLElement>('mat-select');
if (!select) throw new Error(`Missing select ${label}`);
select.click();
await fixture.whenStable();
const option = Array.from(document.querySelectorAll<HTMLElement>('mat-option')).find(
(candidate) => candidate.textContent?.trim() === text,
);
if (!option) throw new Error(`Missing option ${text}`);
option.click();
await fixture.whenStable();
document.querySelector<HTMLElement>('.cdk-overlay-backdrop')?.click();
await fixture.whenStable();
}
async function setInput(selector: string, value: string) {
const input: HTMLInputElement = fixture.nativeElement.querySelector(selector);
input.value = value;
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
}
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
const choose = (label: string, text: string) => chooseInDialog(fixture, label, text);
const threshold = () =>
dialogField('Seuil de préférence en jours ouvrés').querySelector('input')!;
beforeEach(async () => {
localStorage.clear();
@@ -63,19 +48,16 @@ describe('work-sequence rule editor and reload', () => {
it('creates threshold five, edits it to three, and restores its effect, order and activation after reload', async () => {
component.startAddNew(RuleType.OPTIMIZATION);
await fixture.whenStable();
await setInput('input:not([type="number"])', 'Mes reprises');
await typeInDialog(fixture, 'Nom de la règle', 'Mes reprises');
await choose('Éléments du planning', 'Séquences de travail');
await choose('Mesure', 'Déficit des séquences de travail');
await choose('Conditions (toutes doivent être vérifiées)', 'Internes');
await choose('Conditions (toutes doivent être vérifiées)', 'Non vides');
const threshold: HTMLInputElement =
fixture.nativeElement.querySelector('input[type="number"]');
expect(threshold.value).toBe('5');
expect(threshold.min).toBe('1');
expect(threshold.step).toBe('1');
expect(fixture.nativeElement.textContent).toContain('Seuil de préférence en jours ouvrés');
component.saveEdit();
await fixture.whenStable();
expect(threshold().value).toBe('5');
expect(threshold().min).toBe('1');
expect(threshold().step).toBe('1');
await clickDialogButton(fixture, 'Ajouter');
await closed();
const rule = component.rules[0];
expect(rule).toMatchObject({ configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit });
expect(component.getRuleSummary(rule)).toBe(
@@ -92,9 +74,9 @@ describe('work-sequence rule editor and reload', () => {
});
component.startEdit(rule, new Event('click'));
await fixture.whenStable();
await setInput('input[type="number"]', '3');
component.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '3');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.getRuleSummary(component.rules[0])).toContain(
'pour atteindre 3 jours ouvrés',
);
@@ -105,11 +87,11 @@ describe('work-sequence rule editor and reload', () => {
component.startAddNew(RuleType.OPTIMIZATION);
await fixture.whenStable();
await setInput('input:not([type="number"])', 'Ma séquence maximale');
await typeInDialog(fixture, 'Nom de la règle', 'Ma séquence maximale');
await choose('Éléments du planning', 'Séquences de travail');
await choose('Agrégation', 'Maximum');
component.saveEdit();
await fixture.whenStable();
await clickDialogButton(fixture, 'Ajouter');
await closed();
const maximum = component.rules[1];
expect(maximum).toMatchObject({ configuration: OPTIMIZATION_PRESETS.longestWorkSequence });
component.toggleRule(maximum.id);
@@ -140,16 +122,16 @@ describe('work-sequence rule editor and reload', () => {
it('keeps the saved threshold and shows an accessible error for fractional input', async () => {
component.startAddNew(RuleType.OPTIMIZATION);
component.changeOptimizationMeasure('work-sequence-deficit');
await fixture.whenStable();
await setInput('input[type="number"]', '1.5');
component.saveEdit();
await fixture.whenStable();
await choose('Éléments du planning', 'Séquences de travail');
await choose('Mesure', 'Déficit des séquences de travail');
await typeInDialog(fixture, 'Seuil de préférence en jours ouvrés', '1.5');
await clickDialogButton(fixture, 'Ajouter');
expect(component.rules).toEqual([]);
expect(fixture.nativeElement.querySelector('[role="alert"]').textContent).toContain(
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'seuil entier positif',
);
expect(fixture.nativeElement.querySelector('input[type="number"]').value).toBe('1.5');
expect(threshold().value).toBe('1.5');
});
it('distinguishes aggregation units from the working-day threshold', () => {
+64
View File
@@ -0,0 +1,64 @@
import type { ComponentFixture } from '@angular/core/testing';
/** Drives the rule dialog, which Material renders in an overlay outside the panel's fixture. */
export const ruleDialog = () => document.querySelector<HTMLElement>('mat-dialog-container');
function openDialog(): HTMLElement {
const dialog = ruleDialog();
if (!dialog) throw new Error('The rule dialog is not open');
return dialog;
}
export function dialogField(label: string, index = 0): HTMLElement {
const field = Array.from(openDialog().querySelectorAll<HTMLElement>('mat-form-field')).filter(
(candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label,
)[index];
if (!field) throw new Error(`Missing labelled control: ${label}`);
return field;
}
export function dialogButton(text: string): HTMLButtonElement {
const button = Array.from(openDialog().querySelectorAll<HTMLButtonElement>('button')).find(
(candidate) => candidate.textContent?.trim() === text,
);
if (!button) throw new Error(`Missing dialog button: ${text}`);
return button;
}
export async function typeInDialog(
fixture: ComponentFixture<unknown>,
label: string,
value: string,
index = 0,
) {
const input = dialogField(label, index).querySelector<HTMLInputElement>('input')!;
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
await fixture.whenStable();
}
export async function chooseInDialog(
fixture: ComponentFixture<unknown>,
label: string,
text: string,
index = 0,
) {
const control = dialogField(label, index).querySelector<HTMLElement>('mat-select');
if (!control) throw new Error(`Missing select: ${label}`);
control.click();
await fixture.whenStable();
const option = Array.from(document.querySelectorAll<HTMLElement>('mat-option')).find(
(candidate) => candidate.textContent?.trim() === text,
);
if (!option) throw new Error(`Missing option: ${text}`);
option.click();
await fixture.whenStable();
// A multiple select stays open; its transparent backdrop is not the dialog's own.
document.querySelector<HTMLElement>('.cdk-overlay-transparent-backdrop')?.click();
await fixture.whenStable();
}
export async function clickDialogButton(fixture: ComponentFixture<unknown>, text: string) {
dialogButton(text).click();
await fixture.whenStable();
}