# PRESTAKIT : Upgrading from v18 to v19

To migrate your project from `prestakit` v18 to v19, you need to migrate prestations-ng and prestations-be, as usual.
But to migrate to prestations-be v19, you need to migrate your project to Spring Boot 4 / Java 25.

Let's start by migrating to Spring Boot 4 / prestations-be v19.

## PRESTATIONS-BE (via parent - Spring boot 4 / java 25)

From here on, we are in the root folder of your project, for example ~/git/cybsdk/skeleton.

### Spring Boot 4

You can switch to Java 25 `jdk25` + change in IntelliJ: right-click on your project > Open Module Settings > Project > set "SDK" to `jdk25` from devtools and "Language
level" to `25` in "Modules"

Use the latest application-parent v15+ in your `pom.xml`.

You can use this OpenRewrite recipe to simplify the migration (run with java 25).

```bash
source ~/devtools/fordev.sh 25 20
mvn -U org.openrewrite.maven:rewrite-maven-plugin:run -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-spring:RELEASE -Drewrite.activeRecipes=org.openrewrite.java.spring.boot4.UpgradeSpringBoot_4_0 -Pnof,noft
```

#### Fixes

Fix `application.properties`:

```diff
# Remove the following properties if they were added by the recipe
spring.liquibase.password=${spring.datasource.password}
spring.liquibase.username=${spring.datasource.username}
Replace the `spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS` property with `spring.jackson.datatype.datetime.write-dates-as-timestamps` if it was not already done by the recipe
```

If the following plugin with Lombok path was added by the recipe, remove this plugin:

```xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.40</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>
```

If the code uses `AutoConfigureMockMvc`, add:

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc-test</artifactId>
    <scope>test</scope>
</dependency>
```

And replace the old `AutoConfigureMockMvc` import, which is not recognized anymore, with the new one.

If you use Spring/Hibernate dependencies in `pom.xml` (like `hibernate-jpamodelgen`), check the Spring Boot 4 migration
guide to see if it has been replaced by another library: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.0-Migration-Guide

### LDAP

if you use ldap, you should replace `spring-ldap-core` by `spring-boot-starter-ldap` in your `pom.xml` to maintain the LDAP health indicator.

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-ldap</artifactId>
</dependency>
```

### Jackson migration

With Spring Boot 4, Jackson 3 is now used instead of Jackson 2, so we need to replace the previous Jackson 2 classes.
Replace `com.fasterxml.jackson.databind.ObjectMapper` with `tools.jackson.databind.json.JsonMapper`.

### BO : Package renaming

- `ch.vd.cyberadminbe.jms` has been moved to `ch.vd.cyber.backofficebe.jms`
- `ch.vd.cyberadminbe.security` has been moved to `ch.vd.cyber.backofficebe.security`
- `ch.vd.cyberadminbe.editique` has been moved to `ch.vd.cyber.backofficebe.editique`
- `cyberadminbe.config.CyberAdminBeEsbHttpConfig` has been renamed to `backofficebe.config.BoCommonEsbHttpConfig`

### BO : Brave Tracer

If you are using Brave Tracer (search `brave.Tracer` in the code, usually in backoffices), you need to replace it with
OpenTelemetry by adding the following dependencies (already included by `ch.vd.cyber:starter-bo-jdbc-jms` and `ch.vd.cyber:starter-prestation`):

```xml
<!-- Tracing -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-micrometer-tracing-opentelemetry</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
```

And replace `brave.Tracer` imports by `io.micrometer.tracing.Tracer`;

#### BO : EsbMessageListenerWithSleuthIntegration

This base class has been moved from `ch.vd.cyber.sdk:cyberadmin-be` to `ch.vd.cyber.sdk:backoffice-be`
and renamed `EsbMessageListenerWithTracingPropagation`.

The constructor has also been updated :

```java
import ch.vd.cyberadminbe.jms.EsbMessageListenerWithSleuthIntegration;
import brave.Tracer;

public class MyListener extends EsbMessageListenerWithSleuthIntegration {
    public MyListener(final EsbJmsTemplate nozipEsbTemplate,
                      final Tracer tracer) {
        super(nozipEsbTemplate, tracer);
    }
}
```

should now be :

```java
import ch.vd.cyber.backofficebe.jms.EsbMessageListenerWithTracingPropagation;
import io.micrometer.tracing.propagation.Propagator;
import io.micrometer.tracing.Tracer;

public class MyListener extends EsbMessageListenerWithTracingPropagation {
    public MyListener(final EsbJmsTemplate nozipEsbTemplate,
                      final Tracer tracer,
                      final Propagator propagator) {
        super(nozipEsbTemplate, tracer, propagator);
    }
}
```

Finally, if you have mock issues with your integration tests, you can use `ch.vd.cyber.backofficebe.jms.JmsTestUtils.mockTracingPropagation(final Tracer tracerMock, final Propagator propagatorMock)`

