Compare commits

..
Author SHA1 Message Date
copilot-swe-agent[bot]andTHoguet 95f927386d Add logging service and refactor console.warn to use it
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-17 23:38:23 +00:00
copilot-swe-agent[bot] efe7b3da42 Initial plan 2025-11-17 23:30:03 +00:00
CopilotandTHoguet 54c2160f0d Fix setTimeout async anti-pattern in calendar-year component (#50)
* Initial plan

* fix: replace setTimeout async anti-pattern with queueMicrotask and void

Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-18 00:26:18 +01:00
Théophyl HoguetandCopilot 1f3789d82b Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-18 00:23:50 +01:00
Théophyl HoguetandCopilot 3fab4c4922 Update src/app/components/user-input/user-input.html
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-18 00:21:40 +01:00
Théophyl HoguetandCopilot df1b8a509d Update src/app/components/calendar-year/calendar-year.scss
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-18 00:18:19 +01:00
Théophyl HoguetandCopilot b97e9486e8 Update src/app/services/calendar-service.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-18 00:18:10 +01:00
17 changed files with 15450 additions and 15705 deletions

No files matched your search

+4 -4
View File
@@ -20,7 +20,7 @@ jobs:
cache: 'npm'
- name: Install dependencies
run: npm ci --legacy-peer-deps
run: npm ci
- name: Check code formatting with Prettier
run: npx prettier --check "src/**/*.{ts,html,scss,css,json}"
@@ -41,7 +41,7 @@ jobs:
cache: 'npm'
- name: Install dependencies
run: npm ci --legacy-peer-deps
run: npm ci
- name: Run TypeScript compiler
run: npx tsc --noEmit
@@ -59,7 +59,7 @@ jobs:
cache: 'npm'
- name: Install dependencies
run: npm ci --legacy-peer-deps
run: npm ci
- name: Run unit tests
run: npm test -- --watch=false --browsers=ChromeHeadless --code-coverage
@@ -85,7 +85,7 @@ jobs:
cache: 'npm'
- name: Install dependencies
run: npm ci --legacy-peer-deps
run: npm ci
- name: Build production bundle
run: npm run build -- --configuration production
+15137 -15134
View File
File diff suppressed because it is too large. Load diff
+68 -69
View File
@@ -1,71 +1,70 @@
{
"name": "vac-optimizer",
"version": "1.5.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"serve:ssr:vac-optimizer": "node dist/vac-optimizer/server/server.mjs",
"lint": "eslint \"src/**/*.ts\"",
"lint:fix": "eslint \"src/**/*.ts\" --fix",
"format": "prettier --write \"src/**/*.{ts,html,scss,css,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,html,scss,css,json}\""
},
"prettier": {
"printWidth": 100,
"singleQuote": true,
"overrides": [
{
"files": "*.html",
"options": {
"parser": "angular"
}
}
]
},
"private": true,
"dependencies": {
"@angular/animations": "^21.0.1",
"@angular/cdk": "^21.0.1",
"@angular/common": "^21.0.1",
"@angular/compiler": "^21.0.1",
"@angular/core": "^21.0.1",
"@angular/forms": "^21.0.1",
"@angular/material": "^21.0.1",
"@angular/platform-browser": "^21.0.1",
"@angular/platform-server": "^21.0.1",
"@angular/router": "^21.0.1",
"@angular/ssr": "^21.0.1",
"date-holidays": "^3.26.2",
"dayjs": "^1.11.19",
"express": "^5.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^21.0.1",
"@angular/cli": "^21.0.1",
"@angular/compiler-cli": "^21.0.1",
"@eslint/js": "^9.39.1",
"@types/express": "^5.0.1",
"@types/jasmine": "~5.1.0",
"@types/jest": "^30.0.0",
"@types/node": "^24.10.0",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"jasmine-core": "~5.12.1",
"jest": "^30.2.0",
"jest-preset-angular": "^15.0.3",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"prettier": "^3.6.2",
"typescript": "~5.9.2",
"typescript-eslint": "^8.46.4"
}
"name": "vac-optimizer",
"version": "1.5.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"serve:ssr:vac-optimizer": "node dist/vac-optimizer/server/server.mjs",
"lint": "eslint \"src/**/*.ts\"",
"lint:fix": "eslint \"src/**/*.ts\" --fix",
"format": "prettier --write \"src/**/*.{ts,html,scss,css,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,html,scss,css,json}\""
},
"prettier": {
"printWidth": 100,
"singleQuote": true,
"overrides": [
{
"files": "*.html",
"options": {
"parser": "angular"
}
}
]
},
"private": true,
"dependencies": {
"@angular/cdk": "^20.2.12",
"@angular/common": "^20.3.10",
"@angular/compiler": "^20.3.10",
"@angular/core": "^20.3.10",
"@angular/forms": "^20.3.10",
"@angular/material": "^20.2.12",
"@angular/platform-browser": "^20.3.10",
"@angular/platform-server": "^20.3.10",
"@angular/router": "^20.3.10",
"@angular/ssr": "^20.3.10",
"date-holidays": "^3.26.2",
"dayjs": "^1.11.19",
"express": "^5.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^20.3.10",
"@angular/cli": "^20.3.10",
"@angular/compiler-cli": "^20.3.10",
"@eslint/js": "^9.39.1",
"@types/express": "^5.0.1",
"@types/jasmine": "~5.1.0",
"@types/jest": "^30.0.0",
"@types/node": "^24.10.0",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"jasmine-core": "~5.12.1",
"jest": "^30.2.0",
"jest-preset-angular": "^15.0.3",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"prettier": "^3.6.2",
"typescript": "~5.9.2",
"typescript-eslint": "^8.46.4"
}
}
-2
View File
@@ -11,7 +11,6 @@ import {
withEventReplay,
withIncrementalHydration,
} from '@angular/platform-browser';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
export const appConfig: ApplicationConfig = {
providers: [
@@ -19,6 +18,5 @@ export const appConfig: ApplicationConfig = {
provideZonelessChangeDetection(),
provideRouter(routes),
provideClientHydration(withEventReplay(), withIncrementalHydration()),
provideAnimationsAsync(),
],
};
@@ -3,14 +3,15 @@ import { UserInputService } from '../../services/user-input-service';
import { MatCard, MatCardContent } from '@angular/material/card';
import { CalendarMonth } from '../calendar-month/calendar-month';
import { CalendarService, SelectedDates } from '../../services/calendar-service';
import { CommonModule } from '@angular/common';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { DateCacheService } from '../../services/date-cache.service';
import { LoggerService } from '../../services/logger.service';
@Component({
selector: 'app-calendar-year',
imports: [MatCard, CalendarMonth, MatCardContent, MatProgressSpinner],
imports: [MatCard, CalendarMonth, MatCardContent, CommonModule, MatProgressSpinner],
templateUrl: './calendar-year.html',
styleUrl: './calendar-year.scss',
})
@@ -19,6 +20,7 @@ export class CalendarYear {
private userInput = inject(UserInputService);
private calendarService = inject(CalendarService);
private calendarSettingsService = inject(CalendarSettingsService);
private logger = inject(LoggerService);
protected isLoading = signal(true);
protected loadingProgress = signal(0);
@@ -45,15 +47,15 @@ export class CalendarYear {
queueMicrotask(() => {
void (async () => {
if (this.selectedDates) {
// Create a deep copy to avoid mutating the original signal data
const vacationDaysCopy = vacationData.map((vd) => ({ ...vd }));
// Create a copy to avoid mutating the original signal data
const remainingDays = await this.selectedDates.optimizeVacations(
vacationDaysCopy,
{ ...vacationData },
this.calendarSettingsService,
this.calendarService,
(progress: number) => {
this.loadingProgress.set(progress);
},
this.logger,
);
// Update the remaining vacation days signal
this.userInput.remainingVacationDaysSignal.set(remainingDays);
+20 -31
View File
@@ -1,40 +1,29 @@
<div class="user-input">
<p>Optimisez vos jours de vacances en fonction des jours fériés et des week-ends !</p>
<div class="listOfDays">
@for (day of daysOff; track day.id) {
<div class="day-input-wrapper" animate.enter="day-enter" animate.leave="day-leave">
<app-day-input [day]="day" (dayChange)="updateDay($index, $event)" (deleteEntry)="removeFromList($index)"></app-day-input>
</div>
}
<mat-card class="add-day-card mat-elevation-z2" (click)="addDay()">
<button matFab aria-label="Add entry">
<mat-icon>add</mat-icon>
</button>
<h3>Ajouter un jour de vacances</h3>
</mat-card>
</div>
<div class="action-buttons">
<button matFab extended (click)="triggerComputation()">
<mat-icon>calculate</mat-icon>
Calculer
</button>
<app-calendar-settings></app-calendar-settings>
</div>
<form [formGroup]="userInputForm">
<mat-form-field appearance="fill">
<mat-label>Combien de CP par an ?</mat-label>
<input matInput type="number" max="365" min="0" formControlName="CP" />
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Combien de jours de RTT par an ?</mat-label>
<input matInput type="number" max="365" min="0" formControlName="RTT" />
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Autres jours</mat-label>
<input matInput type="number" max="365" min="0" formControlName="Others" />
</mat-form-field>
</form>
@if (hasRemainingDays()) {
<mat-card class="mat-elevation-z2 warning-card">
<mat-card-content class="warning-content">
<mat-icon color="warn">warning</mat-icon>
<div class="warning">
<span>
{{ remainingDays() }} jour{{ remainingDays() > 1 ? 's' : '' }} de vacances
non placé{{ remainingDays() > 1 ? 's' : '' }}:
</span>
@for (day of remainingDaysDetails(); track $index) {
<span class="remaining-day-detail">- {{ day }}</span>
}
<span> Veuillez les placer manuellement. </span>
</div>
<mat-icon color="warn" aria-hidden="true">warning</mat-icon>
<span>
{{ remainingDays() }} jour{{ remainingDays() > 1 ? 's' : '' }} de vacances non
placé{{ remainingDays() > 1 ? 's' : '' }}. Veuillez les placer manuellement.
</span>
</mat-card-content>
</mat-card>
}
<app-calendar-settings></app-calendar-settings>
</div>
@@ -25,79 +25,7 @@
}
}
.listOfDays {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.day-input-wrapper {
animation: slide-fade-in 200ms ease-out;
@starting-style {
opacity: 0;
transform: translateX(-20px);
}
}
.day-enter {
animation: slide-fade-in 200ms ease-out;
}
.day-leave {
opacity: 0;
transform: translateX(20px);
transition:
opacity 200ms ease-in,
transform 200ms ease-in;
}
@keyframes slide-fade-in {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
form {
display: flex;
flex-direction: column;
}
.add-day-card {
display: flex;
flex-direction: row;
align-items: center;
padding: 16px;
gap: 1rem;
margin-bottom: 1rem;
cursor: pointer;
}
.add-day-card h3 {
flex-grow: 1;
margin: 0;
font-weight: normal;
}
.action-buttons {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
gap: 1rem;
}
.warning {
display: flex;
flex-direction: column;
}
:host {
max-width: 100%;
}
@@ -1,7 +1,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { UserInput } from './user-input';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
describe('UserInput', () => {
let component: UserInput;
@@ -10,7 +9,7 @@ describe('UserInput', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UserInput],
providers: [provideZonelessChangeDetection(), provideAnimationsAsync()],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
fixture = TestBed.createComponent(UserInput);
+48 -47
View File
@@ -1,78 +1,79 @@
import { Component, computed, inject, ChangeDetectionStrategy } from '@angular/core';
import { Component, OnInit, OnDestroy, effect, computed } from '@angular/core';
import { MatFormField, MatLabel } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { UserInputService } from '../../services/user-input-service';
import { VacationsNumber } from '../../services/calendar-service';
import { debounceTime, takeUntil, Subject } from 'rxjs';
import { CalendarSettings } from '../calendar-settings/calendar-settings';
import { MatCard, MatCardContent } from '@angular/material/card';
import { MatIcon } from '@angular/material/icon';
import { DayInput } from '../userInput/day-input/day-input';
import { MatButtonModule } from '@angular/material/button';
import { tooltipTypeMapping, DayType, VacDay } from '../../services/calendar-service';
@Component({
selector: 'app-user-input',
imports: [
MatFormField,
MatLabel,
MatInputModule,
ReactiveFormsModule,
CalendarSettings,
MatCard,
MatCardContent,
MatIcon,
MatButtonModule,
DayInput,
],
templateUrl: './user-input.html',
styleUrl: './user-input.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserInput {
private userInputService: UserInputService = inject(UserInputService);
export class UserInput implements OnInit, OnDestroy {
constructor(private userInputService: UserInputService) {
// Watch for signal changes and update form
effect(() => {
const vacationData = this.userInputService.vacationNumberSignal();
this.userInputForm.patchValue(
{
CP: vacationData.cp,
RTT: vacationData.rtt,
Others: vacationData.other,
},
{ emitEvent: false },
);
});
}
private destroy$ = new Subject<void>();
userInputForm: FormGroup = new FormGroup({
CP: new FormControl<number | null>(null),
RTT: new FormControl<number | null>(null),
Others: new FormControl<number | null>(null),
});
protected remainingDays = computed(() => {
const remaining = this.userInputService.remainingVacationDaysSignal();
return remaining.reduce((acc, day) => acc + day.numberOfDays, 0);
});
protected remainingDaysDetails = computed(() => {
const remaining = this.userInputService.remainingVacationDaysSignal();
return remaining
.filter((day) => day.numberOfDays > 0)
.map((day) => {
const typeName = tooltipTypeMapping[day.type as unknown as DayType];
const expiryDate = day.expiryDate.toLocaleDateString('fr-FR', {
day: 'numeric',
month: 'short',
year: 'numeric',
});
return `${day.numberOfDays} ${typeName} (exp. ${expiryDate})`;
});
return remaining.cp + remaining.rtt + remaining.other;
});
protected hasRemainingDays = computed(() => this.remainingDays() > 0);
protected get daysOff() {
return this.userInputService.vacationNumberSignal();
ngOnInit() {
this.userInputForm.valueChanges
.pipe(debounceTime(1500), takeUntil(this.destroy$))
.subscribe(() => this.submitForm());
}
public addDay() {
this.userInputService.vacationNumberSignal.update((days) => [
...days,
this.userInputService.createVacationDay(),
]);
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
public removeFromList(index: number) {
this.userInputService.vacationNumberSignal.update((days) =>
days.filter((_, i) => i !== index),
);
}
public updateDay(index: number, updatedDay: VacDay) {
this.userInputService.vacationNumberSignal.update((days) =>
days.map((day, i) => (i === index ? updatedDay : day)),
);
}
public triggerComputation() {
// Trigger signal update by setting a new array reference
this.userInputService.vacationNumberSignal.update((days) => [...days]);
private submitForm() {
if (this.userInputForm.valid) {
const vacationData: VacationsNumber = {
cp: this.userInputForm.get('CP')?.value || 0,
rtt: this.userInputForm.get('RTT')?.value || 0,
other: this.userInputForm.get('Others')?.value || 0,
};
this.userInputService.vacationNumberSignal.set(vacationData);
}
}
}
@@ -1,36 +0,0 @@
<!-- <mat-list-item role="listitem"> -->
<mat-card class="card">
<mat-form-field class="numberInput">
<input
matInput
type="number"
min="0"
[value]="day().numberOfDays"
(input)="onInput($event)"
/>
</mat-form-field>
<mat-form-field class="dayTypeInput">
<mat-select (valueChange)="onTypeChange($event)" [value]="day().type">
<mat-option></mat-option>
@for (dayType of selectableDayTypes; track $index) {
<mat-option [value]="dayType">{{ tooltipTypeMapping[dayType] }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field class="dateInput">
<mat-label>Choose a date</mat-label>
<input
matInput
type="datetime"
[matDatepicker]="picker"
[value]="day().expiryDate"
(dateChange)="addEvent($event)"
/>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<button matFab aria-label="Delete entry" (click)="deleteEntry.emit()">
<mat-icon>close</mat-icon>
</button>
</mat-card>
<!-- </mat-list-item> -->
@@ -1,21 +0,0 @@
.card {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 16px;
gap: 16px;
flex-wrap: wrap;
}
.dateInput {
flex-grow: 1;
}
.numberInput {
width: 80px;
}
::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
@@ -1,33 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { DayInput } from './day-input';
import { SelectableDayType, VacDay } from '../../../services/calendar-service';
describe('DayInput', () => {
let component: DayInput;
let fixture: ComponentFixture<DayInput>;
const mockVacDay: VacDay = {
id: 'test-id',
type: SelectableDayType.CP,
numberOfDays: 5,
expiryDate: new Date('2025-12-31'),
};
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [DayInput],
providers: [provideAnimationsAsync()],
}).compileComponents();
fixture = TestBed.createComponent(DayInput);
component = fixture.componentInstance;
fixture.componentRef.setInput('day', mockVacDay);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -1,103 +0,0 @@
import { Component, input, output, ChangeDetectionStrategy } from '@angular/core';
import { SelectableDayType, tooltipTypeMapping, VacDay } from '../../../services/calendar-service';
import { MatCard } from '@angular/material/card';
import { MatOption, MatSelect } from '@angular/material/select';
import { MatInput, MatInputModule, MatLabel } from '@angular/material/input';
import {
MatDatepicker,
MatDatepickerInput,
MatDatepickerInputEvent,
MatDatepickerToggle,
} from '@angular/material/datepicker';
import {
DateAdapter,
MAT_DATE_FORMATS,
MAT_DATE_LOCALE,
NativeDateAdapter,
} from '@angular/material/core';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
class CustomDateAdapter extends NativeDateAdapter {
override format(date: Date, displayFormat: unknown): string {
if (displayFormat === 'input') {
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
return `${day}/${month}/${year}`;
}
return super.format(date, displayFormat as object);
}
override parse(value: string): Date | null {
if (!value) return null;
const parts = value.split('/');
if (parts.length === 3) {
const day = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const year = parseInt(parts[2], 10);
if (!isNaN(day) && !isNaN(month) && !isNaN(year)) {
return new Date(year, month, day);
}
}
return null;
}
}
const MY_DATE_FORMATS = {
parse: {
dateInput: 'input',
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
},
};
@Component({
selector: 'app-day-input',
imports: [
MatIconModule,
MatCard,
MatSelect,
MatOption,
MatInput,
MatDatepicker,
MatLabel,
MatDatepickerToggle,
MatDatepickerInput,
MatInputModule,
MatButtonModule,
],
templateUrl: './day-input.html',
styleUrl: './day-input.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{ provide: DateAdapter, useClass: CustomDateAdapter },
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' },
{ provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS },
],
})
export class DayInput {
public day = input.required<VacDay>();
public dayChange = output<VacDay>();
public deleteEntry = output<void>();
protected readonly selectableDayTypes = Object.values(SelectableDayType);
protected readonly tooltipTypeMapping = tooltipTypeMapping;
onInput(event: Event) {
const value = Number((event.target as HTMLInputElement).value);
this.dayChange.emit({ ...this.day(), numberOfDays: value });
}
onTypeChange(type: SelectableDayType) {
this.dayChange.emit({ ...this.day(), type });
}
addEvent(event: MatDatepickerInputEvent<Date>) {
this.dayChange.emit({ ...this.day(), expiryDate: event.value! });
}
}
+55 -114
View File
@@ -6,6 +6,7 @@ import weekOfYear from 'dayjs/plugin/weekOfYear';
import isoWeek from 'dayjs/plugin/isoWeek';
import { CalendarSettingsService } from './calendar-settings-service';
import { DateCacheService } from './date-cache.service';
import { LoggerService } from './logger.service';
dayjs.extend(weekOfYear);
dayjs.extend(isoWeek);
@@ -21,6 +22,7 @@ const allTypesOptions: HolidaysTypes.Options = {
})
export class CalendarService {
private dateCache = inject(DateCacheService);
private logger = inject(LoggerService);
// Cache for holiday timestamps
private holidayTimestampsCache: Set<number> | null = null;
@@ -184,11 +186,10 @@ export class CalendarService {
}
}
export type VacDay = {
id: string;
type: SelectableDayType;
numberOfDays: number;
expiryDate: Date;
export type VacationsNumber = {
rtt: number;
cp: number;
other: number;
};
export type Week = (Date | null)[];
@@ -204,12 +205,6 @@ export enum DayType {
TODAY = 'today',
}
export enum SelectableDayType {
CP = DayType.CP,
RTT = DayType.RTT,
OTHER = DayType.OTHER,
}
export const tooltipTypeMapping: { [key in DayType]: string } = {
[DayType.WEEKEND]: 'Weekend',
[DayType.CLOSED_DAY]: 'Jour Férié',
@@ -544,15 +539,16 @@ export class SelectedDates implements SelectedDateInterface {
}
async optimizeVacations(
vacationDays: VacDay[],
vacationsNumber: VacationsNumber,
calendarSettingsService: CalendarSettingsService,
calendarService: CalendarService,
progressCallback?: (progress: number) => void,
): Promise<VacDay[]> {
if (calendarSettingsService.get('samediMalin')()) this.samediMalin(vacationDays);
logger?: LoggerService,
): Promise<VacationsNumber> {
if (calendarSettingsService.get('samediMalin')()) this.samediMalin(vacationsNumber);
// Calculate total days to process
const totalDays = vacationDays.reduce((sum, vd) => sum + vd.numberOfDays, 0);
const initialVacations = { ...vacationsNumber };
const totalDays = initialVacations.cp + initialVacations.rtt + initialVacations.other;
let processedDays = 0;
// Helper function to update progress, throttled to every 5%
@@ -572,30 +568,30 @@ export class SelectedDates implements SelectedDateInterface {
await updateProgress();
// Track VacDays that can't find valid placements
const exhaustedVacDayIds = new Set<string>();
// Process vacation days ordered by expiration date (earliest first)
while (vacationDays.some((vd) => vd.numberOfDays > 0 && !exhaustedVacDayIds.has(vd.id))) {
// Sort by expiration date to use days that expire first, excluding exhausted ones
const sortedVacDays = [...vacationDays]
.filter((vd) => vd.numberOfDays > 0 && !exhaustedVacDayIds.has(vd.id))
.sort((a, b) => a.expiryDate.getTime() - b.expiryDate.getTime());
if (sortedVacDays.length === 0) {
while (vacationsNumber.cp > 0) {
const result = this.lookForVacation(DayType.CP, calendarService);
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
const vacDayToUse = sortedVacDays[0];
const result = this.lookForVacation(vacDayToUse, calendarService);
vacationsNumber.cp -= 1;
processedDays++;
await updateProgress();
}
while (vacationsNumber.rtt > 0) {
const result = this.lookForVacation(DayType.RTT, calendarService);
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
// Mark this VacDay as exhausted and try other vacation days
exhaustedVacDayIds.add(vacDayToUse.id);
continue;
break;
}
vacDayToUse.numberOfDays -= 1;
vacationsNumber.rtt -= 1;
processedDays++;
await updateProgress();
}
while (vacationsNumber.other > 0) {
const result = this.lookForVacation(DayType.OTHER, calendarService);
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
vacationsNumber.other -= 1;
processedDays++;
await updateProgress();
}
@@ -606,18 +602,18 @@ export class SelectedDates implements SelectedDateInterface {
}
// Inform user if not all days were placed
const remainingDays = vacationDays.reduce((sum, vd) => sum + vd.numberOfDays, 0);
if (remainingDays > 0) {
console.warn(
const remainingDays = vacationsNumber.cp + vacationsNumber.rtt + vacationsNumber.other;
if (remainingDays > 0 && logger) {
logger.warn(
`Optimization stopped: ${remainingDays} of ${totalDays} vacation days remain unplaced. ` +
`Too many days have equivalent placement quality - please place remaining days manually.`,
);
}
return vacationDays;
return vacationsNumber;
}
samediMalin(vacationDays: VacDay[]): void {
samediMalin(vacationsNumber: VacationsNumber): void {
const now = new Date();
now.setHours(0, 0, 0, 0);
const nowTime = now.getTime();
@@ -626,63 +622,14 @@ export class SelectedDates implements SelectedDateInterface {
(date) => date.type === DayType.CLOSED_DAY && date.range.start?.getDay() === 6,
);
// Helper function to get available CP days that don't expire before a given date (ordered by expiry date)
const getAvailableCpDaysForDate = (useByDate: Date): VacDay[] => {
const useByTime = useByDate.getTime();
return vacationDays
.filter(
(vd) =>
vd.type === SelectableDayType.CP &&
vd.numberOfDays > 0 &&
vd.expiryDate.getTime() >= useByTime,
)
.sort((a, b) => a.expiryDate.getTime() - b.expiryDate.getTime());
};
// Helper function to get total available CP days that don't expire before a given date
const getTotalCpDaysForDate = (useByDate: Date): number => {
const useByTime = useByDate.getTime();
return vacationDays
.filter(
(vd) =>
vd.type === SelectableDayType.CP && vd.expiryDate.getTime() >= useByTime,
)
.reduce((sum, vd) => sum + vd.numberOfDays, 0);
};
// Helper function to consume 2 CP days from the available pool for a specific date
const consume2CpDaysForDate = (useByDate: Date): boolean => {
let daysToConsume = 2;
const cpDays = getAvailableCpDaysForDate(useByDate);
for (const cpDay of cpDays) {
if (daysToConsume === 0) break;
const toConsume = Math.min(cpDay.numberOfDays, daysToConsume);
cpDay.numberOfDays -= toConsume;
daysToConsume -= toConsume;
}
return daysToConsume === 0;
};
// Helper function to add 1 OTHER day as reward
const addOtherDayReward = (): void => {
// Find an existing OTHER VacDay or create a new one
const otherDay = vacationDays.find((vd) => vd.type === SelectableDayType.OTHER);
if (otherDay) {
otherDay.numberOfDays += 1;
} else {
// Create a new OTHER VacDay with a far future expiry date
vacationDays.push({
id: crypto.randomUUID(),
type: SelectableDayType.OTHER,
numberOfDays: 1,
expiryDate: new Date(now.getFullYear() + 10, 11, 31),
});
}
};
for (const holiday of samedi_ferie) {
if (!holiday.range.start) continue;
// Skip if no CP days available
if (vacationsNumber.cp < 2) {
continue;
}
// Get the Saturday date (holiday) and the following Sunday
const saturdayDate = new Date(holiday.range.start);
const sundayDate = new Date(saturdayDate);
@@ -707,24 +654,21 @@ export class SelectedDates implements SelectedDateInterface {
const oneDayAfter = new Date(sundayDate);
oneDayAfter.setDate(sundayDate.getDate() + 1);
// Check if we can apply each strategy (not in the past, not already selected, and have non-expired CP days)
// Check if we can apply each strategy (and not in the past)
const canApplyTwoBeforeStrategy =
twoDaysBefore1.getTime() >= nowTime &&
!this.isSelected(twoDaysBefore1) &&
!this.isSelected(twoDaysBefore2) &&
getTotalCpDaysForDate(twoDaysBefore2) >= 2; // Check expiry against the latest date used
!this.isSelected(twoDaysBefore2);
const canApplyTwoAfterStrategy =
twoDaysAfter1.getTime() >= nowTime &&
!this.isSelected(twoDaysAfter1) &&
!this.isSelected(twoDaysAfter2) &&
getTotalCpDaysForDate(twoDaysAfter2) >= 2; // Check expiry against the latest date used
!this.isSelected(twoDaysAfter2);
const canApplyMixedStrategy =
oneDayBefore.getTime() >= nowTime &&
!this.isSelected(oneDayBefore) &&
!this.isSelected(oneDayAfter) &&
getTotalCpDaysForDate(oneDayAfter) >= 2; // Check expiry against the latest date used
!this.isSelected(oneDayAfter);
// Test all applicable strategies and choose the one with the best heuristic score
const strategies: { apply: () => void; heuristic: number }[] = [];
@@ -747,8 +691,8 @@ export class SelectedDates implements SelectedDateInterface {
new DateRange<Date>(twoDaysBefore1, twoDaysBefore2),
),
);
consume2CpDaysForDate(twoDaysBefore2);
addOtherDayReward();
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: heuristic,
});
@@ -771,8 +715,8 @@ export class SelectedDates implements SelectedDateInterface {
new DateRange<Date>(twoDaysAfter1, twoDaysAfter2),
),
);
consume2CpDaysForDate(twoDaysAfter2);
addOtherDayReward();
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: heuristic,
});
@@ -804,8 +748,8 @@ export class SelectedDates implements SelectedDateInterface {
new DateRange<Date>(oneDayAfter, oneDayAfter),
),
);
consume2CpDaysForDate(oneDayAfter);
addOtherDayReward();
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: heuristic,
});
@@ -825,24 +769,22 @@ export class SelectedDates implements SelectedDateInterface {
}
lookForVacation(
vacDay: VacDay,
vacType: DayType,
calendarService: CalendarService,
): { apply: () => void; heuristic: number } {
const daysOfYear = calendarService.monthsInAYearFromNow();
const now = new Date();
now.setHours(0, 0, 0, 0);
const nowTime = now.getTime();
const expiryTime = vacDay.expiryDate.getTime();
// Preprocess: filter out past days, already selected days, and days after expiry date
// Preprocess: filter out past days and already selected days in one pass
const candidateDays: Date[] = [];
for (const month of daysOfYear) {
for (const week of month) {
for (const day of week) {
if (day) {
day.setHours(0, 0, 0, 0);
const dayTime = day.getTime();
if (dayTime >= nowTime && dayTime <= expiryTime && !this.isSelected(day)) {
if (day.getTime() >= nowTime && !this.isSelected(day)) {
candidateDays.push(day);
}
}
@@ -855,7 +797,6 @@ export class SelectedDates implements SelectedDateInterface {
return { apply: () => {}, heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC };
}
const vacType = vacDay.type as unknown as DayType;
const tempDatesBackup = [...this._datesSelected];
let bestStrategy: { apply: () => void; heuristic: number; value: Date } | null = null;
let bestHeuristic = -Infinity;
+52
View File
@@ -0,0 +1,52 @@
import { TestBed } from '@angular/core/testing';
import { LoggerService } from './logger.service';
describe('LoggerService', () => {
let service: LoggerService;
let consoleLogSpy: jasmine.Spy;
let consoleWarnSpy: jasmine.Spy;
let consoleErrorSpy: jasmine.Spy;
let consoleDebugSpy: jasmine.Spy;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(LoggerService);
// Spy on console methods
consoleLogSpy = spyOn(console, 'log');
consoleWarnSpy = spyOn(console, 'warn');
consoleErrorSpy = spyOn(console, 'error');
consoleDebugSpy = spyOn(console, 'debug');
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should log messages', () => {
service.log('test message');
expect(consoleLogSpy).toHaveBeenCalledWith('test message');
});
it('should log warnings', () => {
service.warn('test warning');
expect(consoleWarnSpy).toHaveBeenCalledWith('test warning');
});
it('should log errors', () => {
service.error('test error');
expect(consoleErrorSpy).toHaveBeenCalledWith('test error');
});
it('should log debug messages', () => {
service.debug('test debug');
expect(consoleDebugSpy).toHaveBeenCalledWith('test debug');
});
it('should pass additional arguments to console methods', () => {
const arg1 = { key: 'value' };
const arg2 = [1, 2, 3];
service.log('test', arg1, arg2);
expect(consoleLogSpy).toHaveBeenCalledWith('test', arg1, arg2);
});
});
+47
View File
@@ -0,0 +1,47 @@
import { Injectable } from '@angular/core';
/**
* Logger service that wraps console methods.
* Can be configured to disable logging in production environments.
*/
@Injectable({
providedIn: 'root',
})
export class LoggerService {
private isProduction = false; // Can be configured based on environment
/**
* Log an informational message
*/
log(message: string, ...args: unknown[]): void {
if (!this.isProduction) {
console.log(message, ...args);
}
}
/**
* Log a warning message
*/
warn(message: string, ...args: unknown[]): void {
if (!this.isProduction) {
console.warn(message, ...args);
}
}
/**
* Log an error message
*/
error(message: string, ...args: unknown[]): void {
// Always log errors, even in production
console.error(message, ...args);
}
/**
* Log a debug message
*/
debug(message: string, ...args: unknown[]): void {
if (!this.isProduction) {
console.debug(message, ...args);
}
}
}
+11 -32
View File
@@ -1,5 +1,5 @@
import { Injectable, signal } from '@angular/core';
import { SelectableDayType, VacDay } from './calendar-service';
import { VacationsNumber } from './calendar-service';
@Injectable({
providedIn: 'root',
@@ -9,39 +9,18 @@ export class UserInputService {
return Math.floor(Math.random() * 9) + 1;
}
private getInitialValues(): VacDay[] {
return [
{
id: crypto.randomUUID(),
type: SelectableDayType.CP,
numberOfDays: this.getRandomNumber(),
// today + 365 days
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
{
id: crypto.randomUUID(),
type: SelectableDayType.RTT,
numberOfDays: this.getRandomNumber(),
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
{
id: crypto.randomUUID(),
type: SelectableDayType.OTHER,
numberOfDays: this.getRandomNumber(),
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
];
}
public createVacationDay(): VacDay {
private getInitialValues(): VacationsNumber {
return {
id: crypto.randomUUID(),
type: SelectableDayType.CP,
numberOfDays: 1,
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
cp: this.getRandomNumber(),
rtt: this.getRandomNumber(),
other: this.getRandomNumber(),
};
}
readonly vacationNumberSignal = signal<VacDay[]>(this.getInitialValues());
readonly remainingVacationDaysSignal = signal<VacDay[]>([]);
readonly vacationNumberSignal = signal<VacationsNumber>(this.getInitialValues());
readonly remainingVacationDaysSignal = signal<VacationsNumber>({
cp: 0,
rtt: 0,
other: 0,
});
}