Compare commits

...
Author SHA1 Message Date
copilot-swe-agent[bot] ed6b18b2a3 Initial plan 2025-11-06 23:19:09 +00:00
nessar da31c9c753 Refactor get method in CalendarSettingsService to throw an error if the setting ID doesn't exist 2025-11-07 00:12:02 +01:00
nessar bda3db2aa8 Skip initial execution in storedSignal effect to prevent unnecessary localStorage writes 2025-11-07 00:04:08 +01:00
nessar 7ffa57748b Enhance storedSignal function to accept an Injector for improved context handling in localStorage persistence 2025-11-06 23:59:26 +01:00
Théophyl HoguetandCopilot 275512d443 Update src/app/services/calendar-settings-service.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-06 23:58:42 +01:00
nessar 3eb35854d4 Update typescript-eslint to version 8.46.3 and enhance error handling in storedSignal function 2025-11-06 23:49:14 +01:00
nessar b793019ba7 Refactor calendar settings service to utilize a new storedSignal implementation for localStorage persistence and restore the stored-signal utility 2025-11-06 23:40:18 +01:00
Théophyl HoguetandCopilot d70aef4962 Update src/app/services/calendar-settings-service.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-06 23:33:47 +01:00
nessar 22993a02c5 Refactor calendar settings service to use a definitions map for settings and update related components to access settings via a getter method 2025-11-06 22:22:04 +01:00
nessar 2a60fef8ff Merge remote-tracking branch 'origin/main' into THoguet/issue5 2025-11-06 21:25:23 +01:00
nessar 3fce4c03b5 enregistrer les calendar settings dans le localstorage
Fixes #5
2025-11-06 21:23:55 +01:00
729cc3f4cf Refactor calendar settings dialog to use dynamic settings from service (#30)
* Refactor calendar settings dialog to use dynamic settings from service

* Update src/app/components/dialog/calendar-settings-dialog/calendar-settings-dialog.html

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Add type definition for calendar settings array (#35)

* Initial plan

* Add type definition for calendar settings array

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>

* use inject

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
2025-11-06 19:54:43 +01:00
dependabot[bot] f2b4d36709 Bump @types/node from 20.19.24 to 24.10.0 (#27)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 20.19.24 to 24.10.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 24.10.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-04 00:22:44 +01:00
dependabot[bot] 104bdb273d Bump jasmine-core in the development-dependencies group (#26)
Bumps the development-dependencies group with 1 update: [jasmine-core](https://github.com/jasmine/jasmine).


Updates `jasmine-core` from 5.9.0 to 5.12.1
- [Release notes](https://github.com/jasmine/jasmine/releases)
- [Changelog](https://github.com/jasmine/jasmine/blob/main/RELEASE.md)
- [Commits](https://github.com/jasmine/jasmine/compare/v5.9.0...v5.12.1)

---
updated-dependencies:
- dependency-name: jasmine-core
  dependency-version: 5.12.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: development-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-04 00:22:33 +01:00
Théophyl Hoguet 000f37ec56 Change Trivy image reference in workflow 2025-11-04 00:19:01 +01:00
Théophyl Hoguet a2b5329716 Update image reference for Trivy vulnerability scanner 2025-11-04 00:16:37 +01:00
Théophyl Hoguet cef670955a Update image reference for Trivy vulnerability scan 2025-11-04 00:12:19 +01:00
Théophyl Hoguet 2027b412b3 Update image reference for Trivy scanner step 2025-11-04 00:09:34 +01:00
Théophyl Hoguet 6556dd7cf2 Update image reference for Trivy vulnerability scan 2025-11-04 00:02:57 +01:00
CopilotandTHoguet f7bd101fb7 Modernize CI/CD pipeline with comprehensive automation (#25)
* Initial plan

* Add comprehensive CI/CD workflows and tooling

- Add PR validation workflow with lint, format, type check, test, and build steps
- Improve Docker build workflow with caching, security scanning, and manual trigger
- Add CodeQL security analysis workflow
- Add Dependabot configuration for automated dependency updates
- Configure ESLint with TypeScript support
- Add npm scripts for linting and formatting
- Format code with Prettier
- Fix linting issues in source code

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

* Update README and fix build configuration

- Add CI/CD documentation to README
- Document code quality tools and scripts
- Disable font optimization in production build to avoid network dependency
- Add build cache configuration for GitHub Actions

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-03 21:09:09 +01:00
Théophyl Hoguet fa71dee6a2 Add CodeQL analysis workflow configuration 2025-11-03 20:42:20 +01:00
Théophyl Hoguet a0cf899cc3 Merge pull request #24 from THoguet/copilot/add-application-tests
Add comprehensive test suite for vac-optimizer application
2025-11-03 20:02:28 +01:00
copilot-swe-agent[bot]andTHoguet 80a588741b Add comprehensive tests for vac-optimizer application
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-03 18:12:46 +00:00
copilot-swe-agent[bot] f99db8b82d Initial plan 2025-11-03 17:54:14 +00:00
Théophyl Hoguet e2ed512b11 Merge pull request #1 from THoguet/copilot/identify-improve-slow-code
Optimize vacation algorithm: reduce O(n²) lookups and eliminate redundant Date allocations
2025-11-03 18:53:15 +01:00
copilot-swe-agent[bot]andTHoguet ace0d70a6e Fix DST handling in computeHeuristics by restoring UTC normalization
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-03 17:15:33 +00:00
copilot-swe-agent[bot]andTHoguet 125786e2d9 Refactor: create DateCacheService to reduce date duplication
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-01 21:42:59 +00:00
copilot-swe-agent[bot]andTHoguet dbf504b060 Replace magic number -1 with named constant for better code clarity
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-01 21:07:17 +00:00
copilot-swe-agent[bot]andTHoguet 6061e02835 Address code review feedback: fix Date object reuse and add clarifying comments
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-01 21:01:07 +00:00
copilot-swe-agent[bot]andTHoguet 4e7eb18bc5 Further optimize: simplify heuristics calculation and cache component values
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-01 20:57:38 +00:00
copilot-swe-agent[bot]andTHoguet 601e7855aa Optimize performance: cache dates, reduce lookups, improve algorithms
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-01 20:55:39 +00:00
copilot-swe-agent[bot]andTHoguet d3caf86028 Initial analysis: Identify performance issues
Co-authored-by: THoguet <61246905+THoguet@users.noreply.github.com>
2025-11-01 20:50:49 +00:00
copilot-swe-agent[bot] 1ea8b05332 Initial plan 2025-11-01 20:44:45 +00:00
44 changed files with 1634 additions and 205 deletions

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
version: 2
updates:
# Enable version updates for npm
- package-ecosystem: 'npm'
directory: '/'
schedule:
interval: 'weekly'
day: 'monday'
open-pull-requests-limit: 10
groups:
angular:
patterns:
- '@angular/*'
development-dependencies:
dependency-type: 'development'
update-types:
- 'minor'
- 'patch'
# Enable version updates for GitHub Actions
- package-ecosystem: 'github-actions'
directory: '/'
schedule:
interval: 'weekly'
day: 'monday'
open-pull-requests-limit: 5
# Enable version updates for Docker
- package-ecosystem: 'docker'
directory: '/'
schedule:
interval: 'weekly'
day: 'monday'
open-pull-requests-limit: 5
+41
View File
@@ -0,0 +1,41 @@
name: CodeQL Security Analysis
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 0 * * 1' # Run every Monday at midnight UTC
jobs:
analyze:
name: Analyze Code
runs-on: ubuntu-latest
permissions:
security-events: write
actions: read
contents: read
strategy:
fail-fast: false
matrix:
language: ['javascript-typescript']
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: security-extended,security-and-quality
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: '/language:${{matrix.language}}'
+23 -1
View File
@@ -5,6 +5,7 @@ on:
branches: [main]
release:
types: [published]
workflow_dispatch:
jobs:
build-and-push:
@@ -12,10 +13,14 @@ jobs:
permissions:
contents: read
packages: write
security-events: write
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
@@ -33,11 +38,28 @@ jobs:
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push
uses: docker/build-push-action@v5
id: build
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@0.27.0
with:
image-ref: ghcr.io/thoguet/vac-optimizer@${{ steps.build.outputs.digest }}
format: 'sarif'
output: 'trivy-results.sarif'
- name: Upload Trivy results to GitHub Security tab
uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: 'trivy-results.sarif'
+105
View File
@@ -0,0 +1,105 @@
name: PR Validation
on:
pull_request:
branches: [main]
push:
branches: [main]
jobs:
lint:
name: Lint Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Check code formatting with Prettier
run: npx prettier --check "src/**/*.{ts,html,scss,css,json}"
- name: Run ESLint
run: npx eslint "src/**/*.ts"
type-check:
name: TypeScript Type Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run TypeScript compiler
run: npx tsc --noEmit
test:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run unit tests
run: npm test -- --watch=false --browsers=ChromeHeadless --code-coverage
- name: Upload coverage reports
uses: codecov/codecov-action@v4
if: always()
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage/vac-optimizer/lcov.info
fail_ci_if_error: false
build:
name: Build Application
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build production bundle
run: npm run build -- --configuration production
env:
NG_BUILD_CACHE: '.angular/cache'
- name: Check bundle size
run: |
du -sh dist/vac-optimizer/browser
echo "Build completed successfully"
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: build-artifacts
path: dist/
retention-days: 7
+41
View File
@@ -12,6 +12,38 @@ ng serve
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code Quality
This project uses ESLint and Prettier to maintain code quality and consistency.
### Linting
Check for linting errors:
```bash
npm run lint
```
Auto-fix linting issues:
```bash
npm run lint:fix
```
### Formatting
Check code formatting:
```bash
npm run format:check
```
Format code:
```bash
npm run format
```
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
@@ -54,6 +86,15 @@ ng e2e
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## CI/CD
This project uses GitHub Actions for continuous integration and deployment:
- **PR Validation**: Automatically runs on pull requests to validate code quality, run tests, and build the application
- **Docker Build & Push**: Builds and publishes Docker images to GitHub Container Registry on main branch pushes and releases
- **CodeQL Analysis**: Runs security analysis weekly and on pull requests
- **Dependabot**: Automatically updates dependencies weekly
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
+4 -1
View File
@@ -52,7 +52,10 @@
"maximumError": "16kB"
}
],
"outputHashing": "all"
"outputHashing": "all",
"optimization": {
"fonts": false
}
},
"development": {
"optimization": false,
+34
View File
@@ -0,0 +1,34 @@
import eslintJs from '@eslint/js';
import tseslint from 'typescript-eslint';
import prettier from 'eslint-config-prettier';
import prettierPlugin from 'eslint-plugin-prettier';
export default [
eslintJs.configs.recommended,
...tseslint.configs.recommended,
prettier,
{
files: ['**/*.ts'],
plugins: {
prettier: prettierPlugin,
},
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
rules: {
'prettier/prettier': 'error',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
},
},
{
ignores: ['dist/**', 'node_modules/**', '.angular/**', 'coverage/**'],
},
];
+463 -15
View File
@@ -1,12 +1,12 @@
{
"name": "vac-optimizer",
"version": "0.0.0",
"version": "1.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "vac-optimizer",
"version": "0.0.0",
"version": "1.5.0",
"dependencies": {
"@angular/cdk": "^20.2.10",
"@angular/common": "^20.3.0",
@@ -28,14 +28,15 @@
"@angular/build": "^20.3.7",
"@angular/cli": "^20.3.7",
"@angular/compiler-cli": "^20.3.0",
"@eslint/js": "^9.17.0",
"@types/express": "^5.0.1",
"@types/jasmine": "~5.1.0",
"@types/jest": "^30.0.0",
"@types/node": "^20.17.19",
"@types/node": "^24.10.0",
"eslint": "^9.38.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"jasmine-core": "~5.9.0",
"jasmine-core": "~5.12.1",
"jest": "^30.2.0",
"jest-preset-angular": "^15.0.3",
"karma": "~6.4.0",
@@ -44,7 +45,8 @@
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"prettier": "^3.6.2",
"typescript": "~5.9.2"
"typescript": "~5.9.2",
"typescript-eslint": "^8.46.3"
}
},
"node_modules/@acemir/cssom": {
@@ -3718,6 +3720,44 @@
"@tybys/wasm-util": "^0.10.0"
}
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
"integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "2.0.5",
"run-parallel": "^1.1.9"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/@nodelib/fs.stat": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
"integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
}
},
"node_modules/@nodelib/fs.walk": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
"integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.scandir": "2.1.5",
"fastq": "^1.6.0"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/@npmcli/agent": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz",
@@ -5036,13 +5076,13 @@
"license": "MIT"
},
"node_modules/@types/node": {
"version": "20.19.24",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.24.tgz",
"integrity": "sha512-FE5u0ezmi6y9OZEzlJfg37mqqf6ZDSF2V/NLjUyGrR9uTZ7Sb9F7bLNZ03S4XVUNRWGA7Ck4c1kK+YnuWjl+DA==",
"version": "24.10.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.0.tgz",
"integrity": "sha512-qzQZRBqkFsYyaSWXuEHc2WR9c0a0CXwiE5FWUvn7ZM+vdy1uZLfCunD38UzhuB7YN/J11ndbDBcTmOdxJo9Q7A==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
"undici-types": "~7.16.0"
}
},
"node_modules/@types/qs": {
@@ -5123,6 +5163,264 @@
"dev": true,
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.46.3.tgz",
"integrity": "sha512-sbaQ27XBUopBkRiuY/P9sWGOWUW4rl8fDoHIUmLpZd8uldsTyB4/Zg6bWTegPoTLnKj9Hqgn3QD6cjPNB32Odw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "8.46.3",
"@typescript-eslint/type-utils": "8.46.3",
"@typescript-eslint/utils": "8.46.3",
"@typescript-eslint/visitor-keys": "8.46.3",
"graphemer": "^1.4.0",
"ignore": "^7.0.0",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"@typescript-eslint/parser": "^8.46.3",
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
"version": "7.0.5",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
"integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/@typescript-eslint/parser": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.46.3.tgz",
"integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/scope-manager": "8.46.3",
"@typescript-eslint/types": "8.46.3",
"@typescript-eslint/typescript-estree": "8.46.3",
"@typescript-eslint/visitor-keys": "8.46.3",
"debug": "^4.3.4"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/project-service": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.46.3.tgz",
"integrity": "sha512-Fz8yFXsp2wDFeUElO88S9n4w1I4CWDTXDqDr9gYvZgUpwXQqmZBr9+NTTql5R3J7+hrJZPdpiWaB9VNhAKYLuQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/tsconfig-utils": "^8.46.3",
"@typescript-eslint/types": "^8.46.3",
"debug": "^4.3.4"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/scope-manager": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.46.3.tgz",
"integrity": "sha512-FCi7Y1zgrmxp3DfWfr+3m9ansUUFoy8dkEdeQSgA9gbm8DaHYvZCdkFRQrtKiedFf3Ha6VmoqoAaP68+i+22kg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.46.3",
"@typescript-eslint/visitor-keys": "8.46.3"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/tsconfig-utils": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.46.3.tgz",
"integrity": "sha512-GLupljMniHNIROP0zE7nCcybptolcH8QZfXOpCfhQDAdwJ/ZTlcaBOYebSOZotpti/3HrHSw7D3PZm75gYFsOA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/type-utils": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.46.3.tgz",
"integrity": "sha512-ZPCADbr+qfz3aiTTYNNkCbUt+cjNwI/5McyANNrFBpVxPt7GqpEYz5ZfdwuFyGUnJ9FdDXbGODUu6iRCI6XRXw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.46.3",
"@typescript-eslint/typescript-estree": "8.46.3",
"@typescript-eslint/utils": "8.46.3",
"debug": "^4.3.4",
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/types": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.46.3.tgz",
"integrity": "sha512-G7Ok9WN/ggW7e/tOf8TQYMaxgID3Iujn231hfi0Pc7ZheztIJVpO44ekY00b7akqc6nZcvregk0Jpah3kep6hA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/typescript-estree": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.46.3.tgz",
"integrity": "sha512-f/NvtRjOm80BtNM5OQtlaBdM5BRFUv7gf381j9wygDNL+qOYSNOgtQ/DCndiYi80iIOv76QqaTmp4fa9hwI0OA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/project-service": "8.46.3",
"@typescript-eslint/tsconfig-utils": "8.46.3",
"@typescript-eslint/types": "8.46.3",
"@typescript-eslint/visitor-keys": "8.46.3",
"debug": "^4.3.4",
"fast-glob": "^3.3.2",
"is-glob": "^4.0.3",
"minimatch": "^9.0.4",
"semver": "^7.6.0",
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
"integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^2.0.1"
},
"engines": {
"node": ">=16 || 14 >=14.17"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/@typescript-eslint/utils": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.46.3.tgz",
"integrity": "sha512-VXw7qmdkucEx9WkmR3ld/u6VhRyKeiF1uxWwCy/iuNfokjJ7VhsgLSOTjsol8BunSw190zABzpwdNsze2Kpo4g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.7.0",
"@typescript-eslint/scope-manager": "8.46.3",
"@typescript-eslint/types": "8.46.3",
"@typescript-eslint/typescript-estree": "8.46.3"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/visitor-keys": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.46.3.tgz",
"integrity": "sha512-uk574k8IU0rOF/AjniX8qbLSGURJVUCeM5e4MIMKBFFi8weeiLrG1fyQejyLXQpRZbU/1BuQasleV/RfHC3hHg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.46.3",
"eslint-visitor-keys": "^4.2.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@ungap/structured-clone": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@@ -7680,6 +7978,36 @@
"dev": true,
"license": "Apache-2.0"
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
"@nodelib/fs.walk": "^1.2.3",
"glob-parent": "^5.1.2",
"merge2": "^1.3.0",
"micromatch": "^4.0.8"
},
"engines": {
"node": ">=8.6.0"
}
},
"node_modules/fast-glob/node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/fast-json-stable-stringify": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
@@ -7711,6 +8039,16 @@
],
"license": "BSD-3-Clause"
},
"node_modules/fastq": {
"version": "1.19.1",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
"integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==",
"dev": true,
"license": "ISC",
"dependencies": {
"reusify": "^1.0.4"
}
},
"node_modules/fb-watchman": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz",
@@ -8127,6 +8465,13 @@
"dev": true,
"license": "ISC"
},
"node_modules/graphemer": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
"integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==",
"dev": true,
"license": "MIT"
},
"node_modules/handlebars": {
"version": "4.7.8",
"resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz",
@@ -8805,9 +9150,9 @@
"license": "MIT"
},
"node_modules/jasmine-core": {
"version": "5.9.0",
"resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-5.9.0.tgz",
"integrity": "sha512-OMUvF1iI6+gSRYOhMrH4QYothVLN9C3EJ6wm4g7zLJlnaTl8zbaPOr0bTw70l7QxkoM7sVFOWo83u9B2Fe2Zng==",
"version": "5.12.1",
"resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-5.12.1.tgz",
"integrity": "sha512-P/UbRZ0LKwXe7wEpwDheuhunPwITn4oPALhrJEQJo6756EwNGnsK/TSQrWojBB4cQDQ+VaxWYws9tFNDuiMh2Q==",
"dev": true,
"license": "MIT"
},
@@ -10696,6 +11041,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
}
},
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
@@ -12251,6 +12606,27 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
"integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
@@ -12427,6 +12803,17 @@
"node": ">= 4"
}
},
"node_modules/reusify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
"integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
"dev": true,
"license": "MIT",
"engines": {
"iojs": ">=1.0.0",
"node": ">=0.10.0"
}
},
"node_modules/rfdc": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
@@ -12531,6 +12918,30 @@
"node": ">= 18"
}
},
"node_modules/run-parallel": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
"integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"queue-microtask": "^1.2.2"
}
},
"node_modules/rxjs": {
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
@@ -13695,6 +14106,19 @@
"node": ">=6"
}
},
"node_modules/ts-api-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
"integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18.12"
},
"peerDependencies": {
"typescript": ">=4.8.4"
}
},
"node_modules/ts-jest": {
"version": "29.4.5",
"resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.5.tgz",
@@ -13859,6 +14283,30 @@
"node": ">=14.17"
}
},
"node_modules/typescript-eslint": {
"version": "8.46.3",
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.46.3.tgz",
"integrity": "sha512-bAfgMavTuGo+8n6/QQDVQz4tZ4f7Soqg53RbrlZQEoAltYop/XR4RAts/I0BrO3TTClTSTFJ0wYbla+P8cEWJA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/eslint-plugin": "8.46.3",
"@typescript-eslint/parser": "8.46.3",
"@typescript-eslint/typescript-estree": "8.46.3",
"@typescript-eslint/utils": "8.46.3"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/ua-parser-js": {
"version": "0.7.41",
"resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.41.tgz",
@@ -13901,9 +14349,9 @@
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"dev": true,
"license": "MIT"
},
+10 -4
View File
@@ -7,7 +7,11 @@
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"serve:ssr:vac-optimizer": "node dist/vac-optimizer/server/server.mjs"
"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,
@@ -43,14 +47,15 @@
"@angular/build": "^20.3.7",
"@angular/cli": "^20.3.7",
"@angular/compiler-cli": "^20.3.0",
"@eslint/js": "^9.17.0",
"@types/express": "^5.0.1",
"@types/jasmine": "~5.1.0",
"@types/jest": "^30.0.0",
"@types/node": "^20.17.19",
"@types/node": "^24.10.0",
"eslint": "^9.38.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"jasmine-core": "~5.9.0",
"jasmine-core": "~5.12.1",
"jest": "^30.2.0",
"jest-preset-angular": "^15.0.3",
"karma": "~6.4.0",
@@ -59,6 +64,7 @@
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"prettier": "^3.6.2",
"typescript": "~5.9.2"
"typescript": "~5.9.2",
"typescript-eslint": "^8.46.3"
}
}
+1 -3
View File
@@ -4,9 +4,7 @@ import { appConfig } from './app.config';
import { serverRoutes } from './app.routes.server';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering(withRoutes(serverRoutes))
]
providers: [provideServerRendering(withRoutes(serverRoutes))],
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
+2 -2
View File
@@ -3,6 +3,6 @@ import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: '**',
renderMode: RenderMode.Client
}
renderMode: RenderMode.Client,
},
];
+2 -2
View File
@@ -6,7 +6,7 @@ describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideZonelessChangeDetection()]
providers: [provideZonelessChangeDetection()],
}).compileComponents();
});
@@ -20,6 +20,6 @@ describe('App', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, vac-optimizer');
expect(compiled.querySelector('h1')?.textContent).toContain('vac-optimizer');
});
});
+1 -1
View File
@@ -1,4 +1,4 @@
import { ChangeDetectionStrategy, Component, model, signal } from '@angular/core';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { provideNativeDateAdapter } from '@angular/material/core';
import { MatDivider } from '@angular/material/divider';
@@ -2,7 +2,7 @@
<h3>{{ getMonthName() }} {{ year }}</h3>
<div>
<div class="row header">
@if (calendarSettingsService.showWeekNumbers()) {
@if (calendarSettingsService.get('showWeekNumbers')()) {
<p class="day empty week-number"></p>
}
<p class="day">L</p>
@@ -16,7 +16,7 @@
<div class="cols">
@for (week of weeksInAMonth; track $index) {
<div class="row week">
@if (calendarSettingsService.showWeekNumbers()) {
@if (calendarSettingsService.get('showWeekNumbers')()) {
<p
class="day week-number"
[class.start]="$index === 0"
@@ -1,5 +1,5 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { CalendarMonth } from './calendar-month';
describe('CalendarMonth', () => {
@@ -8,9 +8,9 @@ describe('CalendarMonth', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CalendarMonth]
})
.compileComponents();
imports: [CalendarMonth],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
fixture = TestBed.createComponent(CalendarMonth);
component = fixture.componentInstance;
@@ -1,7 +1,8 @@
import { Component, Input, OnInit } from '@angular/core';
import { Component, Input, OnInit, inject } 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';
import { DateCacheService } from '../../services/date-cache.service';
@Component({
selector: 'app-calendar-month',
@@ -10,7 +11,8 @@ import { CalendarSettingsService } from '../../services/calendar-settings-servic
styleUrl: './calendar-month.scss',
})
export class CalendarMonth implements OnInit {
constructor(protected calendarSettingsService: CalendarSettingsService) {}
protected calendarSettingsService = inject(CalendarSettingsService);
private dateCache = inject(DateCacheService);
@Input({ required: true })
monthIndex!: number;
@@ -18,10 +20,9 @@ export class CalendarMonth implements OnInit {
@Input({ required: true })
year!: number;
// Use DateCacheService instead of creating Date objects
getNow(): Date {
const now = new Date();
now.setHours(0, 0, 0, 0);
return now;
return this.dateCache.getNow();
}
currentMonth: Date = new Date();
@@ -1,5 +1,5 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { CalendarSettings } from './calendar-settings';
describe('CalendarSettings', () => {
@@ -8,9 +8,9 @@ describe('CalendarSettings', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CalendarSettings]
})
.compileComponents();
imports: [CalendarSettings],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
fixture = TestBed.createComponent(CalendarSettings);
component = fixture.componentInstance;
@@ -1,7 +1,7 @@
import { Component } from '@angular/core';
import { MatButton, MatButtonModule } from '@angular/material/button';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatIcon, MatIconModule } from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import { CalendarSettingsDialog } from '../dialog/calendar-settings-dialog/calendar-settings-dialog';
import { MatDividerModule } from '@angular/material/divider';
@@ -10,7 +10,11 @@
@for (month of months; track $index) {
<mat-card class="card">
<mat-card-content>
<app-calendar-month [monthIndex]="month" [year]="getYear(month)" [selectedDates]="selectedDates"></app-calendar-month>
<app-calendar-month
[monthIndex]="month"
[year]="getYear(month)"
[selectedDates]="selectedDates"
></app-calendar-month>
</mat-card-content>
</mat-card>
}
@@ -66,5 +66,10 @@
}
:root {
@include mat.progress-spinner-overrides((size: 0.5rem, active-indicator-width: 0.25rem));
@include mat.progress-spinner-overrides(
(
size: 0.5rem,
active-indicator-width: 0.25rem,
)
);
}
@@ -1,5 +1,5 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { CalendarYear } from './calendar-year';
describe('CalendarYear', () => {
@@ -8,9 +8,9 @@ describe('CalendarYear', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CalendarYear]
})
.compileComponents();
imports: [CalendarYear],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
fixture = TestBed.createComponent(CalendarYear);
component = fixture.componentInstance;
@@ -1,4 +1,4 @@
import { Component, effect, signal } from '@angular/core';
import { Component, effect, signal, inject } from '@angular/core';
import { UserInputService } from '../../services/user-input-service';
import { MatCard, MatCardContent } from '@angular/material/card';
import { CalendarMonth } from '../calendar-month/calendar-month';
@@ -6,6 +6,7 @@ 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';
@Component({
selector: 'app-calendar-year',
@@ -14,17 +15,27 @@ import { CalendarSettingsService } from '../../services/calendar-settings-servic
styleUrl: './calendar-year.scss',
})
export class CalendarYear {
private dateCache = inject(DateCacheService);
private userInput = inject(UserInputService);
private calendarService = inject(CalendarService);
private calendarSettingsService = inject(CalendarSettingsService);
protected isLoading = signal(true);
constructor(
private userInput: UserInputService,
private calendarService: CalendarService,
private calendarSettingsService: CalendarSettingsService,
) {
// Use DateCacheService instead of creating Date objects
private get currentMonth() {
return this.dateCache.getCurrentMonth();
}
private get currentYear() {
return this.dateCache.getCurrentYear();
}
constructor() {
effect(() => {
this.selectedDates = this.calendarService.getSelectedDatesForYear();
const vacationData = this.userInput.vacationNumberSignal();
const c = this.calendarSettingsService.samediMalin();
const c = this.calendarSettingsService.get('samediMalin')();
console.log('Samedi Malin setting:', c);
console.log('Optimizing vacations with data:', vacationData);
this.isLoading.set(true);
@@ -35,6 +46,7 @@ export class CalendarYear {
this.selectedDates.optimizeVacations(
{ ...vacationData },
this.calendarSettingsService,
this.calendarService,
);
}
this.isLoading.set(false);
@@ -45,13 +57,10 @@ export class CalendarYear {
protected selectedDates: SelectedDates = new SelectedDates();
getYear(monthIndex: number): number {
const offset = new Date().getMonth() <= monthIndex ? 0 : 1;
return new Date().getFullYear() + offset;
const offset = this.currentMonth <= monthIndex ? 0 : 1;
return this.currentYear + offset;
}
// months starting from actual date
protected months: number[] = Array.from(
{ length: 12 },
(_, i) => (new Date().getMonth() + i) % 12,
);
// months starting from actual date - cache this array
protected months: number[] = Array.from({ length: 12 }, (_, i) => (this.currentMonth + i) % 12);
}
@@ -1,5 +1,5 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { DarkLightModeButton } from './dark-light-mode-button';
describe('DarkLightModeButton', () => {
@@ -9,6 +9,7 @@ describe('DarkLightModeButton', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [DarkLightModeButton],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
fixture = TestBed.createComponent(DarkLightModeButton);
@@ -4,26 +4,18 @@
<p>Configure your calendar settings here.</p>
</div>
<div style="display: flex; flex-direction: column; gap: 1rem">
@for (setting of calendarSettingsService.settingsArray; track setting.id) {
<div style="align-self: flex-start">
<mat-slide-toggle
id="showWeekNumbers"
name="showWeekNumbers"
[checked]="calendarSettingsService.showWeekNumbers()"
(change)="calendarSettingsService.showWeekNumbers.set($event.checked)"
[id]="setting.id"
[name]="setting.id"
[checked]="setting.signal()"
(change)="setting.signal.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
{{ setting.description }}
</mat-slide-toggle>
</div>
}
</div>
<button mat-button (click)="closeDialog()">Fermer</button>
</div>
@@ -1,5 +1,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { CalendarSettingsDialog } from './calendar-settings-dialog';
describe('CalendarSettingsDialog', () => {
@@ -8,9 +9,17 @@ describe('CalendarSettingsDialog', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CalendarSettingsDialog]
})
.compileComponents();
imports: [CalendarSettingsDialog],
providers: [
provideZonelessChangeDetection(),
{
provide: MatDialogRef,
useValue: {
close: jasmine.createSpy('close'),
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(CalendarSettingsDialog);
component = fixture.componentInstance;
@@ -20,4 +29,13 @@ describe('CalendarSettingsDialog', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have calendar settings service', () => {
expect(component['calendarSettingsService']).toBeDefined();
});
it('should close dialog when closeDialog is called', () => {
component.closeDialog();
expect(component.dialogRef.close).toHaveBeenCalled();
});
});
@@ -1,10 +1,8 @@
import { Component } from '@angular/core';
import { Component, inject } 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';
import { CdkFixedSizeVirtualScroll } from '@angular/cdk/scrolling';
@Component({
selector: 'app-calendar-settings-dialog',
@@ -13,10 +11,8 @@ import { CdkFixedSizeVirtualScroll } from '@angular/cdk/scrolling';
styleUrl: './calendar-settings-dialog.scss',
})
export class CalendarSettingsDialog {
constructor(
public dialogRef: MatDialogRef<CalendarSettingsDialog>,
protected calendarSettingsService: CalendarSettingsService,
) {}
public readonly dialogRef = inject<MatDialogRef<CalendarSettingsDialog>>(MatDialogRef);
protected readonly calendarSettingsService = inject(CalendarSettingsService);
closeDialog() {
this.dialogRef.close();
@@ -1,5 +1,5 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { UserInput } from './user-input';
describe('UserInput', () => {
@@ -8,9 +8,9 @@ describe('UserInput', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UserInput]
})
.compileComponents();
imports: [UserInput],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
fixture = TestBed.createComponent(UserInput);
component = fixture.componentInstance;
@@ -20,4 +20,21 @@ describe('UserInput', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
it('should initialize form with values from service', () => {
expect(component.userInputForm).toBeDefined();
expect(component.userInputForm.get('CP')).toBeDefined();
expect(component.userInputForm.get('RTT')).toBeDefined();
expect(component.userInputForm.get('Others')).toBeDefined();
});
it('should have valid form controls', () => {
const cpControl = component.userInputForm.get('CP');
const rttControl = component.userInputForm.get('RTT');
const othersControl = component.userInputForm.get('Others');
expect(cpControl).toBeTruthy();
expect(rttControl).toBeTruthy();
expect(othersControl).toBeTruthy();
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { Component, OnInit, OnDestroy, effect } from '@angular/core';
import { MatFormField, MatLabel } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
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';
@@ -1,5 +1,5 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { UserSettings } from './user-settings';
describe('UserSettings', () => {
@@ -8,9 +8,9 @@ describe('UserSettings', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UserSettings]
})
.compileComponents();
imports: [UserSettings],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
fixture = TestBed.createComponent(UserSettings);
component = fixture.componentInstance;
+195 -6
View File
@@ -1,16 +1,205 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { CalendarService, DayType, SelectedDate, SelectedDates } from './calendar-service';
import { DateRange } from '@angular/material/datepicker';
import { Calendar } from './calendar';
describe('Calendar', () => {
let service: Calendar;
describe('CalendarService', () => {
let service: CalendarService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(Calendar);
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
service = TestBed.inject(CalendarService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('getHolidays', () => {
it('should return an array of holidays', () => {
const holidays = service.getHolidays();
expect(Array.isArray(holidays)).toBe(true);
expect(holidays.length).toBeGreaterThan(0);
});
it('should cache holidays for the same year', () => {
const holidays1 = service.getHolidays();
const holidays2 = service.getHolidays();
expect(holidays1).toEqual(holidays2);
});
});
describe('static date calculation methods', () => {
it('should calculate days in a week', () => {
const week = CalendarService.daysInWeek(0, 0, 2024);
expect(week.length).toBe(7);
});
it('should calculate weeks in a month', () => {
const weeks = CalendarService.weeksInMonth(0, 2024);
expect(weeks.length).toBeGreaterThan(0);
expect(weeks.length).toBeLessThanOrEqual(6);
});
it('should calculate months in a year', () => {
const months = CalendarService.monthsInYear(2024);
expect(months.length).toBe(12);
});
it('should calculate months from now', () => {
const months = service.monthsInAYearFromNow();
expect(months.length).toBe(12);
});
it('should return week number for a date', () => {
const date = new Date(2024, 0, 1);
const weekNumber = CalendarService.getWeekNumber(date);
expect(weekNumber).toBeGreaterThan(0);
expect(weekNumber).toBeLessThanOrEqual(53);
});
});
describe('getSelectedDatesForYear', () => {
it('should return selected dates for the year', () => {
const selectedDates = service.getSelectedDatesForYear();
expect(selectedDates).toBeDefined();
expect(selectedDates._datesSelected.length).toBeGreaterThan(0);
});
it('should include weekends', () => {
const selectedDates = service.getSelectedDatesForYear();
const hasWeekend = selectedDates._datesSelected.some(
(date) => date.type === DayType.WEEKEND,
);
expect(hasWeekend).toBe(true);
});
it('should include holidays', () => {
const selectedDates = service.getSelectedDatesForYear();
const hasHoliday = selectedDates._datesSelected.some(
(date) => date.type === DayType.CLOSED_DAY,
);
expect(hasHoliday).toBe(true);
});
it('should include today', () => {
const selectedDates = service.getSelectedDatesForYear();
const hasToday = selectedDates._datesSelected.some(
(date) => date.type === DayType.TODAY,
);
expect(hasToday).toBe(true);
});
});
describe('setWeekendSelection', () => {
it('should add weekend for Saturday', () => {
const selectedDates = new SelectedDates();
const saturday = new Date(2024, 0, 6); // A Saturday
service.setWeekendSelection(saturday, selectedDates);
expect(selectedDates._datesSelected.length).toBeGreaterThan(0);
});
});
});
describe('SelectedDate', () => {
it('should check if date is selected', () => {
const date = new Date(2024, 0, 1);
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
expect(selectedDate.isSelected(date)).toBe(true);
});
it('should check if date is start', () => {
const date = new Date(2024, 0, 1);
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
expect(selectedDate.isStart(date)).toBe(true);
});
it('should check if date is end', () => {
const date = new Date(2024, 0, 1);
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
expect(selectedDate.isEnd(date)).toBe(true);
});
it('should return correct classes for date', () => {
const date = new Date(2024, 0, 1);
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
const classes = selectedDate.getClasses(date);
expect(classes).toContain(DayType.CP);
});
it('should return tooltip for selected date', () => {
const date = new Date(2024, 0, 1);
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
const tooltip = selectedDate.getTooltip(date);
expect(tooltip).toBeTruthy();
});
it('should calculate length in days', () => {
const startDate = new Date(2024, 0, 1);
const endDate = new Date(2024, 0, 3);
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(startDate, endDate));
expect(selectedDate.getLengthInDays()).toBe(3);
});
it('should not mark TODAY as selected', () => {
const date = new Date(2024, 0, 1);
const selectedDate = new SelectedDate(DayType.TODAY, new DateRange<Date>(date, date));
expect(selectedDate.isSelected(date)).toBe(false);
});
});
describe('SelectedDates', () => {
it('should push selected dates', () => {
const selectedDates = new SelectedDates();
const date = new Date(2024, 0, 1);
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
expect(selectedDates._datesSelected.length).toBe(1);
});
it('should check if date is selected', () => {
const selectedDates = new SelectedDates();
const date = new Date(2024, 0, 1);
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
expect(selectedDates.isSelected(date)).toBe(true);
});
it('should group adjacent dates', () => {
const selectedDates = new SelectedDates();
const date1 = new Date(2024, 0, 1);
const date2 = new Date(2024, 0, 2);
selectedDates._datesSelected.push(
new SelectedDate(DayType.CP, new DateRange<Date>(date1, date1)),
);
selectedDates._datesSelected.push(
new SelectedDate(DayType.RTT, new DateRange<Date>(date2, date2)),
);
selectedDates.update();
expect(selectedDates.datesSelected.length).toBeGreaterThan(2);
});
it('should compute heuristics', () => {
const selectedDates = new SelectedDates();
const date = new Date(2024, 0, 1);
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
const heuristic = selectedDates.computeHeuristics();
expect(typeof heuristic).toBe('number');
});
it('should return correct classes', () => {
const selectedDates = new SelectedDates();
const date = new Date(2024, 0, 1);
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
const classes = selectedDates.getClasses(date);
expect(classes).toContain(DayType.CP);
});
it('should return tooltip', () => {
const selectedDates = new SelectedDates();
const date = new Date(2024, 0, 1);
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
const tooltip = selectedDates.getTooltip(date);
expect(tooltip).toBeTruthy();
});
});
+125 -70
View File
@@ -1,10 +1,11 @@
import { Injectable } from '@angular/core';
import { Injectable, inject } 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';
import { DateCacheService } from './date-cache.service';
dayjs.extend(weekOfYear);
dayjs.extend(isoWeek);
@@ -19,32 +20,49 @@ const allTypesOptions: HolidaysTypes.Options = {
providedIn: 'root',
})
export class CalendarService {
private dateCache = inject(DateCacheService);
// Cache for holiday timestamps
private holidayTimestampsCache: Set<number> | null = null;
private holidayCacheYear: number | null = null;
// Get selected dates from current date to the next year
getSelectedDatesFromNow(): SelectedDates {
const holidays = this.getHolidays();
let selectedDates: SelectedDates = new SelectedDates();
const _holidays = this.getHolidays();
const selectedDates: SelectedDates = new SelectedDates();
// Logic to populate selectedDates from now until the next year
return selectedDates;
}
getSelectedDatesForYear(): SelectedDates {
const holidays = this.getHolidays();
const monthInAYear = CalendarService.monthsInAYearFromNow();
let selectedDates: SelectedDates = new SelectedDates();
const monthInAYear = this.monthsInAYearFromNow();
const selectedDates: SelectedDates = new SelectedDates();
// Use DateCacheService to get today's date components
const {
date: todayDate,
month: todayMonth,
year: todayYear,
} = this.dateCache.getTodayComponents();
// Create a Set of holiday timestamps for O(1) lookup instead of O(n)
const holidayTimestamps = new Set(holidays.map((h) => h.getTime()));
for (const weeksInAMonth of monthInAYear) {
for (const daysInAWeek of weeksInAMonth) {
for (const day of daysInAWeek) {
if (day) {
this.setWeekendSelection(day, selectedDates);
if (holidays.some((holiday) => holiday.getTime() === day.getTime())) {
if (holidayTimestamps.has(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()
day.getDate() === todayDate &&
day.getMonth() === todayMonth &&
day.getFullYear() === todayYear
) {
selectedDates._datesSelected.push(
new SelectedDate(DayType.TODAY, new DateRange<Date>(day, day)),
@@ -84,12 +102,24 @@ export class CalendarService {
}
getHolidays(): Date[] {
// Cache holidays to avoid recalculation
const currentYear = this.dateCache.getCurrentYear();
if (this.holidayCacheYear === currentYear && this.holidayTimestampsCache) {
// Return timestamps directly for efficient lookup
return Array.from(this.holidayTimestampsCache).map((ts) => new Date(ts));
}
// 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);
const holidays = hd.getHolidays(currentYear, lang);
const holidaysPlusOne = hd.getHolidays(currentYear + 1, lang);
holidays.push(...holidaysPlusOne);
let holidaysDate: Date[] = holidays.map((holiday) => new Date(holiday.date));
const holidaysDate: Date[] = holidays.map((holiday) => new Date(holiday.date));
// Update cache
this.holidayTimestampsCache = new Set(holidaysDate.map((d) => d.getTime()));
this.holidayCacheYear = currentYear;
return holidaysDate;
}
@@ -137,14 +167,14 @@ export class CalendarService {
return months;
}
static monthsInAYearFromNow(): Year {
monthsInAYearFromNow(): Year {
const months: Year = [];
const currentMonthIndex = new Date().getMonth();
const currentYear = new Date().getFullYear();
const currentMonthIndex = this.dateCache.getCurrentMonth();
const currentYear = this.dateCache.getCurrentYear();
for (let i = 0; i < 12; i++) {
const monthIndex = (currentMonthIndex + i) % 12;
const year = currentYear + Math.floor((currentMonthIndex + i) / 12);
months.push(this.weeksInMonth(monthIndex, year));
months.push(CalendarService.weeksInMonth(monthIndex, year));
}
return months;
}
@@ -266,6 +296,9 @@ export class SelectedDates implements SelectedDateInterface {
private minDate: Date | null = null;
private maxDate: Date | null = null;
// Constant to indicate no valid strategy was found
private static readonly NO_VALID_STRATEGY_HEURISTIC = -1;
update(): void {
this.datesSelected = this._datesSelected.slice();
this.grouping();
@@ -449,7 +482,7 @@ export class SelectedDates implements SelectedDateInterface {
const current = sorted[i];
const next = sorted[i + 1];
// Get dates as UTC strings to remove timezone issues
// Get dates as UTC strings to remove timezone issues (handles DST properly)
const currentEndDate = new Date(current.range.end ?? new Date());
const nextStartDate = new Date(next.range.start ?? new Date());
@@ -486,7 +519,7 @@ export class SelectedDates implements SelectedDateInterface {
const daysInRange = selectedDate.getLengthInDays();
// For each day in the range, add it to the appropriate month
let currentDate = new Date(selectedDate.range.start);
const currentDate = new Date(selectedDate.range.start);
for (let i = 0; i < daysInRange; i++) {
const monthKey = currentDate.getFullYear() * 12 + currentDate.getMonth();
monthCounts.set(monthKey, (monthCounts.get(monthKey) ?? 0) + 1);
@@ -505,25 +538,26 @@ export class SelectedDates implements SelectedDateInterface {
optimizeVacations(
vacationsNumber: VacationsNumber,
calendarSettingsService: CalendarSettingsService,
calendarService: CalendarService,
): void {
if (calendarSettingsService.samediMalin()) this.samediMalin(vacationsNumber);
if (calendarSettingsService.get('samediMalin')()) this.samediMalin(vacationsNumber);
while (vacationsNumber.cp > 0) {
const result = this.lookForVacation(DayType.CP);
if (result.heuristic === -1) {
const result = this.lookForVacation(DayType.CP, calendarService);
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
vacationsNumber.cp -= 1;
}
while (vacationsNumber.rtt > 0) {
const result = this.lookForVacation(DayType.RTT);
if (result.heuristic === -1) {
const result = this.lookForVacation(DayType.RTT, calendarService);
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
vacationsNumber.rtt -= 1;
}
while (vacationsNumber.other > 0) {
const result = this.lookForVacation(DayType.OTHER);
if (result.heuristic === -1) {
const result = this.lookForVacation(DayType.OTHER, calendarService);
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
vacationsNumber.other -= 1;
@@ -533,8 +567,9 @@ export class SelectedDates implements SelectedDateInterface {
samediMalin(vacationsNumber: VacationsNumber): void {
const now = new Date();
now.setHours(0, 0, 0, 0);
const nowTime = now.getTime();
const samedi_ferie = this.datesSelected.filter(
const samedi_ferie = this._datesSelected.filter(
(date) => date.type === DayType.CLOSED_DAY && date.range.start?.getDay() === 6,
);
@@ -572,17 +607,17 @@ export class SelectedDates implements SelectedDateInterface {
// Check if we can apply each strategy (and not in the past)
const canApplyTwoBeforeStrategy =
twoDaysBefore1 >= now &&
twoDaysBefore1.getTime() >= nowTime &&
!this.isSelected(twoDaysBefore1) &&
!this.isSelected(twoDaysBefore2);
const canApplyTwoAfterStrategy =
twoDaysAfter1 >= now &&
twoDaysAfter1.getTime() >= nowTime &&
!this.isSelected(twoDaysAfter1) &&
!this.isSelected(twoDaysAfter2);
const canApplyMixedStrategy =
oneDayBefore >= now &&
oneDayBefore.getTime() >= nowTime &&
!this.isSelected(oneDayBefore) &&
!this.isSelected(oneDayAfter);
@@ -597,6 +632,7 @@ export class SelectedDates implements SelectedDateInterface {
new DateRange<Date>(twoDaysBefore1, twoDaysBefore2),
),
);
const heuristic = this.computeHeuristics();
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
@@ -609,7 +645,7 @@ export class SelectedDates implements SelectedDateInterface {
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics(),
heuristic: heuristic,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -620,6 +656,7 @@ export class SelectedDates implements SelectedDateInterface {
this.push(
new SelectedDate(DayType.CP, new DateRange<Date>(twoDaysAfter1, twoDaysAfter2)),
);
const heuristic = this.computeHeuristics();
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
@@ -632,7 +669,7 @@ export class SelectedDates implements SelectedDateInterface {
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics(),
heuristic: heuristic,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -646,6 +683,7 @@ export class SelectedDates implements SelectedDateInterface {
this.push(
new SelectedDate(DayType.CP, new DateRange<Date>(oneDayAfter, oneDayAfter)),
);
const heuristic = this.computeHeuristics();
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
@@ -664,7 +702,7 @@ export class SelectedDates implements SelectedDateInterface {
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics(),
heuristic: heuristic,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -681,65 +719,82 @@ export class SelectedDates implements SelectedDateInterface {
}
}
lookForVacation(vacType: DayType): { apply: () => void; heuristic: number } {
const daysOfYear = CalendarService.monthsInAYearFromNow();
lookForVacation(
vacType: DayType,
calendarService: CalendarService,
): { apply: () => void; heuristic: number } {
const daysOfYear = calendarService.monthsInAYearFromNow();
const now = new Date();
now.setHours(0, 0, 0, 0);
daysOfYear.forEach((month) => {
month.forEach((week) => {
week.forEach((day) => {
if (day) {
if (day) day.setHours(0, 0, 0, 0);
if (day && day < now) {
week[week.indexOf(day)] = null;
}
}
});
});
});
const tempDatesBackup = [...this._datesSelected];
let strategies: { apply: () => void; heuristic: number; value: Date }[] = [];
const nowTime = now.getTime();
// 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 && !this.isSelected(day)) {
if (day) {
day.setHours(0, 0, 0, 0);
if (day.getTime() >= nowTime && !this.isSelected(day)) {
candidateDays.push(day);
}
}
}
}
}
// Early exit if no candidates
if (candidateDays.length === 0) {
return { apply: () => {}, heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC };
}
const tempDatesBackup = [...this._datesSelected];
let bestStrategy: { apply: () => void; heuristic: number; value: Date } | null = null;
let bestHeuristic = -Infinity;
// Evaluate each candidate day
for (const day of candidateDays) {
// Reset to backup state
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
this.grouping();
// 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)),
);
strategies.push({
// Mark this day as vacation (reuse the day object since it's already normalized)
this.datesSelected.push(new SelectedDate(vacType, new DateRange<Date>(day, day)));
const heuristic = this.computeHeuristics();
// Track only if better than current best
if (heuristic > bestHeuristic) {
bestHeuristic = heuristic;
const capturedDay = day;
bestStrategy = {
apply: () => {
this._datesSelected = [...tempDatesBackup];
this.push(
new SelectedDate(
vacType,
new DateRange<Date>(startDay, endDay),
new DateRange<Date>(capturedDay, capturedDay),
),
);
},
heuristic: this.computeHeuristics(),
value: startDay,
});
heuristic: heuristic,
value: capturedDay,
};
}
}
// Restore backup before returning
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
this.grouping();
}
}
}
}
// Apply the strategy with the best heuristic score
if (strategies.length > 0) {
const bestStrategy = strategies.reduce((best, current) =>
current.heuristic > best.heuristic ? current : best,
);
// Apply best strategy if found
if (bestStrategy) {
bestStrategy.apply();
return bestStrategy;
}
return { apply: () => {}, heuristic: -1 };
return { apply: () => {}, heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC };
}
}
@@ -1,16 +1,45 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { CalendarSettingsService } from './calendar-settings-service';
describe('CalendarSettingsService', () => {
let service: CalendarSettingsService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
service = TestBed.inject(CalendarSettingsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should initialize with default values', () => {
expect(service.get('showWeekNumbers')()).toBe(false);
expect(service.get('samediMalin')()).toBe(true);
});
it('should allow updating showWeekNumbers', () => {
service.get('showWeekNumbers').set(true);
expect(service.get('showWeekNumbers')()).toBe(true);
});
it('should allow updating samediMalin', () => {
service.get('samediMalin').set(false);
expect(service.get('samediMalin')()).toBe(false);
});
it('should provide settings array for UI iteration', () => {
const settingsArray = service.settingsArray;
expect(settingsArray.length).toBe(2);
expect(settingsArray[0].id).toBe('showWeekNumbers');
expect(settingsArray[1].id).toBe('samediMalin');
});
it('should return correct descriptions', () => {
expect(service.getDescription('showWeekNumbers')).toBe('Afficher les numéros de semaine');
expect(service.getDescription('samediMalin')).toBe('Activer le Samedi Malin');
});
});
+62 -3
View File
@@ -1,9 +1,68 @@
import { Injectable, signal } from '@angular/core';
import { Injectable, WritableSignal, inject, Injector } from '@angular/core';
import { storedSignal } from '../shared/utils/stored-signal';
interface SettingDefinition {
defaultValue: boolean;
description: string;
}
@Injectable({
providedIn: 'root',
})
export class CalendarSettingsService {
readonly showWeekNumbers = signal(false);
readonly samediMalin = signal(true);
private readonly injector = inject(Injector);
private readonly definitions = new Map<string, SettingDefinition>([
[
'showWeekNumbers',
{
defaultValue: false,
description: 'Afficher les numéros de semaine',
},
],
[
'samediMalin',
{
defaultValue: true,
description: 'Activer le Samedi Malin',
},
],
]);
private readonly signals = new Map<string, WritableSignal<boolean>>();
readonly settingsArray: ReadonlyArray<{
id: string;
signal: WritableSignal<boolean>;
description: string;
}>;
constructor() {
for (const [id, def] of this.definitions) {
const storageKey = `calendarSettings.${id}`;
this.signals.set(id, storedSignal(storageKey, def.defaultValue, this.injector));
}
this.settingsArray = Array.from(this.definitions.entries()).map(([id, def]) => ({
id,
signal: this.signals.get(id)!,
description: def.description,
}));
}
/**
* Returns the signal for the given setting ID.
* @throws Error if the setting ID doesn't exist
*/
get(id: string): WritableSignal<boolean> {
const signal = this.signals.get(id);
if (!signal) {
throw new Error(`Setting with id "${id}" does not exist`);
}
return signal;
}
getDescription(id: string): string {
return this.definitions.get(id)?.description ?? '';
}
}
@@ -0,0 +1,63 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { DateCacheService } from './date-cache.service';
describe('DateCacheService', () => {
let service: DateCacheService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
service = TestBed.inject(DateCacheService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should cache today date', () => {
const today1 = service.getToday();
const today2 = service.getToday();
expect(today1).toBe(today2); // Same reference
});
it('should cache today components', () => {
const components1 = service.getTodayComponents();
const components2 = service.getTodayComponents();
expect(components1).toBe(components2); // Same reference
});
it('should cache current month', () => {
const month1 = service.getCurrentMonth();
const month2 = service.getCurrentMonth();
expect(month1).toBe(month2);
});
it('should cache current year', () => {
const year1 = service.getCurrentYear();
const year2 = service.getCurrentYear();
expect(year1).toBe(year2);
});
it('should clear cache', () => {
const year1 = service.getCurrentYear();
service.clearCache();
const year2 = service.getCurrentYear();
expect(year1).toBe(year2); // Values should be the same even after clearing
});
it('should return today with time normalized to 00:00:00.000', () => {
const today = service.getToday();
expect(today.getHours()).toBe(0);
expect(today.getMinutes()).toBe(0);
expect(today.getSeconds()).toBe(0);
expect(today.getMilliseconds()).toBe(0);
});
it('should return getNow() same as getToday()', () => {
const now = service.getNow();
const today = service.getToday();
expect(now).toBe(today);
});
});
+105
View File
@@ -0,0 +1,105 @@
import { Injectable } from '@angular/core';
/**
* Service to cache and provide commonly used date values.
* This reduces redundant Date object creation across the application.
*/
@Injectable({
providedIn: 'root',
})
export class DateCacheService {
private _today: Date | null = null;
private _todayComponents: { date: number; month: number; year: number } | null = null;
private _currentMonth: number | null = null;
private _currentYear: number | null = null;
/**
* Get today's date (time set to 00:00:00.000)
*/
getToday(): Date {
if (!this._today || this.isNewDay(this._today)) {
this._today = new Date();
this._today.setHours(0, 0, 0, 0);
this._todayComponents = null; // Invalidate components cache
}
return this._today;
}
/**
* Get today's date components (date, month, year) for efficient comparison
*/
getTodayComponents(): { date: number; month: number; year: number } {
if (!this._todayComponents || (this._today && this.isNewDay(this._today))) {
const today = this.getToday();
this._todayComponents = {
date: today.getDate(),
month: today.getMonth(),
year: today.getFullYear(),
};
}
return this._todayComponents;
}
/**
* Get current month (0-11)
*/
getCurrentMonth(): number {
if (this._currentMonth === null || this.isNewMonth()) {
this._currentMonth = new Date().getMonth();
}
return this._currentMonth;
}
/**
* Get current year
*/
getCurrentYear(): number {
if (this._currentYear === null || this.isNewYear()) {
this._currentYear = new Date().getFullYear();
}
return this._currentYear;
}
/**
* Get current date with time set to 00:00:00.000 (alias for getToday)
*/
getNow(): Date {
return this.getToday();
}
/**
* Check if a cached date is from a previous day
*/
private isNewDay(cachedDate: Date): boolean {
const now = new Date();
return (
cachedDate.getDate() !== now.getDate() ||
cachedDate.getMonth() !== now.getMonth() ||
cachedDate.getFullYear() !== now.getFullYear()
);
}
/**
* Check if we're in a new month
*/
private isNewMonth(): boolean {
return this._currentMonth !== null && this._currentMonth !== new Date().getMonth();
}
/**
* Check if we're in a new year
*/
private isNewYear(): boolean {
return this._currentYear !== null && this._currentYear !== new Date().getFullYear();
}
/**
* Clear all caches (useful for testing)
*/
clearCache(): void {
this._today = null;
this._todayComponents = null;
this._currentMonth = null;
this._currentYear = null;
}
}
+28 -2
View File
@@ -1,16 +1,42 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { ThemeService } from './theme-service';
describe('ThemeService', () => {
let service: ThemeService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
service = TestBed.inject(ThemeService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should initialize with system preference', () => {
expect(service.isLightMode()).toBeDefined();
});
it('should toggle theme', () => {
const initialMode = service.isLightMode();
service.toggleTheme();
expect(service.isLightMode()).toBe(!initialMode);
});
it('should force light mode when specified', () => {
service.toggleTheme(true);
expect(service.isLightMode()).toBe(true);
expect(document.body.classList.contains('light-mode')).toBe(true);
expect(document.body.classList.contains('dark-mode')).toBe(false);
});
it('should force dark mode when specified', () => {
service.toggleTheme(false);
expect(service.isLightMode()).toBe(false);
expect(document.body.classList.contains('light-mode')).toBe(false);
expect(document.body.classList.contains('dark-mode')).toBe(true);
});
});
+20 -2
View File
@@ -1,16 +1,34 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { UserInputService } from './user-input-service';
describe('UserInput', () => {
let service: UserInputService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
service = TestBed.inject(UserInputService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should initialize with random vacation numbers', () => {
const vacations = service.vacationNumberSignal();
expect(vacations.cp).toBeGreaterThanOrEqual(1);
expect(vacations.cp).toBeLessThanOrEqual(9);
expect(vacations.rtt).toBeGreaterThanOrEqual(1);
expect(vacations.rtt).toBeLessThanOrEqual(9);
expect(vacations.other).toBeGreaterThanOrEqual(1);
expect(vacations.other).toBeLessThanOrEqual(9);
});
it('should update vacation number signal', () => {
const newVacations = { cp: 5, rtt: 3, other: 2 };
service.vacationNumberSignal.set(newVacations);
expect(service.vacationNumberSignal()).toEqual(newVacations);
});
});
+1 -1
View File
@@ -1,4 +1,4 @@
import { Injectable, signal, PLATFORM_ID, inject } from '@angular/core';
import { Injectable, signal } from '@angular/core';
import { VacationsNumber } from './calendar-service';
@Injectable({
@@ -1,12 +1,14 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { UserSettingsService } from './user-settings-service';
describe('UserSettingsService', () => {
let service: UserSettingsService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
service = TestBed.inject(UserSettingsService);
});
+111
View File
@@ -0,0 +1,111 @@
import { signal, effect, WritableSignal, Injector, runInInjectionContext } from '@angular/core';
/**
* Checks if localStorage is available in the current environment.
* @returns true if localStorage is accessible, false otherwise
*/
function isLocalStorageAvailable(): boolean {
try {
return typeof localStorage !== 'undefined' && localStorage !== null;
} catch {
return false;
}
}
/**
* Creates a signal that automatically persists its value to localStorage.
*
* The signal will:
* - Initialize with the stored value from localStorage if available
* - Fall back to the provided initial value if no stored value exists or parsing fails
* - Automatically sync changes to localStorage with debouncing (300ms delay)
* - Work safely in SSR and environments where localStorage is unavailable
*
* @template T - The type of value stored in the signal (must be JSON-serializable)
* @param key - The localStorage key used to store the value
* @param initialValue - The default value used when no stored value exists
* @param injector - The Angular injector (use inject(Injector) to get current context)
* @param debounceMs - Optional debounce delay in milliseconds (default: 300ms)
* @returns A writable signal that persists to localStorage
*
* @example
* ```typescript
* const injector = inject(Injector);
* const darkMode = storedSignal('theme.darkMode', false, injector);
* darkMode.set(true); // Automatically saved to localStorage after 300ms
* console.log(darkMode()); // true
* ```
*
* @remarks
* - Requires an Injector to create the effect in the proper context
* - Values must be JSON-serializable (no functions, circular references, etc.)
* - In SSR or when localStorage is unavailable, the signal works normally but won't persist
* - Corrupted localStorage data is automatically cleared and reset to initial value
* - localStorage writes are debounced to improve performance with frequent updates
*/
export function storedSignal<T>(
key: string,
initialValue: T,
injector: Injector,
debounceMs = 300,
): WritableSignal<T> {
let parsedValue = initialValue;
if (isLocalStorageAvailable()) {
try {
const storedValue = localStorage.getItem(key);
if (storedValue) {
parsedValue = JSON.parse(storedValue) as T;
}
} catch (error) {
console.warn(
`Failed to parse stored value for key "${key}". Using initial value.`,
error,
);
try {
localStorage.removeItem(key);
} catch {
// Ignore removal errors
}
}
}
const s = signal(parsedValue);
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let isFirstRun = true;
runInInjectionContext(injector, () => {
effect(() => {
const value = s();
// Skip the first execution to avoid writing back what we just read
if (isFirstRun) {
isFirstRun = false;
return;
}
// Clear any pending timeout
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
// Debounce the localStorage write
timeoutId = setTimeout(() => {
if (isLocalStorageAvailable()) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.warn(
`Failed to save value for key "${key}" to localStorage.`,
error,
);
}
}
timeoutId = null;
}, debounceMs);
});
});
return s;
}
+9 -8
View File
@@ -1,18 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta charset="utf-8" />
<title>VacOptimizer</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap"
rel="stylesheet"
/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
</head>
<body>
<app-root></app-root>
</body>
</html>
+1 -2
View File
@@ -2,7 +2,6 @@ import { BootstrapContext, bootstrapApplication } from '@angular/platform-browse
import { App } from './app/app';
import { config } from './app/app.config.server';
const bootstrap = (context: BootstrapContext) =>
bootstrapApplication(App, config, context);
const bootstrap = (context: BootstrapContext) => bootstrapApplication(App, config, context);
export default bootstrap;
+1 -2
View File
@@ -2,5 +2,4 @@ import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig)
.catch((err) => console.error(err));
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
+1 -3
View File
@@ -41,9 +41,7 @@ app.use(
app.use((req, res, next) => {
angularApp
.handle(req)
.then((response) =>
response ? writeResponseToNodeResponse(response, res) : next(),
)
.then((response) => (response ? writeResponseToNodeResponse(response, res) : next()))
.catch(next);
});