### BO : ESB Integration

- Check that you should always create your ListenerContainer with `ch.vd.cyber.backofficebe.jms.EsbConfigUtils.createDefaultMessageListenerContainer(...)`
    - This simplifies the configuration and ensures that the correct `MessageListenerContainer` is used with the new tracing integration.

### Property migration

Run your application with this dependency :

```
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-properties-migrator</artifactId>
    <scope>runtime</scope>
</dependency>
```

Look for logs that indicate properties you should migrate (watch for WARN logs of class PropertiesMigrationListener), update them and remove the dependency

### BO using jpa repositories

As we also have jdbc in the classpath, to avoid having dozens of logs like "Spring Data JDBC - Could not safely
identify store assignment for repository candidate interface", add the property in your application.properties :

`spring.data.jdbc.repositories.enabled=false`

### BO using json payloads with primitives properties

`spring.jackson.deserialization.fail-on-null-for-primitives=false`
or update all concerned payloads to use wrapper classes instead of primitives.

### Debugging tips

Spring boot 4 doesn't support calling a controller with a trailing slash, fix the url called (/api/ping != /api/ping**/**)

### Clean Sonar code smells

You can use the following OpenRewrite recipes to clean Sonar code smells. It is recommended to do it after the migration to avoid mixing the migration changes with code cleaning changes, and to make it easier to review.

```bash
mvn -U org.openrewrite.maven:rewrite-maven-plugin:run -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-testing-frameworks:RELEASE -Drewrite.activeRecipes=org.openrewrite.java.testing.junit.JUnit6BestPractices, -Pnof,noft

mvn -U org.openrewrite.maven:rewrite-maven-plugin:run -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-static-analysis:RELEASE -Drewrite.activeRecipes=org.openrewrite.staticanalysis.CommonStaticAnalysis -Pnof,noft

mvn -U org.openrewrite.maven:rewrite-maven-plugin:run --define rewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-testing-frameworks:RELEASE --define rewrite.activeRecipes=org.openrewrite.java.testing.mockito.MockitoBestPractices --define rewrite.exportDatatables=true -Pnof,noft

mvn -U org.openrewrite.maven:rewrite-maven-plugin:run -Drewrite.activeRecipes=org.openrewrite.java.RemoveUnusedImports -Pnof,noft
```

Take a look at Sonar to see other things that you can improve or ignore.

### Postfinance 9.5.0

Since prestations-be 19.0.3, Postfinance dependency was updated to 9.5.0. Methods signatures and package have moved
but it is the only change that needs to be made on your application. The rest is handled by prestations-be.

You can run the renaming in your application :

```bash
grep -rl 'ch\.postfinance\.sdk' --include='*.java' . \
  | xargs perl -pi -e 's/\bch\.postfinance\.sdk\b/ch.postfinancecheckout.sdk/g'
```

## PRESTATIONS-NG

For the commands in this guide, it is assumed that you are in the `front` folder of your project.

The main feature in `prestations-ng` v19 is the update of the `@angular/*` peer dependencies
to `^21.2.14`, using `node 22+` to build, `npm 10+` as package manager, and `Foehn 2+ (Bootstrap 5+)` for our design system.

There are a lot of breaking changes because our library has migrated to **standalone** components, **signals**, and the **inject function** instead of constructor injection parameters.

