# PRESTAKIT : Upgrading from v15 to v16

## PRESTATIONS-NG

The main feature in `prestations-ng` v16 is the update of the `@angular/*` peer dependencies
to `^15.1.1` and using `node 16+` to build.

### Migrating to ESLint

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

### Running with node 16+

#### Switch to node 16+

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

Be sure to update your `slave-apps` git repository and source your bashrc (or whatever env file you're using) so you will be using node16 by default, verify by executing :

```bash
node -v
```

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

Be sure to use a node version 16+ and use the same command as above.

#### In your project

Update your `package.json` to specify node engine

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

### Updating Angular

`prestations-ng` **v16+** now supports **Angular v15**. You can follow the Angular update guide
at this address:

- [https://update.angular.io/?l=3&v=13.0-14.0](https://update.angular.io/?l=3&v=13.0-14.0)
- [https://update.angular.io/?l=3&v=14.0-15.0](https://update.angular.io/?l=3&v=14.0-15.0)

**If you encounter the following error while doing a `yarn install`:**

`error @yarnpkg/parsers@3.0.0-rc.51: The engine "node" is incompatible with this module. Expected version ">=18.12.0". Got "16.15.0" error Found incompatible module.`

add `@yarnpkg/parsers` version `3.0.0-rc.47.1` as `resolutions` in your `package.json`. Then remove it after migration.

```json
{
    "resolutions": {
        "@yarnpkg/parsers": "3.0.0-rc.47.1"
    }
}
```

#### When having migrated to ESLint

```bash
ng update @angular/core@13 @angular/cli@13

yarn global add @angular/cli@14
ng update @angular/core@14 @angular/cli@14

yarn global add @angular/cli@15
ng update @angular/core@15 @angular/cli@15 --force
ng update @angular-eslint/builder@15
ng update @angular-eslint/eslint-plugin@15 @angular-eslint/eslint-plugin-template@15 @angular-eslint/template-parser@15
ng update @typescript-eslint/eslint-plugin@5 @typescript-eslint/parser@5
ng update eslint-plugin-import eslint-plugin-jasmine eslint-plugin-jsdoc eslint-plugin-rxjs-angular
ng update eslint
ng update eslint-plugin-rxjs@5
ng update \
    @types/jasmine \
    @types/node@16 \
    ts-node@10
ng update @dsivd/prestations-ng@latest
ng g @dsivd/prestations-ng:replace-browsers-list

yarn remove eslint-plugin-prefer-arrow
yarn add eslint-plugin-simple-import-sort --dev
yarn add eslint-import-resolver-typescript --dev
# Remove your resolutions in package.json before executing 'yarn upgrade'
yarn upgrade
```

### Update "package.json" file to replace tilde(~) by caret(^) or add caret(^) when missing on following dependencies to be aligned with prestations-ng library

- @fortawesome/angular-fontawesome
- @fortawesome/fontawesome-free
- @fortawesome/fontawesome-svg-core
- @fortawesome/free-regular-svg-icons
- @fortawesome/free-solid-svg-icons
- core-js
- dayjs
- iban
- ng-http-loader
- ngx-image-cropper
- rxjs
- zone.js

Then run

```bash
yarn install
```

### Update ".eslintrc.json" file if your project was already migrated to ESLint

Replace your current `.eslintrc.json` file by the one found in [ESLINT_MIGRATION.GUIDE](ESLINT_MIGRATION_GUIDE.md#customizing_eslint__inspired_from_otia_and_prestations-ng_s_files_for_rules_)

Then run

```bash
ng lint --fix=true
```

and finally fix manually remaining errors

### Cleanup your project due to CLI improvements

See section "CLI improvements" in angular's blog (https://blog.angular.io/angular-v15-is-now-available-df7be7f2f4c8)

#### Remove files/folder from your project

- delete `/src/polyfills.ts` file (be aware that every `import ...` should be placed in `polyfills` array of `angular.json`)
- delete `/src/test.ts` file
- delete `/src/environments` folder

#### Update your `main.ts` file

```diff
-import { enableProdMode } from '@angular/core';
-import { environment } from './environments/environment';

-if (environment.production) {
-   enableProdMode();
-}
```

#### Update your `angular.json` file

```diff
{
    "projects": {
        "[YOUR_PROJECT_NAME]": {
            "architect": {
                "build": {
                    "options": {
-                       "polyfills": "src/polyfills.ts",
+                       "polyfills": [
+                           "zone.js"
+                       ],
                    },
                    "configurations": {
                        "production": {
-                           "fileReplacements": [
-                               {
-                                   "replace": "src/environments/environment.ts",
-                                   "with": "src/environments/environment.prod.ts"
-                               }
-                           ]
                        }
                    }
                },
                "test": {
                    "options": {
-                       "main": "src/test.ts",
-                       "polyfills": "src/polyfills.ts",
+                       "polyfills": [
+                           "zone.js",
+                           "zone.js/testing"
+                       ],
                    }
                }
            }
        }
    }
}
```

#### Update your `tsconfig.app.json` file

```diff
{
    "files": [
        "main.ts",
-       "polyfills.ts"
    ],
}
```

#### Update your `tsconfig.spec.json` file

```diff
{
-   "files": [
-       "test.ts",
-       "polyfills.ts"
-   ],
}
```

### Update `allowedCommonJsDependencies` in your `angular.json` file to add `dayjs`

```diff
{
    "projects": {
        "[YOUR_PROJECT_NAME]": {
            "architect": {
                "build": {
                    "options": {
                        "allowedCommonJsDependencies": [
                            "core-js/modules/es.array.includes",
                            "iban",
-                           "zone.js/dist/zone-error"
+                           "zone.js/dist/zone-error",
+                           "dayjs",
+                           "buffer"
                        ],
                    },
                }
            }
        }
    }
}
```

### HttpClientModule (`app.module.ts`)

Need to import only once PrestationsNgCoreModule (containing HttpClientModule) in root module and not in lazy modules.
Need to import only once HttpClientModule in root module done by PrestationsNgCoreModule.
See 'Usage note' in https://angular.io/api/common/http/HttpInterceptor

```diff
@NgModule({
    imports: [
-       HttpClientModule,
        NgHttpLoaderModule.forRoot()
    ]
})
```

### Use HTTP_LOADER_FILTERED_URL in your application to filter URLs in ng-http-loader component

- `app.component.ts`: Add a public variable `HTTP_LOADER_FILTERED_URL = HTTP_LOADER_FILTERED_URL;`
- `app.component.html`: Use the previous variable in `[filteredUrlPatterns]` attribute of `ng-http-loader` (`<ng-http-loader [filteredUrlPatterns]="HTTP_LOADER_FILTERED_URL"></ng-http-loader>`)

### Rename your application page wrapper

Rename your application page wrapper (the one containing your `foehn-page`) folder into `page-wrapper` along with it's `.html` and `.ts` files.

### Remove protractor and E2E tests

We do not use E2E tests in our applications. If you feel the need to have some, please use `Cypress` (https://docs.cypress.io/guides/getting-started/installing-cypress).

#### Remove protractor dependency

Since **Angular v12**, **protractor** has been **deprecated** (https://blog.angular.io/the-state-of-end-to-end-testing-with-angular-d175f751cb9c).

```bash
yarn remove protractor
```

Then delete file `front/protractor.conf.js`

#### Remove E2E test

- Delete folder `front/e2e`
- Remove `e2e/tsconfig.e2e.json` from `.eslintrc.json` file

```diff
{
    "overrides": [
        // Typescript
        {
            "files": ["*.ts"],
            "parserOptions": {
                "project": [
                    "tsconfig.json",
-                   "e2e/tsconfig.e2e.json"
                ],
            }
        }
    ]
}
```

- Remove script `"e2e": "ng e2e"` in `package.json` file

```diff
{
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --configuration production",
    "test": "ng test",
+   "lint": "ng lint"
-   "lint": "ng lint",
-   "e2e": "ng e2e"
  }
}
```

- Remove E2E project from `angular.json` file

```diff
{
  "projects": {
-   "[YOUR_PROJECT_NAME]-e2e": {
-     "root": "e2e",
-     "sourceRoot": "e2e",
-     "projectType": "application",
-     "architect": {
-       "e2e": {
-         "builder": "@angular-devkit/build-angular:protractor",
-         "options": {
-           "protractorConfig": "./protractor.conf.js",
-           "devServerTarget": "skeleton:serve"
-         }
-       },
-       "lint": {
-         "builder": "@angular-eslint/builder:lint",
-         "options": {
-           "lintFilePatterns": [
-             "e2e/**/*.ts",
-             "e2e/**/*.html"
-           ]
-         }
-       }
-     }
-   }
- },
}
```

### Use puppeteer when running tests

#### Add puppeteer dependency

```bash
yarn add puppeteer --dev
```

#### Update `karma.conf.js` file

```diff
+process.env.CHROMIUM_BIN = require('puppeteer').executablePath();

module.exports = function(config) {
  config.set({
```

#### Cleanup your jenkins files

Remove `chromium-headless` label attribute on your args.

##### UT folder

```diff
def args = [
-   label: 'chromium-headless'
]
```

##### devex > snap folder

```diff
def buildArgs = [
-   label: 'chromium-headless'
]
```

##### devex > stable folder

```diff
def args = [
-   label: 'chromium-headless'
]
```

### Language deprecations

When using `intellij`, you can run code inspection on your project to fix manually deprecations. 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`

#### Replacement `.toPromise()`

Example of replacement (`meta.service.ts`).

```diff
-load(): Promise<unknown> {
+load(): Observable<unknown> {
    return ANY_OBSERVABLE.pipe(
        // some code
-   ).toPromise();
+   );
}

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

#### `GesdemLoaderGuard` replaced by `gesdemLoaderGuard`

In your `app-routing.module.ts` of your application

```diff
-import { GesdemLoaderGuard } from '@dsivd/prestations-ng';
+import { gesdemLoaderGuard } from '@dsivd/prestations-ng';

-canActivate: [GesdemLoaderGuard]
+canActivate: [gesdemLoaderGuard]
```

#### Replacing `CanActivate` guard by `CanActiveFn`

CanActivate, CanActivateChild, CanDeactivate, CanLoad or CanMatch have been deprecated.
See [https://angular.io/api/router#structures](https://angular.io/api/router#structures).
You can find in the previous link a quick fix but it is better to rewrite your guard so it becomes a `CanActiveFn`, `CanActivateChildFn`, `CanDeactivateFn`, `CanLoadFn` or `CanMatchFn`.

Same goes for Resolve
See [https://angular.io/api/router/Resolve](https://angular.io/api/router/Resolve).

##### Rewriting examples

See [gesdemLoaderGuard generated doc](https://dsi-vd.github.io/prestations-ng/generateddoc/miscellaneous/variables.html#gesdemLoaderGuard) as an example.

Or here is an example of rewriting a `CanActivate` guard returning an `Observable` of `boolean` :

```diff
- @Injectable({
-     providedIn: 'root'
- })
- export class YourGuard implements CanActivate {
+ export const yourGuard: CanActivateFn = (next: ActivatedRouteSnapshot): Observable<boolean> => {

-    constructor(
-        private service1: YourService1,
-        private service2: YourService2
-    ) {}
+    const service1 = ServiceLocator.injector.get(YourService1);
+    const service2 = ServiceLocator.injector.get(YourService2);

-     canActivate(
-         next: ActivatedRouteSnapshot
-     ): Observable<boolean> {
        if (YOUR_CONDITION) {
            return of(false);
        }
        return of(true);
-     }
}
```

CanActivate, CanActivateChild, CanDeactivate, CanLoad or CanMatch will need the same approach to be rewritten.
They all return: `Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree` same as the deprecated version of themselves.

Resolve has as well the same approach to be rewritten but returns: `Observable<T> | Promise<T | T`

#### Replacing `.subscribe` with an error callback

```diff
ANY_OBSERVABLE.pipe(
+   catchError((error: unknown) => {
       // handle your error here then
       // return an observable containing your data (i.e. return of([]) or return of(null) or...)
       // return EMPTY;
       // return throwError(() => YOUR_ERROR);
       // throw new Error(YOUR_ERROR as string);
+   })
).subscribe(
    () => {...success handling here...},
-   () => {...error handling here...},
);
```

### Deprecated features

#### FoehnTableColumnConfiguration

`routerLinkGetter` property has been remove. Use `template` property instead (See [Foehn Table with template](https://dsi-vd.github.io/prestations-ng/list#foehn_table_with_template) for an example)

#### Checkables

For all components extending FoehnCheckableGroupComponent such as:

- foehn-autocomplete
- foehn-checkbox
- foehn-radio
- foehn-select
- or your custom components

we have removed `@Input() allElementDisabled` to replace it by `@Input() disabled`.

See below exemple on our `foehn-radio` component:

```diff
<foehn-radio

-   [allElementDisabled]="true"
+   [disabled]="true"

></foehn-radio>
```

#### Uploaders

- [foehn-bo-multi-upload.component.ts](projects/prestations-ng/src/foehn-upload/foehn-bo-multi-upload/foehn-bo-multi-upload.component.ts)
- [foehn-multi-upload.component.ts](projects/prestations-ng/src/foehn-upload/foehn-multi-upload/foehn-multi-upload.component.ts)
    - remove `[overrideMaxSizeInMo]="xx"`. Now managed by the backend (see `DocumentProperties.fileMaxSizeByFormKey`)

### 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/
yarn install
```

#### Build and launch your application

```bash
yarn build
yarn start
```

Your are good to go if no errors are remaining!

## PRESTATIONS-BE

### Library upgrade

see https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.7-Release-Notes#upgrading-from-spring-boot-26

#### With spring boot starter parent

if you're using `org.springframework.boot.spring-boot-starter-parent` :

```diff
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
-    <version>2.6.x</version>
+    <version>2.7.x</version>
    <relativePath />
  </parent>
```

```diff
- <prestations-be.version>15.x.x</prestations-be.version>
+ <prestations-be.version>16.x.x</prestations-be.version>
```

## Config server

We can now fetch `config-server` to override dictionary values. This retrieval is implemented in `prestations-be` in the `DictionaryService` class and its usage is transparent for caller (i.e. we can still call `getDictionary()` method without changing anything).
However, you need to define some properties if you want to take advantage of this. See `CHANGELOG.md` of `prestations-be` (v16.4.9) for more details.

## Artifacts

We now deploy artifacts to Nexus instead of xFile (will be disabled in end of 2023). This requires us to deploy
to the current repository in Nexus.

Add two distributionManagement (DM), one for applications and one for libraries. Applications DM will be enabled through a profile if the packaging of the project is war,
otherwise your project will use the default libraries DM. With this, we will send artifacts to appropriate repositories.

```xml
<yourPom>
    <distributionManagement>
        <repository>
            <id>nexus.releases</id>
            <name>Nexus releases</name>
            <url>${nexus.url.releases}</url>
        </repository>
        <snapshotRepository>
            <id>nexus.snapshots</id>
            <name>Nexus snaphots</name>
            <url>${nexus.url.snapshots}</url>
            <uniqueVersion>false</uniqueVersion>
        </snapshotRepository>
    </distributionManagement>
    <!-- ... -->
    <profile>
        <id>nexusApps</id>
        <properties>
            <release.goals>clean deploy</release.goals>
            <devex-maven-plugin.phase>deploy</devex-maven-plugin.phase>
        </properties>
        <activation>
            <property>
                <name>packaging</name>
                <value>war</value>
            </property>
        </activation>
        <distributionManagement>
            <repository>
                <id>nexus-dgnsi-server</id>
                <name>Nexus DGNSI</name>
                <url>${nexus.url}/app-${application.repository}-stable</url>
            </repository>
            <snapshotRepository>
                <id>nexus-dgnsi-server</id>
                <name>Nexus DGNSI</name>
                <url>${nexus.url}/app-${application.repository}-snapshots</url>
                <uniqueVersion>false</uniqueVersion>
            </snapshotRepository>
        </distributionManagement>
    </profile>
</yourPom>
```

After, you need to **change the target** of your deployment unit on Devex (target tab). Use the syntax defined [here](https://dgnsiwiki.etat-de-vaud.ch/outils/dgnsiwiki/pages/viewpage.action?pageId=1399292455#id-[MIGRATION][APPLICATION]PassagedexFile%C3%A0NexusArtifacts-ConfigurationDevEx) so that your artifact is taken from Nexus and not from xFile anymore.
Otherwise, Devex would try to fetch an artifact that does not exist in xFile since they are only pushed to Nexus.

> application.repository depends on the type of project (ask for migration wiki page to get it and also other URLs).

In Jenkinsfile (snap and stable only), use the 'withNexus' args to true so that you will use Nexus and not xFile anymore :

```groovy
def buildArgs = [
    name            : 'yourProject',
    withNexus: true
]

stage('Snap2Devex yourProject') {
    snap2Devex(buildArgs)
}
```

#### With application parent

if you're using `ch.vd.cyber.parent.application-parent

```diff
<parent>
    <groupId>ch.vd.cyber.parent</groupId>
    <artifactId>application-parent</artifactId>
-    <version>11.x.x</version>
+    <version>12.x.x</version>
    <relativePath/>
</parent>
```

### WebServiceProperties

You should migrate your technical user (`webservice.username`) to a MiZo generated user.
Ask your **Intégrateur référent** if you're not sure.

### Ref-inf

When using refinf :

```diff
- refinf.baseUrl=https://int-esgate.vd.ch/refinf-rf/v5
+ cyber-cache.base-url=https://int-esgate.vd.ch/cybercache-in
```

When not using refinf (and SdkConfig.class is imported)

```diff
  refinf.configuration.enabled=false
+ cyber-cache.configuration.enabled=false
```

### DocumentProperties

if you're having one or more uploader, you have to define the max size for a file on each uploader in your `application.properties` :
i.e. `document.file-max-size-by-form-key.identityCard=5MB`

### Transmission

The endpoint in gesdem that transmits the action to that backoffice has been upgraded so that if the action was already transmitted, it will return a 200 instead of throwing an Exception, and it will provide the information in a header. AbstractSdkController is able to make the distinction in transmit method, and will call "onAfterTransmit" only if the action was transmitted successfully and if the current request is the one that really made the change of status. If 2 "transmit" requests are sent at the same time, only the first one will call "onAfterTransmit".
If you override methods around transmission, make sure that the new behavior is the wanted one, and if you override "transmit" then make sure to reproduce the new behavior if wanted.

### Sending Emails

If your applications does send emails by building an ch.vd.cyber.prestationsbe.jaxb.evd_0032_1.EsbEmail email object and sending it through GesDemService.sendEmail, you better use the object ch.vd.cyber.prestationsbe.jaxb.evd_0036_2.Email and send it through GesDemService.sendevd36Email, as sendEmail is deprecated and will be removed in the future. (See [Emails](https://dsi-vd.github.io/prestations-ng/prestations-be/emails) for more details)

### Editique Ping URL

Set the property editique-http.ping-url for editique by taking a look at [prestations-be](https://dsigit.etat-de-vaud.ch/outils/git/projects/CYBSDK/repos/prestations-be/browse/CHANGELOG.md)

### Verification page

When possible, the verification page should use the same data as the confirmation PDF
see example in skeleton: https://dsigit.etat-de-vaud.ch/outils/git/projects/CYBSDK/repos/skeleton/browse/front/src/app/verification-page

### POM cleanup

- remove the following dependencies that are already imported in ``
    - `org.mockito.mockito-core`
    - `org.mockito.mockito-junit-jupiter`

- restore the version for `org.codehaus.mojo.exec-maven-plugin`
    - `<version>${exec-maven-plugin.version}</version>`

### H2 usage in tests

If you use H2 for your tests, you could encounter the following issues :

#### Error on reserved keyword

```
Syntax error in SQL statement "insert into document (action_fk, [*]key, reference, is_technical_attachment, id) values (?, ?, ?, ?, ?)"; expected "identifier"
```

Here the column `key` is a keyword in H2, you can avoid this error by adding `;NON_KEYWORDS=KEY` to your connection string

#### Error on "limit" in MODE=Oracle

```
Syntax error in SQL statement "select dbdemande0_.id as col_0_0_ from demande dbdemande0_ where dbdemande0_.reference=? [*]limit ?";
```

A query generated by hibernate with the keyword `limit` will fail.
see https://hibernate.atlassian.net/jira/software/c/projects/HHH/issues/HHH-15318
While waiting for a fix, you can do the following :

```
    @BeforeAll
    public static void setup() {
        // https://hibernate.atlassian.net/jira/software/c/projects/HHH/issues/HHH-15318
        Mode.getInstance("ORACLE").limit = true;
    }
```
