add calendar settings

This commit is contained in:
nessar committed 2025-11-01 03:15:30 +01:00
1 parent d8759eee29
commit d01c93c763
32 files changed
+1290 -1585

No files matched your search

+747 -1445
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "vac-optimizer",
"version": "0.0.0",
"version": "1.5.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
@@ -34,6 +34,7 @@
"@angular/router": "^20.3.0",
"@angular/ssr": "^20.3.7",
"date-holidays": "^3.26.2",
"dayjs": "^1.11.19",
"express": "^5.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
+13 -4
View File
@@ -1,13 +1,22 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import {
provideClientHydration,
withEventReplay,
withIncrementalHydration,
} from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
provideRouter(routes), provideClientHydration(withEventReplay())
]
provideRouter(routes),
provideClientHydration(withEventReplay(), withIncrementalHydration()),
],
};
+2 -1
View File
@@ -3,7 +3,8 @@
<h1>{{ title() }}</h1>
<div class="content">
<app-user-input></app-user-input>
<mat-divider [vertical]="true" style="height: 80%"></mat-divider>
<mat-divider [vertical]="true" />
<mat-divider />
<app-calendar-year></app-calendar-year>
</div>
</main>
+23
View File
@@ -26,3 +26,26 @@
right: 20px;
z-index: 1000;
}
@media (max-width: 768px) {
.mat-divider-vertical {
display: none;
}
.mat-divider-horizontal {
display: block !important;
}
}
.mat-divider-vertical {
height: 80vh;
width: 1px;
margin: 0 16px;
}
.mat-divider-horizontal {
width: 80%;
height: 1px;
margin: 16px 0;
display: none;
}
@@ -2,6 +2,9 @@
<h3>{{ getMonthName() }} {{ year }}</h3>
<div>
<div class="row header">
@if (calendarSettingsService.showWeekNumbers()) {
<p class="day empty week-number"></p>
}
<p class="day">L</p>
<p class="day">M</p>
<p class="day">M</p>
@@ -12,16 +15,36 @@
</div>
<div class="cols">
@for (week of weeksInAMonth; track $index) {
<div class="row week">
@for (day of week; track $index) {
@if (day === null) {
<p class="day empty"></p>
} @else {
<p [class.past]="day < getNow()" [class.start]="selectedDates.isStart(day)" [class.end]="selectedDates.isEnd(day)" [class.selected]="selectedDates.isSelected(day)"
[class]="selectedDates.getClasses(day)" class="day number" [matTooltip]="selectedDates.getTooltip(day)" [matTooltipShowDelay]="500">{{ day.getDate() }}</p>
}
}
</div>
<div class="row week">
@if (calendarSettingsService.showWeekNumbers()) {
<p
class="day week-number"
[class.start]="$index === 0"
[class.end]="$index === weeksInAMonth.length - 1"
>
{{ getWeekNumber(week) }}
</p>
}
@for (day of week; track $index) {
@if (day === null) {
<p class="day empty"></p>
} @else {
<p
[class.past]="day < getNow()"
[class.start]="selectedDates.isStart(day)"
[class.end]="selectedDates.isEnd(day)"
[class.selected]="selectedDates.isSelected(day)"
[class]="selectedDates.getClasses(day)"
class="day number"
[matTooltip]="selectedDates.getTooltip(day)"
[matTooltipShowDelay]="500"
[matTooltipTouchGestures]="'on'"
>
{{ day.getDate() }}
</p>
}
}
</div>
}
</div>
</div>
@@ -103,3 +103,27 @@
.other {
background-color: var(--other-bg);
}
.row .week-number {
height: 30px;
font-weight: bold;
color: var(--week-number-color);
margin-right: 0.5rem;
background-color: var(--week-number-bg);
border-radius: 0;
margin-top: 0;
margin-bottom: 0;
}
.row .week-number:hover {
background-color: var(--week-number-bg-hover);
cursor: default;
}
.row .week-number.start {
border-radius: 30% 30% 0 0;
}
.row .week-number.end {
border-radius: 0 0 30% 30%;
}
@@ -1,6 +1,7 @@
import { Component, Input, OnInit } from '@angular/core';
import { CalendarService, Month, monthNames, SelectedDates } from '../../services/calendar-service';
import { MatTooltip } from '@angular/material/tooltip';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
@Component({
selector: 'app-calendar-month',
@@ -9,6 +10,7 @@ import { MatTooltip } from '@angular/material/tooltip';
styleUrl: './calendar-month.scss',
})
export class CalendarMonth implements OnInit {
constructor(protected calendarSettingsService: CalendarSettingsService) {}
@Input({ required: true })
monthIndex!: number;
@@ -26,7 +28,6 @@ export class CalendarMonth implements OnInit {
weeksInAMonth: Month = [];
@Input({ required: true })
selectedDates!: SelectedDates;
@@ -34,6 +35,15 @@ export class CalendarMonth implements OnInit {
return monthNames[this.monthIndex];
}
getWeekNumber(week: (Date | null)[]): number | null {
for (const day of week) {
if (day) {
return CalendarService.getWeekNumber(day);
}
}
return null;
}
ngOnInit(): void {
this.weeksInAMonth = CalendarService.weeksInMonth(this.monthIndex, this.year);
}
@@ -0,0 +1,4 @@
<button matFab extended (click)="openDialog()">
<mat-icon>settings</mat-icon>
Calendar Settings
</button>
Whitespace-only changes.
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CalendarSettings } from './calendar-settings';
describe('CalendarSettings', () => {
let component: CalendarSettings;
let fixture: ComponentFixture<CalendarSettings>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CalendarSettings]
})
.compileComponents();
fixture = TestBed.createComponent(CalendarSettings);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,20 @@
import { Component } from '@angular/core';
import { MatButton, MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatIcon, MatIconModule } from '@angular/material/icon';
import { CalendarSettingsDialog } from '../dialog/calendar-settings-dialog/calendar-settings-dialog';
import { MatDividerModule } from '@angular/material/divider';
@Component({
selector: 'app-calendar-settings',
imports: [MatButtonModule, MatDividerModule, MatIconModule],
templateUrl: './calendar-settings.html',
styleUrl: './calendar-settings.scss',
})
export class CalendarSettings {
constructor(private dialog: MatDialog) {}
openDialog() {
this.dialog.open(CalendarSettingsDialog);
}
}
@@ -1,10 +1,11 @@
import { Component, effect, signal } from '@angular/core';
import { UserInputService } from '../../services/user-input-service';
import { MatCard, MatCardContent } from '@angular/material/card';
import { CalendarMonth } from "../calendar-month/calendar-month";
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';
@Component({
selector: 'app-calendar-year',
@@ -15,15 +16,24 @@ import { MatProgressSpinner } from '@angular/material/progress-spinner';
export class CalendarYear {
protected isLoading = signal(true);
constructor(private userInput: UserInputService, private calendarService: CalendarService) {
constructor(
private userInput: UserInputService,
private calendarService: CalendarService,
private calendarSettingsService: CalendarSettingsService,
) {
effect(() => {
this.selectedDates = this.calendarService.getSelectedDatesForYear();
const vacationData = this.userInput.vacationNumberSignal();
this.calendarSettingsService.samediMalin();
this.isLoading.set(true);
// Simulate server-side calculation with a small delay
setTimeout(() => {
if (this.selectedDates) {
this.selectedDates.optimizeVacations(vacationData);
// Create a copy to avoid mutating the original signal data
this.selectedDates.optimizeVacations(
{ ...vacationData },
this.calendarSettingsService,
);
}
this.isLoading.set(false);
}, 1);
@@ -38,5 +48,8 @@ export class CalendarYear {
}
// months starting from actual date
protected months: number[] = Array.from({ length: 12 }, (_, i) => (new Date().getMonth() + i) % 12);
protected months: number[] = Array.from(
{ length: 12 },
(_, i) => (new Date().getMonth() + i) % 12,
);
}
@@ -0,0 +1,33 @@
@defer (hydrate on viewport) {
<div class="container">
<div>
<h1>Calendar Settings</h1>
<p>Configure your calendar settings here.</p>
</div>
<div style="display: flex; flex-direction: column; gap: 1rem">
<div style="align-self: flex-start">
<mat-slide-toggle
id="showWeekNumbers"
name="showWeekNumbers"
[checked]="calendarSettingsService.showWeekNumbers()"
(change)="calendarSettingsService.showWeekNumbers.set($event.checked)"
>
Afficher les numéros de semaine
</mat-slide-toggle>
</div>
<div style="align-self: flex-start">
<mat-slide-toggle
id="samediMalin"
name="samediMalin"
[checked]="calendarSettingsService.samediMalin()"
(change)="calendarSettingsService.samediMalin.set($event.checked)"
>
Activer le Samedi Malin
</mat-slide-toggle>
</div>
</div>
<button mat-button (click)="closeDialog()">Fermer</button>
</div>
} @placeholder {
<p>loading ...</p>
}
@@ -0,0 +1,9 @@
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
flex-direction: column;
overflow: hidden;
margin: 16px;
}
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CalendarSettingsDialog } from './calendar-settings-dialog';
describe('CalendarSettingsDialog', () => {
let component: CalendarSettingsDialog;
let fixture: ComponentFixture<CalendarSettingsDialog>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CalendarSettingsDialog]
})
.compileComponents();
fixture = TestBed.createComponent(CalendarSettingsDialog);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,23 @@
import { Component } from '@angular/core';
import { MatButton } from '@angular/material/button';
import { MatCheckbox } from '@angular/material/checkbox';
import { MatDialogRef } from '@angular/material/dialog';
import { CalendarSettingsService } from '../../../services/calendar-settings-service';
import { MatSlideToggle } from '@angular/material/slide-toggle';
@Component({
selector: 'app-calendar-settings-dialog',
imports: [MatButton, MatSlideToggle],
templateUrl: './calendar-settings-dialog.html',
styleUrl: './calendar-settings-dialog.scss',
})
export class CalendarSettingsDialog {
constructor(
public dialogRef: MatDialogRef<CalendarSettingsDialog>,
protected calendarSettingsService: CalendarSettingsService,
) {}
closeDialog() {
this.dialogRef.close();
}
}
@@ -14,4 +14,5 @@
<input matInput type="number" max="365" min="0" formControlName="Others" />
</mat-form-field>
</form>
<app-calendar-settings></app-calendar-settings>
</div>
@@ -18,5 +18,4 @@
form {
display: flex;
flex-direction: column;
gap: 1rem;
}
+19 -11
View File
@@ -5,10 +5,18 @@ import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angula
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';
@Component({
selector: 'app-user-input',
imports: [MatFormField, MatLabel, MatInputModule, ReactiveFormsModule],
imports: [
MatFormField,
MatLabel,
MatInputModule,
ReactiveFormsModule,
CalendarSettings,
CalendarSettings,
],
templateUrl: './user-input.html',
styleUrl: './user-input.scss',
})
@@ -17,11 +25,14 @@ export class UserInput implements OnInit, OnDestroy {
// 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 });
this.userInputForm.patchValue(
{
CP: vacationData.cp,
RTT: vacationData.rtt,
Others: vacationData.other,
},
{ emitEvent: false },
);
});
}
@@ -35,10 +46,7 @@ export class UserInput implements OnInit, OnDestroy {
ngOnInit() {
this.userInputForm.valueChanges
.pipe(
debounceTime(1500),
takeUntil(this.destroy$)
)
.pipe(debounceTime(1500), takeUntil(this.destroy$))
.subscribe(() => this.submitForm());
}
@@ -54,7 +62,7 @@ export class UserInput implements OnInit, OnDestroy {
rtt: this.userInputForm.get('RTT')?.value || 0,
other: this.userInputForm.get('Others')?.value || 0,
};
this.userInputService.setVacationNumber(vacationData);
this.userInputService.vacationNumberSignal.set(vacationData);
}
}
}
@@ -0,0 +1 @@
<p>user-settings works!</p>
Whitespace-only changes.
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UserSettings } from './user-settings';
describe('UserSettings', () => {
let component: UserSettings;
let fixture: ComponentFixture<UserSettings>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UserSettings]
})
.compileComponents();
fixture = TestBed.createComponent(UserSettings);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,9 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-user-settings',
imports: [],
templateUrl: './user-settings.html',
styleUrl: './user-settings.scss',
})
export class UserSettings {}
+8 -8
View File
@@ -3,14 +3,14 @@ import { TestBed } from '@angular/core/testing';
import { Calendar } from './calendar';
describe('Calendar', () => {
let service: Calendar;
let service: Calendar;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(Calendar);
});
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(Calendar);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+166 -85
View File
@@ -1,6 +1,13 @@
import { Injectable } from '@angular/core';
import { DateRange } from '@angular/material/datepicker';
import Holidays, { HolidaysTypes } from 'date-holidays';
import dayjs from 'dayjs';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import isoWeek from 'dayjs/plugin/isoWeek';
import { CalendarSettingsService } from './calendar-settings-service';
dayjs.extend(weekOfYear);
dayjs.extend(isoWeek);
const lang = 'en';
@@ -9,10 +16,9 @@ const allTypesOptions: HolidaysTypes.Options = {
};
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class CalendarService {
// Get selected dates from current date to the next year
getSelectedDatesFromNow(): SelectedDates {
const holidays = this.getHolidays();
@@ -30,11 +36,19 @@ export class CalendarService {
for (const day of daysInAWeek) {
if (day) {
this.setWeekendSelection(day, selectedDates);
if (holidays.some(holiday => holiday.getTime() === day.getTime())) {
selectedDates._datesSelected.push(new SelectedDate(DayType.CLOSED_DAY, new DateRange<Date>(day, day)));
if (holidays.some((holiday) => holiday.getTime() === day.getTime())) {
selectedDates._datesSelected.push(
new SelectedDate(DayType.CLOSED_DAY, new DateRange<Date>(day, day)),
);
}
if (day.getDate() === new Date().getDate() && day.getMonth() === new Date().getMonth() && day.getFullYear() === new Date().getFullYear()) {
selectedDates._datesSelected.push(new SelectedDate(DayType.TODAY, new DateRange<Date>(day, day)));
if (
day.getDate() === new Date().getDate() &&
day.getMonth() === new Date().getMonth() &&
day.getFullYear() === new Date().getFullYear()
) {
selectedDates._datesSelected.push(
new SelectedDate(DayType.TODAY, new DateRange<Date>(day, day)),
);
}
}
}
@@ -46,21 +60,36 @@ export class CalendarService {
setWeekendSelection(date: Date, selectedDates: SelectedDates) {
if (date.getDay() === 6) {
selectedDates._datesSelected.push(new SelectedDate(DayType.WEEKEND, new DateRange<Date>(date, new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1))));
selectedDates._datesSelected.push(
new SelectedDate(
DayType.WEEKEND,
new DateRange<Date>(
date,
new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1),
),
),
);
}
if (date.getDate() === 1 && date.getDay() === 0) {
selectedDates._datesSelected.push(new SelectedDate(DayType.WEEKEND, new DateRange<Date>(new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1), date)));
selectedDates._datesSelected.push(
new SelectedDate(
DayType.WEEKEND,
new DateRange<Date>(
new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1),
date,
),
),
);
}
}
getHolidays(): Date[] {
// Logic to return holidays for the given year
const hd = new Holidays('FR', allTypesOptions);
const holidays = hd.getHolidays(new Date().getFullYear(), lang);
const holidaysPlusOne = hd.getHolidays(new Date().getFullYear() + 1, lang);
holidays.push(...holidaysPlusOne);
let holidaysDate: Date[] = holidays.map(holiday => new Date(holiday.date));
let holidaysDate: Date[] = holidays.map((holiday) => new Date(holiday.date));
return holidaysDate;
}
@@ -91,7 +120,7 @@ export class CalendarService {
let weekIndex = 0;
while (true) {
const week = this.daysInWeek(weekIndex, monthIndex, year);
if (week.every(day => day === null)) {
if (week.every((day) => day === null)) {
break;
}
weeks.push(week);
@@ -100,7 +129,6 @@ export class CalendarService {
return weeks;
}
static monthsInYear(year: number): Year {
const months: Year = [];
for (let monthIndex = 0; monthIndex < 12; monthIndex++) {
@@ -109,7 +137,6 @@ export class CalendarService {
return months;
}
static monthsInAYearFromNow(): Year {
const months: Year = [];
const currentMonthIndex = new Date().getMonth();
@@ -121,6 +148,10 @@ export class CalendarService {
}
return months;
}
static getWeekNumber(date: Date): number {
return dayjs(date).isoWeek();
}
}
export type VacationsNumber = {
@@ -134,39 +165,38 @@ export type Month = Week[];
export type Year = Month[];
export enum DayType {
WEEKEND = "weekend",
CLOSED_DAY = "closed-day",
RTT = "rtt",
CP = "cp",
OTHER = "other",
TODAY = "today",
WEEKEND = 'weekend',
CLOSED_DAY = 'closed-day',
RTT = 'rtt',
CP = 'cp',
OTHER = 'other',
TODAY = 'today',
}
export const tooltipTypeMapping: { [key in DayType]: string } = {
[DayType.WEEKEND]: "Weekend",
[DayType.CLOSED_DAY]: "Jour Férié",
[DayType.RTT]: "RTT",
[DayType.CP]: "Congé Payé",
[DayType.OTHER]: "Autre",
[DayType.WEEKEND]: 'Weekend',
[DayType.CLOSED_DAY]: 'Jour Férié',
[DayType.RTT]: 'RTT',
[DayType.CP]: 'Congé Payé',
[DayType.OTHER]: 'Autre',
[DayType.TODAY]: "Aujourd'hui",
};
export const monthNames: string[] = [
"Janvier",
"Février",
"Mars",
"Avril",
"Mai",
"Juin",
"Juillet",
"Août",
"Septembre",
"Octobre",
"Novembre",
"Décembre"
'Janvier',
'Février',
'Mars',
'Avril',
'Mai',
'Juin',
'Juillet',
'Août',
'Septembre',
'Octobre',
'Novembre',
'Décembre',
];
export interface SelectedDateInterface {
isSelected(date: Date): boolean;
@@ -186,7 +216,12 @@ export class SelectedDate implements SelectedDateInterface {
}
isSelected(date: Date): boolean {
return this.range.start !== null && this.range.end !== null && date >= this.range.start && date <= this.range.end;
return (
this.range.start !== null &&
this.range.end !== null &&
date >= this.range.start &&
date <= this.range.end
);
}
isStart(date: Date): boolean {
@@ -198,9 +233,9 @@ export class SelectedDate implements SelectedDateInterface {
}
getClasses(date: Date): string {
let returnType: DayType | string = "";
let returnType: DayType | string = '';
if (this.type && date >= this.range.start! && date <= this.range.end!) {
returnType = returnType += this.type + " ";
returnType = returnType += this.type + ' ';
}
return returnType;
}
@@ -297,7 +332,7 @@ export class SelectedDates implements SelectedDateInterface {
const motherGroup = new SelectedDate(
null,
new DateRange<Date>(new Date(groupStart), new Date(groupEnd))
new DateRange<Date>(new Date(groupStart), new Date(groupEnd)),
);
result.push(motherGroup);
@@ -307,7 +342,7 @@ export class SelectedDates implements SelectedDateInterface {
}
isSelected(date: Date): boolean {
return this.datesSelected.some(selectedDate => selectedDate.isSelected(date));
return this.datesSelected.some((selectedDate) => selectedDate.isSelected(date));
}
private getRangeBoundaryCounts(date: Date): { starts: number; ends: number } {
@@ -356,15 +391,23 @@ export class SelectedDates implements SelectedDateInterface {
* @returns True if the date is an interior day of at least one selected range; otherwise false.
*/
private existInARangeButNotABoundary(dateTest: Date): boolean {
return this.datesSelected.some(dateSelected => dateSelected.isSelected(dateTest) && !dateSelected.isStart(dateTest) && !dateSelected.isEnd(dateTest));
return this.datesSelected.some(
(dateSelected) =>
dateSelected.isSelected(dateTest) &&
!dateSelected.isStart(dateTest) &&
!dateSelected.isEnd(dateTest),
);
}
getClasses(date: Date): string {
return this.datesSelected.map(dateSelected => dateSelected.getClasses(date)).join(" ");
return this.datesSelected.map((dateSelected) => dateSelected.getClasses(date)).join(' ');
}
getTooltip(date: Date): string | null | undefined {
return this.datesSelected.map(dateSelected => dateSelected.getTooltip(date)).filter(tooltip => tooltip).join(" + ");
return this.datesSelected
.map((dateSelected) => dateSelected.getTooltip(date))
.filter((tooltip) => tooltip)
.join(' + ');
}
computeHeuristics(): number {
@@ -375,11 +418,13 @@ export class SelectedDates implements SelectedDateInterface {
let totalScore = 0;
// Sort all dates by start date to find next closest dates
const sorted = [...this.datesSelected].filter(date => date.type !== null).sort((a, b) => {
const aStart = a.range.start?.getTime() ?? 0;
const bStart = b.range.start?.getTime() ?? 0;
return aStart - bStart;
});
const sorted = [...this.datesSelected]
.filter((date) => date.type !== null)
.sort((a, b) => {
const aStart = a.range.start?.getTime() ?? 0;
const bStart = b.range.start?.getTime() ?? 0;
return aStart - bStart;
});
// PRIMARY: Optimize adjacency - reduce "little holes" between vacation periods
for (let i = 0; i < sorted.length - 1; i++) {
@@ -410,7 +455,7 @@ export class SelectedDates implements SelectedDateInterface {
// Penalty based on days between the two dates
const daysBetween = Math.floor((nextStartTime - currentEndTime) / oneDayInMs) - 1;
// Ensure daysBetween is non-negative before taking sqrt
totalScore -= (Math.sqrt(Math.max(0, daysBetween)));
totalScore -= Math.sqrt(Math.max(0, daysBetween));
}
}
@@ -439,8 +484,11 @@ export class SelectedDates implements SelectedDateInterface {
return totalScore;
}
optimizeVacations(vacationsNumber: VacationsNumber): void {
this.samediMalin(vacationsNumber);
optimizeVacations(
vacationsNumber: VacationsNumber,
calendarSettingsService: CalendarSettingsService,
): void {
if (calendarSettingsService.samediMalin()) this.samediMalin(vacationsNumber);
while (vacationsNumber.cp > 0) {
const result = this.lookForVacation(DayType.CP);
if (result.heuristic === -1) {
@@ -465,7 +513,9 @@ export class SelectedDates implements SelectedDateInterface {
}
samediMalin(vacationsNumber: VacationsNumber): void {
const samedi_ferie = this.datesSelected.filter(date => date.type === DayType.CLOSED_DAY && date.range.start?.getDay() === 6);
const samedi_ferie = this.datesSelected.filter(
(date) => date.type === DayType.CLOSED_DAY && date.range.start?.getDay() === 6,
);
for (const holiday of samedi_ferie) {
if (!holiday.range.start) continue;
@@ -501,31 +551,38 @@ export class SelectedDates implements SelectedDateInterface {
// Check if we can apply each strategy
const canApplyTwoBeforeStrategy =
!this.isSelected(twoDaysBefore1) &&
!this.isSelected(twoDaysBefore2);
!this.isSelected(twoDaysBefore1) && !this.isSelected(twoDaysBefore2);
const canApplyTwoAfterStrategy =
!this.isSelected(twoDaysAfter1) &&
!this.isSelected(twoDaysAfter2);
!this.isSelected(twoDaysAfter1) && !this.isSelected(twoDaysAfter2);
const canApplyMixedStrategy =
!this.isSelected(oneDayBefore) &&
!this.isSelected(oneDayAfter);
!this.isSelected(oneDayBefore) && !this.isSelected(oneDayAfter);
// Test all applicable strategies and choose the one with the best heuristic score
const strategies: { apply: () => void; heuristic: number }[] = [];
const tempDatesBackup = [...this._datesSelected];
if (canApplyTwoBeforeStrategy) {
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(twoDaysBefore1, twoDaysBefore2)));
this.push(
new SelectedDate(
DayType.CP,
new DateRange<Date>(twoDaysBefore1, twoDaysBefore2),
),
);
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(twoDaysBefore1, twoDaysBefore2)));
this.push(
new SelectedDate(
DayType.CP,
new DateRange<Date>(twoDaysBefore1, twoDaysBefore2),
),
);
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics()
heuristic: this.computeHeuristics(),
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -533,15 +590,22 @@ export class SelectedDates implements SelectedDateInterface {
}
if (canApplyTwoAfterStrategy) {
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(twoDaysAfter1, twoDaysAfter2)));
this.push(
new SelectedDate(DayType.CP, new DateRange<Date>(twoDaysAfter1, twoDaysAfter2)),
);
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(twoDaysAfter1, twoDaysAfter2)));
this.push(
new SelectedDate(
DayType.CP,
new DateRange<Date>(twoDaysAfter1, twoDaysAfter2),
),
);
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics()
heuristic: this.computeHeuristics(),
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -549,17 +613,31 @@ export class SelectedDates implements SelectedDateInterface {
}
if (canApplyMixedStrategy) {
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(oneDayBefore, oneDayBefore)));
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(oneDayAfter, oneDayAfter)));
this.push(
new SelectedDate(DayType.CP, new DateRange<Date>(oneDayBefore, oneDayBefore)),
);
this.push(
new SelectedDate(DayType.CP, new DateRange<Date>(oneDayAfter, oneDayAfter)),
);
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(oneDayBefore, oneDayBefore)));
this.push(new SelectedDate(DayType.CP, new DateRange<Date>(oneDayAfter, oneDayAfter)));
this.push(
new SelectedDate(
DayType.CP,
new DateRange<Date>(oneDayBefore, oneDayBefore),
),
);
this.push(
new SelectedDate(
DayType.CP,
new DateRange<Date>(oneDayAfter, oneDayAfter),
),
);
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics()
heuristic: this.computeHeuristics(),
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -569,7 +647,7 @@ export class SelectedDates implements SelectedDateInterface {
// Apply the strategy with the best heuristic score
if (strategies.length > 0) {
const bestStrategy = strategies.reduce((best, current) =>
current.heuristic > best.heuristic ? current : best
current.heuristic > best.heuristic ? current : best,
);
bestStrategy.apply();
}
@@ -580,12 +658,11 @@ export class SelectedDates implements SelectedDateInterface {
const daysOfYear = CalendarService.monthsInAYearFromNow();
const now = new Date();
now.setHours(0, 0, 0, 0);
daysOfYear.forEach(month => {
month.forEach(week => {
week.forEach(day => {
daysOfYear.forEach((month) => {
month.forEach((week) => {
week.forEach((day) => {
if (day) {
if (day)
day.setHours(0, 0, 0, 0);
if (day) day.setHours(0, 0, 0, 0);
if (day && day < now) {
week[week.indexOf(day)] = null;
}
@@ -605,14 +682,21 @@ export class SelectedDates implements SelectedDateInterface {
// mark these days as vacation
const startDay = new Date(day);
const endDay = new Date(day);
this.datesSelected.push(new SelectedDate(vacType, new DateRange<Date>(startDay, endDay)));
this.datesSelected.push(
new SelectedDate(vacType, new DateRange<Date>(startDay, endDay)),
);
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
this.push(new SelectedDate(vacType, new DateRange<Date>(startDay, endDay)));
this.push(
new SelectedDate(
vacType,
new DateRange<Date>(startDay, endDay),
),
);
},
heuristic: this.computeHeuristics(),
value: startDay
value: startDay,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -624,14 +708,11 @@ export class SelectedDates implements SelectedDateInterface {
// Apply the strategy with the best heuristic score
if (strategies.length > 0) {
const bestStrategy = strategies.reduce((best, current) =>
current.heuristic > best.heuristic ? current : best
current.heuristic > best.heuristic ? current : best,
);
strategies.forEach(strategy => {
console.log(`Strategy for ${strategy.value.toDateString()} has heuristic ${strategy.heuristic}`);
});
bestStrategy.apply();
return bestStrategy;
}
return { apply: () => { }, heuristic: -1 };
return { apply: () => {}, heuristic: -1 };
}
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { CalendarSettingsService } from './calendar-settings-service';
describe('CalendarSettingsService', () => {
let service: CalendarSettingsService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CalendarSettingsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,9 @@
import { Injectable, signal } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class CalendarSettingsService {
readonly showWeekNumbers = signal(false);
readonly samediMalin = signal(true);
}
+3 -14
View File
@@ -1,13 +1,10 @@
import { Injectable, signal, PLATFORM_ID, inject } from '@angular/core';
import { VacationsNumber } from './calendar-service';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class UserInputService {
private getRandomNumber(): number {
return Math.floor(Math.random() * 9) + 1;
}
@@ -16,17 +13,9 @@ export class UserInputService {
return {
cp: this.getRandomNumber(),
rtt: this.getRandomNumber(),
other: this.getRandomNumber()
other: this.getRandomNumber(),
};
}
vacationNumberSignal = signal<VacationsNumber>(this.getInitialValues());
get vacationNumber() {
return this.vacationNumberSignal();
}
setVacationNumber(vacationsNumber: VacationsNumber) {
this.vacationNumberSignal.set(vacationsNumber);
}
readonly vacationNumberSignal = signal<VacationsNumber>(this.getInitialValues());
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { UserSettingsService } from './user-settings-service';
describe('UserSettingsService', () => {
let service: UserSettingsService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UserSettingsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,6 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserSettingsService {}
+6
View File
@@ -23,6 +23,9 @@ html {
--number-color: black;
--number-color-hover: black;
--past-color: #b0b0b0;
--week-number-bg: #e0e0e0;
--week-number-bg-hover: #c0c0c0;
--week-number-color: black;
--today-border-color: #1976d2;
--other-month-color: #9e9e9e;
@@ -38,6 +41,9 @@ html {
--number-color: white;
--number-color-hover: white;
--past-color: #757575;
--week-number-bg: #424242;
--week-number-bg-hover: #616161;
--week-number-color: white;
--today-border-color: #0b385c;
--other-month-color: #757575;