Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8298dc88a3 | ||
|
|
6e571ec1b3 | ||
|
|
7eca27b629 | ||
|
|
9f9fe417c8 | ||
|
|
faea06f848 | ||
|
|
0c03df0039 | ||
|
|
f0c4ccb194 | ||
|
|
fc829ad0af | ||
|
|
b0266e31ea | ||
|
|
492cd3a34c | ||
|
|
96053b7f5d | ||
|
|
2013ac5256 | ||
|
|
9142cf56cf | ||
|
|
c05c08f994 | ||
|
|
0aab8e1bb9 | ||
|
|
7127744454 | ||
|
|
26d8bf5184 | ||
|
|
9ff7cb503a | ||
|
|
420dacf379 | ||
|
|
a213caaf92 | ||
|
|
cbdaa8991c | ||
|
|
2caab553aa | ||
|
|
7c1538ee66 | ||
|
|
1ff20d4fcd | ||
|
|
2435f3f01b | ||
|
|
6078b552dd | ||
|
|
d07375b10f | ||
|
|
5769d2e653 | ||
|
|
d6f5b7a7ed | ||
|
|
d70489b111 | ||
|
|
d80749489f | ||
|
|
8ce6582123 | ||
|
|
2b5468090a | ||
|
|
327255b466 | ||
|
|
d3515f89e5 | ||
|
|
3272622abf | ||
|
|
2d5cccff0c | ||
|
|
f30f862aac | ||
|
|
f3d3192aec | ||
|
|
97d7e520fc | ||
|
|
9eeab40755 | ||
|
|
a06b2077a0 | ||
|
|
a850869282 | ||
|
|
8b36565816 | ||
|
|
437d5fca9c | ||
|
|
b86121efac | ||
|
|
81d974cbfe | ||
|
|
1922b9acb2 | ||
|
|
729cc3f4cf | ||
|
|
f2b4d36709 | ||
|
|
104bdb273d | ||
|
|
000f37ec56 | ||
|
|
a2b5329716 | ||
|
|
cef670955a | ||
|
|
2027b412b3 | ||
|
|
6556dd7cf2 | ||
|
|
f7bd101fb7 |
No files matched your search
@@ -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
|
||||||
@@ -1,101 +1,41 @@
|
|||||||
# For most projects, this workflow file will not need changing; you simply need
|
name: CodeQL Security Analysis
|
||||||
# to commit it to your repository.
|
|
||||||
#
|
|
||||||
# You may wish to alter this file to override the set of languages analyzed,
|
|
||||||
# or to provide custom queries or build logic.
|
|
||||||
#
|
|
||||||
# ******** NOTE ********
|
|
||||||
# We have attempted to detect the languages in your repository. Please check
|
|
||||||
# the `language` matrix defined below to confirm you have the correct set of
|
|
||||||
# supported CodeQL languages.
|
|
||||||
#
|
|
||||||
name: "CodeQL Advanced"
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ "main" ]
|
branches: [main]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ "main" ]
|
branches: [main]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '27 7 * * 2'
|
- cron: '0 0 * * 1' # Run every Monday at midnight UTC
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
name: Analyze (${{ matrix.language }})
|
name: Analyze Code
|
||||||
# Runner size impacts CodeQL analysis time. To learn more, please see:
|
runs-on: ubuntu-latest
|
||||||
# - https://gh.io/recommended-hardware-resources-for-running-codeql
|
permissions:
|
||||||
# - https://gh.io/supported-runners-and-hardware-resources
|
security-events: write
|
||||||
# - https://gh.io/using-larger-runners (GitHub.com only)
|
actions: read
|
||||||
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
|
contents: read
|
||||||
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
|
|
||||||
permissions:
|
|
||||||
# required for all workflows
|
|
||||||
security-events: write
|
|
||||||
|
|
||||||
# required to fetch internal or private CodeQL packs
|
strategy:
|
||||||
packages: read
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: ['javascript-typescript']
|
||||||
|
|
||||||
# only required for workflows in private repositories
|
steps:
|
||||||
actions: read
|
- name: Checkout repository
|
||||||
contents: read
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
strategy:
|
- name: Initialize CodeQL
|
||||||
fail-fast: false
|
uses: github/codeql-action/init@v4
|
||||||
matrix:
|
with:
|
||||||
include:
|
languages: ${{ matrix.language }}
|
||||||
- language: actions
|
queries: security-extended,security-and-quality
|
||||||
build-mode: none
|
|
||||||
- language: javascript-typescript
|
|
||||||
build-mode: none
|
|
||||||
# CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
|
|
||||||
# Use `c-cpp` to analyze code written in C, C++ or both
|
|
||||||
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
|
|
||||||
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
|
|
||||||
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
|
|
||||||
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
|
|
||||||
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
|
|
||||||
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
# Add any setup steps before running the `github/codeql-action/init` action.
|
- name: Autobuild
|
||||||
# This includes steps like installing compilers or runtimes (`actions/setup-node`
|
uses: github/codeql-action/autobuild@v4
|
||||||
# or others). This is typically only required for manual builds.
|
|
||||||
# - name: Setup runtime (example)
|
|
||||||
# uses: actions/setup-example@v1
|
|
||||||
|
|
||||||
# Initializes the CodeQL tools for scanning.
|
- name: Perform CodeQL Analysis
|
||||||
- name: Initialize CodeQL
|
uses: github/codeql-action/analyze@v4
|
||||||
uses: github/codeql-action/init@v4
|
with:
|
||||||
with:
|
category: '/language:${{matrix.language}}'
|
||||||
languages: ${{ matrix.language }}
|
|
||||||
build-mode: ${{ matrix.build-mode }}
|
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
|
||||||
# By default, queries listed here will override any specified in a config file.
|
|
||||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
|
||||||
|
|
||||||
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
|
||||||
# queries: security-extended,security-and-quality
|
|
||||||
|
|
||||||
# If the analyze step fails for one of the languages you are analyzing with
|
|
||||||
# "We were unable to automatically build your code", modify the matrix above
|
|
||||||
# to set the build mode to "manual" for that language. Then modify this step
|
|
||||||
# to build your code.
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
|
||||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
|
||||||
- name: Run manual build steps
|
|
||||||
if: matrix.build-mode == 'manual'
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
echo 'If you are using a "manual" build mode for one or more of the' \
|
|
||||||
'languages you are analyzing, replace this with the commands to build' \
|
|
||||||
'your code, for example:'
|
|
||||||
echo ' make bootstrap'
|
|
||||||
echo ' make release'
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
|
||||||
uses: github/codeql-action/analyze@v4
|
|
||||||
with:
|
|
||||||
category: "/language:${{matrix.language}}"
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
name: Dependabot Auto-merge
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
auto-merge:
|
||||||
|
name: Auto-merge Dependabot minor and patch updates
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.actor == 'dependabot[bot]'
|
||||||
|
steps:
|
||||||
|
- name: Fetch Dependabot metadata
|
||||||
|
id: metadata
|
||||||
|
uses: dependabot/fetch-metadata@v2.5.0
|
||||||
|
|
||||||
|
- name: Auto-merge minor and patch updates
|
||||||
|
if: |
|
||||||
|
steps.metadata.outputs.update-type == 'version-update:semver-minor' ||
|
||||||
|
steps.metadata.outputs.update-type == 'version-update:semver-patch'
|
||||||
|
run: gh pr merge --auto --squash "$PR_URL"
|
||||||
|
env:
|
||||||
|
PR_URL: ${{ github.event.pull_request.html_url }}
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -5,6 +5,7 @@ on:
|
|||||||
branches: [main]
|
branches: [main]
|
||||||
release:
|
release:
|
||||||
types: [published]
|
types: [published]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-and-push:
|
build-and-push:
|
||||||
@@ -12,12 +13,16 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
packages: write
|
||||||
|
security-events: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
- name: Log in to GitHub Container Registry
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v4
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
@@ -33,11 +38,28 @@ jobs:
|
|||||||
type=semver,pattern={{version}}
|
type=semver,pattern={{version}}
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
type=sha
|
type=sha
|
||||||
|
type=raw,value=latest,enable={{is_default_branch}}
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@v5
|
id: build
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
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.34.2
|
||||||
|
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@v4
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
sarif_file: 'trivy-results.sarif'
|
||||||
@@ -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@v6
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci --legacy-peer-deps
|
||||||
|
|
||||||
|
- 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@v6
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci --legacy-peer-deps
|
||||||
|
|
||||||
|
- name: Run TypeScript compiler
|
||||||
|
run: npx tsc --noEmit
|
||||||
|
|
||||||
|
test:
|
||||||
|
name: Unit Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci --legacy-peer-deps
|
||||||
|
|
||||||
|
- name: Run unit tests
|
||||||
|
run: npm test -- --watch=false --browsers=ChromeHeadless --code-coverage
|
||||||
|
|
||||||
|
- name: Upload coverage reports
|
||||||
|
uses: codecov/codecov-action@v5
|
||||||
|
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@v6
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci --legacy-peer-deps
|
||||||
|
|
||||||
|
- 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@v6
|
||||||
|
with:
|
||||||
|
name: build-artifacts
|
||||||
|
path: dist/
|
||||||
|
retention-days: 7
|
||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
# Stage 1: Build the Angular application
|
# Stage 1: Build the Angular application
|
||||||
FROM node:20-alpine AS builder
|
FROM node:25-alpine AS builder
|
||||||
|
|
||||||
# Set working directory
|
# Set working directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
@@ -17,7 +17,7 @@ COPY . .
|
|||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# Stage 2: Production image
|
# Stage 2: Production image
|
||||||
FROM node:20-alpine AS production
|
FROM node:25-alpine AS production
|
||||||
|
|
||||||
# Set working directory
|
# Set working directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -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.
|
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
|
## Code scaffolding
|
||||||
|
|
||||||
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
|
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.
|
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
|
## 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.
|
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
@@ -52,7 +52,10 @@
|
|||||||
"maximumError": "16kB"
|
"maximumError": "16kB"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"outputHashing": "all"
|
"outputHashing": "all",
|
||||||
|
"optimization": {
|
||||||
|
"fonts": false
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"development": {
|
"development": {
|
||||||
"optimization": false,
|
"optimization": false,
|
||||||
|
|||||||
@@ -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/**'],
|
||||||
|
},
|
||||||
|
];
|
||||||
Generated
+2748
-2583
File diff suppressed because it is too large.
Load diff
+37
-30
@@ -7,7 +7,11 @@
|
|||||||
"build": "ng build",
|
"build": "ng build",
|
||||||
"watch": "ng build --watch --configuration development",
|
"watch": "ng build --watch --configuration development",
|
||||||
"test": "ng test",
|
"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": {
|
"prettier": {
|
||||||
"printWidth": 100,
|
"printWidth": 100,
|
||||||
@@ -23,42 +27,45 @@
|
|||||||
},
|
},
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular/cdk": "^20.2.10",
|
"@angular/animations": "21.2.0",
|
||||||
"@angular/common": "^20.3.0",
|
"@angular/cdk": "^21.2.0",
|
||||||
"@angular/compiler": "^20.3.0",
|
"@angular/common": "21.2.0",
|
||||||
"@angular/core": "^20.3.7",
|
"@angular/compiler": "21.2.0",
|
||||||
"@angular/forms": "^20.3.0",
|
"@angular/core": "21.2.0",
|
||||||
"@angular/material": "^20.2.10",
|
"@angular/forms": "21.2.0",
|
||||||
"@angular/platform-browser": "^20.3.0",
|
"@angular/material": "^21.2.0",
|
||||||
"@angular/platform-server": "^20.3.0",
|
"@angular/platform-browser": "21.2.0",
|
||||||
"@angular/router": "^20.3.0",
|
"@angular/platform-server": "21.2.0",
|
||||||
"@angular/ssr": "^20.3.7",
|
"@angular/router": "21.2.0",
|
||||||
"date-holidays": "^3.26.2",
|
"@angular/ssr": "21.2.0",
|
||||||
|
"date-holidays": "^3.26.8",
|
||||||
"dayjs": "^1.11.19",
|
"dayjs": "^1.11.19",
|
||||||
"express": "^5.1.0",
|
"express": "^5.2.1",
|
||||||
"rxjs": "~7.8.0",
|
"rxjs": "~7.8.2",
|
||||||
"tslib": "^2.3.0"
|
"tslib": "^2.8.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@angular/build": "^20.3.7",
|
"@angular/build": "21.2.0",
|
||||||
"@angular/cli": "^20.3.7",
|
"@angular/cli": "21.2.0",
|
||||||
"@angular/compiler-cli": "^20.3.0",
|
"@angular/compiler-cli": "21.2.0",
|
||||||
"@types/express": "^5.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"@types/jasmine": "~5.1.0",
|
"@types/express": "^5.0.6",
|
||||||
|
"@types/jasmine": "~6.0.0",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^20.17.19",
|
"@types/node": "^25.3.3",
|
||||||
"eslint": "^9.38.0",
|
"eslint": "^10.0.2",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-prettier": "^5.5.4",
|
"eslint-plugin-prettier": "^5.5.5",
|
||||||
"jasmine-core": "~5.9.0",
|
"jasmine-core": "~6.1.0",
|
||||||
"jest": "^30.2.0",
|
"jest": "^30.2.0",
|
||||||
"jest-preset-angular": "^15.0.3",
|
"jest-preset-angular": "^16.1.1",
|
||||||
"karma": "~6.4.0",
|
"karma": "~6.4.4",
|
||||||
"karma-chrome-launcher": "~3.2.0",
|
"karma-chrome-launcher": "~3.2.0",
|
||||||
"karma-coverage": "~2.2.0",
|
"karma-coverage": "~2.2.1",
|
||||||
"karma-jasmine": "~5.1.0",
|
"karma-jasmine": "~5.1.0",
|
||||||
"karma-jasmine-html-reporter": "~2.1.0",
|
"karma-jasmine-html-reporter": "~2.2.0",
|
||||||
"prettier": "^3.6.2",
|
"prettier": "^3.8.1",
|
||||||
"typescript": "~5.9.2"
|
"typescript": "~5.9.3",
|
||||||
|
"typescript-eslint": "^8.56.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,9 +4,7 @@ import { appConfig } from './app.config';
|
|||||||
import { serverRoutes } from './app.routes.server';
|
import { serverRoutes } from './app.routes.server';
|
||||||
|
|
||||||
const serverConfig: ApplicationConfig = {
|
const serverConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [provideServerRendering(withRoutes(serverRoutes))],
|
||||||
provideServerRendering(withRoutes(serverRoutes))
|
|
||||||
]
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const config = mergeApplicationConfig(appConfig, serverConfig);
|
export const config = mergeApplicationConfig(appConfig, serverConfig);
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
withEventReplay,
|
withEventReplay,
|
||||||
withIncrementalHydration,
|
withIncrementalHydration,
|
||||||
} from '@angular/platform-browser';
|
} from '@angular/platform-browser';
|
||||||
|
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
@@ -18,5 +19,6 @@ export const appConfig: ApplicationConfig = {
|
|||||||
provideZonelessChangeDetection(),
|
provideZonelessChangeDetection(),
|
||||||
provideRouter(routes),
|
provideRouter(routes),
|
||||||
provideClientHydration(withEventReplay(), withIncrementalHydration()),
|
provideClientHydration(withEventReplay(), withIncrementalHydration()),
|
||||||
|
provideAnimationsAsync(),
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -3,6 +3,6 @@ import { RenderMode, ServerRoute } from '@angular/ssr';
|
|||||||
export const serverRoutes: ServerRoute[] = [
|
export const serverRoutes: ServerRoute[] = [
|
||||||
{
|
{
|
||||||
path: '**',
|
path: '**',
|
||||||
renderMode: RenderMode.Client
|
renderMode: RenderMode.Client,
|
||||||
}
|
},
|
||||||
];
|
];
|
||||||
+1
-1
@@ -6,7 +6,7 @@ describe('App', () => {
|
|||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [App],
|
imports: [App],
|
||||||
providers: [provideZonelessChangeDetection()]
|
providers: [provideZonelessChangeDetection()],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -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 { MatDatepickerModule } from '@angular/material/datepicker';
|
||||||
import { provideNativeDateAdapter } from '@angular/material/core';
|
import { provideNativeDateAdapter } from '@angular/material/core';
|
||||||
import { MatDivider } from '@angular/material/divider';
|
import { MatDivider } from '@angular/material/divider';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<h3>{{ getMonthName() }} {{ year }}</h3>
|
<h3>{{ getMonthName() }} {{ year }}</h3>
|
||||||
<div>
|
<div>
|
||||||
<div class="row header">
|
<div class="row header">
|
||||||
@if (calendarSettingsService.showWeekNumbers()) {
|
@if (calendarSettingsService.get('showWeekNumbers')()) {
|
||||||
<p class="day empty week-number"></p>
|
<p class="day empty week-number"></p>
|
||||||
}
|
}
|
||||||
<p class="day">L</p>
|
<p class="day">L</p>
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
<div class="cols">
|
<div class="cols">
|
||||||
@for (week of weeksInAMonth; track $index) {
|
@for (week of weeksInAMonth; track $index) {
|
||||||
<div class="row week">
|
<div class="row week">
|
||||||
@if (calendarSettingsService.showWeekNumbers()) {
|
@if (calendarSettingsService.get('showWeekNumbers')()) {
|
||||||
<p
|
<p
|
||||||
class="day week-number"
|
class="day week-number"
|
||||||
[class.start]="$index === 0"
|
[class.start]="$index === 0"
|
||||||
@@ -38,7 +38,6 @@
|
|||||||
class="day number"
|
class="day number"
|
||||||
[matTooltip]="selectedDates.getTooltip(day)"
|
[matTooltip]="selectedDates.getTooltip(day)"
|
||||||
[matTooltipShowDelay]="500"
|
[matTooltipShowDelay]="500"
|
||||||
[matTooltipTouchGestures]="'on'"
|
|
||||||
>
|
>
|
||||||
{{ day.getDate() }}
|
{{ day.getDate() }}
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -3,22 +3,21 @@ import { provideZonelessChangeDetection } from '@angular/core';
|
|||||||
import { CalendarMonth } from './calendar-month';
|
import { CalendarMonth } from './calendar-month';
|
||||||
|
|
||||||
describe('CalendarMonth', () => {
|
describe('CalendarMonth', () => {
|
||||||
let component: CalendarMonth;
|
let component: CalendarMonth;
|
||||||
let fixture: ComponentFixture<CalendarMonth>;
|
let fixture: ComponentFixture<CalendarMonth>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [CalendarMonth],
|
imports: [CalendarMonth],
|
||||||
providers: [provideZonelessChangeDetection()]
|
providers: [provideZonelessChangeDetection()],
|
||||||
})
|
}).compileComponents();
|
||||||
.compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(CalendarMonth);
|
fixture = TestBed.createComponent(CalendarMonth);
|
||||||
component = fixture.componentInstance;
|
component = fixture.componentInstance;
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create', () => {
|
it('should create', () => {
|
||||||
expect(component).toBeTruthy();
|
expect(component).toBeTruthy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -3,22 +3,21 @@ import { provideZonelessChangeDetection } from '@angular/core';
|
|||||||
import { CalendarSettings } from './calendar-settings';
|
import { CalendarSettings } from './calendar-settings';
|
||||||
|
|
||||||
describe('CalendarSettings', () => {
|
describe('CalendarSettings', () => {
|
||||||
let component: CalendarSettings;
|
let component: CalendarSettings;
|
||||||
let fixture: ComponentFixture<CalendarSettings>;
|
let fixture: ComponentFixture<CalendarSettings>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [CalendarSettings],
|
imports: [CalendarSettings],
|
||||||
providers: [provideZonelessChangeDetection()]
|
providers: [provideZonelessChangeDetection()],
|
||||||
})
|
}).compileComponents();
|
||||||
.compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(CalendarSettings);
|
fixture = TestBed.createComponent(CalendarSettings);
|
||||||
component = fixture.componentInstance;
|
component = fixture.componentInstance;
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create', () => {
|
it('should create', () => {
|
||||||
expect(component).toBeTruthy();
|
expect(component).toBeTruthy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Component } from '@angular/core';
|
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 { 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 { CalendarSettingsDialog } from '../dialog/calendar-settings-dialog/calendar-settings-dialog';
|
||||||
import { MatDividerModule } from '@angular/material/divider';
|
import { MatDividerModule } from '@angular/material/divider';
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,24 @@
|
|||||||
<div class="calendar-year">
|
<div class="calendar-year">
|
||||||
@if (isLoading()) {
|
@if (isLoading()) {
|
||||||
<div class="loading-overlay">
|
<div class="loading-overlay">
|
||||||
<div class="loading-spinner">
|
<div class="loading-spinner">
|
||||||
<mat-spinner></mat-spinner>
|
<div class="spinner-container">
|
||||||
<p>Calcul en cours...</p>
|
<mat-spinner [mode]="'determinate'" [value]="loadingProgress()"></mat-spinner>
|
||||||
|
<div class="spinner-text">{{ loadingProgress() }}%</div>
|
||||||
|
</div>
|
||||||
|
<p>Calcul en cours...</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
@for (month of months; track $index) {
|
@for (month of months; track $index) {
|
||||||
<mat-card class="card">
|
<mat-card class="card">
|
||||||
<mat-card-content>
|
<mat-card-content>
|
||||||
<app-calendar-month [monthIndex]="month" [year]="getYear(month)" [selectedDates]="selectedDates"></app-calendar-month>
|
<app-calendar-month
|
||||||
</mat-card-content>
|
[monthIndex]="month"
|
||||||
</mat-card>
|
[year]="getYear(month)"
|
||||||
|
[selectedDates]="selectedDates"
|
||||||
|
></app-calendar-month>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
@@ -51,20 +51,32 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.spinner-container {
|
||||||
|
position: relative;
|
||||||
|
display: inline-block;
|
||||||
|
|
||||||
|
::ng-deep .mat-mdc-progress-spinner {
|
||||||
|
// Override Material spinner size
|
||||||
|
width: 100px;
|
||||||
|
height: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner-text {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
left: 50%;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #333;
|
||||||
|
pointer-events: none;
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
color: #ddd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.card {
|
.card {
|
||||||
margin: 16px;
|
margin: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes spin {
|
|
||||||
0% {
|
|
||||||
transform: rotate(0deg);
|
|
||||||
}
|
|
||||||
|
|
||||||
100% {
|
|
||||||
transform: rotate(360deg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
:root {
|
|
||||||
@include mat.progress-spinner-overrides((size: 0.5rem, active-indicator-width: 0.25rem));
|
|
||||||
}
|
|
||||||
@@ -3,22 +3,21 @@ import { provideZonelessChangeDetection } from '@angular/core';
|
|||||||
import { CalendarYear } from './calendar-year';
|
import { CalendarYear } from './calendar-year';
|
||||||
|
|
||||||
describe('CalendarYear', () => {
|
describe('CalendarYear', () => {
|
||||||
let component: CalendarYear;
|
let component: CalendarYear;
|
||||||
let fixture: ComponentFixture<CalendarYear>;
|
let fixture: ComponentFixture<CalendarYear>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [CalendarYear],
|
imports: [CalendarYear],
|
||||||
providers: [provideZonelessChangeDetection()]
|
providers: [provideZonelessChangeDetection()],
|
||||||
})
|
}).compileComponents();
|
||||||
.compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(CalendarYear);
|
fixture = TestBed.createComponent(CalendarYear);
|
||||||
component = fixture.componentInstance;
|
component = fixture.componentInstance;
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create', () => {
|
it('should create', () => {
|
||||||
expect(component).toBeTruthy();
|
expect(component).toBeTruthy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,16 +1,16 @@
|
|||||||
import { Component, effect, signal, inject } from '@angular/core';
|
import { Component, effect, signal, inject, untracked } from '@angular/core';
|
||||||
import { UserInputService } from '../../services/user-input-service';
|
import { UserInputService } from '../../services/user-input-service';
|
||||||
import { MatCard, MatCardContent } from '@angular/material/card';
|
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 { CalendarService, SelectedDates } from '../../services/calendar-service';
|
||||||
import { CommonModule } from '@angular/common';
|
|
||||||
import { MatProgressSpinner } from '@angular/material/progress-spinner';
|
import { MatProgressSpinner } from '@angular/material/progress-spinner';
|
||||||
import { CalendarSettingsService } from '../../services/calendar-settings-service';
|
import { CalendarSettingsService } from '../../services/calendar-settings-service';
|
||||||
import { DateCacheService } from '../../services/date-cache.service';
|
import { DateCacheService } from '../../services/date-cache.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-calendar-year',
|
selector: 'app-calendar-year',
|
||||||
imports: [MatCard, CalendarMonth, MatCardContent, CommonModule, MatProgressSpinner],
|
imports: [MatCard, CalendarMonth, MatCardContent, MatProgressSpinner],
|
||||||
templateUrl: './calendar-year.html',
|
templateUrl: './calendar-year.html',
|
||||||
styleUrl: './calendar-year.scss',
|
styleUrl: './calendar-year.scss',
|
||||||
})
|
})
|
||||||
@@ -21,6 +21,7 @@ export class CalendarYear {
|
|||||||
private calendarSettingsService = inject(CalendarSettingsService);
|
private calendarSettingsService = inject(CalendarSettingsService);
|
||||||
|
|
||||||
protected isLoading = signal(true);
|
protected isLoading = signal(true);
|
||||||
|
protected loadingProgress = signal(0);
|
||||||
|
|
||||||
// Use DateCacheService instead of creating Date objects
|
// Use DateCacheService instead of creating Date objects
|
||||||
private get currentMonth() {
|
private get currentMonth() {
|
||||||
@@ -33,24 +34,35 @@ export class CalendarYear {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
|
this.userInput.computeTriggerSignal();
|
||||||
|
|
||||||
this.selectedDates = this.calendarService.getSelectedDatesForYear();
|
this.selectedDates = this.calendarService.getSelectedDatesForYear();
|
||||||
const vacationData = this.userInput.vacationNumberSignal();
|
const vacationData = untracked(() => this.userInput.vacationNumberSignal());
|
||||||
const c = this.calendarSettingsService.samediMalin();
|
const c = untracked(() => this.calendarSettingsService.get('samediMalin')());
|
||||||
console.log('Samedi Malin setting:', c);
|
console.log('Samedi Malin setting:', c);
|
||||||
console.log('Optimizing vacations with data:', vacationData);
|
console.log('Optimizing vacations with data:', vacationData);
|
||||||
this.isLoading.set(true);
|
this.isLoading.set(true);
|
||||||
// Simulate server-side calculation with a small delay
|
this.loadingProgress.set(0);
|
||||||
setTimeout(() => {
|
// Defer execution to allow UI to update
|
||||||
if (this.selectedDates) {
|
queueMicrotask(() => {
|
||||||
// Create a copy to avoid mutating the original signal data
|
void (async () => {
|
||||||
this.selectedDates.optimizeVacations(
|
if (this.selectedDates) {
|
||||||
{ ...vacationData },
|
// Create a deep copy to avoid mutating the original signal data
|
||||||
this.calendarSettingsService,
|
const vacationDaysCopy = vacationData.map((vd) => ({ ...vd }));
|
||||||
this.calendarService,
|
const remainingDays = await this.selectedDates.optimizeVacations(
|
||||||
);
|
vacationDaysCopy,
|
||||||
}
|
this.calendarSettingsService,
|
||||||
this.isLoading.set(false);
|
this.calendarService,
|
||||||
}, 1);
|
(progress: number) => {
|
||||||
|
this.loadingProgress.set(progress);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// Update the remaining vacation days signal
|
||||||
|
this.userInput.remainingVacationDaysSignal.set(remainingDays);
|
||||||
|
}
|
||||||
|
this.isLoading.set(false);
|
||||||
|
})();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,26 +4,18 @@
|
|||||||
<p>Configure your calendar settings here.</p>
|
<p>Configure your calendar settings here.</p>
|
||||||
</div>
|
</div>
|
||||||
<div style="display: flex; flex-direction: column; gap: 1rem">
|
<div style="display: flex; flex-direction: column; gap: 1rem">
|
||||||
<div style="align-self: flex-start">
|
@for (setting of calendarSettingsService.settingsArray; track setting.id) {
|
||||||
<mat-slide-toggle
|
<div style="align-self: flex-start">
|
||||||
id="showWeekNumbers"
|
<mat-slide-toggle
|
||||||
name="showWeekNumbers"
|
[id]="setting.id"
|
||||||
[checked]="calendarSettingsService.showWeekNumbers()"
|
[name]="setting.id"
|
||||||
(change)="calendarSettingsService.showWeekNumbers.set($event.checked)"
|
[checked]="setting.signal()"
|
||||||
>
|
(change)="setting.signal.set($event.checked)"
|
||||||
Afficher les numéros de semaine
|
>
|
||||||
</mat-slide-toggle>
|
{{ setting.description }}
|
||||||
</div>
|
</mat-slide-toggle>
|
||||||
<div style="align-self: flex-start">
|
</div>
|
||||||
<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>
|
</div>
|
||||||
<button mat-button (click)="closeDialog()">Fermer</button>
|
<button mat-button (click)="closeDialog()">Fermer</button>
|
||||||
</div>
|
</div>
|
||||||
+29
-30
@@ -4,39 +4,38 @@ import { MatDialogRef } from '@angular/material/dialog';
|
|||||||
import { CalendarSettingsDialog } from './calendar-settings-dialog';
|
import { CalendarSettingsDialog } from './calendar-settings-dialog';
|
||||||
|
|
||||||
describe('CalendarSettingsDialog', () => {
|
describe('CalendarSettingsDialog', () => {
|
||||||
let component: CalendarSettingsDialog;
|
let component: CalendarSettingsDialog;
|
||||||
let fixture: ComponentFixture<CalendarSettingsDialog>;
|
let fixture: ComponentFixture<CalendarSettingsDialog>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [CalendarSettingsDialog],
|
imports: [CalendarSettingsDialog],
|
||||||
providers: [
|
providers: [
|
||||||
provideZonelessChangeDetection(),
|
provideZonelessChangeDetection(),
|
||||||
{
|
{
|
||||||
provide: MatDialogRef,
|
provide: MatDialogRef,
|
||||||
useValue: {
|
useValue: {
|
||||||
close: jasmine.createSpy('close')
|
close: jasmine.createSpy('close'),
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
})
|
}).compileComponents();
|
||||||
.compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(CalendarSettingsDialog);
|
fixture = TestBed.createComponent(CalendarSettingsDialog);
|
||||||
component = fixture.componentInstance;
|
component = fixture.componentInstance;
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create', () => {
|
it('should create', () => {
|
||||||
expect(component).toBeTruthy();
|
expect(component).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should have calendar settings service', () => {
|
it('should have calendar settings service', () => {
|
||||||
expect(component['calendarSettingsService']).toBeDefined();
|
expect(component['calendarSettingsService']).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should close dialog when closeDialog is called', () => {
|
it('should close dialog when closeDialog is called', () => {
|
||||||
component.closeDialog();
|
component.closeDialog();
|
||||||
expect(component.dialogRef.close).toHaveBeenCalled();
|
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 { MatButton } from '@angular/material/button';
|
||||||
import { MatCheckbox } from '@angular/material/checkbox';
|
|
||||||
import { MatDialogRef } from '@angular/material/dialog';
|
import { MatDialogRef } from '@angular/material/dialog';
|
||||||
import { CalendarSettingsService } from '../../../services/calendar-settings-service';
|
import { CalendarSettingsService } from '../../../services/calendar-settings-service';
|
||||||
import { MatSlideToggle } from '@angular/material/slide-toggle';
|
import { MatSlideToggle } from '@angular/material/slide-toggle';
|
||||||
import { CdkFixedSizeVirtualScroll } from '@angular/cdk/scrolling';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-calendar-settings-dialog',
|
selector: 'app-calendar-settings-dialog',
|
||||||
@@ -13,10 +11,8 @@ import { CdkFixedSizeVirtualScroll } from '@angular/cdk/scrolling';
|
|||||||
styleUrl: './calendar-settings-dialog.scss',
|
styleUrl: './calendar-settings-dialog.scss',
|
||||||
})
|
})
|
||||||
export class CalendarSettingsDialog {
|
export class CalendarSettingsDialog {
|
||||||
constructor(
|
public readonly dialogRef = inject<MatDialogRef<CalendarSettingsDialog>>(MatDialogRef);
|
||||||
public dialogRef: MatDialogRef<CalendarSettingsDialog>,
|
protected readonly calendarSettingsService = inject(CalendarSettingsService);
|
||||||
protected calendarSettingsService: CalendarSettingsService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
closeDialog() {
|
closeDialog() {
|
||||||
this.dialogRef.close();
|
this.dialogRef.close();
|
||||||
|
|||||||
@@ -1,18 +1,44 @@
|
|||||||
<div class="user-input">
|
<div class="user-input">
|
||||||
<p>Optimisez vos jours de vacances en fonction des jours fériés et des week-ends !</p>
|
<p>Optimisez vos jours de vacances en fonction des jours fériés et des week-ends !</p>
|
||||||
<form [formGroup]="userInputForm">
|
<div class="listOfDays">
|
||||||
<mat-form-field appearance="fill">
|
@for (day of daysOff; track day.id) {
|
||||||
<mat-label>Combien de CP par an ?</mat-label>
|
<div class="day-input-wrapper" animate.enter="day-enter" animate.leave="day-leave">
|
||||||
<input matInput type="number" max="365" min="0" formControlName="CP" />
|
<app-day-input
|
||||||
</mat-form-field>
|
[day]="day"
|
||||||
<mat-form-field appearance="fill">
|
(dayChange)="updateDay($index, $event)"
|
||||||
<mat-label>Combien de jours de RTT par an ?</mat-label>
|
(deleteEntry)="removeFromList($index)"
|
||||||
<input matInput type="number" max="365" min="0" formControlName="RTT" />
|
></app-day-input>
|
||||||
</mat-form-field>
|
</div>
|
||||||
<mat-form-field appearance="fill">
|
}
|
||||||
<mat-label>Autres jours</mat-label>
|
<mat-card class="add-day-card mat-elevation-z2" (click)="addDay()">
|
||||||
<input matInput type="number" max="365" min="0" formControlName="Others" />
|
<button matFab aria-label="Add entry">
|
||||||
</mat-form-field>
|
<mat-icon>add</mat-icon>
|
||||||
</form>
|
</button>
|
||||||
<app-calendar-settings></app-calendar-settings>
|
<h3>Ajouter un jour de vacances</h3>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
<div class="action-buttons">
|
||||||
|
<button matFab extended (click)="triggerComputation()">
|
||||||
|
<mat-icon>calculate</mat-icon>
|
||||||
|
Calculer
|
||||||
|
</button>
|
||||||
|
<app-calendar-settings></app-calendar-settings>
|
||||||
|
</div>
|
||||||
|
@if (hasRemainingDays()) {
|
||||||
|
<mat-card class="mat-elevation-z2 warning-card">
|
||||||
|
<mat-card-content class="warning-content">
|
||||||
|
<mat-icon color="warn">warning</mat-icon>
|
||||||
|
<div class="warning">
|
||||||
|
<span>
|
||||||
|
{{ remainingDays() }} jour{{ remainingDays() > 1 ? 's' : '' }} de vacances
|
||||||
|
non placé{{ remainingDays() > 1 ? 's' : '' }}:
|
||||||
|
</span>
|
||||||
|
@for (day of remainingDaysDetails(); track $index) {
|
||||||
|
<span class="remaining-day-detail">- {{ day }}</span>
|
||||||
|
}
|
||||||
|
<span> Veuillez les placer manuellement. </span>
|
||||||
|
</div>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
@@ -13,9 +13,91 @@
|
|||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
margin-top: 0.25rem;
|
margin-top: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.warning-card {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.warning-content {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.listOfDays {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.day-input-wrapper {
|
||||||
|
animation: slide-fade-in 200ms ease-out;
|
||||||
|
|
||||||
|
@starting-style {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(-20px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.day-enter {
|
||||||
|
animation: slide-fade-in 200ms ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.day-leave {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(20px);
|
||||||
|
transition:
|
||||||
|
opacity 200ms ease-in,
|
||||||
|
transform 200ms ease-in;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes slide-fade-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(-20px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateX(0);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
form {
|
form {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.add-day-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
padding: 16px;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-day-card h3 {
|
||||||
|
flex-grow: 1;
|
||||||
|
margin: 0;
|
||||||
|
font-weight: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.action-buttons {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.warning {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
@@ -1,41 +1,46 @@
|
|||||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
import { provideZonelessChangeDetection } from '@angular/core';
|
import { provideZonelessChangeDetection } from '@angular/core';
|
||||||
import { UserInput } from './user-input';
|
import { UserInput } from './user-input';
|
||||||
|
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
|
||||||
|
import { UserInputService } from '../../services/user-input-service';
|
||||||
|
|
||||||
describe('UserInput', () => {
|
describe('UserInput', () => {
|
||||||
let component: UserInput;
|
let component: UserInput;
|
||||||
let fixture: ComponentFixture<UserInput>;
|
let fixture: ComponentFixture<UserInput>;
|
||||||
|
let userInputService: UserInputService;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [UserInput],
|
imports: [UserInput],
|
||||||
providers: [provideZonelessChangeDetection()]
|
providers: [provideZonelessChangeDetection(), provideAnimationsAsync()],
|
||||||
})
|
}).compileComponents();
|
||||||
.compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(UserInput);
|
fixture = TestBed.createComponent(UserInput);
|
||||||
component = fixture.componentInstance;
|
component = fixture.componentInstance;
|
||||||
fixture.detectChanges();
|
userInputService = TestBed.inject(UserInputService);
|
||||||
});
|
fixture.detectChanges();
|
||||||
|
});
|
||||||
|
|
||||||
it('should create', () => {
|
it('should create', () => {
|
||||||
expect(component).toBeTruthy();
|
expect(component).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should initialize form with values from service', () => {
|
it('should initialize with vacation days from service', () => {
|
||||||
expect(component.userInputForm).toBeDefined();
|
const vacationDays = userInputService.vacationNumberSignal();
|
||||||
expect(component.userInputForm.get('CP')).toBeDefined();
|
expect(vacationDays).toBeDefined();
|
||||||
expect(component.userInputForm.get('RTT')).toBeDefined();
|
expect(Array.isArray(vacationDays)).toBe(true);
|
||||||
expect(component.userInputForm.get('Others')).toBeDefined();
|
expect(vacationDays.length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should have valid form controls', () => {
|
it('should add a new vacation day', () => {
|
||||||
const cpControl = component.userInputForm.get('CP');
|
const initialLength = userInputService.vacationNumberSignal().length;
|
||||||
const rttControl = component.userInputForm.get('RTT');
|
component.addDay();
|
||||||
const othersControl = component.userInputForm.get('Others');
|
expect(userInputService.vacationNumberSignal().length).toBe(initialLength + 1);
|
||||||
|
});
|
||||||
|
|
||||||
expect(cpControl).toBeTruthy();
|
it('should remove a vacation day', () => {
|
||||||
expect(rttControl).toBeTruthy();
|
const initialLength = userInputService.vacationNumberSignal().length;
|
||||||
expect(othersControl).toBeTruthy();
|
component.removeFromList(0);
|
||||||
});
|
expect(userInputService.vacationNumberSignal().length).toBe(initialLength - 1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,68 +1,77 @@
|
|||||||
import { Component, OnInit, OnDestroy, effect } from '@angular/core';
|
import { Component, computed, inject, ChangeDetectionStrategy } from '@angular/core';
|
||||||
import { MatFormField, MatLabel } from '@angular/material/form-field';
|
|
||||||
import { MatInputModule } from '@angular/material/input';
|
import { MatInputModule } from '@angular/material/input';
|
||||||
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
|
||||||
import { UserInputService } from '../../services/user-input-service';
|
import { UserInputService } from '../../services/user-input-service';
|
||||||
import { VacationsNumber } from '../../services/calendar-service';
|
|
||||||
import { debounceTime, takeUntil, Subject } from 'rxjs';
|
|
||||||
import { CalendarSettings } from '../calendar-settings/calendar-settings';
|
import { CalendarSettings } from '../calendar-settings/calendar-settings';
|
||||||
|
import { MatCard, MatCardContent } from '@angular/material/card';
|
||||||
|
import { MatIcon } from '@angular/material/icon';
|
||||||
|
import { DayInput } from '../userInput/day-input/day-input';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { tooltipTypeMapping, DayType, VacDay } from '../../services/calendar-service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-user-input',
|
selector: 'app-user-input',
|
||||||
imports: [
|
imports: [
|
||||||
MatFormField,
|
|
||||||
MatLabel,
|
|
||||||
MatInputModule,
|
MatInputModule,
|
||||||
ReactiveFormsModule,
|
|
||||||
CalendarSettings,
|
|
||||||
CalendarSettings,
|
CalendarSettings,
|
||||||
|
MatCard,
|
||||||
|
MatCardContent,
|
||||||
|
MatIcon,
|
||||||
|
MatButtonModule,
|
||||||
|
DayInput,
|
||||||
],
|
],
|
||||||
templateUrl: './user-input.html',
|
templateUrl: './user-input.html',
|
||||||
styleUrl: './user-input.scss',
|
styleUrl: './user-input.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class UserInput implements OnInit, OnDestroy {
|
export class UserInput {
|
||||||
constructor(private userInputService: UserInputService) {
|
private userInputService: UserInputService = inject(UserInputService);
|
||||||
// Watch for signal changes and update form
|
|
||||||
effect(() => {
|
|
||||||
const vacationData = this.userInputService.vacationNumberSignal();
|
|
||||||
this.userInputForm.patchValue(
|
|
||||||
{
|
|
||||||
CP: vacationData.cp,
|
|
||||||
RTT: vacationData.rtt,
|
|
||||||
Others: vacationData.other,
|
|
||||||
},
|
|
||||||
{ emitEvent: false },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private destroy$ = new Subject<void>();
|
protected remainingDays = computed(() => {
|
||||||
|
const remaining = this.userInputService.remainingVacationDaysSignal();
|
||||||
userInputForm: FormGroup = new FormGroup({
|
return remaining.reduce((acc, day) => acc + day.numberOfDays, 0);
|
||||||
CP: new FormControl<number | null>(null),
|
|
||||||
RTT: new FormControl<number | null>(null),
|
|
||||||
Others: new FormControl<number | null>(null),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
ngOnInit() {
|
protected remainingDaysDetails = computed(() => {
|
||||||
this.userInputForm.valueChanges
|
const remaining = this.userInputService.remainingVacationDaysSignal();
|
||||||
.pipe(debounceTime(1500), takeUntil(this.destroy$))
|
return remaining
|
||||||
.subscribe(() => this.submitForm());
|
.filter((day) => day.numberOfDays > 0)
|
||||||
|
.map((day) => {
|
||||||
|
const typeName = tooltipTypeMapping[day.type as unknown as DayType];
|
||||||
|
const expiryDate = day.expiryDate.toLocaleDateString('fr-FR', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
year: 'numeric',
|
||||||
|
});
|
||||||
|
return `${day.numberOfDays} ${typeName} (exp. ${expiryDate})`;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
protected hasRemainingDays = computed(() => this.remainingDays() > 0);
|
||||||
|
|
||||||
|
protected get daysOff() {
|
||||||
|
return this.userInputService.vacationNumberSignal();
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy() {
|
public addDay() {
|
||||||
this.destroy$.next();
|
this.userInputService.vacationNumberSignal.update((days) => [
|
||||||
this.destroy$.complete();
|
...days,
|
||||||
|
this.userInputService.createVacationDay(),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private submitForm() {
|
public removeFromList(index: number) {
|
||||||
if (this.userInputForm.valid) {
|
this.userInputService.vacationNumberSignal.update((days) =>
|
||||||
const vacationData: VacationsNumber = {
|
days.filter((_, i) => i !== index),
|
||||||
cp: this.userInputForm.get('CP')?.value || 0,
|
);
|
||||||
rtt: this.userInputForm.get('RTT')?.value || 0,
|
}
|
||||||
other: this.userInputForm.get('Others')?.value || 0,
|
|
||||||
};
|
public updateDay(index: number, updatedDay: VacDay) {
|
||||||
this.userInputService.vacationNumberSignal.set(vacationData);
|
this.userInputService.vacationNumberSignal.update((days) =>
|
||||||
}
|
days.map((day, i) => (i === index ? updatedDay : day)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public triggerComputation() {
|
||||||
|
this.userInputService.requestComputation();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,22 +3,21 @@ import { provideZonelessChangeDetection } from '@angular/core';
|
|||||||
import { UserSettings } from './user-settings';
|
import { UserSettings } from './user-settings';
|
||||||
|
|
||||||
describe('UserSettings', () => {
|
describe('UserSettings', () => {
|
||||||
let component: UserSettings;
|
let component: UserSettings;
|
||||||
let fixture: ComponentFixture<UserSettings>;
|
let fixture: ComponentFixture<UserSettings>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [UserSettings],
|
imports: [UserSettings],
|
||||||
providers: [provideZonelessChangeDetection()]
|
providers: [provideZonelessChangeDetection()],
|
||||||
})
|
}).compileComponents();
|
||||||
.compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(UserSettings);
|
fixture = TestBed.createComponent(UserSettings);
|
||||||
component = fixture.componentInstance;
|
component = fixture.componentInstance;
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create', () => {
|
it('should create', () => {
|
||||||
expect(component).toBeTruthy();
|
expect(component).toBeTruthy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<!-- <mat-list-item role="listitem"> -->
|
||||||
|
<mat-card class="card">
|
||||||
|
<mat-form-field class="numberInput">
|
||||||
|
<input
|
||||||
|
matInput
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
[value]="day().numberOfDays"
|
||||||
|
(input)="onInput($event)"
|
||||||
|
/>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field class="dayTypeInput">
|
||||||
|
<mat-select (valueChange)="onTypeChange($event)" [value]="day().type">
|
||||||
|
<mat-option></mat-option>
|
||||||
|
@for (dayType of selectableDayTypes; track $index) {
|
||||||
|
<mat-option [value]="dayType">{{ tooltipTypeMapping[dayType] }}</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field class="dateInput">
|
||||||
|
<mat-label>Choose a date</mat-label>
|
||||||
|
<input
|
||||||
|
matInput
|
||||||
|
type="datetime"
|
||||||
|
[matDatepicker]="picker"
|
||||||
|
[value]="day().expiryDate"
|
||||||
|
(dateChange)="addEvent($event)"
|
||||||
|
/>
|
||||||
|
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
|
||||||
|
<mat-datepicker #picker></mat-datepicker>
|
||||||
|
</mat-form-field>
|
||||||
|
<button matFab aria-label="Delete entry" (click)="deleteEntry.emit()">
|
||||||
|
<mat-icon>close</mat-icon>
|
||||||
|
</button>
|
||||||
|
</mat-card>
|
||||||
|
<!-- </mat-list-item> -->
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
.card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 16px;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dateInput {
|
||||||
|
flex-grow: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.numberInput {
|
||||||
|
width: 80px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .mat-mdc-form-field-subscript-wrapper {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
|
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
|
||||||
|
|
||||||
|
import { DayInput } from './day-input';
|
||||||
|
import { SelectableDayType, VacDay } from '../../../services/calendar-service';
|
||||||
|
|
||||||
|
describe('DayInput', () => {
|
||||||
|
let component: DayInput;
|
||||||
|
let fixture: ComponentFixture<DayInput>;
|
||||||
|
|
||||||
|
const mockVacDay: VacDay = {
|
||||||
|
id: 'test-id',
|
||||||
|
type: SelectableDayType.CP,
|
||||||
|
numberOfDays: 5,
|
||||||
|
expiryDate: new Date('2025-12-31'),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [DayInput],
|
||||||
|
providers: [provideAnimationsAsync()],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
fixture = TestBed.createComponent(DayInput);
|
||||||
|
component = fixture.componentInstance;
|
||||||
|
fixture.componentRef.setInput('day', mockVacDay);
|
||||||
|
fixture.detectChanges();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create', () => {
|
||||||
|
expect(component).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { Component, input, output, ChangeDetectionStrategy } from '@angular/core';
|
||||||
|
import { SelectableDayType, tooltipTypeMapping, VacDay } from '../../../services/calendar-service';
|
||||||
|
import { MatCard } from '@angular/material/card';
|
||||||
|
import { MatOption, MatSelect } from '@angular/material/select';
|
||||||
|
import { MatInput, MatInputModule, MatLabel } from '@angular/material/input';
|
||||||
|
import {
|
||||||
|
MatDatepicker,
|
||||||
|
MatDatepickerInput,
|
||||||
|
MatDatepickerInputEvent,
|
||||||
|
MatDatepickerToggle,
|
||||||
|
} from '@angular/material/datepicker';
|
||||||
|
import {
|
||||||
|
DateAdapter,
|
||||||
|
MAT_DATE_FORMATS,
|
||||||
|
MAT_DATE_LOCALE,
|
||||||
|
NativeDateAdapter,
|
||||||
|
} from '@angular/material/core';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
|
||||||
|
class CustomDateAdapter extends NativeDateAdapter {
|
||||||
|
override format(date: Date, displayFormat: unknown): string {
|
||||||
|
if (displayFormat === 'input') {
|
||||||
|
const day = date.getDate().toString().padStart(2, '0');
|
||||||
|
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||||
|
const year = date.getFullYear();
|
||||||
|
return `${day}/${month}/${year}`;
|
||||||
|
}
|
||||||
|
return super.format(date, displayFormat as object);
|
||||||
|
}
|
||||||
|
|
||||||
|
override parse(value: string): Date | null {
|
||||||
|
if (!value) return null;
|
||||||
|
const parts = value.split('/');
|
||||||
|
if (parts.length === 3) {
|
||||||
|
const day = parseInt(parts[0], 10);
|
||||||
|
const month = parseInt(parts[1], 10) - 1;
|
||||||
|
const year = parseInt(parts[2], 10);
|
||||||
|
if (!isNaN(day) && !isNaN(month) && !isNaN(year)) {
|
||||||
|
return new Date(year, month, day);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MY_DATE_FORMATS = {
|
||||||
|
parse: {
|
||||||
|
dateInput: 'input',
|
||||||
|
},
|
||||||
|
display: {
|
||||||
|
dateInput: 'input',
|
||||||
|
monthYearLabel: { year: 'numeric', month: 'short' },
|
||||||
|
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
|
||||||
|
monthYearA11yLabel: { year: 'numeric', month: 'long' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-day-input',
|
||||||
|
imports: [
|
||||||
|
MatIconModule,
|
||||||
|
MatCard,
|
||||||
|
MatSelect,
|
||||||
|
MatOption,
|
||||||
|
MatInput,
|
||||||
|
MatDatepicker,
|
||||||
|
MatLabel,
|
||||||
|
MatDatepickerToggle,
|
||||||
|
MatDatepickerInput,
|
||||||
|
MatInputModule,
|
||||||
|
MatButtonModule,
|
||||||
|
],
|
||||||
|
templateUrl: './day-input.html',
|
||||||
|
styleUrl: './day-input.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
providers: [
|
||||||
|
{ provide: DateAdapter, useClass: CustomDateAdapter },
|
||||||
|
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' },
|
||||||
|
{ provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class DayInput {
|
||||||
|
public day = input.required<VacDay>();
|
||||||
|
public dayChange = output<VacDay>();
|
||||||
|
public deleteEntry = output<void>();
|
||||||
|
|
||||||
|
protected readonly selectableDayTypes = Object.values(SelectableDayType);
|
||||||
|
protected readonly tooltipTypeMapping = tooltipTypeMapping;
|
||||||
|
|
||||||
|
onInput(event: Event) {
|
||||||
|
const value = Number((event.target as HTMLInputElement).value);
|
||||||
|
this.dayChange.emit({ ...this.day(), numberOfDays: value });
|
||||||
|
}
|
||||||
|
|
||||||
|
onTypeChange(type: SelectableDayType) {
|
||||||
|
this.dayChange.emit({ ...this.day(), type });
|
||||||
|
}
|
||||||
|
|
||||||
|
addEvent(event: MatDatepickerInputEvent<Date>) {
|
||||||
|
this.dayChange.emit({ ...this.day(), expiryDate: event.value! });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,6 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideZonelessChangeDetection } from '@angular/core';
|
import { provideZonelessChangeDetection } from '@angular/core';
|
||||||
import {
|
import { CalendarService, DayType, SelectedDate, SelectedDates } from './calendar-service';
|
||||||
CalendarService,
|
|
||||||
DayType,
|
|
||||||
SelectedDate,
|
|
||||||
SelectedDates,
|
|
||||||
} from './calendar-service';
|
|
||||||
import { DateRange } from '@angular/material/datepicker';
|
import { DateRange } from '@angular/material/datepicker';
|
||||||
|
|
||||||
describe('CalendarService', () => {
|
describe('CalendarService', () => {
|
||||||
@@ -111,47 +106,32 @@ describe('CalendarService', () => {
|
|||||||
describe('SelectedDate', () => {
|
describe('SelectedDate', () => {
|
||||||
it('should check if date is selected', () => {
|
it('should check if date is selected', () => {
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
const selectedDate = new SelectedDate(
|
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
|
||||||
DayType.CP,
|
|
||||||
new DateRange<Date>(date, date),
|
|
||||||
);
|
|
||||||
expect(selectedDate.isSelected(date)).toBe(true);
|
expect(selectedDate.isSelected(date)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should check if date is start', () => {
|
it('should check if date is start', () => {
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
const selectedDate = new SelectedDate(
|
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
|
||||||
DayType.CP,
|
|
||||||
new DateRange<Date>(date, date),
|
|
||||||
);
|
|
||||||
expect(selectedDate.isStart(date)).toBe(true);
|
expect(selectedDate.isStart(date)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should check if date is end', () => {
|
it('should check if date is end', () => {
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
const selectedDate = new SelectedDate(
|
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
|
||||||
DayType.CP,
|
|
||||||
new DateRange<Date>(date, date),
|
|
||||||
);
|
|
||||||
expect(selectedDate.isEnd(date)).toBe(true);
|
expect(selectedDate.isEnd(date)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return correct classes for date', () => {
|
it('should return correct classes for date', () => {
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
const selectedDate = new SelectedDate(
|
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
|
||||||
DayType.CP,
|
|
||||||
new DateRange<Date>(date, date),
|
|
||||||
);
|
|
||||||
const classes = selectedDate.getClasses(date);
|
const classes = selectedDate.getClasses(date);
|
||||||
expect(classes).toContain(DayType.CP);
|
expect(classes).toContain(DayType.CP);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return tooltip for selected date', () => {
|
it('should return tooltip for selected date', () => {
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
const selectedDate = new SelectedDate(
|
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(date, date));
|
||||||
DayType.CP,
|
|
||||||
new DateRange<Date>(date, date),
|
|
||||||
);
|
|
||||||
const tooltip = selectedDate.getTooltip(date);
|
const tooltip = selectedDate.getTooltip(date);
|
||||||
expect(tooltip).toBeTruthy();
|
expect(tooltip).toBeTruthy();
|
||||||
});
|
});
|
||||||
@@ -159,19 +139,13 @@ describe('SelectedDate', () => {
|
|||||||
it('should calculate length in days', () => {
|
it('should calculate length in days', () => {
|
||||||
const startDate = new Date(2024, 0, 1);
|
const startDate = new Date(2024, 0, 1);
|
||||||
const endDate = new Date(2024, 0, 3);
|
const endDate = new Date(2024, 0, 3);
|
||||||
const selectedDate = new SelectedDate(
|
const selectedDate = new SelectedDate(DayType.CP, new DateRange<Date>(startDate, endDate));
|
||||||
DayType.CP,
|
|
||||||
new DateRange<Date>(startDate, endDate),
|
|
||||||
);
|
|
||||||
expect(selectedDate.getLengthInDays()).toBe(3);
|
expect(selectedDate.getLengthInDays()).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not mark TODAY as selected', () => {
|
it('should not mark TODAY as selected', () => {
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
const selectedDate = new SelectedDate(
|
const selectedDate = new SelectedDate(DayType.TODAY, new DateRange<Date>(date, date));
|
||||||
DayType.TODAY,
|
|
||||||
new DateRange<Date>(date, date),
|
|
||||||
);
|
|
||||||
expect(selectedDate.isSelected(date)).toBe(false);
|
expect(selectedDate.isSelected(date)).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -180,18 +154,14 @@ describe('SelectedDates', () => {
|
|||||||
it('should push selected dates', () => {
|
it('should push selected dates', () => {
|
||||||
const selectedDates = new SelectedDates();
|
const selectedDates = new SelectedDates();
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
selectedDates.push(
|
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
|
||||||
new SelectedDate(DayType.CP, new DateRange<Date>(date, date)),
|
|
||||||
);
|
|
||||||
expect(selectedDates._datesSelected.length).toBe(1);
|
expect(selectedDates._datesSelected.length).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should check if date is selected', () => {
|
it('should check if date is selected', () => {
|
||||||
const selectedDates = new SelectedDates();
|
const selectedDates = new SelectedDates();
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
selectedDates.push(
|
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
|
||||||
new SelectedDate(DayType.CP, new DateRange<Date>(date, date)),
|
|
||||||
);
|
|
||||||
expect(selectedDates.isSelected(date)).toBe(true);
|
expect(selectedDates.isSelected(date)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -212,9 +182,7 @@ describe('SelectedDates', () => {
|
|||||||
it('should compute heuristics', () => {
|
it('should compute heuristics', () => {
|
||||||
const selectedDates = new SelectedDates();
|
const selectedDates = new SelectedDates();
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
selectedDates.push(
|
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
|
||||||
new SelectedDate(DayType.CP, new DateRange<Date>(date, date)),
|
|
||||||
);
|
|
||||||
const heuristic = selectedDates.computeHeuristics();
|
const heuristic = selectedDates.computeHeuristics();
|
||||||
expect(typeof heuristic).toBe('number');
|
expect(typeof heuristic).toBe('number');
|
||||||
});
|
});
|
||||||
@@ -222,9 +190,7 @@ describe('SelectedDates', () => {
|
|||||||
it('should return correct classes', () => {
|
it('should return correct classes', () => {
|
||||||
const selectedDates = new SelectedDates();
|
const selectedDates = new SelectedDates();
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
selectedDates.push(
|
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
|
||||||
new SelectedDate(DayType.CP, new DateRange<Date>(date, date)),
|
|
||||||
);
|
|
||||||
const classes = selectedDates.getClasses(date);
|
const classes = selectedDates.getClasses(date);
|
||||||
expect(classes).toContain(DayType.CP);
|
expect(classes).toContain(DayType.CP);
|
||||||
});
|
});
|
||||||
@@ -232,9 +198,7 @@ describe('SelectedDates', () => {
|
|||||||
it('should return tooltip', () => {
|
it('should return tooltip', () => {
|
||||||
const selectedDates = new SelectedDates();
|
const selectedDates = new SelectedDates();
|
||||||
const date = new Date(2024, 0, 1);
|
const date = new Date(2024, 0, 1);
|
||||||
selectedDates.push(
|
selectedDates.push(new SelectedDate(DayType.CP, new DateRange<Date>(date, date)));
|
||||||
new SelectedDate(DayType.CP, new DateRange<Date>(date, date)),
|
|
||||||
);
|
|
||||||
const tooltip = selectedDates.getTooltip(date);
|
const tooltip = selectedDates.getTooltip(date);
|
||||||
expect(tooltip).toBeTruthy();
|
expect(tooltip).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,8 +28,8 @@ export class CalendarService {
|
|||||||
|
|
||||||
// Get selected dates from current date to the next year
|
// Get selected dates from current date to the next year
|
||||||
getSelectedDatesFromNow(): SelectedDates {
|
getSelectedDatesFromNow(): SelectedDates {
|
||||||
const holidays = this.getHolidays();
|
const _holidays = this.getHolidays();
|
||||||
let selectedDates: SelectedDates = new SelectedDates();
|
const selectedDates: SelectedDates = new SelectedDates();
|
||||||
// Logic to populate selectedDates from now until the next year
|
// Logic to populate selectedDates from now until the next year
|
||||||
return selectedDates;
|
return selectedDates;
|
||||||
}
|
}
|
||||||
@@ -37,7 +37,7 @@ export class CalendarService {
|
|||||||
getSelectedDatesForYear(): SelectedDates {
|
getSelectedDatesForYear(): SelectedDates {
|
||||||
const holidays = this.getHolidays();
|
const holidays = this.getHolidays();
|
||||||
const monthInAYear = this.monthsInAYearFromNow();
|
const monthInAYear = this.monthsInAYearFromNow();
|
||||||
let selectedDates: SelectedDates = new SelectedDates();
|
const selectedDates: SelectedDates = new SelectedDates();
|
||||||
|
|
||||||
// Use DateCacheService to get today's date components
|
// Use DateCacheService to get today's date components
|
||||||
const {
|
const {
|
||||||
@@ -184,10 +184,11 @@ export class CalendarService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type VacationsNumber = {
|
export type VacDay = {
|
||||||
rtt: number;
|
id: string;
|
||||||
cp: number;
|
type: SelectableDayType;
|
||||||
other: number;
|
numberOfDays: number;
|
||||||
|
expiryDate: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Week = (Date | null)[];
|
export type Week = (Date | null)[];
|
||||||
@@ -203,6 +204,12 @@ export enum DayType {
|
|||||||
TODAY = 'today',
|
TODAY = 'today',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum SelectableDayType {
|
||||||
|
CP = DayType.CP,
|
||||||
|
RTT = DayType.RTT,
|
||||||
|
OTHER = DayType.OTHER,
|
||||||
|
}
|
||||||
|
|
||||||
export const tooltipTypeMapping: { [key in DayType]: string } = {
|
export const tooltipTypeMapping: { [key in DayType]: string } = {
|
||||||
[DayType.WEEKEND]: 'Weekend',
|
[DayType.WEEKEND]: 'Weekend',
|
||||||
[DayType.CLOSED_DAY]: 'Jour Férié',
|
[DayType.CLOSED_DAY]: 'Jour Férié',
|
||||||
@@ -266,7 +273,7 @@ export class SelectedDate implements SelectedDateInterface {
|
|||||||
getClasses(date: Date): string {
|
getClasses(date: Date): string {
|
||||||
let returnType: DayType | string = '';
|
let returnType: DayType | string = '';
|
||||||
if (this.type && date >= this.range.start! && date <= this.range.end!) {
|
if (this.type && date >= this.range.start! && date <= this.range.end!) {
|
||||||
returnType = returnType += this.type + ' ';
|
returnType += this.type + ' ';
|
||||||
}
|
}
|
||||||
return returnType;
|
return returnType;
|
||||||
}
|
}
|
||||||
@@ -298,6 +305,7 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
|
|
||||||
// Constant to indicate no valid strategy was found
|
// Constant to indicate no valid strategy was found
|
||||||
private static readonly NO_VALID_STRATEGY_HEURISTIC = -1;
|
private static readonly NO_VALID_STRATEGY_HEURISTIC = -1;
|
||||||
|
private static readonly MAX_DAYS_WITH_SAME_HEURISTIC = 9;
|
||||||
|
|
||||||
update(): void {
|
update(): void {
|
||||||
this.datesSelected = this._datesSelected.slice();
|
this.datesSelected = this._datesSelected.slice();
|
||||||
@@ -501,7 +509,7 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
|
|
||||||
// Check if adjacent (next day) - this is the best case!
|
// Check if adjacent (next day) - this is the best case!
|
||||||
if (nextStartTime - currentEndTime === oneDayInMs) {
|
if (nextStartTime - currentEndTime === oneDayInMs) {
|
||||||
totalScore += 10; // Big bonus for adjacency
|
totalScore += 15; // 50% increased bonus for adjacency; adjacency is highly valued in the scoring system
|
||||||
} else if (nextStartTime > currentEndTime) {
|
} else if (nextStartTime > currentEndTime) {
|
||||||
// Penalty based on days between the two dates
|
// Penalty based on days between the two dates
|
||||||
const daysBetween = Math.floor((nextStartTime - currentEndTime) / oneDayInMs) - 1;
|
const daysBetween = Math.floor((nextStartTime - currentEndTime) / oneDayInMs) - 1;
|
||||||
@@ -519,7 +527,7 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
const daysInRange = selectedDate.getLengthInDays();
|
const daysInRange = selectedDate.getLengthInDays();
|
||||||
|
|
||||||
// For each day in the range, add it to the appropriate month
|
// 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++) {
|
for (let i = 0; i < daysInRange; i++) {
|
||||||
const monthKey = currentDate.getFullYear() * 12 + currentDate.getMonth();
|
const monthKey = currentDate.getFullYear() * 12 + currentDate.getMonth();
|
||||||
monthCounts.set(monthKey, (monthCounts.get(monthKey) ?? 0) + 1);
|
monthCounts.set(monthKey, (monthCounts.get(monthKey) ?? 0) + 1);
|
||||||
@@ -535,36 +543,81 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
return totalScore;
|
return totalScore;
|
||||||
}
|
}
|
||||||
|
|
||||||
optimizeVacations(
|
async optimizeVacations(
|
||||||
vacationsNumber: VacationsNumber,
|
vacationDays: VacDay[],
|
||||||
calendarSettingsService: CalendarSettingsService,
|
calendarSettingsService: CalendarSettingsService,
|
||||||
calendarService: CalendarService,
|
calendarService: CalendarService,
|
||||||
): void {
|
progressCallback?: (progress: number) => void,
|
||||||
if (calendarSettingsService.samediMalin()) this.samediMalin(vacationsNumber);
|
): Promise<VacDay[]> {
|
||||||
while (vacationsNumber.cp > 0) {
|
if (calendarSettingsService.get('samediMalin')()) this.samediMalin(vacationDays);
|
||||||
const result = this.lookForVacation(DayType.CP, calendarService);
|
|
||||||
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
|
// Calculate total days to process
|
||||||
|
const totalDays = vacationDays.reduce((sum, vd) => sum + vd.numberOfDays, 0);
|
||||||
|
let processedDays = 0;
|
||||||
|
|
||||||
|
// Helper function to update progress, throttled to every 5%
|
||||||
|
let lastReportedProgress = 0;
|
||||||
|
const PROGRESS_STEP = 5; // percent
|
||||||
|
const updateProgress = async () => {
|
||||||
|
if (progressCallback && totalDays > 0) {
|
||||||
|
const progress = Math.round((processedDays / totalDays) * 100);
|
||||||
|
if (progress - lastReportedProgress >= PROGRESS_STEP || progress === 100) {
|
||||||
|
progressCallback(progress);
|
||||||
|
lastReportedProgress = progress;
|
||||||
|
// Allow UI to update with a microtask
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
await updateProgress();
|
||||||
|
|
||||||
|
// Track VacDays that can't find valid placements
|
||||||
|
const exhaustedVacDayIds = new Set<string>();
|
||||||
|
|
||||||
|
// Process vacation days ordered by expiration date (earliest first)
|
||||||
|
while (vacationDays.some((vd) => vd.numberOfDays > 0 && !exhaustedVacDayIds.has(vd.id))) {
|
||||||
|
// Sort by expiration date to use days that expire first, excluding exhausted ones
|
||||||
|
const sortedVacDays = [...vacationDays]
|
||||||
|
.filter((vd) => vd.numberOfDays > 0 && !exhaustedVacDayIds.has(vd.id))
|
||||||
|
.sort((a, b) => a.expiryDate.getTime() - b.expiryDate.getTime());
|
||||||
|
|
||||||
|
if (sortedVacDays.length === 0) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
vacationsNumber.cp -= 1;
|
|
||||||
}
|
const vacDayToUse = sortedVacDays[0];
|
||||||
while (vacationsNumber.rtt > 0) {
|
const result = this.lookForVacation(vacDayToUse, calendarService);
|
||||||
const result = this.lookForVacation(DayType.RTT, calendarService);
|
|
||||||
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
|
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
|
||||||
break;
|
// Mark this VacDay as exhausted and try other vacation days
|
||||||
|
exhaustedVacDayIds.add(vacDayToUse.id);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
vacationsNumber.rtt -= 1;
|
|
||||||
|
vacDayToUse.numberOfDays -= 1;
|
||||||
|
processedDays++;
|
||||||
|
await updateProgress();
|
||||||
}
|
}
|
||||||
while (vacationsNumber.other > 0) {
|
|
||||||
const result = this.lookForVacation(DayType.OTHER, calendarService);
|
// Final progress update (100%)
|
||||||
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
|
if (progressCallback) {
|
||||||
break;
|
progressCallback(100);
|
||||||
}
|
|
||||||
vacationsNumber.other -= 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Inform user if not all days were placed
|
||||||
|
const remainingDays = vacationDays.reduce((sum, vd) => sum + vd.numberOfDays, 0);
|
||||||
|
if (remainingDays > 0) {
|
||||||
|
console.warn(
|
||||||
|
`Optimization stopped: ${remainingDays} of ${totalDays} vacation days remain unplaced. ` +
|
||||||
|
`Too many days have equivalent placement quality - please place remaining days manually.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return vacationDays;
|
||||||
}
|
}
|
||||||
|
|
||||||
samediMalin(vacationsNumber: VacationsNumber): void {
|
samediMalin(vacationDays: VacDay[]): void {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
now.setHours(0, 0, 0, 0);
|
now.setHours(0, 0, 0, 0);
|
||||||
const nowTime = now.getTime();
|
const nowTime = now.getTime();
|
||||||
@@ -573,14 +626,63 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
(date) => date.type === DayType.CLOSED_DAY && date.range.start?.getDay() === 6,
|
(date) => date.type === DayType.CLOSED_DAY && date.range.start?.getDay() === 6,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Helper function to get available CP days that don't expire before a given date (ordered by expiry date)
|
||||||
|
const getAvailableCpDaysForDate = (useByDate: Date): VacDay[] => {
|
||||||
|
const useByTime = useByDate.getTime();
|
||||||
|
return vacationDays
|
||||||
|
.filter(
|
||||||
|
(vd) =>
|
||||||
|
vd.type === SelectableDayType.CP &&
|
||||||
|
vd.numberOfDays > 0 &&
|
||||||
|
vd.expiryDate.getTime() >= useByTime,
|
||||||
|
)
|
||||||
|
.sort((a, b) => a.expiryDate.getTime() - b.expiryDate.getTime());
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to get total available CP days that don't expire before a given date
|
||||||
|
const getTotalCpDaysForDate = (useByDate: Date): number => {
|
||||||
|
const useByTime = useByDate.getTime();
|
||||||
|
return vacationDays
|
||||||
|
.filter(
|
||||||
|
(vd) =>
|
||||||
|
vd.type === SelectableDayType.CP && vd.expiryDate.getTime() >= useByTime,
|
||||||
|
)
|
||||||
|
.reduce((sum, vd) => sum + vd.numberOfDays, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to consume 2 CP days from the available pool for a specific date
|
||||||
|
const consume2CpDaysForDate = (useByDate: Date): boolean => {
|
||||||
|
let daysToConsume = 2;
|
||||||
|
const cpDays = getAvailableCpDaysForDate(useByDate);
|
||||||
|
for (const cpDay of cpDays) {
|
||||||
|
if (daysToConsume === 0) break;
|
||||||
|
const toConsume = Math.min(cpDay.numberOfDays, daysToConsume);
|
||||||
|
cpDay.numberOfDays -= toConsume;
|
||||||
|
daysToConsume -= toConsume;
|
||||||
|
}
|
||||||
|
return daysToConsume === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to add 1 OTHER day as reward
|
||||||
|
const addOtherDayReward = (): void => {
|
||||||
|
// Find an existing OTHER VacDay or create a new one
|
||||||
|
const otherDay = vacationDays.find((vd) => vd.type === SelectableDayType.OTHER);
|
||||||
|
if (otherDay) {
|
||||||
|
otherDay.numberOfDays += 1;
|
||||||
|
} else {
|
||||||
|
// Create a new OTHER VacDay with a far future expiry date
|
||||||
|
vacationDays.push({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
type: SelectableDayType.OTHER,
|
||||||
|
numberOfDays: 1,
|
||||||
|
expiryDate: new Date(now.getFullYear() + 10, 11, 31),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
for (const holiday of samedi_ferie) {
|
for (const holiday of samedi_ferie) {
|
||||||
if (!holiday.range.start) continue;
|
if (!holiday.range.start) continue;
|
||||||
|
|
||||||
// Skip if no CP days available
|
|
||||||
if (vacationsNumber.cp < 2) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the Saturday date (holiday) and the following Sunday
|
// Get the Saturday date (holiday) and the following Sunday
|
||||||
const saturdayDate = new Date(holiday.range.start);
|
const saturdayDate = new Date(holiday.range.start);
|
||||||
const sundayDate = new Date(saturdayDate);
|
const sundayDate = new Date(saturdayDate);
|
||||||
@@ -605,21 +707,24 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
const oneDayAfter = new Date(sundayDate);
|
const oneDayAfter = new Date(sundayDate);
|
||||||
oneDayAfter.setDate(sundayDate.getDate() + 1);
|
oneDayAfter.setDate(sundayDate.getDate() + 1);
|
||||||
|
|
||||||
// Check if we can apply each strategy (and not in the past)
|
// Check if we can apply each strategy (not in the past, not already selected, and have non-expired CP days)
|
||||||
const canApplyTwoBeforeStrategy =
|
const canApplyTwoBeforeStrategy =
|
||||||
twoDaysBefore1.getTime() >= nowTime &&
|
twoDaysBefore1.getTime() >= nowTime &&
|
||||||
!this.isSelected(twoDaysBefore1) &&
|
!this.isSelected(twoDaysBefore1) &&
|
||||||
!this.isSelected(twoDaysBefore2);
|
!this.isSelected(twoDaysBefore2) &&
|
||||||
|
getTotalCpDaysForDate(twoDaysBefore2) >= 2; // Check expiry against the latest date used
|
||||||
|
|
||||||
const canApplyTwoAfterStrategy =
|
const canApplyTwoAfterStrategy =
|
||||||
twoDaysAfter1.getTime() >= nowTime &&
|
twoDaysAfter1.getTime() >= nowTime &&
|
||||||
!this.isSelected(twoDaysAfter1) &&
|
!this.isSelected(twoDaysAfter1) &&
|
||||||
!this.isSelected(twoDaysAfter2);
|
!this.isSelected(twoDaysAfter2) &&
|
||||||
|
getTotalCpDaysForDate(twoDaysAfter2) >= 2; // Check expiry against the latest date used
|
||||||
|
|
||||||
const canApplyMixedStrategy =
|
const canApplyMixedStrategy =
|
||||||
oneDayBefore.getTime() >= nowTime &&
|
oneDayBefore.getTime() >= nowTime &&
|
||||||
!this.isSelected(oneDayBefore) &&
|
!this.isSelected(oneDayBefore) &&
|
||||||
!this.isSelected(oneDayAfter);
|
!this.isSelected(oneDayAfter) &&
|
||||||
|
getTotalCpDaysForDate(oneDayAfter) >= 2; // Check expiry against the latest date used
|
||||||
|
|
||||||
// Test all applicable strategies and choose the one with the best heuristic score
|
// Test all applicable strategies and choose the one with the best heuristic score
|
||||||
const strategies: { apply: () => void; heuristic: number }[] = [];
|
const strategies: { apply: () => void; heuristic: number }[] = [];
|
||||||
@@ -642,8 +747,8 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
new DateRange<Date>(twoDaysBefore1, twoDaysBefore2),
|
new DateRange<Date>(twoDaysBefore1, twoDaysBefore2),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
vacationsNumber.cp -= 2;
|
consume2CpDaysForDate(twoDaysBefore2);
|
||||||
vacationsNumber.other += 1; // Reward: gain 1 other day
|
addOtherDayReward();
|
||||||
},
|
},
|
||||||
heuristic: heuristic,
|
heuristic: heuristic,
|
||||||
});
|
});
|
||||||
@@ -666,8 +771,8 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
new DateRange<Date>(twoDaysAfter1, twoDaysAfter2),
|
new DateRange<Date>(twoDaysAfter1, twoDaysAfter2),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
vacationsNumber.cp -= 2;
|
consume2CpDaysForDate(twoDaysAfter2);
|
||||||
vacationsNumber.other += 1; // Reward: gain 1 other day
|
addOtherDayReward();
|
||||||
},
|
},
|
||||||
heuristic: heuristic,
|
heuristic: heuristic,
|
||||||
});
|
});
|
||||||
@@ -699,8 +804,8 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
new DateRange<Date>(oneDayAfter, oneDayAfter),
|
new DateRange<Date>(oneDayAfter, oneDayAfter),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
vacationsNumber.cp -= 2;
|
consume2CpDaysForDate(oneDayAfter);
|
||||||
vacationsNumber.other += 1; // Reward: gain 1 other day
|
addOtherDayReward();
|
||||||
},
|
},
|
||||||
heuristic: heuristic,
|
heuristic: heuristic,
|
||||||
});
|
});
|
||||||
@@ -719,20 +824,25 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
lookForVacation(vacType: DayType, calendarService: CalendarService): { apply: () => void; heuristic: number } {
|
lookForVacation(
|
||||||
|
vacDay: VacDay,
|
||||||
|
calendarService: CalendarService,
|
||||||
|
): { apply: () => void; heuristic: number } {
|
||||||
const daysOfYear = calendarService.monthsInAYearFromNow();
|
const daysOfYear = calendarService.monthsInAYearFromNow();
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
now.setHours(0, 0, 0, 0);
|
now.setHours(0, 0, 0, 0);
|
||||||
const nowTime = now.getTime();
|
const nowTime = now.getTime();
|
||||||
|
const expiryTime = vacDay.expiryDate.getTime();
|
||||||
|
|
||||||
// Preprocess: filter out past days and already selected days in one pass
|
// Preprocess: filter out past days, already selected days, and days after expiry date
|
||||||
const candidateDays: Date[] = [];
|
const candidateDays: Date[] = [];
|
||||||
for (const month of daysOfYear) {
|
for (const month of daysOfYear) {
|
||||||
for (const week of month) {
|
for (const week of month) {
|
||||||
for (const day of week) {
|
for (const day of week) {
|
||||||
if (day) {
|
if (day) {
|
||||||
day.setHours(0, 0, 0, 0);
|
day.setHours(0, 0, 0, 0);
|
||||||
if (day.getTime() >= nowTime && !this.isSelected(day)) {
|
const dayTime = day.getTime();
|
||||||
|
if (dayTime >= nowTime && dayTime <= expiryTime && !this.isSelected(day)) {
|
||||||
candidateDays.push(day);
|
candidateDays.push(day);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -745,9 +855,11 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
return { apply: () => {}, heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC };
|
return { apply: () => {}, heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const vacType = vacDay.type as unknown as DayType;
|
||||||
const tempDatesBackup = [...this._datesSelected];
|
const tempDatesBackup = [...this._datesSelected];
|
||||||
let bestStrategy: { apply: () => void; heuristic: number; value: Date } | null = null;
|
let bestStrategy: { apply: () => void; heuristic: number; value: Date } | null = null;
|
||||||
let bestHeuristic = -Infinity;
|
let bestHeuristic = -Infinity;
|
||||||
|
let daysWithBestHeuristic = 0;
|
||||||
|
|
||||||
// Evaluate each candidate day
|
// Evaluate each candidate day
|
||||||
for (const day of candidateDays) {
|
for (const day of candidateDays) {
|
||||||
@@ -764,6 +876,7 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
// Track only if better than current best
|
// Track only if better than current best
|
||||||
if (heuristic > bestHeuristic) {
|
if (heuristic > bestHeuristic) {
|
||||||
bestHeuristic = heuristic;
|
bestHeuristic = heuristic;
|
||||||
|
daysWithBestHeuristic = 1;
|
||||||
const capturedDay = day;
|
const capturedDay = day;
|
||||||
bestStrategy = {
|
bestStrategy = {
|
||||||
apply: () => {
|
apply: () => {
|
||||||
@@ -778,9 +891,25 @@ export class SelectedDates implements SelectedDateInterface {
|
|||||||
heuristic: heuristic,
|
heuristic: heuristic,
|
||||||
value: capturedDay,
|
value: capturedDay,
|
||||||
};
|
};
|
||||||
|
} else if (heuristic === bestHeuristic) {
|
||||||
|
daysWithBestHeuristic++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if too many days have the same best heuristic after evaluating all days
|
||||||
|
if (daysWithBestHeuristic > SelectedDates.MAX_DAYS_WITH_SAME_HEURISTIC) {
|
||||||
|
// Restore backup before stopping
|
||||||
|
this._datesSelected = [...tempDatesBackup];
|
||||||
|
this.datesSelected = this._datesSelected.slice();
|
||||||
|
this.grouping();
|
||||||
|
|
||||||
|
// Stop optimization - let user decide manually
|
||||||
|
return {
|
||||||
|
apply: () => {},
|
||||||
|
heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Restore backup before returning
|
// Restore backup before returning
|
||||||
this._datesSelected = [...tempDatesBackup];
|
this._datesSelected = [...tempDatesBackup];
|
||||||
this.datesSelected = this._datesSelected.slice();
|
this.datesSelected = this._datesSelected.slice();
|
||||||
|
|||||||
@@ -17,17 +17,29 @@ describe('CalendarSettingsService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should initialize with default values', () => {
|
it('should initialize with default values', () => {
|
||||||
expect(service.showWeekNumbers()).toBe(false);
|
expect(service.get('showWeekNumbers')()).toBe(false);
|
||||||
expect(service.samediMalin()).toBe(true);
|
expect(service.get('samediMalin')()).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow updating showWeekNumbers', () => {
|
it('should allow updating showWeekNumbers', () => {
|
||||||
service.showWeekNumbers.set(true);
|
service.get('showWeekNumbers').set(true);
|
||||||
expect(service.showWeekNumbers()).toBe(true);
|
expect(service.get('showWeekNumbers')()).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow updating samediMalin', () => {
|
it('should allow updating samediMalin', () => {
|
||||||
service.samediMalin.set(false);
|
service.get('samediMalin').set(false);
|
||||||
expect(service.samediMalin()).toBe(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');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -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({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class CalendarSettingsService {
|
export class CalendarSettingsService {
|
||||||
readonly showWeekNumbers = signal(false);
|
private readonly injector = inject(Injector);
|
||||||
readonly samediMalin = signal(true);
|
|
||||||
|
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 ?? '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,40 +3,40 @@ import { provideZonelessChangeDetection } from '@angular/core';
|
|||||||
import { ThemeService } from './theme-service';
|
import { ThemeService } from './theme-service';
|
||||||
|
|
||||||
describe('ThemeService', () => {
|
describe('ThemeService', () => {
|
||||||
let service: ThemeService;
|
let service: ThemeService;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [provideZonelessChangeDetection()],
|
providers: [provideZonelessChangeDetection()],
|
||||||
});
|
});
|
||||||
service = TestBed.inject(ThemeService);
|
service = TestBed.inject(ThemeService);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be created', () => {
|
it('should be created', () => {
|
||||||
expect(service).toBeTruthy();
|
expect(service).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should initialize with system preference', () => {
|
it('should initialize with system preference', () => {
|
||||||
expect(service.isLightMode()).toBeDefined();
|
expect(service.isLightMode()).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should toggle theme', () => {
|
it('should toggle theme', () => {
|
||||||
const initialMode = service.isLightMode();
|
const initialMode = service.isLightMode();
|
||||||
service.toggleTheme();
|
service.toggleTheme();
|
||||||
expect(service.isLightMode()).toBe(!initialMode);
|
expect(service.isLightMode()).toBe(!initialMode);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should force light mode when specified', () => {
|
it('should force light mode when specified', () => {
|
||||||
service.toggleTheme(true);
|
service.toggleTheme(true);
|
||||||
expect(service.isLightMode()).toBe(true);
|
expect(service.isLightMode()).toBe(true);
|
||||||
expect(document.body.classList.contains('light-mode')).toBe(true);
|
expect(document.body.classList.contains('light-mode')).toBe(true);
|
||||||
expect(document.body.classList.contains('dark-mode')).toBe(false);
|
expect(document.body.classList.contains('dark-mode')).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should force dark mode when specified', () => {
|
it('should force dark mode when specified', () => {
|
||||||
service.toggleTheme(false);
|
service.toggleTheme(false);
|
||||||
expect(service.isLightMode()).toBe(false);
|
expect(service.isLightMode()).toBe(false);
|
||||||
expect(document.body.classList.contains('light-mode')).toBe(false);
|
expect(document.body.classList.contains('light-mode')).toBe(false);
|
||||||
expect(document.body.classList.contains('dark-mode')).toBe(true);
|
expect(document.body.classList.contains('dark-mode')).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideZonelessChangeDetection } from '@angular/core';
|
import { provideZonelessChangeDetection } from '@angular/core';
|
||||||
import { UserInputService } from './user-input-service';
|
import { UserInputService } from './user-input-service';
|
||||||
|
import { SelectableDayType, VacDay } from './calendar-service';
|
||||||
|
|
||||||
describe('UserInput', () => {
|
describe('UserInputService', () => {
|
||||||
let service: UserInputService;
|
let service: UserInputService;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -16,19 +17,41 @@ describe('UserInput', () => {
|
|||||||
expect(service).toBeTruthy();
|
expect(service).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should initialize with random vacation numbers', () => {
|
it('should initialize with vacation days array', () => {
|
||||||
const vacations = service.vacationNumberSignal();
|
const vacations = service.vacationNumberSignal();
|
||||||
expect(vacations.cp).toBeGreaterThanOrEqual(1);
|
expect(Array.isArray(vacations)).toBe(true);
|
||||||
expect(vacations.cp).toBeLessThanOrEqual(9);
|
expect(vacations.length).toBeGreaterThan(0);
|
||||||
expect(vacations.rtt).toBeGreaterThanOrEqual(1);
|
});
|
||||||
expect(vacations.rtt).toBeLessThanOrEqual(9);
|
|
||||||
expect(vacations.other).toBeGreaterThanOrEqual(1);
|
it('should have vacation days with valid properties', () => {
|
||||||
expect(vacations.other).toBeLessThanOrEqual(9);
|
const vacations = service.vacationNumberSignal();
|
||||||
|
vacations.forEach((day) => {
|
||||||
|
expect(day.id).toBeDefined();
|
||||||
|
expect(day.type).toBeDefined();
|
||||||
|
expect(day.numberOfDays).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(day.numberOfDays).toBeLessThanOrEqual(9);
|
||||||
|
expect(day.expiryDate).toBeInstanceOf(Date);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should update vacation number signal', () => {
|
it('should update vacation number signal', () => {
|
||||||
const newVacations = { cp: 5, rtt: 3, other: 2 };
|
const newVacations: VacDay[] = [
|
||||||
|
{
|
||||||
|
id: 'test-id',
|
||||||
|
type: SelectableDayType.CP,
|
||||||
|
numberOfDays: 5,
|
||||||
|
expiryDate: new Date(),
|
||||||
|
},
|
||||||
|
];
|
||||||
service.vacationNumberSignal.set(newVacations);
|
service.vacationNumberSignal.set(newVacations);
|
||||||
expect(service.vacationNumberSignal()).toEqual(newVacations);
|
expect(service.vacationNumberSignal()).toEqual(newVacations);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should create a new vacation day', () => {
|
||||||
|
const newDay = service.createVacationDay();
|
||||||
|
expect(newDay.id).toBeDefined();
|
||||||
|
expect(newDay.type).toBe(SelectableDayType.CP);
|
||||||
|
expect(newDay.numberOfDays).toBe(1);
|
||||||
|
expect(newDay.expiryDate).toBeInstanceOf(Date);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Injectable, signal, PLATFORM_ID, inject } from '@angular/core';
|
import { Injectable, signal } from '@angular/core';
|
||||||
import { VacationsNumber } from './calendar-service';
|
import { SelectableDayType, VacDay } from './calendar-service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -9,13 +9,44 @@ export class UserInputService {
|
|||||||
return Math.floor(Math.random() * 9) + 1;
|
return Math.floor(Math.random() * 9) + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private getInitialValues(): VacationsNumber {
|
private getInitialValues(): VacDay[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
type: SelectableDayType.CP,
|
||||||
|
numberOfDays: this.getRandomNumber(),
|
||||||
|
// today + 365 days
|
||||||
|
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
type: SelectableDayType.RTT,
|
||||||
|
numberOfDays: this.getRandomNumber(),
|
||||||
|
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
type: SelectableDayType.OTHER,
|
||||||
|
numberOfDays: this.getRandomNumber(),
|
||||||
|
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public createVacationDay(): VacDay {
|
||||||
return {
|
return {
|
||||||
cp: this.getRandomNumber(),
|
id: crypto.randomUUID(),
|
||||||
rtt: this.getRandomNumber(),
|
type: SelectableDayType.CP,
|
||||||
other: this.getRandomNumber(),
|
numberOfDays: 1,
|
||||||
|
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
readonly vacationNumberSignal = signal<VacationsNumber>(this.getInitialValues());
|
readonly vacationNumberSignal = signal<VacDay[]>(this.getInitialValues());
|
||||||
|
readonly remainingVacationDaysSignal = signal<VacDay[]>([]);
|
||||||
|
readonly computeTriggerSignal = signal(0);
|
||||||
|
|
||||||
|
public requestComputation(): void {
|
||||||
|
this.computeTriggerSignal.update((count) => count + 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
+10
-9
@@ -1,18 +1,19 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8" />
|
||||||
<title>VacOptimizer</title>
|
<title>VacOptimizer</title>
|
||||||
<base href="/">
|
<base href="/" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
<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
|
||||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
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>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<app-root></app-root>
|
<app-root></app-root>
|
||||||
</body>
|
</body>
|
||||||
|
</html>
|
||||||
</html>
|
|
||||||
+1
-2
@@ -2,7 +2,6 @@ import { BootstrapContext, bootstrapApplication } from '@angular/platform-browse
|
|||||||
import { App } from './app/app';
|
import { App } from './app/app';
|
||||||
import { config } from './app/app.config.server';
|
import { config } from './app/app.config.server';
|
||||||
|
|
||||||
const bootstrap = (context: BootstrapContext) =>
|
const bootstrap = (context: BootstrapContext) => bootstrapApplication(App, config, context);
|
||||||
bootstrapApplication(App, config, context);
|
|
||||||
|
|
||||||
export default bootstrap;
|
export default bootstrap;
|
||||||
+1
-2
@@ -2,5 +2,4 @@ import { bootstrapApplication } from '@angular/platform-browser';
|
|||||||
import { appConfig } from './app/app.config';
|
import { appConfig } from './app/app.config';
|
||||||
import { App } from './app/app';
|
import { App } from './app/app';
|
||||||
|
|
||||||
bootstrapApplication(App, appConfig)
|
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
|
||||||
.catch((err) => console.error(err));
|
|
||||||
+1
-3
@@ -41,9 +41,7 @@ app.use(
|
|||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
angularApp
|
angularApp
|
||||||
.handle(req)
|
.handle(req)
|
||||||
.then((response) =>
|
.then((response) => (response ? writeResponseToNodeResponse(response, res) : next()))
|
||||||
response ? writeResponseToNodeResponse(response, res) : next(),
|
|
||||||
)
|
|
||||||
.catch(next);
|
.catch(next);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+3
-9
@@ -4,14 +4,8 @@
|
|||||||
"extends": "./tsconfig.json",
|
"extends": "./tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": "./out-tsc/app",
|
"outDir": "./out-tsc/app",
|
||||||
"types": [
|
"types": ["node"]
|
||||||
"node"
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"include": [
|
"include": ["src/**/*.ts"],
|
||||||
"src/**/*.ts"
|
"exclude": ["src/**/*.spec.ts"]
|
||||||
],
|
|
||||||
"exclude": [
|
|
||||||
"src/**/*.spec.ts"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
+1
-1
@@ -31,4 +31,4 @@
|
|||||||
"path": "./tsconfig.spec.json"
|
"path": "./tsconfig.spec.json"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+3
-7
@@ -4,11 +4,7 @@
|
|||||||
"extends": "./tsconfig.json",
|
"extends": "./tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": "./out-tsc/spec",
|
"outDir": "./out-tsc/spec",
|
||||||
"types": [
|
"types": ["jasmine"]
|
||||||
"jasmine"
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"include": [
|
"include": ["src/**/*.ts"]
|
||||||
"src/**/*.ts"
|
}
|
||||||
]
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user