> 🚨 **Read carefully the following [PITFALLS](ANGULAR_SIGNALS.md#common_pitfalls), especially points 4, 6 & 8**

> 🚨 **When working in a `multi-project` repository and `.husky` folder exists, delete `_` folder in `.husky` to be able to commit**

### Migrate to ESLint

💡 **NB : you can skip this step if you already have a `front/.eslintrc.json` file, it means it is already done.**

Follow [our migration guide](ESLINT_MIGRATION_GUIDE.md) to migrate your project from TSLint to ESLint.

### Upgrade to Angular 20

Just FYI if you are curious about the details, you can find the Angular update guide at this address [https://angular.dev/update-guide?v=19.0-20.0&l=1](https://angular.dev/update-guide?v=19.0-20.0&l=1)

💡 **NB: Commit before continuing so your repository is clean.**

Remove your `resolutions` in `package.json` before starting: if you have `resolutions` in `package.json`, remove the section manually.

In the next commands, commit before each ng update.

```bash
npm install
npm install @angular/cli@19 -g
ng update @angular/core@19 @angular/cli@19
ng update @dsivd/prestations-ng@18
```

#### Switch to node 22+

##### If you are using our `slave-apps`

Be sure to update your `slave-apps` git repository and source your `.bashrc` (or whatever file you're using).

Verify your node version in your terminal by executing:

```bash
node -v
```

💡 **NB: If the version is still v20+ by default, type `node22` in your terminal to switch to node v22+**

```bash
node22
```

##### If you are NOT using our `slave-apps`

Be sure to use a node version 22+ in your terminal:

```bash
node -v
```

##### IntelliJ node version

Change the IntelliJ Node.js version to 22+ by going to

- `File > Settings > Languages & Frameworks > TypeScript` and selecting a node version 22+ in `Node runtime`.
- `File > Settings > Languages & Frameworks > JavaScript Runtime` and selecting a node version 22+ in `Node runtime`.

#### Continue with Angular 20 migration

```bash
npm install @angular/cli@20 -g
ng update @angular/core@20 @angular/cli@20
```

- When asked "Select the migrations that you'd like to run",
    - accept **"use-application-builder"** by hitting "Space" key
    - hit "Enter" key
- When asked "Select the migrations that you'd like to run",
    - accept **"control-flow-migration"** by hitting "Space" key
    - hit "Down arrow" key
    - accept **"router-current-navigation"** by hitting "Space" key
    - hit "Enter" key

🚨 **IMPORTANT: Search for every `@for` in your project and check that `track` statement is present and has a unique identifier.
When a unique identifier such as `id` is not possible, track by object or as a last resort use `track $index`.**

💡 **NB: When using `@angular/cdk` in your project**

```bash
ng update @angular/cdk@20
```

NB: you might need to use the `--force` option

### Running with node 22+

#### In your project

Update your `package.json` file to specify the node engine:

```json
{
    "engines": {
        "node": ">=22.18.0"
    }
}
```

#### Update your jenkins files

- Change `nodeVersion: 20` to use node 22

##### UT folder

```diff
buildAppPipelinePodmanUT([
-   jdk: 21,
+   jdk: 25,
-   node: 20,
+   node: 22,
])
```

### Upgrade to Angular 21

`prestations-ng` **v19+** now supports **Angular v21**.

Just FYI if you are curious about the details, you can find the Angular update guide at this address [https://angular.dev/update-guide?v=20.0-21.0&l=1](https://angular.dev/update-guide?v=20.0-21.0&l=1)

💡 **NB: Commit before continuing so your repository is clean.**
💡 **NB: When using `ngx-matomo-client` in your project, you will need to add `--force` to `ng update @dsivd/prestations-ng` and `npm install @types/node@22 ts-node@10`**

```bash
npm install @angular/cli@21 -g
ng update @dsivd/prestations-ng@latest
```

- When asked again "Select the migrations that you'd like to run"
    - accept **"router-current-navigation"** by hitting "Space" key
    - hit "Enter" key

```bash
ng update @angular/cli@21
```

- When asked "Select the migrations that you'd like to run"
    - accept **"use-application-builder"** by hitting "Space" key
    - hit "Enter" key

```bash
npm install @types/node@22 ts-node@10
```

💡 **NB: When using `@angular/cdk` in your project**

```bash
ng update @angular/cdk@21
```

💡 **NB: When using `ngx-matomo-client` in your project**

```bash
ng update ngx-matomo-client@9
```

💡 **NB: Upgrade all other libraries needed by your project (such as: primeng, lodash, ...) to their latest version compatible with angular 21**

### Quick fix

- In all custom components extending `FoehnInputComponent`, in `providers` providing `FoehnInputComponent` remove `multi: true,`.

```diff
{
   provide: FoehnInputComponent,
   useExisting: forwardRef(() => ItemListComponent),
-  multi: true,
}
```

- In your `.eslintrc.json`, remove `"/src/main.ts",` from `ignorePatterns`.
- In `main.ts`, replace `platformBrowserDynamic` by `platformBrowser`.
- When using `<foehn-list-summary` component, replace `[list]` by `[(model)]` (with double binding to handle item being removed).

### Now fix your project before continuing

🚨 **IMPORTANT: Fix your project because our new prestations-ng v19+ is standalone, uses signals instead of observables, and uses the inject function instead of constructor injection parameters.**

- Only keep `modules` related to your application, such as `AppRoutingModule`.
- Remove all other imports of **modules** and make sure you are using the new **standalone components** by adding them directly from your template (Alt+Enter). You can search for `<foehn-` with a file mask `*.html` to help you find standalone components.
- Add `providePrestationsNgCore(),` to the `providers` array of your `app.module.ts` file.
- Check every `constructor` in your project and remove unused `constructor` parameters (like `ActivatedRoute` in components extending `AbstractPageComponent`).

Run the following command until you have no more errors.

```bash
npm run build
```

💡 **TIP: If your IntelliJ is still showing you errors on `@if` or `@for`, close it and re-open it to fix.**

### Migrate to inject function

```bash
ng generate @angular/core:inject
```

✔ Which directory do you want to migrate? **./**

✔ Do you want to migrate abstract classes? Abstract classes are not migrated by default, because their parameters aren't guaranteed to be injectable. **Yes**

✔ Do you want to clean up all constructors or keep them backwards compatible? Enabling this option will include an additional signature of `constructor(...args:
 unknown[]);` that will avoid errors for sub-classes, but will increase the amount of generated code by the migration. **No**

✔ Do you want optional inject calls to be non-nullable? Enable this option if you want the return type to be identical to @Optional(), at the expense of worse
type safety. **Yes**

Then:

- Go through every file that has changed and fix what is broken.
- Reorder public / private and remove unused imports so ESLINT is happy again.

Little example of cleaning when extending `AbstractPageComponent`:

Before:

```ts
sessionInfoData: SessionInfoWithApplicationService;

constructor(
    protected override activatedRoute: ActivatedRoute,
    private readonly dictionaryService: SdkDictionaryService,
    sessionInfoData: SessionInfoWithApplicationService
) {
    super(activatedRoute);
    this.sessionInfoData = sessionInfoData;
}
```

After:

```ts
sessionInfoData = inject(SessionInfoWithApplicationService);

private readonly dictionaryService = inject(SdkDictionaryService);
```

Most of the time, you can remove `activatedRoute` because it was used as a constructor parameter for `AbstractPageComponent`.

### Migrate to self-closing tags

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:self-closing-tag
```

✔ Which directory do you want to migrate? **./**

### Migrate to standalone

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

💡 **TIP: Check [Migrating from NgModules](COMPONENTS.md#migrating_from_ngmodules) for more information before running the following commands.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:standalone
```

Choose **"Convert all components, directives and pipes to standalone"** then

✔ Which directory do you want to migrate? **./**

```bash
npm run build
```

```bash
ng generate @angular/core:standalone
```

Choose **"Remove unnecessary NgModule classes"** then

✔ Which directory do you want to migrate? **./**

```bash
npm run build
```

```bash
ng generate @angular/core:standalone
```

Choose **"Bootstrap the application using standalone APIs"** then

✔ Which directory do you want to migrate? **./**

#### Now check and fix manually the migration of your `app.component.ts` to standalone

It should look like that:

```diff
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
-   // eslint-disable-next-line @angular-eslint/prefer-standalone
-   standalone: false
+   imports: [
+       RouterOutlet,
+       NgHttpLoaderComponent,
+       RedirectComponent,
+   ]
})
```

Create a file under `src/app` called `app.routes.ts` with the following content:

```ts
export const routes: Routes = [
    // Your routes found in app-routing.module.ts go here
];
```

Create a file under `src/app` called `app.config.ts` with the following content or adapt it to your needs:

```ts
export const appConfig: ApplicationConfig = {
    providers: [
        provideZoneChangeDetection(),
        providePrestationsNgCore(),
        provideRouter(routes),
        META_SERVICE_PROVIDER,
        provideHttpClient(
            withInterceptors([pendingRequestsInterceptor$]),
            withXsrfConfiguration({
                cookieName: 'XSRF-TOKEN',
                headerName: 'X-XSRF-TOKEN',
            }),
        ),
    ],
};
```

Now replace the content of `main.ts` with the following content:

```ts
import { bootstrapApplication } from '@angular/platform-browser';

import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

bootstrapApplication(AppComponent, appConfig).catch((err) =>
    console.error(err),
);
```

Clean up your project by removing `app-routing.module.ts` and `app.module.ts` files if they have not already been removed.

#### Migration to lazy-loaded routes when working with large applications

You may have some other modules that are lazy-loaded. Just be sure that all your components are standalone before continuing.

> You can run the following command to convert eagerly loaded component routes to lazy loaded routes. This allows the build process to split the production bundle into smaller chunks, to avoid a big JS bundle that includes all routes, which negatively affects initial page load of an application.

> This migration will also collect information about all the components declared in NgModules and output the list of routes that use them (including corresponding location of the file). Consider making those components standalone.

```bash
ng generate @angular/core:route-lazy-loading
```

Here is an example when doing it manually because schematic above does not work as intended:

Your `app.routes.ts` file should look something like this:

```ts
const routes: Routes = [
    {
        path: '',
        component: PageWrapperComponent,
        data: { root: true },
        children: [
            {
                path: 'demandes',
                loadChildren: () =>
                    import('./modules/demandes/demandes.module').then(
                        (m) => m.DemandesModule,
                    ),
            },
            { path: '404', component: FoehnNotfoundComponent },
            { path: '', redirectTo: 'demandes', pathMatch: 'full' },
            { path: '**', redirectTo: '/404', pathMatch: 'full' },
        ],
    },
];
```

Now, navigate to `DemandesModule`, at the same file level as `demandes.module.ts`, you create a `demandes.routes.ts` file with the following content:

```ts
export const demandes_routes: Routes = [
    // Your routes found in demandes.module.ts go here
];
```

Then replace `loadChildren: () => import('./modules/demandes/demandes.module').then(m => m.DemandesModule)` by `loadChildren: () => import('./modules/demandes/demandes.routes').then(m => m.demandes_routes)`.

Now you can safely delete `demandes.module.ts` as all components are `standalone` now.

---

You can `lazy-load` components as well, for example:

```diff
export const demandes_routes: Routes = [
-   { path: 'list', component: DemandeListPageComponent },
+   { path: 'list', loadComponent: () => import('./demande-list-page/demande-list-page.component').then(m => m.DemandeListPageComponent) },
];
```

### Migrate from NgClass to class bindings

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:ngclass-to-class
```

✔ Which directory do you want to migrate? **./**

✔ Should the migration also migrate space-separated keys? **Yes**

- Check every file that has changed and fix what is broken.
- Check remaining `ngClass` usage in your project and replace it with class bindings.

**Be aware that `[class]` replaces all element classes. When you have static classes, concatenate them with dynamic ones.**

Replacement example:

Before:

```html
[ngClass]="isLabelSrOnly ? 'visually-hidden' : 'vd-p'"
```

After:

```html
[class.visually-hidden]="isLabelSrOnly()" [class.vd-p]="!isLabelSrOnly()"
```

---

Before:

```html
class="modal" [ngClass]="modalSize"
```

After:

```html
[class]="'modal ' + modalSize()"
```

---

Before:

```html
class="form-label" [ngClass]="isLabelSrOnly() ? 'visually-hidden' :
labelStyleModifier()"
```

After:

```html
[class]="'form-label ' + (isLabelSrOnly() ? 'visually-hidden' :
(labelStyleModifier() ?? ''))"
```

### Migrate from NgStyle to style bindings

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:ngstyle-to-style
```

✔ Which directory do you want to migrate? **./**

✔ Should the migration also migrate object references? **No**

- Check every file that has changed and fix what is broken.
- Check remaining `ngStyle` usage in your project and replace it with style bindings.

### Convert CommonModule usage to standalone imports

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:common-to-standalone
```

✔ Which directory do you want to migrate? **./**

- Check every file that has changed and fix what is broken.

### Migrate @HostListener

Search for `@HostListener` in your project and replace it with the `host` object in the `@Component` or `@Directive` decorator.

For example, when using `@HostListener` in a directive:

Before:

```ts
@Directive({
    selector: '[numberCurrencyFormatter]',
})
export class NumberCurrencyFormatterDirective implements OnInit {
    @HostListener('blur', ['$event.target.value'])
    onBlur(value: string): void {
        this.hasFocus = false;
        this.setFormatting(value);
    }
}
```

After:

```ts
@Directive({
    selector: '[numberCurrencyFormatter]',
    host: {
        '(blur)': 'onBlur($event)',
    },
})
export class NumberCurrencyFormatterDirective implements OnInit {
    onBlur(event: FocusEvent): void {
        this.hasFocus = false;
        const value = (event.target as HTMLInputElement).value;
        this.setFormatting(value);
    }
}
```

### Migrate to signal queries

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:signal-queries-migration --insert-todos
```

✔ Which directory do you want to migrate? **./**

✔ Do you want to migrate as much as possible, even if it may break your build? **No**

- Check every file that has changed and fix what is broken.
- Check every remaining `@ViewChild`, `@ViewChildren`, `@ContentChild`, and `@ContentChildren` usage in your project and replace them with signal queries.
- Check every **TODO** comment added by the migration and fix them.

### Migrate to output functions

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:output-migration
```

✔ Which directory do you want to migrate? **./**

Check every remaining `@Output` usage in your project and replace them with output function.

When needing to subscribe to an output, you can use `outputToObservable` from `@angular/core/rxjs-interop`.

### Migrate to input signals

Check our [Angular signals guide](ANGULAR_SIGNALS.md) for more information about signals and input signals.

🚨 **WARNING: The following command will work only when your application compiles without errors. If you have errors, fix them before continuing.**

```bash
npm run build
```

Fix remaining errors and warnings, then run the following command:

```bash
ng generate @angular/core:signal-input-migration --insert-todos
```

✔ Which directory do you want to migrate? **./**

✔ Do you want to migrate as much as possible, even if it may break your build? **No**

- Check every file that has changed and fix what is broken.
- Check every remaining `@Input` usage in your project and replace them with input signals.
- Check every **TODO** comment added by the migration and fix them.

### Migrate to vitest

[Angular migration guide: migrating to Vitest](https://angular.dev/guide/testing/migrating-to-vitest)

```bash
npm install --save-dev vitest jsdom
```

In your `angular.json` file, remove `"zone.js/dist/zone-error"` from `"allowedCommonJsDependencies"`

then find the `test` target for your project and change the `builder` to `@angular/build:unit-test` and add following options:

```json
{
    "projects": {
        "your-project-name": {
            "architect": {
                "test": {
                    "builder": "@angular/build:unit-test",
                    "options": {
                        "buildTarget": "your-project-name:build"
                    }
                }
            }
        }
    }
}
```

In your package.json file, add the following scripts:

```diff
{
    "scripts": {
-       "test": "ng test",
+       "test": "ng test --watch=false",
    }
}
```

In your `tsconfig.spec.json` file, remove from `types` `jasmine` and `node` and add `vitest/globals`:

```diff
{
    "compilerOptions": {
        "types": [
-           "jasmine",
-           "node"
+           "vitest/globals"
        ]
    }
}
```

In your `.gitignore` file, add the following line to ignore the `screenshot` folder:

```
__screenshots__
```

Now remove karma and jasmine dependencies

```bash
npm uninstall jasmine jasmine-core jasmine-spec-reporter
npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter
npm uninstall puppeteer
npm uninstall @types/jasmine @types/jasminewd2
rm karma.conf.js
```

- search for `karma.conf.js` in your project and remove all references to it.
- search for `protractor.conf.js` in your project and remove them if they still exist.

Then run the following command to migrate from jasmine to vitest:

```bash
ng g @schematics/angular:refactor-jasmine-vitest --no-report
```

Now you can run your tests with `npm test` and check that everything is up and running.

In your tests, replace `waitForAsync(() => ...)` by `async(...)` and add `await` before `TestBed.configureTestingModule`.
For example, replace this:

Before:

```ts
import {
    provideHttpClient,
    withInterceptorsFromDi,
} from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { AppModule } from './app.module';

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
            imports: [AppModule, RouterModule.forRoot([])],
            providers: [
                provideHttpClient(withInterceptorsFromDi()),
                provideHttpClientTesting(),
            ],
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});
```

After:

```ts
import {
    provideHttpClient,
    withInterceptorsFromDi,
} from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';

import { AppComponent } from './app.component';

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            imports: [AppComponent],
            providers: [
                provideHttpClient(withInterceptorsFromDi()),
                provideHttpClientTesting(),
                provideRouter([]),
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        await fixture.whenStable();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});
```

#### Running fakeAsync tests using spyOnProperty with Vitest

Example of transformation:

```diff
beforeEach(() => {
-   spyOnProperty(sessionInfo, 'data').and.returnValue(of(sessionInfoData));
+   vi.spyOn(sessionInfo, 'data', 'get').mockReturnValue(of(sessionInfoData));
});

- it('should properly map the initial data', fakeAsync(() => {
+ it('should properly map the initial data', async () => {
    const form = new MenuOrderForm();
-   service.enrichWithSessionInfoData(form);
-   tick(200);
+   await firstValueFrom(service.enrichWithSessionInfoData(form));

    // expect(...) here
- }));
+ });
```

### Migrate to eslint flat configuration

```bash
npm uninstall @angular-eslint/builder @angular-eslint/eslint-plugin @angular-eslint/eslint-plugin-template @angular-eslint/template-parser
npm uninstall @typescript-eslint/eslint-plugin @typescript-eslint/parser @typescript-eslint/types @typescript-eslint/utils
npm uninstall eslint-import-resolver-typescript eslint-plugin-cypress eslint-plugin-import eslint-plugin-jasmine eslint-plugin-rxjs eslint-plugin-rxjs-angular eslint-plugin-simple-npm eslint-plugin-simple-import-sort
npm uninstall eslint

npm install --save-dev eslint@^9 angular-eslint@21 typescript-eslint@^8
npm install --save-dev @typescript-eslint/parser@8 @smarttools/eslint-plugin-rxjs@1
npm install --save-dev eslint-plugin-simple-import-sort@13
npm install --save-dev eslint-config-prettier@10
npm install --save-dev eslint-plugin-import-x@4
npm install --save-dev prettier
```

In your `front` folder, add a `.prettierrc` file with the following content:

```json
{
    "printWidth": 100,
    "singleQuote": true,
    "arrowParens": "always",
    "trailingComma": "all",
    "htmlWhitespaceSensitivity": "css",
    "overrides": [
        {
            "files": ["*.html"],
            "options": {
                "parser": "angular"
            }
        }
    ]
}
```

Add a `.prettierignore` file with the following content:

```text
node_modules
.git
target
package.json
package-lock.json
dist
coverage
.angular
```

Remove your old `.eslintrc.json` file in your `front` folder:

```bash
rm .eslintrc.json
```

- search for `.eslintrc.json` in your project and remove them.
- add a new `eslint.config.mjs` file with the following content:

```ts
// @ts-check
import prettier from 'eslint-config-prettier';
import tseslint from 'typescript-eslint';
import angular from 'angular-eslint';

import prestationsNg from '@dsivd/prestations-ng/eslint';

export default tseslint.config(
    {
        ignores: ['**/coverage/**', '**/dist/**'],
    },

    // ─── TypeScript ────────────────────────────────────────────────────────────
    {
        files: ['**/*.ts'],
        extends: [...prestationsNg.configs.tsRecommended],
        languageOptions: {
            parserOptions: {
                projectService: true,
                tsconfigRootDir: import.meta.dirname,
            },
        },
        processor: angular.processInlineTemplates,
    },

    // ─── HTML templates ────────────────────────────────────────────────────────
    {
        files: ['**/*.html'],
        extends: [...prestationsNg.configs.templateRecommended],
    },

    // ─── Prettier (must be last — disables formatting rules) ───────────────────
    prettier,
);
```

That is the whole file. The two `*Recommended` configs come from the library and carry
everything: the `eslint`, `typescript-eslint` and `angular-eslint` baselines, the template
accessibility set, the naming and import conventions, and the rules written by the library
itself. You declare no `plugins` and list no rule.

The packages installed above are still required — the library's config imports them from your
`node_modules` rather than shipping its own copies. For the same reason, do **not** spread
`angular.configs.tsRecommended` or `angular.configs.templateRecommended` yourself: they are
already included, and declaring the same plugin twice from two different copies makes ESLint
fail outright.

#### prestations-ng ESLint rules

The library ships **shareable custom configs** that are auto-updatable with the library version. Two
rules are enabled today — `no-direct-signal-mutation` and `no-uninvoked-signal-in-template` — and both
are documented in [the plugin guide](ESLINT_PLUGIN.md), alongside the leaner `tsRules` / `templateRules`
configs for a project that supplies its own style.

One consequence to keep in mind:

- A rule added — or tightened — in a later version of the library lands in the config, so
  `npm update` **will make your lint fail** on the offending code. That is the point — it is
  how a practice is rolled out to every project. Each addition is listed in the
  [CHANGELOG](CHANGELOG.md), and a rule you cannot fix right away can be turned off in your
  own `rules` block, which is applied after the shared config:

    ```ts
    rules: {
        '@dsivd/prestations-ng/no-direct-signal-mutation': ['off'],
    },
    ```

#### Delete `typings.d.ts`

In `front/src/`, remove the file `typings.d.ts` if it is still there.

#### Update your tsconfig\*.json files

- Replace your `tsconfig.json` content with:

```json
{
    "compileOnSave": false,
    "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "noImplicitOverride": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "sourceMap": true,
        "declaration": false,
        "experimentalDecorators": true,
        "useDefineForClassFields": false,
        "moduleResolution": "bundler",
        "importHelpers": true,
        "isolatedModules": true,
        "target": "ES2022",
        "module": "ES2022",
        "paths": {
            "@dsivd/prestations-ng": ["./node_modules/@dsivd/prestations-ng"]
        }
    },
    "angularCompilerOptions": {
        "enableI18nLegacyMessageIdFormat": false,
        "strictInjectionParameters": true,
        "strictInputAccessModifiers": true,
        "strictTemplates": true,
        "strictStandalone": true
    },
    "files": [],
    "references": [
        {
            "path": "./tsconfig.app.json"
        },
        {
            "path": "./tsconfig.spec.json"
        }
    ]
}
```

- Replace your `tsconfig.app.json` content with:

```json
{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": []
    },
    "include": ["src/**/*.ts"],
    "exclude": ["src/**/*.spec.ts"]
}
```

- Update your package.json, add the following script to run eslint:

```diff
"scripts": {
-   "lint": "ng lint",
+   "lint": "ng lint --fix=true",
+   "format:prettier": "prettier --config ./.prettierrc --write \"{,!(.scannerwork|target|coverage|node_modules|.angular)/**/}*{.ts,.js,.jsx,.json,.css,.scss,.md,.html}\"",
}
```

### Husky pre-commit hook

💡 **Tip: For multi-projects, see section below `Husky pre-commit hook for multi-project repository`**

```bash
npm install --save-dev husky lint-staged
npx husky init
echo "cd front" > .husky/pre-commit
echo "npx lint-staged" >> .husky/pre-commit
chmod +x .husky/pre-commit
mv ./.husky ../.husky
git add -A
```

- In your `package.json`, modify `prepare` script to run husky from the parent folder:

```diff
- "prepare": "husky"
+ "prepare": "cd .. && husky"
```

Then run:

```bash
npm install
```

You should see in your project root folder `.husky` a new folder `_`.

#### Husky pre-commit hook for multi-project repository

💡 **Tip: Skip this part if you are not in a multi-project repository and follow section `Husky pre-commit hook`**
🚨 **WARNING: You need to repeat this section for every "child" project**

```bash
npm install --save-dev husky lint-staged
npx husky init
chmod +x .husky/pre-commit
```

---

🚨 **WARNING: To be done in your "child" project folder only when migrating your first project. For other projects, you can skip this step and remove the `.husky` folder in your "child" project folder.**

```bash
mv ./.husky ../../.husky
git add -A
```

Replace `.husky/pre-commit` content with the following:

```bash
projects=$(git diff --cached --name-only --diff-filter=ACMR | awk -F'/' '{print $1}' | sort -u)

for project in $projects; do
  if [ -d "$project/front" ]; then
    echo "➡️  lint-staged pour $project/front"
    (cd "$project/front" && npx lint-staged) || exit 1
  fi
done
```

---

Now continue adapting your `package.json` and modify `prepare` script to run husky from the parent folder:

```diff
- "prepare": "husky"
+ "prepare": "cd ../.. && husky"
```

Then run:

```bash
npm install
```

You should see in your project root folder `.husky` a new folder `_`.

#### lint-staged

In your `package.json` file, check for existing `lint-staged` section and add/modify with the `"lint-staged"` section in the following content. If it does not exist, create it:

```json
{
    "scripts": {...},
    "lint-staged": {
        "*.ts": [
            "eslint --fix",
            "prettier --config ./.prettierrc --write"
        ],
        "*.{js,jsx,json,css,scss,md,html}": [
            "prettier --config ./.prettierrc --write"
        ]
    }
}
```

#### Manually run formatting commands

```bash
npm run format:prettier
npm run lint
```

Fix your `meta.service.ts` by replacing:

Before:

```ts
export const metaServiceFactory =
    (metaService: MetaService): Function =>
    () =>
        lastValueFrom(metaService.load());

export const META_SERVICE_PROVIDER = provideAppInitializer(() => {
    const initializerFn = metaServiceFactory(inject(MetaService));
    return initializerFn();
});
```

After:

```ts
export const META_SERVICE_PROVIDER = provideAppInitializer(() => {
    const metaService = inject(MetaService);
    return lastValueFrom(metaService.load());
});
```

Run again until no more errors:

```bash
npm run lint
```

Then:

```bash
npm run format:prettier
```

### Browsers list update

Run update schematic:

```bash
ng g @dsivd/prestations-ng:replace-browsers-list
```

### Remove deprecated packages

```bash
npm uninstall @angular/platform-browser-dynamic
npm uninstall @angular/animations
```

### Add missing `^` or `~` in `package.json` devDependencies

Check you devDependencies in your `package.json` file and add `^` in front of every version number if missing excepted for `typescript` where you should add `~`. Then run:

```bash
npm install
npm update
```

### Configure IntelliJ IDEA to use ESLint and Prettier on save

- To configure ESLint automatically in the current project, open "_File -> Settings..._" (`Ctrl+Alt+S`) and either:
    - Search for `ESLint` and check radio box "_Automatic ESLint configuration_" and check checkbox "_Run eslint --fix on save_"
    - Search for `Prettier` and check radio box "_Automatic Prettier configuration_" and check checkbox "_Run on save_"

### Language deprecations

When using `IntelliJ`, you can run code inspection on your project to fix deprecations manually. Two ways:

- IntelliJ window menu, go to: `Code > Analyze code > Run inspection by name...` (or **Ctrl+Alt+Maj+i**) and type `Deprecated symbol used`.
- Or select your project in your project panel and `right click` on it then `Analyze > Run inspection by name...` (or **Ctrl+Alt+Maj+i**) and type `Deprecated symbol used`.

### Last but not least, check if your application is working!!!

#### Be sure your application gets a fresh start

```bash
rm -rf .angular/
rm -rf node_modules/
npm install
```

#### Build and launch your application

💡 **NB: You will most probably need to fix some compilation errors such as adding `override` when needed**

```bash
npm run build
npm start
```

You're good if no errors are remaining!
Finally check if your tests run well :

```bash
npm run test
```

> 🚨 **Read carefully the following [PITFALLS](ANGULAR_SIGNALS.md#common_pitfalls), especially points 4, 6 & 8 and check again your application**

### Release your application using `jenkins-libs`

When your code has been merged/rebased onto `master`, you need to update your application in `jenkins-libs` to use node 22 instead of node 20.

See [getImtPortailApplications](https://dsigit.etat-de-vaud.ch/outils/git/projects/PEE/repos/jenkins-libs/browse/vars/getImtPortailApplications.groovy)

```diff
[
        'project': 'cybersdk',
        'name'   : 'skeleton',
        'gitUrl' : 'ssh://git@bitbucket.etat-de-vaud.ch/cybsdk/skeleton.git',
        'jdk'    : '21',
-       'node'   : '20'
+       'node'   : '22'
],
```

## RENOVATE BOT

Enroll your project in Renovate bot to automatically update your dependencies.
See [Mend Renovate CE](https://dgnsiwiki.etat-de-vaud.ch/outils/dgnsiwiki/x/7QFDgg) for more information.
